11cb0ef41Sopenharmony_ci// Copyright 2012 the V8 project authors. All rights reserved.
21cb0ef41Sopenharmony_ci// Use of this source code is governed by a BSD-style license that can be
31cb0ef41Sopenharmony_ci// found in the LICENSE file.
41cb0ef41Sopenharmony_ci
51cb0ef41Sopenharmony_ci#include "src/execution/isolate.h"
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_ci#include <stdlib.h>
81cb0ef41Sopenharmony_ci
91cb0ef41Sopenharmony_ci#include <atomic>
101cb0ef41Sopenharmony_ci#include <cstdint>
111cb0ef41Sopenharmony_ci#include <fstream>
121cb0ef41Sopenharmony_ci#include <memory>
131cb0ef41Sopenharmony_ci#include <sstream>
141cb0ef41Sopenharmony_ci#include <string>
151cb0ef41Sopenharmony_ci#include <unordered_map>
161cb0ef41Sopenharmony_ci#include <utility>
171cb0ef41Sopenharmony_ci
181cb0ef41Sopenharmony_ci#include "include/v8-template.h"
191cb0ef41Sopenharmony_ci#include "src/api/api-inl.h"
201cb0ef41Sopenharmony_ci#include "src/ast/ast-value-factory.h"
211cb0ef41Sopenharmony_ci#include "src/ast/scopes.h"
221cb0ef41Sopenharmony_ci#include "src/base/hashmap.h"
231cb0ef41Sopenharmony_ci#include "src/base/logging.h"
241cb0ef41Sopenharmony_ci#include "src/base/platform/mutex.h"
251cb0ef41Sopenharmony_ci#include "src/base/platform/platform.h"
261cb0ef41Sopenharmony_ci#include "src/base/sys-info.h"
271cb0ef41Sopenharmony_ci#include "src/base/utils/random-number-generator.h"
281cb0ef41Sopenharmony_ci#include "src/baseline/baseline-batch-compiler.h"
291cb0ef41Sopenharmony_ci#include "src/bigint/bigint.h"
301cb0ef41Sopenharmony_ci#include "src/builtins/builtins-promise.h"
311cb0ef41Sopenharmony_ci#include "src/builtins/constants-table-builder.h"
321cb0ef41Sopenharmony_ci#include "src/codegen/assembler-inl.h"
331cb0ef41Sopenharmony_ci#include "src/codegen/compilation-cache.h"
341cb0ef41Sopenharmony_ci#include "src/codegen/flush-instruction-cache.h"
351cb0ef41Sopenharmony_ci#include "src/common/assert-scope.h"
361cb0ef41Sopenharmony_ci#include "src/common/ptr-compr-inl.h"
371cb0ef41Sopenharmony_ci#include "src/compiler-dispatcher/lazy-compile-dispatcher.h"
381cb0ef41Sopenharmony_ci#include "src/compiler-dispatcher/optimizing-compile-dispatcher.h"
391cb0ef41Sopenharmony_ci#include "src/date/date.h"
401cb0ef41Sopenharmony_ci#include "src/debug/debug-frames.h"
411cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
421cb0ef41Sopenharmony_ci#include "src/debug/debug-wasm-objects.h"
431cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
441cb0ef41Sopenharmony_ci#include "src/debug/debug.h"
451cb0ef41Sopenharmony_ci#include "src/deoptimizer/deoptimizer.h"
461cb0ef41Sopenharmony_ci#include "src/deoptimizer/materialized-object-store.h"
471cb0ef41Sopenharmony_ci#include "src/diagnostics/basic-block-profiler.h"
481cb0ef41Sopenharmony_ci#include "src/diagnostics/compilation-statistics.h"
491cb0ef41Sopenharmony_ci#include "src/execution/frames-inl.h"
501cb0ef41Sopenharmony_ci#include "src/execution/frames.h"
511cb0ef41Sopenharmony_ci#include "src/execution/isolate-inl.h"
521cb0ef41Sopenharmony_ci#include "src/execution/local-isolate.h"
531cb0ef41Sopenharmony_ci#include "src/execution/messages.h"
541cb0ef41Sopenharmony_ci#include "src/execution/microtask-queue.h"
551cb0ef41Sopenharmony_ci#include "src/execution/protectors-inl.h"
561cb0ef41Sopenharmony_ci#include "src/execution/simulator.h"
571cb0ef41Sopenharmony_ci#include "src/execution/tiering-manager.h"
581cb0ef41Sopenharmony_ci#include "src/execution/v8threads.h"
591cb0ef41Sopenharmony_ci#include "src/execution/vm-state-inl.h"
601cb0ef41Sopenharmony_ci#include "src/handles/global-handles-inl.h"
611cb0ef41Sopenharmony_ci#include "src/handles/persistent-handles.h"
621cb0ef41Sopenharmony_ci#include "src/heap/heap-inl.h"
631cb0ef41Sopenharmony_ci#include "src/heap/heap.h"
641cb0ef41Sopenharmony_ci#include "src/heap/local-heap.h"
651cb0ef41Sopenharmony_ci#include "src/heap/parked-scope.h"
661cb0ef41Sopenharmony_ci#include "src/heap/read-only-heap.h"
671cb0ef41Sopenharmony_ci#include "src/heap/safepoint.h"
681cb0ef41Sopenharmony_ci#include "src/ic/stub-cache.h"
691cb0ef41Sopenharmony_ci#include "src/init/bootstrapper.h"
701cb0ef41Sopenharmony_ci#include "src/init/setup-isolate.h"
711cb0ef41Sopenharmony_ci#include "src/init/v8.h"
721cb0ef41Sopenharmony_ci#include "src/interpreter/interpreter.h"
731cb0ef41Sopenharmony_ci#include "src/libsampler/sampler.h"
741cb0ef41Sopenharmony_ci#include "src/logging/counters.h"
751cb0ef41Sopenharmony_ci#include "src/logging/log.h"
761cb0ef41Sopenharmony_ci#include "src/logging/metrics.h"
771cb0ef41Sopenharmony_ci#include "src/logging/runtime-call-stats-scope.h"
781cb0ef41Sopenharmony_ci#include "src/numbers/hash-seed-inl.h"
791cb0ef41Sopenharmony_ci#include "src/objects/backing-store.h"
801cb0ef41Sopenharmony_ci#include "src/objects/call-site-info-inl.h"
811cb0ef41Sopenharmony_ci#include "src/objects/elements.h"
821cb0ef41Sopenharmony_ci#include "src/objects/feedback-vector.h"
831cb0ef41Sopenharmony_ci#include "src/objects/hash-table-inl.h"
841cb0ef41Sopenharmony_ci#include "src/objects/js-array-buffer-inl.h"
851cb0ef41Sopenharmony_ci#include "src/objects/js-array-inl.h"
861cb0ef41Sopenharmony_ci#include "src/objects/js-generator-inl.h"
871cb0ef41Sopenharmony_ci#include "src/objects/js-weak-refs-inl.h"
881cb0ef41Sopenharmony_ci#include "src/objects/managed-inl.h"
891cb0ef41Sopenharmony_ci#include "src/objects/module-inl.h"
901cb0ef41Sopenharmony_ci#include "src/objects/promise-inl.h"
911cb0ef41Sopenharmony_ci#include "src/objects/prototype.h"
921cb0ef41Sopenharmony_ci#include "src/objects/slots.h"
931cb0ef41Sopenharmony_ci#include "src/objects/smi.h"
941cb0ef41Sopenharmony_ci#include "src/objects/source-text-module-inl.h"
951cb0ef41Sopenharmony_ci#include "src/objects/visitors.h"
961cb0ef41Sopenharmony_ci#include "src/profiler/heap-profiler.h"
971cb0ef41Sopenharmony_ci#include "src/profiler/tracing-cpu-profiler.h"
981cb0ef41Sopenharmony_ci#include "src/regexp/regexp-stack.h"
991cb0ef41Sopenharmony_ci#include "src/snapshot/embedded/embedded-data-inl.h"
1001cb0ef41Sopenharmony_ci#include "src/snapshot/embedded/embedded-file-writer-interface.h"
1011cb0ef41Sopenharmony_ci#include "src/snapshot/read-only-deserializer.h"
1021cb0ef41Sopenharmony_ci#include "src/snapshot/shared-heap-deserializer.h"
1031cb0ef41Sopenharmony_ci#include "src/snapshot/startup-deserializer.h"
1041cb0ef41Sopenharmony_ci#include "src/strings/string-builder-inl.h"
1051cb0ef41Sopenharmony_ci#include "src/strings/string-stream.h"
1061cb0ef41Sopenharmony_ci#include "src/tasks/cancelable-task.h"
1071cb0ef41Sopenharmony_ci#include "src/tracing/tracing-category-observer.h"
1081cb0ef41Sopenharmony_ci#include "src/utils/address-map.h"
1091cb0ef41Sopenharmony_ci#include "src/utils/ostreams.h"
1101cb0ef41Sopenharmony_ci#include "src/utils/version.h"
1111cb0ef41Sopenharmony_ci#include "src/zone/accounting-allocator.h"
1121cb0ef41Sopenharmony_ci#include "src/zone/type-stats.h"
1131cb0ef41Sopenharmony_ci#ifdef V8_INTL_SUPPORT
1141cb0ef41Sopenharmony_ci#include "src/objects/intl-objects.h"
1151cb0ef41Sopenharmony_ci#include "unicode/locid.h"
1161cb0ef41Sopenharmony_ci#include "unicode/uobject.h"
1171cb0ef41Sopenharmony_ci#endif  // V8_INTL_SUPPORT
1181cb0ef41Sopenharmony_ci
1191cb0ef41Sopenharmony_ci#if V8_ENABLE_MAGLEV
1201cb0ef41Sopenharmony_ci#include "src/maglev/maglev-concurrent-dispatcher.h"
1211cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_MAGLEV
1221cb0ef41Sopenharmony_ci
1231cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
1241cb0ef41Sopenharmony_ci#include "src/trap-handler/trap-handler.h"
1251cb0ef41Sopenharmony_ci#include "src/wasm/wasm-code-manager.h"
1261cb0ef41Sopenharmony_ci#include "src/wasm/wasm-engine.h"
1271cb0ef41Sopenharmony_ci#include "src/wasm/wasm-module.h"
1281cb0ef41Sopenharmony_ci#include "src/wasm/wasm-objects.h"
1291cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
1301cb0ef41Sopenharmony_ci
1311cb0ef41Sopenharmony_ci#if defined(V8_OS_WIN64)
1321cb0ef41Sopenharmony_ci#include "src/diagnostics/unwinding-info-win64.h"
1331cb0ef41Sopenharmony_ci#endif  // V8_OS_WIN64
1341cb0ef41Sopenharmony_ci
1351cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_CONSERVATIVE_STACK_SCANNING
1361cb0ef41Sopenharmony_ci#include "src/base/platform/wrappers.h"
1371cb0ef41Sopenharmony_ci#include "src/heap/conservative-stack-visitor.h"
1381cb0ef41Sopenharmony_ci#endif
1391cb0ef41Sopenharmony_ci
1401cb0ef41Sopenharmony_ci#if USE_SIMULATOR
1411cb0ef41Sopenharmony_ci#include "src/execution/simulator-base.h"
1421cb0ef41Sopenharmony_ci#endif
1431cb0ef41Sopenharmony_ci
1441cb0ef41Sopenharmony_ciextern "C" const uint8_t* v8_Default_embedded_blob_code_;
1451cb0ef41Sopenharmony_ciextern "C" uint32_t v8_Default_embedded_blob_code_size_;
1461cb0ef41Sopenharmony_ciextern "C" const uint8_t* v8_Default_embedded_blob_data_;
1471cb0ef41Sopenharmony_ciextern "C" uint32_t v8_Default_embedded_blob_data_size_;
1481cb0ef41Sopenharmony_ci
1491cb0ef41Sopenharmony_cinamespace v8 {
1501cb0ef41Sopenharmony_cinamespace internal {
1511cb0ef41Sopenharmony_ci
1521cb0ef41Sopenharmony_ci#ifdef DEBUG
1531cb0ef41Sopenharmony_ci#define TRACE_ISOLATE(tag)                                                  \
1541cb0ef41Sopenharmony_ci  do {                                                                      \
1551cb0ef41Sopenharmony_ci    if (FLAG_trace_isolates) {                                              \
1561cb0ef41Sopenharmony_ci      PrintF("Isolate %p (id %d)" #tag "\n", reinterpret_cast<void*>(this), \
1571cb0ef41Sopenharmony_ci             id());                                                         \
1581cb0ef41Sopenharmony_ci    }                                                                       \
1591cb0ef41Sopenharmony_ci  } while (false)
1601cb0ef41Sopenharmony_ci#else
1611cb0ef41Sopenharmony_ci#define TRACE_ISOLATE(tag)
1621cb0ef41Sopenharmony_ci#endif
1631cb0ef41Sopenharmony_ci
1641cb0ef41Sopenharmony_ciconst uint8_t* DefaultEmbeddedBlobCode() {
1651cb0ef41Sopenharmony_ci  return v8_Default_embedded_blob_code_;
1661cb0ef41Sopenharmony_ci}
1671cb0ef41Sopenharmony_ciuint32_t DefaultEmbeddedBlobCodeSize() {
1681cb0ef41Sopenharmony_ci  return v8_Default_embedded_blob_code_size_;
1691cb0ef41Sopenharmony_ci}
1701cb0ef41Sopenharmony_ciconst uint8_t* DefaultEmbeddedBlobData() {
1711cb0ef41Sopenharmony_ci  return v8_Default_embedded_blob_data_;
1721cb0ef41Sopenharmony_ci}
1731cb0ef41Sopenharmony_ciuint32_t DefaultEmbeddedBlobDataSize() {
1741cb0ef41Sopenharmony_ci  return v8_Default_embedded_blob_data_size_;
1751cb0ef41Sopenharmony_ci}
1761cb0ef41Sopenharmony_ci
1771cb0ef41Sopenharmony_cinamespace {
1781cb0ef41Sopenharmony_ci// These variables provide access to the current embedded blob without requiring
1791cb0ef41Sopenharmony_ci// an isolate instance. This is needed e.g. by Code::InstructionStart, which may
1801cb0ef41Sopenharmony_ci// not have access to an isolate but still needs to access the embedded blob.
1811cb0ef41Sopenharmony_ci// The variables are initialized by each isolate in Init(). Writes and reads are
1821cb0ef41Sopenharmony_ci// relaxed since we can guarantee that the current thread has initialized these
1831cb0ef41Sopenharmony_ci// variables before accessing them. Different threads may race, but this is fine
1841cb0ef41Sopenharmony_ci// since they all attempt to set the same values of the blob pointer and size.
1851cb0ef41Sopenharmony_ci
1861cb0ef41Sopenharmony_cistd::atomic<const uint8_t*> current_embedded_blob_code_(nullptr);
1871cb0ef41Sopenharmony_cistd::atomic<uint32_t> current_embedded_blob_code_size_(0);
1881cb0ef41Sopenharmony_cistd::atomic<const uint8_t*> current_embedded_blob_data_(nullptr);
1891cb0ef41Sopenharmony_cistd::atomic<uint32_t> current_embedded_blob_data_size_(0);
1901cb0ef41Sopenharmony_ci
1911cb0ef41Sopenharmony_ci// The various workflows around embedded snapshots are fairly complex. We need
1921cb0ef41Sopenharmony_ci// to support plain old snapshot builds, nosnap builds, and the requirements of
1931cb0ef41Sopenharmony_ci// subtly different serialization tests. There's two related knobs to twiddle:
1941cb0ef41Sopenharmony_ci//
1951cb0ef41Sopenharmony_ci// - The default embedded blob may be overridden by setting the sticky embedded
1961cb0ef41Sopenharmony_ci// blob. This is set automatically whenever we create a new embedded blob.
1971cb0ef41Sopenharmony_ci//
1981cb0ef41Sopenharmony_ci// - Lifecycle management can be either manual or set to refcounting.
1991cb0ef41Sopenharmony_ci//
2001cb0ef41Sopenharmony_ci// A few situations to demonstrate their use:
2011cb0ef41Sopenharmony_ci//
2021cb0ef41Sopenharmony_ci// - A plain old snapshot build neither overrides the default blob nor
2031cb0ef41Sopenharmony_ci// refcounts.
2041cb0ef41Sopenharmony_ci//
2051cb0ef41Sopenharmony_ci// - mksnapshot sets the sticky blob and manually frees the embedded
2061cb0ef41Sopenharmony_ci// blob once done.
2071cb0ef41Sopenharmony_ci//
2081cb0ef41Sopenharmony_ci// - Most serializer tests do the same.
2091cb0ef41Sopenharmony_ci//
2101cb0ef41Sopenharmony_ci// - Nosnapshot builds set the sticky blob and enable refcounting.
2111cb0ef41Sopenharmony_ci
2121cb0ef41Sopenharmony_ci// This mutex protects access to the following variables:
2131cb0ef41Sopenharmony_ci// - sticky_embedded_blob_code_
2141cb0ef41Sopenharmony_ci// - sticky_embedded_blob_code_size_
2151cb0ef41Sopenharmony_ci// - sticky_embedded_blob_data_
2161cb0ef41Sopenharmony_ci// - sticky_embedded_blob_data_size_
2171cb0ef41Sopenharmony_ci// - enable_embedded_blob_refcounting_
2181cb0ef41Sopenharmony_ci// - current_embedded_blob_refs_
2191cb0ef41Sopenharmony_cibase::LazyMutex current_embedded_blob_refcount_mutex_ = LAZY_MUTEX_INITIALIZER;
2201cb0ef41Sopenharmony_ci
2211cb0ef41Sopenharmony_ciconst uint8_t* sticky_embedded_blob_code_ = nullptr;
2221cb0ef41Sopenharmony_ciuint32_t sticky_embedded_blob_code_size_ = 0;
2231cb0ef41Sopenharmony_ciconst uint8_t* sticky_embedded_blob_data_ = nullptr;
2241cb0ef41Sopenharmony_ciuint32_t sticky_embedded_blob_data_size_ = 0;
2251cb0ef41Sopenharmony_ci
2261cb0ef41Sopenharmony_cibool enable_embedded_blob_refcounting_ = true;
2271cb0ef41Sopenharmony_ciint current_embedded_blob_refs_ = 0;
2281cb0ef41Sopenharmony_ci
2291cb0ef41Sopenharmony_ciconst uint8_t* StickyEmbeddedBlobCode() { return sticky_embedded_blob_code_; }
2301cb0ef41Sopenharmony_ciuint32_t StickyEmbeddedBlobCodeSize() {
2311cb0ef41Sopenharmony_ci  return sticky_embedded_blob_code_size_;
2321cb0ef41Sopenharmony_ci}
2331cb0ef41Sopenharmony_ciconst uint8_t* StickyEmbeddedBlobData() { return sticky_embedded_blob_data_; }
2341cb0ef41Sopenharmony_ciuint32_t StickyEmbeddedBlobDataSize() {
2351cb0ef41Sopenharmony_ci  return sticky_embedded_blob_data_size_;
2361cb0ef41Sopenharmony_ci}
2371cb0ef41Sopenharmony_ci
2381cb0ef41Sopenharmony_civoid SetStickyEmbeddedBlob(const uint8_t* code, uint32_t code_size,
2391cb0ef41Sopenharmony_ci                           const uint8_t* data, uint32_t data_size) {
2401cb0ef41Sopenharmony_ci  sticky_embedded_blob_code_ = code;
2411cb0ef41Sopenharmony_ci  sticky_embedded_blob_code_size_ = code_size;
2421cb0ef41Sopenharmony_ci  sticky_embedded_blob_data_ = data;
2431cb0ef41Sopenharmony_ci  sticky_embedded_blob_data_size_ = data_size;
2441cb0ef41Sopenharmony_ci}
2451cb0ef41Sopenharmony_ci
2461cb0ef41Sopenharmony_ci}  // namespace
2471cb0ef41Sopenharmony_ci
2481cb0ef41Sopenharmony_civoid DisableEmbeddedBlobRefcounting() {
2491cb0ef41Sopenharmony_ci  base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer());
2501cb0ef41Sopenharmony_ci  enable_embedded_blob_refcounting_ = false;
2511cb0ef41Sopenharmony_ci}
2521cb0ef41Sopenharmony_ci
2531cb0ef41Sopenharmony_civoid FreeCurrentEmbeddedBlob() {
2541cb0ef41Sopenharmony_ci  CHECK(!enable_embedded_blob_refcounting_);
2551cb0ef41Sopenharmony_ci  base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer());
2561cb0ef41Sopenharmony_ci
2571cb0ef41Sopenharmony_ci  if (StickyEmbeddedBlobCode() == nullptr) return;
2581cb0ef41Sopenharmony_ci
2591cb0ef41Sopenharmony_ci  CHECK_EQ(StickyEmbeddedBlobCode(), Isolate::CurrentEmbeddedBlobCode());
2601cb0ef41Sopenharmony_ci  CHECK_EQ(StickyEmbeddedBlobData(), Isolate::CurrentEmbeddedBlobData());
2611cb0ef41Sopenharmony_ci
2621cb0ef41Sopenharmony_ci  OffHeapInstructionStream::FreeOffHeapOffHeapInstructionStream(
2631cb0ef41Sopenharmony_ci      const_cast<uint8_t*>(Isolate::CurrentEmbeddedBlobCode()),
2641cb0ef41Sopenharmony_ci      Isolate::CurrentEmbeddedBlobCodeSize(),
2651cb0ef41Sopenharmony_ci      const_cast<uint8_t*>(Isolate::CurrentEmbeddedBlobData()),
2661cb0ef41Sopenharmony_ci      Isolate::CurrentEmbeddedBlobDataSize());
2671cb0ef41Sopenharmony_ci
2681cb0ef41Sopenharmony_ci  current_embedded_blob_code_.store(nullptr, std::memory_order_relaxed);
2691cb0ef41Sopenharmony_ci  current_embedded_blob_code_size_.store(0, std::memory_order_relaxed);
2701cb0ef41Sopenharmony_ci  current_embedded_blob_data_.store(nullptr, std::memory_order_relaxed);
2711cb0ef41Sopenharmony_ci  current_embedded_blob_data_size_.store(0, std::memory_order_relaxed);
2721cb0ef41Sopenharmony_ci  sticky_embedded_blob_code_ = nullptr;
2731cb0ef41Sopenharmony_ci  sticky_embedded_blob_code_size_ = 0;
2741cb0ef41Sopenharmony_ci  sticky_embedded_blob_data_ = nullptr;
2751cb0ef41Sopenharmony_ci  sticky_embedded_blob_data_size_ = 0;
2761cb0ef41Sopenharmony_ci}
2771cb0ef41Sopenharmony_ci
2781cb0ef41Sopenharmony_ci// static
2791cb0ef41Sopenharmony_cibool Isolate::CurrentEmbeddedBlobIsBinaryEmbedded() {
2801cb0ef41Sopenharmony_ci  // In some situations, we must be able to rely on the embedded blob being
2811cb0ef41Sopenharmony_ci  // immortal immovable. This is the case if the blob is binary-embedded.
2821cb0ef41Sopenharmony_ci  // See blob lifecycle controls above for descriptions of when the current
2831cb0ef41Sopenharmony_ci  // embedded blob may change (e.g. in tests or mksnapshot). If the blob is
2841cb0ef41Sopenharmony_ci  // binary-embedded, it is immortal immovable.
2851cb0ef41Sopenharmony_ci  const uint8_t* code =
2861cb0ef41Sopenharmony_ci      current_embedded_blob_code_.load(std::memory_order_relaxed);
2871cb0ef41Sopenharmony_ci  if (code == nullptr) return false;
2881cb0ef41Sopenharmony_ci  return code == DefaultEmbeddedBlobCode();
2891cb0ef41Sopenharmony_ci}
2901cb0ef41Sopenharmony_ci
2911cb0ef41Sopenharmony_civoid Isolate::SetEmbeddedBlob(const uint8_t* code, uint32_t code_size,
2921cb0ef41Sopenharmony_ci                              const uint8_t* data, uint32_t data_size) {
2931cb0ef41Sopenharmony_ci  CHECK_NOT_NULL(code);
2941cb0ef41Sopenharmony_ci  CHECK_NOT_NULL(data);
2951cb0ef41Sopenharmony_ci
2961cb0ef41Sopenharmony_ci  embedded_blob_code_ = code;
2971cb0ef41Sopenharmony_ci  embedded_blob_code_size_ = code_size;
2981cb0ef41Sopenharmony_ci  embedded_blob_data_ = data;
2991cb0ef41Sopenharmony_ci  embedded_blob_data_size_ = data_size;
3001cb0ef41Sopenharmony_ci  current_embedded_blob_code_.store(code, std::memory_order_relaxed);
3011cb0ef41Sopenharmony_ci  current_embedded_blob_code_size_.store(code_size, std::memory_order_relaxed);
3021cb0ef41Sopenharmony_ci  current_embedded_blob_data_.store(data, std::memory_order_relaxed);
3031cb0ef41Sopenharmony_ci  current_embedded_blob_data_size_.store(data_size, std::memory_order_relaxed);
3041cb0ef41Sopenharmony_ci
3051cb0ef41Sopenharmony_ci#ifdef DEBUG
3061cb0ef41Sopenharmony_ci  // Verify that the contents of the embedded blob are unchanged from
3071cb0ef41Sopenharmony_ci  // serialization-time, just to ensure the compiler isn't messing with us.
3081cb0ef41Sopenharmony_ci  EmbeddedData d = EmbeddedData::FromBlob();
3091cb0ef41Sopenharmony_ci  if (d.EmbeddedBlobDataHash() != d.CreateEmbeddedBlobDataHash()) {
3101cb0ef41Sopenharmony_ci    FATAL(
3111cb0ef41Sopenharmony_ci        "Embedded blob data section checksum verification failed. This "
3121cb0ef41Sopenharmony_ci        "indicates that the embedded blob has been modified since compilation "
3131cb0ef41Sopenharmony_ci        "time.");
3141cb0ef41Sopenharmony_ci  }
3151cb0ef41Sopenharmony_ci  if (FLAG_text_is_readable) {
3161cb0ef41Sopenharmony_ci    if (d.EmbeddedBlobCodeHash() != d.CreateEmbeddedBlobCodeHash()) {
3171cb0ef41Sopenharmony_ci      FATAL(
3181cb0ef41Sopenharmony_ci          "Embedded blob code section checksum verification failed. This "
3191cb0ef41Sopenharmony_ci          "indicates that the embedded blob has been modified since "
3201cb0ef41Sopenharmony_ci          "compilation time. A common cause is a debugging breakpoint set "
3211cb0ef41Sopenharmony_ci          "within builtin code.");
3221cb0ef41Sopenharmony_ci    }
3231cb0ef41Sopenharmony_ci  }
3241cb0ef41Sopenharmony_ci#endif  // DEBUG
3251cb0ef41Sopenharmony_ci}
3261cb0ef41Sopenharmony_ci
3271cb0ef41Sopenharmony_civoid Isolate::ClearEmbeddedBlob() {
3281cb0ef41Sopenharmony_ci  CHECK(enable_embedded_blob_refcounting_);
3291cb0ef41Sopenharmony_ci  CHECK_EQ(embedded_blob_code_, CurrentEmbeddedBlobCode());
3301cb0ef41Sopenharmony_ci  CHECK_EQ(embedded_blob_code_, StickyEmbeddedBlobCode());
3311cb0ef41Sopenharmony_ci  CHECK_EQ(embedded_blob_data_, CurrentEmbeddedBlobData());
3321cb0ef41Sopenharmony_ci  CHECK_EQ(embedded_blob_data_, StickyEmbeddedBlobData());
3331cb0ef41Sopenharmony_ci
3341cb0ef41Sopenharmony_ci  embedded_blob_code_ = nullptr;
3351cb0ef41Sopenharmony_ci  embedded_blob_code_size_ = 0;
3361cb0ef41Sopenharmony_ci  embedded_blob_data_ = nullptr;
3371cb0ef41Sopenharmony_ci  embedded_blob_data_size_ = 0;
3381cb0ef41Sopenharmony_ci  current_embedded_blob_code_.store(nullptr, std::memory_order_relaxed);
3391cb0ef41Sopenharmony_ci  current_embedded_blob_code_size_.store(0, std::memory_order_relaxed);
3401cb0ef41Sopenharmony_ci  current_embedded_blob_data_.store(nullptr, std::memory_order_relaxed);
3411cb0ef41Sopenharmony_ci  current_embedded_blob_data_size_.store(0, std::memory_order_relaxed);
3421cb0ef41Sopenharmony_ci  sticky_embedded_blob_code_ = nullptr;
3431cb0ef41Sopenharmony_ci  sticky_embedded_blob_code_size_ = 0;
3441cb0ef41Sopenharmony_ci  sticky_embedded_blob_data_ = nullptr;
3451cb0ef41Sopenharmony_ci  sticky_embedded_blob_data_size_ = 0;
3461cb0ef41Sopenharmony_ci}
3471cb0ef41Sopenharmony_ci
3481cb0ef41Sopenharmony_ciconst uint8_t* Isolate::embedded_blob_code() const {
3491cb0ef41Sopenharmony_ci  return embedded_blob_code_;
3501cb0ef41Sopenharmony_ci}
3511cb0ef41Sopenharmony_ciuint32_t Isolate::embedded_blob_code_size() const {
3521cb0ef41Sopenharmony_ci  return embedded_blob_code_size_;
3531cb0ef41Sopenharmony_ci}
3541cb0ef41Sopenharmony_ciconst uint8_t* Isolate::embedded_blob_data() const {
3551cb0ef41Sopenharmony_ci  return embedded_blob_data_;
3561cb0ef41Sopenharmony_ci}
3571cb0ef41Sopenharmony_ciuint32_t Isolate::embedded_blob_data_size() const {
3581cb0ef41Sopenharmony_ci  return embedded_blob_data_size_;
3591cb0ef41Sopenharmony_ci}
3601cb0ef41Sopenharmony_ci
3611cb0ef41Sopenharmony_ci// static
3621cb0ef41Sopenharmony_ciconst uint8_t* Isolate::CurrentEmbeddedBlobCode() {
3631cb0ef41Sopenharmony_ci  return current_embedded_blob_code_.load(std::memory_order_relaxed);
3641cb0ef41Sopenharmony_ci}
3651cb0ef41Sopenharmony_ci
3661cb0ef41Sopenharmony_ci// static
3671cb0ef41Sopenharmony_ciuint32_t Isolate::CurrentEmbeddedBlobCodeSize() {
3681cb0ef41Sopenharmony_ci  return current_embedded_blob_code_size_.load(std::memory_order_relaxed);
3691cb0ef41Sopenharmony_ci}
3701cb0ef41Sopenharmony_ci
3711cb0ef41Sopenharmony_ci// static
3721cb0ef41Sopenharmony_ciconst uint8_t* Isolate::CurrentEmbeddedBlobData() {
3731cb0ef41Sopenharmony_ci  return current_embedded_blob_data_.load(std::memory_order_relaxed);
3741cb0ef41Sopenharmony_ci}
3751cb0ef41Sopenharmony_ci
3761cb0ef41Sopenharmony_ci// static
3771cb0ef41Sopenharmony_ciuint32_t Isolate::CurrentEmbeddedBlobDataSize() {
3781cb0ef41Sopenharmony_ci  return current_embedded_blob_data_size_.load(std::memory_order_relaxed);
3791cb0ef41Sopenharmony_ci}
3801cb0ef41Sopenharmony_ci
3811cb0ef41Sopenharmony_ci// static
3821cb0ef41Sopenharmony_cibase::AddressRegion Isolate::GetShortBuiltinsCallRegion() {
3831cb0ef41Sopenharmony_ci  // Update calculations below if the assert fails.
3841cb0ef41Sopenharmony_ci  STATIC_ASSERT(kMaxPCRelativeCodeRangeInMB <= 4096);
3851cb0ef41Sopenharmony_ci  if (kMaxPCRelativeCodeRangeInMB == 0) {
3861cb0ef41Sopenharmony_ci    // Return empty region if pc-relative calls/jumps are not supported.
3871cb0ef41Sopenharmony_ci    return base::AddressRegion(kNullAddress, 0);
3881cb0ef41Sopenharmony_ci  }
3891cb0ef41Sopenharmony_ci  constexpr size_t max_size = std::numeric_limits<size_t>::max();
3901cb0ef41Sopenharmony_ci  if (uint64_t{kMaxPCRelativeCodeRangeInMB} * MB > max_size) {
3911cb0ef41Sopenharmony_ci    // The whole addressable space is reachable with pc-relative calls/jumps.
3921cb0ef41Sopenharmony_ci    return base::AddressRegion(kNullAddress, max_size);
3931cb0ef41Sopenharmony_ci  }
3941cb0ef41Sopenharmony_ci  constexpr size_t radius = kMaxPCRelativeCodeRangeInMB * MB;
3951cb0ef41Sopenharmony_ci
3961cb0ef41Sopenharmony_ci  DCHECK_LT(CurrentEmbeddedBlobCodeSize(), radius);
3971cb0ef41Sopenharmony_ci  Address embedded_blob_code_start =
3981cb0ef41Sopenharmony_ci      reinterpret_cast<Address>(CurrentEmbeddedBlobCode());
3991cb0ef41Sopenharmony_ci  if (embedded_blob_code_start == kNullAddress) {
4001cb0ef41Sopenharmony_ci    // Return empty region if there's no embedded blob.
4011cb0ef41Sopenharmony_ci    return base::AddressRegion(kNullAddress, 0);
4021cb0ef41Sopenharmony_ci  }
4031cb0ef41Sopenharmony_ci  Address embedded_blob_code_end =
4041cb0ef41Sopenharmony_ci      embedded_blob_code_start + CurrentEmbeddedBlobCodeSize();
4051cb0ef41Sopenharmony_ci  Address region_start =
4061cb0ef41Sopenharmony_ci      (embedded_blob_code_end > radius) ? (embedded_blob_code_end - radius) : 0;
4071cb0ef41Sopenharmony_ci  Address region_end = embedded_blob_code_start + radius;
4081cb0ef41Sopenharmony_ci  if (region_end < embedded_blob_code_start) {
4091cb0ef41Sopenharmony_ci    region_end = static_cast<Address>(-1);
4101cb0ef41Sopenharmony_ci  }
4111cb0ef41Sopenharmony_ci  return base::AddressRegion(region_start, region_end - region_start);
4121cb0ef41Sopenharmony_ci}
4131cb0ef41Sopenharmony_ci
4141cb0ef41Sopenharmony_cisize_t Isolate::HashIsolateForEmbeddedBlob() {
4151cb0ef41Sopenharmony_ci  DCHECK(builtins_.is_initialized());
4161cb0ef41Sopenharmony_ci  DCHECK(Builtins::AllBuiltinsAreIsolateIndependent());
4171cb0ef41Sopenharmony_ci
4181cb0ef41Sopenharmony_ci  DisallowGarbageCollection no_gc;
4191cb0ef41Sopenharmony_ci
4201cb0ef41Sopenharmony_ci  static constexpr size_t kSeed = 0;
4211cb0ef41Sopenharmony_ci  size_t hash = kSeed;
4221cb0ef41Sopenharmony_ci
4231cb0ef41Sopenharmony_ci  // Hash data sections of builtin code objects.
4241cb0ef41Sopenharmony_ci  for (Builtin builtin = Builtins::kFirst; builtin <= Builtins::kLast;
4251cb0ef41Sopenharmony_ci       ++builtin) {
4261cb0ef41Sopenharmony_ci    Code code = FromCodeT(builtins()->code(builtin));
4271cb0ef41Sopenharmony_ci
4281cb0ef41Sopenharmony_ci    DCHECK(Internals::HasHeapObjectTag(code.ptr()));
4291cb0ef41Sopenharmony_ci    uint8_t* const code_ptr =
4301cb0ef41Sopenharmony_ci        reinterpret_cast<uint8_t*>(code.ptr() - kHeapObjectTag);
4311cb0ef41Sopenharmony_ci
4321cb0ef41Sopenharmony_ci    // These static asserts ensure we don't miss relevant fields. We don't hash
4331cb0ef41Sopenharmony_ci    // pointer compression base, instruction/metadata size value and flags since
4341cb0ef41Sopenharmony_ci    // they change when creating the off-heap trampolines. Other data fields
4351cb0ef41Sopenharmony_ci    // must remain the same.
4361cb0ef41Sopenharmony_ci#ifdef V8_EXTERNAL_CODE_SPACE
4371cb0ef41Sopenharmony_ci    STATIC_ASSERT(Code::kMainCageBaseUpper32BitsOffset == Code::kDataStart);
4381cb0ef41Sopenharmony_ci    STATIC_ASSERT(Code::kInstructionSizeOffset ==
4391cb0ef41Sopenharmony_ci                  Code::kMainCageBaseUpper32BitsOffsetEnd + 1);
4401cb0ef41Sopenharmony_ci#else
4411cb0ef41Sopenharmony_ci    STATIC_ASSERT(Code::kInstructionSizeOffset == Code::kDataStart);
4421cb0ef41Sopenharmony_ci#endif  // V8_EXTERNAL_CODE_SPACE
4431cb0ef41Sopenharmony_ci    STATIC_ASSERT(Code::kMetadataSizeOffset ==
4441cb0ef41Sopenharmony_ci                  Code::kInstructionSizeOffsetEnd + 1);
4451cb0ef41Sopenharmony_ci    STATIC_ASSERT(Code::kFlagsOffset == Code::kMetadataSizeOffsetEnd + 1);
4461cb0ef41Sopenharmony_ci    STATIC_ASSERT(Code::kBuiltinIndexOffset == Code::kFlagsOffsetEnd + 1);
4471cb0ef41Sopenharmony_ci    static constexpr int kStartOffset = Code::kBuiltinIndexOffset;
4481cb0ef41Sopenharmony_ci
4491cb0ef41Sopenharmony_ci    for (int j = kStartOffset; j < Code::kUnalignedHeaderSize; j++) {
4501cb0ef41Sopenharmony_ci      hash = base::hash_combine(hash, size_t{code_ptr[j]});
4511cb0ef41Sopenharmony_ci    }
4521cb0ef41Sopenharmony_ci  }
4531cb0ef41Sopenharmony_ci
4541cb0ef41Sopenharmony_ci  // The builtins constants table is also tightly tied to embedded builtins.
4551cb0ef41Sopenharmony_ci  hash = base::hash_combine(
4561cb0ef41Sopenharmony_ci      hash, static_cast<size_t>(heap_.builtins_constants_table().length()));
4571cb0ef41Sopenharmony_ci
4581cb0ef41Sopenharmony_ci  return hash;
4591cb0ef41Sopenharmony_ci}
4601cb0ef41Sopenharmony_ci
4611cb0ef41Sopenharmony_cibase::Thread::LocalStorageKey Isolate::isolate_key_;
4621cb0ef41Sopenharmony_cibase::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_;
4631cb0ef41Sopenharmony_cistd::atomic<bool> Isolate::isolate_key_created_{false};
4641cb0ef41Sopenharmony_ci
4651cb0ef41Sopenharmony_cinamespace {
4661cb0ef41Sopenharmony_ci// A global counter for all generated Isolates, might overflow.
4671cb0ef41Sopenharmony_cistd::atomic<int> isolate_counter{0};
4681cb0ef41Sopenharmony_ci}  // namespace
4691cb0ef41Sopenharmony_ci
4701cb0ef41Sopenharmony_ciIsolate::PerIsolateThreadData*
4711cb0ef41Sopenharmony_ciIsolate::FindOrAllocatePerThreadDataForThisThread() {
4721cb0ef41Sopenharmony_ci  ThreadId thread_id = ThreadId::Current();
4731cb0ef41Sopenharmony_ci  PerIsolateThreadData* per_thread = nullptr;
4741cb0ef41Sopenharmony_ci  {
4751cb0ef41Sopenharmony_ci    base::MutexGuard lock_guard(&thread_data_table_mutex_);
4761cb0ef41Sopenharmony_ci    per_thread = thread_data_table_.Lookup(thread_id);
4771cb0ef41Sopenharmony_ci    if (per_thread == nullptr) {
4781cb0ef41Sopenharmony_ci      if (FLAG_adjust_os_scheduling_parameters) {
4791cb0ef41Sopenharmony_ci        base::OS::AdjustSchedulingParams();
4801cb0ef41Sopenharmony_ci      }
4811cb0ef41Sopenharmony_ci      per_thread = new PerIsolateThreadData(this, thread_id);
4821cb0ef41Sopenharmony_ci      thread_data_table_.Insert(per_thread);
4831cb0ef41Sopenharmony_ci    }
4841cb0ef41Sopenharmony_ci    DCHECK(thread_data_table_.Lookup(thread_id) == per_thread);
4851cb0ef41Sopenharmony_ci  }
4861cb0ef41Sopenharmony_ci  return per_thread;
4871cb0ef41Sopenharmony_ci}
4881cb0ef41Sopenharmony_ci
4891cb0ef41Sopenharmony_civoid Isolate::DiscardPerThreadDataForThisThread() {
4901cb0ef41Sopenharmony_ci  ThreadId thread_id = ThreadId::TryGetCurrent();
4911cb0ef41Sopenharmony_ci  if (thread_id.IsValid()) {
4921cb0ef41Sopenharmony_ci    DCHECK_NE(thread_manager_->mutex_owner_.load(std::memory_order_relaxed),
4931cb0ef41Sopenharmony_ci              thread_id);
4941cb0ef41Sopenharmony_ci    base::MutexGuard lock_guard(&thread_data_table_mutex_);
4951cb0ef41Sopenharmony_ci    PerIsolateThreadData* per_thread = thread_data_table_.Lookup(thread_id);
4961cb0ef41Sopenharmony_ci    if (per_thread) {
4971cb0ef41Sopenharmony_ci      DCHECK(!per_thread->thread_state_);
4981cb0ef41Sopenharmony_ci      thread_data_table_.Remove(per_thread);
4991cb0ef41Sopenharmony_ci    }
5001cb0ef41Sopenharmony_ci  }
5011cb0ef41Sopenharmony_ci}
5021cb0ef41Sopenharmony_ci
5031cb0ef41Sopenharmony_ciIsolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() {
5041cb0ef41Sopenharmony_ci  ThreadId thread_id = ThreadId::Current();
5051cb0ef41Sopenharmony_ci  return FindPerThreadDataForThread(thread_id);
5061cb0ef41Sopenharmony_ci}
5071cb0ef41Sopenharmony_ci
5081cb0ef41Sopenharmony_ciIsolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread(
5091cb0ef41Sopenharmony_ci    ThreadId thread_id) {
5101cb0ef41Sopenharmony_ci  PerIsolateThreadData* per_thread = nullptr;
5111cb0ef41Sopenharmony_ci  {
5121cb0ef41Sopenharmony_ci    base::MutexGuard lock_guard(&thread_data_table_mutex_);
5131cb0ef41Sopenharmony_ci    per_thread = thread_data_table_.Lookup(thread_id);
5141cb0ef41Sopenharmony_ci  }
5151cb0ef41Sopenharmony_ci  return per_thread;
5161cb0ef41Sopenharmony_ci}
5171cb0ef41Sopenharmony_ci
5181cb0ef41Sopenharmony_civoid Isolate::InitializeOncePerProcess() {
5191cb0ef41Sopenharmony_ci  isolate_key_ = base::Thread::CreateThreadLocalKey();
5201cb0ef41Sopenharmony_ci  bool expected = false;
5211cb0ef41Sopenharmony_ci  CHECK(isolate_key_created_.compare_exchange_strong(
5221cb0ef41Sopenharmony_ci      expected, true, std::memory_order_relaxed));
5231cb0ef41Sopenharmony_ci  per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey();
5241cb0ef41Sopenharmony_ci
5251cb0ef41Sopenharmony_ci  Heap::InitializeOncePerProcess();
5261cb0ef41Sopenharmony_ci}
5271cb0ef41Sopenharmony_ci
5281cb0ef41Sopenharmony_civoid Isolate::DisposeOncePerProcess() {
5291cb0ef41Sopenharmony_ci  base::Thread::DeleteThreadLocalKey(isolate_key_);
5301cb0ef41Sopenharmony_ci  bool expected = true;
5311cb0ef41Sopenharmony_ci  CHECK(isolate_key_created_.compare_exchange_strong(
5321cb0ef41Sopenharmony_ci      expected, false, std::memory_order_relaxed));
5331cb0ef41Sopenharmony_ci  base::Thread::DeleteThreadLocalKey(per_isolate_thread_data_key_);
5341cb0ef41Sopenharmony_ci}
5351cb0ef41Sopenharmony_ci
5361cb0ef41Sopenharmony_ciAddress Isolate::get_address_from_id(IsolateAddressId id) {
5371cb0ef41Sopenharmony_ci  return isolate_addresses_[id];
5381cb0ef41Sopenharmony_ci}
5391cb0ef41Sopenharmony_ci
5401cb0ef41Sopenharmony_cichar* Isolate::Iterate(RootVisitor* v, char* thread_storage) {
5411cb0ef41Sopenharmony_ci  ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage);
5421cb0ef41Sopenharmony_ci  Iterate(v, thread);
5431cb0ef41Sopenharmony_ci  return thread_storage + sizeof(ThreadLocalTop);
5441cb0ef41Sopenharmony_ci}
5451cb0ef41Sopenharmony_ci
5461cb0ef41Sopenharmony_civoid Isolate::IterateThread(ThreadVisitor* v, char* t) {
5471cb0ef41Sopenharmony_ci  ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t);
5481cb0ef41Sopenharmony_ci  v->VisitThread(this, thread);
5491cb0ef41Sopenharmony_ci}
5501cb0ef41Sopenharmony_ci
5511cb0ef41Sopenharmony_civoid Isolate::Iterate(RootVisitor* v, ThreadLocalTop* thread) {
5521cb0ef41Sopenharmony_ci  // Visit the roots from the top for a given thread.
5531cb0ef41Sopenharmony_ci  v->VisitRootPointer(Root::kStackRoots, nullptr,
5541cb0ef41Sopenharmony_ci                      FullObjectSlot(&thread->pending_exception_));
5551cb0ef41Sopenharmony_ci  v->VisitRootPointer(Root::kStackRoots, nullptr,
5561cb0ef41Sopenharmony_ci                      FullObjectSlot(&thread->pending_message_));
5571cb0ef41Sopenharmony_ci  v->VisitRootPointer(Root::kStackRoots, nullptr,
5581cb0ef41Sopenharmony_ci                      FullObjectSlot(&thread->context_));
5591cb0ef41Sopenharmony_ci  v->VisitRootPointer(Root::kStackRoots, nullptr,
5601cb0ef41Sopenharmony_ci                      FullObjectSlot(&thread->scheduled_exception_));
5611cb0ef41Sopenharmony_ci
5621cb0ef41Sopenharmony_ci  for (v8::TryCatch* block = thread->try_catch_handler_; block != nullptr;
5631cb0ef41Sopenharmony_ci       block = block->next_) {
5641cb0ef41Sopenharmony_ci    // TODO(3770): Make TryCatch::exception_ an Address (and message_obj_ too).
5651cb0ef41Sopenharmony_ci    v->VisitRootPointer(
5661cb0ef41Sopenharmony_ci        Root::kStackRoots, nullptr,
5671cb0ef41Sopenharmony_ci        FullObjectSlot(reinterpret_cast<Address>(&(block->exception_))));
5681cb0ef41Sopenharmony_ci    v->VisitRootPointer(
5691cb0ef41Sopenharmony_ci        Root::kStackRoots, nullptr,
5701cb0ef41Sopenharmony_ci        FullObjectSlot(reinterpret_cast<Address>(&(block->message_obj_))));
5711cb0ef41Sopenharmony_ci  }
5721cb0ef41Sopenharmony_ci
5731cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_CONSERVATIVE_STACK_SCANNING
5741cb0ef41Sopenharmony_ci  ConservativeStackVisitor stack_visitor(this, v);
5751cb0ef41Sopenharmony_ci  thread_local_top()->stack_.IteratePointers(&stack_visitor);
5761cb0ef41Sopenharmony_ci#endif
5771cb0ef41Sopenharmony_ci
5781cb0ef41Sopenharmony_ci  // Iterate over pointers on native execution stack.
5791cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
5801cb0ef41Sopenharmony_ci  wasm::WasmCodeRefScope wasm_code_ref_scope;
5811cb0ef41Sopenharmony_ci  if (FLAG_experimental_wasm_stack_switching) {
5821cb0ef41Sopenharmony_ci    wasm::StackMemory* current = wasm_stacks_;
5831cb0ef41Sopenharmony_ci    DCHECK_NOT_NULL(current);
5841cb0ef41Sopenharmony_ci    do {
5851cb0ef41Sopenharmony_ci      if (current->IsActive()) {
5861cb0ef41Sopenharmony_ci        // The active stack's jump buffer does not match the current state, use
5871cb0ef41Sopenharmony_ci        // the thread info below instead.
5881cb0ef41Sopenharmony_ci        current = current->next();
5891cb0ef41Sopenharmony_ci        continue;
5901cb0ef41Sopenharmony_ci      }
5911cb0ef41Sopenharmony_ci      for (StackFrameIterator it(this, current); !it.done(); it.Advance()) {
5921cb0ef41Sopenharmony_ci        it.frame()->Iterate(v);
5931cb0ef41Sopenharmony_ci      }
5941cb0ef41Sopenharmony_ci      current = current->next();
5951cb0ef41Sopenharmony_ci    } while (current != wasm_stacks_);
5961cb0ef41Sopenharmony_ci  }
5971cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
5981cb0ef41Sopenharmony_ci  for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) {
5991cb0ef41Sopenharmony_ci    it.frame()->Iterate(v);
6001cb0ef41Sopenharmony_ci  }
6011cb0ef41Sopenharmony_ci}
6021cb0ef41Sopenharmony_ci
6031cb0ef41Sopenharmony_civoid Isolate::Iterate(RootVisitor* v) {
6041cb0ef41Sopenharmony_ci  ThreadLocalTop* current_t = thread_local_top();
6051cb0ef41Sopenharmony_ci  Iterate(v, current_t);
6061cb0ef41Sopenharmony_ci}
6071cb0ef41Sopenharmony_ci
6081cb0ef41Sopenharmony_civoid Isolate::RegisterTryCatchHandler(v8::TryCatch* that) {
6091cb0ef41Sopenharmony_ci  thread_local_top()->try_catch_handler_ = that;
6101cb0ef41Sopenharmony_ci}
6111cb0ef41Sopenharmony_ci
6121cb0ef41Sopenharmony_civoid Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) {
6131cb0ef41Sopenharmony_ci  DCHECK(thread_local_top()->try_catch_handler_ == that);
6141cb0ef41Sopenharmony_ci  thread_local_top()->try_catch_handler_ = that->next_;
6151cb0ef41Sopenharmony_ci}
6161cb0ef41Sopenharmony_ci
6171cb0ef41Sopenharmony_ciHandle<String> Isolate::StackTraceString() {
6181cb0ef41Sopenharmony_ci  if (stack_trace_nesting_level_ == 0) {
6191cb0ef41Sopenharmony_ci    stack_trace_nesting_level_++;
6201cb0ef41Sopenharmony_ci    HeapStringAllocator allocator;
6211cb0ef41Sopenharmony_ci    StringStream::ClearMentionedObjectCache(this);
6221cb0ef41Sopenharmony_ci    StringStream accumulator(&allocator);
6231cb0ef41Sopenharmony_ci    incomplete_message_ = &accumulator;
6241cb0ef41Sopenharmony_ci    PrintStack(&accumulator);
6251cb0ef41Sopenharmony_ci    Handle<String> stack_trace = accumulator.ToString(this);
6261cb0ef41Sopenharmony_ci    incomplete_message_ = nullptr;
6271cb0ef41Sopenharmony_ci    stack_trace_nesting_level_ = 0;
6281cb0ef41Sopenharmony_ci    return stack_trace;
6291cb0ef41Sopenharmony_ci  } else if (stack_trace_nesting_level_ == 1) {
6301cb0ef41Sopenharmony_ci    stack_trace_nesting_level_++;
6311cb0ef41Sopenharmony_ci    base::OS::PrintError(
6321cb0ef41Sopenharmony_ci        "\n\nAttempt to print stack while printing stack (double fault)\n");
6331cb0ef41Sopenharmony_ci    base::OS::PrintError(
6341cb0ef41Sopenharmony_ci        "If you are lucky you may find a partial stack dump on stdout.\n\n");
6351cb0ef41Sopenharmony_ci    incomplete_message_->OutputToStdOut();
6361cb0ef41Sopenharmony_ci    return factory()->empty_string();
6371cb0ef41Sopenharmony_ci  } else {
6381cb0ef41Sopenharmony_ci    base::OS::Abort();
6391cb0ef41Sopenharmony_ci  }
6401cb0ef41Sopenharmony_ci}
6411cb0ef41Sopenharmony_ci
6421cb0ef41Sopenharmony_civoid Isolate::PushStackTraceAndDie(void* ptr1, void* ptr2, void* ptr3,
6431cb0ef41Sopenharmony_ci                                   void* ptr4) {
6441cb0ef41Sopenharmony_ci  StackTraceFailureMessage message(this,
6451cb0ef41Sopenharmony_ci                                   StackTraceFailureMessage::kIncludeStackTrace,
6461cb0ef41Sopenharmony_ci                                   ptr1, ptr2, ptr3, ptr4);
6471cb0ef41Sopenharmony_ci  message.Print();
6481cb0ef41Sopenharmony_ci  base::OS::Abort();
6491cb0ef41Sopenharmony_ci}
6501cb0ef41Sopenharmony_ci
6511cb0ef41Sopenharmony_civoid Isolate::PushParamsAndDie(void* ptr1, void* ptr2, void* ptr3, void* ptr4,
6521cb0ef41Sopenharmony_ci                               void* ptr5, void* ptr6) {
6531cb0ef41Sopenharmony_ci  StackTraceFailureMessage message(
6541cb0ef41Sopenharmony_ci      this, StackTraceFailureMessage::kDontIncludeStackTrace, ptr1, ptr2, ptr3,
6551cb0ef41Sopenharmony_ci      ptr4, ptr5, ptr6);
6561cb0ef41Sopenharmony_ci  message.Print();
6571cb0ef41Sopenharmony_ci  base::OS::Abort();
6581cb0ef41Sopenharmony_ci}
6591cb0ef41Sopenharmony_ci
6601cb0ef41Sopenharmony_civoid StackTraceFailureMessage::Print() volatile {
6611cb0ef41Sopenharmony_ci  // Print the details of this failure message object, including its own address
6621cb0ef41Sopenharmony_ci  // to force stack allocation.
6631cb0ef41Sopenharmony_ci  base::OS::PrintError(
6641cb0ef41Sopenharmony_ci      "Stacktrace:\n    ptr1=%p\n    ptr2=%p\n    ptr3=%p\n    ptr4=%p\n    "
6651cb0ef41Sopenharmony_ci      "ptr5=%p\n    ptr6=%p\n    failure_message_object=%p\n%s",
6661cb0ef41Sopenharmony_ci      ptr1_, ptr2_, ptr3_, ptr4_, ptr5_, ptr6_, this, &js_stack_trace_[0]);
6671cb0ef41Sopenharmony_ci}
6681cb0ef41Sopenharmony_ci
6691cb0ef41Sopenharmony_ciStackTraceFailureMessage::StackTraceFailureMessage(
6701cb0ef41Sopenharmony_ci    Isolate* isolate, StackTraceFailureMessage::StackTraceMode mode, void* ptr1,
6711cb0ef41Sopenharmony_ci    void* ptr2, void* ptr3, void* ptr4, void* ptr5, void* ptr6) {
6721cb0ef41Sopenharmony_ci  isolate_ = isolate;
6731cb0ef41Sopenharmony_ci  ptr1_ = ptr1;
6741cb0ef41Sopenharmony_ci  ptr2_ = ptr2;
6751cb0ef41Sopenharmony_ci  ptr3_ = ptr3;
6761cb0ef41Sopenharmony_ci  ptr4_ = ptr4;
6771cb0ef41Sopenharmony_ci  ptr5_ = ptr5;
6781cb0ef41Sopenharmony_ci  ptr6_ = ptr6;
6791cb0ef41Sopenharmony_ci  // Write a stracktrace into the {js_stack_trace_} buffer.
6801cb0ef41Sopenharmony_ci  const size_t buffer_length = arraysize(js_stack_trace_);
6811cb0ef41Sopenharmony_ci  memset(&js_stack_trace_, 0, buffer_length);
6821cb0ef41Sopenharmony_ci  memset(&code_objects_, 0, sizeof(code_objects_));
6831cb0ef41Sopenharmony_ci  if (mode == kIncludeStackTrace) {
6841cb0ef41Sopenharmony_ci    FixedStringAllocator fixed(&js_stack_trace_[0], buffer_length - 1);
6851cb0ef41Sopenharmony_ci    StringStream accumulator(&fixed, StringStream::kPrintObjectConcise);
6861cb0ef41Sopenharmony_ci    isolate->PrintStack(&accumulator, Isolate::kPrintStackVerbose);
6871cb0ef41Sopenharmony_ci    // Keeping a reference to the last code objects to increase likelyhood that
6881cb0ef41Sopenharmony_ci    // they get included in the minidump.
6891cb0ef41Sopenharmony_ci    const size_t code_objects_length = arraysize(code_objects_);
6901cb0ef41Sopenharmony_ci    size_t i = 0;
6911cb0ef41Sopenharmony_ci    StackFrameIterator it(isolate);
6921cb0ef41Sopenharmony_ci    for (; !it.done() && i < code_objects_length; it.Advance()) {
6931cb0ef41Sopenharmony_ci      code_objects_[i++] =
6941cb0ef41Sopenharmony_ci          reinterpret_cast<void*>(it.frame()->unchecked_code().ptr());
6951cb0ef41Sopenharmony_ci    }
6961cb0ef41Sopenharmony_ci  }
6971cb0ef41Sopenharmony_ci}
6981cb0ef41Sopenharmony_ci
6991cb0ef41Sopenharmony_cibool NoExtension(const v8::FunctionCallbackInfo<v8::Value>&) { return false; }
7001cb0ef41Sopenharmony_ci
7011cb0ef41Sopenharmony_cinamespace {
7021cb0ef41Sopenharmony_ci
7031cb0ef41Sopenharmony_ciclass CallSiteBuilder {
7041cb0ef41Sopenharmony_ci public:
7051cb0ef41Sopenharmony_ci  CallSiteBuilder(Isolate* isolate, FrameSkipMode mode, int limit,
7061cb0ef41Sopenharmony_ci                  Handle<Object> caller)
7071cb0ef41Sopenharmony_ci      : isolate_(isolate),
7081cb0ef41Sopenharmony_ci        mode_(mode),
7091cb0ef41Sopenharmony_ci        limit_(limit),
7101cb0ef41Sopenharmony_ci        caller_(caller),
7111cb0ef41Sopenharmony_ci        skip_next_frame_(mode != SKIP_NONE) {
7121cb0ef41Sopenharmony_ci    DCHECK_IMPLIES(mode_ == SKIP_UNTIL_SEEN, caller_->IsJSFunction());
7131cb0ef41Sopenharmony_ci    // Modern web applications are usually built with multiple layers of
7141cb0ef41Sopenharmony_ci    // framework and library code, and stack depth tends to be more than
7151cb0ef41Sopenharmony_ci    // a dozen frames, so we over-allocate a bit here to avoid growing
7161cb0ef41Sopenharmony_ci    // the elements array in the common case.
7171cb0ef41Sopenharmony_ci    elements_ = isolate->factory()->NewFixedArray(std::min(64, limit));
7181cb0ef41Sopenharmony_ci  }
7191cb0ef41Sopenharmony_ci
7201cb0ef41Sopenharmony_ci  bool Visit(FrameSummary const& summary) {
7211cb0ef41Sopenharmony_ci    if (Full()) return false;
7221cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
7231cb0ef41Sopenharmony_ci    if (summary.IsWasm()) {
7241cb0ef41Sopenharmony_ci      AppendWasmFrame(summary.AsWasm());
7251cb0ef41Sopenharmony_ci      return true;
7261cb0ef41Sopenharmony_ci    }
7271cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
7281cb0ef41Sopenharmony_ci    AppendJavaScriptFrame(summary.AsJavaScript());
7291cb0ef41Sopenharmony_ci    return true;
7301cb0ef41Sopenharmony_ci  }
7311cb0ef41Sopenharmony_ci
7321cb0ef41Sopenharmony_ci  void AppendAsyncFrame(Handle<JSGeneratorObject> generator_object) {
7331cb0ef41Sopenharmony_ci    Handle<JSFunction> function(generator_object->function(), isolate_);
7341cb0ef41Sopenharmony_ci    if (!IsVisibleInStackTrace(function)) return;
7351cb0ef41Sopenharmony_ci    int flags = CallSiteInfo::kIsAsync;
7361cb0ef41Sopenharmony_ci    if (IsStrictFrame(function)) flags |= CallSiteInfo::kIsStrict;
7371cb0ef41Sopenharmony_ci
7381cb0ef41Sopenharmony_ci    Handle<Object> receiver(generator_object->receiver(), isolate_);
7391cb0ef41Sopenharmony_ci    Handle<BytecodeArray> code(function->shared().GetBytecodeArray(isolate_),
7401cb0ef41Sopenharmony_ci                               isolate_);
7411cb0ef41Sopenharmony_ci    // The stored bytecode offset is relative to a different base than what
7421cb0ef41Sopenharmony_ci    // is used in the source position table, hence the subtraction.
7431cb0ef41Sopenharmony_ci    int offset = Smi::ToInt(generator_object->input_or_debug_pos()) -
7441cb0ef41Sopenharmony_ci                 (BytecodeArray::kHeaderSize - kHeapObjectTag);
7451cb0ef41Sopenharmony_ci
7461cb0ef41Sopenharmony_ci    Handle<FixedArray> parameters = isolate_->factory()->empty_fixed_array();
7471cb0ef41Sopenharmony_ci    if (V8_UNLIKELY(FLAG_detailed_error_stack_trace)) {
7481cb0ef41Sopenharmony_ci      parameters = isolate_->factory()->CopyFixedArrayUpTo(
7491cb0ef41Sopenharmony_ci          handle(generator_object->parameters_and_registers(), isolate_),
7501cb0ef41Sopenharmony_ci          function->shared()
7511cb0ef41Sopenharmony_ci              .internal_formal_parameter_count_without_receiver());
7521cb0ef41Sopenharmony_ci    }
7531cb0ef41Sopenharmony_ci
7541cb0ef41Sopenharmony_ci    AppendFrame(receiver, function, code, offset, flags, parameters);
7551cb0ef41Sopenharmony_ci  }
7561cb0ef41Sopenharmony_ci
7571cb0ef41Sopenharmony_ci  void AppendPromiseCombinatorFrame(Handle<JSFunction> element_function,
7581cb0ef41Sopenharmony_ci                                    Handle<JSFunction> combinator) {
7591cb0ef41Sopenharmony_ci    if (!IsVisibleInStackTrace(combinator)) return;
7601cb0ef41Sopenharmony_ci    int flags =
7611cb0ef41Sopenharmony_ci        CallSiteInfo::kIsAsync | CallSiteInfo::kIsSourcePositionComputed;
7621cb0ef41Sopenharmony_ci
7631cb0ef41Sopenharmony_ci    Handle<Object> receiver(combinator->native_context().promise_function(),
7641cb0ef41Sopenharmony_ci                            isolate_);
7651cb0ef41Sopenharmony_ci    // TODO(v8:11880): avoid roundtrips between cdc and code.
7661cb0ef41Sopenharmony_ci    Handle<Code> code(FromCodeT(combinator->code()), isolate_);
7671cb0ef41Sopenharmony_ci
7681cb0ef41Sopenharmony_ci    // TODO(mmarchini) save Promises list from the Promise combinator
7691cb0ef41Sopenharmony_ci    Handle<FixedArray> parameters = isolate_->factory()->empty_fixed_array();
7701cb0ef41Sopenharmony_ci
7711cb0ef41Sopenharmony_ci    // We store the offset of the promise into the element function's
7721cb0ef41Sopenharmony_ci    // hash field for element callbacks.
7731cb0ef41Sopenharmony_ci    int promise_index =
7741cb0ef41Sopenharmony_ci        Smi::ToInt(Smi::cast(element_function->GetIdentityHash())) - 1;
7751cb0ef41Sopenharmony_ci
7761cb0ef41Sopenharmony_ci    AppendFrame(receiver, combinator, code, promise_index, flags, parameters);
7771cb0ef41Sopenharmony_ci  }
7781cb0ef41Sopenharmony_ci
7791cb0ef41Sopenharmony_ci  void AppendJavaScriptFrame(
7801cb0ef41Sopenharmony_ci      FrameSummary::JavaScriptFrameSummary const& summary) {
7811cb0ef41Sopenharmony_ci    // Filter out internal frames that we do not want to show.
7821cb0ef41Sopenharmony_ci    if (!IsVisibleInStackTrace(summary.function())) return;
7831cb0ef41Sopenharmony_ci
7841cb0ef41Sopenharmony_ci    int flags = 0;
7851cb0ef41Sopenharmony_ci    Handle<JSFunction> function = summary.function();
7861cb0ef41Sopenharmony_ci    if (IsStrictFrame(function)) flags |= CallSiteInfo::kIsStrict;
7871cb0ef41Sopenharmony_ci    if (summary.is_constructor()) flags |= CallSiteInfo::kIsConstructor;
7881cb0ef41Sopenharmony_ci
7891cb0ef41Sopenharmony_ci    AppendFrame(summary.receiver(), function, summary.abstract_code(),
7901cb0ef41Sopenharmony_ci                summary.code_offset(), flags, summary.parameters());
7911cb0ef41Sopenharmony_ci  }
7921cb0ef41Sopenharmony_ci
7931cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
7941cb0ef41Sopenharmony_ci  void AppendWasmFrame(FrameSummary::WasmFrameSummary const& summary) {
7951cb0ef41Sopenharmony_ci    if (summary.code()->kind() != wasm::WasmCode::kWasmFunction) return;
7961cb0ef41Sopenharmony_ci    Handle<WasmInstanceObject> instance = summary.wasm_instance();
7971cb0ef41Sopenharmony_ci    int flags = CallSiteInfo::kIsWasm;
7981cb0ef41Sopenharmony_ci    if (instance->module_object().is_asm_js()) {
7991cb0ef41Sopenharmony_ci      flags |= CallSiteInfo::kIsAsmJsWasm;
8001cb0ef41Sopenharmony_ci      if (summary.at_to_number_conversion()) {
8011cb0ef41Sopenharmony_ci        flags |= CallSiteInfo::kIsAsmJsAtNumberConversion;
8021cb0ef41Sopenharmony_ci      }
8031cb0ef41Sopenharmony_ci    }
8041cb0ef41Sopenharmony_ci
8051cb0ef41Sopenharmony_ci    auto code = Managed<wasm::GlobalWasmCodeRef>::Allocate(
8061cb0ef41Sopenharmony_ci        isolate_, 0, summary.code(),
8071cb0ef41Sopenharmony_ci        instance->module_object().shared_native_module());
8081cb0ef41Sopenharmony_ci    AppendFrame(instance,
8091cb0ef41Sopenharmony_ci                handle(Smi::FromInt(summary.function_index()), isolate_), code,
8101cb0ef41Sopenharmony_ci                summary.code_offset(), flags,
8111cb0ef41Sopenharmony_ci                isolate_->factory()->empty_fixed_array());
8121cb0ef41Sopenharmony_ci  }
8131cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
8141cb0ef41Sopenharmony_ci
8151cb0ef41Sopenharmony_ci  bool Full() { return index_ >= limit_; }
8161cb0ef41Sopenharmony_ci
8171cb0ef41Sopenharmony_ci  Handle<FixedArray> Build() {
8181cb0ef41Sopenharmony_ci    return FixedArray::ShrinkOrEmpty(isolate_, elements_, index_);
8191cb0ef41Sopenharmony_ci  }
8201cb0ef41Sopenharmony_ci
8211cb0ef41Sopenharmony_ci private:
8221cb0ef41Sopenharmony_ci  // Poison stack frames below the first strict mode frame.
8231cb0ef41Sopenharmony_ci  // The stack trace API should not expose receivers and function
8241cb0ef41Sopenharmony_ci  // objects on frames deeper than the top-most one with a strict mode
8251cb0ef41Sopenharmony_ci  // function.
8261cb0ef41Sopenharmony_ci  bool IsStrictFrame(Handle<JSFunction> function) {
8271cb0ef41Sopenharmony_ci    if (!encountered_strict_function_) {
8281cb0ef41Sopenharmony_ci      encountered_strict_function_ =
8291cb0ef41Sopenharmony_ci          is_strict(function->shared().language_mode());
8301cb0ef41Sopenharmony_ci    }
8311cb0ef41Sopenharmony_ci    return encountered_strict_function_;
8321cb0ef41Sopenharmony_ci  }
8331cb0ef41Sopenharmony_ci
8341cb0ef41Sopenharmony_ci  // Determines whether the given stack frame should be displayed in a stack
8351cb0ef41Sopenharmony_ci  // trace.
8361cb0ef41Sopenharmony_ci  bool IsVisibleInStackTrace(Handle<JSFunction> function) {
8371cb0ef41Sopenharmony_ci    return ShouldIncludeFrame(function) && IsNotHidden(function);
8381cb0ef41Sopenharmony_ci  }
8391cb0ef41Sopenharmony_ci
8401cb0ef41Sopenharmony_ci  // This mechanism excludes a number of uninteresting frames from the stack
8411cb0ef41Sopenharmony_ci  // trace. This can be be the first frame (which will be a builtin-exit frame
8421cb0ef41Sopenharmony_ci  // for the error constructor builtin) or every frame until encountering a
8431cb0ef41Sopenharmony_ci  // user-specified function.
8441cb0ef41Sopenharmony_ci  bool ShouldIncludeFrame(Handle<JSFunction> function) {
8451cb0ef41Sopenharmony_ci    switch (mode_) {
8461cb0ef41Sopenharmony_ci      case SKIP_NONE:
8471cb0ef41Sopenharmony_ci        return true;
8481cb0ef41Sopenharmony_ci      case SKIP_FIRST:
8491cb0ef41Sopenharmony_ci        if (!skip_next_frame_) return true;
8501cb0ef41Sopenharmony_ci        skip_next_frame_ = false;
8511cb0ef41Sopenharmony_ci        return false;
8521cb0ef41Sopenharmony_ci      case SKIP_UNTIL_SEEN:
8531cb0ef41Sopenharmony_ci        if (skip_next_frame_ && (*function == *caller_)) {
8541cb0ef41Sopenharmony_ci          skip_next_frame_ = false;
8551cb0ef41Sopenharmony_ci          return false;
8561cb0ef41Sopenharmony_ci        }
8571cb0ef41Sopenharmony_ci        return !skip_next_frame_;
8581cb0ef41Sopenharmony_ci    }
8591cb0ef41Sopenharmony_ci    UNREACHABLE();
8601cb0ef41Sopenharmony_ci  }
8611cb0ef41Sopenharmony_ci
8621cb0ef41Sopenharmony_ci  bool IsNotHidden(Handle<JSFunction> function) {
8631cb0ef41Sopenharmony_ci    // TODO(szuend): Remove this check once the flag is enabled
8641cb0ef41Sopenharmony_ci    //               by default.
8651cb0ef41Sopenharmony_ci    if (!FLAG_experimental_stack_trace_frames &&
8661cb0ef41Sopenharmony_ci        function->shared().IsApiFunction()) {
8671cb0ef41Sopenharmony_ci      return false;
8681cb0ef41Sopenharmony_ci    }
8691cb0ef41Sopenharmony_ci    // Functions defined not in user scripts are not visible unless directly
8701cb0ef41Sopenharmony_ci    // exposed, in which case the native flag is set.
8711cb0ef41Sopenharmony_ci    // The --builtins-in-stack-traces command line flag allows including
8721cb0ef41Sopenharmony_ci    // internal call sites in the stack trace for debugging purposes.
8731cb0ef41Sopenharmony_ci    if (!FLAG_builtins_in_stack_traces &&
8741cb0ef41Sopenharmony_ci        !function->shared().IsUserJavaScript()) {
8751cb0ef41Sopenharmony_ci      return function->shared().native() || function->shared().IsApiFunction();
8761cb0ef41Sopenharmony_ci    }
8771cb0ef41Sopenharmony_ci    return true;
8781cb0ef41Sopenharmony_ci  }
8791cb0ef41Sopenharmony_ci
8801cb0ef41Sopenharmony_ci  void AppendFrame(Handle<Object> receiver_or_instance, Handle<Object> function,
8811cb0ef41Sopenharmony_ci                   Handle<HeapObject> code, int offset, int flags,
8821cb0ef41Sopenharmony_ci                   Handle<FixedArray> parameters) {
8831cb0ef41Sopenharmony_ci    if (receiver_or_instance->IsTheHole(isolate_)) {
8841cb0ef41Sopenharmony_ci      // TODO(jgruber): Fix all cases in which frames give us a hole value
8851cb0ef41Sopenharmony_ci      // (e.g. the receiver in RegExp constructor frames).
8861cb0ef41Sopenharmony_ci      receiver_or_instance = isolate_->factory()->undefined_value();
8871cb0ef41Sopenharmony_ci    }
8881cb0ef41Sopenharmony_ci    auto info = isolate_->factory()->NewCallSiteInfo(
8891cb0ef41Sopenharmony_ci        receiver_or_instance, function, code, offset, flags, parameters);
8901cb0ef41Sopenharmony_ci    elements_ = FixedArray::SetAndGrow(isolate_, elements_, index_++, info);
8911cb0ef41Sopenharmony_ci  }
8921cb0ef41Sopenharmony_ci
8931cb0ef41Sopenharmony_ci  Isolate* isolate_;
8941cb0ef41Sopenharmony_ci  const FrameSkipMode mode_;
8951cb0ef41Sopenharmony_ci  int index_ = 0;
8961cb0ef41Sopenharmony_ci  const int limit_;
8971cb0ef41Sopenharmony_ci  const Handle<Object> caller_;
8981cb0ef41Sopenharmony_ci  bool skip_next_frame_;
8991cb0ef41Sopenharmony_ci  bool encountered_strict_function_ = false;
9001cb0ef41Sopenharmony_ci  Handle<FixedArray> elements_;
9011cb0ef41Sopenharmony_ci};
9021cb0ef41Sopenharmony_ci
9031cb0ef41Sopenharmony_cibool GetStackTraceLimit(Isolate* isolate, int* result) {
9041cb0ef41Sopenharmony_ci  if (FLAG_correctness_fuzzer_suppressions) return false;
9051cb0ef41Sopenharmony_ci  Handle<JSObject> error = isolate->error_function();
9061cb0ef41Sopenharmony_ci
9071cb0ef41Sopenharmony_ci  Handle<String> key = isolate->factory()->stackTraceLimit_string();
9081cb0ef41Sopenharmony_ci  Handle<Object> stack_trace_limit =
9091cb0ef41Sopenharmony_ci      JSReceiver::GetDataProperty(isolate, error, key);
9101cb0ef41Sopenharmony_ci  if (!stack_trace_limit->IsNumber()) return false;
9111cb0ef41Sopenharmony_ci
9121cb0ef41Sopenharmony_ci  // Ensure that limit is not negative.
9131cb0ef41Sopenharmony_ci  *result = std::max(FastD2IChecked(stack_trace_limit->Number()), 0);
9141cb0ef41Sopenharmony_ci
9151cb0ef41Sopenharmony_ci  if (*result != FLAG_stack_trace_limit) {
9161cb0ef41Sopenharmony_ci    isolate->CountUsage(v8::Isolate::kErrorStackTraceLimit);
9171cb0ef41Sopenharmony_ci  }
9181cb0ef41Sopenharmony_ci
9191cb0ef41Sopenharmony_ci  return true;
9201cb0ef41Sopenharmony_ci}
9211cb0ef41Sopenharmony_ci
9221cb0ef41Sopenharmony_cibool IsBuiltinFunction(Isolate* isolate, HeapObject object, Builtin builtin) {
9231cb0ef41Sopenharmony_ci  if (!object.IsJSFunction()) return false;
9241cb0ef41Sopenharmony_ci  JSFunction const function = JSFunction::cast(object);
9251cb0ef41Sopenharmony_ci  return function.code() == isolate->builtins()->code(builtin);
9261cb0ef41Sopenharmony_ci}
9271cb0ef41Sopenharmony_ci
9281cb0ef41Sopenharmony_civoid CaptureAsyncStackTrace(Isolate* isolate, Handle<JSPromise> promise,
9291cb0ef41Sopenharmony_ci                            CallSiteBuilder* builder) {
9301cb0ef41Sopenharmony_ci  while (!builder->Full()) {
9311cb0ef41Sopenharmony_ci    // Check that the {promise} is not settled.
9321cb0ef41Sopenharmony_ci    if (promise->status() != Promise::kPending) return;
9331cb0ef41Sopenharmony_ci
9341cb0ef41Sopenharmony_ci    // Check that we have exactly one PromiseReaction on the {promise}.
9351cb0ef41Sopenharmony_ci    if (!promise->reactions().IsPromiseReaction()) return;
9361cb0ef41Sopenharmony_ci    Handle<PromiseReaction> reaction(
9371cb0ef41Sopenharmony_ci        PromiseReaction::cast(promise->reactions()), isolate);
9381cb0ef41Sopenharmony_ci    if (!reaction->next().IsSmi()) return;
9391cb0ef41Sopenharmony_ci
9401cb0ef41Sopenharmony_ci    // Check if the {reaction} has one of the known async function or
9411cb0ef41Sopenharmony_ci    // async generator continuations as its fulfill handler.
9421cb0ef41Sopenharmony_ci    if (IsBuiltinFunction(isolate, reaction->fulfill_handler(),
9431cb0ef41Sopenharmony_ci                          Builtin::kAsyncFunctionAwaitResolveClosure) ||
9441cb0ef41Sopenharmony_ci        IsBuiltinFunction(isolate, reaction->fulfill_handler(),
9451cb0ef41Sopenharmony_ci                          Builtin::kAsyncGeneratorAwaitResolveClosure) ||
9461cb0ef41Sopenharmony_ci        IsBuiltinFunction(isolate, reaction->fulfill_handler(),
9471cb0ef41Sopenharmony_ci                          Builtin::kAsyncGeneratorYieldResolveClosure)) {
9481cb0ef41Sopenharmony_ci      // Now peek into the handlers' AwaitContext to get to
9491cb0ef41Sopenharmony_ci      // the JSGeneratorObject for the async function.
9501cb0ef41Sopenharmony_ci      Handle<Context> context(
9511cb0ef41Sopenharmony_ci          JSFunction::cast(reaction->fulfill_handler()).context(), isolate);
9521cb0ef41Sopenharmony_ci      Handle<JSGeneratorObject> generator_object(
9531cb0ef41Sopenharmony_ci          JSGeneratorObject::cast(context->extension()), isolate);
9541cb0ef41Sopenharmony_ci      CHECK(generator_object->is_suspended());
9551cb0ef41Sopenharmony_ci
9561cb0ef41Sopenharmony_ci      // Append async frame corresponding to the {generator_object}.
9571cb0ef41Sopenharmony_ci      builder->AppendAsyncFrame(generator_object);
9581cb0ef41Sopenharmony_ci
9591cb0ef41Sopenharmony_ci      // Try to continue from here.
9601cb0ef41Sopenharmony_ci      if (generator_object->IsJSAsyncFunctionObject()) {
9611cb0ef41Sopenharmony_ci        Handle<JSAsyncFunctionObject> async_function_object =
9621cb0ef41Sopenharmony_ci            Handle<JSAsyncFunctionObject>::cast(generator_object);
9631cb0ef41Sopenharmony_ci        promise = handle(async_function_object->promise(), isolate);
9641cb0ef41Sopenharmony_ci      } else {
9651cb0ef41Sopenharmony_ci        Handle<JSAsyncGeneratorObject> async_generator_object =
9661cb0ef41Sopenharmony_ci            Handle<JSAsyncGeneratorObject>::cast(generator_object);
9671cb0ef41Sopenharmony_ci        if (async_generator_object->queue().IsUndefined(isolate)) return;
9681cb0ef41Sopenharmony_ci        Handle<AsyncGeneratorRequest> async_generator_request(
9691cb0ef41Sopenharmony_ci            AsyncGeneratorRequest::cast(async_generator_object->queue()),
9701cb0ef41Sopenharmony_ci            isolate);
9711cb0ef41Sopenharmony_ci        promise = handle(JSPromise::cast(async_generator_request->promise()),
9721cb0ef41Sopenharmony_ci                         isolate);
9731cb0ef41Sopenharmony_ci      }
9741cb0ef41Sopenharmony_ci    } else if (IsBuiltinFunction(isolate, reaction->fulfill_handler(),
9751cb0ef41Sopenharmony_ci                                 Builtin::kPromiseAllResolveElementClosure)) {
9761cb0ef41Sopenharmony_ci      Handle<JSFunction> function(JSFunction::cast(reaction->fulfill_handler()),
9771cb0ef41Sopenharmony_ci                                  isolate);
9781cb0ef41Sopenharmony_ci      Handle<Context> context(function->context(), isolate);
9791cb0ef41Sopenharmony_ci      Handle<JSFunction> combinator(context->native_context().promise_all(),
9801cb0ef41Sopenharmony_ci                                    isolate);
9811cb0ef41Sopenharmony_ci      builder->AppendPromiseCombinatorFrame(function, combinator);
9821cb0ef41Sopenharmony_ci
9831cb0ef41Sopenharmony_ci      // Now peak into the Promise.all() resolve element context to
9841cb0ef41Sopenharmony_ci      // find the promise capability that's being resolved when all
9851cb0ef41Sopenharmony_ci      // the concurrent promises resolve.
9861cb0ef41Sopenharmony_ci      int const index =
9871cb0ef41Sopenharmony_ci          PromiseBuiltins::kPromiseAllResolveElementCapabilitySlot;
9881cb0ef41Sopenharmony_ci      Handle<PromiseCapability> capability(
9891cb0ef41Sopenharmony_ci          PromiseCapability::cast(context->get(index)), isolate);
9901cb0ef41Sopenharmony_ci      if (!capability->promise().IsJSPromise()) return;
9911cb0ef41Sopenharmony_ci      promise = handle(JSPromise::cast(capability->promise()), isolate);
9921cb0ef41Sopenharmony_ci    } else if (IsBuiltinFunction(
9931cb0ef41Sopenharmony_ci                   isolate, reaction->fulfill_handler(),
9941cb0ef41Sopenharmony_ci                   Builtin::kPromiseAllSettledResolveElementClosure)) {
9951cb0ef41Sopenharmony_ci      Handle<JSFunction> function(JSFunction::cast(reaction->fulfill_handler()),
9961cb0ef41Sopenharmony_ci                                  isolate);
9971cb0ef41Sopenharmony_ci      Handle<Context> context(function->context(), isolate);
9981cb0ef41Sopenharmony_ci      Handle<JSFunction> combinator(
9991cb0ef41Sopenharmony_ci          context->native_context().promise_all_settled(), isolate);
10001cb0ef41Sopenharmony_ci      builder->AppendPromiseCombinatorFrame(function, combinator);
10011cb0ef41Sopenharmony_ci
10021cb0ef41Sopenharmony_ci      // Now peak into the Promise.allSettled() resolve element context to
10031cb0ef41Sopenharmony_ci      // find the promise capability that's being resolved when all
10041cb0ef41Sopenharmony_ci      // the concurrent promises resolve.
10051cb0ef41Sopenharmony_ci      int const index =
10061cb0ef41Sopenharmony_ci          PromiseBuiltins::kPromiseAllResolveElementCapabilitySlot;
10071cb0ef41Sopenharmony_ci      Handle<PromiseCapability> capability(
10081cb0ef41Sopenharmony_ci          PromiseCapability::cast(context->get(index)), isolate);
10091cb0ef41Sopenharmony_ci      if (!capability->promise().IsJSPromise()) return;
10101cb0ef41Sopenharmony_ci      promise = handle(JSPromise::cast(capability->promise()), isolate);
10111cb0ef41Sopenharmony_ci    } else if (IsBuiltinFunction(isolate, reaction->reject_handler(),
10121cb0ef41Sopenharmony_ci                                 Builtin::kPromiseAnyRejectElementClosure)) {
10131cb0ef41Sopenharmony_ci      Handle<JSFunction> function(JSFunction::cast(reaction->reject_handler()),
10141cb0ef41Sopenharmony_ci                                  isolate);
10151cb0ef41Sopenharmony_ci      Handle<Context> context(function->context(), isolate);
10161cb0ef41Sopenharmony_ci      Handle<JSFunction> combinator(context->native_context().promise_any(),
10171cb0ef41Sopenharmony_ci                                    isolate);
10181cb0ef41Sopenharmony_ci      builder->AppendPromiseCombinatorFrame(function, combinator);
10191cb0ef41Sopenharmony_ci
10201cb0ef41Sopenharmony_ci      // Now peak into the Promise.any() reject element context to
10211cb0ef41Sopenharmony_ci      // find the promise capability that's being resolved when any of
10221cb0ef41Sopenharmony_ci      // the concurrent promises resolve.
10231cb0ef41Sopenharmony_ci      int const index = PromiseBuiltins::kPromiseAnyRejectElementCapabilitySlot;
10241cb0ef41Sopenharmony_ci      Handle<PromiseCapability> capability(
10251cb0ef41Sopenharmony_ci          PromiseCapability::cast(context->get(index)), isolate);
10261cb0ef41Sopenharmony_ci      if (!capability->promise().IsJSPromise()) return;
10271cb0ef41Sopenharmony_ci      promise = handle(JSPromise::cast(capability->promise()), isolate);
10281cb0ef41Sopenharmony_ci    } else if (IsBuiltinFunction(isolate, reaction->fulfill_handler(),
10291cb0ef41Sopenharmony_ci                                 Builtin::kPromiseCapabilityDefaultResolve)) {
10301cb0ef41Sopenharmony_ci      Handle<JSFunction> function(JSFunction::cast(reaction->fulfill_handler()),
10311cb0ef41Sopenharmony_ci                                  isolate);
10321cb0ef41Sopenharmony_ci      Handle<Context> context(function->context(), isolate);
10331cb0ef41Sopenharmony_ci      promise =
10341cb0ef41Sopenharmony_ci          handle(JSPromise::cast(context->get(PromiseBuiltins::kPromiseSlot)),
10351cb0ef41Sopenharmony_ci                 isolate);
10361cb0ef41Sopenharmony_ci    } else {
10371cb0ef41Sopenharmony_ci      // We have some generic promise chain here, so try to
10381cb0ef41Sopenharmony_ci      // continue with the chained promise on the reaction
10391cb0ef41Sopenharmony_ci      // (only works for native promise chains).
10401cb0ef41Sopenharmony_ci      Handle<HeapObject> promise_or_capability(
10411cb0ef41Sopenharmony_ci          reaction->promise_or_capability(), isolate);
10421cb0ef41Sopenharmony_ci      if (promise_or_capability->IsJSPromise()) {
10431cb0ef41Sopenharmony_ci        promise = Handle<JSPromise>::cast(promise_or_capability);
10441cb0ef41Sopenharmony_ci      } else if (promise_or_capability->IsPromiseCapability()) {
10451cb0ef41Sopenharmony_ci        Handle<PromiseCapability> capability =
10461cb0ef41Sopenharmony_ci            Handle<PromiseCapability>::cast(promise_or_capability);
10471cb0ef41Sopenharmony_ci        if (!capability->promise().IsJSPromise()) return;
10481cb0ef41Sopenharmony_ci        promise = handle(JSPromise::cast(capability->promise()), isolate);
10491cb0ef41Sopenharmony_ci      } else {
10501cb0ef41Sopenharmony_ci        // Otherwise the {promise_or_capability} must be undefined here.
10511cb0ef41Sopenharmony_ci        CHECK(promise_or_capability->IsUndefined(isolate));
10521cb0ef41Sopenharmony_ci        return;
10531cb0ef41Sopenharmony_ci      }
10541cb0ef41Sopenharmony_ci    }
10551cb0ef41Sopenharmony_ci  }
10561cb0ef41Sopenharmony_ci}
10571cb0ef41Sopenharmony_ci
10581cb0ef41Sopenharmony_civoid CaptureAsyncStackTrace(Isolate* isolate, CallSiteBuilder* builder) {
10591cb0ef41Sopenharmony_ci  Handle<Object> current_microtask = isolate->factory()->current_microtask();
10601cb0ef41Sopenharmony_ci  if (current_microtask->IsPromiseReactionJobTask()) {
10611cb0ef41Sopenharmony_ci    Handle<PromiseReactionJobTask> promise_reaction_job_task =
10621cb0ef41Sopenharmony_ci        Handle<PromiseReactionJobTask>::cast(current_microtask);
10631cb0ef41Sopenharmony_ci    // Check if the {reaction} has one of the known async function or
10641cb0ef41Sopenharmony_ci    // async generator continuations as its fulfill handler.
10651cb0ef41Sopenharmony_ci    if (IsBuiltinFunction(isolate, promise_reaction_job_task->handler(),
10661cb0ef41Sopenharmony_ci                          Builtin::kAsyncFunctionAwaitResolveClosure) ||
10671cb0ef41Sopenharmony_ci        IsBuiltinFunction(isolate, promise_reaction_job_task->handler(),
10681cb0ef41Sopenharmony_ci                          Builtin::kAsyncGeneratorAwaitResolveClosure) ||
10691cb0ef41Sopenharmony_ci        IsBuiltinFunction(isolate, promise_reaction_job_task->handler(),
10701cb0ef41Sopenharmony_ci                          Builtin::kAsyncGeneratorYieldResolveClosure) ||
10711cb0ef41Sopenharmony_ci        IsBuiltinFunction(isolate, promise_reaction_job_task->handler(),
10721cb0ef41Sopenharmony_ci                          Builtin::kAsyncFunctionAwaitRejectClosure) ||
10731cb0ef41Sopenharmony_ci        IsBuiltinFunction(isolate, promise_reaction_job_task->handler(),
10741cb0ef41Sopenharmony_ci                          Builtin::kAsyncGeneratorAwaitRejectClosure)) {
10751cb0ef41Sopenharmony_ci      // Now peek into the handlers' AwaitContext to get to
10761cb0ef41Sopenharmony_ci      // the JSGeneratorObject for the async function.
10771cb0ef41Sopenharmony_ci      Handle<Context> context(
10781cb0ef41Sopenharmony_ci          JSFunction::cast(promise_reaction_job_task->handler()).context(),
10791cb0ef41Sopenharmony_ci          isolate);
10801cb0ef41Sopenharmony_ci      Handle<JSGeneratorObject> generator_object(
10811cb0ef41Sopenharmony_ci          JSGeneratorObject::cast(context->extension()), isolate);
10821cb0ef41Sopenharmony_ci      if (generator_object->is_executing()) {
10831cb0ef41Sopenharmony_ci        if (generator_object->IsJSAsyncFunctionObject()) {
10841cb0ef41Sopenharmony_ci          Handle<JSAsyncFunctionObject> async_function_object =
10851cb0ef41Sopenharmony_ci              Handle<JSAsyncFunctionObject>::cast(generator_object);
10861cb0ef41Sopenharmony_ci          Handle<JSPromise> promise(async_function_object->promise(), isolate);
10871cb0ef41Sopenharmony_ci          CaptureAsyncStackTrace(isolate, promise, builder);
10881cb0ef41Sopenharmony_ci        } else {
10891cb0ef41Sopenharmony_ci          Handle<JSAsyncGeneratorObject> async_generator_object =
10901cb0ef41Sopenharmony_ci              Handle<JSAsyncGeneratorObject>::cast(generator_object);
10911cb0ef41Sopenharmony_ci          Handle<Object> queue(async_generator_object->queue(), isolate);
10921cb0ef41Sopenharmony_ci          if (!queue->IsUndefined(isolate)) {
10931cb0ef41Sopenharmony_ci            Handle<AsyncGeneratorRequest> async_generator_request =
10941cb0ef41Sopenharmony_ci                Handle<AsyncGeneratorRequest>::cast(queue);
10951cb0ef41Sopenharmony_ci            Handle<JSPromise> promise(
10961cb0ef41Sopenharmony_ci                JSPromise::cast(async_generator_request->promise()), isolate);
10971cb0ef41Sopenharmony_ci            CaptureAsyncStackTrace(isolate, promise, builder);
10981cb0ef41Sopenharmony_ci          }
10991cb0ef41Sopenharmony_ci        }
11001cb0ef41Sopenharmony_ci      }
11011cb0ef41Sopenharmony_ci    } else {
11021cb0ef41Sopenharmony_ci      // The {promise_reaction_job_task} doesn't belong to an await (or
11031cb0ef41Sopenharmony_ci      // yield inside an async generator), but we might still be able to
11041cb0ef41Sopenharmony_ci      // find an async frame if we follow along the chain of promises on
11051cb0ef41Sopenharmony_ci      // the {promise_reaction_job_task}.
11061cb0ef41Sopenharmony_ci      Handle<HeapObject> promise_or_capability(
11071cb0ef41Sopenharmony_ci          promise_reaction_job_task->promise_or_capability(), isolate);
11081cb0ef41Sopenharmony_ci      if (promise_or_capability->IsJSPromise()) {
11091cb0ef41Sopenharmony_ci        Handle<JSPromise> promise =
11101cb0ef41Sopenharmony_ci            Handle<JSPromise>::cast(promise_or_capability);
11111cb0ef41Sopenharmony_ci        CaptureAsyncStackTrace(isolate, promise, builder);
11121cb0ef41Sopenharmony_ci      }
11131cb0ef41Sopenharmony_ci    }
11141cb0ef41Sopenharmony_ci  }
11151cb0ef41Sopenharmony_ci}
11161cb0ef41Sopenharmony_ci
11171cb0ef41Sopenharmony_citemplate <typename Visitor>
11181cb0ef41Sopenharmony_civoid VisitStack(Isolate* isolate, Visitor* visitor,
11191cb0ef41Sopenharmony_ci                StackTrace::StackTraceOptions options = StackTrace::kDetailed) {
11201cb0ef41Sopenharmony_ci  DisallowJavascriptExecution no_js(isolate);
11211cb0ef41Sopenharmony_ci  for (StackFrameIterator it(isolate); !it.done(); it.Advance()) {
11221cb0ef41Sopenharmony_ci    StackFrame* frame = it.frame();
11231cb0ef41Sopenharmony_ci    switch (frame->type()) {
11241cb0ef41Sopenharmony_ci      case StackFrame::BUILTIN_EXIT:
11251cb0ef41Sopenharmony_ci      case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION:
11261cb0ef41Sopenharmony_ci      case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH:
11271cb0ef41Sopenharmony_ci      case StackFrame::OPTIMIZED:
11281cb0ef41Sopenharmony_ci      case StackFrame::INTERPRETED:
11291cb0ef41Sopenharmony_ci      case StackFrame::BASELINE:
11301cb0ef41Sopenharmony_ci      case StackFrame::BUILTIN:
11311cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
11321cb0ef41Sopenharmony_ci      case StackFrame::WASM:
11331cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
11341cb0ef41Sopenharmony_ci      {
11351cb0ef41Sopenharmony_ci        // A standard frame may include many summarized frames (due to
11361cb0ef41Sopenharmony_ci        // inlining).
11371cb0ef41Sopenharmony_ci        std::vector<FrameSummary> summaries;
11381cb0ef41Sopenharmony_ci        CommonFrame::cast(frame)->Summarize(&summaries);
11391cb0ef41Sopenharmony_ci        for (auto rit = summaries.rbegin(); rit != summaries.rend(); ++rit) {
11401cb0ef41Sopenharmony_ci          FrameSummary& summary = *rit;
11411cb0ef41Sopenharmony_ci          // Skip frames from other origins when asked to do so.
11421cb0ef41Sopenharmony_ci          if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) &&
11431cb0ef41Sopenharmony_ci              !summary.native_context()->HasSameSecurityTokenAs(
11441cb0ef41Sopenharmony_ci                  isolate->context())) {
11451cb0ef41Sopenharmony_ci            continue;
11461cb0ef41Sopenharmony_ci          }
11471cb0ef41Sopenharmony_ci          if (!visitor->Visit(summary)) return;
11481cb0ef41Sopenharmony_ci        }
11491cb0ef41Sopenharmony_ci        break;
11501cb0ef41Sopenharmony_ci      }
11511cb0ef41Sopenharmony_ci
11521cb0ef41Sopenharmony_ci      default:
11531cb0ef41Sopenharmony_ci        break;
11541cb0ef41Sopenharmony_ci    }
11551cb0ef41Sopenharmony_ci  }
11561cb0ef41Sopenharmony_ci}
11571cb0ef41Sopenharmony_ci
11581cb0ef41Sopenharmony_ciHandle<FixedArray> CaptureSimpleStackTrace(Isolate* isolate, int limit,
11591cb0ef41Sopenharmony_ci                                           FrameSkipMode mode,
11601cb0ef41Sopenharmony_ci                                           Handle<Object> caller) {
11611cb0ef41Sopenharmony_ci  TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("v8.stack_trace"), __func__,
11621cb0ef41Sopenharmony_ci                     "maxFrameCount", limit);
11631cb0ef41Sopenharmony_ci
11641cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
11651cb0ef41Sopenharmony_ci  wasm::WasmCodeRefScope code_ref_scope;
11661cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
11671cb0ef41Sopenharmony_ci
11681cb0ef41Sopenharmony_ci  CallSiteBuilder builder(isolate, mode, limit, caller);
11691cb0ef41Sopenharmony_ci  VisitStack(isolate, &builder);
11701cb0ef41Sopenharmony_ci
11711cb0ef41Sopenharmony_ci  // If --async-stack-traces are enabled and the "current microtask" is a
11721cb0ef41Sopenharmony_ci  // PromiseReactionJobTask, we try to enrich the stack trace with async
11731cb0ef41Sopenharmony_ci  // frames.
11741cb0ef41Sopenharmony_ci  if (FLAG_async_stack_traces) {
11751cb0ef41Sopenharmony_ci    CaptureAsyncStackTrace(isolate, &builder);
11761cb0ef41Sopenharmony_ci  }
11771cb0ef41Sopenharmony_ci
11781cb0ef41Sopenharmony_ci  Handle<FixedArray> stack_trace = builder.Build();
11791cb0ef41Sopenharmony_ci  TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("v8.stack_trace"), __func__,
11801cb0ef41Sopenharmony_ci                   "frameCount", stack_trace->length());
11811cb0ef41Sopenharmony_ci  return stack_trace;
11821cb0ef41Sopenharmony_ci}
11831cb0ef41Sopenharmony_ci
11841cb0ef41Sopenharmony_ci}  // namespace
11851cb0ef41Sopenharmony_ci
11861cb0ef41Sopenharmony_ciMaybeHandle<JSObject> Isolate::CaptureAndSetErrorStack(
11871cb0ef41Sopenharmony_ci    Handle<JSObject> error_object, FrameSkipMode mode, Handle<Object> caller) {
11881cb0ef41Sopenharmony_ci  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.stack_trace"), __func__);
11891cb0ef41Sopenharmony_ci  Handle<Object> error_stack = factory()->undefined_value();
11901cb0ef41Sopenharmony_ci
11911cb0ef41Sopenharmony_ci  // Capture the "simple stack trace" for the error.stack property,
11921cb0ef41Sopenharmony_ci  // which can be disabled by setting Error.stackTraceLimit to a non
11931cb0ef41Sopenharmony_ci  // number value or simply deleting the property. If the inspector
11941cb0ef41Sopenharmony_ci  // is active, and requests more stack frames than the JavaScript
11951cb0ef41Sopenharmony_ci  // program itself, we collect up to the maximum.
11961cb0ef41Sopenharmony_ci  int stack_trace_limit = 0;
11971cb0ef41Sopenharmony_ci  if (GetStackTraceLimit(this, &stack_trace_limit)) {
11981cb0ef41Sopenharmony_ci    int limit = stack_trace_limit;
11991cb0ef41Sopenharmony_ci    if (capture_stack_trace_for_uncaught_exceptions_ &&
12001cb0ef41Sopenharmony_ci        !(stack_trace_for_uncaught_exceptions_options_ &
12011cb0ef41Sopenharmony_ci          StackTrace::kExposeFramesAcrossSecurityOrigins)) {
12021cb0ef41Sopenharmony_ci      // Collect up to the maximum of what the JavaScript program and
12031cb0ef41Sopenharmony_ci      // the inspector want. There's a special case here where the API
12041cb0ef41Sopenharmony_ci      // can ask the stack traces to also include cross-origin frames,
12051cb0ef41Sopenharmony_ci      // in which case we collect a separate trace below. Note that
12061cb0ef41Sopenharmony_ci      // the inspector doesn't use this option, so we could as well
12071cb0ef41Sopenharmony_ci      // just deprecate this in the future.
12081cb0ef41Sopenharmony_ci      if (limit < stack_trace_for_uncaught_exceptions_frame_limit_) {
12091cb0ef41Sopenharmony_ci        limit = stack_trace_for_uncaught_exceptions_frame_limit_;
12101cb0ef41Sopenharmony_ci      }
12111cb0ef41Sopenharmony_ci    }
12121cb0ef41Sopenharmony_ci    error_stack = CaptureSimpleStackTrace(this, limit, mode, caller);
12131cb0ef41Sopenharmony_ci  }
12141cb0ef41Sopenharmony_ci
12151cb0ef41Sopenharmony_ci  // Next is the inspector part: Depending on whether we got a "simple
12161cb0ef41Sopenharmony_ci  // stack trace" above and whether that's usable (meaning the API
12171cb0ef41Sopenharmony_ci  // didn't request to include cross-origin frames), we remember the
12181cb0ef41Sopenharmony_ci  // cap for the stack trace (either a positive limit indicating that
12191cb0ef41Sopenharmony_ci  // the Error.stackTraceLimit value was below what was requested via
12201cb0ef41Sopenharmony_ci  // the API, or a negative limit to indicate the opposite), or we
12211cb0ef41Sopenharmony_ci  // collect a "detailed stack trace" eagerly and stash that away.
12221cb0ef41Sopenharmony_ci  if (capture_stack_trace_for_uncaught_exceptions_) {
12231cb0ef41Sopenharmony_ci    Handle<Object> limit_or_stack_frame_infos;
12241cb0ef41Sopenharmony_ci    if (error_stack->IsUndefined(this) ||
12251cb0ef41Sopenharmony_ci        (stack_trace_for_uncaught_exceptions_options_ &
12261cb0ef41Sopenharmony_ci         StackTrace::kExposeFramesAcrossSecurityOrigins)) {
12271cb0ef41Sopenharmony_ci      limit_or_stack_frame_infos = CaptureDetailedStackTrace(
12281cb0ef41Sopenharmony_ci          stack_trace_for_uncaught_exceptions_frame_limit_,
12291cb0ef41Sopenharmony_ci          stack_trace_for_uncaught_exceptions_options_);
12301cb0ef41Sopenharmony_ci    } else {
12311cb0ef41Sopenharmony_ci      int limit =
12321cb0ef41Sopenharmony_ci          stack_trace_limit > stack_trace_for_uncaught_exceptions_frame_limit_
12331cb0ef41Sopenharmony_ci              ? -stack_trace_for_uncaught_exceptions_frame_limit_
12341cb0ef41Sopenharmony_ci              : stack_trace_limit;
12351cb0ef41Sopenharmony_ci      limit_or_stack_frame_infos = handle(Smi::FromInt(limit), this);
12361cb0ef41Sopenharmony_ci    }
12371cb0ef41Sopenharmony_ci    error_stack =
12381cb0ef41Sopenharmony_ci        factory()->NewErrorStackData(error_stack, limit_or_stack_frame_infos);
12391cb0ef41Sopenharmony_ci  }
12401cb0ef41Sopenharmony_ci
12411cb0ef41Sopenharmony_ci  RETURN_ON_EXCEPTION(
12421cb0ef41Sopenharmony_ci      this,
12431cb0ef41Sopenharmony_ci      JSObject::SetProperty(this, error_object, factory()->error_stack_symbol(),
12441cb0ef41Sopenharmony_ci                            error_stack, StoreOrigin::kMaybeKeyed,
12451cb0ef41Sopenharmony_ci                            Just(ShouldThrow::kThrowOnError)),
12461cb0ef41Sopenharmony_ci      JSObject);
12471cb0ef41Sopenharmony_ci  return error_object;
12481cb0ef41Sopenharmony_ci}
12491cb0ef41Sopenharmony_ci
12501cb0ef41Sopenharmony_ciHandle<FixedArray> Isolate::GetDetailedStackTrace(
12511cb0ef41Sopenharmony_ci    Handle<JSReceiver> error_object) {
12521cb0ef41Sopenharmony_ci  Handle<Object> error_stack = JSReceiver::GetDataProperty(
12531cb0ef41Sopenharmony_ci      this, error_object, factory()->error_stack_symbol());
12541cb0ef41Sopenharmony_ci  if (!error_stack->IsErrorStackData()) {
12551cb0ef41Sopenharmony_ci    return Handle<FixedArray>();
12561cb0ef41Sopenharmony_ci  }
12571cb0ef41Sopenharmony_ci  Handle<ErrorStackData> error_stack_data =
12581cb0ef41Sopenharmony_ci      Handle<ErrorStackData>::cast(error_stack);
12591cb0ef41Sopenharmony_ci  ErrorStackData::EnsureStackFrameInfos(this, error_stack_data);
12601cb0ef41Sopenharmony_ci  if (!error_stack_data->limit_or_stack_frame_infos().IsFixedArray()) {
12611cb0ef41Sopenharmony_ci    return Handle<FixedArray>();
12621cb0ef41Sopenharmony_ci  }
12631cb0ef41Sopenharmony_ci  return handle(
12641cb0ef41Sopenharmony_ci      FixedArray::cast(error_stack_data->limit_or_stack_frame_infos()), this);
12651cb0ef41Sopenharmony_ci}
12661cb0ef41Sopenharmony_ci
12671cb0ef41Sopenharmony_ciHandle<FixedArray> Isolate::GetSimpleStackTrace(
12681cb0ef41Sopenharmony_ci    Handle<JSReceiver> error_object) {
12691cb0ef41Sopenharmony_ci  Handle<Object> error_stack = JSReceiver::GetDataProperty(
12701cb0ef41Sopenharmony_ci      this, error_object, factory()->error_stack_symbol());
12711cb0ef41Sopenharmony_ci  if (error_stack->IsFixedArray()) {
12721cb0ef41Sopenharmony_ci    return Handle<FixedArray>::cast(error_stack);
12731cb0ef41Sopenharmony_ci  }
12741cb0ef41Sopenharmony_ci  if (!error_stack->IsErrorStackData()) {
12751cb0ef41Sopenharmony_ci    return factory()->empty_fixed_array();
12761cb0ef41Sopenharmony_ci  }
12771cb0ef41Sopenharmony_ci  Handle<ErrorStackData> error_stack_data =
12781cb0ef41Sopenharmony_ci      Handle<ErrorStackData>::cast(error_stack);
12791cb0ef41Sopenharmony_ci  if (!error_stack_data->HasCallSiteInfos()) {
12801cb0ef41Sopenharmony_ci    return factory()->empty_fixed_array();
12811cb0ef41Sopenharmony_ci  }
12821cb0ef41Sopenharmony_ci  return handle(error_stack_data->call_site_infos(), this);
12831cb0ef41Sopenharmony_ci}
12841cb0ef41Sopenharmony_ci
12851cb0ef41Sopenharmony_ciAddress Isolate::GetAbstractPC(int* line, int* column) {
12861cb0ef41Sopenharmony_ci  JavaScriptFrameIterator it(this);
12871cb0ef41Sopenharmony_ci
12881cb0ef41Sopenharmony_ci  if (it.done()) {
12891cb0ef41Sopenharmony_ci    *line = -1;
12901cb0ef41Sopenharmony_ci    *column = -1;
12911cb0ef41Sopenharmony_ci    return kNullAddress;
12921cb0ef41Sopenharmony_ci  }
12931cb0ef41Sopenharmony_ci  JavaScriptFrame* frame = it.frame();
12941cb0ef41Sopenharmony_ci  DCHECK(!frame->is_builtin());
12951cb0ef41Sopenharmony_ci
12961cb0ef41Sopenharmony_ci  Handle<SharedFunctionInfo> shared = handle(frame->function().shared(), this);
12971cb0ef41Sopenharmony_ci  SharedFunctionInfo::EnsureSourcePositionsAvailable(this, shared);
12981cb0ef41Sopenharmony_ci  int position = frame->position();
12991cb0ef41Sopenharmony_ci
13001cb0ef41Sopenharmony_ci  Object maybe_script = frame->function().shared().script();
13011cb0ef41Sopenharmony_ci  if (maybe_script.IsScript()) {
13021cb0ef41Sopenharmony_ci    Handle<Script> script(Script::cast(maybe_script), this);
13031cb0ef41Sopenharmony_ci    Script::PositionInfo info;
13041cb0ef41Sopenharmony_ci    Script::GetPositionInfo(script, position, &info, Script::WITH_OFFSET);
13051cb0ef41Sopenharmony_ci    *line = info.line + 1;
13061cb0ef41Sopenharmony_ci    *column = info.column + 1;
13071cb0ef41Sopenharmony_ci  } else {
13081cb0ef41Sopenharmony_ci    *line = position;
13091cb0ef41Sopenharmony_ci    *column = -1;
13101cb0ef41Sopenharmony_ci  }
13111cb0ef41Sopenharmony_ci
13121cb0ef41Sopenharmony_ci  if (frame->is_unoptimized()) {
13131cb0ef41Sopenharmony_ci    UnoptimizedFrame* iframe = static_cast<UnoptimizedFrame*>(frame);
13141cb0ef41Sopenharmony_ci    Address bytecode_start =
13151cb0ef41Sopenharmony_ci        iframe->GetBytecodeArray().GetFirstBytecodeAddress();
13161cb0ef41Sopenharmony_ci    return bytecode_start + iframe->GetBytecodeOffset();
13171cb0ef41Sopenharmony_ci  }
13181cb0ef41Sopenharmony_ci
13191cb0ef41Sopenharmony_ci  return frame->pc();
13201cb0ef41Sopenharmony_ci}
13211cb0ef41Sopenharmony_ci
13221cb0ef41Sopenharmony_cinamespace {
13231cb0ef41Sopenharmony_ci
13241cb0ef41Sopenharmony_ciclass StackFrameBuilder {
13251cb0ef41Sopenharmony_ci public:
13261cb0ef41Sopenharmony_ci  StackFrameBuilder(Isolate* isolate, int limit)
13271cb0ef41Sopenharmony_ci      : isolate_(isolate),
13281cb0ef41Sopenharmony_ci        frames_(isolate_->factory()->empty_fixed_array()),
13291cb0ef41Sopenharmony_ci        index_(0),
13301cb0ef41Sopenharmony_ci        limit_(limit) {}
13311cb0ef41Sopenharmony_ci
13321cb0ef41Sopenharmony_ci  bool Visit(FrameSummary& summary) {
13331cb0ef41Sopenharmony_ci    // Check if we have enough capacity left.
13341cb0ef41Sopenharmony_ci    if (index_ >= limit_) return false;
13351cb0ef41Sopenharmony_ci    // Skip frames that aren't subject to debugging.
13361cb0ef41Sopenharmony_ci    if (!summary.is_subject_to_debugging()) return true;
13371cb0ef41Sopenharmony_ci    Handle<StackFrameInfo> frame = summary.CreateStackFrameInfo();
13381cb0ef41Sopenharmony_ci    frames_ = FixedArray::SetAndGrow(isolate_, frames_, index_++, frame);
13391cb0ef41Sopenharmony_ci    return true;
13401cb0ef41Sopenharmony_ci  }
13411cb0ef41Sopenharmony_ci
13421cb0ef41Sopenharmony_ci  Handle<FixedArray> Build() {
13431cb0ef41Sopenharmony_ci    return FixedArray::ShrinkOrEmpty(isolate_, frames_, index_);
13441cb0ef41Sopenharmony_ci  }
13451cb0ef41Sopenharmony_ci
13461cb0ef41Sopenharmony_ci private:
13471cb0ef41Sopenharmony_ci  Isolate* isolate_;
13481cb0ef41Sopenharmony_ci  Handle<FixedArray> frames_;
13491cb0ef41Sopenharmony_ci  int index_;
13501cb0ef41Sopenharmony_ci  int limit_;
13511cb0ef41Sopenharmony_ci};
13521cb0ef41Sopenharmony_ci
13531cb0ef41Sopenharmony_ci}  // namespace
13541cb0ef41Sopenharmony_ci
13551cb0ef41Sopenharmony_ciHandle<FixedArray> Isolate::CaptureDetailedStackTrace(
13561cb0ef41Sopenharmony_ci    int limit, StackTrace::StackTraceOptions options) {
13571cb0ef41Sopenharmony_ci  TRACE_EVENT_BEGIN1(TRACE_DISABLED_BY_DEFAULT("v8.stack_trace"), __func__,
13581cb0ef41Sopenharmony_ci                     "maxFrameCount", limit);
13591cb0ef41Sopenharmony_ci  StackFrameBuilder builder(this, limit);
13601cb0ef41Sopenharmony_ci  VisitStack(this, &builder, options);
13611cb0ef41Sopenharmony_ci  Handle<FixedArray> stack_trace = builder.Build();
13621cb0ef41Sopenharmony_ci  TRACE_EVENT_END1(TRACE_DISABLED_BY_DEFAULT("v8.stack_trace"), __func__,
13631cb0ef41Sopenharmony_ci                   "frameCount", stack_trace->length());
13641cb0ef41Sopenharmony_ci  return stack_trace;
13651cb0ef41Sopenharmony_ci}
13661cb0ef41Sopenharmony_ci
13671cb0ef41Sopenharmony_cinamespace {
13681cb0ef41Sopenharmony_ci
13691cb0ef41Sopenharmony_ciclass CurrentScriptNameStackVisitor {
13701cb0ef41Sopenharmony_ci public:
13711cb0ef41Sopenharmony_ci  explicit CurrentScriptNameStackVisitor(Isolate* isolate)
13721cb0ef41Sopenharmony_ci      : isolate_(isolate) {}
13731cb0ef41Sopenharmony_ci
13741cb0ef41Sopenharmony_ci  bool Visit(FrameSummary& summary) {
13751cb0ef41Sopenharmony_ci    // Skip frames that aren't subject to debugging. Keep this in sync with
13761cb0ef41Sopenharmony_ci    // StackFrameBuilder::Visit so both visitors visit the same frames.
13771cb0ef41Sopenharmony_ci    if (!summary.is_subject_to_debugging()) return true;
13781cb0ef41Sopenharmony_ci
13791cb0ef41Sopenharmony_ci    // Frames that are subject to debugging always have a valid script object.
13801cb0ef41Sopenharmony_ci    Handle<Script> script = Handle<Script>::cast(summary.script());
13811cb0ef41Sopenharmony_ci    Handle<Object> name_or_url_obj =
13821cb0ef41Sopenharmony_ci        handle(script->GetNameOrSourceURL(), isolate_);
13831cb0ef41Sopenharmony_ci    if (!name_or_url_obj->IsString()) return true;
13841cb0ef41Sopenharmony_ci
13851cb0ef41Sopenharmony_ci    Handle<String> name_or_url = Handle<String>::cast(name_or_url_obj);
13861cb0ef41Sopenharmony_ci    if (!name_or_url->length()) return true;
13871cb0ef41Sopenharmony_ci
13881cb0ef41Sopenharmony_ci    name_or_url_ = name_or_url;
13891cb0ef41Sopenharmony_ci    return false;
13901cb0ef41Sopenharmony_ci  }
13911cb0ef41Sopenharmony_ci
13921cb0ef41Sopenharmony_ci  Handle<String> CurrentScriptNameOrSourceURL() const { return name_or_url_; }
13931cb0ef41Sopenharmony_ci
13941cb0ef41Sopenharmony_ci private:
13951cb0ef41Sopenharmony_ci  Isolate* const isolate_;
13961cb0ef41Sopenharmony_ci  Handle<String> name_or_url_;
13971cb0ef41Sopenharmony_ci};
13981cb0ef41Sopenharmony_ci
13991cb0ef41Sopenharmony_ci}  // namespace
14001cb0ef41Sopenharmony_ci
14011cb0ef41Sopenharmony_ciHandle<String> Isolate::CurrentScriptNameOrSourceURL() {
14021cb0ef41Sopenharmony_ci  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.stack_trace"), __func__);
14031cb0ef41Sopenharmony_ci  CurrentScriptNameStackVisitor visitor(this);
14041cb0ef41Sopenharmony_ci  VisitStack(this, &visitor);
14051cb0ef41Sopenharmony_ci  return visitor.CurrentScriptNameOrSourceURL();
14061cb0ef41Sopenharmony_ci}
14071cb0ef41Sopenharmony_ci
14081cb0ef41Sopenharmony_civoid Isolate::PrintStack(FILE* out, PrintStackMode mode) {
14091cb0ef41Sopenharmony_ci  if (stack_trace_nesting_level_ == 0) {
14101cb0ef41Sopenharmony_ci    stack_trace_nesting_level_++;
14111cb0ef41Sopenharmony_ci    StringStream::ClearMentionedObjectCache(this);
14121cb0ef41Sopenharmony_ci    HeapStringAllocator allocator;
14131cb0ef41Sopenharmony_ci    StringStream accumulator(&allocator);
14141cb0ef41Sopenharmony_ci    incomplete_message_ = &accumulator;
14151cb0ef41Sopenharmony_ci    PrintStack(&accumulator, mode);
14161cb0ef41Sopenharmony_ci    accumulator.OutputToFile(out);
14171cb0ef41Sopenharmony_ci    InitializeLoggingAndCounters();
14181cb0ef41Sopenharmony_ci    accumulator.Log(this);
14191cb0ef41Sopenharmony_ci    incomplete_message_ = nullptr;
14201cb0ef41Sopenharmony_ci    stack_trace_nesting_level_ = 0;
14211cb0ef41Sopenharmony_ci  } else if (stack_trace_nesting_level_ == 1) {
14221cb0ef41Sopenharmony_ci    stack_trace_nesting_level_++;
14231cb0ef41Sopenharmony_ci    base::OS::PrintError(
14241cb0ef41Sopenharmony_ci        "\n\nAttempt to print stack while printing stack (double fault)\n");
14251cb0ef41Sopenharmony_ci    base::OS::PrintError(
14261cb0ef41Sopenharmony_ci        "If you are lucky you may find a partial stack dump on stdout.\n\n");
14271cb0ef41Sopenharmony_ci    incomplete_message_->OutputToFile(out);
14281cb0ef41Sopenharmony_ci  }
14291cb0ef41Sopenharmony_ci}
14301cb0ef41Sopenharmony_ci
14311cb0ef41Sopenharmony_cistatic void PrintFrames(Isolate* isolate, StringStream* accumulator,
14321cb0ef41Sopenharmony_ci                        StackFrame::PrintMode mode) {
14331cb0ef41Sopenharmony_ci  StackFrameIterator it(isolate);
14341cb0ef41Sopenharmony_ci  for (int i = 0; !it.done(); it.Advance()) {
14351cb0ef41Sopenharmony_ci    it.frame()->Print(accumulator, mode, i++);
14361cb0ef41Sopenharmony_ci  }
14371cb0ef41Sopenharmony_ci}
14381cb0ef41Sopenharmony_ci
14391cb0ef41Sopenharmony_civoid Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) {
14401cb0ef41Sopenharmony_ci  HandleScope scope(this);
14411cb0ef41Sopenharmony_ci  DCHECK(accumulator->IsMentionedObjectCacheClear(this));
14421cb0ef41Sopenharmony_ci
14431cb0ef41Sopenharmony_ci  // Avoid printing anything if there are no frames.
14441cb0ef41Sopenharmony_ci  if (c_entry_fp(thread_local_top()) == 0) return;
14451cb0ef41Sopenharmony_ci
14461cb0ef41Sopenharmony_ci  accumulator->Add(
14471cb0ef41Sopenharmony_ci      "\n==== JS stack trace =========================================\n\n");
14481cb0ef41Sopenharmony_ci  PrintFrames(this, accumulator, StackFrame::OVERVIEW);
14491cb0ef41Sopenharmony_ci  if (mode == kPrintStackVerbose) {
14501cb0ef41Sopenharmony_ci    accumulator->Add(
14511cb0ef41Sopenharmony_ci        "\n==== Details ================================================\n\n");
14521cb0ef41Sopenharmony_ci    PrintFrames(this, accumulator, StackFrame::DETAILS);
14531cb0ef41Sopenharmony_ci    accumulator->PrintMentionedObjectCache(this);
14541cb0ef41Sopenharmony_ci  }
14551cb0ef41Sopenharmony_ci  accumulator->Add("=====================\n\n");
14561cb0ef41Sopenharmony_ci}
14571cb0ef41Sopenharmony_ci
14581cb0ef41Sopenharmony_civoid Isolate::SetFailedAccessCheckCallback(
14591cb0ef41Sopenharmony_ci    v8::FailedAccessCheckCallback callback) {
14601cb0ef41Sopenharmony_ci  thread_local_top()->failed_access_check_callback_ = callback;
14611cb0ef41Sopenharmony_ci}
14621cb0ef41Sopenharmony_ci
14631cb0ef41Sopenharmony_civoid Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) {
14641cb0ef41Sopenharmony_ci  if (!thread_local_top()->failed_access_check_callback_) {
14651cb0ef41Sopenharmony_ci    return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess));
14661cb0ef41Sopenharmony_ci  }
14671cb0ef41Sopenharmony_ci
14681cb0ef41Sopenharmony_ci  DCHECK(receiver->IsAccessCheckNeeded());
14691cb0ef41Sopenharmony_ci  DCHECK(!context().is_null());
14701cb0ef41Sopenharmony_ci
14711cb0ef41Sopenharmony_ci  // Get the data object from access check info.
14721cb0ef41Sopenharmony_ci  HandleScope scope(this);
14731cb0ef41Sopenharmony_ci  Handle<Object> data;
14741cb0ef41Sopenharmony_ci  {
14751cb0ef41Sopenharmony_ci    DisallowGarbageCollection no_gc;
14761cb0ef41Sopenharmony_ci    AccessCheckInfo access_check_info = AccessCheckInfo::Get(this, receiver);
14771cb0ef41Sopenharmony_ci    if (access_check_info.is_null()) {
14781cb0ef41Sopenharmony_ci      no_gc.Release();
14791cb0ef41Sopenharmony_ci      return ScheduleThrow(
14801cb0ef41Sopenharmony_ci          *factory()->NewTypeError(MessageTemplate::kNoAccess));
14811cb0ef41Sopenharmony_ci    }
14821cb0ef41Sopenharmony_ci    data = handle(access_check_info.data(), this);
14831cb0ef41Sopenharmony_ci  }
14841cb0ef41Sopenharmony_ci
14851cb0ef41Sopenharmony_ci  // Leaving JavaScript.
14861cb0ef41Sopenharmony_ci  VMState<EXTERNAL> state(this);
14871cb0ef41Sopenharmony_ci  thread_local_top()->failed_access_check_callback_(
14881cb0ef41Sopenharmony_ci      v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data));
14891cb0ef41Sopenharmony_ci}
14901cb0ef41Sopenharmony_ci
14911cb0ef41Sopenharmony_cibool Isolate::MayAccess(Handle<Context> accessing_context,
14921cb0ef41Sopenharmony_ci                        Handle<JSObject> receiver) {
14931cb0ef41Sopenharmony_ci  DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded());
14941cb0ef41Sopenharmony_ci
14951cb0ef41Sopenharmony_ci  // Check for compatibility between the security tokens in the
14961cb0ef41Sopenharmony_ci  // current lexical context and the accessed object.
14971cb0ef41Sopenharmony_ci
14981cb0ef41Sopenharmony_ci  // During bootstrapping, callback functions are not enabled yet.
14991cb0ef41Sopenharmony_ci  if (bootstrapper()->IsActive()) return true;
15001cb0ef41Sopenharmony_ci  {
15011cb0ef41Sopenharmony_ci    DisallowGarbageCollection no_gc;
15021cb0ef41Sopenharmony_ci
15031cb0ef41Sopenharmony_ci    if (receiver->IsJSGlobalProxy()) {
15041cb0ef41Sopenharmony_ci      Object receiver_context = JSGlobalProxy::cast(*receiver).native_context();
15051cb0ef41Sopenharmony_ci      if (!receiver_context.IsContext()) return false;
15061cb0ef41Sopenharmony_ci
15071cb0ef41Sopenharmony_ci      // Get the native context of current top context.
15081cb0ef41Sopenharmony_ci      // avoid using Isolate::native_context() because it uses Handle.
15091cb0ef41Sopenharmony_ci      Context native_context =
15101cb0ef41Sopenharmony_ci          accessing_context->global_object().native_context();
15111cb0ef41Sopenharmony_ci      if (receiver_context == native_context) return true;
15121cb0ef41Sopenharmony_ci
15131cb0ef41Sopenharmony_ci      if (Context::cast(receiver_context).security_token() ==
15141cb0ef41Sopenharmony_ci          native_context.security_token())
15151cb0ef41Sopenharmony_ci        return true;
15161cb0ef41Sopenharmony_ci    }
15171cb0ef41Sopenharmony_ci  }
15181cb0ef41Sopenharmony_ci
15191cb0ef41Sopenharmony_ci  HandleScope scope(this);
15201cb0ef41Sopenharmony_ci  Handle<Object> data;
15211cb0ef41Sopenharmony_ci  v8::AccessCheckCallback callback = nullptr;
15221cb0ef41Sopenharmony_ci  {
15231cb0ef41Sopenharmony_ci    DisallowGarbageCollection no_gc;
15241cb0ef41Sopenharmony_ci    AccessCheckInfo access_check_info = AccessCheckInfo::Get(this, receiver);
15251cb0ef41Sopenharmony_ci    if (access_check_info.is_null()) return false;
15261cb0ef41Sopenharmony_ci    Object fun_obj = access_check_info.callback();
15271cb0ef41Sopenharmony_ci    callback = v8::ToCData<v8::AccessCheckCallback>(fun_obj);
15281cb0ef41Sopenharmony_ci    data = handle(access_check_info.data(), this);
15291cb0ef41Sopenharmony_ci  }
15301cb0ef41Sopenharmony_ci
15311cb0ef41Sopenharmony_ci  {
15321cb0ef41Sopenharmony_ci    // Leaving JavaScript.
15331cb0ef41Sopenharmony_ci    VMState<EXTERNAL> state(this);
15341cb0ef41Sopenharmony_ci    return callback(v8::Utils::ToLocal(accessing_context),
15351cb0ef41Sopenharmony_ci                    v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(data));
15361cb0ef41Sopenharmony_ci  }
15371cb0ef41Sopenharmony_ci}
15381cb0ef41Sopenharmony_ci
15391cb0ef41Sopenharmony_ciObject Isolate::StackOverflow() {
15401cb0ef41Sopenharmony_ci  // Whoever calls this method should not have overflown the stack limit by too
15411cb0ef41Sopenharmony_ci  // much. Otherwise we risk actually running out of stack space.
15421cb0ef41Sopenharmony_ci  // We allow for up to 8kB overflow, because we typically allow up to 4KB
15431cb0ef41Sopenharmony_ci  // overflow per frame in generated code, but might call through more smaller
15441cb0ef41Sopenharmony_ci  // frames until we reach this method.
15451cb0ef41Sopenharmony_ci  // If this DCHECK fails, one of the frames on the stack should be augmented by
15461cb0ef41Sopenharmony_ci  // an additional stack check.
15471cb0ef41Sopenharmony_ci#if defined(V8_USE_ADDRESS_SANITIZER) || defined(MEMORY_SANITIZER)
15481cb0ef41Sopenharmony_ci  // Allow for a bit more overflow in sanitizer builds, because C++ frames take
15491cb0ef41Sopenharmony_ci  // significantly more space there.
15501cb0ef41Sopenharmony_ci  DCHECK_GE(GetCurrentStackPosition(), stack_guard()->real_climit() - 32 * KB);
15511cb0ef41Sopenharmony_ci#else
15521cb0ef41Sopenharmony_ci  DCHECK_GE(GetCurrentStackPosition(), stack_guard()->real_climit() - 8 * KB);
15531cb0ef41Sopenharmony_ci#endif
15541cb0ef41Sopenharmony_ci
15551cb0ef41Sopenharmony_ci  if (FLAG_correctness_fuzzer_suppressions) {
15561cb0ef41Sopenharmony_ci    FATAL("Aborting on stack overflow");
15571cb0ef41Sopenharmony_ci  }
15581cb0ef41Sopenharmony_ci
15591cb0ef41Sopenharmony_ci  DisallowJavascriptExecution no_js(this);
15601cb0ef41Sopenharmony_ci  HandleScope scope(this);
15611cb0ef41Sopenharmony_ci
15621cb0ef41Sopenharmony_ci  Handle<JSFunction> fun = range_error_function();
15631cb0ef41Sopenharmony_ci  Handle<Object> msg = factory()->NewStringFromAsciiChecked(
15641cb0ef41Sopenharmony_ci      MessageFormatter::TemplateString(MessageTemplate::kStackOverflow));
15651cb0ef41Sopenharmony_ci  Handle<Object> options = factory()->undefined_value();
15661cb0ef41Sopenharmony_ci  Handle<Object> no_caller;
15671cb0ef41Sopenharmony_ci  Handle<JSObject> exception;
15681cb0ef41Sopenharmony_ci  ASSIGN_RETURN_FAILURE_ON_EXCEPTION(
15691cb0ef41Sopenharmony_ci      this, exception,
15701cb0ef41Sopenharmony_ci      ErrorUtils::Construct(this, fun, fun, msg, options, SKIP_NONE, no_caller,
15711cb0ef41Sopenharmony_ci                            ErrorUtils::StackTraceCollection::kEnabled));
15721cb0ef41Sopenharmony_ci  JSObject::AddProperty(this, exception, factory()->wasm_uncatchable_symbol(),
15731cb0ef41Sopenharmony_ci                        factory()->true_value(), NONE);
15741cb0ef41Sopenharmony_ci
15751cb0ef41Sopenharmony_ci  Throw(*exception);
15761cb0ef41Sopenharmony_ci
15771cb0ef41Sopenharmony_ci#ifdef VERIFY_HEAP
15781cb0ef41Sopenharmony_ci  if (FLAG_verify_heap && FLAG_stress_compaction) {
15791cb0ef41Sopenharmony_ci    heap()->CollectAllGarbage(Heap::kNoGCFlags,
15801cb0ef41Sopenharmony_ci                              GarbageCollectionReason::kTesting);
15811cb0ef41Sopenharmony_ci  }
15821cb0ef41Sopenharmony_ci#endif  // VERIFY_HEAP
15831cb0ef41Sopenharmony_ci
15841cb0ef41Sopenharmony_ci  return ReadOnlyRoots(heap()).exception();
15851cb0ef41Sopenharmony_ci}
15861cb0ef41Sopenharmony_ci
15871cb0ef41Sopenharmony_ciObject Isolate::ThrowAt(Handle<JSObject> exception, MessageLocation* location) {
15881cb0ef41Sopenharmony_ci  Handle<Name> key_start_pos = factory()->error_start_pos_symbol();
15891cb0ef41Sopenharmony_ci  Object::SetProperty(this, exception, key_start_pos,
15901cb0ef41Sopenharmony_ci                      handle(Smi::FromInt(location->start_pos()), this),
15911cb0ef41Sopenharmony_ci                      StoreOrigin::kMaybeKeyed,
15921cb0ef41Sopenharmony_ci                      Just(ShouldThrow::kThrowOnError))
15931cb0ef41Sopenharmony_ci      .Check();
15941cb0ef41Sopenharmony_ci
15951cb0ef41Sopenharmony_ci  Handle<Name> key_end_pos = factory()->error_end_pos_symbol();
15961cb0ef41Sopenharmony_ci  Object::SetProperty(this, exception, key_end_pos,
15971cb0ef41Sopenharmony_ci                      handle(Smi::FromInt(location->end_pos()), this),
15981cb0ef41Sopenharmony_ci                      StoreOrigin::kMaybeKeyed,
15991cb0ef41Sopenharmony_ci                      Just(ShouldThrow::kThrowOnError))
16001cb0ef41Sopenharmony_ci      .Check();
16011cb0ef41Sopenharmony_ci
16021cb0ef41Sopenharmony_ci  Handle<Name> key_script = factory()->error_script_symbol();
16031cb0ef41Sopenharmony_ci  Object::SetProperty(this, exception, key_script, location->script(),
16041cb0ef41Sopenharmony_ci                      StoreOrigin::kMaybeKeyed,
16051cb0ef41Sopenharmony_ci                      Just(ShouldThrow::kThrowOnError))
16061cb0ef41Sopenharmony_ci      .Check();
16071cb0ef41Sopenharmony_ci
16081cb0ef41Sopenharmony_ci  return ThrowInternal(*exception, location);
16091cb0ef41Sopenharmony_ci}
16101cb0ef41Sopenharmony_ci
16111cb0ef41Sopenharmony_ciObject Isolate::TerminateExecution() {
16121cb0ef41Sopenharmony_ci  return Throw(ReadOnlyRoots(this).termination_exception());
16131cb0ef41Sopenharmony_ci}
16141cb0ef41Sopenharmony_ci
16151cb0ef41Sopenharmony_civoid Isolate::CancelTerminateExecution() {
16161cb0ef41Sopenharmony_ci  if (try_catch_handler()) {
16171cb0ef41Sopenharmony_ci    try_catch_handler()->has_terminated_ = false;
16181cb0ef41Sopenharmony_ci  }
16191cb0ef41Sopenharmony_ci  if (has_pending_exception() &&
16201cb0ef41Sopenharmony_ci      pending_exception() == ReadOnlyRoots(this).termination_exception()) {
16211cb0ef41Sopenharmony_ci    thread_local_top()->external_caught_exception_ = false;
16221cb0ef41Sopenharmony_ci    clear_pending_exception();
16231cb0ef41Sopenharmony_ci  }
16241cb0ef41Sopenharmony_ci  if (has_scheduled_exception() &&
16251cb0ef41Sopenharmony_ci      scheduled_exception() == ReadOnlyRoots(this).termination_exception()) {
16261cb0ef41Sopenharmony_ci    thread_local_top()->external_caught_exception_ = false;
16271cb0ef41Sopenharmony_ci    clear_scheduled_exception();
16281cb0ef41Sopenharmony_ci  }
16291cb0ef41Sopenharmony_ci}
16301cb0ef41Sopenharmony_ci
16311cb0ef41Sopenharmony_civoid Isolate::RequestInterrupt(InterruptCallback callback, void* data) {
16321cb0ef41Sopenharmony_ci  ExecutionAccess access(this);
16331cb0ef41Sopenharmony_ci  api_interrupts_queue_.push(InterruptEntry(callback, data));
16341cb0ef41Sopenharmony_ci  stack_guard()->RequestApiInterrupt();
16351cb0ef41Sopenharmony_ci}
16361cb0ef41Sopenharmony_ci
16371cb0ef41Sopenharmony_civoid Isolate::InvokeApiInterruptCallbacks() {
16381cb0ef41Sopenharmony_ci  RCS_SCOPE(this, RuntimeCallCounterId::kInvokeApiInterruptCallbacks);
16391cb0ef41Sopenharmony_ci  // Note: callback below should be called outside of execution access lock.
16401cb0ef41Sopenharmony_ci  while (true) {
16411cb0ef41Sopenharmony_ci    InterruptEntry entry;
16421cb0ef41Sopenharmony_ci    {
16431cb0ef41Sopenharmony_ci      ExecutionAccess access(this);
16441cb0ef41Sopenharmony_ci      if (api_interrupts_queue_.empty()) return;
16451cb0ef41Sopenharmony_ci      entry = api_interrupts_queue_.front();
16461cb0ef41Sopenharmony_ci      api_interrupts_queue_.pop();
16471cb0ef41Sopenharmony_ci    }
16481cb0ef41Sopenharmony_ci    VMState<EXTERNAL> state(this);
16491cb0ef41Sopenharmony_ci    HandleScope handle_scope(this);
16501cb0ef41Sopenharmony_ci    entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second);
16511cb0ef41Sopenharmony_ci  }
16521cb0ef41Sopenharmony_ci}
16531cb0ef41Sopenharmony_ci
16541cb0ef41Sopenharmony_cinamespace {
16551cb0ef41Sopenharmony_ci
16561cb0ef41Sopenharmony_civoid ReportBootstrappingException(Handle<Object> exception,
16571cb0ef41Sopenharmony_ci                                  MessageLocation* location) {
16581cb0ef41Sopenharmony_ci  base::OS::PrintError("Exception thrown during bootstrapping\n");
16591cb0ef41Sopenharmony_ci  if (location == nullptr || location->script().is_null()) return;
16601cb0ef41Sopenharmony_ci  // We are bootstrapping and caught an error where the location is set
16611cb0ef41Sopenharmony_ci  // and we have a script for the location.
16621cb0ef41Sopenharmony_ci  // In this case we could have an extension (or an internal error
16631cb0ef41Sopenharmony_ci  // somewhere) and we print out the line number at which the error occurred
16641cb0ef41Sopenharmony_ci  // to the console for easier debugging.
16651cb0ef41Sopenharmony_ci  int line_number =
16661cb0ef41Sopenharmony_ci      location->script()->GetLineNumber(location->start_pos()) + 1;
16671cb0ef41Sopenharmony_ci  if (exception->IsString() && location->script()->name().IsString()) {
16681cb0ef41Sopenharmony_ci    base::OS::PrintError(
16691cb0ef41Sopenharmony_ci        "Extension or internal compilation error: %s in %s at line %d.\n",
16701cb0ef41Sopenharmony_ci        String::cast(*exception).ToCString().get(),
16711cb0ef41Sopenharmony_ci        String::cast(location->script()->name()).ToCString().get(),
16721cb0ef41Sopenharmony_ci        line_number);
16731cb0ef41Sopenharmony_ci  } else if (location->script()->name().IsString()) {
16741cb0ef41Sopenharmony_ci    base::OS::PrintError(
16751cb0ef41Sopenharmony_ci        "Extension or internal compilation error in %s at line %d.\n",
16761cb0ef41Sopenharmony_ci        String::cast(location->script()->name()).ToCString().get(),
16771cb0ef41Sopenharmony_ci        line_number);
16781cb0ef41Sopenharmony_ci  } else if (exception->IsString()) {
16791cb0ef41Sopenharmony_ci    base::OS::PrintError("Extension or internal compilation error: %s.\n",
16801cb0ef41Sopenharmony_ci                         String::cast(*exception).ToCString().get());
16811cb0ef41Sopenharmony_ci  } else {
16821cb0ef41Sopenharmony_ci    base::OS::PrintError("Extension or internal compilation error.\n");
16831cb0ef41Sopenharmony_ci  }
16841cb0ef41Sopenharmony_ci#ifdef OBJECT_PRINT
16851cb0ef41Sopenharmony_ci  // Since comments and empty lines have been stripped from the source of
16861cb0ef41Sopenharmony_ci  // builtins, print the actual source here so that line numbers match.
16871cb0ef41Sopenharmony_ci  if (location->script()->source().IsString()) {
16881cb0ef41Sopenharmony_ci    Handle<String> src(String::cast(location->script()->source()),
16891cb0ef41Sopenharmony_ci                       location->script()->GetIsolate());
16901cb0ef41Sopenharmony_ci    PrintF("Failing script:");
16911cb0ef41Sopenharmony_ci    int len = src->length();
16921cb0ef41Sopenharmony_ci    if (len == 0) {
16931cb0ef41Sopenharmony_ci      PrintF(" <not available>\n");
16941cb0ef41Sopenharmony_ci    } else {
16951cb0ef41Sopenharmony_ci      PrintF("\n");
16961cb0ef41Sopenharmony_ci      line_number = 1;
16971cb0ef41Sopenharmony_ci      PrintF("%5d: ", line_number);
16981cb0ef41Sopenharmony_ci      for (int i = 0; i < len; i++) {
16991cb0ef41Sopenharmony_ci        uint16_t character = src->Get(i);
17001cb0ef41Sopenharmony_ci        PrintF("%c", character);
17011cb0ef41Sopenharmony_ci        if (character == '\n' && i < len - 2) {
17021cb0ef41Sopenharmony_ci          PrintF("%5d: ", ++line_number);
17031cb0ef41Sopenharmony_ci        }
17041cb0ef41Sopenharmony_ci      }
17051cb0ef41Sopenharmony_ci      PrintF("\n");
17061cb0ef41Sopenharmony_ci    }
17071cb0ef41Sopenharmony_ci  }
17081cb0ef41Sopenharmony_ci#endif
17091cb0ef41Sopenharmony_ci}
17101cb0ef41Sopenharmony_ci
17111cb0ef41Sopenharmony_ci}  // anonymous namespace
17121cb0ef41Sopenharmony_ci
17131cb0ef41Sopenharmony_ciHandle<JSMessageObject> Isolate::CreateMessageOrAbort(
17141cb0ef41Sopenharmony_ci    Handle<Object> exception, MessageLocation* location) {
17151cb0ef41Sopenharmony_ci  Handle<JSMessageObject> message_obj = CreateMessage(exception, location);
17161cb0ef41Sopenharmony_ci
17171cb0ef41Sopenharmony_ci  // If the abort-on-uncaught-exception flag is specified, and if the
17181cb0ef41Sopenharmony_ci  // embedder didn't specify a custom uncaught exception callback,
17191cb0ef41Sopenharmony_ci  // or if the custom callback determined that V8 should abort, then
17201cb0ef41Sopenharmony_ci  // abort.
17211cb0ef41Sopenharmony_ci  if (FLAG_abort_on_uncaught_exception) {
17221cb0ef41Sopenharmony_ci    CatchType prediction = PredictExceptionCatcher();
17231cb0ef41Sopenharmony_ci    if ((prediction == NOT_CAUGHT || prediction == CAUGHT_BY_EXTERNAL) &&
17241cb0ef41Sopenharmony_ci        (!abort_on_uncaught_exception_callback_ ||
17251cb0ef41Sopenharmony_ci         abort_on_uncaught_exception_callback_(
17261cb0ef41Sopenharmony_ci             reinterpret_cast<v8::Isolate*>(this)))) {
17271cb0ef41Sopenharmony_ci      // Prevent endless recursion.
17281cb0ef41Sopenharmony_ci      FLAG_abort_on_uncaught_exception = false;
17291cb0ef41Sopenharmony_ci      // This flag is intended for use by JavaScript developers, so
17301cb0ef41Sopenharmony_ci      // print a user-friendly stack trace (not an internal one).
17311cb0ef41Sopenharmony_ci      PrintF(stderr, "%s\n\nFROM\n",
17321cb0ef41Sopenharmony_ci             MessageHandler::GetLocalizedMessage(this, message_obj).get());
17331cb0ef41Sopenharmony_ci      std::ostringstream stack_trace_stream;
17341cb0ef41Sopenharmony_ci      PrintCurrentStackTrace(stack_trace_stream);
17351cb0ef41Sopenharmony_ci      PrintF(stderr, "%s", stack_trace_stream.str().c_str());
17361cb0ef41Sopenharmony_ci      base::OS::Abort();
17371cb0ef41Sopenharmony_ci    }
17381cb0ef41Sopenharmony_ci  }
17391cb0ef41Sopenharmony_ci
17401cb0ef41Sopenharmony_ci  return message_obj;
17411cb0ef41Sopenharmony_ci}
17421cb0ef41Sopenharmony_ci
17431cb0ef41Sopenharmony_ciObject Isolate::ThrowInternal(Object raw_exception, MessageLocation* location) {
17441cb0ef41Sopenharmony_ci  DCHECK(!has_pending_exception());
17451cb0ef41Sopenharmony_ci  IF_WASM(DCHECK_IMPLIES, trap_handler::IsTrapHandlerEnabled(),
17461cb0ef41Sopenharmony_ci          !trap_handler::IsThreadInWasm());
17471cb0ef41Sopenharmony_ci
17481cb0ef41Sopenharmony_ci  HandleScope scope(this);
17491cb0ef41Sopenharmony_ci  Handle<Object> exception(raw_exception, this);
17501cb0ef41Sopenharmony_ci
17511cb0ef41Sopenharmony_ci  if (FLAG_print_all_exceptions) {
17521cb0ef41Sopenharmony_ci    PrintF("=========================================================\n");
17531cb0ef41Sopenharmony_ci    PrintF("Exception thrown:\n");
17541cb0ef41Sopenharmony_ci    if (location) {
17551cb0ef41Sopenharmony_ci      Handle<Script> script = location->script();
17561cb0ef41Sopenharmony_ci      Handle<Object> name(script->GetNameOrSourceURL(), this);
17571cb0ef41Sopenharmony_ci      PrintF("at ");
17581cb0ef41Sopenharmony_ci      if (name->IsString() && String::cast(*name).length() > 0)
17591cb0ef41Sopenharmony_ci        String::cast(*name).PrintOn(stdout);
17601cb0ef41Sopenharmony_ci      else
17611cb0ef41Sopenharmony_ci        PrintF("<anonymous>");
17621cb0ef41Sopenharmony_ci// Script::GetLineNumber and Script::GetColumnNumber can allocate on the heap to
17631cb0ef41Sopenharmony_ci// initialize the line_ends array, so be careful when calling them.
17641cb0ef41Sopenharmony_ci#ifdef DEBUG
17651cb0ef41Sopenharmony_ci      if (AllowGarbageCollection::IsAllowed()) {
17661cb0ef41Sopenharmony_ci#else
17671cb0ef41Sopenharmony_ci      if ((false)) {
17681cb0ef41Sopenharmony_ci#endif
17691cb0ef41Sopenharmony_ci        PrintF(", %d:%d - %d:%d\n",
17701cb0ef41Sopenharmony_ci               Script::GetLineNumber(script, location->start_pos()) + 1,
17711cb0ef41Sopenharmony_ci               Script::GetColumnNumber(script, location->start_pos()),
17721cb0ef41Sopenharmony_ci               Script::GetLineNumber(script, location->end_pos()) + 1,
17731cb0ef41Sopenharmony_ci               Script::GetColumnNumber(script, location->end_pos()));
17741cb0ef41Sopenharmony_ci        // Make sure to update the raw exception pointer in case it moved.
17751cb0ef41Sopenharmony_ci        raw_exception = *exception;
17761cb0ef41Sopenharmony_ci      } else {
17771cb0ef41Sopenharmony_ci        PrintF(", line %d\n", script->GetLineNumber(location->start_pos()) + 1);
17781cb0ef41Sopenharmony_ci      }
17791cb0ef41Sopenharmony_ci    }
17801cb0ef41Sopenharmony_ci    raw_exception.Print();
17811cb0ef41Sopenharmony_ci    PrintF("Stack Trace:\n");
17821cb0ef41Sopenharmony_ci    PrintStack(stdout);
17831cb0ef41Sopenharmony_ci    PrintF("=========================================================\n");
17841cb0ef41Sopenharmony_ci  }
17851cb0ef41Sopenharmony_ci
17861cb0ef41Sopenharmony_ci  // Determine whether a message needs to be created for the given exception
17871cb0ef41Sopenharmony_ci  // depending on the following criteria:
17881cb0ef41Sopenharmony_ci  // 1) External v8::TryCatch missing: Always create a message because any
17891cb0ef41Sopenharmony_ci  //    JavaScript handler for a finally-block might re-throw to top-level.
17901cb0ef41Sopenharmony_ci  // 2) External v8::TryCatch exists: Only create a message if the handler
17911cb0ef41Sopenharmony_ci  //    captures messages or is verbose (which reports despite the catch).
17921cb0ef41Sopenharmony_ci  // 3) ReThrow from v8::TryCatch: The message from a previous throw still
17931cb0ef41Sopenharmony_ci  //    exists and we preserve it instead of creating a new message.
17941cb0ef41Sopenharmony_ci  bool requires_message = try_catch_handler() == nullptr ||
17951cb0ef41Sopenharmony_ci                          try_catch_handler()->is_verbose_ ||
17961cb0ef41Sopenharmony_ci                          try_catch_handler()->capture_message_;
17971cb0ef41Sopenharmony_ci  bool rethrowing_message = thread_local_top()->rethrowing_message_;
17981cb0ef41Sopenharmony_ci
17991cb0ef41Sopenharmony_ci  thread_local_top()->rethrowing_message_ = false;
18001cb0ef41Sopenharmony_ci
18011cb0ef41Sopenharmony_ci  // Notify debugger of exception.
18021cb0ef41Sopenharmony_ci  if (is_catchable_by_javascript(raw_exception)) {
18031cb0ef41Sopenharmony_ci    base::Optional<Object> maybe_exception = debug()->OnThrow(exception);
18041cb0ef41Sopenharmony_ci    if (maybe_exception.has_value()) {
18051cb0ef41Sopenharmony_ci      return *maybe_exception;
18061cb0ef41Sopenharmony_ci    }
18071cb0ef41Sopenharmony_ci  }
18081cb0ef41Sopenharmony_ci
18091cb0ef41Sopenharmony_ci  // Generate the message if required.
18101cb0ef41Sopenharmony_ci  if (requires_message && !rethrowing_message) {
18111cb0ef41Sopenharmony_ci    MessageLocation computed_location;
18121cb0ef41Sopenharmony_ci    // If no location was specified we try to use a computed one instead.
18131cb0ef41Sopenharmony_ci    if (location == nullptr && ComputeLocation(&computed_location)) {
18141cb0ef41Sopenharmony_ci      location = &computed_location;
18151cb0ef41Sopenharmony_ci    }
18161cb0ef41Sopenharmony_ci    if (bootstrapper()->IsActive()) {
18171cb0ef41Sopenharmony_ci      // It's not safe to try to make message objects or collect stack traces
18181cb0ef41Sopenharmony_ci      // while the bootstrapper is active since the infrastructure may not have
18191cb0ef41Sopenharmony_ci      // been properly initialized.
18201cb0ef41Sopenharmony_ci      ReportBootstrappingException(exception, location);
18211cb0ef41Sopenharmony_ci    } else {
18221cb0ef41Sopenharmony_ci      Handle<Object> message_obj = CreateMessageOrAbort(exception, location);
18231cb0ef41Sopenharmony_ci      set_pending_message(*message_obj);
18241cb0ef41Sopenharmony_ci    }
18251cb0ef41Sopenharmony_ci  }
18261cb0ef41Sopenharmony_ci
18271cb0ef41Sopenharmony_ci  // Set the exception being thrown.
18281cb0ef41Sopenharmony_ci  set_pending_exception(*exception);
18291cb0ef41Sopenharmony_ci  return ReadOnlyRoots(heap()).exception();
18301cb0ef41Sopenharmony_ci}
18311cb0ef41Sopenharmony_ci
18321cb0ef41Sopenharmony_ciObject Isolate::ReThrow(Object exception) {
18331cb0ef41Sopenharmony_ci  DCHECK(!has_pending_exception());
18341cb0ef41Sopenharmony_ci
18351cb0ef41Sopenharmony_ci  // Set the exception being re-thrown.
18361cb0ef41Sopenharmony_ci  set_pending_exception(exception);
18371cb0ef41Sopenharmony_ci  return ReadOnlyRoots(heap()).exception();
18381cb0ef41Sopenharmony_ci}
18391cb0ef41Sopenharmony_ci
18401cb0ef41Sopenharmony_ciObject Isolate::ReThrow(Object exception, Object message) {
18411cb0ef41Sopenharmony_ci  DCHECK(!has_pending_exception());
18421cb0ef41Sopenharmony_ci  DCHECK(!has_pending_message());
18431cb0ef41Sopenharmony_ci
18441cb0ef41Sopenharmony_ci  set_pending_message(message);
18451cb0ef41Sopenharmony_ci  return ReThrow(exception);
18461cb0ef41Sopenharmony_ci}
18471cb0ef41Sopenharmony_ci
18481cb0ef41Sopenharmony_cinamespace {
18491cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
18501cb0ef41Sopenharmony_ci// This scope will set the thread-in-wasm flag after the execution of all
18511cb0ef41Sopenharmony_ci// destructors. The thread-in-wasm flag is only set when the scope gets enabled.
18521cb0ef41Sopenharmony_ciclass SetThreadInWasmFlagScope {
18531cb0ef41Sopenharmony_ci public:
18541cb0ef41Sopenharmony_ci  SetThreadInWasmFlagScope() {
18551cb0ef41Sopenharmony_ci    DCHECK_IMPLIES(trap_handler::IsTrapHandlerEnabled(),
18561cb0ef41Sopenharmony_ci                   !trap_handler::IsThreadInWasm());
18571cb0ef41Sopenharmony_ci  }
18581cb0ef41Sopenharmony_ci
18591cb0ef41Sopenharmony_ci  ~SetThreadInWasmFlagScope() {
18601cb0ef41Sopenharmony_ci    if (enabled_) trap_handler::SetThreadInWasm();
18611cb0ef41Sopenharmony_ci  }
18621cb0ef41Sopenharmony_ci
18631cb0ef41Sopenharmony_ci  void Enable() { enabled_ = true; }
18641cb0ef41Sopenharmony_ci
18651cb0ef41Sopenharmony_ci private:
18661cb0ef41Sopenharmony_ci  bool enabled_ = false;
18671cb0ef41Sopenharmony_ci};
18681cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
18691cb0ef41Sopenharmony_ci}  // namespace
18701cb0ef41Sopenharmony_ci
18711cb0ef41Sopenharmony_ciObject Isolate::UnwindAndFindHandler() {
18721cb0ef41Sopenharmony_ci  // TODO(v8:12676): Fix gcmole failures in this function.
18731cb0ef41Sopenharmony_ci  DisableGCMole no_gcmole;
18741cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
18751cb0ef41Sopenharmony_ci  // Create the {SetThreadInWasmFlagScope} first in this function so that its
18761cb0ef41Sopenharmony_ci  // destructor gets called after all the other destructors. It is important
18771cb0ef41Sopenharmony_ci  // that the destructor sets the thread-in-wasm flag after all other
18781cb0ef41Sopenharmony_ci  // destructors. The other destructors may cause exceptions, e.g. ASan on
18791cb0ef41Sopenharmony_ci  // Windows, which would invalidate the thread-in-wasm flag when the wasm trap
18801cb0ef41Sopenharmony_ci  // handler handles such non-wasm exceptions.
18811cb0ef41Sopenharmony_ci  SetThreadInWasmFlagScope set_thread_in_wasm_flag_scope;
18821cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
18831cb0ef41Sopenharmony_ci  Object exception = pending_exception();
18841cb0ef41Sopenharmony_ci
18851cb0ef41Sopenharmony_ci  auto FoundHandler = [&](Context context, Address instruction_start,
18861cb0ef41Sopenharmony_ci                          intptr_t handler_offset,
18871cb0ef41Sopenharmony_ci                          Address constant_pool_address, Address handler_sp,
18881cb0ef41Sopenharmony_ci                          Address handler_fp, int num_frames_above_handler) {
18891cb0ef41Sopenharmony_ci    // Store information to be consumed by the CEntry.
18901cb0ef41Sopenharmony_ci    thread_local_top()->pending_handler_context_ = context;
18911cb0ef41Sopenharmony_ci    thread_local_top()->pending_handler_entrypoint_ =
18921cb0ef41Sopenharmony_ci        instruction_start + handler_offset;
18931cb0ef41Sopenharmony_ci    thread_local_top()->pending_handler_constant_pool_ = constant_pool_address;
18941cb0ef41Sopenharmony_ci    thread_local_top()->pending_handler_fp_ = handler_fp;
18951cb0ef41Sopenharmony_ci    thread_local_top()->pending_handler_sp_ = handler_sp;
18961cb0ef41Sopenharmony_ci    thread_local_top()->num_frames_above_pending_handler_ =
18971cb0ef41Sopenharmony_ci        num_frames_above_handler;
18981cb0ef41Sopenharmony_ci
18991cb0ef41Sopenharmony_ci    // Return and clear pending exception. The contract is that:
19001cb0ef41Sopenharmony_ci    // (1) the pending exception is stored in one place (no duplication), and
19011cb0ef41Sopenharmony_ci    // (2) within generated-code land, that one place is the return register.
19021cb0ef41Sopenharmony_ci    // If/when we unwind back into C++ (returning to the JSEntry stub,
19031cb0ef41Sopenharmony_ci    // or to Execution::CallWasm), the returned exception will be sent
19041cb0ef41Sopenharmony_ci    // back to isolate->set_pending_exception(...).
19051cb0ef41Sopenharmony_ci    clear_pending_exception();
19061cb0ef41Sopenharmony_ci    return exception;
19071cb0ef41Sopenharmony_ci  };
19081cb0ef41Sopenharmony_ci
19091cb0ef41Sopenharmony_ci  // Special handling of termination exceptions, uncatchable by JavaScript and
19101cb0ef41Sopenharmony_ci  // Wasm code, we unwind the handlers until the top ENTRY handler is found.
19111cb0ef41Sopenharmony_ci  bool catchable_by_js = is_catchable_by_javascript(exception);
19121cb0ef41Sopenharmony_ci  if (!catchable_by_js && !context().is_null()) {
19131cb0ef41Sopenharmony_ci    // Because the array join stack will not pop the elements when throwing the
19141cb0ef41Sopenharmony_ci    // uncatchable terminate exception, we need to clear the array join stack to
19151cb0ef41Sopenharmony_ci    // avoid leaving the stack in an invalid state.
19161cb0ef41Sopenharmony_ci    // See also CycleProtectedArrayJoin.
19171cb0ef41Sopenharmony_ci    raw_native_context().set_array_join_stack(
19181cb0ef41Sopenharmony_ci        ReadOnlyRoots(this).undefined_value());
19191cb0ef41Sopenharmony_ci  }
19201cb0ef41Sopenharmony_ci
19211cb0ef41Sopenharmony_ci  int visited_frames = 0;
19221cb0ef41Sopenharmony_ci
19231cb0ef41Sopenharmony_ci  // Compute handler and stack unwinding information by performing a full walk
19241cb0ef41Sopenharmony_ci  // over the stack and dispatching according to the frame type.
19251cb0ef41Sopenharmony_ci  for (StackFrameIterator iter(this);; iter.Advance(), visited_frames++) {
19261cb0ef41Sopenharmony_ci    // Handler must exist.
19271cb0ef41Sopenharmony_ci    DCHECK(!iter.done());
19281cb0ef41Sopenharmony_ci
19291cb0ef41Sopenharmony_ci    StackFrame* frame = iter.frame();
19301cb0ef41Sopenharmony_ci
19311cb0ef41Sopenharmony_ci    switch (frame->type()) {
19321cb0ef41Sopenharmony_ci      case StackFrame::ENTRY:
19331cb0ef41Sopenharmony_ci      case StackFrame::CONSTRUCT_ENTRY: {
19341cb0ef41Sopenharmony_ci        // For JSEntry frames we always have a handler.
19351cb0ef41Sopenharmony_ci        StackHandler* handler = frame->top_handler();
19361cb0ef41Sopenharmony_ci
19371cb0ef41Sopenharmony_ci        // Restore the next handler.
19381cb0ef41Sopenharmony_ci        thread_local_top()->handler_ = handler->next_address();
19391cb0ef41Sopenharmony_ci
19401cb0ef41Sopenharmony_ci        // Gather information from the handler.
19411cb0ef41Sopenharmony_ci        Code code = frame->LookupCode();
19421cb0ef41Sopenharmony_ci        HandlerTable table(code);
19431cb0ef41Sopenharmony_ci        return FoundHandler(Context(), code.InstructionStart(this, frame->pc()),
19441cb0ef41Sopenharmony_ci                            table.LookupReturn(0), code.constant_pool(),
19451cb0ef41Sopenharmony_ci                            handler->address() + StackHandlerConstants::kSize,
19461cb0ef41Sopenharmony_ci                            0, visited_frames);
19471cb0ef41Sopenharmony_ci      }
19481cb0ef41Sopenharmony_ci
19491cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
19501cb0ef41Sopenharmony_ci      case StackFrame::C_WASM_ENTRY: {
19511cb0ef41Sopenharmony_ci        StackHandler* handler = frame->top_handler();
19521cb0ef41Sopenharmony_ci        thread_local_top()->handler_ = handler->next_address();
19531cb0ef41Sopenharmony_ci        Code code = frame->LookupCode();
19541cb0ef41Sopenharmony_ci        HandlerTable table(code);
19551cb0ef41Sopenharmony_ci        Address instruction_start = code.InstructionStart(this, frame->pc());
19561cb0ef41Sopenharmony_ci        int return_offset = static_cast<int>(frame->pc() - instruction_start);
19571cb0ef41Sopenharmony_ci        int handler_offset = table.LookupReturn(return_offset);
19581cb0ef41Sopenharmony_ci        DCHECK_NE(-1, handler_offset);
19591cb0ef41Sopenharmony_ci        // Compute the stack pointer from the frame pointer. This ensures that
19601cb0ef41Sopenharmony_ci        // argument slots on the stack are dropped as returning would.
19611cb0ef41Sopenharmony_ci        Address return_sp = frame->fp() +
19621cb0ef41Sopenharmony_ci                            StandardFrameConstants::kFixedFrameSizeAboveFp -
19631cb0ef41Sopenharmony_ci                            code.stack_slots() * kSystemPointerSize;
19641cb0ef41Sopenharmony_ci        return FoundHandler(Context(), instruction_start, handler_offset,
19651cb0ef41Sopenharmony_ci                            code.constant_pool(), return_sp, frame->fp(),
19661cb0ef41Sopenharmony_ci                            visited_frames);
19671cb0ef41Sopenharmony_ci      }
19681cb0ef41Sopenharmony_ci
19691cb0ef41Sopenharmony_ci      case StackFrame::WASM: {
19701cb0ef41Sopenharmony_ci        if (!is_catchable_by_wasm(exception)) break;
19711cb0ef41Sopenharmony_ci
19721cb0ef41Sopenharmony_ci        // For WebAssembly frames we perform a lookup in the handler table.
19731cb0ef41Sopenharmony_ci        // This code ref scope is here to avoid a check failure when looking up
19741cb0ef41Sopenharmony_ci        // the code. It's not actually necessary to keep the code alive as it's
19751cb0ef41Sopenharmony_ci        // currently being executed.
19761cb0ef41Sopenharmony_ci        wasm::WasmCodeRefScope code_ref_scope;
19771cb0ef41Sopenharmony_ci        WasmFrame* wasm_frame = static_cast<WasmFrame*>(frame);
19781cb0ef41Sopenharmony_ci        wasm::WasmCode* wasm_code =
19791cb0ef41Sopenharmony_ci            wasm::GetWasmCodeManager()->LookupCode(frame->pc());
19801cb0ef41Sopenharmony_ci        int offset = wasm_frame->LookupExceptionHandlerInTable();
19811cb0ef41Sopenharmony_ci        if (offset < 0) break;
19821cb0ef41Sopenharmony_ci        wasm::GetWasmEngine()->SampleCatchEvent(this);
19831cb0ef41Sopenharmony_ci        // Compute the stack pointer from the frame pointer. This ensures that
19841cb0ef41Sopenharmony_ci        // argument slots on the stack are dropped as returning would.
19851cb0ef41Sopenharmony_ci        Address return_sp = frame->fp() +
19861cb0ef41Sopenharmony_ci                            StandardFrameConstants::kFixedFrameSizeAboveFp -
19871cb0ef41Sopenharmony_ci                            wasm_code->stack_slots() * kSystemPointerSize;
19881cb0ef41Sopenharmony_ci
19891cb0ef41Sopenharmony_ci        // This is going to be handled by WebAssembly, so we need to set the TLS
19901cb0ef41Sopenharmony_ci        // flag. The {SetThreadInWasmFlagScope} will set the flag after all
19911cb0ef41Sopenharmony_ci        // destructors have been executed.
19921cb0ef41Sopenharmony_ci        set_thread_in_wasm_flag_scope.Enable();
19931cb0ef41Sopenharmony_ci        return FoundHandler(Context(), wasm_code->instruction_start(), offset,
19941cb0ef41Sopenharmony_ci                            wasm_code->constant_pool(), return_sp, frame->fp(),
19951cb0ef41Sopenharmony_ci                            visited_frames);
19961cb0ef41Sopenharmony_ci      }
19971cb0ef41Sopenharmony_ci
19981cb0ef41Sopenharmony_ci      case StackFrame::WASM_COMPILE_LAZY: {
19991cb0ef41Sopenharmony_ci        // Can only fail directly on invocation. This happens if an invalid
20001cb0ef41Sopenharmony_ci        // function was validated lazily.
20011cb0ef41Sopenharmony_ci        DCHECK(FLAG_wasm_lazy_validation);
20021cb0ef41Sopenharmony_ci        break;
20031cb0ef41Sopenharmony_ci      }
20041cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
20051cb0ef41Sopenharmony_ci
20061cb0ef41Sopenharmony_ci      case StackFrame::OPTIMIZED: {
20071cb0ef41Sopenharmony_ci        // For optimized frames we perform a lookup in the handler table.
20081cb0ef41Sopenharmony_ci        if (!catchable_by_js) break;
20091cb0ef41Sopenharmony_ci        OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame);
20101cb0ef41Sopenharmony_ci        Code code = frame->LookupCode();
20111cb0ef41Sopenharmony_ci        int offset = js_frame->LookupExceptionHandlerInTable(nullptr, nullptr);
20121cb0ef41Sopenharmony_ci        if (offset < 0) break;
20131cb0ef41Sopenharmony_ci        // Compute the stack pointer from the frame pointer. This ensures
20141cb0ef41Sopenharmony_ci        // that argument slots on the stack are dropped as returning would.
20151cb0ef41Sopenharmony_ci        Address return_sp = frame->fp() +
20161cb0ef41Sopenharmony_ci                            StandardFrameConstants::kFixedFrameSizeAboveFp -
20171cb0ef41Sopenharmony_ci                            code.stack_slots() * kSystemPointerSize;
20181cb0ef41Sopenharmony_ci
20191cb0ef41Sopenharmony_ci        // TODO(bmeurer): Turbofanned BUILTIN frames appear as OPTIMIZED,
20201cb0ef41Sopenharmony_ci        // but do not have a code kind of TURBOFAN.
20211cb0ef41Sopenharmony_ci        if (CodeKindCanDeoptimize(code.kind()) &&
20221cb0ef41Sopenharmony_ci            code.marked_for_deoptimization()) {
20231cb0ef41Sopenharmony_ci          // If the target code is lazy deoptimized, we jump to the original
20241cb0ef41Sopenharmony_ci          // return address, but we make a note that we are throwing, so
20251cb0ef41Sopenharmony_ci          // that the deoptimizer can do the right thing.
20261cb0ef41Sopenharmony_ci          offset = static_cast<int>(frame->pc() - code.entry());
20271cb0ef41Sopenharmony_ci          set_deoptimizer_lazy_throw(true);
20281cb0ef41Sopenharmony_ci        }
20291cb0ef41Sopenharmony_ci
20301cb0ef41Sopenharmony_ci        return FoundHandler(Context(), code.InstructionStart(this, frame->pc()),
20311cb0ef41Sopenharmony_ci                            offset, code.constant_pool(), return_sp,
20321cb0ef41Sopenharmony_ci                            frame->fp(), visited_frames);
20331cb0ef41Sopenharmony_ci      }
20341cb0ef41Sopenharmony_ci
20351cb0ef41Sopenharmony_ci      case StackFrame::STUB: {
20361cb0ef41Sopenharmony_ci        // Some stubs are able to handle exceptions.
20371cb0ef41Sopenharmony_ci        if (!catchable_by_js) break;
20381cb0ef41Sopenharmony_ci        StubFrame* stub_frame = static_cast<StubFrame*>(frame);
20391cb0ef41Sopenharmony_ci#if defined(DEBUG) && V8_ENABLE_WEBASSEMBLY
20401cb0ef41Sopenharmony_ci        wasm::WasmCodeRefScope code_ref_scope;
20411cb0ef41Sopenharmony_ci        DCHECK_NULL(wasm::GetWasmCodeManager()->LookupCode(frame->pc()));
20421cb0ef41Sopenharmony_ci#endif  // defined(DEBUG) && V8_ENABLE_WEBASSEMBLY
20431cb0ef41Sopenharmony_ci        Code code = stub_frame->LookupCode();
20441cb0ef41Sopenharmony_ci        if (!code.IsCode() || code.kind() != CodeKind::BUILTIN ||
20451cb0ef41Sopenharmony_ci            !code.has_handler_table() || !code.is_turbofanned()) {
20461cb0ef41Sopenharmony_ci          break;
20471cb0ef41Sopenharmony_ci        }
20481cb0ef41Sopenharmony_ci
20491cb0ef41Sopenharmony_ci        int offset = stub_frame->LookupExceptionHandlerInTable();
20501cb0ef41Sopenharmony_ci        if (offset < 0) break;
20511cb0ef41Sopenharmony_ci
20521cb0ef41Sopenharmony_ci        // Compute the stack pointer from the frame pointer. This ensures
20531cb0ef41Sopenharmony_ci        // that argument slots on the stack are dropped as returning would.
20541cb0ef41Sopenharmony_ci        Address return_sp = frame->fp() +
20551cb0ef41Sopenharmony_ci                            StandardFrameConstants::kFixedFrameSizeAboveFp -
20561cb0ef41Sopenharmony_ci                            code.stack_slots() * kSystemPointerSize;
20571cb0ef41Sopenharmony_ci
20581cb0ef41Sopenharmony_ci        return FoundHandler(Context(), code.InstructionStart(this, frame->pc()),
20591cb0ef41Sopenharmony_ci                            offset, code.constant_pool(), return_sp,
20601cb0ef41Sopenharmony_ci                            frame->fp(), visited_frames);
20611cb0ef41Sopenharmony_ci      }
20621cb0ef41Sopenharmony_ci
20631cb0ef41Sopenharmony_ci      case StackFrame::INTERPRETED:
20641cb0ef41Sopenharmony_ci      case StackFrame::BASELINE: {
20651cb0ef41Sopenharmony_ci        // For interpreted frame we perform a range lookup in the handler table.
20661cb0ef41Sopenharmony_ci        if (!catchable_by_js) break;
20671cb0ef41Sopenharmony_ci        UnoptimizedFrame* js_frame = UnoptimizedFrame::cast(frame);
20681cb0ef41Sopenharmony_ci        int register_slots = UnoptimizedFrameConstants::RegisterStackSlotCount(
20691cb0ef41Sopenharmony_ci            js_frame->GetBytecodeArray().register_count());
20701cb0ef41Sopenharmony_ci        int context_reg = 0;  // Will contain register index holding context.
20711cb0ef41Sopenharmony_ci        int offset =
20721cb0ef41Sopenharmony_ci            js_frame->LookupExceptionHandlerInTable(&context_reg, nullptr);
20731cb0ef41Sopenharmony_ci        if (offset < 0) break;
20741cb0ef41Sopenharmony_ci        // Compute the stack pointer from the frame pointer. This ensures that
20751cb0ef41Sopenharmony_ci        // argument slots on the stack are dropped as returning would.
20761cb0ef41Sopenharmony_ci        // Note: This is only needed for interpreted frames that have been
20771cb0ef41Sopenharmony_ci        //       materialized by the deoptimizer. If there is a handler frame
20781cb0ef41Sopenharmony_ci        //       in between then {frame->sp()} would already be correct.
20791cb0ef41Sopenharmony_ci        Address return_sp = frame->fp() -
20801cb0ef41Sopenharmony_ci                            InterpreterFrameConstants::kFixedFrameSizeFromFp -
20811cb0ef41Sopenharmony_ci                            register_slots * kSystemPointerSize;
20821cb0ef41Sopenharmony_ci
20831cb0ef41Sopenharmony_ci        // Patch the bytecode offset in the interpreted frame to reflect the
20841cb0ef41Sopenharmony_ci        // position of the exception handler. The special builtin below will
20851cb0ef41Sopenharmony_ci        // take care of continuing to dispatch at that position. Also restore
20861cb0ef41Sopenharmony_ci        // the correct context for the handler from the interpreter register.
20871cb0ef41Sopenharmony_ci        Context context =
20881cb0ef41Sopenharmony_ci            Context::cast(js_frame->ReadInterpreterRegister(context_reg));
20891cb0ef41Sopenharmony_ci        DCHECK(context.IsContext());
20901cb0ef41Sopenharmony_ci
20911cb0ef41Sopenharmony_ci        if (frame->is_baseline()) {
20921cb0ef41Sopenharmony_ci          BaselineFrame* sp_frame = BaselineFrame::cast(js_frame);
20931cb0ef41Sopenharmony_ci          Code code = sp_frame->LookupCode();
20941cb0ef41Sopenharmony_ci          intptr_t pc_offset = sp_frame->GetPCForBytecodeOffset(offset);
20951cb0ef41Sopenharmony_ci          // Patch the context register directly on the frame, so that we don't
20961cb0ef41Sopenharmony_ci          // need to have a context read + write in the baseline code.
20971cb0ef41Sopenharmony_ci          sp_frame->PatchContext(context);
20981cb0ef41Sopenharmony_ci          return FoundHandler(
20991cb0ef41Sopenharmony_ci              Context(), code.InstructionStart(this, sp_frame->sp()), pc_offset,
21001cb0ef41Sopenharmony_ci              code.constant_pool(), return_sp, sp_frame->fp(), visited_frames);
21011cb0ef41Sopenharmony_ci        } else {
21021cb0ef41Sopenharmony_ci          InterpretedFrame::cast(js_frame)->PatchBytecodeOffset(
21031cb0ef41Sopenharmony_ci              static_cast<int>(offset));
21041cb0ef41Sopenharmony_ci
21051cb0ef41Sopenharmony_ci          Code code =
21061cb0ef41Sopenharmony_ci              FromCodeT(builtins()->code(Builtin::kInterpreterEnterAtBytecode));
21071cb0ef41Sopenharmony_ci          // We subtract a frame from visited_frames because otherwise the
21081cb0ef41Sopenharmony_ci          // shadow stack will drop the underlying interpreter entry trampoline
21091cb0ef41Sopenharmony_ci          // in which the handler runs.
21101cb0ef41Sopenharmony_ci          //
21111cb0ef41Sopenharmony_ci          // An interpreted frame cannot be the first frame we look at
21121cb0ef41Sopenharmony_ci          // because at a minimum, an exit frame into C++ has to separate
21131cb0ef41Sopenharmony_ci          // it and the context in which this C++ code runs.
21141cb0ef41Sopenharmony_ci          CHECK_GE(visited_frames, 1);
21151cb0ef41Sopenharmony_ci          return FoundHandler(context, code.InstructionStart(), 0,
21161cb0ef41Sopenharmony_ci                              code.constant_pool(), return_sp, frame->fp(),
21171cb0ef41Sopenharmony_ci                              visited_frames - 1);
21181cb0ef41Sopenharmony_ci        }
21191cb0ef41Sopenharmony_ci      }
21201cb0ef41Sopenharmony_ci
21211cb0ef41Sopenharmony_ci      case StackFrame::BUILTIN:
21221cb0ef41Sopenharmony_ci        // For builtin frames we are guaranteed not to find a handler.
21231cb0ef41Sopenharmony_ci        if (catchable_by_js) {
21241cb0ef41Sopenharmony_ci          CHECK_EQ(-1, BuiltinFrame::cast(frame)->LookupExceptionHandlerInTable(
21251cb0ef41Sopenharmony_ci                           nullptr, nullptr));
21261cb0ef41Sopenharmony_ci        }
21271cb0ef41Sopenharmony_ci        break;
21281cb0ef41Sopenharmony_ci
21291cb0ef41Sopenharmony_ci      case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH: {
21301cb0ef41Sopenharmony_ci        // Builtin continuation frames with catch can handle exceptions.
21311cb0ef41Sopenharmony_ci        if (!catchable_by_js) break;
21321cb0ef41Sopenharmony_ci        JavaScriptBuiltinContinuationWithCatchFrame* js_frame =
21331cb0ef41Sopenharmony_ci            JavaScriptBuiltinContinuationWithCatchFrame::cast(frame);
21341cb0ef41Sopenharmony_ci        js_frame->SetException(exception);
21351cb0ef41Sopenharmony_ci
21361cb0ef41Sopenharmony_ci        // Reconstruct the stack pointer from the frame pointer.
21371cb0ef41Sopenharmony_ci        Address return_sp = js_frame->fp() - js_frame->GetSPToFPDelta();
21381cb0ef41Sopenharmony_ci        Code code = js_frame->LookupCode();
21391cb0ef41Sopenharmony_ci        return FoundHandler(Context(), code.InstructionStart(), 0,
21401cb0ef41Sopenharmony_ci                            code.constant_pool(), return_sp, frame->fp(),
21411cb0ef41Sopenharmony_ci                            visited_frames);
21421cb0ef41Sopenharmony_ci      }
21431cb0ef41Sopenharmony_ci
21441cb0ef41Sopenharmony_ci      default:
21451cb0ef41Sopenharmony_ci        // All other types can not handle exception.
21461cb0ef41Sopenharmony_ci        break;
21471cb0ef41Sopenharmony_ci    }
21481cb0ef41Sopenharmony_ci
21491cb0ef41Sopenharmony_ci    if (frame->is_optimized()) {
21501cb0ef41Sopenharmony_ci      // Remove per-frame stored materialized objects.
21511cb0ef41Sopenharmony_ci      bool removed = materialized_object_store_->Remove(frame->fp());
21521cb0ef41Sopenharmony_ci      USE(removed);
21531cb0ef41Sopenharmony_ci      // If there were any materialized objects, the code should be
21541cb0ef41Sopenharmony_ci      // marked for deopt.
21551cb0ef41Sopenharmony_ci      DCHECK_IMPLIES(removed, frame->LookupCode().marked_for_deoptimization());
21561cb0ef41Sopenharmony_ci    }
21571cb0ef41Sopenharmony_ci  }
21581cb0ef41Sopenharmony_ci
21591cb0ef41Sopenharmony_ci  UNREACHABLE();
21601cb0ef41Sopenharmony_ci}
21611cb0ef41Sopenharmony_ci
21621cb0ef41Sopenharmony_cinamespace {
21631cb0ef41Sopenharmony_ciHandlerTable::CatchPrediction PredictException(JavaScriptFrame* frame) {
21641cb0ef41Sopenharmony_ci  HandlerTable::CatchPrediction prediction;
21651cb0ef41Sopenharmony_ci  if (frame->is_optimized()) {
21661cb0ef41Sopenharmony_ci    if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) {
21671cb0ef41Sopenharmony_ci      // This optimized frame will catch. It's handler table does not include
21681cb0ef41Sopenharmony_ci      // exception prediction, and we need to use the corresponding handler
21691cb0ef41Sopenharmony_ci      // tables on the unoptimized code objects.
21701cb0ef41Sopenharmony_ci      std::vector<FrameSummary> summaries;
21711cb0ef41Sopenharmony_ci      frame->Summarize(&summaries);
21721cb0ef41Sopenharmony_ci      for (size_t i = summaries.size(); i != 0; i--) {
21731cb0ef41Sopenharmony_ci        const FrameSummary& summary = summaries[i - 1];
21741cb0ef41Sopenharmony_ci        Handle<AbstractCode> code = summary.AsJavaScript().abstract_code();
21751cb0ef41Sopenharmony_ci        if (code->IsCode() && code->kind() == CodeKind::BUILTIN) {
21761cb0ef41Sopenharmony_ci          prediction = code->GetCode().GetBuiltinCatchPrediction();
21771cb0ef41Sopenharmony_ci          if (prediction == HandlerTable::UNCAUGHT) continue;
21781cb0ef41Sopenharmony_ci          return prediction;
21791cb0ef41Sopenharmony_ci        }
21801cb0ef41Sopenharmony_ci
21811cb0ef41Sopenharmony_ci        // Must have been constructed from a bytecode array.
21821cb0ef41Sopenharmony_ci        CHECK_EQ(CodeKind::INTERPRETED_FUNCTION, code->kind());
21831cb0ef41Sopenharmony_ci        int code_offset = summary.code_offset();
21841cb0ef41Sopenharmony_ci        HandlerTable table(code->GetBytecodeArray());
21851cb0ef41Sopenharmony_ci        int index = table.LookupRange(code_offset, nullptr, &prediction);
21861cb0ef41Sopenharmony_ci        if (index <= 0) continue;
21871cb0ef41Sopenharmony_ci        if (prediction == HandlerTable::UNCAUGHT) continue;
21881cb0ef41Sopenharmony_ci        return prediction;
21891cb0ef41Sopenharmony_ci      }
21901cb0ef41Sopenharmony_ci    }
21911cb0ef41Sopenharmony_ci  } else if (frame->LookupExceptionHandlerInTable(nullptr, &prediction) > 0) {
21921cb0ef41Sopenharmony_ci    return prediction;
21931cb0ef41Sopenharmony_ci  }
21941cb0ef41Sopenharmony_ci  return HandlerTable::UNCAUGHT;
21951cb0ef41Sopenharmony_ci}
21961cb0ef41Sopenharmony_ci
21971cb0ef41Sopenharmony_ciIsolate::CatchType ToCatchType(HandlerTable::CatchPrediction prediction) {
21981cb0ef41Sopenharmony_ci  switch (prediction) {
21991cb0ef41Sopenharmony_ci    case HandlerTable::UNCAUGHT:
22001cb0ef41Sopenharmony_ci      return Isolate::NOT_CAUGHT;
22011cb0ef41Sopenharmony_ci    case HandlerTable::CAUGHT:
22021cb0ef41Sopenharmony_ci      return Isolate::CAUGHT_BY_JAVASCRIPT;
22031cb0ef41Sopenharmony_ci    case HandlerTable::PROMISE:
22041cb0ef41Sopenharmony_ci      return Isolate::CAUGHT_BY_PROMISE;
22051cb0ef41Sopenharmony_ci    case HandlerTable::UNCAUGHT_ASYNC_AWAIT:
22061cb0ef41Sopenharmony_ci    case HandlerTable::ASYNC_AWAIT:
22071cb0ef41Sopenharmony_ci      return Isolate::CAUGHT_BY_ASYNC_AWAIT;
22081cb0ef41Sopenharmony_ci    default:
22091cb0ef41Sopenharmony_ci      UNREACHABLE();
22101cb0ef41Sopenharmony_ci  }
22111cb0ef41Sopenharmony_ci}
22121cb0ef41Sopenharmony_ci}  // anonymous namespace
22131cb0ef41Sopenharmony_ci
22141cb0ef41Sopenharmony_ciIsolate::CatchType Isolate::PredictExceptionCatcher() {
22151cb0ef41Sopenharmony_ci  Address external_handler = thread_local_top()->try_catch_handler_address();
22161cb0ef41Sopenharmony_ci  if (TopExceptionHandlerType(Object()) ==
22171cb0ef41Sopenharmony_ci      ExceptionHandlerType::kExternalTryCatch) {
22181cb0ef41Sopenharmony_ci    return CAUGHT_BY_EXTERNAL;
22191cb0ef41Sopenharmony_ci  }
22201cb0ef41Sopenharmony_ci
22211cb0ef41Sopenharmony_ci  // Search for an exception handler by performing a full walk over the stack.
22221cb0ef41Sopenharmony_ci  for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) {
22231cb0ef41Sopenharmony_ci    StackFrame* frame = iter.frame();
22241cb0ef41Sopenharmony_ci
22251cb0ef41Sopenharmony_ci    switch (frame->type()) {
22261cb0ef41Sopenharmony_ci      case StackFrame::ENTRY:
22271cb0ef41Sopenharmony_ci      case StackFrame::CONSTRUCT_ENTRY: {
22281cb0ef41Sopenharmony_ci        Address entry_handler = frame->top_handler()->next_address();
22291cb0ef41Sopenharmony_ci        // The exception has been externally caught if and only if there is an
22301cb0ef41Sopenharmony_ci        // external handler which is on top of the top-most JS_ENTRY handler.
22311cb0ef41Sopenharmony_ci        if (external_handler != kNullAddress &&
22321cb0ef41Sopenharmony_ci            !try_catch_handler()->is_verbose_) {
22331cb0ef41Sopenharmony_ci          if (entry_handler == kNullAddress ||
22341cb0ef41Sopenharmony_ci              entry_handler > external_handler) {
22351cb0ef41Sopenharmony_ci            return CAUGHT_BY_EXTERNAL;
22361cb0ef41Sopenharmony_ci          }
22371cb0ef41Sopenharmony_ci        }
22381cb0ef41Sopenharmony_ci      } break;
22391cb0ef41Sopenharmony_ci
22401cb0ef41Sopenharmony_ci      // For JavaScript frames we perform a lookup in the handler table.
22411cb0ef41Sopenharmony_ci      case StackFrame::OPTIMIZED:
22421cb0ef41Sopenharmony_ci      case StackFrame::INTERPRETED:
22431cb0ef41Sopenharmony_ci      case StackFrame::BASELINE:
22441cb0ef41Sopenharmony_ci      case StackFrame::BUILTIN: {
22451cb0ef41Sopenharmony_ci        JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame);
22461cb0ef41Sopenharmony_ci        Isolate::CatchType prediction = ToCatchType(PredictException(js_frame));
22471cb0ef41Sopenharmony_ci        if (prediction == NOT_CAUGHT) break;
22481cb0ef41Sopenharmony_ci        return prediction;
22491cb0ef41Sopenharmony_ci      }
22501cb0ef41Sopenharmony_ci
22511cb0ef41Sopenharmony_ci      case StackFrame::STUB: {
22521cb0ef41Sopenharmony_ci        Handle<Code> code(frame->LookupCode(), this);
22531cb0ef41Sopenharmony_ci        if (!code->IsCode() || code->kind() != CodeKind::BUILTIN ||
22541cb0ef41Sopenharmony_ci            !code->has_handler_table() || !code->is_turbofanned()) {
22551cb0ef41Sopenharmony_ci          break;
22561cb0ef41Sopenharmony_ci        }
22571cb0ef41Sopenharmony_ci
22581cb0ef41Sopenharmony_ci        CatchType prediction = ToCatchType(code->GetBuiltinCatchPrediction());
22591cb0ef41Sopenharmony_ci        if (prediction != NOT_CAUGHT) return prediction;
22601cb0ef41Sopenharmony_ci      } break;
22611cb0ef41Sopenharmony_ci
22621cb0ef41Sopenharmony_ci      case StackFrame::JAVA_SCRIPT_BUILTIN_CONTINUATION_WITH_CATCH: {
22631cb0ef41Sopenharmony_ci        Handle<Code> code(frame->LookupCode(), this);
22641cb0ef41Sopenharmony_ci        CatchType prediction = ToCatchType(code->GetBuiltinCatchPrediction());
22651cb0ef41Sopenharmony_ci        if (prediction != NOT_CAUGHT) return prediction;
22661cb0ef41Sopenharmony_ci      } break;
22671cb0ef41Sopenharmony_ci
22681cb0ef41Sopenharmony_ci      default:
22691cb0ef41Sopenharmony_ci        // All other types can not handle exception.
22701cb0ef41Sopenharmony_ci        break;
22711cb0ef41Sopenharmony_ci    }
22721cb0ef41Sopenharmony_ci  }
22731cb0ef41Sopenharmony_ci
22741cb0ef41Sopenharmony_ci  // Handler not found.
22751cb0ef41Sopenharmony_ci  return NOT_CAUGHT;
22761cb0ef41Sopenharmony_ci}
22771cb0ef41Sopenharmony_ci
22781cb0ef41Sopenharmony_ciObject Isolate::ThrowIllegalOperation() {
22791cb0ef41Sopenharmony_ci  if (FLAG_stack_trace_on_illegal) PrintStack(stdout);
22801cb0ef41Sopenharmony_ci  return Throw(ReadOnlyRoots(heap()).illegal_access_string());
22811cb0ef41Sopenharmony_ci}
22821cb0ef41Sopenharmony_ci
22831cb0ef41Sopenharmony_civoid Isolate::ScheduleThrow(Object exception) {
22841cb0ef41Sopenharmony_ci  // When scheduling a throw we first throw the exception to get the
22851cb0ef41Sopenharmony_ci  // error reporting if it is uncaught before rescheduling it.
22861cb0ef41Sopenharmony_ci  Throw(exception);
22871cb0ef41Sopenharmony_ci  PropagatePendingExceptionToExternalTryCatch(
22881cb0ef41Sopenharmony_ci      TopExceptionHandlerType(pending_exception()));
22891cb0ef41Sopenharmony_ci  if (has_pending_exception()) {
22901cb0ef41Sopenharmony_ci    set_scheduled_exception(pending_exception());
22911cb0ef41Sopenharmony_ci    thread_local_top()->external_caught_exception_ = false;
22921cb0ef41Sopenharmony_ci    clear_pending_exception();
22931cb0ef41Sopenharmony_ci  }
22941cb0ef41Sopenharmony_ci}
22951cb0ef41Sopenharmony_ci
22961cb0ef41Sopenharmony_civoid Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) {
22971cb0ef41Sopenharmony_ci  DCHECK(handler == try_catch_handler());
22981cb0ef41Sopenharmony_ci  DCHECK(handler->HasCaught());
22991cb0ef41Sopenharmony_ci  DCHECK(handler->rethrow_);
23001cb0ef41Sopenharmony_ci  DCHECK(handler->capture_message_);
23011cb0ef41Sopenharmony_ci  Object message(reinterpret_cast<Address>(handler->message_obj_));
23021cb0ef41Sopenharmony_ci  DCHECK(message.IsJSMessageObject() || message.IsTheHole(this));
23031cb0ef41Sopenharmony_ci  set_pending_message(message);
23041cb0ef41Sopenharmony_ci}
23051cb0ef41Sopenharmony_ci
23061cb0ef41Sopenharmony_civoid Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) {
23071cb0ef41Sopenharmony_ci  DCHECK(has_scheduled_exception());
23081cb0ef41Sopenharmony_ci  if (reinterpret_cast<void*>(scheduled_exception().ptr()) ==
23091cb0ef41Sopenharmony_ci      handler->exception_) {
23101cb0ef41Sopenharmony_ci    DCHECK_NE(scheduled_exception(),
23111cb0ef41Sopenharmony_ci              ReadOnlyRoots(heap()).termination_exception());
23121cb0ef41Sopenharmony_ci    clear_scheduled_exception();
23131cb0ef41Sopenharmony_ci  } else {
23141cb0ef41Sopenharmony_ci    DCHECK_EQ(scheduled_exception(),
23151cb0ef41Sopenharmony_ci              ReadOnlyRoots(heap()).termination_exception());
23161cb0ef41Sopenharmony_ci    // Clear termination once we returned from all V8 frames.
23171cb0ef41Sopenharmony_ci    if (thread_local_top()->CallDepthIsZero()) {
23181cb0ef41Sopenharmony_ci      thread_local_top()->external_caught_exception_ = false;
23191cb0ef41Sopenharmony_ci      clear_scheduled_exception();
23201cb0ef41Sopenharmony_ci    }
23211cb0ef41Sopenharmony_ci  }
23221cb0ef41Sopenharmony_ci  if (reinterpret_cast<void*>(thread_local_top()->pending_message_.ptr()) ==
23231cb0ef41Sopenharmony_ci      handler->message_obj_) {
23241cb0ef41Sopenharmony_ci    clear_pending_message();
23251cb0ef41Sopenharmony_ci  }
23261cb0ef41Sopenharmony_ci}
23271cb0ef41Sopenharmony_ci
23281cb0ef41Sopenharmony_ciObject Isolate::PromoteScheduledException() {
23291cb0ef41Sopenharmony_ci  Object thrown = scheduled_exception();
23301cb0ef41Sopenharmony_ci  clear_scheduled_exception();
23311cb0ef41Sopenharmony_ci  // Re-throw the exception to avoid getting repeated error reporting.
23321cb0ef41Sopenharmony_ci  return ReThrow(thrown);
23331cb0ef41Sopenharmony_ci}
23341cb0ef41Sopenharmony_ci
23351cb0ef41Sopenharmony_civoid Isolate::PrintCurrentStackTrace(std::ostream& out) {
23361cb0ef41Sopenharmony_ci  Handle<FixedArray> frames = CaptureSimpleStackTrace(
23371cb0ef41Sopenharmony_ci      this, FixedArray::kMaxLength, SKIP_NONE, factory()->undefined_value());
23381cb0ef41Sopenharmony_ci
23391cb0ef41Sopenharmony_ci  IncrementalStringBuilder builder(this);
23401cb0ef41Sopenharmony_ci  for (int i = 0; i < frames->length(); ++i) {
23411cb0ef41Sopenharmony_ci    Handle<CallSiteInfo> frame(CallSiteInfo::cast(frames->get(i)), this);
23421cb0ef41Sopenharmony_ci    SerializeCallSiteInfo(this, frame, &builder);
23431cb0ef41Sopenharmony_ci  }
23441cb0ef41Sopenharmony_ci
23451cb0ef41Sopenharmony_ci  Handle<String> stack_trace = builder.Finish().ToHandleChecked();
23461cb0ef41Sopenharmony_ci  stack_trace->PrintOn(out);
23471cb0ef41Sopenharmony_ci}
23481cb0ef41Sopenharmony_ci
23491cb0ef41Sopenharmony_cibool Isolate::ComputeLocation(MessageLocation* target) {
23501cb0ef41Sopenharmony_ci  StackTraceFrameIterator it(this);
23511cb0ef41Sopenharmony_ci  if (it.done()) return false;
23521cb0ef41Sopenharmony_ci  // Compute the location from the function and the relocation info of the
23531cb0ef41Sopenharmony_ci  // baseline code. For optimized code this will use the deoptimization
23541cb0ef41Sopenharmony_ci  // information to get canonical location information.
23551cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
23561cb0ef41Sopenharmony_ci  wasm::WasmCodeRefScope code_ref_scope;
23571cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
23581cb0ef41Sopenharmony_ci  FrameSummary summary = it.GetTopValidFrame();
23591cb0ef41Sopenharmony_ci  Handle<SharedFunctionInfo> shared;
23601cb0ef41Sopenharmony_ci  Handle<Object> script = summary.script();
23611cb0ef41Sopenharmony_ci  if (!script->IsScript() || Script::cast(*script).source().IsUndefined(this)) {
23621cb0ef41Sopenharmony_ci    return false;
23631cb0ef41Sopenharmony_ci  }
23641cb0ef41Sopenharmony_ci
23651cb0ef41Sopenharmony_ci  if (summary.IsJavaScript()) {
23661cb0ef41Sopenharmony_ci    shared = handle(summary.AsJavaScript().function()->shared(), this);
23671cb0ef41Sopenharmony_ci  }
23681cb0ef41Sopenharmony_ci  if (summary.AreSourcePositionsAvailable()) {
23691cb0ef41Sopenharmony_ci    int pos = summary.SourcePosition();
23701cb0ef41Sopenharmony_ci    *target =
23711cb0ef41Sopenharmony_ci        MessageLocation(Handle<Script>::cast(script), pos, pos + 1, shared);
23721cb0ef41Sopenharmony_ci  } else {
23731cb0ef41Sopenharmony_ci    *target = MessageLocation(Handle<Script>::cast(script), shared,
23741cb0ef41Sopenharmony_ci                              summary.code_offset());
23751cb0ef41Sopenharmony_ci  }
23761cb0ef41Sopenharmony_ci  return true;
23771cb0ef41Sopenharmony_ci}
23781cb0ef41Sopenharmony_ci
23791cb0ef41Sopenharmony_cibool Isolate::ComputeLocationFromException(MessageLocation* target,
23801cb0ef41Sopenharmony_ci                                           Handle<Object> exception) {
23811cb0ef41Sopenharmony_ci  if (!exception->IsJSObject()) return false;
23821cb0ef41Sopenharmony_ci
23831cb0ef41Sopenharmony_ci  Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol();
23841cb0ef41Sopenharmony_ci  Handle<Object> start_pos = JSReceiver::GetDataProperty(
23851cb0ef41Sopenharmony_ci      this, Handle<JSObject>::cast(exception), start_pos_symbol);
23861cb0ef41Sopenharmony_ci  if (!start_pos->IsSmi()) return false;
23871cb0ef41Sopenharmony_ci  int start_pos_value = Handle<Smi>::cast(start_pos)->value();
23881cb0ef41Sopenharmony_ci
23891cb0ef41Sopenharmony_ci  Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol();
23901cb0ef41Sopenharmony_ci  Handle<Object> end_pos = JSReceiver::GetDataProperty(
23911cb0ef41Sopenharmony_ci      this, Handle<JSObject>::cast(exception), end_pos_symbol);
23921cb0ef41Sopenharmony_ci  if (!end_pos->IsSmi()) return false;
23931cb0ef41Sopenharmony_ci  int end_pos_value = Handle<Smi>::cast(end_pos)->value();
23941cb0ef41Sopenharmony_ci
23951cb0ef41Sopenharmony_ci  Handle<Name> script_symbol = factory()->error_script_symbol();
23961cb0ef41Sopenharmony_ci  Handle<Object> script = JSReceiver::GetDataProperty(
23971cb0ef41Sopenharmony_ci      this, Handle<JSObject>::cast(exception), script_symbol);
23981cb0ef41Sopenharmony_ci  if (!script->IsScript()) return false;
23991cb0ef41Sopenharmony_ci
24001cb0ef41Sopenharmony_ci  Handle<Script> cast_script(Script::cast(*script), this);
24011cb0ef41Sopenharmony_ci  *target = MessageLocation(cast_script, start_pos_value, end_pos_value);
24021cb0ef41Sopenharmony_ci  return true;
24031cb0ef41Sopenharmony_ci}
24041cb0ef41Sopenharmony_ci
24051cb0ef41Sopenharmony_cibool Isolate::ComputeLocationFromSimpleStackTrace(MessageLocation* target,
24061cb0ef41Sopenharmony_ci                                                  Handle<Object> exception) {
24071cb0ef41Sopenharmony_ci  if (!exception->IsJSReceiver()) {
24081cb0ef41Sopenharmony_ci    return false;
24091cb0ef41Sopenharmony_ci  }
24101cb0ef41Sopenharmony_ci  Handle<FixedArray> call_site_infos =
24111cb0ef41Sopenharmony_ci      GetSimpleStackTrace(Handle<JSReceiver>::cast(exception));
24121cb0ef41Sopenharmony_ci  for (int i = 0; i < call_site_infos->length(); ++i) {
24131cb0ef41Sopenharmony_ci    Handle<CallSiteInfo> call_site_info(
24141cb0ef41Sopenharmony_ci        CallSiteInfo::cast(call_site_infos->get(i)), this);
24151cb0ef41Sopenharmony_ci    if (CallSiteInfo::ComputeLocation(call_site_info, target)) {
24161cb0ef41Sopenharmony_ci      return true;
24171cb0ef41Sopenharmony_ci    }
24181cb0ef41Sopenharmony_ci  }
24191cb0ef41Sopenharmony_ci  return false;
24201cb0ef41Sopenharmony_ci}
24211cb0ef41Sopenharmony_ci
24221cb0ef41Sopenharmony_cibool Isolate::ComputeLocationFromDetailedStackTrace(MessageLocation* target,
24231cb0ef41Sopenharmony_ci                                                    Handle<Object> exception) {
24241cb0ef41Sopenharmony_ci  if (!exception->IsJSReceiver()) return false;
24251cb0ef41Sopenharmony_ci
24261cb0ef41Sopenharmony_ci  Handle<FixedArray> stack_frame_infos =
24271cb0ef41Sopenharmony_ci      GetDetailedStackTrace(Handle<JSReceiver>::cast(exception));
24281cb0ef41Sopenharmony_ci  if (stack_frame_infos.is_null() || stack_frame_infos->length() == 0) {
24291cb0ef41Sopenharmony_ci    return false;
24301cb0ef41Sopenharmony_ci  }
24311cb0ef41Sopenharmony_ci
24321cb0ef41Sopenharmony_ci  Handle<StackFrameInfo> info(StackFrameInfo::cast(stack_frame_infos->get(0)),
24331cb0ef41Sopenharmony_ci                              this);
24341cb0ef41Sopenharmony_ci  const int pos = StackFrameInfo::GetSourcePosition(info);
24351cb0ef41Sopenharmony_ci  *target = MessageLocation(handle(info->script(), this), pos, pos + 1);
24361cb0ef41Sopenharmony_ci  return true;
24371cb0ef41Sopenharmony_ci}
24381cb0ef41Sopenharmony_ci
24391cb0ef41Sopenharmony_ciHandle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception,
24401cb0ef41Sopenharmony_ci                                               MessageLocation* location) {
24411cb0ef41Sopenharmony_ci  Handle<FixedArray> stack_trace_object;
24421cb0ef41Sopenharmony_ci  if (capture_stack_trace_for_uncaught_exceptions_) {
24431cb0ef41Sopenharmony_ci    if (exception->IsJSError()) {
24441cb0ef41Sopenharmony_ci      // We fetch the stack trace that corresponds to this error object.
24451cb0ef41Sopenharmony_ci      // If the lookup fails, the exception is probably not a valid Error
24461cb0ef41Sopenharmony_ci      // object. In that case, we fall through and capture the stack trace
24471cb0ef41Sopenharmony_ci      // at this throw site.
24481cb0ef41Sopenharmony_ci      stack_trace_object =
24491cb0ef41Sopenharmony_ci          GetDetailedStackTrace(Handle<JSObject>::cast(exception));
24501cb0ef41Sopenharmony_ci    }
24511cb0ef41Sopenharmony_ci    if (stack_trace_object.is_null()) {
24521cb0ef41Sopenharmony_ci      // Not an error object, we capture stack and location at throw site.
24531cb0ef41Sopenharmony_ci      stack_trace_object = CaptureDetailedStackTrace(
24541cb0ef41Sopenharmony_ci          stack_trace_for_uncaught_exceptions_frame_limit_,
24551cb0ef41Sopenharmony_ci          stack_trace_for_uncaught_exceptions_options_);
24561cb0ef41Sopenharmony_ci    }
24571cb0ef41Sopenharmony_ci  }
24581cb0ef41Sopenharmony_ci  MessageLocation computed_location;
24591cb0ef41Sopenharmony_ci  if (location == nullptr &&
24601cb0ef41Sopenharmony_ci      (ComputeLocationFromException(&computed_location, exception) ||
24611cb0ef41Sopenharmony_ci       ComputeLocationFromSimpleStackTrace(&computed_location, exception) ||
24621cb0ef41Sopenharmony_ci       ComputeLocation(&computed_location))) {
24631cb0ef41Sopenharmony_ci    location = &computed_location;
24641cb0ef41Sopenharmony_ci  }
24651cb0ef41Sopenharmony_ci
24661cb0ef41Sopenharmony_ci  return MessageHandler::MakeMessageObject(
24671cb0ef41Sopenharmony_ci      this, MessageTemplate::kUncaughtException, location, exception,
24681cb0ef41Sopenharmony_ci      stack_trace_object);
24691cb0ef41Sopenharmony_ci}
24701cb0ef41Sopenharmony_ci
24711cb0ef41Sopenharmony_ciHandle<JSMessageObject> Isolate::CreateMessageFromException(
24721cb0ef41Sopenharmony_ci    Handle<Object> exception) {
24731cb0ef41Sopenharmony_ci  Handle<FixedArray> stack_trace_object;
24741cb0ef41Sopenharmony_ci  if (exception->IsJSError()) {
24751cb0ef41Sopenharmony_ci    stack_trace_object =
24761cb0ef41Sopenharmony_ci        GetDetailedStackTrace(Handle<JSObject>::cast(exception));
24771cb0ef41Sopenharmony_ci  }
24781cb0ef41Sopenharmony_ci
24791cb0ef41Sopenharmony_ci  MessageLocation* location = nullptr;
24801cb0ef41Sopenharmony_ci  MessageLocation computed_location;
24811cb0ef41Sopenharmony_ci  if (ComputeLocationFromException(&computed_location, exception) ||
24821cb0ef41Sopenharmony_ci      ComputeLocationFromDetailedStackTrace(&computed_location, exception)) {
24831cb0ef41Sopenharmony_ci    location = &computed_location;
24841cb0ef41Sopenharmony_ci  }
24851cb0ef41Sopenharmony_ci
24861cb0ef41Sopenharmony_ci  return MessageHandler::MakeMessageObject(
24871cb0ef41Sopenharmony_ci      this, MessageTemplate::kPlaceholderOnly, location, exception,
24881cb0ef41Sopenharmony_ci      stack_trace_object);
24891cb0ef41Sopenharmony_ci}
24901cb0ef41Sopenharmony_ci
24911cb0ef41Sopenharmony_ciIsolate::ExceptionHandlerType Isolate::TopExceptionHandlerType(
24921cb0ef41Sopenharmony_ci    Object exception) {
24931cb0ef41Sopenharmony_ci  DCHECK_NE(ReadOnlyRoots(heap()).the_hole_value(), exception);
24941cb0ef41Sopenharmony_ci
24951cb0ef41Sopenharmony_ci  Address js_handler = Isolate::handler(thread_local_top());
24961cb0ef41Sopenharmony_ci  Address external_handler = thread_local_top()->try_catch_handler_address();
24971cb0ef41Sopenharmony_ci
24981cb0ef41Sopenharmony_ci  // A handler cannot be on top if it doesn't exist. For uncatchable exceptions,
24991cb0ef41Sopenharmony_ci  // the JavaScript handler cannot be on top.
25001cb0ef41Sopenharmony_ci  if (js_handler == kNullAddress || !is_catchable_by_javascript(exception)) {
25011cb0ef41Sopenharmony_ci    if (external_handler == kNullAddress) {
25021cb0ef41Sopenharmony_ci      return ExceptionHandlerType::kNone;
25031cb0ef41Sopenharmony_ci    }
25041cb0ef41Sopenharmony_ci    return ExceptionHandlerType::kExternalTryCatch;
25051cb0ef41Sopenharmony_ci  }
25061cb0ef41Sopenharmony_ci
25071cb0ef41Sopenharmony_ci  if (external_handler == kNullAddress) {
25081cb0ef41Sopenharmony_ci    return ExceptionHandlerType::kJavaScriptHandler;
25091cb0ef41Sopenharmony_ci  }
25101cb0ef41Sopenharmony_ci
25111cb0ef41Sopenharmony_ci  // The exception has been externally caught if and only if there is an
25121cb0ef41Sopenharmony_ci  // external handler which is on top of the top-most JS_ENTRY handler.
25131cb0ef41Sopenharmony_ci  //
25141cb0ef41Sopenharmony_ci  // Note, that finally clauses would re-throw an exception unless it's aborted
25151cb0ef41Sopenharmony_ci  // by jumps in control flow (like return, break, etc.) and we'll have another
25161cb0ef41Sopenharmony_ci  // chance to set proper v8::TryCatch later.
25171cb0ef41Sopenharmony_ci  DCHECK_NE(kNullAddress, external_handler);
25181cb0ef41Sopenharmony_ci  DCHECK_NE(kNullAddress, js_handler);
25191cb0ef41Sopenharmony_ci  if (external_handler < js_handler) {
25201cb0ef41Sopenharmony_ci    return ExceptionHandlerType::kExternalTryCatch;
25211cb0ef41Sopenharmony_ci  }
25221cb0ef41Sopenharmony_ci  return ExceptionHandlerType::kJavaScriptHandler;
25231cb0ef41Sopenharmony_ci}
25241cb0ef41Sopenharmony_ci
25251cb0ef41Sopenharmony_cistd::vector<MemoryRange>* Isolate::GetCodePages() const {
25261cb0ef41Sopenharmony_ci  return code_pages_.load(std::memory_order_acquire);
25271cb0ef41Sopenharmony_ci}
25281cb0ef41Sopenharmony_ci
25291cb0ef41Sopenharmony_civoid Isolate::SetCodePages(std::vector<MemoryRange>* new_code_pages) {
25301cb0ef41Sopenharmony_ci  code_pages_.store(new_code_pages, std::memory_order_release);
25311cb0ef41Sopenharmony_ci}
25321cb0ef41Sopenharmony_ci
25331cb0ef41Sopenharmony_civoid Isolate::ReportPendingMessages() {
25341cb0ef41Sopenharmony_ci  DCHECK(AllowExceptions::IsAllowed(this));
25351cb0ef41Sopenharmony_ci
25361cb0ef41Sopenharmony_ci  // The embedder might run script in response to an exception.
25371cb0ef41Sopenharmony_ci  AllowJavascriptExecutionDebugOnly allow_script(this);
25381cb0ef41Sopenharmony_ci
25391cb0ef41Sopenharmony_ci  Object exception_obj = pending_exception();
25401cb0ef41Sopenharmony_ci  ExceptionHandlerType top_handler = TopExceptionHandlerType(exception_obj);
25411cb0ef41Sopenharmony_ci
25421cb0ef41Sopenharmony_ci  // Try to propagate the exception to an external v8::TryCatch handler. If
25431cb0ef41Sopenharmony_ci  // propagation was unsuccessful, then we will get another chance at reporting
25441cb0ef41Sopenharmony_ci  // the pending message if the exception is re-thrown.
25451cb0ef41Sopenharmony_ci  bool has_been_propagated =
25461cb0ef41Sopenharmony_ci      PropagatePendingExceptionToExternalTryCatch(top_handler);
25471cb0ef41Sopenharmony_ci  if (!has_been_propagated) return;
25481cb0ef41Sopenharmony_ci
25491cb0ef41Sopenharmony_ci  // Clear the pending message object early to avoid endless recursion.
25501cb0ef41Sopenharmony_ci  Object message_obj = pending_message();
25511cb0ef41Sopenharmony_ci  clear_pending_message();
25521cb0ef41Sopenharmony_ci
25531cb0ef41Sopenharmony_ci  // For uncatchable exceptions we do nothing. If needed, the exception and the
25541cb0ef41Sopenharmony_ci  // message have already been propagated to v8::TryCatch.
25551cb0ef41Sopenharmony_ci  if (!is_catchable_by_javascript(exception_obj)) return;
25561cb0ef41Sopenharmony_ci
25571cb0ef41Sopenharmony_ci  // Determine whether the message needs to be reported to all message handlers
25581cb0ef41Sopenharmony_ci  // depending on whether the topmost external v8::TryCatch is verbose. We know
25591cb0ef41Sopenharmony_ci  // there's no JavaScript handler on top; if there was, we would've returned
25601cb0ef41Sopenharmony_ci  // early.
25611cb0ef41Sopenharmony_ci  DCHECK_NE(ExceptionHandlerType::kJavaScriptHandler, top_handler);
25621cb0ef41Sopenharmony_ci
25631cb0ef41Sopenharmony_ci  bool should_report_exception;
25641cb0ef41Sopenharmony_ci  if (top_handler == ExceptionHandlerType::kExternalTryCatch) {
25651cb0ef41Sopenharmony_ci    should_report_exception = try_catch_handler()->is_verbose_;
25661cb0ef41Sopenharmony_ci  } else {
25671cb0ef41Sopenharmony_ci    should_report_exception = true;
25681cb0ef41Sopenharmony_ci  }
25691cb0ef41Sopenharmony_ci
25701cb0ef41Sopenharmony_ci  // Actually report the pending message to all message handlers.
25711cb0ef41Sopenharmony_ci  if (!message_obj.IsTheHole(this) && should_report_exception) {
25721cb0ef41Sopenharmony_ci    HandleScope scope(this);
25731cb0ef41Sopenharmony_ci    Handle<JSMessageObject> message(JSMessageObject::cast(message_obj), this);
25741cb0ef41Sopenharmony_ci    Handle<Object> exception(exception_obj, this);
25751cb0ef41Sopenharmony_ci    Handle<Script> script(message->script(), this);
25761cb0ef41Sopenharmony_ci    // Clear the exception and restore it afterwards, otherwise
25771cb0ef41Sopenharmony_ci    // CollectSourcePositions will abort.
25781cb0ef41Sopenharmony_ci    clear_pending_exception();
25791cb0ef41Sopenharmony_ci    JSMessageObject::EnsureSourcePositionsAvailable(this, message);
25801cb0ef41Sopenharmony_ci    set_pending_exception(*exception);
25811cb0ef41Sopenharmony_ci    int start_pos = message->GetStartPosition();
25821cb0ef41Sopenharmony_ci    int end_pos = message->GetEndPosition();
25831cb0ef41Sopenharmony_ci    MessageLocation location(script, start_pos, end_pos);
25841cb0ef41Sopenharmony_ci    MessageHandler::ReportMessage(this, &location, message);
25851cb0ef41Sopenharmony_ci  }
25861cb0ef41Sopenharmony_ci}
25871cb0ef41Sopenharmony_ci
25881cb0ef41Sopenharmony_cibool Isolate::OptionalRescheduleException(bool clear_exception) {
25891cb0ef41Sopenharmony_ci  DCHECK(has_pending_exception());
25901cb0ef41Sopenharmony_ci  PropagatePendingExceptionToExternalTryCatch(
25911cb0ef41Sopenharmony_ci      TopExceptionHandlerType(pending_exception()));
25921cb0ef41Sopenharmony_ci
25931cb0ef41Sopenharmony_ci  bool is_termination_exception =
25941cb0ef41Sopenharmony_ci      pending_exception() == ReadOnlyRoots(this).termination_exception();
25951cb0ef41Sopenharmony_ci
25961cb0ef41Sopenharmony_ci  if (is_termination_exception) {
25971cb0ef41Sopenharmony_ci    if (clear_exception) {
25981cb0ef41Sopenharmony_ci      thread_local_top()->external_caught_exception_ = false;
25991cb0ef41Sopenharmony_ci      clear_pending_exception();
26001cb0ef41Sopenharmony_ci      return false;
26011cb0ef41Sopenharmony_ci    }
26021cb0ef41Sopenharmony_ci  } else if (thread_local_top()->external_caught_exception_) {
26031cb0ef41Sopenharmony_ci    // If the exception is externally caught, clear it if there are no
26041cb0ef41Sopenharmony_ci    // JavaScript frames on the way to the C++ frame that has the
26051cb0ef41Sopenharmony_ci    // external handler.
26061cb0ef41Sopenharmony_ci    DCHECK_NE(thread_local_top()->try_catch_handler_address(), kNullAddress);
26071cb0ef41Sopenharmony_ci    Address external_handler_address =
26081cb0ef41Sopenharmony_ci        thread_local_top()->try_catch_handler_address();
26091cb0ef41Sopenharmony_ci    JavaScriptFrameIterator it(this);
26101cb0ef41Sopenharmony_ci    if (it.done() || (it.frame()->sp() > external_handler_address)) {
26111cb0ef41Sopenharmony_ci      clear_exception = true;
26121cb0ef41Sopenharmony_ci    }
26131cb0ef41Sopenharmony_ci  }
26141cb0ef41Sopenharmony_ci
26151cb0ef41Sopenharmony_ci  // Clear the exception if needed.
26161cb0ef41Sopenharmony_ci  if (clear_exception) {
26171cb0ef41Sopenharmony_ci    thread_local_top()->external_caught_exception_ = false;
26181cb0ef41Sopenharmony_ci    clear_pending_exception();
26191cb0ef41Sopenharmony_ci    return false;
26201cb0ef41Sopenharmony_ci  }
26211cb0ef41Sopenharmony_ci
26221cb0ef41Sopenharmony_ci  // Reschedule the exception.
26231cb0ef41Sopenharmony_ci  set_scheduled_exception(pending_exception());
26241cb0ef41Sopenharmony_ci  clear_pending_exception();
26251cb0ef41Sopenharmony_ci  return true;
26261cb0ef41Sopenharmony_ci}
26271cb0ef41Sopenharmony_ci
26281cb0ef41Sopenharmony_civoid Isolate::PushPromise(Handle<JSObject> promise) {
26291cb0ef41Sopenharmony_ci  Handle<Object> promise_on_stack(debug()->thread_local_.promise_stack_, this);
26301cb0ef41Sopenharmony_ci  promise_on_stack = factory()->NewPromiseOnStack(promise_on_stack, promise);
26311cb0ef41Sopenharmony_ci  debug()->thread_local_.promise_stack_ = *promise_on_stack;
26321cb0ef41Sopenharmony_ci}
26331cb0ef41Sopenharmony_ci
26341cb0ef41Sopenharmony_civoid Isolate::PopPromise() {
26351cb0ef41Sopenharmony_ci  if (!IsPromiseStackEmpty()) {
26361cb0ef41Sopenharmony_ci    debug()->thread_local_.promise_stack_ =
26371cb0ef41Sopenharmony_ci        PromiseOnStack::cast(debug()->thread_local_.promise_stack_).prev();
26381cb0ef41Sopenharmony_ci  }
26391cb0ef41Sopenharmony_ci}
26401cb0ef41Sopenharmony_ci
26411cb0ef41Sopenharmony_cibool Isolate::IsPromiseStackEmpty() const {
26421cb0ef41Sopenharmony_ci  DCHECK_IMPLIES(!debug()->thread_local_.promise_stack_.IsSmi(),
26431cb0ef41Sopenharmony_ci                 debug()->thread_local_.promise_stack_.IsPromiseOnStack());
26441cb0ef41Sopenharmony_ci  return debug()->thread_local_.promise_stack_.IsSmi();
26451cb0ef41Sopenharmony_ci}
26461cb0ef41Sopenharmony_ci
26471cb0ef41Sopenharmony_cinamespace {
26481cb0ef41Sopenharmony_cibool PromiseIsRejectHandler(Isolate* isolate, Handle<JSReceiver> handler) {
26491cb0ef41Sopenharmony_ci  // Recurse to the forwarding Promise (e.g. return false) due to
26501cb0ef41Sopenharmony_ci  //  - await reaction forwarding to the throwaway Promise, which has
26511cb0ef41Sopenharmony_ci  //    a dependency edge to the outer Promise.
26521cb0ef41Sopenharmony_ci  //  - PromiseIdResolveHandler forwarding to the output of .then
26531cb0ef41Sopenharmony_ci  //  - Promise.all/Promise.race forwarding to a throwaway Promise, which
26541cb0ef41Sopenharmony_ci  //    has a dependency edge to the generated outer Promise.
26551cb0ef41Sopenharmony_ci  // Otherwise, this is a real reject handler for the Promise.
26561cb0ef41Sopenharmony_ci  Handle<Symbol> key = isolate->factory()->promise_forwarding_handler_symbol();
26571cb0ef41Sopenharmony_ci  Handle<Object> forwarding_handler =
26581cb0ef41Sopenharmony_ci      JSReceiver::GetDataProperty(isolate, handler, key);
26591cb0ef41Sopenharmony_ci  return forwarding_handler->IsUndefined(isolate);
26601cb0ef41Sopenharmony_ci}
26611cb0ef41Sopenharmony_ci
26621cb0ef41Sopenharmony_cibool PromiseHasUserDefinedRejectHandlerInternal(Isolate* isolate,
26631cb0ef41Sopenharmony_ci                                                Handle<JSPromise> promise) {
26641cb0ef41Sopenharmony_ci  Handle<Object> current(promise->reactions(), isolate);
26651cb0ef41Sopenharmony_ci  while (!current->IsSmi()) {
26661cb0ef41Sopenharmony_ci    Handle<PromiseReaction> reaction = Handle<PromiseReaction>::cast(current);
26671cb0ef41Sopenharmony_ci    Handle<HeapObject> promise_or_capability(reaction->promise_or_capability(),
26681cb0ef41Sopenharmony_ci                                             isolate);
26691cb0ef41Sopenharmony_ci    if (!promise_or_capability->IsUndefined(isolate)) {
26701cb0ef41Sopenharmony_ci      if (!promise_or_capability->IsJSPromise()) {
26711cb0ef41Sopenharmony_ci        promise_or_capability = handle(
26721cb0ef41Sopenharmony_ci            Handle<PromiseCapability>::cast(promise_or_capability)->promise(),
26731cb0ef41Sopenharmony_ci            isolate);
26741cb0ef41Sopenharmony_ci      }
26751cb0ef41Sopenharmony_ci      promise = Handle<JSPromise>::cast(promise_or_capability);
26761cb0ef41Sopenharmony_ci      if (!reaction->reject_handler().IsUndefined(isolate)) {
26771cb0ef41Sopenharmony_ci        Handle<JSReceiver> reject_handler(
26781cb0ef41Sopenharmony_ci            JSReceiver::cast(reaction->reject_handler()), isolate);
26791cb0ef41Sopenharmony_ci        if (PromiseIsRejectHandler(isolate, reject_handler)) return true;
26801cb0ef41Sopenharmony_ci      }
26811cb0ef41Sopenharmony_ci      if (isolate->PromiseHasUserDefinedRejectHandler(promise)) return true;
26821cb0ef41Sopenharmony_ci    }
26831cb0ef41Sopenharmony_ci    current = handle(reaction->next(), isolate);
26841cb0ef41Sopenharmony_ci  }
26851cb0ef41Sopenharmony_ci  return false;
26861cb0ef41Sopenharmony_ci}
26871cb0ef41Sopenharmony_ci
26881cb0ef41Sopenharmony_ci}  // namespace
26891cb0ef41Sopenharmony_ci
26901cb0ef41Sopenharmony_cibool Isolate::PromiseHasUserDefinedRejectHandler(Handle<JSPromise> promise) {
26911cb0ef41Sopenharmony_ci  Handle<Symbol> key = factory()->promise_handled_by_symbol();
26921cb0ef41Sopenharmony_ci  std::stack<Handle<JSPromise>> promises;
26931cb0ef41Sopenharmony_ci  // First descend into the outermost promise and collect the stack of
26941cb0ef41Sopenharmony_ci  // Promises for reverse processing.
26951cb0ef41Sopenharmony_ci  while (true) {
26961cb0ef41Sopenharmony_ci    // If this promise was marked as being handled by a catch block
26971cb0ef41Sopenharmony_ci    // in an async function, then it has a user-defined reject handler.
26981cb0ef41Sopenharmony_ci    if (promise->handled_hint()) return true;
26991cb0ef41Sopenharmony_ci    if (promise->status() == Promise::kPending) {
27001cb0ef41Sopenharmony_ci      promises.push(promise);
27011cb0ef41Sopenharmony_ci    }
27021cb0ef41Sopenharmony_ci    Handle<Object> outer_promise_obj =
27031cb0ef41Sopenharmony_ci        JSObject::GetDataProperty(this, promise, key);
27041cb0ef41Sopenharmony_ci    if (!outer_promise_obj->IsJSPromise()) break;
27051cb0ef41Sopenharmony_ci    promise = Handle<JSPromise>::cast(outer_promise_obj);
27061cb0ef41Sopenharmony_ci  }
27071cb0ef41Sopenharmony_ci
27081cb0ef41Sopenharmony_ci  while (!promises.empty()) {
27091cb0ef41Sopenharmony_ci    promise = promises.top();
27101cb0ef41Sopenharmony_ci    if (PromiseHasUserDefinedRejectHandlerInternal(this, promise)) return true;
27111cb0ef41Sopenharmony_ci    promises.pop();
27121cb0ef41Sopenharmony_ci  }
27131cb0ef41Sopenharmony_ci  return false;
27141cb0ef41Sopenharmony_ci}
27151cb0ef41Sopenharmony_ci
27161cb0ef41Sopenharmony_ciHandle<Object> Isolate::GetPromiseOnStackOnThrow() {
27171cb0ef41Sopenharmony_ci  Handle<Object> undefined = factory()->undefined_value();
27181cb0ef41Sopenharmony_ci  if (IsPromiseStackEmpty()) return undefined;
27191cb0ef41Sopenharmony_ci  // Find the top-most try-catch or try-finally handler.
27201cb0ef41Sopenharmony_ci  CatchType prediction = PredictExceptionCatcher();
27211cb0ef41Sopenharmony_ci  if (prediction == NOT_CAUGHT || prediction == CAUGHT_BY_EXTERNAL) {
27221cb0ef41Sopenharmony_ci    return undefined;
27231cb0ef41Sopenharmony_ci  }
27241cb0ef41Sopenharmony_ci  Handle<Object> retval = undefined;
27251cb0ef41Sopenharmony_ci  Handle<Object> promise_stack(debug()->thread_local_.promise_stack_, this);
27261cb0ef41Sopenharmony_ci  for (StackFrameIterator it(this); !it.done(); it.Advance()) {
27271cb0ef41Sopenharmony_ci    StackFrame* frame = it.frame();
27281cb0ef41Sopenharmony_ci    HandlerTable::CatchPrediction catch_prediction;
27291cb0ef41Sopenharmony_ci    if (frame->is_java_script()) {
27301cb0ef41Sopenharmony_ci      catch_prediction = PredictException(JavaScriptFrame::cast(frame));
27311cb0ef41Sopenharmony_ci    } else if (frame->type() == StackFrame::STUB) {
27321cb0ef41Sopenharmony_ci      Code code = frame->LookupCode();
27331cb0ef41Sopenharmony_ci      if (!code.IsCode() || code.kind() != CodeKind::BUILTIN ||
27341cb0ef41Sopenharmony_ci          !code.has_handler_table() || !code.is_turbofanned()) {
27351cb0ef41Sopenharmony_ci        continue;
27361cb0ef41Sopenharmony_ci      }
27371cb0ef41Sopenharmony_ci      catch_prediction = code.GetBuiltinCatchPrediction();
27381cb0ef41Sopenharmony_ci    } else {
27391cb0ef41Sopenharmony_ci      continue;
27401cb0ef41Sopenharmony_ci    }
27411cb0ef41Sopenharmony_ci
27421cb0ef41Sopenharmony_ci    switch (catch_prediction) {
27431cb0ef41Sopenharmony_ci      case HandlerTable::UNCAUGHT:
27441cb0ef41Sopenharmony_ci        continue;
27451cb0ef41Sopenharmony_ci      case HandlerTable::CAUGHT:
27461cb0ef41Sopenharmony_ci        if (retval->IsJSPromise()) {
27471cb0ef41Sopenharmony_ci          // Caught the result of an inner async/await invocation.
27481cb0ef41Sopenharmony_ci          // Mark the inner promise as caught in the "synchronous case" so
27491cb0ef41Sopenharmony_ci          // that Debug::OnException will see. In the synchronous case,
27501cb0ef41Sopenharmony_ci          // namely in the code in an async function before the first
27511cb0ef41Sopenharmony_ci          // await, the function which has this exception event has not yet
27521cb0ef41Sopenharmony_ci          // returned, so the generated Promise has not yet been marked
27531cb0ef41Sopenharmony_ci          // by AsyncFunctionAwaitCaught with promiseHandledHintSymbol.
27541cb0ef41Sopenharmony_ci          Handle<JSPromise>::cast(retval)->set_handled_hint(true);
27551cb0ef41Sopenharmony_ci        }
27561cb0ef41Sopenharmony_ci        return retval;
27571cb0ef41Sopenharmony_ci      case HandlerTable::PROMISE: {
27581cb0ef41Sopenharmony_ci        Handle<JSObject> promise;
27591cb0ef41Sopenharmony_ci        if (promise_stack->IsPromiseOnStack() &&
27601cb0ef41Sopenharmony_ci            PromiseOnStack::GetPromise(
27611cb0ef41Sopenharmony_ci                Handle<PromiseOnStack>::cast(promise_stack))
27621cb0ef41Sopenharmony_ci                .ToHandle(&promise)) {
27631cb0ef41Sopenharmony_ci          return promise;
27641cb0ef41Sopenharmony_ci        }
27651cb0ef41Sopenharmony_ci        return undefined;
27661cb0ef41Sopenharmony_ci      }
27671cb0ef41Sopenharmony_ci      case HandlerTable::UNCAUGHT_ASYNC_AWAIT:
27681cb0ef41Sopenharmony_ci      case HandlerTable::ASYNC_AWAIT: {
27691cb0ef41Sopenharmony_ci        // If in the initial portion of async/await, continue the loop to pop up
27701cb0ef41Sopenharmony_ci        // successive async/await stack frames until an asynchronous one with
27711cb0ef41Sopenharmony_ci        // dependents is found, or a non-async stack frame is encountered, in
27721cb0ef41Sopenharmony_ci        // order to handle the synchronous async/await catch prediction case:
27731cb0ef41Sopenharmony_ci        // assume that async function calls are awaited.
27741cb0ef41Sopenharmony_ci        if (!promise_stack->IsPromiseOnStack()) {
27751cb0ef41Sopenharmony_ci          return retval;
27761cb0ef41Sopenharmony_ci        }
27771cb0ef41Sopenharmony_ci        Handle<PromiseOnStack> promise_on_stack =
27781cb0ef41Sopenharmony_ci            Handle<PromiseOnStack>::cast(promise_stack);
27791cb0ef41Sopenharmony_ci        if (!PromiseOnStack::GetPromise(promise_on_stack).ToHandle(&retval)) {
27801cb0ef41Sopenharmony_ci          return retval;
27811cb0ef41Sopenharmony_ci        }
27821cb0ef41Sopenharmony_ci        if (retval->IsJSPromise()) {
27831cb0ef41Sopenharmony_ci          if (PromiseHasUserDefinedRejectHandler(
27841cb0ef41Sopenharmony_ci                  Handle<JSPromise>::cast(retval))) {
27851cb0ef41Sopenharmony_ci            return retval;
27861cb0ef41Sopenharmony_ci          }
27871cb0ef41Sopenharmony_ci        }
27881cb0ef41Sopenharmony_ci        promise_stack = handle(promise_on_stack->prev(), this);
27891cb0ef41Sopenharmony_ci        continue;
27901cb0ef41Sopenharmony_ci      }
27911cb0ef41Sopenharmony_ci    }
27921cb0ef41Sopenharmony_ci  }
27931cb0ef41Sopenharmony_ci  return retval;
27941cb0ef41Sopenharmony_ci}
27951cb0ef41Sopenharmony_ci
27961cb0ef41Sopenharmony_civoid Isolate::SetCaptureStackTraceForUncaughtExceptions(
27971cb0ef41Sopenharmony_ci    bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
27981cb0ef41Sopenharmony_ci  capture_stack_trace_for_uncaught_exceptions_ = capture;
27991cb0ef41Sopenharmony_ci  stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit;
28001cb0ef41Sopenharmony_ci  stack_trace_for_uncaught_exceptions_options_ = options;
28011cb0ef41Sopenharmony_ci}
28021cb0ef41Sopenharmony_ci
28031cb0ef41Sopenharmony_cibool Isolate::get_capture_stack_trace_for_uncaught_exceptions() const {
28041cb0ef41Sopenharmony_ci  return capture_stack_trace_for_uncaught_exceptions_;
28051cb0ef41Sopenharmony_ci}
28061cb0ef41Sopenharmony_ci
28071cb0ef41Sopenharmony_civoid Isolate::SetAbortOnUncaughtExceptionCallback(
28081cb0ef41Sopenharmony_ci    v8::Isolate::AbortOnUncaughtExceptionCallback callback) {
28091cb0ef41Sopenharmony_ci  abort_on_uncaught_exception_callback_ = callback;
28101cb0ef41Sopenharmony_ci}
28111cb0ef41Sopenharmony_ci
28121cb0ef41Sopenharmony_civoid Isolate::InstallConditionalFeatures(Handle<Context> context) {
28131cb0ef41Sopenharmony_ci  Handle<JSGlobalObject> global = handle(context->global_object(), this);
28141cb0ef41Sopenharmony_ci  Handle<String> sab_name = factory()->SharedArrayBuffer_string();
28151cb0ef41Sopenharmony_ci  if (IsSharedArrayBufferConstructorEnabled(context)) {
28161cb0ef41Sopenharmony_ci    if (!JSObject::HasRealNamedProperty(this, global, sab_name)
28171cb0ef41Sopenharmony_ci             .FromMaybe(true)) {
28181cb0ef41Sopenharmony_ci      JSObject::AddProperty(this, global, factory()->SharedArrayBuffer_string(),
28191cb0ef41Sopenharmony_ci                            shared_array_buffer_fun(), DONT_ENUM);
28201cb0ef41Sopenharmony_ci    }
28211cb0ef41Sopenharmony_ci  }
28221cb0ef41Sopenharmony_ci}
28231cb0ef41Sopenharmony_ci
28241cb0ef41Sopenharmony_cibool Isolate::IsSharedArrayBufferConstructorEnabled(Handle<Context> context) {
28251cb0ef41Sopenharmony_ci  if (!FLAG_harmony_sharedarraybuffer) return false;
28261cb0ef41Sopenharmony_ci
28271cb0ef41Sopenharmony_ci  if (!FLAG_enable_sharedarraybuffer_per_context) return true;
28281cb0ef41Sopenharmony_ci
28291cb0ef41Sopenharmony_ci  if (sharedarraybuffer_constructor_enabled_callback()) {
28301cb0ef41Sopenharmony_ci    v8::Local<v8::Context> api_context = v8::Utils::ToLocal(context);
28311cb0ef41Sopenharmony_ci    return sharedarraybuffer_constructor_enabled_callback()(api_context);
28321cb0ef41Sopenharmony_ci  }
28331cb0ef41Sopenharmony_ci  return false;
28341cb0ef41Sopenharmony_ci}
28351cb0ef41Sopenharmony_ci
28361cb0ef41Sopenharmony_cibool Isolate::IsWasmSimdEnabled(Handle<Context> context) {
28371cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
28381cb0ef41Sopenharmony_ci  if (wasm_simd_enabled_callback()) {
28391cb0ef41Sopenharmony_ci    v8::Local<v8::Context> api_context = v8::Utils::ToLocal(context);
28401cb0ef41Sopenharmony_ci    return wasm_simd_enabled_callback()(api_context);
28411cb0ef41Sopenharmony_ci  }
28421cb0ef41Sopenharmony_ci  return FLAG_experimental_wasm_simd;
28431cb0ef41Sopenharmony_ci#else
28441cb0ef41Sopenharmony_ci  return false;
28451cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
28461cb0ef41Sopenharmony_ci}
28471cb0ef41Sopenharmony_ci
28481cb0ef41Sopenharmony_cibool Isolate::AreWasmExceptionsEnabled(Handle<Context> context) {
28491cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
28501cb0ef41Sopenharmony_ci  if (wasm_exceptions_enabled_callback()) {
28511cb0ef41Sopenharmony_ci    v8::Local<v8::Context> api_context = v8::Utils::ToLocal(context);
28521cb0ef41Sopenharmony_ci    return wasm_exceptions_enabled_callback()(api_context);
28531cb0ef41Sopenharmony_ci  }
28541cb0ef41Sopenharmony_ci  return FLAG_experimental_wasm_eh;
28551cb0ef41Sopenharmony_ci#else
28561cb0ef41Sopenharmony_ci  return false;
28571cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
28581cb0ef41Sopenharmony_ci}
28591cb0ef41Sopenharmony_ci
28601cb0ef41Sopenharmony_cibool Isolate::IsWasmDynamicTieringEnabled() {
28611cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
28621cb0ef41Sopenharmony_ci  if (FLAG_wasm_dynamic_tiering) return true;
28631cb0ef41Sopenharmony_ci  if (wasm_dynamic_tiering_enabled_callback()) {
28641cb0ef41Sopenharmony_ci    HandleScope handle_scope(this);
28651cb0ef41Sopenharmony_ci    v8::Local<v8::Context> api_context =
28661cb0ef41Sopenharmony_ci        v8::Utils::ToLocal(handle(context(), this));
28671cb0ef41Sopenharmony_ci    return wasm_dynamic_tiering_enabled_callback()(api_context);
28681cb0ef41Sopenharmony_ci  }
28691cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
28701cb0ef41Sopenharmony_ci  return false;
28711cb0ef41Sopenharmony_ci}
28721cb0ef41Sopenharmony_ci
28731cb0ef41Sopenharmony_ciHandle<Context> Isolate::GetIncumbentContext() {
28741cb0ef41Sopenharmony_ci  JavaScriptFrameIterator it(this);
28751cb0ef41Sopenharmony_ci
28761cb0ef41Sopenharmony_ci  // 1st candidate: most-recently-entered author function's context
28771cb0ef41Sopenharmony_ci  // if it's newer than the last Context::BackupIncumbentScope entry.
28781cb0ef41Sopenharmony_ci  //
28791cb0ef41Sopenharmony_ci  // NOTE: This code assumes that the stack grows downward.
28801cb0ef41Sopenharmony_ci  Address top_backup_incumbent =
28811cb0ef41Sopenharmony_ci      top_backup_incumbent_scope()
28821cb0ef41Sopenharmony_ci          ? top_backup_incumbent_scope()->JSStackComparableAddressPrivate()
28831cb0ef41Sopenharmony_ci          : 0;
28841cb0ef41Sopenharmony_ci  if (!it.done() &&
28851cb0ef41Sopenharmony_ci      (!top_backup_incumbent || it.frame()->sp() < top_backup_incumbent)) {
28861cb0ef41Sopenharmony_ci    Context context = Context::cast(it.frame()->context());
28871cb0ef41Sopenharmony_ci    return Handle<Context>(context.native_context(), this);
28881cb0ef41Sopenharmony_ci  }
28891cb0ef41Sopenharmony_ci
28901cb0ef41Sopenharmony_ci  // 2nd candidate: the last Context::Scope's incumbent context if any.
28911cb0ef41Sopenharmony_ci  if (top_backup_incumbent_scope()) {
28921cb0ef41Sopenharmony_ci    return Utils::OpenHandle(
28931cb0ef41Sopenharmony_ci        *top_backup_incumbent_scope()->backup_incumbent_context_);
28941cb0ef41Sopenharmony_ci  }
28951cb0ef41Sopenharmony_ci
28961cb0ef41Sopenharmony_ci  // Last candidate: the entered context or microtask context.
28971cb0ef41Sopenharmony_ci  // Given that there is no other author function is running, there must be
28981cb0ef41Sopenharmony_ci  // no cross-context function running, then the incumbent realm must match
28991cb0ef41Sopenharmony_ci  // the entry realm.
29001cb0ef41Sopenharmony_ci  v8::Local<v8::Context> entered_context =
29011cb0ef41Sopenharmony_ci      reinterpret_cast<v8::Isolate*>(this)->GetEnteredOrMicrotaskContext();
29021cb0ef41Sopenharmony_ci  return Utils::OpenHandle(*entered_context);
29031cb0ef41Sopenharmony_ci}
29041cb0ef41Sopenharmony_ci
29051cb0ef41Sopenharmony_cichar* Isolate::ArchiveThread(char* to) {
29061cb0ef41Sopenharmony_ci  MemCopy(to, reinterpret_cast<char*>(thread_local_top()),
29071cb0ef41Sopenharmony_ci          sizeof(ThreadLocalTop));
29081cb0ef41Sopenharmony_ci  return to + sizeof(ThreadLocalTop);
29091cb0ef41Sopenharmony_ci}
29101cb0ef41Sopenharmony_ci
29111cb0ef41Sopenharmony_cichar* Isolate::RestoreThread(char* from) {
29121cb0ef41Sopenharmony_ci  MemCopy(reinterpret_cast<char*>(thread_local_top()), from,
29131cb0ef41Sopenharmony_ci          sizeof(ThreadLocalTop));
29141cb0ef41Sopenharmony_ci  DCHECK(context().is_null() || context().IsContext());
29151cb0ef41Sopenharmony_ci  return from + sizeof(ThreadLocalTop);
29161cb0ef41Sopenharmony_ci}
29171cb0ef41Sopenharmony_ci
29181cb0ef41Sopenharmony_civoid Isolate::ReleaseSharedPtrs() {
29191cb0ef41Sopenharmony_ci  base::MutexGuard lock(&managed_ptr_destructors_mutex_);
29201cb0ef41Sopenharmony_ci  while (managed_ptr_destructors_head_) {
29211cb0ef41Sopenharmony_ci    ManagedPtrDestructor* l = managed_ptr_destructors_head_;
29221cb0ef41Sopenharmony_ci    ManagedPtrDestructor* n = nullptr;
29231cb0ef41Sopenharmony_ci    managed_ptr_destructors_head_ = nullptr;
29241cb0ef41Sopenharmony_ci    for (; l != nullptr; l = n) {
29251cb0ef41Sopenharmony_ci      l->destructor_(l->shared_ptr_ptr_);
29261cb0ef41Sopenharmony_ci      n = l->next_;
29271cb0ef41Sopenharmony_ci      delete l;
29281cb0ef41Sopenharmony_ci    }
29291cb0ef41Sopenharmony_ci  }
29301cb0ef41Sopenharmony_ci}
29311cb0ef41Sopenharmony_ci
29321cb0ef41Sopenharmony_cibool Isolate::IsBuiltinTableHandleLocation(Address* handle_location) {
29331cb0ef41Sopenharmony_ci  FullObjectSlot location(handle_location);
29341cb0ef41Sopenharmony_ci  FullObjectSlot first_root(builtin_table());
29351cb0ef41Sopenharmony_ci  FullObjectSlot last_root(first_root + Builtins::kBuiltinCount);
29361cb0ef41Sopenharmony_ci  if (location >= last_root) return false;
29371cb0ef41Sopenharmony_ci  if (location < first_root) return false;
29381cb0ef41Sopenharmony_ci  return true;
29391cb0ef41Sopenharmony_ci}
29401cb0ef41Sopenharmony_ci
29411cb0ef41Sopenharmony_civoid Isolate::RegisterManagedPtrDestructor(ManagedPtrDestructor* destructor) {
29421cb0ef41Sopenharmony_ci  base::MutexGuard lock(&managed_ptr_destructors_mutex_);
29431cb0ef41Sopenharmony_ci  DCHECK_NULL(destructor->prev_);
29441cb0ef41Sopenharmony_ci  DCHECK_NULL(destructor->next_);
29451cb0ef41Sopenharmony_ci  if (managed_ptr_destructors_head_) {
29461cb0ef41Sopenharmony_ci    managed_ptr_destructors_head_->prev_ = destructor;
29471cb0ef41Sopenharmony_ci  }
29481cb0ef41Sopenharmony_ci  destructor->next_ = managed_ptr_destructors_head_;
29491cb0ef41Sopenharmony_ci  managed_ptr_destructors_head_ = destructor;
29501cb0ef41Sopenharmony_ci}
29511cb0ef41Sopenharmony_ci
29521cb0ef41Sopenharmony_civoid Isolate::UnregisterManagedPtrDestructor(ManagedPtrDestructor* destructor) {
29531cb0ef41Sopenharmony_ci  base::MutexGuard lock(&managed_ptr_destructors_mutex_);
29541cb0ef41Sopenharmony_ci  if (destructor->prev_) {
29551cb0ef41Sopenharmony_ci    destructor->prev_->next_ = destructor->next_;
29561cb0ef41Sopenharmony_ci  } else {
29571cb0ef41Sopenharmony_ci    DCHECK_EQ(destructor, managed_ptr_destructors_head_);
29581cb0ef41Sopenharmony_ci    managed_ptr_destructors_head_ = destructor->next_;
29591cb0ef41Sopenharmony_ci  }
29601cb0ef41Sopenharmony_ci  if (destructor->next_) destructor->next_->prev_ = destructor->prev_;
29611cb0ef41Sopenharmony_ci  destructor->prev_ = nullptr;
29621cb0ef41Sopenharmony_ci  destructor->next_ = nullptr;
29631cb0ef41Sopenharmony_ci}
29641cb0ef41Sopenharmony_ci
29651cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
29661cb0ef41Sopenharmony_civoid Isolate::AddSharedWasmMemory(Handle<WasmMemoryObject> memory_object) {
29671cb0ef41Sopenharmony_ci  HandleScope scope(this);
29681cb0ef41Sopenharmony_ci  Handle<WeakArrayList> shared_wasm_memories =
29691cb0ef41Sopenharmony_ci      factory()->shared_wasm_memories();
29701cb0ef41Sopenharmony_ci  shared_wasm_memories = WeakArrayList::AddToEnd(
29711cb0ef41Sopenharmony_ci      this, shared_wasm_memories, MaybeObjectHandle::Weak(memory_object));
29721cb0ef41Sopenharmony_ci  heap()->set_shared_wasm_memories(*shared_wasm_memories);
29731cb0ef41Sopenharmony_ci}
29741cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
29751cb0ef41Sopenharmony_ci
29761cb0ef41Sopenharmony_ciIsolate::PerIsolateThreadData::~PerIsolateThreadData() {
29771cb0ef41Sopenharmony_ci#if defined(USE_SIMULATOR)
29781cb0ef41Sopenharmony_ci  delete simulator_;
29791cb0ef41Sopenharmony_ci#endif
29801cb0ef41Sopenharmony_ci}
29811cb0ef41Sopenharmony_ci
29821cb0ef41Sopenharmony_ciIsolate::PerIsolateThreadData* Isolate::ThreadDataTable::Lookup(
29831cb0ef41Sopenharmony_ci    ThreadId thread_id) {
29841cb0ef41Sopenharmony_ci  auto t = table_.find(thread_id);
29851cb0ef41Sopenharmony_ci  if (t == table_.end()) return nullptr;
29861cb0ef41Sopenharmony_ci  return t->second;
29871cb0ef41Sopenharmony_ci}
29881cb0ef41Sopenharmony_ci
29891cb0ef41Sopenharmony_civoid Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) {
29901cb0ef41Sopenharmony_ci  bool inserted = table_.insert(std::make_pair(data->thread_id_, data)).second;
29911cb0ef41Sopenharmony_ci  CHECK(inserted);
29921cb0ef41Sopenharmony_ci}
29931cb0ef41Sopenharmony_ci
29941cb0ef41Sopenharmony_civoid Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) {
29951cb0ef41Sopenharmony_ci  table_.erase(data->thread_id_);
29961cb0ef41Sopenharmony_ci  delete data;
29971cb0ef41Sopenharmony_ci}
29981cb0ef41Sopenharmony_ci
29991cb0ef41Sopenharmony_civoid Isolate::ThreadDataTable::RemoveAllThreads() {
30001cb0ef41Sopenharmony_ci  for (auto& x : table_) {
30011cb0ef41Sopenharmony_ci    delete x.second;
30021cb0ef41Sopenharmony_ci  }
30031cb0ef41Sopenharmony_ci  table_.clear();
30041cb0ef41Sopenharmony_ci}
30051cb0ef41Sopenharmony_ci
30061cb0ef41Sopenharmony_ciclass TracingAccountingAllocator : public AccountingAllocator {
30071cb0ef41Sopenharmony_ci public:
30081cb0ef41Sopenharmony_ci  explicit TracingAccountingAllocator(Isolate* isolate) : isolate_(isolate) {}
30091cb0ef41Sopenharmony_ci  ~TracingAccountingAllocator() = default;
30101cb0ef41Sopenharmony_ci
30111cb0ef41Sopenharmony_ci protected:
30121cb0ef41Sopenharmony_ci  void TraceAllocateSegmentImpl(v8::internal::Segment* segment) override {
30131cb0ef41Sopenharmony_ci    base::MutexGuard lock(&mutex_);
30141cb0ef41Sopenharmony_ci    UpdateMemoryTrafficAndReportMemoryUsage(segment->total_size());
30151cb0ef41Sopenharmony_ci  }
30161cb0ef41Sopenharmony_ci
30171cb0ef41Sopenharmony_ci  void TraceZoneCreationImpl(const Zone* zone) override {
30181cb0ef41Sopenharmony_ci    base::MutexGuard lock(&mutex_);
30191cb0ef41Sopenharmony_ci    active_zones_.insert(zone);
30201cb0ef41Sopenharmony_ci    nesting_depth_++;
30211cb0ef41Sopenharmony_ci  }
30221cb0ef41Sopenharmony_ci
30231cb0ef41Sopenharmony_ci  void TraceZoneDestructionImpl(const Zone* zone) override {
30241cb0ef41Sopenharmony_ci    base::MutexGuard lock(&mutex_);
30251cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_PRECISE_ZONE_STATS
30261cb0ef41Sopenharmony_ci    if (FLAG_trace_zone_type_stats) {
30271cb0ef41Sopenharmony_ci      type_stats_.MergeWith(zone->type_stats());
30281cb0ef41Sopenharmony_ci    }
30291cb0ef41Sopenharmony_ci#endif
30301cb0ef41Sopenharmony_ci    UpdateMemoryTrafficAndReportMemoryUsage(zone->segment_bytes_allocated());
30311cb0ef41Sopenharmony_ci    active_zones_.erase(zone);
30321cb0ef41Sopenharmony_ci    nesting_depth_--;
30331cb0ef41Sopenharmony_ci
30341cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_PRECISE_ZONE_STATS
30351cb0ef41Sopenharmony_ci    if (FLAG_trace_zone_type_stats && active_zones_.empty()) {
30361cb0ef41Sopenharmony_ci      type_stats_.Dump();
30371cb0ef41Sopenharmony_ci    }
30381cb0ef41Sopenharmony_ci#endif
30391cb0ef41Sopenharmony_ci  }
30401cb0ef41Sopenharmony_ci
30411cb0ef41Sopenharmony_ci private:
30421cb0ef41Sopenharmony_ci  void UpdateMemoryTrafficAndReportMemoryUsage(size_t memory_traffic_delta) {
30431cb0ef41Sopenharmony_ci    if (!FLAG_trace_zone_stats &&
30441cb0ef41Sopenharmony_ci        !(TracingFlags::zone_stats.load(std::memory_order_relaxed) &
30451cb0ef41Sopenharmony_ci          v8::tracing::TracingCategoryObserver::ENABLED_BY_TRACING)) {
30461cb0ef41Sopenharmony_ci      // Don't print anything if the zone tracing was enabled only because of
30471cb0ef41Sopenharmony_ci      // FLAG_trace_zone_type_stats.
30481cb0ef41Sopenharmony_ci      return;
30491cb0ef41Sopenharmony_ci    }
30501cb0ef41Sopenharmony_ci
30511cb0ef41Sopenharmony_ci    memory_traffic_since_last_report_ += memory_traffic_delta;
30521cb0ef41Sopenharmony_ci    if (memory_traffic_since_last_report_ < FLAG_zone_stats_tolerance) return;
30531cb0ef41Sopenharmony_ci    memory_traffic_since_last_report_ = 0;
30541cb0ef41Sopenharmony_ci
30551cb0ef41Sopenharmony_ci    Dump(buffer_, true);
30561cb0ef41Sopenharmony_ci
30571cb0ef41Sopenharmony_ci    {
30581cb0ef41Sopenharmony_ci      std::string trace_str = buffer_.str();
30591cb0ef41Sopenharmony_ci
30601cb0ef41Sopenharmony_ci      if (FLAG_trace_zone_stats) {
30611cb0ef41Sopenharmony_ci        PrintF(
30621cb0ef41Sopenharmony_ci            "{"
30631cb0ef41Sopenharmony_ci            "\"type\": \"v8-zone-trace\", "
30641cb0ef41Sopenharmony_ci            "\"stats\": %s"
30651cb0ef41Sopenharmony_ci            "}\n",
30661cb0ef41Sopenharmony_ci            trace_str.c_str());
30671cb0ef41Sopenharmony_ci      }
30681cb0ef41Sopenharmony_ci      if (V8_UNLIKELY(
30691cb0ef41Sopenharmony_ci              TracingFlags::zone_stats.load(std::memory_order_relaxed) &
30701cb0ef41Sopenharmony_ci              v8::tracing::TracingCategoryObserver::ENABLED_BY_TRACING)) {
30711cb0ef41Sopenharmony_ci        TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("v8.zone_stats"),
30721cb0ef41Sopenharmony_ci                             "V8.Zone_Stats", TRACE_EVENT_SCOPE_THREAD, "stats",
30731cb0ef41Sopenharmony_ci                             TRACE_STR_COPY(trace_str.c_str()));
30741cb0ef41Sopenharmony_ci      }
30751cb0ef41Sopenharmony_ci    }
30761cb0ef41Sopenharmony_ci
30771cb0ef41Sopenharmony_ci    // Clear the buffer.
30781cb0ef41Sopenharmony_ci    buffer_.str(std::string());
30791cb0ef41Sopenharmony_ci  }
30801cb0ef41Sopenharmony_ci
30811cb0ef41Sopenharmony_ci  void Dump(std::ostringstream& out, bool dump_details) {
30821cb0ef41Sopenharmony_ci    // Note: Neither isolate nor zones are locked, so be careful with accesses
30831cb0ef41Sopenharmony_ci    // as the allocator is potentially used on a concurrent thread.
30841cb0ef41Sopenharmony_ci    double time = isolate_->time_millis_since_init();
30851cb0ef41Sopenharmony_ci    out << "{"
30861cb0ef41Sopenharmony_ci        << "\"isolate\": \"" << reinterpret_cast<void*>(isolate_) << "\", "
30871cb0ef41Sopenharmony_ci        << "\"time\": " << time << ", ";
30881cb0ef41Sopenharmony_ci    size_t total_segment_bytes_allocated = 0;
30891cb0ef41Sopenharmony_ci    size_t total_zone_allocation_size = 0;
30901cb0ef41Sopenharmony_ci    size_t total_zone_freed_size = 0;
30911cb0ef41Sopenharmony_ci
30921cb0ef41Sopenharmony_ci    if (dump_details) {
30931cb0ef41Sopenharmony_ci      // Print detailed zone stats if memory usage changes direction.
30941cb0ef41Sopenharmony_ci      out << "\"zones\": [";
30951cb0ef41Sopenharmony_ci      bool first = true;
30961cb0ef41Sopenharmony_ci      for (const Zone* zone : active_zones_) {
30971cb0ef41Sopenharmony_ci        size_t zone_segment_bytes_allocated = zone->segment_bytes_allocated();
30981cb0ef41Sopenharmony_ci        size_t zone_allocation_size = zone->allocation_size_for_tracing();
30991cb0ef41Sopenharmony_ci        size_t freed_size = zone->freed_size_for_tracing();
31001cb0ef41Sopenharmony_ci        if (first) {
31011cb0ef41Sopenharmony_ci          first = false;
31021cb0ef41Sopenharmony_ci        } else {
31031cb0ef41Sopenharmony_ci          out << ", ";
31041cb0ef41Sopenharmony_ci        }
31051cb0ef41Sopenharmony_ci        out << "{"
31061cb0ef41Sopenharmony_ci            << "\"name\": \"" << zone->name() << "\", "
31071cb0ef41Sopenharmony_ci            << "\"allocated\": " << zone_segment_bytes_allocated << ", "
31081cb0ef41Sopenharmony_ci            << "\"used\": " << zone_allocation_size << ", "
31091cb0ef41Sopenharmony_ci            << "\"freed\": " << freed_size << "}";
31101cb0ef41Sopenharmony_ci        total_segment_bytes_allocated += zone_segment_bytes_allocated;
31111cb0ef41Sopenharmony_ci        total_zone_allocation_size += zone_allocation_size;
31121cb0ef41Sopenharmony_ci        total_zone_freed_size += freed_size;
31131cb0ef41Sopenharmony_ci      }
31141cb0ef41Sopenharmony_ci      out << "], ";
31151cb0ef41Sopenharmony_ci    } else {
31161cb0ef41Sopenharmony_ci      // Just calculate total allocated/used memory values.
31171cb0ef41Sopenharmony_ci      for (const Zone* zone : active_zones_) {
31181cb0ef41Sopenharmony_ci        total_segment_bytes_allocated += zone->segment_bytes_allocated();
31191cb0ef41Sopenharmony_ci        total_zone_allocation_size += zone->allocation_size_for_tracing();
31201cb0ef41Sopenharmony_ci        total_zone_freed_size += zone->freed_size_for_tracing();
31211cb0ef41Sopenharmony_ci      }
31221cb0ef41Sopenharmony_ci    }
31231cb0ef41Sopenharmony_ci    out << "\"allocated\": " << total_segment_bytes_allocated << ", "
31241cb0ef41Sopenharmony_ci        << "\"used\": " << total_zone_allocation_size << ", "
31251cb0ef41Sopenharmony_ci        << "\"freed\": " << total_zone_freed_size << "}";
31261cb0ef41Sopenharmony_ci  }
31271cb0ef41Sopenharmony_ci
31281cb0ef41Sopenharmony_ci  Isolate* const isolate_;
31291cb0ef41Sopenharmony_ci  std::atomic<size_t> nesting_depth_{0};
31301cb0ef41Sopenharmony_ci
31311cb0ef41Sopenharmony_ci  base::Mutex mutex_;
31321cb0ef41Sopenharmony_ci  std::unordered_set<const Zone*> active_zones_;
31331cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_PRECISE_ZONE_STATS
31341cb0ef41Sopenharmony_ci  TypeStats type_stats_;
31351cb0ef41Sopenharmony_ci#endif
31361cb0ef41Sopenharmony_ci  std::ostringstream buffer_;
31371cb0ef41Sopenharmony_ci  // This value is increased on both allocations and deallocations.
31381cb0ef41Sopenharmony_ci  size_t memory_traffic_since_last_report_ = 0;
31391cb0ef41Sopenharmony_ci};
31401cb0ef41Sopenharmony_ci
31411cb0ef41Sopenharmony_ci#ifdef DEBUG
31421cb0ef41Sopenharmony_cistd::atomic<size_t> Isolate::non_disposed_isolates_;
31431cb0ef41Sopenharmony_ci#endif  // DEBUG
31441cb0ef41Sopenharmony_ci
31451cb0ef41Sopenharmony_ci// static
31461cb0ef41Sopenharmony_ciIsolate* Isolate::New() { return Isolate::Allocate(false); }
31471cb0ef41Sopenharmony_ci
31481cb0ef41Sopenharmony_ci// static
31491cb0ef41Sopenharmony_ciIsolate* Isolate::NewShared(const v8::Isolate::CreateParams& params) {
31501cb0ef41Sopenharmony_ci  DCHECK(ReadOnlyHeap::IsReadOnlySpaceShared());
31511cb0ef41Sopenharmony_ci  Isolate* isolate = Isolate::Allocate(true);
31521cb0ef41Sopenharmony_ci  v8::Isolate::Initialize(reinterpret_cast<v8::Isolate*>(isolate), params);
31531cb0ef41Sopenharmony_ci  return isolate;
31541cb0ef41Sopenharmony_ci}
31551cb0ef41Sopenharmony_ci
31561cb0ef41Sopenharmony_ci// static
31571cb0ef41Sopenharmony_ciIsolate* Isolate::Allocate(bool is_shared) {
31581cb0ef41Sopenharmony_ci  // v8::V8::Initialize() must be called before creating any isolates.
31591cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(V8::GetCurrentPlatform());
31601cb0ef41Sopenharmony_ci  // IsolateAllocator allocates the memory for the Isolate object according to
31611cb0ef41Sopenharmony_ci  // the given allocation mode.
31621cb0ef41Sopenharmony_ci  std::unique_ptr<IsolateAllocator> isolate_allocator =
31631cb0ef41Sopenharmony_ci      std::make_unique<IsolateAllocator>();
31641cb0ef41Sopenharmony_ci  // Construct Isolate object in the allocated memory.
31651cb0ef41Sopenharmony_ci  void* isolate_ptr = isolate_allocator->isolate_memory();
31661cb0ef41Sopenharmony_ci  Isolate* isolate =
31671cb0ef41Sopenharmony_ci      new (isolate_ptr) Isolate(std::move(isolate_allocator), is_shared);
31681cb0ef41Sopenharmony_ci#ifdef V8_COMPRESS_POINTERS_IN_ISOLATE_CAGE
31691cb0ef41Sopenharmony_ci  DCHECK(IsAligned(isolate->isolate_root(), kPtrComprCageBaseAlignment));
31701cb0ef41Sopenharmony_ci  DCHECK_EQ(isolate->isolate_root(), isolate->cage_base());
31711cb0ef41Sopenharmony_ci#endif
31721cb0ef41Sopenharmony_ci
31731cb0ef41Sopenharmony_ci#ifdef DEBUG
31741cb0ef41Sopenharmony_ci  non_disposed_isolates_++;
31751cb0ef41Sopenharmony_ci#endif  // DEBUG
31761cb0ef41Sopenharmony_ci
31771cb0ef41Sopenharmony_ci  return isolate;
31781cb0ef41Sopenharmony_ci}
31791cb0ef41Sopenharmony_ci
31801cb0ef41Sopenharmony_ci// static
31811cb0ef41Sopenharmony_civoid Isolate::Delete(Isolate* isolate) {
31821cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(isolate);
31831cb0ef41Sopenharmony_ci  // v8::V8::Dispose() must only be called after deleting all isolates.
31841cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(V8::GetCurrentPlatform());
31851cb0ef41Sopenharmony_ci  // Temporarily set this isolate as current so that various parts of
31861cb0ef41Sopenharmony_ci  // the isolate can access it in their destructors without having a
31871cb0ef41Sopenharmony_ci  // direct pointer. We don't use Enter/Exit here to avoid
31881cb0ef41Sopenharmony_ci  // initializing the thread data.
31891cb0ef41Sopenharmony_ci  PerIsolateThreadData* saved_data = isolate->CurrentPerIsolateThreadData();
31901cb0ef41Sopenharmony_ci  DCHECK_EQ(true, isolate_key_created_.load(std::memory_order_relaxed));
31911cb0ef41Sopenharmony_ci  Isolate* saved_isolate = reinterpret_cast<Isolate*>(
31921cb0ef41Sopenharmony_ci      base::Thread::GetThreadLocal(isolate->isolate_key_));
31931cb0ef41Sopenharmony_ci  SetIsolateThreadLocals(isolate, nullptr);
31941cb0ef41Sopenharmony_ci  isolate->set_thread_id(ThreadId::Current());
31951cb0ef41Sopenharmony_ci
31961cb0ef41Sopenharmony_ci  isolate->Deinit();
31971cb0ef41Sopenharmony_ci
31981cb0ef41Sopenharmony_ci#ifdef DEBUG
31991cb0ef41Sopenharmony_ci  non_disposed_isolates_--;
32001cb0ef41Sopenharmony_ci#endif  // DEBUG
32011cb0ef41Sopenharmony_ci
32021cb0ef41Sopenharmony_ci  // Take ownership of the IsolateAllocator to ensure the Isolate memory will
32031cb0ef41Sopenharmony_ci  // be available during Isolate descructor call.
32041cb0ef41Sopenharmony_ci  std::unique_ptr<IsolateAllocator> isolate_allocator =
32051cb0ef41Sopenharmony_ci      std::move(isolate->isolate_allocator_);
32061cb0ef41Sopenharmony_ci  isolate->~Isolate();
32071cb0ef41Sopenharmony_ci  // Now free the memory owned by the allocator.
32081cb0ef41Sopenharmony_ci  isolate_allocator.reset();
32091cb0ef41Sopenharmony_ci
32101cb0ef41Sopenharmony_ci  // Restore the previous current isolate.
32111cb0ef41Sopenharmony_ci  SetIsolateThreadLocals(saved_isolate, saved_data);
32121cb0ef41Sopenharmony_ci}
32131cb0ef41Sopenharmony_ci
32141cb0ef41Sopenharmony_civoid Isolate::SetUpFromReadOnlyArtifacts(
32151cb0ef41Sopenharmony_ci    std::shared_ptr<ReadOnlyArtifacts> artifacts, ReadOnlyHeap* ro_heap) {
32161cb0ef41Sopenharmony_ci  if (ReadOnlyHeap::IsReadOnlySpaceShared()) {
32171cb0ef41Sopenharmony_ci    DCHECK_NOT_NULL(artifacts);
32181cb0ef41Sopenharmony_ci    artifacts_ = artifacts;
32191cb0ef41Sopenharmony_ci  } else {
32201cb0ef41Sopenharmony_ci    DCHECK_NULL(artifacts);
32211cb0ef41Sopenharmony_ci  }
32221cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(ro_heap);
32231cb0ef41Sopenharmony_ci  DCHECK_IMPLIES(read_only_heap_ != nullptr, read_only_heap_ == ro_heap);
32241cb0ef41Sopenharmony_ci  read_only_heap_ = ro_heap;
32251cb0ef41Sopenharmony_ci  heap_.SetUpFromReadOnlyHeap(read_only_heap_);
32261cb0ef41Sopenharmony_ci}
32271cb0ef41Sopenharmony_ci
32281cb0ef41Sopenharmony_civ8::PageAllocator* Isolate::page_allocator() const {
32291cb0ef41Sopenharmony_ci  return isolate_allocator_->page_allocator();
32301cb0ef41Sopenharmony_ci}
32311cb0ef41Sopenharmony_ci
32321cb0ef41Sopenharmony_ciIsolate::Isolate(std::unique_ptr<i::IsolateAllocator> isolate_allocator,
32331cb0ef41Sopenharmony_ci                 bool is_shared)
32341cb0ef41Sopenharmony_ci    : isolate_data_(this, isolate_allocator->GetPtrComprCageBase()),
32351cb0ef41Sopenharmony_ci      is_shared_(is_shared),
32361cb0ef41Sopenharmony_ci      isolate_allocator_(std::move(isolate_allocator)),
32371cb0ef41Sopenharmony_ci      id_(isolate_counter.fetch_add(1, std::memory_order_relaxed)),
32381cb0ef41Sopenharmony_ci      allocator_(new TracingAccountingAllocator(this)),
32391cb0ef41Sopenharmony_ci      builtins_(this),
32401cb0ef41Sopenharmony_ci#if defined(DEBUG) || defined(VERIFY_HEAP)
32411cb0ef41Sopenharmony_ci      num_active_deserializers_(0),
32421cb0ef41Sopenharmony_ci#endif
32431cb0ef41Sopenharmony_ci      rail_mode_(PERFORMANCE_ANIMATION),
32441cb0ef41Sopenharmony_ci      code_event_dispatcher_(new CodeEventDispatcher()),
32451cb0ef41Sopenharmony_ci      detailed_source_positions_for_profiling_(FLAG_detailed_line_info),
32461cb0ef41Sopenharmony_ci      persistent_handles_list_(new PersistentHandlesList()),
32471cb0ef41Sopenharmony_ci      jitless_(FLAG_jitless),
32481cb0ef41Sopenharmony_ci#if V8_SFI_HAS_UNIQUE_ID
32491cb0ef41Sopenharmony_ci      next_unique_sfi_id_(0),
32501cb0ef41Sopenharmony_ci#endif
32511cb0ef41Sopenharmony_ci      next_module_async_evaluating_ordinal_(
32521cb0ef41Sopenharmony_ci          SourceTextModule::kFirstAsyncEvaluatingOrdinal),
32531cb0ef41Sopenharmony_ci      cancelable_task_manager_(new CancelableTaskManager()) {
32541cb0ef41Sopenharmony_ci  TRACE_ISOLATE(constructor);
32551cb0ef41Sopenharmony_ci  CheckIsolateLayout();
32561cb0ef41Sopenharmony_ci
32571cb0ef41Sopenharmony_ci  // ThreadManager is initialized early to support locking an isolate
32581cb0ef41Sopenharmony_ci  // before it is entered.
32591cb0ef41Sopenharmony_ci  thread_manager_ = new ThreadManager(this);
32601cb0ef41Sopenharmony_ci
32611cb0ef41Sopenharmony_ci  handle_scope_data_.Initialize();
32621cb0ef41Sopenharmony_ci
32631cb0ef41Sopenharmony_ci  // A shared Isolate is used to support JavaScript shared memory features
32641cb0ef41Sopenharmony_ci  // across Isolates. These features require all of the following to hold in the
32651cb0ef41Sopenharmony_ci  // build configuration:
32661cb0ef41Sopenharmony_ci  //
32671cb0ef41Sopenharmony_ci  // 1. The RO space is shared, so e.g. immortal RO maps can be shared across
32681cb0ef41Sopenharmony_ci  //   Isolates.
32691cb0ef41Sopenharmony_ci  // 2. HeapObjects are shareable across Isolates, which requires either
32701cb0ef41Sopenharmony_ci  //   pointers to be uncompressed (!COMPRESS_POINTER_BOOL), or that there is a
32711cb0ef41Sopenharmony_ci  //   single virtual memory reservation shared by all Isolates in the process
32721cb0ef41Sopenharmony_ci  //   for compressing pointers (COMPRESS_POINTERS_IN_SHARED_CAGE_BOOL).
32731cb0ef41Sopenharmony_ci  CHECK_IMPLIES(is_shared_, V8_SHARED_RO_HEAP_BOOL &&
32741cb0ef41Sopenharmony_ci                                (!COMPRESS_POINTERS_BOOL ||
32751cb0ef41Sopenharmony_ci                                 COMPRESS_POINTERS_IN_SHARED_CAGE_BOOL));
32761cb0ef41Sopenharmony_ci
32771cb0ef41Sopenharmony_ci#define ISOLATE_INIT_EXECUTE(type, name, initial_value) \
32781cb0ef41Sopenharmony_ci  name##_ = (initial_value);
32791cb0ef41Sopenharmony_ci  ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE)
32801cb0ef41Sopenharmony_ci#undef ISOLATE_INIT_EXECUTE
32811cb0ef41Sopenharmony_ci
32821cb0ef41Sopenharmony_ci#define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \
32831cb0ef41Sopenharmony_ci  memset(name##_, 0, sizeof(type) * length);
32841cb0ef41Sopenharmony_ci  ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE)
32851cb0ef41Sopenharmony_ci#undef ISOLATE_INIT_ARRAY_EXECUTE
32861cb0ef41Sopenharmony_ci
32871cb0ef41Sopenharmony_ci  InitializeLoggingAndCounters();
32881cb0ef41Sopenharmony_ci  debug_ = new Debug(this);
32891cb0ef41Sopenharmony_ci
32901cb0ef41Sopenharmony_ci  InitializeDefaultEmbeddedBlob();
32911cb0ef41Sopenharmony_ci
32921cb0ef41Sopenharmony_ci  MicrotaskQueue::SetUpDefaultMicrotaskQueue(this);
32931cb0ef41Sopenharmony_ci
32941cb0ef41Sopenharmony_ci  if (is_shared_) {
32951cb0ef41Sopenharmony_ci    global_safepoint_ = std::make_unique<GlobalSafepoint>(this);
32961cb0ef41Sopenharmony_ci  }
32971cb0ef41Sopenharmony_ci}
32981cb0ef41Sopenharmony_ci
32991cb0ef41Sopenharmony_civoid Isolate::CheckIsolateLayout() {
33001cb0ef41Sopenharmony_ci  CHECK_EQ(OFFSET_OF(Isolate, isolate_data_), 0);
33011cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.embedder_data_)),
33021cb0ef41Sopenharmony_ci           Internals::kIsolateEmbedderDataOffset);
33031cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(
33041cb0ef41Sopenharmony_ci               OFFSET_OF(Isolate, isolate_data_.fast_c_call_caller_fp_)),
33051cb0ef41Sopenharmony_ci           Internals::kIsolateFastCCallCallerFpOffset);
33061cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(
33071cb0ef41Sopenharmony_ci               OFFSET_OF(Isolate, isolate_data_.fast_c_call_caller_pc_)),
33081cb0ef41Sopenharmony_ci           Internals::kIsolateFastCCallCallerPcOffset);
33091cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.cage_base_)),
33101cb0ef41Sopenharmony_ci           Internals::kIsolateCageBaseOffset);
33111cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(
33121cb0ef41Sopenharmony_ci               OFFSET_OF(Isolate, isolate_data_.long_task_stats_counter_)),
33131cb0ef41Sopenharmony_ci           Internals::kIsolateLongTaskStatsCounterOffset);
33141cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.stack_guard_)),
33151cb0ef41Sopenharmony_ci           Internals::kIsolateStackGuardOffset);
33161cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.roots_table_)),
33171cb0ef41Sopenharmony_ci           Internals::kIsolateRootsOffset);
33181cb0ef41Sopenharmony_ci
33191cb0ef41Sopenharmony_ci  STATIC_ASSERT(Internals::kStackGuardSize == sizeof(StackGuard));
33201cb0ef41Sopenharmony_ci  STATIC_ASSERT(Internals::kBuiltinTier0TableSize ==
33211cb0ef41Sopenharmony_ci                Builtins::kBuiltinTier0Count * kSystemPointerSize);
33221cb0ef41Sopenharmony_ci  STATIC_ASSERT(Internals::kBuiltinTier0EntryTableSize ==
33231cb0ef41Sopenharmony_ci                Builtins::kBuiltinTier0Count * kSystemPointerSize);
33241cb0ef41Sopenharmony_ci
33251cb0ef41Sopenharmony_ci#ifdef V8_SANDBOXED_EXTERNAL_POINTERS
33261cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(ExternalPointerTable, buffer_)),
33271cb0ef41Sopenharmony_ci           Internals::kExternalPointerTableBufferOffset);
33281cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(ExternalPointerTable, capacity_)),
33291cb0ef41Sopenharmony_ci           Internals::kExternalPointerTableCapacityOffset);
33301cb0ef41Sopenharmony_ci  CHECK_EQ(static_cast<int>(OFFSET_OF(ExternalPointerTable, freelist_head_)),
33311cb0ef41Sopenharmony_ci           Internals::kExternalPointerTableFreelistHeadOffset);
33321cb0ef41Sopenharmony_ci#endif
33331cb0ef41Sopenharmony_ci}
33341cb0ef41Sopenharmony_ci
33351cb0ef41Sopenharmony_civoid Isolate::ClearSerializerData() {
33361cb0ef41Sopenharmony_ci  delete external_reference_map_;
33371cb0ef41Sopenharmony_ci  external_reference_map_ = nullptr;
33381cb0ef41Sopenharmony_ci}
33391cb0ef41Sopenharmony_ci
33401cb0ef41Sopenharmony_cibool Isolate::LogObjectRelocation() {
33411cb0ef41Sopenharmony_ci  return FLAG_verify_predictable || logger()->is_logging() || is_profiling() ||
33421cb0ef41Sopenharmony_ci         heap()->isolate()->logger()->is_listening_to_code_events() ||
33431cb0ef41Sopenharmony_ci         (heap_profiler() != nullptr &&
33441cb0ef41Sopenharmony_ci          heap_profiler()->is_tracking_object_moves()) ||
33451cb0ef41Sopenharmony_ci         heap()->has_heap_object_allocation_tracker();
33461cb0ef41Sopenharmony_ci}
33471cb0ef41Sopenharmony_ci
33481cb0ef41Sopenharmony_civoid Isolate::Deinit() {
33491cb0ef41Sopenharmony_ci  TRACE_ISOLATE(deinit);
33501cb0ef41Sopenharmony_ci  DisallowHeapAllocation no_allocation;
33511cb0ef41Sopenharmony_ci
33521cb0ef41Sopenharmony_ci  tracing_cpu_profiler_.reset();
33531cb0ef41Sopenharmony_ci  if (FLAG_stress_sampling_allocation_profiler > 0) {
33541cb0ef41Sopenharmony_ci    heap_profiler()->StopSamplingHeapProfiler();
33551cb0ef41Sopenharmony_ci  }
33561cb0ef41Sopenharmony_ci
33571cb0ef41Sopenharmony_ci  metrics_recorder_->NotifyIsolateDisposal();
33581cb0ef41Sopenharmony_ci  recorder_context_id_map_.clear();
33591cb0ef41Sopenharmony_ci
33601cb0ef41Sopenharmony_ci#if defined(V8_OS_WIN64)
33611cb0ef41Sopenharmony_ci  if (win64_unwindinfo::CanRegisterUnwindInfoForNonABICompliantCodeRange() &&
33621cb0ef41Sopenharmony_ci      heap()->memory_allocator() && RequiresCodeRange() &&
33631cb0ef41Sopenharmony_ci      heap()->code_range()->AtomicDecrementUnwindInfoUseCount() == 1) {
33641cb0ef41Sopenharmony_ci    const base::AddressRegion& code_region = heap()->code_region();
33651cb0ef41Sopenharmony_ci    void* start = reinterpret_cast<void*>(code_region.begin());
33661cb0ef41Sopenharmony_ci    win64_unwindinfo::UnregisterNonABICompliantCodeRange(start);
33671cb0ef41Sopenharmony_ci  }
33681cb0ef41Sopenharmony_ci#endif  // V8_OS_WIN64
33691cb0ef41Sopenharmony_ci
33701cb0ef41Sopenharmony_ci  FutexEmulation::IsolateDeinit(this);
33711cb0ef41Sopenharmony_ci
33721cb0ef41Sopenharmony_ci  debug()->Unload();
33731cb0ef41Sopenharmony_ci
33741cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
33751cb0ef41Sopenharmony_ci  wasm::GetWasmEngine()->DeleteCompileJobsOnIsolate(this);
33761cb0ef41Sopenharmony_ci
33771cb0ef41Sopenharmony_ci  BackingStore::RemoveSharedWasmMemoryObjects(this);
33781cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
33791cb0ef41Sopenharmony_ci
33801cb0ef41Sopenharmony_ci  if (concurrent_recompilation_enabled()) {
33811cb0ef41Sopenharmony_ci    optimizing_compile_dispatcher_->Stop();
33821cb0ef41Sopenharmony_ci    delete optimizing_compile_dispatcher_;
33831cb0ef41Sopenharmony_ci    optimizing_compile_dispatcher_ = nullptr;
33841cb0ef41Sopenharmony_ci  }
33851cb0ef41Sopenharmony_ci
33861cb0ef41Sopenharmony_ci  // All client isolates should already be detached.
33871cb0ef41Sopenharmony_ci  if (is_shared()) global_safepoint()->AssertNoClients();
33881cb0ef41Sopenharmony_ci
33891cb0ef41Sopenharmony_ci  if (FLAG_print_deopt_stress) {
33901cb0ef41Sopenharmony_ci    PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_);
33911cb0ef41Sopenharmony_ci  }
33921cb0ef41Sopenharmony_ci
33931cb0ef41Sopenharmony_ci  // We must stop the logger before we tear down other components.
33941cb0ef41Sopenharmony_ci  sampler::Sampler* sampler = logger_->sampler();
33951cb0ef41Sopenharmony_ci  if (sampler && sampler->IsActive()) sampler->Stop();
33961cb0ef41Sopenharmony_ci
33971cb0ef41Sopenharmony_ci  FreeThreadResources();
33981cb0ef41Sopenharmony_ci  logger_->StopProfilerThread();
33991cb0ef41Sopenharmony_ci
34001cb0ef41Sopenharmony_ci  // We start with the heap tear down so that releasing managed objects does
34011cb0ef41Sopenharmony_ci  // not cause a GC.
34021cb0ef41Sopenharmony_ci  heap_.StartTearDown();
34031cb0ef41Sopenharmony_ci
34041cb0ef41Sopenharmony_ci  // This stops cancelable tasks (i.e. concurrent marking tasks).
34051cb0ef41Sopenharmony_ci  // Stop concurrent tasks before destroying resources since they might still
34061cb0ef41Sopenharmony_ci  // use those.
34071cb0ef41Sopenharmony_ci  {
34081cb0ef41Sopenharmony_ci    IgnoreLocalGCRequests ignore_gc_requests(heap());
34091cb0ef41Sopenharmony_ci    ParkedScope parked_scope(main_thread_local_heap());
34101cb0ef41Sopenharmony_ci    cancelable_task_manager()->CancelAndWait();
34111cb0ef41Sopenharmony_ci  }
34121cb0ef41Sopenharmony_ci
34131cb0ef41Sopenharmony_ci  // Cancel all compiler tasks.
34141cb0ef41Sopenharmony_ci  delete baseline_batch_compiler_;
34151cb0ef41Sopenharmony_ci  baseline_batch_compiler_ = nullptr;
34161cb0ef41Sopenharmony_ci
34171cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_MAGLEV
34181cb0ef41Sopenharmony_ci  delete maglev_concurrent_dispatcher_;
34191cb0ef41Sopenharmony_ci  maglev_concurrent_dispatcher_ = nullptr;
34201cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_MAGLEV
34211cb0ef41Sopenharmony_ci
34221cb0ef41Sopenharmony_ci  if (lazy_compile_dispatcher_) {
34231cb0ef41Sopenharmony_ci    lazy_compile_dispatcher_->AbortAll();
34241cb0ef41Sopenharmony_ci    lazy_compile_dispatcher_.reset();
34251cb0ef41Sopenharmony_ci  }
34261cb0ef41Sopenharmony_ci
34271cb0ef41Sopenharmony_ci  // At this point there are no more background threads left in this isolate.
34281cb0ef41Sopenharmony_ci  heap_.safepoint()->AssertMainThreadIsOnlyThread();
34291cb0ef41Sopenharmony_ci
34301cb0ef41Sopenharmony_ci  {
34311cb0ef41Sopenharmony_ci    // This isolate might have to park for a shared GC initiated by another
34321cb0ef41Sopenharmony_ci    // client isolate before it can actually detach from the shared isolate.
34331cb0ef41Sopenharmony_ci    AllowGarbageCollection allow_shared_gc;
34341cb0ef41Sopenharmony_ci    DetachFromSharedIsolate();
34351cb0ef41Sopenharmony_ci  }
34361cb0ef41Sopenharmony_ci
34371cb0ef41Sopenharmony_ci  ReleaseSharedPtrs();
34381cb0ef41Sopenharmony_ci
34391cb0ef41Sopenharmony_ci  builtins_.TearDown();
34401cb0ef41Sopenharmony_ci  bootstrapper_->TearDown();
34411cb0ef41Sopenharmony_ci
34421cb0ef41Sopenharmony_ci  if (tiering_manager_ != nullptr) {
34431cb0ef41Sopenharmony_ci    delete tiering_manager_;
34441cb0ef41Sopenharmony_ci    tiering_manager_ = nullptr;
34451cb0ef41Sopenharmony_ci  }
34461cb0ef41Sopenharmony_ci
34471cb0ef41Sopenharmony_ci  delete heap_profiler_;
34481cb0ef41Sopenharmony_ci  heap_profiler_ = nullptr;
34491cb0ef41Sopenharmony_ci
34501cb0ef41Sopenharmony_ci  string_table_.reset();
34511cb0ef41Sopenharmony_ci
34521cb0ef41Sopenharmony_ci#if USE_SIMULATOR
34531cb0ef41Sopenharmony_ci  delete simulator_data_;
34541cb0ef41Sopenharmony_ci  simulator_data_ = nullptr;
34551cb0ef41Sopenharmony_ci#endif
34561cb0ef41Sopenharmony_ci
34571cb0ef41Sopenharmony_ci  // After all concurrent tasks are stopped, we know for sure that stats aren't
34581cb0ef41Sopenharmony_ci  // updated anymore.
34591cb0ef41Sopenharmony_ci  DumpAndResetStats();
34601cb0ef41Sopenharmony_ci
34611cb0ef41Sopenharmony_ci  heap_.TearDown();
34621cb0ef41Sopenharmony_ci
34631cb0ef41Sopenharmony_ci  main_thread_local_isolate_.reset();
34641cb0ef41Sopenharmony_ci
34651cb0ef41Sopenharmony_ci  FILE* logfile = logger_->TearDownAndGetLogFile();
34661cb0ef41Sopenharmony_ci  if (logfile != nullptr) base::Fclose(logfile);
34671cb0ef41Sopenharmony_ci
34681cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
34691cb0ef41Sopenharmony_ci  wasm::GetWasmEngine()->RemoveIsolate(this);
34701cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
34711cb0ef41Sopenharmony_ci
34721cb0ef41Sopenharmony_ci  TearDownEmbeddedBlob();
34731cb0ef41Sopenharmony_ci
34741cb0ef41Sopenharmony_ci  delete interpreter_;
34751cb0ef41Sopenharmony_ci  interpreter_ = nullptr;
34761cb0ef41Sopenharmony_ci
34771cb0ef41Sopenharmony_ci  delete ast_string_constants_;
34781cb0ef41Sopenharmony_ci  ast_string_constants_ = nullptr;
34791cb0ef41Sopenharmony_ci
34801cb0ef41Sopenharmony_ci  code_event_dispatcher_.reset();
34811cb0ef41Sopenharmony_ci
34821cb0ef41Sopenharmony_ci  delete root_index_map_;
34831cb0ef41Sopenharmony_ci  root_index_map_ = nullptr;
34841cb0ef41Sopenharmony_ci
34851cb0ef41Sopenharmony_ci  delete compiler_zone_;
34861cb0ef41Sopenharmony_ci  compiler_zone_ = nullptr;
34871cb0ef41Sopenharmony_ci  compiler_cache_ = nullptr;
34881cb0ef41Sopenharmony_ci
34891cb0ef41Sopenharmony_ci  SetCodePages(nullptr);
34901cb0ef41Sopenharmony_ci
34911cb0ef41Sopenharmony_ci  ClearSerializerData();
34921cb0ef41Sopenharmony_ci
34931cb0ef41Sopenharmony_ci#ifdef V8_SANDBOXED_EXTERNAL_POINTERS
34941cb0ef41Sopenharmony_ci  external_pointer_table().TearDown();
34951cb0ef41Sopenharmony_ci#endif  // V8_SANDBOXED_EXTERNAL_POINTERS
34961cb0ef41Sopenharmony_ci
34971cb0ef41Sopenharmony_ci  {
34981cb0ef41Sopenharmony_ci    base::MutexGuard lock_guard(&thread_data_table_mutex_);
34991cb0ef41Sopenharmony_ci    thread_data_table_.RemoveAllThreads();
35001cb0ef41Sopenharmony_ci  }
35011cb0ef41Sopenharmony_ci}
35021cb0ef41Sopenharmony_ci
35031cb0ef41Sopenharmony_civoid Isolate::SetIsolateThreadLocals(Isolate* isolate,
35041cb0ef41Sopenharmony_ci                                     PerIsolateThreadData* data) {
35051cb0ef41Sopenharmony_ci  base::Thread::SetThreadLocal(isolate_key_, isolate);
35061cb0ef41Sopenharmony_ci  base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data);
35071cb0ef41Sopenharmony_ci}
35081cb0ef41Sopenharmony_ci
35091cb0ef41Sopenharmony_ciIsolate::~Isolate() {
35101cb0ef41Sopenharmony_ci  TRACE_ISOLATE(destructor);
35111cb0ef41Sopenharmony_ci
35121cb0ef41Sopenharmony_ci  // The entry stack must be empty when we get here.
35131cb0ef41Sopenharmony_ci  DCHECK(entry_stack_ == nullptr || entry_stack_->previous_item == nullptr);
35141cb0ef41Sopenharmony_ci
35151cb0ef41Sopenharmony_ci  delete entry_stack_;
35161cb0ef41Sopenharmony_ci  entry_stack_ = nullptr;
35171cb0ef41Sopenharmony_ci
35181cb0ef41Sopenharmony_ci  delete date_cache_;
35191cb0ef41Sopenharmony_ci  date_cache_ = nullptr;
35201cb0ef41Sopenharmony_ci
35211cb0ef41Sopenharmony_ci  delete regexp_stack_;
35221cb0ef41Sopenharmony_ci  regexp_stack_ = nullptr;
35231cb0ef41Sopenharmony_ci
35241cb0ef41Sopenharmony_ci  delete descriptor_lookup_cache_;
35251cb0ef41Sopenharmony_ci  descriptor_lookup_cache_ = nullptr;
35261cb0ef41Sopenharmony_ci
35271cb0ef41Sopenharmony_ci  delete load_stub_cache_;
35281cb0ef41Sopenharmony_ci  load_stub_cache_ = nullptr;
35291cb0ef41Sopenharmony_ci  delete store_stub_cache_;
35301cb0ef41Sopenharmony_ci  store_stub_cache_ = nullptr;
35311cb0ef41Sopenharmony_ci
35321cb0ef41Sopenharmony_ci  delete materialized_object_store_;
35331cb0ef41Sopenharmony_ci  materialized_object_store_ = nullptr;
35341cb0ef41Sopenharmony_ci
35351cb0ef41Sopenharmony_ci  delete logger_;
35361cb0ef41Sopenharmony_ci  logger_ = nullptr;
35371cb0ef41Sopenharmony_ci
35381cb0ef41Sopenharmony_ci  delete handle_scope_implementer_;
35391cb0ef41Sopenharmony_ci  handle_scope_implementer_ = nullptr;
35401cb0ef41Sopenharmony_ci
35411cb0ef41Sopenharmony_ci  delete code_tracer();
35421cb0ef41Sopenharmony_ci  set_code_tracer(nullptr);
35431cb0ef41Sopenharmony_ci
35441cb0ef41Sopenharmony_ci  delete compilation_cache_;
35451cb0ef41Sopenharmony_ci  compilation_cache_ = nullptr;
35461cb0ef41Sopenharmony_ci  delete bootstrapper_;
35471cb0ef41Sopenharmony_ci  bootstrapper_ = nullptr;
35481cb0ef41Sopenharmony_ci  delete inner_pointer_to_code_cache_;
35491cb0ef41Sopenharmony_ci  inner_pointer_to_code_cache_ = nullptr;
35501cb0ef41Sopenharmony_ci
35511cb0ef41Sopenharmony_ci  delete thread_manager_;
35521cb0ef41Sopenharmony_ci  thread_manager_ = nullptr;
35531cb0ef41Sopenharmony_ci
35541cb0ef41Sopenharmony_ci  bigint_processor_->Destroy();
35551cb0ef41Sopenharmony_ci
35561cb0ef41Sopenharmony_ci  delete global_handles_;
35571cb0ef41Sopenharmony_ci  global_handles_ = nullptr;
35581cb0ef41Sopenharmony_ci  delete eternal_handles_;
35591cb0ef41Sopenharmony_ci  eternal_handles_ = nullptr;
35601cb0ef41Sopenharmony_ci
35611cb0ef41Sopenharmony_ci  delete string_stream_debug_object_cache_;
35621cb0ef41Sopenharmony_ci  string_stream_debug_object_cache_ = nullptr;
35631cb0ef41Sopenharmony_ci
35641cb0ef41Sopenharmony_ci  delete random_number_generator_;
35651cb0ef41Sopenharmony_ci  random_number_generator_ = nullptr;
35661cb0ef41Sopenharmony_ci
35671cb0ef41Sopenharmony_ci  delete fuzzer_rng_;
35681cb0ef41Sopenharmony_ci  fuzzer_rng_ = nullptr;
35691cb0ef41Sopenharmony_ci
35701cb0ef41Sopenharmony_ci  delete debug_;
35711cb0ef41Sopenharmony_ci  debug_ = nullptr;
35721cb0ef41Sopenharmony_ci
35731cb0ef41Sopenharmony_ci  delete cancelable_task_manager_;
35741cb0ef41Sopenharmony_ci  cancelable_task_manager_ = nullptr;
35751cb0ef41Sopenharmony_ci
35761cb0ef41Sopenharmony_ci  delete allocator_;
35771cb0ef41Sopenharmony_ci  allocator_ = nullptr;
35781cb0ef41Sopenharmony_ci
35791cb0ef41Sopenharmony_ci  // Assert that |default_microtask_queue_| is the last MicrotaskQueue instance.
35801cb0ef41Sopenharmony_ci  DCHECK_IMPLIES(default_microtask_queue_,
35811cb0ef41Sopenharmony_ci                 default_microtask_queue_ == default_microtask_queue_->next());
35821cb0ef41Sopenharmony_ci  delete default_microtask_queue_;
35831cb0ef41Sopenharmony_ci  default_microtask_queue_ = nullptr;
35841cb0ef41Sopenharmony_ci
35851cb0ef41Sopenharmony_ci  // The ReadOnlyHeap should not be destroyed when sharing without pointer
35861cb0ef41Sopenharmony_ci  // compression as the object itself is shared.
35871cb0ef41Sopenharmony_ci  if (read_only_heap_->IsOwnedByIsolate()) {
35881cb0ef41Sopenharmony_ci    delete read_only_heap_;
35891cb0ef41Sopenharmony_ci    read_only_heap_ = nullptr;
35901cb0ef41Sopenharmony_ci  }
35911cb0ef41Sopenharmony_ci}
35921cb0ef41Sopenharmony_ci
35931cb0ef41Sopenharmony_civoid Isolate::InitializeThreadLocal() {
35941cb0ef41Sopenharmony_ci  thread_local_top()->Initialize(this);
35951cb0ef41Sopenharmony_ci  clear_pending_exception();
35961cb0ef41Sopenharmony_ci  clear_pending_message();
35971cb0ef41Sopenharmony_ci  clear_scheduled_exception();
35981cb0ef41Sopenharmony_ci}
35991cb0ef41Sopenharmony_ci
36001cb0ef41Sopenharmony_civoid Isolate::SetTerminationOnExternalTryCatch() {
36011cb0ef41Sopenharmony_ci  if (try_catch_handler() == nullptr) return;
36021cb0ef41Sopenharmony_ci  try_catch_handler()->can_continue_ = false;
36031cb0ef41Sopenharmony_ci  try_catch_handler()->has_terminated_ = true;
36041cb0ef41Sopenharmony_ci  try_catch_handler()->exception_ =
36051cb0ef41Sopenharmony_ci      reinterpret_cast<void*>(ReadOnlyRoots(heap()).null_value().ptr());
36061cb0ef41Sopenharmony_ci}
36071cb0ef41Sopenharmony_ci
36081cb0ef41Sopenharmony_cibool Isolate::PropagatePendingExceptionToExternalTryCatch(
36091cb0ef41Sopenharmony_ci    ExceptionHandlerType top_handler) {
36101cb0ef41Sopenharmony_ci  Object exception = pending_exception();
36111cb0ef41Sopenharmony_ci
36121cb0ef41Sopenharmony_ci  if (top_handler == ExceptionHandlerType::kJavaScriptHandler) {
36131cb0ef41Sopenharmony_ci    thread_local_top()->external_caught_exception_ = false;
36141cb0ef41Sopenharmony_ci    return false;
36151cb0ef41Sopenharmony_ci  }
36161cb0ef41Sopenharmony_ci
36171cb0ef41Sopenharmony_ci  if (top_handler == ExceptionHandlerType::kNone) {
36181cb0ef41Sopenharmony_ci    thread_local_top()->external_caught_exception_ = false;
36191cb0ef41Sopenharmony_ci    return true;
36201cb0ef41Sopenharmony_ci  }
36211cb0ef41Sopenharmony_ci
36221cb0ef41Sopenharmony_ci  DCHECK_EQ(ExceptionHandlerType::kExternalTryCatch, top_handler);
36231cb0ef41Sopenharmony_ci  thread_local_top()->external_caught_exception_ = true;
36241cb0ef41Sopenharmony_ci  if (!is_catchable_by_javascript(exception)) {
36251cb0ef41Sopenharmony_ci    SetTerminationOnExternalTryCatch();
36261cb0ef41Sopenharmony_ci  } else {
36271cb0ef41Sopenharmony_ci    v8::TryCatch* handler = try_catch_handler();
36281cb0ef41Sopenharmony_ci    DCHECK(pending_message().IsJSMessageObject() ||
36291cb0ef41Sopenharmony_ci           pending_message().IsTheHole(this));
36301cb0ef41Sopenharmony_ci    handler->can_continue_ = true;
36311cb0ef41Sopenharmony_ci    handler->has_terminated_ = false;
36321cb0ef41Sopenharmony_ci    handler->exception_ = reinterpret_cast<void*>(exception.ptr());
36331cb0ef41Sopenharmony_ci    // Propagate to the external try-catch only if we got an actual message.
36341cb0ef41Sopenharmony_ci    if (!has_pending_message()) return true;
36351cb0ef41Sopenharmony_ci    handler->message_obj_ = reinterpret_cast<void*>(pending_message().ptr());
36361cb0ef41Sopenharmony_ci  }
36371cb0ef41Sopenharmony_ci  return true;
36381cb0ef41Sopenharmony_ci}
36391cb0ef41Sopenharmony_ci
36401cb0ef41Sopenharmony_cibool Isolate::InitializeCounters() {
36411cb0ef41Sopenharmony_ci  if (async_counters_) return false;
36421cb0ef41Sopenharmony_ci  async_counters_ = std::make_shared<Counters>(this);
36431cb0ef41Sopenharmony_ci  return true;
36441cb0ef41Sopenharmony_ci}
36451cb0ef41Sopenharmony_ci
36461cb0ef41Sopenharmony_civoid Isolate::InitializeLoggingAndCounters() {
36471cb0ef41Sopenharmony_ci  if (logger_ == nullptr) {
36481cb0ef41Sopenharmony_ci    logger_ = new Logger(this);
36491cb0ef41Sopenharmony_ci  }
36501cb0ef41Sopenharmony_ci  InitializeCounters();
36511cb0ef41Sopenharmony_ci}
36521cb0ef41Sopenharmony_ci
36531cb0ef41Sopenharmony_cinamespace {
36541cb0ef41Sopenharmony_ci
36551cb0ef41Sopenharmony_civoid CreateOffHeapTrampolines(Isolate* isolate) {
36561cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(isolate->embedded_blob_code());
36571cb0ef41Sopenharmony_ci  DCHECK_NE(0, isolate->embedded_blob_code_size());
36581cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(isolate->embedded_blob_data());
36591cb0ef41Sopenharmony_ci  DCHECK_NE(0, isolate->embedded_blob_data_size());
36601cb0ef41Sopenharmony_ci
36611cb0ef41Sopenharmony_ci  HandleScope scope(isolate);
36621cb0ef41Sopenharmony_ci  Builtins* builtins = isolate->builtins();
36631cb0ef41Sopenharmony_ci
36641cb0ef41Sopenharmony_ci  EmbeddedData d = EmbeddedData::FromBlob(isolate);
36651cb0ef41Sopenharmony_ci
36661cb0ef41Sopenharmony_ci  STATIC_ASSERT(Builtins::kAllBuiltinsAreIsolateIndependent);
36671cb0ef41Sopenharmony_ci  for (Builtin builtin = Builtins::kFirst; builtin <= Builtins::kLast;
36681cb0ef41Sopenharmony_ci       ++builtin) {
36691cb0ef41Sopenharmony_ci    Address instruction_start = d.InstructionStartOfBuiltin(builtin);
36701cb0ef41Sopenharmony_ci    // TODO(v8:11880): avoid roundtrips between cdc and code.
36711cb0ef41Sopenharmony_ci    Handle<Code> trampoline = isolate->factory()->NewOffHeapTrampolineFor(
36721cb0ef41Sopenharmony_ci        FromCodeT(builtins->code_handle(builtin), isolate), instruction_start);
36731cb0ef41Sopenharmony_ci
36741cb0ef41Sopenharmony_ci    // From this point onwards, the old builtin code object is unreachable and
36751cb0ef41Sopenharmony_ci    // will be collected by the next GC.
36761cb0ef41Sopenharmony_ci    builtins->set_code(builtin, ToCodeT(*trampoline));
36771cb0ef41Sopenharmony_ci  }
36781cb0ef41Sopenharmony_ci}
36791cb0ef41Sopenharmony_ci
36801cb0ef41Sopenharmony_ci#ifdef DEBUG
36811cb0ef41Sopenharmony_cibool IsolateIsCompatibleWithEmbeddedBlob(Isolate* isolate) {
36821cb0ef41Sopenharmony_ci  EmbeddedData d = EmbeddedData::FromBlob(isolate);
36831cb0ef41Sopenharmony_ci  return (d.IsolateHash() == isolate->HashIsolateForEmbeddedBlob());
36841cb0ef41Sopenharmony_ci}
36851cb0ef41Sopenharmony_ci#endif  // DEBUG
36861cb0ef41Sopenharmony_ci
36871cb0ef41Sopenharmony_ci}  // namespace
36881cb0ef41Sopenharmony_ci
36891cb0ef41Sopenharmony_civoid Isolate::InitializeDefaultEmbeddedBlob() {
36901cb0ef41Sopenharmony_ci  const uint8_t* code = DefaultEmbeddedBlobCode();
36911cb0ef41Sopenharmony_ci  uint32_t code_size = DefaultEmbeddedBlobCodeSize();
36921cb0ef41Sopenharmony_ci  const uint8_t* data = DefaultEmbeddedBlobData();
36931cb0ef41Sopenharmony_ci  uint32_t data_size = DefaultEmbeddedBlobDataSize();
36941cb0ef41Sopenharmony_ci
36951cb0ef41Sopenharmony_ci  if (StickyEmbeddedBlobCode() != nullptr) {
36961cb0ef41Sopenharmony_ci    base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer());
36971cb0ef41Sopenharmony_ci    // Check again now that we hold the lock.
36981cb0ef41Sopenharmony_ci    if (StickyEmbeddedBlobCode() != nullptr) {
36991cb0ef41Sopenharmony_ci      code = StickyEmbeddedBlobCode();
37001cb0ef41Sopenharmony_ci      code_size = StickyEmbeddedBlobCodeSize();
37011cb0ef41Sopenharmony_ci      data = StickyEmbeddedBlobData();
37021cb0ef41Sopenharmony_ci      data_size = StickyEmbeddedBlobDataSize();
37031cb0ef41Sopenharmony_ci      current_embedded_blob_refs_++;
37041cb0ef41Sopenharmony_ci    }
37051cb0ef41Sopenharmony_ci  }
37061cb0ef41Sopenharmony_ci
37071cb0ef41Sopenharmony_ci  if (code == nullptr) {
37081cb0ef41Sopenharmony_ci    CHECK_EQ(0, code_size);
37091cb0ef41Sopenharmony_ci  } else {
37101cb0ef41Sopenharmony_ci    SetEmbeddedBlob(code, code_size, data, data_size);
37111cb0ef41Sopenharmony_ci  }
37121cb0ef41Sopenharmony_ci}
37131cb0ef41Sopenharmony_ci
37141cb0ef41Sopenharmony_civoid Isolate::CreateAndSetEmbeddedBlob() {
37151cb0ef41Sopenharmony_ci  base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer());
37161cb0ef41Sopenharmony_ci
37171cb0ef41Sopenharmony_ci  PrepareBuiltinSourcePositionMap();
37181cb0ef41Sopenharmony_ci
37191cb0ef41Sopenharmony_ci  PrepareBuiltinLabelInfoMap();
37201cb0ef41Sopenharmony_ci
37211cb0ef41Sopenharmony_ci  // If a sticky blob has been set, we reuse it.
37221cb0ef41Sopenharmony_ci  if (StickyEmbeddedBlobCode() != nullptr) {
37231cb0ef41Sopenharmony_ci    CHECK_EQ(embedded_blob_code(), StickyEmbeddedBlobCode());
37241cb0ef41Sopenharmony_ci    CHECK_EQ(embedded_blob_data(), StickyEmbeddedBlobData());
37251cb0ef41Sopenharmony_ci    CHECK_EQ(CurrentEmbeddedBlobCode(), StickyEmbeddedBlobCode());
37261cb0ef41Sopenharmony_ci    CHECK_EQ(CurrentEmbeddedBlobData(), StickyEmbeddedBlobData());
37271cb0ef41Sopenharmony_ci  } else {
37281cb0ef41Sopenharmony_ci    // Create and set a new embedded blob.
37291cb0ef41Sopenharmony_ci    uint8_t* code;
37301cb0ef41Sopenharmony_ci    uint32_t code_size;
37311cb0ef41Sopenharmony_ci    uint8_t* data;
37321cb0ef41Sopenharmony_ci    uint32_t data_size;
37331cb0ef41Sopenharmony_ci    OffHeapInstructionStream::CreateOffHeapOffHeapInstructionStream(
37341cb0ef41Sopenharmony_ci        this, &code, &code_size, &data, &data_size);
37351cb0ef41Sopenharmony_ci
37361cb0ef41Sopenharmony_ci    CHECK_EQ(0, current_embedded_blob_refs_);
37371cb0ef41Sopenharmony_ci    const uint8_t* const_code = const_cast<const uint8_t*>(code);
37381cb0ef41Sopenharmony_ci    const uint8_t* const_data = const_cast<const uint8_t*>(data);
37391cb0ef41Sopenharmony_ci    SetEmbeddedBlob(const_code, code_size, const_data, data_size);
37401cb0ef41Sopenharmony_ci    current_embedded_blob_refs_++;
37411cb0ef41Sopenharmony_ci
37421cb0ef41Sopenharmony_ci    SetStickyEmbeddedBlob(code, code_size, data, data_size);
37431cb0ef41Sopenharmony_ci  }
37441cb0ef41Sopenharmony_ci
37451cb0ef41Sopenharmony_ci  MaybeRemapEmbeddedBuiltinsIntoCodeRange();
37461cb0ef41Sopenharmony_ci
37471cb0ef41Sopenharmony_ci  CreateOffHeapTrampolines(this);
37481cb0ef41Sopenharmony_ci}
37491cb0ef41Sopenharmony_ci
37501cb0ef41Sopenharmony_civoid Isolate::MaybeRemapEmbeddedBuiltinsIntoCodeRange() {
37511cb0ef41Sopenharmony_ci  if (!is_short_builtin_calls_enabled() || !RequiresCodeRange()) {
37521cb0ef41Sopenharmony_ci    return;
37531cb0ef41Sopenharmony_ci  }
37541cb0ef41Sopenharmony_ci  if (V8_ENABLE_NEAR_CODE_RANGE_BOOL &&
37551cb0ef41Sopenharmony_ci      GetShortBuiltinsCallRegion().contains(heap_.code_region())) {
37561cb0ef41Sopenharmony_ci    // The embedded builtins are within the pc-relative reach from the code
37571cb0ef41Sopenharmony_ci    // range, so there's no need to remap embedded builtins.
37581cb0ef41Sopenharmony_ci    return;
37591cb0ef41Sopenharmony_ci  }
37601cb0ef41Sopenharmony_ci
37611cb0ef41Sopenharmony_ci  CHECK_NOT_NULL(embedded_blob_code_);
37621cb0ef41Sopenharmony_ci  CHECK_NE(embedded_blob_code_size_, 0);
37631cb0ef41Sopenharmony_ci
37641cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(heap_.code_range_);
37651cb0ef41Sopenharmony_ci  embedded_blob_code_ = heap_.code_range_->RemapEmbeddedBuiltins(
37661cb0ef41Sopenharmony_ci      this, embedded_blob_code_, embedded_blob_code_size_);
37671cb0ef41Sopenharmony_ci  CHECK_NOT_NULL(embedded_blob_code_);
37681cb0ef41Sopenharmony_ci  // The un-embedded code blob is already a part of the registered code range
37691cb0ef41Sopenharmony_ci  // so it's not necessary to register it again.
37701cb0ef41Sopenharmony_ci}
37711cb0ef41Sopenharmony_ci
37721cb0ef41Sopenharmony_civoid Isolate::TearDownEmbeddedBlob() {
37731cb0ef41Sopenharmony_ci  // Nothing to do in case the blob is embedded into the binary or unset.
37741cb0ef41Sopenharmony_ci  if (StickyEmbeddedBlobCode() == nullptr) return;
37751cb0ef41Sopenharmony_ci
37761cb0ef41Sopenharmony_ci  if (!is_short_builtin_calls_enabled()) {
37771cb0ef41Sopenharmony_ci    CHECK_EQ(embedded_blob_code(), StickyEmbeddedBlobCode());
37781cb0ef41Sopenharmony_ci    CHECK_EQ(embedded_blob_data(), StickyEmbeddedBlobData());
37791cb0ef41Sopenharmony_ci  }
37801cb0ef41Sopenharmony_ci  CHECK_EQ(CurrentEmbeddedBlobCode(), StickyEmbeddedBlobCode());
37811cb0ef41Sopenharmony_ci  CHECK_EQ(CurrentEmbeddedBlobData(), StickyEmbeddedBlobData());
37821cb0ef41Sopenharmony_ci
37831cb0ef41Sopenharmony_ci  base::MutexGuard guard(current_embedded_blob_refcount_mutex_.Pointer());
37841cb0ef41Sopenharmony_ci  current_embedded_blob_refs_--;
37851cb0ef41Sopenharmony_ci  if (current_embedded_blob_refs_ == 0 && enable_embedded_blob_refcounting_) {
37861cb0ef41Sopenharmony_ci    // We own the embedded blob and are the last holder. Free it.
37871cb0ef41Sopenharmony_ci    OffHeapInstructionStream::FreeOffHeapOffHeapInstructionStream(
37881cb0ef41Sopenharmony_ci        const_cast<uint8_t*>(CurrentEmbeddedBlobCode()),
37891cb0ef41Sopenharmony_ci        embedded_blob_code_size(),
37901cb0ef41Sopenharmony_ci        const_cast<uint8_t*>(CurrentEmbeddedBlobData()),
37911cb0ef41Sopenharmony_ci        embedded_blob_data_size());
37921cb0ef41Sopenharmony_ci    ClearEmbeddedBlob();
37931cb0ef41Sopenharmony_ci  }
37941cb0ef41Sopenharmony_ci}
37951cb0ef41Sopenharmony_ci
37961cb0ef41Sopenharmony_cibool Isolate::InitWithoutSnapshot() {
37971cb0ef41Sopenharmony_ci  return Init(nullptr, nullptr, nullptr, false);
37981cb0ef41Sopenharmony_ci}
37991cb0ef41Sopenharmony_ci
38001cb0ef41Sopenharmony_cibool Isolate::InitWithSnapshot(SnapshotData* startup_snapshot_data,
38011cb0ef41Sopenharmony_ci                               SnapshotData* read_only_snapshot_data,
38021cb0ef41Sopenharmony_ci                               SnapshotData* shared_heap_snapshot_data,
38031cb0ef41Sopenharmony_ci                               bool can_rehash) {
38041cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(startup_snapshot_data);
38051cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(read_only_snapshot_data);
38061cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(shared_heap_snapshot_data);
38071cb0ef41Sopenharmony_ci  return Init(startup_snapshot_data, read_only_snapshot_data,
38081cb0ef41Sopenharmony_ci              shared_heap_snapshot_data, can_rehash);
38091cb0ef41Sopenharmony_ci}
38101cb0ef41Sopenharmony_ci
38111cb0ef41Sopenharmony_cistatic std::string AddressToString(uintptr_t address) {
38121cb0ef41Sopenharmony_ci  std::stringstream stream_address;
38131cb0ef41Sopenharmony_ci  stream_address << "0x" << std::hex << address;
38141cb0ef41Sopenharmony_ci  return stream_address.str();
38151cb0ef41Sopenharmony_ci}
38161cb0ef41Sopenharmony_ci
38171cb0ef41Sopenharmony_civoid Isolate::AddCrashKeysForIsolateAndHeapPointers() {
38181cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(add_crash_key_callback_);
38191cb0ef41Sopenharmony_ci
38201cb0ef41Sopenharmony_ci  const uintptr_t isolate_address = reinterpret_cast<uintptr_t>(this);
38211cb0ef41Sopenharmony_ci  add_crash_key_callback_(v8::CrashKeyId::kIsolateAddress,
38221cb0ef41Sopenharmony_ci                          AddressToString(isolate_address));
38231cb0ef41Sopenharmony_ci
38241cb0ef41Sopenharmony_ci  const uintptr_t ro_space_firstpage_address =
38251cb0ef41Sopenharmony_ci      heap()->read_only_space()->FirstPageAddress();
38261cb0ef41Sopenharmony_ci  add_crash_key_callback_(v8::CrashKeyId::kReadonlySpaceFirstPageAddress,
38271cb0ef41Sopenharmony_ci                          AddressToString(ro_space_firstpage_address));
38281cb0ef41Sopenharmony_ci
38291cb0ef41Sopenharmony_ci  if (heap()->map_space()) {
38301cb0ef41Sopenharmony_ci    const uintptr_t map_space_firstpage_address =
38311cb0ef41Sopenharmony_ci        heap()->map_space()->FirstPageAddress();
38321cb0ef41Sopenharmony_ci    add_crash_key_callback_(v8::CrashKeyId::kMapSpaceFirstPageAddress,
38331cb0ef41Sopenharmony_ci                            AddressToString(map_space_firstpage_address));
38341cb0ef41Sopenharmony_ci  }
38351cb0ef41Sopenharmony_ci
38361cb0ef41Sopenharmony_ci  const uintptr_t code_space_firstpage_address =
38371cb0ef41Sopenharmony_ci      heap()->code_space()->FirstPageAddress();
38381cb0ef41Sopenharmony_ci  add_crash_key_callback_(v8::CrashKeyId::kCodeSpaceFirstPageAddress,
38391cb0ef41Sopenharmony_ci                          AddressToString(code_space_firstpage_address));
38401cb0ef41Sopenharmony_ci}
38411cb0ef41Sopenharmony_ci
38421cb0ef41Sopenharmony_civoid Isolate::InitializeCodeRanges() {
38431cb0ef41Sopenharmony_ci  DCHECK_NULL(GetCodePages());
38441cb0ef41Sopenharmony_ci  MemoryRange embedded_range{
38451cb0ef41Sopenharmony_ci      reinterpret_cast<const void*>(embedded_blob_code()),
38461cb0ef41Sopenharmony_ci      embedded_blob_code_size()};
38471cb0ef41Sopenharmony_ci  code_pages_buffer1_.push_back(embedded_range);
38481cb0ef41Sopenharmony_ci  SetCodePages(&code_pages_buffer1_);
38491cb0ef41Sopenharmony_ci}
38501cb0ef41Sopenharmony_ci
38511cb0ef41Sopenharmony_cinamespace {
38521cb0ef41Sopenharmony_ci
38531cb0ef41Sopenharmony_ci// This global counter contains number of stack loads/stores per optimized/wasm
38541cb0ef41Sopenharmony_ci// function.
38551cb0ef41Sopenharmony_ciusing MapOfLoadsAndStoresPerFunction =
38561cb0ef41Sopenharmony_ci    std::map<std::string /* function_name */,
38571cb0ef41Sopenharmony_ci             std::pair<uint64_t /* loads */, uint64_t /* stores */>>;
38581cb0ef41Sopenharmony_ciMapOfLoadsAndStoresPerFunction* stack_access_count_map = nullptr;
38591cb0ef41Sopenharmony_ci
38601cb0ef41Sopenharmony_ciclass BigIntPlatform : public bigint::Platform {
38611cb0ef41Sopenharmony_ci public:
38621cb0ef41Sopenharmony_ci  explicit BigIntPlatform(Isolate* isolate) : isolate_(isolate) {}
38631cb0ef41Sopenharmony_ci  ~BigIntPlatform() override = default;
38641cb0ef41Sopenharmony_ci
38651cb0ef41Sopenharmony_ci  bool InterruptRequested() override {
38661cb0ef41Sopenharmony_ci    StackLimitCheck interrupt_check(isolate_);
38671cb0ef41Sopenharmony_ci    return (interrupt_check.InterruptRequested() &&
38681cb0ef41Sopenharmony_ci            isolate_->stack_guard()->HasTerminationRequest());
38691cb0ef41Sopenharmony_ci  }
38701cb0ef41Sopenharmony_ci
38711cb0ef41Sopenharmony_ci private:
38721cb0ef41Sopenharmony_ci  Isolate* isolate_;
38731cb0ef41Sopenharmony_ci};
38741cb0ef41Sopenharmony_ci}  // namespace
38751cb0ef41Sopenharmony_ci
38761cb0ef41Sopenharmony_ciVirtualMemoryCage* Isolate::GetPtrComprCodeCageForTesting() {
38771cb0ef41Sopenharmony_ci  return V8_EXTERNAL_CODE_SPACE_BOOL ? heap_.code_range() : GetPtrComprCage();
38781cb0ef41Sopenharmony_ci}
38791cb0ef41Sopenharmony_ci
38801cb0ef41Sopenharmony_cibool Isolate::Init(SnapshotData* startup_snapshot_data,
38811cb0ef41Sopenharmony_ci                   SnapshotData* read_only_snapshot_data,
38821cb0ef41Sopenharmony_ci                   SnapshotData* shared_heap_snapshot_data, bool can_rehash) {
38831cb0ef41Sopenharmony_ci  TRACE_ISOLATE(init);
38841cb0ef41Sopenharmony_ci  const bool create_heap_objects = (read_only_snapshot_data == nullptr);
38851cb0ef41Sopenharmony_ci  // We either have all or none.
38861cb0ef41Sopenharmony_ci  DCHECK_EQ(create_heap_objects, startup_snapshot_data == nullptr);
38871cb0ef41Sopenharmony_ci  DCHECK_EQ(create_heap_objects, shared_heap_snapshot_data == nullptr);
38881cb0ef41Sopenharmony_ci
38891cb0ef41Sopenharmony_ci  base::ElapsedTimer timer;
38901cb0ef41Sopenharmony_ci  if (create_heap_objects && FLAG_profile_deserialization) timer.Start();
38911cb0ef41Sopenharmony_ci
38921cb0ef41Sopenharmony_ci  time_millis_at_init_ = heap_.MonotonicallyIncreasingTimeInMs();
38931cb0ef41Sopenharmony_ci
38941cb0ef41Sopenharmony_ci  stress_deopt_count_ = FLAG_deopt_every_n_times;
38951cb0ef41Sopenharmony_ci  force_slow_path_ = FLAG_force_slow_path;
38961cb0ef41Sopenharmony_ci
38971cb0ef41Sopenharmony_ci  has_fatal_error_ = false;
38981cb0ef41Sopenharmony_ci
38991cb0ef41Sopenharmony_ci  // The initialization process does not handle memory exhaustion.
39001cb0ef41Sopenharmony_ci  AlwaysAllocateScope always_allocate(heap());
39011cb0ef41Sopenharmony_ci
39021cb0ef41Sopenharmony_ci#define ASSIGN_ELEMENT(CamelName, hacker_name)                  \
39031cb0ef41Sopenharmony_ci  isolate_addresses_[IsolateAddressId::k##CamelName##Address] = \
39041cb0ef41Sopenharmony_ci      reinterpret_cast<Address>(hacker_name##_address());
39051cb0ef41Sopenharmony_ci  FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT)
39061cb0ef41Sopenharmony_ci#undef ASSIGN_ELEMENT
39071cb0ef41Sopenharmony_ci
39081cb0ef41Sopenharmony_ci  // We need to initialize code_pages_ before any on-heap code is allocated to
39091cb0ef41Sopenharmony_ci  // make sure we record all code allocations.
39101cb0ef41Sopenharmony_ci  InitializeCodeRanges();
39111cb0ef41Sopenharmony_ci
39121cb0ef41Sopenharmony_ci  compilation_cache_ = new CompilationCache(this);
39131cb0ef41Sopenharmony_ci  descriptor_lookup_cache_ = new DescriptorLookupCache();
39141cb0ef41Sopenharmony_ci  inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this);
39151cb0ef41Sopenharmony_ci  global_handles_ = new GlobalHandles(this);
39161cb0ef41Sopenharmony_ci  eternal_handles_ = new EternalHandles();
39171cb0ef41Sopenharmony_ci  bootstrapper_ = new Bootstrapper(this);
39181cb0ef41Sopenharmony_ci  handle_scope_implementer_ = new HandleScopeImplementer(this);
39191cb0ef41Sopenharmony_ci  load_stub_cache_ = new StubCache(this);
39201cb0ef41Sopenharmony_ci  store_stub_cache_ = new StubCache(this);
39211cb0ef41Sopenharmony_ci  materialized_object_store_ = new MaterializedObjectStore(this);
39221cb0ef41Sopenharmony_ci  regexp_stack_ = new RegExpStack();
39231cb0ef41Sopenharmony_ci  date_cache_ = new DateCache();
39241cb0ef41Sopenharmony_ci  heap_profiler_ = new HeapProfiler(heap());
39251cb0ef41Sopenharmony_ci  interpreter_ = new interpreter::Interpreter(this);
39261cb0ef41Sopenharmony_ci  bigint_processor_ = bigint::Processor::New(new BigIntPlatform(this));
39271cb0ef41Sopenharmony_ci
39281cb0ef41Sopenharmony_ci  if (FLAG_lazy_compile_dispatcher) {
39291cb0ef41Sopenharmony_ci    lazy_compile_dispatcher_ = std::make_unique<LazyCompileDispatcher>(
39301cb0ef41Sopenharmony_ci        this, V8::GetCurrentPlatform(), FLAG_stack_size);
39311cb0ef41Sopenharmony_ci  }
39321cb0ef41Sopenharmony_ci  baseline_batch_compiler_ = new baseline::BaselineBatchCompiler(this);
39331cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_MAGLEV
39341cb0ef41Sopenharmony_ci  maglev_concurrent_dispatcher_ = new maglev::MaglevConcurrentDispatcher(this);
39351cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_MAGLEV
39361cb0ef41Sopenharmony_ci
39371cb0ef41Sopenharmony_ci#if USE_SIMULATOR
39381cb0ef41Sopenharmony_ci  simulator_data_ = new SimulatorData;
39391cb0ef41Sopenharmony_ci#endif
39401cb0ef41Sopenharmony_ci
39411cb0ef41Sopenharmony_ci  // Enable logging before setting up the heap
39421cb0ef41Sopenharmony_ci  logger_->SetUp(this);
39431cb0ef41Sopenharmony_ci
39441cb0ef41Sopenharmony_ci  metrics_recorder_ = std::make_shared<metrics::Recorder>();
39451cb0ef41Sopenharmony_ci
39461cb0ef41Sopenharmony_ci  {
39471cb0ef41Sopenharmony_ci    // Ensure that the thread has a valid stack guard.  The v8::Locker object
39481cb0ef41Sopenharmony_ci    // will ensure this too, but we don't have to use lockers if we are only
39491cb0ef41Sopenharmony_ci    // using one thread.
39501cb0ef41Sopenharmony_ci    ExecutionAccess lock(this);
39511cb0ef41Sopenharmony_ci    stack_guard()->InitThread(lock);
39521cb0ef41Sopenharmony_ci  }
39531cb0ef41Sopenharmony_ci
39541cb0ef41Sopenharmony_ci  // Create LocalIsolate/LocalHeap for the main thread and set state to Running.
39551cb0ef41Sopenharmony_ci  main_thread_local_isolate_.reset(new LocalIsolate(this, ThreadKind::kMain));
39561cb0ef41Sopenharmony_ci
39571cb0ef41Sopenharmony_ci  {
39581cb0ef41Sopenharmony_ci    IgnoreLocalGCRequests ignore_gc_requests(heap());
39591cb0ef41Sopenharmony_ci    main_thread_local_heap()->Unpark();
39601cb0ef41Sopenharmony_ci  }
39611cb0ef41Sopenharmony_ci
39621cb0ef41Sopenharmony_ci  // Lock clients_mutex_ in order to prevent shared GCs from other clients
39631cb0ef41Sopenharmony_ci  // during deserialization.
39641cb0ef41Sopenharmony_ci  base::Optional<base::MutexGuard> clients_guard;
39651cb0ef41Sopenharmony_ci
39661cb0ef41Sopenharmony_ci  if (shared_isolate_) {
39671cb0ef41Sopenharmony_ci    clients_guard.emplace(&shared_isolate_->global_safepoint()->clients_mutex_);
39681cb0ef41Sopenharmony_ci  }
39691cb0ef41Sopenharmony_ci
39701cb0ef41Sopenharmony_ci  // The main thread LocalHeap needs to be set up when attaching to the shared
39711cb0ef41Sopenharmony_ci  // isolate. Otherwise a global safepoint would find an isolate without
39721cb0ef41Sopenharmony_ci  // LocalHeaps and not wait until this thread is ready for a GC.
39731cb0ef41Sopenharmony_ci  AttachToSharedIsolate();
39741cb0ef41Sopenharmony_ci
39751cb0ef41Sopenharmony_ci  // SetUp the object heap.
39761cb0ef41Sopenharmony_ci  DCHECK(!heap_.HasBeenSetUp());
39771cb0ef41Sopenharmony_ci  heap_.SetUp(main_thread_local_heap());
39781cb0ef41Sopenharmony_ci  ReadOnlyHeap::SetUp(this, read_only_snapshot_data, can_rehash);
39791cb0ef41Sopenharmony_ci  heap_.SetUpSpaces(&isolate_data_.new_allocation_info_,
39801cb0ef41Sopenharmony_ci                    &isolate_data_.old_allocation_info_);
39811cb0ef41Sopenharmony_ci
39821cb0ef41Sopenharmony_ci  if (OwnsStringTable()) {
39831cb0ef41Sopenharmony_ci    string_table_ = std::make_shared<StringTable>(this);
39841cb0ef41Sopenharmony_ci  } else {
39851cb0ef41Sopenharmony_ci    // Only refer to shared string table after attaching to the shared isolate.
39861cb0ef41Sopenharmony_ci    DCHECK_NOT_NULL(shared_isolate());
39871cb0ef41Sopenharmony_ci    string_table_ = shared_isolate()->string_table_;
39881cb0ef41Sopenharmony_ci  }
39891cb0ef41Sopenharmony_ci
39901cb0ef41Sopenharmony_ci  if (V8_SHORT_BUILTIN_CALLS_BOOL && FLAG_short_builtin_calls) {
39911cb0ef41Sopenharmony_ci    // Check if the system has more than 4GB of physical memory by comparing the
39921cb0ef41Sopenharmony_ci    // old space size with respective threshold value.
39931cb0ef41Sopenharmony_ci    //
39941cb0ef41Sopenharmony_ci    // Additionally, enable if there is already a process-wide CodeRange that
39951cb0ef41Sopenharmony_ci    // has re-embedded builtins.
39961cb0ef41Sopenharmony_ci    is_short_builtin_calls_enabled_ = (heap_.MaxOldGenerationSize() >=
39971cb0ef41Sopenharmony_ci                                       kShortBuiltinCallsOldSpaceSizeThreshold);
39981cb0ef41Sopenharmony_ci    if (COMPRESS_POINTERS_IN_SHARED_CAGE_BOOL) {
39991cb0ef41Sopenharmony_ci      std::shared_ptr<CodeRange> code_range =
40001cb0ef41Sopenharmony_ci          CodeRange::GetProcessWideCodeRange();
40011cb0ef41Sopenharmony_ci      if (code_range && code_range->embedded_blob_code_copy() != nullptr) {
40021cb0ef41Sopenharmony_ci        is_short_builtin_calls_enabled_ = true;
40031cb0ef41Sopenharmony_ci      }
40041cb0ef41Sopenharmony_ci    }
40051cb0ef41Sopenharmony_ci    if (V8_ENABLE_NEAR_CODE_RANGE_BOOL) {
40061cb0ef41Sopenharmony_ci      // The short builtin calls could still be enabled if allocated code range
40071cb0ef41Sopenharmony_ci      // is close enough to embedded builtins so that the latter could be
40081cb0ef41Sopenharmony_ci      // reached using pc-relative (short) calls/jumps.
40091cb0ef41Sopenharmony_ci      is_short_builtin_calls_enabled_ |=
40101cb0ef41Sopenharmony_ci          GetShortBuiltinsCallRegion().contains(heap_.code_region());
40111cb0ef41Sopenharmony_ci    }
40121cb0ef41Sopenharmony_ci  }
40131cb0ef41Sopenharmony_ci#ifdef V8_EXTERNAL_CODE_SPACE
40141cb0ef41Sopenharmony_ci  if (heap_.code_range()) {
40151cb0ef41Sopenharmony_ci    code_cage_base_ = GetPtrComprCageBaseAddress(heap_.code_range()->base());
40161cb0ef41Sopenharmony_ci  } else {
40171cb0ef41Sopenharmony_ci    code_cage_base_ = cage_base();
40181cb0ef41Sopenharmony_ci  }
40191cb0ef41Sopenharmony_ci#endif  // V8_EXTERNAL_CODE_SPACE
40201cb0ef41Sopenharmony_ci
40211cb0ef41Sopenharmony_ci  isolate_data_.external_reference_table()->Init(this);
40221cb0ef41Sopenharmony_ci
40231cb0ef41Sopenharmony_ci#ifdef V8_SANDBOXED_EXTERNAL_POINTERS
40241cb0ef41Sopenharmony_ci  external_pointer_table().Init(this);
40251cb0ef41Sopenharmony_ci#endif  // V8_SANDBOXED_EXTERNAL_POINTERS
40261cb0ef41Sopenharmony_ci
40271cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
40281cb0ef41Sopenharmony_ci  wasm::GetWasmEngine()->AddIsolate(this);
40291cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
40301cb0ef41Sopenharmony_ci
40311cb0ef41Sopenharmony_ci  if (setup_delegate_ == nullptr) {
40321cb0ef41Sopenharmony_ci    setup_delegate_ = new SetupIsolateDelegate(create_heap_objects);
40331cb0ef41Sopenharmony_ci  }
40341cb0ef41Sopenharmony_ci
40351cb0ef41Sopenharmony_ci  if (!FLAG_inline_new) heap_.DisableInlineAllocation();
40361cb0ef41Sopenharmony_ci
40371cb0ef41Sopenharmony_ci  if (!setup_delegate_->SetupHeap(&heap_)) {
40381cb0ef41Sopenharmony_ci    V8::FatalProcessOutOfMemory(this, "heap object creation");
40391cb0ef41Sopenharmony_ci  }
40401cb0ef41Sopenharmony_ci
40411cb0ef41Sopenharmony_ci  if (create_heap_objects) {
40421cb0ef41Sopenharmony_ci    // Terminate the startup and shared heap object caches so we can iterate.
40431cb0ef41Sopenharmony_ci    startup_object_cache_.push_back(ReadOnlyRoots(this).undefined_value());
40441cb0ef41Sopenharmony_ci    shared_heap_object_cache_.push_back(ReadOnlyRoots(this).undefined_value());
40451cb0ef41Sopenharmony_ci  }
40461cb0ef41Sopenharmony_ci
40471cb0ef41Sopenharmony_ci  InitializeThreadLocal();
40481cb0ef41Sopenharmony_ci
40491cb0ef41Sopenharmony_ci  // Profiler has to be created after ThreadLocal is initialized
40501cb0ef41Sopenharmony_ci  // because it makes use of interrupts.
40511cb0ef41Sopenharmony_ci  tracing_cpu_profiler_.reset(new TracingCpuProfilerImpl(this));
40521cb0ef41Sopenharmony_ci
40531cb0ef41Sopenharmony_ci  bootstrapper_->Initialize(create_heap_objects);
40541cb0ef41Sopenharmony_ci
40551cb0ef41Sopenharmony_ci  if (create_heap_objects) {
40561cb0ef41Sopenharmony_ci    builtins_constants_table_builder_ = new BuiltinsConstantsTableBuilder(this);
40571cb0ef41Sopenharmony_ci
40581cb0ef41Sopenharmony_ci    setup_delegate_->SetupBuiltins(this);
40591cb0ef41Sopenharmony_ci
40601cb0ef41Sopenharmony_ci#ifndef V8_TARGET_ARCH_ARM
40611cb0ef41Sopenharmony_ci    // Store the interpreter entry trampoline on the root list. It is used as a
40621cb0ef41Sopenharmony_ci    // template for further copies that may later be created to help profile
40631cb0ef41Sopenharmony_ci    // interpreted code.
40641cb0ef41Sopenharmony_ci    // We currently cannot do this on arm due to RELATIVE_CODE_TARGETs
40651cb0ef41Sopenharmony_ci    // assuming that all possible Code targets may be addressed with an int24
40661cb0ef41Sopenharmony_ci    // offset, effectively limiting code space size to 32MB. We can guarantee
40671cb0ef41Sopenharmony_ci    // this at mksnapshot-time, but not at runtime.
40681cb0ef41Sopenharmony_ci    // See also: https://crbug.com/v8/8713.
40691cb0ef41Sopenharmony_ci    heap_.SetInterpreterEntryTrampolineForProfiling(
40701cb0ef41Sopenharmony_ci        FromCodeT(builtins()->code(Builtin::kInterpreterEntryTrampoline)));
40711cb0ef41Sopenharmony_ci#endif
40721cb0ef41Sopenharmony_ci
40731cb0ef41Sopenharmony_ci    builtins_constants_table_builder_->Finalize();
40741cb0ef41Sopenharmony_ci    delete builtins_constants_table_builder_;
40751cb0ef41Sopenharmony_ci    builtins_constants_table_builder_ = nullptr;
40761cb0ef41Sopenharmony_ci
40771cb0ef41Sopenharmony_ci    CreateAndSetEmbeddedBlob();
40781cb0ef41Sopenharmony_ci  } else {
40791cb0ef41Sopenharmony_ci    setup_delegate_->SetupBuiltins(this);
40801cb0ef41Sopenharmony_ci    MaybeRemapEmbeddedBuiltinsIntoCodeRange();
40811cb0ef41Sopenharmony_ci  }
40821cb0ef41Sopenharmony_ci
40831cb0ef41Sopenharmony_ci  // Initialize custom memcopy and memmove functions (must happen after
40841cb0ef41Sopenharmony_ci  // embedded blob setup).
40851cb0ef41Sopenharmony_ci  init_memcopy_functions();
40861cb0ef41Sopenharmony_ci
40871cb0ef41Sopenharmony_ci  if (FLAG_log_internal_timer_events) {
40881cb0ef41Sopenharmony_ci    set_event_logger(Logger::DefaultEventLoggerSentinel);
40891cb0ef41Sopenharmony_ci  }
40901cb0ef41Sopenharmony_ci
40911cb0ef41Sopenharmony_ci  if (FLAG_trace_turbo || FLAG_trace_turbo_graph || FLAG_turbo_profiling) {
40921cb0ef41Sopenharmony_ci    PrintF("Concurrent recompilation has been disabled for tracing.\n");
40931cb0ef41Sopenharmony_ci  } else if (OptimizingCompileDispatcher::Enabled()) {
40941cb0ef41Sopenharmony_ci    optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this);
40951cb0ef41Sopenharmony_ci  }
40961cb0ef41Sopenharmony_ci
40971cb0ef41Sopenharmony_ci  // Initialize before deserialization since collections may occur,
40981cb0ef41Sopenharmony_ci  // clearing/updating ICs (and thus affecting tiering decisions).
40991cb0ef41Sopenharmony_ci  tiering_manager_ = new TieringManager(this);
41001cb0ef41Sopenharmony_ci
41011cb0ef41Sopenharmony_ci  // If we are deserializing, read the state into the now-empty heap.
41021cb0ef41Sopenharmony_ci  {
41031cb0ef41Sopenharmony_ci    CodePageCollectionMemoryModificationScope modification_scope(heap());
41041cb0ef41Sopenharmony_ci
41051cb0ef41Sopenharmony_ci    if (create_heap_objects) {
41061cb0ef41Sopenharmony_ci      heap_.read_only_space()->ClearStringPaddingIfNeeded();
41071cb0ef41Sopenharmony_ci      read_only_heap_->OnCreateHeapObjectsComplete(this);
41081cb0ef41Sopenharmony_ci    } else {
41091cb0ef41Sopenharmony_ci      SharedHeapDeserializer shared_heap_deserializer(
41101cb0ef41Sopenharmony_ci          this, shared_heap_snapshot_data, can_rehash);
41111cb0ef41Sopenharmony_ci      shared_heap_deserializer.DeserializeIntoIsolate();
41121cb0ef41Sopenharmony_ci
41131cb0ef41Sopenharmony_ci      StartupDeserializer startup_deserializer(this, startup_snapshot_data,
41141cb0ef41Sopenharmony_ci                                               can_rehash);
41151cb0ef41Sopenharmony_ci      startup_deserializer.DeserializeIntoIsolate();
41161cb0ef41Sopenharmony_ci    }
41171cb0ef41Sopenharmony_ci    load_stub_cache_->Initialize();
41181cb0ef41Sopenharmony_ci    store_stub_cache_->Initialize();
41191cb0ef41Sopenharmony_ci    interpreter_->Initialize();
41201cb0ef41Sopenharmony_ci    heap_.NotifyDeserializationComplete();
41211cb0ef41Sopenharmony_ci  }
41221cb0ef41Sopenharmony_ci
41231cb0ef41Sopenharmony_ci#ifdef VERIFY_HEAP
41241cb0ef41Sopenharmony_ci  if (FLAG_verify_heap) {
41251cb0ef41Sopenharmony_ci    heap_.VerifyReadOnlyHeap();
41261cb0ef41Sopenharmony_ci  }
41271cb0ef41Sopenharmony_ci#endif
41281cb0ef41Sopenharmony_ci
41291cb0ef41Sopenharmony_ci  delete setup_delegate_;
41301cb0ef41Sopenharmony_ci  setup_delegate_ = nullptr;
41311cb0ef41Sopenharmony_ci
41321cb0ef41Sopenharmony_ci  Builtins::InitializeIsolateDataTables(this);
41331cb0ef41Sopenharmony_ci
41341cb0ef41Sopenharmony_ci  // Extra steps in the logger after the heap has been set up.
41351cb0ef41Sopenharmony_ci  logger_->LateSetup(this);
41361cb0ef41Sopenharmony_ci
41371cb0ef41Sopenharmony_ci#ifdef DEBUG
41381cb0ef41Sopenharmony_ci  // Verify that the current heap state (usually deserialized from the snapshot)
41391cb0ef41Sopenharmony_ci  // is compatible with the embedded blob. If this DCHECK fails, we've likely
41401cb0ef41Sopenharmony_ci  // loaded a snapshot generated by a different V8 version or build-time
41411cb0ef41Sopenharmony_ci  // configuration.
41421cb0ef41Sopenharmony_ci  if (!IsolateIsCompatibleWithEmbeddedBlob(this)) {
41431cb0ef41Sopenharmony_ci    FATAL(
41441cb0ef41Sopenharmony_ci        "The Isolate is incompatible with the embedded blob. This is usually "
41451cb0ef41Sopenharmony_ci        "caused by incorrect usage of mksnapshot. When generating custom "
41461cb0ef41Sopenharmony_ci        "snapshots, embedders must ensure they pass the same flags as during "
41471cb0ef41Sopenharmony_ci        "the V8 build process (e.g.: --turbo-instruction-scheduling).");
41481cb0ef41Sopenharmony_ci  }
41491cb0ef41Sopenharmony_ci#endif  // DEBUG
41501cb0ef41Sopenharmony_ci
41511cb0ef41Sopenharmony_ci#ifndef V8_TARGET_ARCH_ARM
41521cb0ef41Sopenharmony_ci  // The IET for profiling should always be a full on-heap Code object.
41531cb0ef41Sopenharmony_ci  DCHECK(!Code::cast(heap_.interpreter_entry_trampoline_for_profiling())
41541cb0ef41Sopenharmony_ci              .is_off_heap_trampoline());
41551cb0ef41Sopenharmony_ci#endif  // V8_TARGET_ARCH_ARM
41561cb0ef41Sopenharmony_ci
41571cb0ef41Sopenharmony_ci  if (FLAG_print_builtin_code) builtins()->PrintBuiltinCode();
41581cb0ef41Sopenharmony_ci  if (FLAG_print_builtin_size) builtins()->PrintBuiltinSize();
41591cb0ef41Sopenharmony_ci
41601cb0ef41Sopenharmony_ci  // Finish initialization of ThreadLocal after deserialization is done.
41611cb0ef41Sopenharmony_ci  clear_pending_exception();
41621cb0ef41Sopenharmony_ci  clear_pending_message();
41631cb0ef41Sopenharmony_ci  clear_scheduled_exception();
41641cb0ef41Sopenharmony_ci
41651cb0ef41Sopenharmony_ci  // Quiet the heap NaN if needed on target platform.
41661cb0ef41Sopenharmony_ci  if (!create_heap_objects)
41671cb0ef41Sopenharmony_ci    Assembler::QuietNaN(ReadOnlyRoots(this).nan_value());
41681cb0ef41Sopenharmony_ci
41691cb0ef41Sopenharmony_ci  if (FLAG_trace_turbo) {
41701cb0ef41Sopenharmony_ci    // Create an empty file.
41711cb0ef41Sopenharmony_ci    std::ofstream(GetTurboCfgFileName(this).c_str(), std::ios_base::trunc);
41721cb0ef41Sopenharmony_ci  }
41731cb0ef41Sopenharmony_ci
41741cb0ef41Sopenharmony_ci  {
41751cb0ef41Sopenharmony_ci    HandleScope scope(this);
41761cb0ef41Sopenharmony_ci    ast_string_constants_ = new AstStringConstants(this, HashSeed(this));
41771cb0ef41Sopenharmony_ci  }
41781cb0ef41Sopenharmony_ci
41791cb0ef41Sopenharmony_ci  initialized_from_snapshot_ = !create_heap_objects;
41801cb0ef41Sopenharmony_ci
41811cb0ef41Sopenharmony_ci  if (FLAG_stress_sampling_allocation_profiler > 0) {
41821cb0ef41Sopenharmony_ci    uint64_t sample_interval = FLAG_stress_sampling_allocation_profiler;
41831cb0ef41Sopenharmony_ci    int stack_depth = 128;
41841cb0ef41Sopenharmony_ci    v8::HeapProfiler::SamplingFlags sampling_flags =
41851cb0ef41Sopenharmony_ci        v8::HeapProfiler::SamplingFlags::kSamplingForceGC;
41861cb0ef41Sopenharmony_ci    heap_profiler()->StartSamplingHeapProfiler(sample_interval, stack_depth,
41871cb0ef41Sopenharmony_ci                                               sampling_flags);
41881cb0ef41Sopenharmony_ci  }
41891cb0ef41Sopenharmony_ci
41901cb0ef41Sopenharmony_ci#if defined(V8_OS_WIN64)
41911cb0ef41Sopenharmony_ci  if (win64_unwindinfo::CanRegisterUnwindInfoForNonABICompliantCodeRange() &&
41921cb0ef41Sopenharmony_ci      heap()->code_range()->AtomicIncrementUnwindInfoUseCount() == 0) {
41931cb0ef41Sopenharmony_ci    const base::AddressRegion& code_region = heap()->code_region();
41941cb0ef41Sopenharmony_ci    void* start = reinterpret_cast<void*>(code_region.begin());
41951cb0ef41Sopenharmony_ci    size_t size_in_bytes = code_region.size();
41961cb0ef41Sopenharmony_ci    win64_unwindinfo::RegisterNonABICompliantCodeRange(start, size_in_bytes);
41971cb0ef41Sopenharmony_ci  }
41981cb0ef41Sopenharmony_ci#endif  // V8_OS_WIN64
41991cb0ef41Sopenharmony_ci
42001cb0ef41Sopenharmony_ci  if (create_heap_objects && FLAG_profile_deserialization) {
42011cb0ef41Sopenharmony_ci    double ms = timer.Elapsed().InMillisecondsF();
42021cb0ef41Sopenharmony_ci    PrintF("[Initializing isolate from scratch took %0.3f ms]\n", ms);
42031cb0ef41Sopenharmony_ci  }
42041cb0ef41Sopenharmony_ci
42051cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_WEBASSEMBLY
42061cb0ef41Sopenharmony_ci  if (FLAG_experimental_wasm_stack_switching) {
42071cb0ef41Sopenharmony_ci    std::unique_ptr<wasm::StackMemory> stack(
42081cb0ef41Sopenharmony_ci        wasm::StackMemory::GetCurrentStackView(this));
42091cb0ef41Sopenharmony_ci    this->wasm_stacks() = stack.get();
42101cb0ef41Sopenharmony_ci    if (FLAG_trace_wasm_stack_switching) {
42111cb0ef41Sopenharmony_ci      PrintF("Set up native stack object (limit: %p, base: %p)\n",
42121cb0ef41Sopenharmony_ci             stack->jslimit(), reinterpret_cast<void*>(stack->base()));
42131cb0ef41Sopenharmony_ci    }
42141cb0ef41Sopenharmony_ci    HandleScope scope(this);
42151cb0ef41Sopenharmony_ci    Handle<WasmContinuationObject> continuation =
42161cb0ef41Sopenharmony_ci        WasmContinuationObject::New(this, std::move(stack));
42171cb0ef41Sopenharmony_ci    heap()
42181cb0ef41Sopenharmony_ci        ->roots_table()
42191cb0ef41Sopenharmony_ci        .slot(RootIndex::kActiveContinuation)
42201cb0ef41Sopenharmony_ci        .store(*continuation);
42211cb0ef41Sopenharmony_ci  }
42221cb0ef41Sopenharmony_ci#endif
42231cb0ef41Sopenharmony_ci
42241cb0ef41Sopenharmony_ci  initialized_ = true;
42251cb0ef41Sopenharmony_ci
42261cb0ef41Sopenharmony_ci  return true;
42271cb0ef41Sopenharmony_ci}
42281cb0ef41Sopenharmony_ci
42291cb0ef41Sopenharmony_civoid Isolate::Enter() {
42301cb0ef41Sopenharmony_ci  Isolate* current_isolate = nullptr;
42311cb0ef41Sopenharmony_ci  PerIsolateThreadData* current_data = CurrentPerIsolateThreadData();
42321cb0ef41Sopenharmony_ci  if (current_data != nullptr) {
42331cb0ef41Sopenharmony_ci    current_isolate = current_data->isolate_;
42341cb0ef41Sopenharmony_ci    DCHECK_NOT_NULL(current_isolate);
42351cb0ef41Sopenharmony_ci    if (current_isolate == this) {
42361cb0ef41Sopenharmony_ci      DCHECK(Current() == this);
42371cb0ef41Sopenharmony_ci      DCHECK_NOT_NULL(entry_stack_);
42381cb0ef41Sopenharmony_ci      DCHECK(entry_stack_->previous_thread_data == nullptr ||
42391cb0ef41Sopenharmony_ci             entry_stack_->previous_thread_data->thread_id() ==
42401cb0ef41Sopenharmony_ci                 ThreadId::Current());
42411cb0ef41Sopenharmony_ci      // Same thread re-enters the isolate, no need to re-init anything.
42421cb0ef41Sopenharmony_ci      entry_stack_->entry_count++;
42431cb0ef41Sopenharmony_ci      return;
42441cb0ef41Sopenharmony_ci    }
42451cb0ef41Sopenharmony_ci  }
42461cb0ef41Sopenharmony_ci
42471cb0ef41Sopenharmony_ci  PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread();
42481cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(data);
42491cb0ef41Sopenharmony_ci  DCHECK(data->isolate_ == this);
42501cb0ef41Sopenharmony_ci
42511cb0ef41Sopenharmony_ci  EntryStackItem* item =
42521cb0ef41Sopenharmony_ci      new EntryStackItem(current_data, current_isolate, entry_stack_);
42531cb0ef41Sopenharmony_ci  entry_stack_ = item;
42541cb0ef41Sopenharmony_ci
42551cb0ef41Sopenharmony_ci  SetIsolateThreadLocals(this, data);
42561cb0ef41Sopenharmony_ci
42571cb0ef41Sopenharmony_ci  // In case it's the first time some thread enters the isolate.
42581cb0ef41Sopenharmony_ci  set_thread_id(data->thread_id());
42591cb0ef41Sopenharmony_ci}
42601cb0ef41Sopenharmony_ci
42611cb0ef41Sopenharmony_civoid Isolate::Exit() {
42621cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(entry_stack_);
42631cb0ef41Sopenharmony_ci  DCHECK(entry_stack_->previous_thread_data == nullptr ||
42641cb0ef41Sopenharmony_ci         entry_stack_->previous_thread_data->thread_id() ==
42651cb0ef41Sopenharmony_ci             ThreadId::Current());
42661cb0ef41Sopenharmony_ci
42671cb0ef41Sopenharmony_ci  if (--entry_stack_->entry_count > 0) return;
42681cb0ef41Sopenharmony_ci
42691cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(CurrentPerIsolateThreadData());
42701cb0ef41Sopenharmony_ci  DCHECK(CurrentPerIsolateThreadData()->isolate_ == this);
42711cb0ef41Sopenharmony_ci
42721cb0ef41Sopenharmony_ci  // Pop the stack.
42731cb0ef41Sopenharmony_ci  EntryStackItem* item = entry_stack_;
42741cb0ef41Sopenharmony_ci  entry_stack_ = item->previous_item;
42751cb0ef41Sopenharmony_ci
42761cb0ef41Sopenharmony_ci  PerIsolateThreadData* previous_thread_data = item->previous_thread_data;
42771cb0ef41Sopenharmony_ci  Isolate* previous_isolate = item->previous_isolate;
42781cb0ef41Sopenharmony_ci
42791cb0ef41Sopenharmony_ci  delete item;
42801cb0ef41Sopenharmony_ci
42811cb0ef41Sopenharmony_ci  // Reinit the current thread for the isolate it was running before this one.
42821cb0ef41Sopenharmony_ci  SetIsolateThreadLocals(previous_isolate, previous_thread_data);
42831cb0ef41Sopenharmony_ci}
42841cb0ef41Sopenharmony_ci
42851cb0ef41Sopenharmony_cistd::unique_ptr<PersistentHandles> Isolate::NewPersistentHandles() {
42861cb0ef41Sopenharmony_ci  return std::make_unique<PersistentHandles>(this);
42871cb0ef41Sopenharmony_ci}
42881cb0ef41Sopenharmony_ci
42891cb0ef41Sopenharmony_civoid Isolate::DumpAndResetStats() {
42901cb0ef41Sopenharmony_ci  if (FLAG_trace_turbo_stack_accesses) {
42911cb0ef41Sopenharmony_ci    StdoutStream os;
42921cb0ef41Sopenharmony_ci    uint64_t total_loads = 0;
42931cb0ef41Sopenharmony_ci    uint64_t total_stores = 0;
42941cb0ef41Sopenharmony_ci    os << "=== Stack access counters === " << std::endl;
42951cb0ef41Sopenharmony_ci    if (!stack_access_count_map) {
42961cb0ef41Sopenharmony_ci      os << "No stack accesses in optimized/wasm functions found.";
42971cb0ef41Sopenharmony_ci    } else {
42981cb0ef41Sopenharmony_ci      DCHECK_NOT_NULL(stack_access_count_map);
42991cb0ef41Sopenharmony_ci      os << "Number of optimized/wasm stack-access functions: "
43001cb0ef41Sopenharmony_ci         << stack_access_count_map->size() << std::endl;
43011cb0ef41Sopenharmony_ci      for (auto it = stack_access_count_map->cbegin();
43021cb0ef41Sopenharmony_ci           it != stack_access_count_map->cend(); it++) {
43031cb0ef41Sopenharmony_ci        std::string function_name((*it).first);
43041cb0ef41Sopenharmony_ci        std::pair<uint64_t, uint64_t> per_func_count = (*it).second;
43051cb0ef41Sopenharmony_ci        os << "Name: " << function_name << ", Loads: " << per_func_count.first
43061cb0ef41Sopenharmony_ci           << ", Stores: " << per_func_count.second << std::endl;
43071cb0ef41Sopenharmony_ci        total_loads += per_func_count.first;
43081cb0ef41Sopenharmony_ci        total_stores += per_func_count.second;
43091cb0ef41Sopenharmony_ci      }
43101cb0ef41Sopenharmony_ci      os << "Total Loads: " << total_loads << ", Total Stores: " << total_stores
43111cb0ef41Sopenharmony_ci         << std::endl;
43121cb0ef41Sopenharmony_ci      stack_access_count_map = nullptr;
43131cb0ef41Sopenharmony_ci    }
43141cb0ef41Sopenharmony_ci  }
43151cb0ef41Sopenharmony_ci  if (turbo_statistics() != nullptr) {
43161cb0ef41Sopenharmony_ci    DCHECK(FLAG_turbo_stats || FLAG_turbo_stats_nvp);
43171cb0ef41Sopenharmony_ci    StdoutStream os;
43181cb0ef41Sopenharmony_ci    if (FLAG_turbo_stats) {
43191cb0ef41Sopenharmony_ci      AsPrintableStatistics ps = {*turbo_statistics(), false};
43201cb0ef41Sopenharmony_ci      os << ps << std::endl;
43211cb0ef41Sopenharmony_ci    }
43221cb0ef41Sopenharmony_ci    if (FLAG_turbo_stats_nvp) {
43231cb0ef41Sopenharmony_ci      AsPrintableStatistics ps = {*turbo_statistics(), true};
43241cb0ef41Sopenharmony_ci      os << ps << std::endl;
43251cb0ef41Sopenharmony_ci    }
43261cb0ef41Sopenharmony_ci    delete turbo_statistics_;
43271cb0ef41Sopenharmony_ci    turbo_statistics_ = nullptr;
43281cb0ef41Sopenharmony_ci  }
43291cb0ef41Sopenharmony_ci#if V8_ENABLE_WEBASSEMBLY
43301cb0ef41Sopenharmony_ci  // TODO(7424): There is no public API for the {WasmEngine} yet. So for now we
43311cb0ef41Sopenharmony_ci  // just dump and reset the engines statistics together with the Isolate.
43321cb0ef41Sopenharmony_ci  if (FLAG_turbo_stats_wasm) {
43331cb0ef41Sopenharmony_ci    wasm::GetWasmEngine()->DumpAndResetTurboStatistics();
43341cb0ef41Sopenharmony_ci  }
43351cb0ef41Sopenharmony_ci#endif  // V8_ENABLE_WEBASSEMBLY
43361cb0ef41Sopenharmony_ci#if V8_RUNTIME_CALL_STATS
43371cb0ef41Sopenharmony_ci  if (V8_UNLIKELY(TracingFlags::runtime_stats.load(std::memory_order_relaxed) ==
43381cb0ef41Sopenharmony_ci                  v8::tracing::TracingCategoryObserver::ENABLED_BY_NATIVE)) {
43391cb0ef41Sopenharmony_ci    counters()->worker_thread_runtime_call_stats()->AddToMainTable(
43401cb0ef41Sopenharmony_ci        counters()->runtime_call_stats());
43411cb0ef41Sopenharmony_ci    counters()->runtime_call_stats()->Print();
43421cb0ef41Sopenharmony_ci    counters()->runtime_call_stats()->Reset();
43431cb0ef41Sopenharmony_ci  }
43441cb0ef41Sopenharmony_ci#endif  // V8_RUNTIME_CALL_STATS
43451cb0ef41Sopenharmony_ci  if (BasicBlockProfiler::Get()->HasData(this)) {
43461cb0ef41Sopenharmony_ci    StdoutStream out;
43471cb0ef41Sopenharmony_ci    BasicBlockProfiler::Get()->Print(out, this);
43481cb0ef41Sopenharmony_ci    BasicBlockProfiler::Get()->ResetCounts(this);
43491cb0ef41Sopenharmony_ci  }
43501cb0ef41Sopenharmony_ci}
43511cb0ef41Sopenharmony_ci
43521cb0ef41Sopenharmony_civoid Isolate::AbortConcurrentOptimization(BlockingBehavior behavior) {
43531cb0ef41Sopenharmony_ci  if (concurrent_recompilation_enabled()) {
43541cb0ef41Sopenharmony_ci    DisallowGarbageCollection no_recursive_gc;
43551cb0ef41Sopenharmony_ci    optimizing_compile_dispatcher()->Flush(behavior);
43561cb0ef41Sopenharmony_ci  }
43571cb0ef41Sopenharmony_ci}
43581cb0ef41Sopenharmony_ci
43591cb0ef41Sopenharmony_ciCompilationStatistics* Isolate::GetTurboStatistics() {
43601cb0ef41Sopenharmony_ci  if (turbo_statistics() == nullptr)
43611cb0ef41Sopenharmony_ci    set_turbo_statistics(new CompilationStatistics());
43621cb0ef41Sopenharmony_ci  return turbo_statistics();
43631cb0ef41Sopenharmony_ci}
43641cb0ef41Sopenharmony_ci
43651cb0ef41Sopenharmony_ciCodeTracer* Isolate::GetCodeTracer() {
43661cb0ef41Sopenharmony_ci  if (code_tracer() == nullptr) set_code_tracer(new CodeTracer(id()));
43671cb0ef41Sopenharmony_ci  return code_tracer();
43681cb0ef41Sopenharmony_ci}
43691cb0ef41Sopenharmony_ci
43701cb0ef41Sopenharmony_cibool Isolate::use_optimizer() {
43711cb0ef41Sopenharmony_ci  // TODO(v8:7700): Update this predicate for a world with multiple tiers.
43721cb0ef41Sopenharmony_ci  return (FLAG_opt || FLAG_maglev) && !serializer_enabled_ &&
43731cb0ef41Sopenharmony_ci         CpuFeatures::SupportsOptimizer() && !is_precise_count_code_coverage();
43741cb0ef41Sopenharmony_ci}
43751cb0ef41Sopenharmony_ci
43761cb0ef41Sopenharmony_civoid Isolate::IncreaseTotalRegexpCodeGenerated(Handle<HeapObject> code) {
43771cb0ef41Sopenharmony_ci  PtrComprCageBase cage_base(this);
43781cb0ef41Sopenharmony_ci  DCHECK(code->IsCode(cage_base) || code->IsByteArray(cage_base));
43791cb0ef41Sopenharmony_ci  total_regexp_code_generated_ += code->Size(cage_base);
43801cb0ef41Sopenharmony_ci}
43811cb0ef41Sopenharmony_ci
43821cb0ef41Sopenharmony_cibool Isolate::NeedsDetailedOptimizedCodeLineInfo() const {
43831cb0ef41Sopenharmony_ci  return NeedsSourcePositionsForProfiling() ||
43841cb0ef41Sopenharmony_ci         detailed_source_positions_for_profiling();
43851cb0ef41Sopenharmony_ci}
43861cb0ef41Sopenharmony_ci
43871cb0ef41Sopenharmony_cibool Isolate::NeedsSourcePositionsForProfiling() const {
43881cb0ef41Sopenharmony_ci  return
43891cb0ef41Sopenharmony_ci      // Static conditions.
43901cb0ef41Sopenharmony_ci      FLAG_trace_deopt || FLAG_trace_turbo || FLAG_trace_turbo_graph ||
43911cb0ef41Sopenharmony_ci      FLAG_turbo_profiling || FLAG_perf_prof || FLAG_log_maps || FLAG_log_ic ||
43921cb0ef41Sopenharmony_ci      // Dynamic conditions; changing any of these conditions triggers source
43931cb0ef41Sopenharmony_ci      // position collection for the entire heap
43941cb0ef41Sopenharmony_ci      // (CollectSourcePositionsForAllBytecodeArrays).
43951cb0ef41Sopenharmony_ci      is_profiling() || debug_->is_active() || logger_->is_logging();
43961cb0ef41Sopenharmony_ci}
43971cb0ef41Sopenharmony_ci
43981cb0ef41Sopenharmony_civoid Isolate::SetFeedbackVectorsForProfilingTools(Object value) {
43991cb0ef41Sopenharmony_ci  DCHECK(value.IsUndefined(this) || value.IsArrayList());
44001cb0ef41Sopenharmony_ci  heap()->set_feedback_vectors_for_profiling_tools(value);
44011cb0ef41Sopenharmony_ci}
44021cb0ef41Sopenharmony_ci
44031cb0ef41Sopenharmony_civoid Isolate::MaybeInitializeVectorListFromHeap() {
44041cb0ef41Sopenharmony_ci  if (!heap()->feedback_vectors_for_profiling_tools().IsUndefined(this)) {
44051cb0ef41Sopenharmony_ci    // Already initialized, return early.
44061cb0ef41Sopenharmony_ci    DCHECK(heap()->feedback_vectors_for_profiling_tools().IsArrayList());
44071cb0ef41Sopenharmony_ci    return;
44081cb0ef41Sopenharmony_ci  }
44091cb0ef41Sopenharmony_ci
44101cb0ef41Sopenharmony_ci  // Collect existing feedback vectors.
44111cb0ef41Sopenharmony_ci  std::vector<Handle<FeedbackVector>> vectors;
44121cb0ef41Sopenharmony_ci
44131cb0ef41Sopenharmony_ci  {
44141cb0ef41Sopenharmony_ci    HeapObjectIterator heap_iterator(heap());
44151cb0ef41Sopenharmony_ci    for (HeapObject current_obj = heap_iterator.Next(); !current_obj.is_null();
44161cb0ef41Sopenharmony_ci         current_obj = heap_iterator.Next()) {
44171cb0ef41Sopenharmony_ci      if (!current_obj.IsFeedbackVector()) continue;
44181cb0ef41Sopenharmony_ci
44191cb0ef41Sopenharmony_ci      FeedbackVector vector = FeedbackVector::cast(current_obj);
44201cb0ef41Sopenharmony_ci      SharedFunctionInfo shared = vector.shared_function_info();
44211cb0ef41Sopenharmony_ci
44221cb0ef41Sopenharmony_ci      // No need to preserve the feedback vector for non-user-visible functions.
44231cb0ef41Sopenharmony_ci      if (!shared.IsSubjectToDebugging()) continue;
44241cb0ef41Sopenharmony_ci
44251cb0ef41Sopenharmony_ci      vectors.emplace_back(vector, this);
44261cb0ef41Sopenharmony_ci    }
44271cb0ef41Sopenharmony_ci  }
44281cb0ef41Sopenharmony_ci
44291cb0ef41Sopenharmony_ci  // Add collected feedback vectors to the root list lest we lose them to GC.
44301cb0ef41Sopenharmony_ci  Handle<ArrayList> list =
44311cb0ef41Sopenharmony_ci      ArrayList::New(this, static_cast<int>(vectors.size()));
44321cb0ef41Sopenharmony_ci  for (const auto& vector : vectors) list = ArrayList::Add(this, list, vector);
44331cb0ef41Sopenharmony_ci  SetFeedbackVectorsForProfilingTools(*list);
44341cb0ef41Sopenharmony_ci}
44351cb0ef41Sopenharmony_ci
44361cb0ef41Sopenharmony_civoid Isolate::set_date_cache(DateCache* date_cache) {
44371cb0ef41Sopenharmony_ci  if (date_cache != date_cache_) {
44381cb0ef41Sopenharmony_ci    delete date_cache_;
44391cb0ef41Sopenharmony_ci  }
44401cb0ef41Sopenharmony_ci  date_cache_ = date_cache;
44411cb0ef41Sopenharmony_ci}
44421cb0ef41Sopenharmony_ci
44431cb0ef41Sopenharmony_ciIsolate::KnownPrototype Isolate::IsArrayOrObjectOrStringPrototype(
44441cb0ef41Sopenharmony_ci    Object object) {
44451cb0ef41Sopenharmony_ci  Object context = heap()->native_contexts_list();
44461cb0ef41Sopenharmony_ci  while (!context.IsUndefined(this)) {
44471cb0ef41Sopenharmony_ci    Context current_context = Context::cast(context);
44481cb0ef41Sopenharmony_ci    if (current_context.initial_object_prototype() == object) {
44491cb0ef41Sopenharmony_ci      return KnownPrototype::kObject;
44501cb0ef41Sopenharmony_ci    } else if (current_context.initial_array_prototype() == object) {
44511cb0ef41Sopenharmony_ci      return KnownPrototype::kArray;
44521cb0ef41Sopenharmony_ci    } else if (current_context.initial_string_prototype() == object) {
44531cb0ef41Sopenharmony_ci      return KnownPrototype::kString;
44541cb0ef41Sopenharmony_ci    }
44551cb0ef41Sopenharmony_ci    context = current_context.next_context_link();
44561cb0ef41Sopenharmony_ci  }
44571cb0ef41Sopenharmony_ci  return KnownPrototype::kNone;
44581cb0ef41Sopenharmony_ci}
44591cb0ef41Sopenharmony_ci
44601cb0ef41Sopenharmony_cibool Isolate::IsInAnyContext(Object object, uint32_t index) {
44611cb0ef41Sopenharmony_ci  DisallowGarbageCollection no_gc;
44621cb0ef41Sopenharmony_ci  Object context = heap()->native_contexts_list();
44631cb0ef41Sopenharmony_ci  while (!context.IsUndefined(this)) {
44641cb0ef41Sopenharmony_ci    Context current_context = Context::cast(context);
44651cb0ef41Sopenharmony_ci    if (current_context.get(index) == object) {
44661cb0ef41Sopenharmony_ci      return true;
44671cb0ef41Sopenharmony_ci    }
44681cb0ef41Sopenharmony_ci    context = current_context.next_context_link();
44691cb0ef41Sopenharmony_ci  }
44701cb0ef41Sopenharmony_ci  return false;
44711cb0ef41Sopenharmony_ci}
44721cb0ef41Sopenharmony_ci
44731cb0ef41Sopenharmony_civoid Isolate::UpdateNoElementsProtectorOnSetElement(Handle<JSObject> object) {
44741cb0ef41Sopenharmony_ci  DisallowGarbageCollection no_gc;
44751cb0ef41Sopenharmony_ci  if (!object->map().is_prototype_map()) return;
44761cb0ef41Sopenharmony_ci  if (!Protectors::IsNoElementsIntact(this)) return;
44771cb0ef41Sopenharmony_ci  KnownPrototype obj_type = IsArrayOrObjectOrStringPrototype(*object);
44781cb0ef41Sopenharmony_ci  if (obj_type == KnownPrototype::kNone) return;
44791cb0ef41Sopenharmony_ci  if (obj_type == KnownPrototype::kObject) {
44801cb0ef41Sopenharmony_ci    this->CountUsage(v8::Isolate::kObjectPrototypeHasElements);
44811cb0ef41Sopenharmony_ci  } else if (obj_type == KnownPrototype::kArray) {
44821cb0ef41Sopenharmony_ci    this->CountUsage(v8::Isolate::kArrayPrototypeHasElements);
44831cb0ef41Sopenharmony_ci  }
44841cb0ef41Sopenharmony_ci  Protectors::InvalidateNoElements(this);
44851cb0ef41Sopenharmony_ci}
44861cb0ef41Sopenharmony_ci
44871cb0ef41Sopenharmony_cistatic base::RandomNumberGenerator* ensure_rng_exists(
44881cb0ef41Sopenharmony_ci    base::RandomNumberGenerator** rng, int seed) {
44891cb0ef41Sopenharmony_ci  if (*rng == nullptr) {
44901cb0ef41Sopenharmony_ci    if (seed != 0) {
44911cb0ef41Sopenharmony_ci      *rng = new base::RandomNumberGenerator(seed);
44921cb0ef41Sopenharmony_ci    } else {
44931cb0ef41Sopenharmony_ci      *rng = new base::RandomNumberGenerator();
44941cb0ef41Sopenharmony_ci    }
44951cb0ef41Sopenharmony_ci  }
44961cb0ef41Sopenharmony_ci  return *rng;
44971cb0ef41Sopenharmony_ci}
44981cb0ef41Sopenharmony_ci
44991cb0ef41Sopenharmony_cibase::RandomNumberGenerator* Isolate::random_number_generator() {
45001cb0ef41Sopenharmony_ci  // TODO(bmeurer) Initialized lazily because it depends on flags; can
45011cb0ef41Sopenharmony_ci  // be fixed once the default isolate cleanup is done.
45021cb0ef41Sopenharmony_ci  return ensure_rng_exists(&random_number_generator_, FLAG_random_seed);
45031cb0ef41Sopenharmony_ci}
45041cb0ef41Sopenharmony_ci
45051cb0ef41Sopenharmony_cibase::RandomNumberGenerator* Isolate::fuzzer_rng() {
45061cb0ef41Sopenharmony_ci  if (fuzzer_rng_ == nullptr) {
45071cb0ef41Sopenharmony_ci    int64_t seed = FLAG_fuzzer_random_seed;
45081cb0ef41Sopenharmony_ci    if (seed == 0) {
45091cb0ef41Sopenharmony_ci      seed = random_number_generator()->initial_seed();
45101cb0ef41Sopenharmony_ci    }
45111cb0ef41Sopenharmony_ci
45121cb0ef41Sopenharmony_ci    fuzzer_rng_ = new base::RandomNumberGenerator(seed);
45131cb0ef41Sopenharmony_ci  }
45141cb0ef41Sopenharmony_ci
45151cb0ef41Sopenharmony_ci  return fuzzer_rng_;
45161cb0ef41Sopenharmony_ci}
45171cb0ef41Sopenharmony_ci
45181cb0ef41Sopenharmony_ciint Isolate::GenerateIdentityHash(uint32_t mask) {
45191cb0ef41Sopenharmony_ci  int hash;
45201cb0ef41Sopenharmony_ci  int attempts = 0;
45211cb0ef41Sopenharmony_ci  do {
45221cb0ef41Sopenharmony_ci    hash = random_number_generator()->NextInt() & mask;
45231cb0ef41Sopenharmony_ci  } while (hash == 0 && attempts++ < 30);
45241cb0ef41Sopenharmony_ci  return hash != 0 ? hash : 1;
45251cb0ef41Sopenharmony_ci}
45261cb0ef41Sopenharmony_ci
45271cb0ef41Sopenharmony_ciCode Isolate::FindCodeObject(Address a) {
45281cb0ef41Sopenharmony_ci  return heap()->GcSafeFindCodeForInnerPointer(a);
45291cb0ef41Sopenharmony_ci}
45301cb0ef41Sopenharmony_ci
45311cb0ef41Sopenharmony_ci#ifdef DEBUG
45321cb0ef41Sopenharmony_ci#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
45331cb0ef41Sopenharmony_ci  const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_);
45341cb0ef41Sopenharmony_ciISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
45351cb0ef41Sopenharmony_ciISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
45361cb0ef41Sopenharmony_ci#undef ISOLATE_FIELD_OFFSET
45371cb0ef41Sopenharmony_ci#endif
45381cb0ef41Sopenharmony_ci
45391cb0ef41Sopenharmony_ciHandle<Symbol> Isolate::SymbolFor(RootIndex dictionary_index,
45401cb0ef41Sopenharmony_ci                                  Handle<String> name, bool private_symbol) {
45411cb0ef41Sopenharmony_ci  Handle<String> key = factory()->InternalizeString(name);
45421cb0ef41Sopenharmony_ci  Handle<RegisteredSymbolTable> dictionary =
45431cb0ef41Sopenharmony_ci      Handle<RegisteredSymbolTable>::cast(root_handle(dictionary_index));
45441cb0ef41Sopenharmony_ci  InternalIndex entry = dictionary->FindEntry(this, key);
45451cb0ef41Sopenharmony_ci  Handle<Symbol> symbol;
45461cb0ef41Sopenharmony_ci  if (entry.is_not_found()) {
45471cb0ef41Sopenharmony_ci    symbol =
45481cb0ef41Sopenharmony_ci        private_symbol ? factory()->NewPrivateSymbol() : factory()->NewSymbol();
45491cb0ef41Sopenharmony_ci    symbol->set_description(*key);
45501cb0ef41Sopenharmony_ci    dictionary = RegisteredSymbolTable::Add(this, dictionary, key, symbol);
45511cb0ef41Sopenharmony_ci
45521cb0ef41Sopenharmony_ci    switch (dictionary_index) {
45531cb0ef41Sopenharmony_ci      case RootIndex::kPublicSymbolTable:
45541cb0ef41Sopenharmony_ci        symbol->set_is_in_public_symbol_table(true);
45551cb0ef41Sopenharmony_ci        heap()->set_public_symbol_table(*dictionary);
45561cb0ef41Sopenharmony_ci        break;
45571cb0ef41Sopenharmony_ci      case RootIndex::kApiSymbolTable:
45581cb0ef41Sopenharmony_ci        heap()->set_api_symbol_table(*dictionary);
45591cb0ef41Sopenharmony_ci        break;
45601cb0ef41Sopenharmony_ci      case RootIndex::kApiPrivateSymbolTable:
45611cb0ef41Sopenharmony_ci        heap()->set_api_private_symbol_table(*dictionary);
45621cb0ef41Sopenharmony_ci        break;
45631cb0ef41Sopenharmony_ci      default:
45641cb0ef41Sopenharmony_ci        UNREACHABLE();
45651cb0ef41Sopenharmony_ci    }
45661cb0ef41Sopenharmony_ci  } else {
45671cb0ef41Sopenharmony_ci    symbol = Handle<Symbol>(Symbol::cast(dictionary->ValueAt(entry)), this);
45681cb0ef41Sopenharmony_ci  }
45691cb0ef41Sopenharmony_ci  return symbol;
45701cb0ef41Sopenharmony_ci}
45711cb0ef41Sopenharmony_ci
45721cb0ef41Sopenharmony_civoid Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) {
45731cb0ef41Sopenharmony_ci  auto pos = std::find(before_call_entered_callbacks_.begin(),
45741cb0ef41Sopenharmony_ci                       before_call_entered_callbacks_.end(), callback);
45751cb0ef41Sopenharmony_ci  if (pos != before_call_entered_callbacks_.end()) return;
45761cb0ef41Sopenharmony_ci  before_call_entered_callbacks_.push_back(callback);
45771cb0ef41Sopenharmony_ci}
45781cb0ef41Sopenharmony_ci
45791cb0ef41Sopenharmony_civoid Isolate::RemoveBeforeCallEnteredCallback(
45801cb0ef41Sopenharmony_ci    BeforeCallEnteredCallback callback) {
45811cb0ef41Sopenharmony_ci  auto pos = std::find(before_call_entered_callbacks_.begin(),
45821cb0ef41Sopenharmony_ci                       before_call_entered_callbacks_.end(), callback);
45831cb0ef41Sopenharmony_ci  if (pos == before_call_entered_callbacks_.end()) return;
45841cb0ef41Sopenharmony_ci  before_call_entered_callbacks_.erase(pos);
45851cb0ef41Sopenharmony_ci}
45861cb0ef41Sopenharmony_ci
45871cb0ef41Sopenharmony_civoid Isolate::AddCallCompletedCallback(CallCompletedCallback callback) {
45881cb0ef41Sopenharmony_ci  auto pos = std::find(call_completed_callbacks_.begin(),
45891cb0ef41Sopenharmony_ci                       call_completed_callbacks_.end(), callback);
45901cb0ef41Sopenharmony_ci  if (pos != call_completed_callbacks_.end()) return;
45911cb0ef41Sopenharmony_ci  call_completed_callbacks_.push_back(callback);
45921cb0ef41Sopenharmony_ci}
45931cb0ef41Sopenharmony_ci
45941cb0ef41Sopenharmony_civoid Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) {
45951cb0ef41Sopenharmony_ci  auto pos = std::find(call_completed_callbacks_.begin(),
45961cb0ef41Sopenharmony_ci                       call_completed_callbacks_.end(), callback);
45971cb0ef41Sopenharmony_ci  if (pos == call_completed_callbacks_.end()) return;
45981cb0ef41Sopenharmony_ci  call_completed_callbacks_.erase(pos);
45991cb0ef41Sopenharmony_ci}
46001cb0ef41Sopenharmony_ci
46011cb0ef41Sopenharmony_civoid Isolate::FireCallCompletedCallbackInternal(
46021cb0ef41Sopenharmony_ci    MicrotaskQueue* microtask_queue) {
46031cb0ef41Sopenharmony_ci  DCHECK(thread_local_top()->CallDepthIsZero());
46041cb0ef41Sopenharmony_ci
46051cb0ef41Sopenharmony_ci  bool perform_checkpoint =
46061cb0ef41Sopenharmony_ci      microtask_queue &&
46071cb0ef41Sopenharmony_ci      microtask_queue->microtasks_policy() == v8::MicrotasksPolicy::kAuto;
46081cb0ef41Sopenharmony_ci
46091cb0ef41Sopenharmony_ci  v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this);
46101cb0ef41Sopenharmony_ci  if (perform_checkpoint) microtask_queue->PerformCheckpoint(isolate);
46111cb0ef41Sopenharmony_ci
46121cb0ef41Sopenharmony_ci  if (call_completed_callbacks_.empty()) return;
46131cb0ef41Sopenharmony_ci  // Fire callbacks.  Increase call depth to prevent recursive callbacks.
46141cb0ef41Sopenharmony_ci  v8::Isolate::SuppressMicrotaskExecutionScope suppress(isolate);
46151cb0ef41Sopenharmony_ci  std::vector<CallCompletedCallback> callbacks(call_completed_callbacks_);
46161cb0ef41Sopenharmony_ci  for (auto& callback : callbacks) {
46171cb0ef41Sopenharmony_ci    callback(reinterpret_cast<v8::Isolate*>(this));
46181cb0ef41Sopenharmony_ci  }
46191cb0ef41Sopenharmony_ci}
46201cb0ef41Sopenharmony_ci
46211cb0ef41Sopenharmony_civoid Isolate::UpdatePromiseHookProtector() {
46221cb0ef41Sopenharmony_ci  if (Protectors::IsPromiseHookIntact(this)) {
46231cb0ef41Sopenharmony_ci    HandleScope scope(this);
46241cb0ef41Sopenharmony_ci    Protectors::InvalidatePromiseHook(this);
46251cb0ef41Sopenharmony_ci  }
46261cb0ef41Sopenharmony_ci}
46271cb0ef41Sopenharmony_ci
46281cb0ef41Sopenharmony_civoid Isolate::PromiseHookStateUpdated() {
46291cb0ef41Sopenharmony_ci  promise_hook_flags_ =
46301cb0ef41Sopenharmony_ci    (promise_hook_flags_ & PromiseHookFields::HasContextPromiseHook::kMask) |
46311cb0ef41Sopenharmony_ci    PromiseHookFields::HasIsolatePromiseHook::encode(promise_hook_) |
46321cb0ef41Sopenharmony_ci    PromiseHookFields::HasAsyncEventDelegate::encode(async_event_delegate_) |
46331cb0ef41Sopenharmony_ci    PromiseHookFields::IsDebugActive::encode(debug()->is_active());
46341cb0ef41Sopenharmony_ci
46351cb0ef41Sopenharmony_ci  if (promise_hook_flags_ != 0) {
46361cb0ef41Sopenharmony_ci    UpdatePromiseHookProtector();
46371cb0ef41Sopenharmony_ci  }
46381cb0ef41Sopenharmony_ci}
46391cb0ef41Sopenharmony_ci
46401cb0ef41Sopenharmony_cinamespace {
46411cb0ef41Sopenharmony_ci
46421cb0ef41Sopenharmony_ciMaybeHandle<JSPromise> NewRejectedPromise(Isolate* isolate,
46431cb0ef41Sopenharmony_ci                                          v8::Local<v8::Context> api_context,
46441cb0ef41Sopenharmony_ci                                          Handle<Object> exception) {
46451cb0ef41Sopenharmony_ci  v8::Local<v8::Promise::Resolver> resolver;
46461cb0ef41Sopenharmony_ci  ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(
46471cb0ef41Sopenharmony_ci      isolate, resolver, v8::Promise::Resolver::New(api_context),
46481cb0ef41Sopenharmony_ci      MaybeHandle<JSPromise>());
46491cb0ef41Sopenharmony_ci
46501cb0ef41Sopenharmony_ci  RETURN_ON_SCHEDULED_EXCEPTION_VALUE(
46511cb0ef41Sopenharmony_ci      isolate, resolver->Reject(api_context, v8::Utils::ToLocal(exception)),
46521cb0ef41Sopenharmony_ci      MaybeHandle<JSPromise>());
46531cb0ef41Sopenharmony_ci
46541cb0ef41Sopenharmony_ci  v8::Local<v8::Promise> promise = resolver->GetPromise();
46551cb0ef41Sopenharmony_ci  return v8::Utils::OpenHandle(*promise);
46561cb0ef41Sopenharmony_ci}
46571cb0ef41Sopenharmony_ci
46581cb0ef41Sopenharmony_ci}  // namespace
46591cb0ef41Sopenharmony_ci
46601cb0ef41Sopenharmony_ciMaybeHandle<JSPromise> Isolate::RunHostImportModuleDynamicallyCallback(
46611cb0ef41Sopenharmony_ci    Handle<Script> referrer, Handle<Object> specifier,
46621cb0ef41Sopenharmony_ci    MaybeHandle<Object> maybe_import_assertions_argument) {
46631cb0ef41Sopenharmony_ci  v8::Local<v8::Context> api_context =
46641cb0ef41Sopenharmony_ci      v8::Utils::ToLocal(Handle<Context>::cast(native_context()));
46651cb0ef41Sopenharmony_ci  if (host_import_module_dynamically_with_import_assertions_callback_ ==
46661cb0ef41Sopenharmony_ci          nullptr &&
46671cb0ef41Sopenharmony_ci      host_import_module_dynamically_callback_ == nullptr) {
46681cb0ef41Sopenharmony_ci    Handle<Object> exception =
46691cb0ef41Sopenharmony_ci        factory()->NewError(error_function(), MessageTemplate::kUnsupported);
46701cb0ef41Sopenharmony_ci    return NewRejectedPromise(this, api_context, exception);
46711cb0ef41Sopenharmony_ci  }
46721cb0ef41Sopenharmony_ci
46731cb0ef41Sopenharmony_ci  Handle<String> specifier_str;
46741cb0ef41Sopenharmony_ci  MaybeHandle<String> maybe_specifier = Object::ToString(this, specifier);
46751cb0ef41Sopenharmony_ci  if (!maybe_specifier.ToHandle(&specifier_str)) {
46761cb0ef41Sopenharmony_ci    Handle<Object> exception(pending_exception(), this);
46771cb0ef41Sopenharmony_ci    clear_pending_exception();
46781cb0ef41Sopenharmony_ci    return NewRejectedPromise(this, api_context, exception);
46791cb0ef41Sopenharmony_ci  }
46801cb0ef41Sopenharmony_ci  DCHECK(!has_pending_exception());
46811cb0ef41Sopenharmony_ci
46821cb0ef41Sopenharmony_ci  v8::Local<v8::Promise> promise;
46831cb0ef41Sopenharmony_ci  Handle<FixedArray> import_assertions_array;
46841cb0ef41Sopenharmony_ci  if (!GetImportAssertionsFromArgument(maybe_import_assertions_argument)
46851cb0ef41Sopenharmony_ci           .ToHandle(&import_assertions_array)) {
46861cb0ef41Sopenharmony_ci    Handle<Object> exception(pending_exception(), this);
46871cb0ef41Sopenharmony_ci    clear_pending_exception();
46881cb0ef41Sopenharmony_ci    return NewRejectedPromise(this, api_context, exception);
46891cb0ef41Sopenharmony_ci  }
46901cb0ef41Sopenharmony_ci  if (host_import_module_dynamically_callback_) {
46911cb0ef41Sopenharmony_ci    ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(
46921cb0ef41Sopenharmony_ci        this, promise,
46931cb0ef41Sopenharmony_ci        host_import_module_dynamically_callback_(
46941cb0ef41Sopenharmony_ci            api_context,
46951cb0ef41Sopenharmony_ci            v8::Utils::ToLocal(handle(referrer->host_defined_options(), this)),
46961cb0ef41Sopenharmony_ci            v8::Utils::ToLocal(handle(referrer->name(), this)),
46971cb0ef41Sopenharmony_ci            v8::Utils::ToLocal(specifier_str),
46981cb0ef41Sopenharmony_ci            ToApiHandle<v8::FixedArray>(import_assertions_array)),
46991cb0ef41Sopenharmony_ci        MaybeHandle<JSPromise>());
47001cb0ef41Sopenharmony_ci  } else {
47011cb0ef41Sopenharmony_ci    // TODO(cbruni, v8:12302): Avoid creating tempory ScriptOrModule objects.
47021cb0ef41Sopenharmony_ci    auto script_or_module = i::Handle<i::ScriptOrModule>::cast(
47031cb0ef41Sopenharmony_ci        this->factory()->NewStruct(i::SCRIPT_OR_MODULE_TYPE));
47041cb0ef41Sopenharmony_ci    script_or_module->set_resource_name(referrer->name());
47051cb0ef41Sopenharmony_ci    script_or_module->set_host_defined_options(
47061cb0ef41Sopenharmony_ci        referrer->host_defined_options());
47071cb0ef41Sopenharmony_ci    ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(
47081cb0ef41Sopenharmony_ci        this, promise,
47091cb0ef41Sopenharmony_ci        host_import_module_dynamically_with_import_assertions_callback_(
47101cb0ef41Sopenharmony_ci            api_context, v8::Utils::ToLocal(script_or_module),
47111cb0ef41Sopenharmony_ci            v8::Utils::ToLocal(specifier_str),
47121cb0ef41Sopenharmony_ci            ToApiHandle<v8::FixedArray>(import_assertions_array)),
47131cb0ef41Sopenharmony_ci        MaybeHandle<JSPromise>());
47141cb0ef41Sopenharmony_ci  }
47151cb0ef41Sopenharmony_ci  return v8::Utils::OpenHandle(*promise);
47161cb0ef41Sopenharmony_ci}
47171cb0ef41Sopenharmony_ci
47181cb0ef41Sopenharmony_ciMaybeHandle<FixedArray> Isolate::GetImportAssertionsFromArgument(
47191cb0ef41Sopenharmony_ci    MaybeHandle<Object> maybe_import_assertions_argument) {
47201cb0ef41Sopenharmony_ci  Handle<FixedArray> import_assertions_array = factory()->empty_fixed_array();
47211cb0ef41Sopenharmony_ci  Handle<Object> import_assertions_argument;
47221cb0ef41Sopenharmony_ci  if (!maybe_import_assertions_argument.ToHandle(&import_assertions_argument) ||
47231cb0ef41Sopenharmony_ci      import_assertions_argument->IsUndefined()) {
47241cb0ef41Sopenharmony_ci    return import_assertions_array;
47251cb0ef41Sopenharmony_ci  }
47261cb0ef41Sopenharmony_ci
47271cb0ef41Sopenharmony_ci  // The parser shouldn't have allowed the second argument to import() if
47281cb0ef41Sopenharmony_ci  // the flag wasn't enabled.
47291cb0ef41Sopenharmony_ci  DCHECK(FLAG_harmony_import_assertions || FLAG_harmony_import_attributes);
47301cb0ef41Sopenharmony_ci
47311cb0ef41Sopenharmony_ci  if (!import_assertions_argument->IsJSReceiver()) {
47321cb0ef41Sopenharmony_ci    this->Throw(
47331cb0ef41Sopenharmony_ci        *factory()->NewTypeError(MessageTemplate::kNonObjectImportArgument));
47341cb0ef41Sopenharmony_ci    return MaybeHandle<FixedArray>();
47351cb0ef41Sopenharmony_ci  }
47361cb0ef41Sopenharmony_ci
47371cb0ef41Sopenharmony_ci  Handle<JSReceiver> import_assertions_argument_receiver =
47381cb0ef41Sopenharmony_ci      Handle<JSReceiver>::cast(import_assertions_argument);
47391cb0ef41Sopenharmony_ci
47401cb0ef41Sopenharmony_ci  Handle<Object> import_assertions_object;
47411cb0ef41Sopenharmony_ci
47421cb0ef41Sopenharmony_ci  if (FLAG_harmony_import_attributes) {
47431cb0ef41Sopenharmony_ci    Handle<Name> with_key = factory()->with_string();
47441cb0ef41Sopenharmony_ci    if (!JSReceiver::GetProperty(this, import_assertions_argument_receiver,
47451cb0ef41Sopenharmony_ci                                 with_key)
47461cb0ef41Sopenharmony_ci             .ToHandle(&import_assertions_object)) {
47471cb0ef41Sopenharmony_ci      // This can happen if the property has a getter function that throws
47481cb0ef41Sopenharmony_ci      // an error.
47491cb0ef41Sopenharmony_ci      return MaybeHandle<FixedArray>();
47501cb0ef41Sopenharmony_ci    }
47511cb0ef41Sopenharmony_ci  }
47521cb0ef41Sopenharmony_ci
47531cb0ef41Sopenharmony_ci  if (FLAG_harmony_import_assertions &&
47541cb0ef41Sopenharmony_ci      (!FLAG_harmony_import_attributes ||
47551cb0ef41Sopenharmony_ci       import_assertions_object->IsUndefined())) {
47561cb0ef41Sopenharmony_ci    Handle<Name> assert_key = factory()->assert_string();
47571cb0ef41Sopenharmony_ci    if (!JSReceiver::GetProperty(this, import_assertions_argument_receiver,
47581cb0ef41Sopenharmony_ci                                 assert_key)
47591cb0ef41Sopenharmony_ci             .ToHandle(&import_assertions_object)) {
47601cb0ef41Sopenharmony_ci      // This can happen if the property has a getter function that throws
47611cb0ef41Sopenharmony_ci      // an error.
47621cb0ef41Sopenharmony_ci      return MaybeHandle<FixedArray>();
47631cb0ef41Sopenharmony_ci    }
47641cb0ef41Sopenharmony_ci  }
47651cb0ef41Sopenharmony_ci
47661cb0ef41Sopenharmony_ci  // If there is no 'with' or 'assert' option in the options bag, it's not an
47671cb0ef41Sopenharmony_ci  // error. Just do the import() as if no assertions were provided.
47681cb0ef41Sopenharmony_ci  if (import_assertions_object->IsUndefined()) return import_assertions_array;
47691cb0ef41Sopenharmony_ci
47701cb0ef41Sopenharmony_ci  if (!import_assertions_object->IsJSReceiver()) {
47711cb0ef41Sopenharmony_ci    this->Throw(
47721cb0ef41Sopenharmony_ci        *factory()->NewTypeError(MessageTemplate::kNonObjectAssertOption));
47731cb0ef41Sopenharmony_ci    return MaybeHandle<FixedArray>();
47741cb0ef41Sopenharmony_ci  }
47751cb0ef41Sopenharmony_ci
47761cb0ef41Sopenharmony_ci  Handle<JSReceiver> import_assertions_object_receiver =
47771cb0ef41Sopenharmony_ci      Handle<JSReceiver>::cast(import_assertions_object);
47781cb0ef41Sopenharmony_ci
47791cb0ef41Sopenharmony_ci  Handle<FixedArray> assertion_keys;
47801cb0ef41Sopenharmony_ci  if (!KeyAccumulator::GetKeys(import_assertions_object_receiver,
47811cb0ef41Sopenharmony_ci                               KeyCollectionMode::kOwnOnly, ENUMERABLE_STRINGS,
47821cb0ef41Sopenharmony_ci                               GetKeysConversion::kConvertToString)
47831cb0ef41Sopenharmony_ci           .ToHandle(&assertion_keys)) {
47841cb0ef41Sopenharmony_ci    // This happens if the assertions object is a Proxy whose ownKeys() or
47851cb0ef41Sopenharmony_ci    // getOwnPropertyDescriptor() trap throws.
47861cb0ef41Sopenharmony_ci    return MaybeHandle<FixedArray>();
47871cb0ef41Sopenharmony_ci  }
47881cb0ef41Sopenharmony_ci
47891cb0ef41Sopenharmony_ci  bool has_non_string_attribute = false;
47901cb0ef41Sopenharmony_ci
47911cb0ef41Sopenharmony_ci  // The assertions will be passed to the host in the form: [key1,
47921cb0ef41Sopenharmony_ci  // value1, key2, value2, ...].
47931cb0ef41Sopenharmony_ci  constexpr size_t kAssertionEntrySizeForDynamicImport = 2;
47941cb0ef41Sopenharmony_ci  import_assertions_array = factory()->NewFixedArray(static_cast<int>(
47951cb0ef41Sopenharmony_ci      assertion_keys->length() * kAssertionEntrySizeForDynamicImport));
47961cb0ef41Sopenharmony_ci  for (int i = 0; i < assertion_keys->length(); i++) {
47971cb0ef41Sopenharmony_ci    Handle<String> assertion_key(String::cast(assertion_keys->get(i)), this);
47981cb0ef41Sopenharmony_ci    Handle<Object> assertion_value;
47991cb0ef41Sopenharmony_ci    if (!Object::GetPropertyOrElement(this, import_assertions_object_receiver,
48001cb0ef41Sopenharmony_ci                                      assertion_key)
48011cb0ef41Sopenharmony_ci             .ToHandle(&assertion_value)) {
48021cb0ef41Sopenharmony_ci      // This can happen if the property has a getter function that throws
48031cb0ef41Sopenharmony_ci      // an error.
48041cb0ef41Sopenharmony_ci      return MaybeHandle<FixedArray>();
48051cb0ef41Sopenharmony_ci    }
48061cb0ef41Sopenharmony_ci
48071cb0ef41Sopenharmony_ci    if (!assertion_value->IsString()) {
48081cb0ef41Sopenharmony_ci      has_non_string_attribute = true;
48091cb0ef41Sopenharmony_ci    }
48101cb0ef41Sopenharmony_ci
48111cb0ef41Sopenharmony_ci    import_assertions_array->set((i * kAssertionEntrySizeForDynamicImport),
48121cb0ef41Sopenharmony_ci                                 *assertion_key);
48131cb0ef41Sopenharmony_ci    import_assertions_array->set((i * kAssertionEntrySizeForDynamicImport) + 1,
48141cb0ef41Sopenharmony_ci                                 *assertion_value);
48151cb0ef41Sopenharmony_ci  }
48161cb0ef41Sopenharmony_ci
48171cb0ef41Sopenharmony_ci  if (has_non_string_attribute) {
48181cb0ef41Sopenharmony_ci    this->Throw(*factory()->NewTypeError(
48191cb0ef41Sopenharmony_ci        MessageTemplate::kNonStringImportAssertionValue));
48201cb0ef41Sopenharmony_ci    return MaybeHandle<FixedArray>();
48211cb0ef41Sopenharmony_ci  }
48221cb0ef41Sopenharmony_ci
48231cb0ef41Sopenharmony_ci  return import_assertions_array;
48241cb0ef41Sopenharmony_ci}
48251cb0ef41Sopenharmony_ci
48261cb0ef41Sopenharmony_civoid Isolate::ClearKeptObjects() { heap()->ClearKeptObjects(); }
48271cb0ef41Sopenharmony_ci
48281cb0ef41Sopenharmony_civoid Isolate::SetHostImportModuleDynamicallyCallback(
48291cb0ef41Sopenharmony_ci    HostImportModuleDynamicallyCallback callback) {
48301cb0ef41Sopenharmony_ci  DCHECK_NULL(host_import_module_dynamically_with_import_assertions_callback_);
48311cb0ef41Sopenharmony_ci  host_import_module_dynamically_callback_ = callback;
48321cb0ef41Sopenharmony_ci}
48331cb0ef41Sopenharmony_ci
48341cb0ef41Sopenharmony_civoid Isolate::SetHostImportModuleDynamicallyCallback(
48351cb0ef41Sopenharmony_ci    HostImportModuleDynamicallyWithImportAssertionsCallback callback) {
48361cb0ef41Sopenharmony_ci  DCHECK_NULL(host_import_module_dynamically_callback_);
48371cb0ef41Sopenharmony_ci  host_import_module_dynamically_with_import_assertions_callback_ = callback;
48381cb0ef41Sopenharmony_ci}
48391cb0ef41Sopenharmony_ci
48401cb0ef41Sopenharmony_ciMaybeHandle<JSObject> Isolate::RunHostInitializeImportMetaObjectCallback(
48411cb0ef41Sopenharmony_ci    Handle<SourceTextModule> module) {
48421cb0ef41Sopenharmony_ci  CHECK(module->import_meta(kAcquireLoad).IsTheHole(this));
48431cb0ef41Sopenharmony_ci  Handle<JSObject> import_meta = factory()->NewJSObjectWithNullProto();
48441cb0ef41Sopenharmony_ci  if (host_initialize_import_meta_object_callback_ != nullptr) {
48451cb0ef41Sopenharmony_ci    v8::Local<v8::Context> api_context =
48461cb0ef41Sopenharmony_ci        v8::Utils::ToLocal(Handle<Context>(native_context()));
48471cb0ef41Sopenharmony_ci    host_initialize_import_meta_object_callback_(
48481cb0ef41Sopenharmony_ci        api_context, Utils::ToLocal(Handle<Module>::cast(module)),
48491cb0ef41Sopenharmony_ci        v8::Local<v8::Object>::Cast(v8::Utils::ToLocal(import_meta)));
48501cb0ef41Sopenharmony_ci    if (has_scheduled_exception()) {
48511cb0ef41Sopenharmony_ci      PromoteScheduledException();
48521cb0ef41Sopenharmony_ci      return {};
48531cb0ef41Sopenharmony_ci    }
48541cb0ef41Sopenharmony_ci  }
48551cb0ef41Sopenharmony_ci  return import_meta;
48561cb0ef41Sopenharmony_ci}
48571cb0ef41Sopenharmony_ci
48581cb0ef41Sopenharmony_civoid Isolate::SetHostInitializeImportMetaObjectCallback(
48591cb0ef41Sopenharmony_ci    HostInitializeImportMetaObjectCallback callback) {
48601cb0ef41Sopenharmony_ci  host_initialize_import_meta_object_callback_ = callback;
48611cb0ef41Sopenharmony_ci}
48621cb0ef41Sopenharmony_ci
48631cb0ef41Sopenharmony_civoid Isolate::SetHostCreateShadowRealmContextCallback(
48641cb0ef41Sopenharmony_ci    HostCreateShadowRealmContextCallback callback) {
48651cb0ef41Sopenharmony_ci  host_create_shadow_realm_context_callback_ = callback;
48661cb0ef41Sopenharmony_ci}
48671cb0ef41Sopenharmony_ci
48681cb0ef41Sopenharmony_ciMaybeHandle<NativeContext> Isolate::RunHostCreateShadowRealmContextCallback() {
48691cb0ef41Sopenharmony_ci  if (host_create_shadow_realm_context_callback_ == nullptr) {
48701cb0ef41Sopenharmony_ci    Handle<Object> exception =
48711cb0ef41Sopenharmony_ci        factory()->NewError(error_function(), MessageTemplate::kUnsupported);
48721cb0ef41Sopenharmony_ci    Throw(*exception);
48731cb0ef41Sopenharmony_ci    return kNullMaybeHandle;
48741cb0ef41Sopenharmony_ci  }
48751cb0ef41Sopenharmony_ci
48761cb0ef41Sopenharmony_ci  v8::Local<v8::Context> api_context =
48771cb0ef41Sopenharmony_ci      v8::Utils::ToLocal(Handle<Context>(native_context()));
48781cb0ef41Sopenharmony_ci  v8::Local<v8::Context> shadow_realm_context;
48791cb0ef41Sopenharmony_ci  ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(
48801cb0ef41Sopenharmony_ci      this, shadow_realm_context,
48811cb0ef41Sopenharmony_ci      host_create_shadow_realm_context_callback_(api_context),
48821cb0ef41Sopenharmony_ci      MaybeHandle<NativeContext>());
48831cb0ef41Sopenharmony_ci  Handle<Context> shadow_realm_context_handle =
48841cb0ef41Sopenharmony_ci      v8::Utils::OpenHandle(*shadow_realm_context);
48851cb0ef41Sopenharmony_ci  DCHECK(shadow_realm_context_handle->IsNativeContext());
48861cb0ef41Sopenharmony_ci  return Handle<NativeContext>::cast(shadow_realm_context_handle);
48871cb0ef41Sopenharmony_ci}
48881cb0ef41Sopenharmony_ci
48891cb0ef41Sopenharmony_ciMaybeHandle<Object> Isolate::RunPrepareStackTraceCallback(
48901cb0ef41Sopenharmony_ci    Handle<Context> context, Handle<JSObject> error, Handle<JSArray> sites) {
48911cb0ef41Sopenharmony_ci  v8::Local<v8::Context> api_context = Utils::ToLocal(context);
48921cb0ef41Sopenharmony_ci
48931cb0ef41Sopenharmony_ci  v8::Local<v8::Value> stack;
48941cb0ef41Sopenharmony_ci  ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(
48951cb0ef41Sopenharmony_ci      this, stack,
48961cb0ef41Sopenharmony_ci      prepare_stack_trace_callback_(api_context, Utils::ToLocal(error),
48971cb0ef41Sopenharmony_ci                                    Utils::ToLocal(sites)),
48981cb0ef41Sopenharmony_ci      MaybeHandle<Object>());
48991cb0ef41Sopenharmony_ci  return Utils::OpenHandle(*stack);
49001cb0ef41Sopenharmony_ci}
49011cb0ef41Sopenharmony_ci
49021cb0ef41Sopenharmony_ciint Isolate::LookupOrAddExternallyCompiledFilename(const char* filename) {
49031cb0ef41Sopenharmony_ci  if (embedded_file_writer_ != nullptr) {
49041cb0ef41Sopenharmony_ci    return embedded_file_writer_->LookupOrAddExternallyCompiledFilename(
49051cb0ef41Sopenharmony_ci        filename);
49061cb0ef41Sopenharmony_ci  }
49071cb0ef41Sopenharmony_ci  return 0;
49081cb0ef41Sopenharmony_ci}
49091cb0ef41Sopenharmony_ci
49101cb0ef41Sopenharmony_ciconst char* Isolate::GetExternallyCompiledFilename(int index) const {
49111cb0ef41Sopenharmony_ci  if (embedded_file_writer_ != nullptr) {
49121cb0ef41Sopenharmony_ci    return embedded_file_writer_->GetExternallyCompiledFilename(index);
49131cb0ef41Sopenharmony_ci  }
49141cb0ef41Sopenharmony_ci  return "";
49151cb0ef41Sopenharmony_ci}
49161cb0ef41Sopenharmony_ci
49171cb0ef41Sopenharmony_ciint Isolate::GetExternallyCompiledFilenameCount() const {
49181cb0ef41Sopenharmony_ci  if (embedded_file_writer_ != nullptr) {
49191cb0ef41Sopenharmony_ci    return embedded_file_writer_->GetExternallyCompiledFilenameCount();
49201cb0ef41Sopenharmony_ci  }
49211cb0ef41Sopenharmony_ci  return 0;
49221cb0ef41Sopenharmony_ci}
49231cb0ef41Sopenharmony_ci
49241cb0ef41Sopenharmony_civoid Isolate::PrepareBuiltinSourcePositionMap() {
49251cb0ef41Sopenharmony_ci  if (embedded_file_writer_ != nullptr) {
49261cb0ef41Sopenharmony_ci    return embedded_file_writer_->PrepareBuiltinSourcePositionMap(
49271cb0ef41Sopenharmony_ci        this->builtins());
49281cb0ef41Sopenharmony_ci  }
49291cb0ef41Sopenharmony_ci}
49301cb0ef41Sopenharmony_ci
49311cb0ef41Sopenharmony_civoid Isolate::PrepareBuiltinLabelInfoMap() {
49321cb0ef41Sopenharmony_ci  if (embedded_file_writer_ != nullptr) {
49331cb0ef41Sopenharmony_ci    embedded_file_writer_->PrepareBuiltinLabelInfoMap(
49341cb0ef41Sopenharmony_ci        heap()->construct_stub_create_deopt_pc_offset().value(),
49351cb0ef41Sopenharmony_ci        heap()->construct_stub_invoke_deopt_pc_offset().value());
49361cb0ef41Sopenharmony_ci  }
49371cb0ef41Sopenharmony_ci}
49381cb0ef41Sopenharmony_ci
49391cb0ef41Sopenharmony_ci#if defined(V8_OS_WIN64)
49401cb0ef41Sopenharmony_civoid Isolate::SetBuiltinUnwindData(
49411cb0ef41Sopenharmony_ci    Builtin builtin,
49421cb0ef41Sopenharmony_ci    const win64_unwindinfo::BuiltinUnwindInfo& unwinding_info) {
49431cb0ef41Sopenharmony_ci  if (embedded_file_writer_ != nullptr) {
49441cb0ef41Sopenharmony_ci    embedded_file_writer_->SetBuiltinUnwindData(builtin, unwinding_info);
49451cb0ef41Sopenharmony_ci  }
49461cb0ef41Sopenharmony_ci}
49471cb0ef41Sopenharmony_ci#endif  // V8_OS_WIN64
49481cb0ef41Sopenharmony_ci
49491cb0ef41Sopenharmony_civoid Isolate::SetPrepareStackTraceCallback(PrepareStackTraceCallback callback) {
49501cb0ef41Sopenharmony_ci  prepare_stack_trace_callback_ = callback;
49511cb0ef41Sopenharmony_ci}
49521cb0ef41Sopenharmony_ci
49531cb0ef41Sopenharmony_cibool Isolate::HasPrepareStackTraceCallback() const {
49541cb0ef41Sopenharmony_ci  return prepare_stack_trace_callback_ != nullptr;
49551cb0ef41Sopenharmony_ci}
49561cb0ef41Sopenharmony_ci
49571cb0ef41Sopenharmony_civoid Isolate::SetAddCrashKeyCallback(AddCrashKeyCallback callback) {
49581cb0ef41Sopenharmony_ci  add_crash_key_callback_ = callback;
49591cb0ef41Sopenharmony_ci
49601cb0ef41Sopenharmony_ci  // Log the initial set of data.
49611cb0ef41Sopenharmony_ci  AddCrashKeysForIsolateAndHeapPointers();
49621cb0ef41Sopenharmony_ci}
49631cb0ef41Sopenharmony_ci
49641cb0ef41Sopenharmony_civoid Isolate::SetAtomicsWaitCallback(v8::Isolate::AtomicsWaitCallback callback,
49651cb0ef41Sopenharmony_ci                                     void* data) {
49661cb0ef41Sopenharmony_ci  atomics_wait_callback_ = callback;
49671cb0ef41Sopenharmony_ci  atomics_wait_callback_data_ = data;
49681cb0ef41Sopenharmony_ci}
49691cb0ef41Sopenharmony_ci
49701cb0ef41Sopenharmony_civoid Isolate::RunAtomicsWaitCallback(v8::Isolate::AtomicsWaitEvent event,
49711cb0ef41Sopenharmony_ci                                     Handle<JSArrayBuffer> array_buffer,
49721cb0ef41Sopenharmony_ci                                     size_t offset_in_bytes, int64_t value,
49731cb0ef41Sopenharmony_ci                                     double timeout_in_ms,
49741cb0ef41Sopenharmony_ci                                     AtomicsWaitWakeHandle* stop_handle) {
49751cb0ef41Sopenharmony_ci  DCHECK(array_buffer->is_shared());
49761cb0ef41Sopenharmony_ci  if (atomics_wait_callback_ == nullptr) return;
49771cb0ef41Sopenharmony_ci  HandleScope handle_scope(this);
49781cb0ef41Sopenharmony_ci  atomics_wait_callback_(
49791cb0ef41Sopenharmony_ci      event, v8::Utils::ToLocalShared(array_buffer), offset_in_bytes, value,
49801cb0ef41Sopenharmony_ci      timeout_in_ms,
49811cb0ef41Sopenharmony_ci      reinterpret_cast<v8::Isolate::AtomicsWaitWakeHandle*>(stop_handle),
49821cb0ef41Sopenharmony_ci      atomics_wait_callback_data_);
49831cb0ef41Sopenharmony_ci}
49841cb0ef41Sopenharmony_ci
49851cb0ef41Sopenharmony_civoid Isolate::SetPromiseHook(PromiseHook hook) {
49861cb0ef41Sopenharmony_ci  promise_hook_ = hook;
49871cb0ef41Sopenharmony_ci  PromiseHookStateUpdated();
49881cb0ef41Sopenharmony_ci}
49891cb0ef41Sopenharmony_ci
49901cb0ef41Sopenharmony_civoid Isolate::RunAllPromiseHooks(PromiseHookType type,
49911cb0ef41Sopenharmony_ci                                 Handle<JSPromise> promise,
49921cb0ef41Sopenharmony_ci                                 Handle<Object> parent) {
49931cb0ef41Sopenharmony_ci#ifdef V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS
49941cb0ef41Sopenharmony_ci  if (HasContextPromiseHooks()) {
49951cb0ef41Sopenharmony_ci    native_context()->RunPromiseHook(type, promise, parent);
49961cb0ef41Sopenharmony_ci  }
49971cb0ef41Sopenharmony_ci#endif
49981cb0ef41Sopenharmony_ci  if (HasIsolatePromiseHooks() || HasAsyncEventDelegate()) {
49991cb0ef41Sopenharmony_ci    RunPromiseHook(type, promise, parent);
50001cb0ef41Sopenharmony_ci  }
50011cb0ef41Sopenharmony_ci}
50021cb0ef41Sopenharmony_ci
50031cb0ef41Sopenharmony_civoid Isolate::RunPromiseHook(PromiseHookType type, Handle<JSPromise> promise,
50041cb0ef41Sopenharmony_ci                             Handle<Object> parent) {
50051cb0ef41Sopenharmony_ci  if (!HasIsolatePromiseHooks()) return;
50061cb0ef41Sopenharmony_ci  DCHECK(promise_hook_ != nullptr);
50071cb0ef41Sopenharmony_ci  promise_hook_(type, v8::Utils::PromiseToLocal(promise),
50081cb0ef41Sopenharmony_ci                v8::Utils::ToLocal(parent));
50091cb0ef41Sopenharmony_ci}
50101cb0ef41Sopenharmony_ci
50111cb0ef41Sopenharmony_civoid Isolate::OnAsyncFunctionSuspended(Handle<JSPromise> promise,
50121cb0ef41Sopenharmony_ci                                       Handle<JSPromise> parent) {
50131cb0ef41Sopenharmony_ci  DCHECK_EQ(0, promise->async_task_id());
50141cb0ef41Sopenharmony_ci  RunAllPromiseHooks(PromiseHookType::kInit, promise, parent);
50151cb0ef41Sopenharmony_ci  if (HasAsyncEventDelegate()) {
50161cb0ef41Sopenharmony_ci    DCHECK_NE(nullptr, async_event_delegate_);
50171cb0ef41Sopenharmony_ci    promise->set_async_task_id(++async_task_count_);
50181cb0ef41Sopenharmony_ci    async_event_delegate_->AsyncEventOccurred(debug::kDebugAwait,
50191cb0ef41Sopenharmony_ci                                              promise->async_task_id(), false);
50201cb0ef41Sopenharmony_ci  }
50211cb0ef41Sopenharmony_ci  if (debug()->is_active()) {
50221cb0ef41Sopenharmony_ci    // We are about to suspend execution of the current async function,
50231cb0ef41Sopenharmony_ci    // so pop the outer promise from the isolate's promise stack.
50241cb0ef41Sopenharmony_ci    PopPromise();
50251cb0ef41Sopenharmony_ci  }
50261cb0ef41Sopenharmony_ci}
50271cb0ef41Sopenharmony_ci
50281cb0ef41Sopenharmony_civoid Isolate::OnPromiseThen(Handle<JSPromise> promise) {
50291cb0ef41Sopenharmony_ci  if (!HasAsyncEventDelegate()) return;
50301cb0ef41Sopenharmony_ci  Maybe<debug::DebugAsyncActionType> action_type =
50311cb0ef41Sopenharmony_ci      Nothing<debug::DebugAsyncActionType>();
50321cb0ef41Sopenharmony_ci  for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) {
50331cb0ef41Sopenharmony_ci    std::vector<Handle<SharedFunctionInfo>> infos;
50341cb0ef41Sopenharmony_ci    it.frame()->GetFunctions(&infos);
50351cb0ef41Sopenharmony_ci    for (auto it = infos.rbegin(); it != infos.rend(); ++it) {
50361cb0ef41Sopenharmony_ci      Handle<SharedFunctionInfo> info = *it;
50371cb0ef41Sopenharmony_ci      if (info->HasBuiltinId()) {
50381cb0ef41Sopenharmony_ci        // We should not report PromiseThen and PromiseCatch which is called
50391cb0ef41Sopenharmony_ci        // indirectly, e.g. Promise.all calls Promise.then internally.
50401cb0ef41Sopenharmony_ci        switch (info->builtin_id()) {
50411cb0ef41Sopenharmony_ci          case Builtin::kPromisePrototypeCatch:
50421cb0ef41Sopenharmony_ci            action_type = Just(debug::kDebugPromiseCatch);
50431cb0ef41Sopenharmony_ci            continue;
50441cb0ef41Sopenharmony_ci          case Builtin::kPromisePrototypeFinally:
50451cb0ef41Sopenharmony_ci            action_type = Just(debug::kDebugPromiseFinally);
50461cb0ef41Sopenharmony_ci            continue;
50471cb0ef41Sopenharmony_ci          case Builtin::kPromisePrototypeThen:
50481cb0ef41Sopenharmony_ci            action_type = Just(debug::kDebugPromiseThen);
50491cb0ef41Sopenharmony_ci            continue;
50501cb0ef41Sopenharmony_ci          default:
50511cb0ef41Sopenharmony_ci            return;
50521cb0ef41Sopenharmony_ci        }
50531cb0ef41Sopenharmony_ci      }
50541cb0ef41Sopenharmony_ci      if (info->IsUserJavaScript() && action_type.IsJust()) {
50551cb0ef41Sopenharmony_ci        DCHECK_EQ(0, promise->async_task_id());
50561cb0ef41Sopenharmony_ci        promise->set_async_task_id(++async_task_count_);
50571cb0ef41Sopenharmony_ci        async_event_delegate_->AsyncEventOccurred(action_type.FromJust(),
50581cb0ef41Sopenharmony_ci                                                  promise->async_task_id(),
50591cb0ef41Sopenharmony_ci                                                  debug()->IsBlackboxed(info));
50601cb0ef41Sopenharmony_ci      }
50611cb0ef41Sopenharmony_ci      return;
50621cb0ef41Sopenharmony_ci    }
50631cb0ef41Sopenharmony_ci  }
50641cb0ef41Sopenharmony_ci}
50651cb0ef41Sopenharmony_ci
50661cb0ef41Sopenharmony_civoid Isolate::OnPromiseBefore(Handle<JSPromise> promise) {
50671cb0ef41Sopenharmony_ci  RunPromiseHook(PromiseHookType::kBefore, promise,
50681cb0ef41Sopenharmony_ci                 factory()->undefined_value());
50691cb0ef41Sopenharmony_ci  if (HasAsyncEventDelegate()) {
50701cb0ef41Sopenharmony_ci    if (promise->async_task_id()) {
50711cb0ef41Sopenharmony_ci      async_event_delegate_->AsyncEventOccurred(
50721cb0ef41Sopenharmony_ci          debug::kDebugWillHandle, promise->async_task_id(), false);
50731cb0ef41Sopenharmony_ci    }
50741cb0ef41Sopenharmony_ci  }
50751cb0ef41Sopenharmony_ci  if (debug()->is_active()) PushPromise(promise);
50761cb0ef41Sopenharmony_ci}
50771cb0ef41Sopenharmony_ci
50781cb0ef41Sopenharmony_civoid Isolate::OnPromiseAfter(Handle<JSPromise> promise) {
50791cb0ef41Sopenharmony_ci  RunPromiseHook(PromiseHookType::kAfter, promise,
50801cb0ef41Sopenharmony_ci                 factory()->undefined_value());
50811cb0ef41Sopenharmony_ci  if (HasAsyncEventDelegate()) {
50821cb0ef41Sopenharmony_ci    if (promise->async_task_id()) {
50831cb0ef41Sopenharmony_ci      async_event_delegate_->AsyncEventOccurred(
50841cb0ef41Sopenharmony_ci          debug::kDebugDidHandle, promise->async_task_id(), false);
50851cb0ef41Sopenharmony_ci    }
50861cb0ef41Sopenharmony_ci  }
50871cb0ef41Sopenharmony_ci  if (debug()->is_active()) PopPromise();
50881cb0ef41Sopenharmony_ci}
50891cb0ef41Sopenharmony_ci
50901cb0ef41Sopenharmony_civoid Isolate::OnTerminationDuringRunMicrotasks() {
50911cb0ef41Sopenharmony_ci  // This performs cleanup for when RunMicrotasks (in
50921cb0ef41Sopenharmony_ci  // builtins-microtask-queue-gen.cc) is aborted via a termination exception.
50931cb0ef41Sopenharmony_ci  // This has to be kept in sync with the code in said file. Currently this
50941cb0ef41Sopenharmony_ci  // includes:
50951cb0ef41Sopenharmony_ci  //
50961cb0ef41Sopenharmony_ci  //  (1) Resetting the |current_microtask| slot on the Isolate to avoid leaking
50971cb0ef41Sopenharmony_ci  //      memory (and also to keep |current_microtask| not being undefined as an
50981cb0ef41Sopenharmony_ci  //      indicator that we're currently pumping the microtask queue).
50991cb0ef41Sopenharmony_ci  //  (2) Empty the promise stack to avoid leaking memory.
51001cb0ef41Sopenharmony_ci  //  (3) If the |current_microtask| is a promise reaction or resolve thenable
51011cb0ef41Sopenharmony_ci  //      job task, then signal the async event delegate and debugger that the
51021cb0ef41Sopenharmony_ci  //      microtask finished running.
51031cb0ef41Sopenharmony_ci  //
51041cb0ef41Sopenharmony_ci
51051cb0ef41Sopenharmony_ci  // Reset the |current_microtask| global slot.
51061cb0ef41Sopenharmony_ci  Handle<Microtask> current_microtask(
51071cb0ef41Sopenharmony_ci      Microtask::cast(heap()->current_microtask()), this);
51081cb0ef41Sopenharmony_ci  heap()->set_current_microtask(ReadOnlyRoots(this).undefined_value());
51091cb0ef41Sopenharmony_ci
51101cb0ef41Sopenharmony_ci  // Empty the promise stack.
51111cb0ef41Sopenharmony_ci  debug()->thread_local_.promise_stack_ = Smi::zero();
51121cb0ef41Sopenharmony_ci
51131cb0ef41Sopenharmony_ci  if (current_microtask->IsPromiseReactionJobTask()) {
51141cb0ef41Sopenharmony_ci    Handle<PromiseReactionJobTask> promise_reaction_job_task =
51151cb0ef41Sopenharmony_ci        Handle<PromiseReactionJobTask>::cast(current_microtask);
51161cb0ef41Sopenharmony_ci    Handle<HeapObject> promise_or_capability(
51171cb0ef41Sopenharmony_ci        promise_reaction_job_task->promise_or_capability(), this);
51181cb0ef41Sopenharmony_ci    if (promise_or_capability->IsPromiseCapability()) {
51191cb0ef41Sopenharmony_ci      promise_or_capability = handle(
51201cb0ef41Sopenharmony_ci          Handle<PromiseCapability>::cast(promise_or_capability)->promise(),
51211cb0ef41Sopenharmony_ci          this);
51221cb0ef41Sopenharmony_ci    }
51231cb0ef41Sopenharmony_ci    if (promise_or_capability->IsJSPromise()) {
51241cb0ef41Sopenharmony_ci      OnPromiseAfter(Handle<JSPromise>::cast(promise_or_capability));
51251cb0ef41Sopenharmony_ci    }
51261cb0ef41Sopenharmony_ci  } else if (current_microtask->IsPromiseResolveThenableJobTask()) {
51271cb0ef41Sopenharmony_ci    Handle<PromiseResolveThenableJobTask> promise_resolve_thenable_job_task =
51281cb0ef41Sopenharmony_ci        Handle<PromiseResolveThenableJobTask>::cast(current_microtask);
51291cb0ef41Sopenharmony_ci    Handle<JSPromise> promise_to_resolve(
51301cb0ef41Sopenharmony_ci        promise_resolve_thenable_job_task->promise_to_resolve(), this);
51311cb0ef41Sopenharmony_ci    OnPromiseAfter(promise_to_resolve);
51321cb0ef41Sopenharmony_ci  }
51331cb0ef41Sopenharmony_ci
51341cb0ef41Sopenharmony_ci  SetTerminationOnExternalTryCatch();
51351cb0ef41Sopenharmony_ci}
51361cb0ef41Sopenharmony_ci
51371cb0ef41Sopenharmony_civoid Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) {
51381cb0ef41Sopenharmony_ci  promise_reject_callback_ = callback;
51391cb0ef41Sopenharmony_ci}
51401cb0ef41Sopenharmony_ci
51411cb0ef41Sopenharmony_civoid Isolate::ReportPromiseReject(Handle<JSPromise> promise,
51421cb0ef41Sopenharmony_ci                                  Handle<Object> value,
51431cb0ef41Sopenharmony_ci                                  v8::PromiseRejectEvent event) {
51441cb0ef41Sopenharmony_ci  if (promise_reject_callback_ == nullptr) return;
51451cb0ef41Sopenharmony_ci  promise_reject_callback_(v8::PromiseRejectMessage(
51461cb0ef41Sopenharmony_ci      v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value)));
51471cb0ef41Sopenharmony_ci}
51481cb0ef41Sopenharmony_ci
51491cb0ef41Sopenharmony_civoid Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) {
51501cb0ef41Sopenharmony_ci  DCHECK(!use_counter_callback_);
51511cb0ef41Sopenharmony_ci  use_counter_callback_ = callback;
51521cb0ef41Sopenharmony_ci}
51531cb0ef41Sopenharmony_ci
51541cb0ef41Sopenharmony_civoid Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) {
51551cb0ef41Sopenharmony_ci  // The counter callback
51561cb0ef41Sopenharmony_ci  // - may cause the embedder to call into V8, which is not generally possible
51571cb0ef41Sopenharmony_ci  //   during GC.
51581cb0ef41Sopenharmony_ci  // - requires a current native context, which may not always exist.
51591cb0ef41Sopenharmony_ci  // TODO(jgruber): Consider either removing the native context requirement in
51601cb0ef41Sopenharmony_ci  // blink, or passing it to the callback explicitly.
51611cb0ef41Sopenharmony_ci  if (heap_.gc_state() == Heap::NOT_IN_GC && !context().is_null()) {
51621cb0ef41Sopenharmony_ci    DCHECK(context().IsContext());
51631cb0ef41Sopenharmony_ci    DCHECK(context().native_context().IsNativeContext());
51641cb0ef41Sopenharmony_ci    if (use_counter_callback_) {
51651cb0ef41Sopenharmony_ci      HandleScope handle_scope(this);
51661cb0ef41Sopenharmony_ci      use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature);
51671cb0ef41Sopenharmony_ci    }
51681cb0ef41Sopenharmony_ci  } else {
51691cb0ef41Sopenharmony_ci    heap_.IncrementDeferredCount(feature);
51701cb0ef41Sopenharmony_ci  }
51711cb0ef41Sopenharmony_ci}
51721cb0ef41Sopenharmony_ci
51731cb0ef41Sopenharmony_civoid Isolate::CountUsage(v8::Isolate::UseCounterFeature feature, int count) {
51741cb0ef41Sopenharmony_ci  for (int i = 0; i < count; ++i) {
51751cb0ef41Sopenharmony_ci    CountUsage(feature);
51761cb0ef41Sopenharmony_ci  }
51771cb0ef41Sopenharmony_ci}
51781cb0ef41Sopenharmony_ci
51791cb0ef41Sopenharmony_ciint Isolate::GetNextScriptId() { return heap()->NextScriptId(); }
51801cb0ef41Sopenharmony_ci
51811cb0ef41Sopenharmony_ci// static
51821cb0ef41Sopenharmony_cistd::string Isolate::GetTurboCfgFileName(Isolate* isolate) {
51831cb0ef41Sopenharmony_ci  if (FLAG_trace_turbo_cfg_file == nullptr) {
51841cb0ef41Sopenharmony_ci    std::ostringstream os;
51851cb0ef41Sopenharmony_ci    os << "turbo-" << base::OS::GetCurrentProcessId() << "-";
51861cb0ef41Sopenharmony_ci    if (isolate != nullptr) {
51871cb0ef41Sopenharmony_ci      os << isolate->id();
51881cb0ef41Sopenharmony_ci    } else {
51891cb0ef41Sopenharmony_ci      os << "any";
51901cb0ef41Sopenharmony_ci    }
51911cb0ef41Sopenharmony_ci    os << ".cfg";
51921cb0ef41Sopenharmony_ci    return os.str();
51931cb0ef41Sopenharmony_ci  } else {
51941cb0ef41Sopenharmony_ci    return FLAG_trace_turbo_cfg_file;
51951cb0ef41Sopenharmony_ci  }
51961cb0ef41Sopenharmony_ci}
51971cb0ef41Sopenharmony_ci
51981cb0ef41Sopenharmony_ci// Heap::detached_contexts tracks detached contexts as pairs
51991cb0ef41Sopenharmony_ci// (number of GC since the context was detached, the context).
52001cb0ef41Sopenharmony_civoid Isolate::AddDetachedContext(Handle<Context> context) {
52011cb0ef41Sopenharmony_ci  HandleScope scope(this);
52021cb0ef41Sopenharmony_ci  Handle<WeakArrayList> detached_contexts = factory()->detached_contexts();
52031cb0ef41Sopenharmony_ci  detached_contexts = WeakArrayList::AddToEnd(
52041cb0ef41Sopenharmony_ci      this, detached_contexts, MaybeObjectHandle(Smi::zero(), this),
52051cb0ef41Sopenharmony_ci      MaybeObjectHandle::Weak(context));
52061cb0ef41Sopenharmony_ci  heap()->set_detached_contexts(*detached_contexts);
52071cb0ef41Sopenharmony_ci}
52081cb0ef41Sopenharmony_ci
52091cb0ef41Sopenharmony_civoid Isolate::CheckDetachedContextsAfterGC() {
52101cb0ef41Sopenharmony_ci  HandleScope scope(this);
52111cb0ef41Sopenharmony_ci  Handle<WeakArrayList> detached_contexts = factory()->detached_contexts();
52121cb0ef41Sopenharmony_ci  int length = detached_contexts->length();
52131cb0ef41Sopenharmony_ci  if (length == 0) return;
52141cb0ef41Sopenharmony_ci  int new_length = 0;
52151cb0ef41Sopenharmony_ci  for (int i = 0; i < length; i += 2) {
52161cb0ef41Sopenharmony_ci    int mark_sweeps = detached_contexts->Get(i).ToSmi().value();
52171cb0ef41Sopenharmony_ci    MaybeObject context = detached_contexts->Get(i + 1);
52181cb0ef41Sopenharmony_ci    DCHECK(context->IsWeakOrCleared());
52191cb0ef41Sopenharmony_ci    if (!context->IsCleared()) {
52201cb0ef41Sopenharmony_ci      detached_contexts->Set(
52211cb0ef41Sopenharmony_ci          new_length, MaybeObject::FromSmi(Smi::FromInt(mark_sweeps + 1)));
52221cb0ef41Sopenharmony_ci      detached_contexts->Set(new_length + 1, context);
52231cb0ef41Sopenharmony_ci      new_length += 2;
52241cb0ef41Sopenharmony_ci    }
52251cb0ef41Sopenharmony_ci  }
52261cb0ef41Sopenharmony_ci  detached_contexts->set_length(new_length);
52271cb0ef41Sopenharmony_ci  while (new_length < length) {
52281cb0ef41Sopenharmony_ci    detached_contexts->Set(new_length, MaybeObject::FromSmi(Smi::zero()));
52291cb0ef41Sopenharmony_ci    ++new_length;
52301cb0ef41Sopenharmony_ci  }
52311cb0ef41Sopenharmony_ci
52321cb0ef41Sopenharmony_ci  if (FLAG_trace_detached_contexts) {
52331cb0ef41Sopenharmony_ci    PrintF("%d detached contexts are collected out of %d\n",
52341cb0ef41Sopenharmony_ci           length - new_length, length);
52351cb0ef41Sopenharmony_ci    for (int i = 0; i < new_length; i += 2) {
52361cb0ef41Sopenharmony_ci      int mark_sweeps = detached_contexts->Get(i).ToSmi().value();
52371cb0ef41Sopenharmony_ci      MaybeObject context = detached_contexts->Get(i + 1);
52381cb0ef41Sopenharmony_ci      DCHECK(context->IsWeakOrCleared());
52391cb0ef41Sopenharmony_ci      if (mark_sweeps > 3) {
52401cb0ef41Sopenharmony_ci        PrintF("detached context %p\n survived %d GCs (leak?)\n",
52411cb0ef41Sopenharmony_ci               reinterpret_cast<void*>(context.ptr()), mark_sweeps);
52421cb0ef41Sopenharmony_ci      }
52431cb0ef41Sopenharmony_ci    }
52441cb0ef41Sopenharmony_ci  }
52451cb0ef41Sopenharmony_ci}
52461cb0ef41Sopenharmony_ci
52471cb0ef41Sopenharmony_civoid Isolate::DetachGlobal(Handle<Context> env) {
52481cb0ef41Sopenharmony_ci  counters()->errors_thrown_per_context()->AddSample(
52491cb0ef41Sopenharmony_ci      env->native_context().GetErrorsThrown());
52501cb0ef41Sopenharmony_ci
52511cb0ef41Sopenharmony_ci  ReadOnlyRoots roots(this);
52521cb0ef41Sopenharmony_ci  Handle<JSGlobalProxy> global_proxy(env->global_proxy(), this);
52531cb0ef41Sopenharmony_ci  global_proxy->set_native_context(roots.null_value());
52541cb0ef41Sopenharmony_ci  // NOTE: Turbofan's JSNativeContextSpecialization depends on DetachGlobal
52551cb0ef41Sopenharmony_ci  // causing a map change.
52561cb0ef41Sopenharmony_ci  JSObject::ForceSetPrototype(this, global_proxy, factory()->null_value());
52571cb0ef41Sopenharmony_ci  global_proxy->map().set_constructor_or_back_pointer(roots.null_value(),
52581cb0ef41Sopenharmony_ci                                                      kRelaxedStore);
52591cb0ef41Sopenharmony_ci  if (FLAG_track_detached_contexts) AddDetachedContext(env);
52601cb0ef41Sopenharmony_ci  DCHECK(global_proxy->IsDetached());
52611cb0ef41Sopenharmony_ci
52621cb0ef41Sopenharmony_ci  env->native_context().set_microtask_queue(this, nullptr);
52631cb0ef41Sopenharmony_ci}
52641cb0ef41Sopenharmony_ci
52651cb0ef41Sopenharmony_cidouble Isolate::LoadStartTimeMs() {
52661cb0ef41Sopenharmony_ci  base::MutexGuard guard(&rail_mutex_);
52671cb0ef41Sopenharmony_ci  return load_start_time_ms_;
52681cb0ef41Sopenharmony_ci}
52691cb0ef41Sopenharmony_ci
52701cb0ef41Sopenharmony_civoid Isolate::UpdateLoadStartTime() {
52711cb0ef41Sopenharmony_ci  base::MutexGuard guard(&rail_mutex_);
52721cb0ef41Sopenharmony_ci  load_start_time_ms_ = heap()->MonotonicallyIncreasingTimeInMs();
52731cb0ef41Sopenharmony_ci}
52741cb0ef41Sopenharmony_ci
52751cb0ef41Sopenharmony_civoid Isolate::SetRAILMode(RAILMode rail_mode) {
52761cb0ef41Sopenharmony_ci  RAILMode old_rail_mode = rail_mode_.load();
52771cb0ef41Sopenharmony_ci  if (old_rail_mode != PERFORMANCE_LOAD && rail_mode == PERFORMANCE_LOAD) {
52781cb0ef41Sopenharmony_ci    base::MutexGuard guard(&rail_mutex_);
52791cb0ef41Sopenharmony_ci    load_start_time_ms_ = heap()->MonotonicallyIncreasingTimeInMs();
52801cb0ef41Sopenharmony_ci  }
52811cb0ef41Sopenharmony_ci  rail_mode_.store(rail_mode);
52821cb0ef41Sopenharmony_ci  if (old_rail_mode == PERFORMANCE_LOAD && rail_mode != PERFORMANCE_LOAD) {
52831cb0ef41Sopenharmony_ci    heap()->incremental_marking()->incremental_marking_job()->ScheduleTask(
52841cb0ef41Sopenharmony_ci        heap());
52851cb0ef41Sopenharmony_ci  }
52861cb0ef41Sopenharmony_ci  if (FLAG_trace_rail) {
52871cb0ef41Sopenharmony_ci    PrintIsolate(this, "RAIL mode: %s\n", RAILModeName(rail_mode));
52881cb0ef41Sopenharmony_ci  }
52891cb0ef41Sopenharmony_ci}
52901cb0ef41Sopenharmony_ci
52911cb0ef41Sopenharmony_civoid Isolate::IsolateInBackgroundNotification() {
52921cb0ef41Sopenharmony_ci  is_isolate_in_background_ = true;
52931cb0ef41Sopenharmony_ci  heap()->ActivateMemoryReducerIfNeeded();
52941cb0ef41Sopenharmony_ci}
52951cb0ef41Sopenharmony_ci
52961cb0ef41Sopenharmony_civoid Isolate::IsolateInForegroundNotification() {
52971cb0ef41Sopenharmony_ci  is_isolate_in_background_ = false;
52981cb0ef41Sopenharmony_ci}
52991cb0ef41Sopenharmony_ci
53001cb0ef41Sopenharmony_civoid Isolate::PrintWithTimestamp(const char* format, ...) {
53011cb0ef41Sopenharmony_ci  base::OS::Print("[%d:%p] %8.0f ms: ", base::OS::GetCurrentProcessId(),
53021cb0ef41Sopenharmony_ci                  static_cast<void*>(this), time_millis_since_init());
53031cb0ef41Sopenharmony_ci  va_list arguments;
53041cb0ef41Sopenharmony_ci  va_start(arguments, format);
53051cb0ef41Sopenharmony_ci  base::OS::VPrint(format, arguments);
53061cb0ef41Sopenharmony_ci  va_end(arguments);
53071cb0ef41Sopenharmony_ci}
53081cb0ef41Sopenharmony_ci
53091cb0ef41Sopenharmony_civoid Isolate::SetIdle(bool is_idle) {
53101cb0ef41Sopenharmony_ci  StateTag state = current_vm_state();
53111cb0ef41Sopenharmony_ci  if (js_entry_sp() != kNullAddress) return;
53121cb0ef41Sopenharmony_ci  DCHECK(state == EXTERNAL || state == IDLE);
53131cb0ef41Sopenharmony_ci  if (is_idle) {
53141cb0ef41Sopenharmony_ci    set_current_vm_state(IDLE);
53151cb0ef41Sopenharmony_ci  } else if (state == IDLE) {
53161cb0ef41Sopenharmony_ci    set_current_vm_state(EXTERNAL);
53171cb0ef41Sopenharmony_ci  }
53181cb0ef41Sopenharmony_ci}
53191cb0ef41Sopenharmony_ci
53201cb0ef41Sopenharmony_civoid Isolate::CollectSourcePositionsForAllBytecodeArrays() {
53211cb0ef41Sopenharmony_ci  if (!initialized_) return;
53221cb0ef41Sopenharmony_ci
53231cb0ef41Sopenharmony_ci  HandleScope scope(this);
53241cb0ef41Sopenharmony_ci  std::vector<Handle<SharedFunctionInfo>> sfis;
53251cb0ef41Sopenharmony_ci  {
53261cb0ef41Sopenharmony_ci    HeapObjectIterator iterator(heap());
53271cb0ef41Sopenharmony_ci    for (HeapObject obj = iterator.Next(); !obj.is_null();
53281cb0ef41Sopenharmony_ci         obj = iterator.Next()) {
53291cb0ef41Sopenharmony_ci      if (!obj.IsSharedFunctionInfo()) continue;
53301cb0ef41Sopenharmony_ci      SharedFunctionInfo sfi = SharedFunctionInfo::cast(obj);
53311cb0ef41Sopenharmony_ci      if (!sfi.CanCollectSourcePosition(this)) continue;
53321cb0ef41Sopenharmony_ci      sfis.push_back(Handle<SharedFunctionInfo>(sfi, this));
53331cb0ef41Sopenharmony_ci    }
53341cb0ef41Sopenharmony_ci  }
53351cb0ef41Sopenharmony_ci  for (auto sfi : sfis) {
53361cb0ef41Sopenharmony_ci    SharedFunctionInfo::EnsureSourcePositionsAvailable(this, sfi);
53371cb0ef41Sopenharmony_ci  }
53381cb0ef41Sopenharmony_ci}
53391cb0ef41Sopenharmony_ci
53401cb0ef41Sopenharmony_ci#ifdef V8_INTL_SUPPORT
53411cb0ef41Sopenharmony_ci
53421cb0ef41Sopenharmony_cinamespace {
53431cb0ef41Sopenharmony_ci
53441cb0ef41Sopenharmony_cistd::string GetStringFromLocales(Isolate* isolate, Handle<Object> locales) {
53451cb0ef41Sopenharmony_ci  if (locales->IsUndefined(isolate)) return "";
53461cb0ef41Sopenharmony_ci  return std::string(String::cast(*locales).ToCString().get());
53471cb0ef41Sopenharmony_ci}
53481cb0ef41Sopenharmony_ci
53491cb0ef41Sopenharmony_cibool StringEqualsLocales(Isolate* isolate, const std::string& str,
53501cb0ef41Sopenharmony_ci                         Handle<Object> locales) {
53511cb0ef41Sopenharmony_ci  if (locales->IsUndefined(isolate)) return str == "";
53521cb0ef41Sopenharmony_ci  return Handle<String>::cast(locales)->IsEqualTo(
53531cb0ef41Sopenharmony_ci      base::VectorOf(str.c_str(), str.length()));
53541cb0ef41Sopenharmony_ci}
53551cb0ef41Sopenharmony_ci
53561cb0ef41Sopenharmony_ci}  // namespace
53571cb0ef41Sopenharmony_ci
53581cb0ef41Sopenharmony_ciconst std::string& Isolate::DefaultLocale() {
53591cb0ef41Sopenharmony_ci  if (default_locale_.empty()) {
53601cb0ef41Sopenharmony_ci    icu::Locale default_locale;
53611cb0ef41Sopenharmony_ci    // Translate ICU's fallback locale to a well-known locale.
53621cb0ef41Sopenharmony_ci    if (strcmp(default_locale.getName(), "en_US_POSIX") == 0 ||
53631cb0ef41Sopenharmony_ci        strcmp(default_locale.getName(), "c") == 0) {
53641cb0ef41Sopenharmony_ci      set_default_locale("en-US");
53651cb0ef41Sopenharmony_ci    } else {
53661cb0ef41Sopenharmony_ci      // Set the locale
53671cb0ef41Sopenharmony_ci      set_default_locale(default_locale.isBogus()
53681cb0ef41Sopenharmony_ci                             ? "und"
53691cb0ef41Sopenharmony_ci                             : Intl::ToLanguageTag(default_locale).FromJust());
53701cb0ef41Sopenharmony_ci    }
53711cb0ef41Sopenharmony_ci    DCHECK(!default_locale_.empty());
53721cb0ef41Sopenharmony_ci  }
53731cb0ef41Sopenharmony_ci  return default_locale_;
53741cb0ef41Sopenharmony_ci}
53751cb0ef41Sopenharmony_ci
53761cb0ef41Sopenharmony_civoid Isolate::ResetDefaultLocale() {
53771cb0ef41Sopenharmony_ci  default_locale_.clear();
53781cb0ef41Sopenharmony_ci  clear_cached_icu_objects();
53791cb0ef41Sopenharmony_ci  // We inline fast paths assuming certain locales. Since this path is rarely
53801cb0ef41Sopenharmony_ci  // taken, we deoptimize everything to keep things simple.
53811cb0ef41Sopenharmony_ci  Deoptimizer::DeoptimizeAll(this);
53821cb0ef41Sopenharmony_ci}
53831cb0ef41Sopenharmony_ci
53841cb0ef41Sopenharmony_ciicu::UMemory* Isolate::get_cached_icu_object(ICUObjectCacheType cache_type,
53851cb0ef41Sopenharmony_ci                                             Handle<Object> locales) {
53861cb0ef41Sopenharmony_ci  const ICUObjectCacheEntry& entry =
53871cb0ef41Sopenharmony_ci      icu_object_cache_[static_cast<int>(cache_type)];
53881cb0ef41Sopenharmony_ci  return StringEqualsLocales(this, entry.locales, locales) ? entry.obj.get()
53891cb0ef41Sopenharmony_ci                                                           : nullptr;
53901cb0ef41Sopenharmony_ci}
53911cb0ef41Sopenharmony_ci
53921cb0ef41Sopenharmony_civoid Isolate::set_icu_object_in_cache(ICUObjectCacheType cache_type,
53931cb0ef41Sopenharmony_ci                                      Handle<Object> locales,
53941cb0ef41Sopenharmony_ci                                      std::shared_ptr<icu::UMemory> obj) {
53951cb0ef41Sopenharmony_ci  icu_object_cache_[static_cast<int>(cache_type)] = {
53961cb0ef41Sopenharmony_ci      GetStringFromLocales(this, locales), std::move(obj)};
53971cb0ef41Sopenharmony_ci}
53981cb0ef41Sopenharmony_ci
53991cb0ef41Sopenharmony_civoid Isolate::clear_cached_icu_object(ICUObjectCacheType cache_type) {
54001cb0ef41Sopenharmony_ci  icu_object_cache_[static_cast<int>(cache_type)] = ICUObjectCacheEntry{};
54011cb0ef41Sopenharmony_ci}
54021cb0ef41Sopenharmony_ci
54031cb0ef41Sopenharmony_civoid Isolate::clear_cached_icu_objects() {
54041cb0ef41Sopenharmony_ci  for (int i = 0; i < kICUObjectCacheTypeCount; i++) {
54051cb0ef41Sopenharmony_ci    clear_cached_icu_object(static_cast<ICUObjectCacheType>(i));
54061cb0ef41Sopenharmony_ci  }
54071cb0ef41Sopenharmony_ci}
54081cb0ef41Sopenharmony_ci
54091cb0ef41Sopenharmony_ci#endif  // V8_INTL_SUPPORT
54101cb0ef41Sopenharmony_ci
54111cb0ef41Sopenharmony_cibool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const {
54121cb0ef41Sopenharmony_ci  StackGuard* stack_guard = isolate_->stack_guard();
54131cb0ef41Sopenharmony_ci#ifdef USE_SIMULATOR
54141cb0ef41Sopenharmony_ci  // The simulator uses a separate JS stack.
54151cb0ef41Sopenharmony_ci  Address jssp_address = Simulator::current(isolate_)->get_sp();
54161cb0ef41Sopenharmony_ci  uintptr_t jssp = static_cast<uintptr_t>(jssp_address);
54171cb0ef41Sopenharmony_ci  if (jssp - gap < stack_guard->real_jslimit()) return true;
54181cb0ef41Sopenharmony_ci#endif  // USE_SIMULATOR
54191cb0ef41Sopenharmony_ci  return GetCurrentStackPosition() - gap < stack_guard->real_climit();
54201cb0ef41Sopenharmony_ci}
54211cb0ef41Sopenharmony_ci
54221cb0ef41Sopenharmony_ciSaveContext::SaveContext(Isolate* isolate) : isolate_(isolate) {
54231cb0ef41Sopenharmony_ci  if (!isolate->context().is_null()) {
54241cb0ef41Sopenharmony_ci    context_ = Handle<Context>(isolate->context(), isolate);
54251cb0ef41Sopenharmony_ci  }
54261cb0ef41Sopenharmony_ci
54271cb0ef41Sopenharmony_ci  c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top());
54281cb0ef41Sopenharmony_ci}
54291cb0ef41Sopenharmony_ci
54301cb0ef41Sopenharmony_ciSaveContext::~SaveContext() {
54311cb0ef41Sopenharmony_ci  isolate_->set_context(context_.is_null() ? Context() : *context_);
54321cb0ef41Sopenharmony_ci}
54331cb0ef41Sopenharmony_ci
54341cb0ef41Sopenharmony_cibool SaveContext::IsBelowFrame(CommonFrame* frame) {
54351cb0ef41Sopenharmony_ci  return (c_entry_fp_ == 0) || (c_entry_fp_ > frame->sp());
54361cb0ef41Sopenharmony_ci}
54371cb0ef41Sopenharmony_ci
54381cb0ef41Sopenharmony_ciSaveAndSwitchContext::SaveAndSwitchContext(Isolate* isolate,
54391cb0ef41Sopenharmony_ci                                           Context new_context)
54401cb0ef41Sopenharmony_ci    : SaveContext(isolate) {
54411cb0ef41Sopenharmony_ci  isolate->set_context(new_context);
54421cb0ef41Sopenharmony_ci}
54431cb0ef41Sopenharmony_ci
54441cb0ef41Sopenharmony_ci#ifdef DEBUG
54451cb0ef41Sopenharmony_ciAssertNoContextChange::AssertNoContextChange(Isolate* isolate)
54461cb0ef41Sopenharmony_ci    : isolate_(isolate), context_(isolate->context(), isolate) {}
54471cb0ef41Sopenharmony_ci
54481cb0ef41Sopenharmony_cinamespace {
54491cb0ef41Sopenharmony_ci
54501cb0ef41Sopenharmony_cibool Overlapping(const MemoryRange& a, const MemoryRange& b) {
54511cb0ef41Sopenharmony_ci  uintptr_t a1 = reinterpret_cast<uintptr_t>(a.start);
54521cb0ef41Sopenharmony_ci  uintptr_t a2 = a1 + a.length_in_bytes;
54531cb0ef41Sopenharmony_ci  uintptr_t b1 = reinterpret_cast<uintptr_t>(b.start);
54541cb0ef41Sopenharmony_ci  uintptr_t b2 = b1 + b.length_in_bytes;
54551cb0ef41Sopenharmony_ci  // Either b1 or b2 are in the [a1, a2) range.
54561cb0ef41Sopenharmony_ci  return (a1 <= b1 && b1 < a2) || (a1 <= b2 && b2 < a2);
54571cb0ef41Sopenharmony_ci}
54581cb0ef41Sopenharmony_ci
54591cb0ef41Sopenharmony_ci}  // anonymous namespace
54601cb0ef41Sopenharmony_ci
54611cb0ef41Sopenharmony_ci#endif  // DEBUG
54621cb0ef41Sopenharmony_ci
54631cb0ef41Sopenharmony_civoid Isolate::AddCodeMemoryRange(MemoryRange range) {
54641cb0ef41Sopenharmony_ci  base::MutexGuard guard(&code_pages_mutex_);
54651cb0ef41Sopenharmony_ci  std::vector<MemoryRange>* old_code_pages = GetCodePages();
54661cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(old_code_pages);
54671cb0ef41Sopenharmony_ci#ifdef DEBUG
54681cb0ef41Sopenharmony_ci  auto overlapping = [range](const MemoryRange& a) {
54691cb0ef41Sopenharmony_ci    return Overlapping(range, a);
54701cb0ef41Sopenharmony_ci  };
54711cb0ef41Sopenharmony_ci  DCHECK_EQ(old_code_pages->end(),
54721cb0ef41Sopenharmony_ci            std::find_if(old_code_pages->begin(), old_code_pages->end(),
54731cb0ef41Sopenharmony_ci                         overlapping));
54741cb0ef41Sopenharmony_ci#endif
54751cb0ef41Sopenharmony_ci
54761cb0ef41Sopenharmony_ci  std::vector<MemoryRange>* new_code_pages;
54771cb0ef41Sopenharmony_ci  if (old_code_pages == &code_pages_buffer1_) {
54781cb0ef41Sopenharmony_ci    new_code_pages = &code_pages_buffer2_;
54791cb0ef41Sopenharmony_ci  } else {
54801cb0ef41Sopenharmony_ci    new_code_pages = &code_pages_buffer1_;
54811cb0ef41Sopenharmony_ci  }
54821cb0ef41Sopenharmony_ci
54831cb0ef41Sopenharmony_ci  // Copy all existing data from the old vector to the new vector and insert the
54841cb0ef41Sopenharmony_ci  // new page.
54851cb0ef41Sopenharmony_ci  new_code_pages->clear();
54861cb0ef41Sopenharmony_ci  new_code_pages->reserve(old_code_pages->size() + 1);
54871cb0ef41Sopenharmony_ci  std::merge(old_code_pages->begin(), old_code_pages->end(), &range, &range + 1,
54881cb0ef41Sopenharmony_ci             std::back_inserter(*new_code_pages),
54891cb0ef41Sopenharmony_ci             [](const MemoryRange& a, const MemoryRange& b) {
54901cb0ef41Sopenharmony_ci               return a.start < b.start;
54911cb0ef41Sopenharmony_ci             });
54921cb0ef41Sopenharmony_ci
54931cb0ef41Sopenharmony_ci  // Atomically switch out the pointer
54941cb0ef41Sopenharmony_ci  SetCodePages(new_code_pages);
54951cb0ef41Sopenharmony_ci}
54961cb0ef41Sopenharmony_ci
54971cb0ef41Sopenharmony_ci// |chunk| is either a Page or an executable LargePage.
54981cb0ef41Sopenharmony_civoid Isolate::AddCodeMemoryChunk(MemoryChunk* chunk) {
54991cb0ef41Sopenharmony_ci  // We only keep track of individual code pages/allocations if we are on arm32,
55001cb0ef41Sopenharmony_ci  // because on x64 and arm64 we have a code range which makes this unnecessary.
55011cb0ef41Sopenharmony_ci#if !defined(V8_TARGET_ARCH_ARM)
55021cb0ef41Sopenharmony_ci  return;
55031cb0ef41Sopenharmony_ci#else
55041cb0ef41Sopenharmony_ci  void* new_page_start = reinterpret_cast<void*>(chunk->area_start());
55051cb0ef41Sopenharmony_ci  size_t new_page_size = chunk->area_size();
55061cb0ef41Sopenharmony_ci
55071cb0ef41Sopenharmony_ci  MemoryRange new_range{new_page_start, new_page_size};
55081cb0ef41Sopenharmony_ci
55091cb0ef41Sopenharmony_ci  AddCodeMemoryRange(new_range);
55101cb0ef41Sopenharmony_ci#endif  // !defined(V8_TARGET_ARCH_ARM)
55111cb0ef41Sopenharmony_ci}
55121cb0ef41Sopenharmony_ci
55131cb0ef41Sopenharmony_civoid Isolate::AddCodeRange(Address begin, size_t length_in_bytes) {
55141cb0ef41Sopenharmony_ci  AddCodeMemoryRange(
55151cb0ef41Sopenharmony_ci      MemoryRange{reinterpret_cast<void*>(begin), length_in_bytes});
55161cb0ef41Sopenharmony_ci}
55171cb0ef41Sopenharmony_ci
55181cb0ef41Sopenharmony_cibool Isolate::RequiresCodeRange() const {
55191cb0ef41Sopenharmony_ci  return kPlatformRequiresCodeRange && !jitless_;
55201cb0ef41Sopenharmony_ci}
55211cb0ef41Sopenharmony_ci
55221cb0ef41Sopenharmony_civ8::metrics::Recorder::ContextId Isolate::GetOrRegisterRecorderContextId(
55231cb0ef41Sopenharmony_ci    Handle<NativeContext> context) {
55241cb0ef41Sopenharmony_ci  if (serializer_enabled_) return v8::metrics::Recorder::ContextId::Empty();
55251cb0ef41Sopenharmony_ci  i::Object id = context->recorder_context_id();
55261cb0ef41Sopenharmony_ci  if (id.IsNullOrUndefined()) {
55271cb0ef41Sopenharmony_ci    CHECK_LT(last_recorder_context_id_, i::Smi::kMaxValue);
55281cb0ef41Sopenharmony_ci    context->set_recorder_context_id(
55291cb0ef41Sopenharmony_ci        i::Smi::FromIntptr(++last_recorder_context_id_));
55301cb0ef41Sopenharmony_ci    v8::HandleScope handle_scope(reinterpret_cast<v8::Isolate*>(this));
55311cb0ef41Sopenharmony_ci    auto result = recorder_context_id_map_.emplace(
55321cb0ef41Sopenharmony_ci        std::piecewise_construct,
55331cb0ef41Sopenharmony_ci        std::forward_as_tuple(last_recorder_context_id_),
55341cb0ef41Sopenharmony_ci        std::forward_as_tuple(reinterpret_cast<v8::Isolate*>(this),
55351cb0ef41Sopenharmony_ci                              ToApiHandle<v8::Context>(context)));
55361cb0ef41Sopenharmony_ci    result.first->second.SetWeak(
55371cb0ef41Sopenharmony_ci        reinterpret_cast<void*>(last_recorder_context_id_),
55381cb0ef41Sopenharmony_ci        RemoveContextIdCallback, v8::WeakCallbackType::kParameter);
55391cb0ef41Sopenharmony_ci    return v8::metrics::Recorder::ContextId(last_recorder_context_id_);
55401cb0ef41Sopenharmony_ci  } else {
55411cb0ef41Sopenharmony_ci    DCHECK(id.IsSmi());
55421cb0ef41Sopenharmony_ci    return v8::metrics::Recorder::ContextId(
55431cb0ef41Sopenharmony_ci        static_cast<uintptr_t>(i::Smi::ToInt(id)));
55441cb0ef41Sopenharmony_ci  }
55451cb0ef41Sopenharmony_ci}
55461cb0ef41Sopenharmony_ci
55471cb0ef41Sopenharmony_ciMaybeLocal<v8::Context> Isolate::GetContextFromRecorderContextId(
55481cb0ef41Sopenharmony_ci    v8::metrics::Recorder::ContextId id) {
55491cb0ef41Sopenharmony_ci  auto result = recorder_context_id_map_.find(id.id_);
55501cb0ef41Sopenharmony_ci  if (result == recorder_context_id_map_.end() || result->second.IsEmpty())
55511cb0ef41Sopenharmony_ci    return MaybeLocal<v8::Context>();
55521cb0ef41Sopenharmony_ci  return result->second.Get(reinterpret_cast<v8::Isolate*>(this));
55531cb0ef41Sopenharmony_ci}
55541cb0ef41Sopenharmony_ci
55551cb0ef41Sopenharmony_civoid Isolate::UpdateLongTaskStats() {
55561cb0ef41Sopenharmony_ci  if (last_long_task_stats_counter_ != isolate_data_.long_task_stats_counter_) {
55571cb0ef41Sopenharmony_ci    last_long_task_stats_counter_ = isolate_data_.long_task_stats_counter_;
55581cb0ef41Sopenharmony_ci    long_task_stats_ = v8::metrics::LongTaskStats{};
55591cb0ef41Sopenharmony_ci  }
55601cb0ef41Sopenharmony_ci}
55611cb0ef41Sopenharmony_ci
55621cb0ef41Sopenharmony_civ8::metrics::LongTaskStats* Isolate::GetCurrentLongTaskStats() {
55631cb0ef41Sopenharmony_ci  UpdateLongTaskStats();
55641cb0ef41Sopenharmony_ci  return &long_task_stats_;
55651cb0ef41Sopenharmony_ci}
55661cb0ef41Sopenharmony_ci
55671cb0ef41Sopenharmony_civoid Isolate::RemoveContextIdCallback(const v8::WeakCallbackInfo<void>& data) {
55681cb0ef41Sopenharmony_ci  Isolate* isolate = reinterpret_cast<Isolate*>(data.GetIsolate());
55691cb0ef41Sopenharmony_ci  uintptr_t context_id = reinterpret_cast<uintptr_t>(data.GetParameter());
55701cb0ef41Sopenharmony_ci  isolate->recorder_context_id_map_.erase(context_id);
55711cb0ef41Sopenharmony_ci}
55721cb0ef41Sopenharmony_ci
55731cb0ef41Sopenharmony_ciLocalHeap* Isolate::main_thread_local_heap() {
55741cb0ef41Sopenharmony_ci  return main_thread_local_isolate()->heap();
55751cb0ef41Sopenharmony_ci}
55761cb0ef41Sopenharmony_ci
55771cb0ef41Sopenharmony_ciLocalHeap* Isolate::CurrentLocalHeap() {
55781cb0ef41Sopenharmony_ci  LocalHeap* local_heap = LocalHeap::Current();
55791cb0ef41Sopenharmony_ci  return local_heap ? local_heap : main_thread_local_heap();
55801cb0ef41Sopenharmony_ci}
55811cb0ef41Sopenharmony_ci
55821cb0ef41Sopenharmony_ci// |chunk| is either a Page or an executable LargePage.
55831cb0ef41Sopenharmony_civoid Isolate::RemoveCodeMemoryChunk(MemoryChunk* chunk) {
55841cb0ef41Sopenharmony_ci  // We only keep track of individual code pages/allocations if we are on arm32,
55851cb0ef41Sopenharmony_ci  // because on x64 and arm64 we have a code range which makes this unnecessary.
55861cb0ef41Sopenharmony_ci#if !defined(V8_TARGET_ARCH_ARM)
55871cb0ef41Sopenharmony_ci  return;
55881cb0ef41Sopenharmony_ci#else
55891cb0ef41Sopenharmony_ci  void* removed_page_start = reinterpret_cast<void*>(chunk->area_start());
55901cb0ef41Sopenharmony_ci  std::vector<MemoryRange>* old_code_pages = GetCodePages();
55911cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(old_code_pages);
55921cb0ef41Sopenharmony_ci
55931cb0ef41Sopenharmony_ci  std::vector<MemoryRange>* new_code_pages;
55941cb0ef41Sopenharmony_ci  if (old_code_pages == &code_pages_buffer1_) {
55951cb0ef41Sopenharmony_ci    new_code_pages = &code_pages_buffer2_;
55961cb0ef41Sopenharmony_ci  } else {
55971cb0ef41Sopenharmony_ci    new_code_pages = &code_pages_buffer1_;
55981cb0ef41Sopenharmony_ci  }
55991cb0ef41Sopenharmony_ci
56001cb0ef41Sopenharmony_ci  // Copy all existing data from the old vector to the new vector except the
56011cb0ef41Sopenharmony_ci  // removed page.
56021cb0ef41Sopenharmony_ci  new_code_pages->clear();
56031cb0ef41Sopenharmony_ci  new_code_pages->reserve(old_code_pages->size() - 1);
56041cb0ef41Sopenharmony_ci  std::remove_copy_if(old_code_pages->begin(), old_code_pages->end(),
56051cb0ef41Sopenharmony_ci                      std::back_inserter(*new_code_pages),
56061cb0ef41Sopenharmony_ci                      [removed_page_start](const MemoryRange& range) {
56071cb0ef41Sopenharmony_ci                        return range.start == removed_page_start;
56081cb0ef41Sopenharmony_ci                      });
56091cb0ef41Sopenharmony_ci  DCHECK_EQ(old_code_pages->size(), new_code_pages->size() + 1);
56101cb0ef41Sopenharmony_ci  // Atomically switch out the pointer
56111cb0ef41Sopenharmony_ci  SetCodePages(new_code_pages);
56121cb0ef41Sopenharmony_ci#endif  // !defined(V8_TARGET_ARCH_ARM)
56131cb0ef41Sopenharmony_ci}
56141cb0ef41Sopenharmony_ci
56151cb0ef41Sopenharmony_ci#undef TRACE_ISOLATE
56161cb0ef41Sopenharmony_ci
56171cb0ef41Sopenharmony_ci// static
56181cb0ef41Sopenharmony_ciAddress Isolate::load_from_stack_count_address(const char* function_name) {
56191cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(function_name);
56201cb0ef41Sopenharmony_ci  if (!stack_access_count_map) {
56211cb0ef41Sopenharmony_ci    stack_access_count_map = new MapOfLoadsAndStoresPerFunction{};
56221cb0ef41Sopenharmony_ci  }
56231cb0ef41Sopenharmony_ci  auto& map = *stack_access_count_map;
56241cb0ef41Sopenharmony_ci  std::string name(function_name);
56251cb0ef41Sopenharmony_ci  // It is safe to return the address of std::map values.
56261cb0ef41Sopenharmony_ci  // Only iterators and references to the erased elements are invalidated.
56271cb0ef41Sopenharmony_ci  return reinterpret_cast<Address>(&map[name].first);
56281cb0ef41Sopenharmony_ci}
56291cb0ef41Sopenharmony_ci
56301cb0ef41Sopenharmony_ci// static
56311cb0ef41Sopenharmony_ciAddress Isolate::store_to_stack_count_address(const char* function_name) {
56321cb0ef41Sopenharmony_ci  DCHECK_NOT_NULL(function_name);
56331cb0ef41Sopenharmony_ci  if (!stack_access_count_map) {
56341cb0ef41Sopenharmony_ci    stack_access_count_map = new MapOfLoadsAndStoresPerFunction{};
56351cb0ef41Sopenharmony_ci  }
56361cb0ef41Sopenharmony_ci  auto& map = *stack_access_count_map;
56371cb0ef41Sopenharmony_ci  std::string name(function_name);
56381cb0ef41Sopenharmony_ci  // It is safe to return the address of std::map values.
56391cb0ef41Sopenharmony_ci  // Only iterators and references to the erased elements are invalidated.
56401cb0ef41Sopenharmony_ci  return reinterpret_cast<Address>(&map[name].second);
56411cb0ef41Sopenharmony_ci}
56421cb0ef41Sopenharmony_ci
56431cb0ef41Sopenharmony_civoid Isolate::AttachToSharedIsolate() {
56441cb0ef41Sopenharmony_ci  DCHECK(!attached_to_shared_isolate_);
56451cb0ef41Sopenharmony_ci
56461cb0ef41Sopenharmony_ci  if (shared_isolate_) {
56471cb0ef41Sopenharmony_ci    DCHECK(shared_isolate_->is_shared());
56481cb0ef41Sopenharmony_ci    shared_isolate_->global_safepoint()->AppendClient(this);
56491cb0ef41Sopenharmony_ci  }
56501cb0ef41Sopenharmony_ci
56511cb0ef41Sopenharmony_ci#if DEBUG
56521cb0ef41Sopenharmony_ci  attached_to_shared_isolate_ = true;
56531cb0ef41Sopenharmony_ci#endif  // DEBUG
56541cb0ef41Sopenharmony_ci}
56551cb0ef41Sopenharmony_ci
56561cb0ef41Sopenharmony_civoid Isolate::DetachFromSharedIsolate() {
56571cb0ef41Sopenharmony_ci  DCHECK(attached_to_shared_isolate_);
56581cb0ef41Sopenharmony_ci
56591cb0ef41Sopenharmony_ci  if (shared_isolate_) {
56601cb0ef41Sopenharmony_ci    shared_isolate_->global_safepoint()->RemoveClient(this);
56611cb0ef41Sopenharmony_ci    shared_isolate_ = nullptr;
56621cb0ef41Sopenharmony_ci  }
56631cb0ef41Sopenharmony_ci
56641cb0ef41Sopenharmony_ci#if DEBUG
56651cb0ef41Sopenharmony_ci  attached_to_shared_isolate_ = false;
56661cb0ef41Sopenharmony_ci#endif  // DEBUG
56671cb0ef41Sopenharmony_ci}
56681cb0ef41Sopenharmony_ci
56691cb0ef41Sopenharmony_ci}  // namespace internal
56701cb0ef41Sopenharmony_ci}  // namespace v8
5671