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

5 6
#ifndef V8_EXECUTION_ISOLATE_H_
#define V8_EXECUTION_ISOLATE_H_
7

8
#include <cstddef>
9
#include <functional>
10
#include <memory>
11
#include <queue>
12
#include <unordered_map>
13
#include <vector>
14

15
#include "include/v8-inspector.h"
16
#include "include/v8-internal.h"
17 18
#include "include/v8.h"
#include "src/base/macros.h"
19
#include "src/builtins/builtins.h"
20
#include "src/common/globals.h"
21
#include "src/debug/interface-types.h"
22 23 24 25
#include "src/execution/execution.h"
#include "src/execution/futex-emulation.h"
#include "src/execution/isolate-data.h"
#include "src/execution/messages.h"
26
#include "src/execution/stack-guard.h"
27
#include "src/handles/handles.h"
28
#include "src/heap/factory.h"
29
#include "src/heap/heap.h"
30
#include "src/heap/read-only-heap.h"
31
#include "src/init/isolate-allocator.h"
32
#include "src/objects/code.h"
33
#include "src/objects/contexts.h"
34
#include "src/objects/debug-objects.h"
35
#include "src/runtime/runtime.h"
36
#include "src/strings/unicode.h"
37
#include "src/utils/allocation.h"
38

39 40 41
#ifdef V8_INTL_SUPPORT
#include "unicode/uversion.h"  // Define U_ICU_NAMESPACE.
namespace U_ICU_NAMESPACE {
42
class UMemory;
43 44 45
}  // namespace U_ICU_NAMESPACE
#endif  // V8_INTL_SUPPORT

46
namespace v8 {
47 48 49 50 51

namespace base {
class RandomNumberGenerator;
}

52 53
namespace debug {
class ConsoleDelegate;
54
class AsyncEventDelegate;
55
}  // namespace debug
56

57 58
namespace internal {

59 60 61 62
namespace heap {
class HeapTester;
}  // namespace heap

63
class AddressToIndexHashMap;
64
class AstStringConstants;
65
class Bootstrapper;
66
class BuiltinsConstantsTableBuilder;
67
class CancelableTaskManager;
68
class CodeEventDispatcher;
69
class CodeTracer;
70
class CompilationCache;
71
class CompilationStatistics;
72
class CompilerDispatcher;
73
class Counters;
74
class Debug;
75
class DeoptimizerData;
76
class DescriptorLookupCache;
77
class EmbeddedFileWriterInterface;
78
class EternalHandles;
79
class HandleScopeImplementer;
80
class HeapObjectToIndexHashMap;
81
class HeapProfiler;
82
class InnerPointerToCodeCache;
83
class Logger;
jarin@chromium.org's avatar
jarin@chromium.org committed
84
class MaterializedObjectStore;
85
class Microtask;
86
class MicrotaskQueue;
87
class OptimizingCompileDispatcher;
88 89
class PersistentHandles;
class PersistentHandlesList;
90
class ReadOnlyArtifacts;
91
class ReadOnlyDeserializer;
92
class RegExpStack;
93
class RootVisitor;
94
class RuntimeProfiler;
95
class SetupIsolateDelegate;
96
class Simulator;
97
class StandardFrame;
98
class StartupDeserializer;
99 100 101 102
class StubCache;
class ThreadManager;
class ThreadState;
class ThreadVisitor;  // Defined in v8threads.h
103
class TracingCpuProfilerImpl;
jarin@chromium.org's avatar
jarin@chromium.org committed
104
class UnicodeCache;
105
struct ManagedPtrDestructor;
106

107 108
template <StateTag Tag>
class VMState;
109

110 111 112
namespace interpreter {
class Interpreter;
}
113

114 115 116 117
namespace compiler {
class PerIsolateCompilerCache;
}

118
namespace wasm {
119
class WasmEngine;
120 121
}

122 123 124 125
namespace win64_unwindinfo {
class BuiltinUnwindInfo;
}

126 127 128 129 130 131 132
#define RETURN_FAILURE_IF_SCHEDULED_EXCEPTION(isolate) \
  do {                                                 \
    Isolate* __isolate__ = (isolate);                  \
    DCHECK(!__isolate__->has_pending_exception());     \
    if (__isolate__->has_scheduled_exception()) {      \
      return __isolate__->PromoteScheduledException(); \
    }                                                  \
133
  } while (false)
134

135 136
// Macros for MaybeHandle.

137 138 139
#define RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, value) \
  do {                                                      \
    Isolate* __isolate__ = (isolate);                       \
140
    DCHECK(!__isolate__->has_pending_exception());          \
141 142 143 144
    if (__isolate__->has_scheduled_exception()) {           \
      __isolate__->PromoteScheduledException();             \
      return value;                                         \
    }                                                       \
145 146
  } while (false)

147 148 149
#define RETURN_EXCEPTION_IF_SCHEDULED_EXCEPTION(isolate, T) \
  RETURN_VALUE_IF_SCHEDULED_EXCEPTION(isolate, MaybeHandle<T>())

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
#define ASSIGN_RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, dst, call, value) \
  do {                                                                        \
    Isolate* __isolate__ = (isolate);                                         \
    if (!(call).ToLocal(&dst)) {                                              \
      DCHECK(__isolate__->has_scheduled_exception());                         \
      __isolate__->PromoteScheduledException();                               \
      return value;                                                           \
    }                                                                         \
  } while (false)

#define RETURN_ON_SCHEDULED_EXCEPTION_VALUE(isolate, call, value) \
  do {                                                            \
    Isolate* __isolate__ = (isolate);                             \
    if ((call).IsNothing()) {                                     \
      DCHECK(__isolate__->has_scheduled_exception());             \
      __isolate__->PromoteScheduledException();                   \
      return value;                                               \
    }                                                             \
  } while (false)

170
/**
171
 * RETURN_RESULT_OR_FAILURE is used in functions with return type Object (such
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
 * as "RUNTIME_FUNCTION(...) {...}" or "BUILTIN(...) {...}" ) to return either
 * the contents of a MaybeHandle<X>, or the "exception" sentinel value.
 * Example usage:
 *
 * RUNTIME_FUNCTION(Runtime_Func) {
 *   ...
 *   RETURN_RESULT_OR_FAILURE(
 *       isolate,
 *       FunctionWithReturnTypeMaybeHandleX(...));
 * }
 *
 * If inside a function with return type MaybeHandle<X> use RETURN_ON_EXCEPTION
 * instead.
 * If inside a function with return type Handle<X>, or Maybe<X> use
 * RETURN_ON_EXCEPTION_VALUE instead.
 */
188 189 190 191 192 193 194 195 196 197
#define RETURN_RESULT_OR_FAILURE(isolate, call)      \
  do {                                               \
    Handle<Object> __result__;                       \
    Isolate* __isolate__ = (isolate);                \
    if (!(call).ToHandle(&__result__)) {             \
      DCHECK(__isolate__->has_pending_exception());  \
      return ReadOnlyRoots(__isolate__).exception(); \
    }                                                \
    DCHECK(!__isolate__->has_pending_exception());   \
    return *__result__;                              \
198 199
  } while (false)

200 201 202 203 204 205
#define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value) \
  do {                                                              \
    if (!(call).ToHandle(&dst)) {                                   \
      DCHECK((isolate)->has_pending_exception());                   \
      return value;                                                 \
    }                                                               \
206 207
  } while (false)

208 209
#define ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call)                \
  do {                                                                        \
210
    auto* __isolate__ = (isolate);                                            \
211 212
    ASSIGN_RETURN_ON_EXCEPTION_VALUE(__isolate__, dst, call,                  \
                                     ReadOnlyRoots(__isolate__).exception()); \
213
  } while (false)
214

215
#define ASSIGN_RETURN_ON_EXCEPTION(isolate, dst, call, T) \
216 217
  ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, MaybeHandle<T>())

218 219 220 221
#define THROW_NEW_ERROR(isolate, call, T)                                \
  do {                                                                   \
    auto* __isolate__ = (isolate);                                       \
    return __isolate__->template Throw<T>(__isolate__->factory()->call); \
222 223
  } while (false)

224 225
#define THROW_NEW_ERROR_RETURN_FAILURE(isolate, call)         \
  do {                                                        \
226
    auto* __isolate__ = (isolate);                            \
227
    return __isolate__->Throw(*__isolate__->factory()->call); \
228 229
  } while (false)

230 231
#define THROW_NEW_ERROR_RETURN_VALUE(isolate, call, value) \
  do {                                                     \
232
    auto* __isolate__ = (isolate);                         \
233 234 235 236
    __isolate__->Throw(*__isolate__->factory()->call);     \
    return value;                                          \
  } while (false)

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
/**
 * RETURN_ON_EXCEPTION_VALUE conditionally returns the given value when the
 * given MaybeHandle is empty. It is typically used in functions with return
 * type Maybe<X> or Handle<X>. Example usage:
 *
 * Handle<X> Func() {
 *   ...
 *   RETURN_ON_EXCEPTION_VALUE(
 *       isolate,
 *       FunctionWithReturnTypeMaybeHandleX(...),
 *       Handle<X>());
 *   // code to handle non exception
 *   ...
 * }
 *
 * Maybe<bool> Func() {
 *   ..
 *   RETURN_ON_EXCEPTION_VALUE(
 *       isolate,
 *       FunctionWithReturnTypeMaybeHandleX(...),
 *       Nothing<bool>);
 *   // code to handle non exception
 *   return Just(true);
 * }
 *
 * If inside a function with return type MaybeHandle<X>, use RETURN_ON_EXCEPTION
 * instead.
264
 * If inside a function with return type Object, use
265 266
 * RETURN_FAILURE_ON_EXCEPTION instead.
 */
267 268 269 270 271 272
#define RETURN_ON_EXCEPTION_VALUE(isolate, call, value) \
  do {                                                  \
    if ((call).is_null()) {                             \
      DCHECK((isolate)->has_pending_exception());       \
      return value;                                     \
    }                                                   \
273 274
  } while (false)

275 276 277
/**
 * RETURN_FAILURE_ON_EXCEPTION conditionally returns the "exception" sentinel if
 * the given MaybeHandle is empty; so it can only be used in functions with
278
 * return type Object, such as RUNTIME_FUNCTION(...) {...} or BUILTIN(...)
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
 * {...}. Example usage:
 *
 * RUNTIME_FUNCTION(Runtime_Func) {
 *   ...
 *   RETURN_FAILURE_ON_EXCEPTION(
 *       isolate,
 *       FunctionWithReturnTypeMaybeHandleX(...));
 *   // code to handle non exception
 *   ...
 * }
 *
 * If inside a function with return type MaybeHandle<X>, use RETURN_ON_EXCEPTION
 * instead.
 * If inside a function with return type Maybe<X> or Handle<X>, use
 * RETURN_ON_EXCEPTION_VALUE instead.
 */
295 296 297 298 299
#define RETURN_FAILURE_ON_EXCEPTION(isolate, call)                     \
  do {                                                                 \
    Isolate* __isolate__ = (isolate);                                  \
    RETURN_ON_EXCEPTION_VALUE(__isolate__, call,                       \
                              ReadOnlyRoots(__isolate__).exception()); \
300
  } while (false);
301

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316
/**
 * RETURN_ON_EXCEPTION conditionally returns an empty MaybeHandle<T> if the
 * given MaybeHandle is empty. Use it to return immediately from a function with
 * return type MaybeHandle when an exception was thrown. Example usage:
 *
 * MaybeHandle<X> Func() {
 *   ...
 *   RETURN_ON_EXCEPTION(
 *       isolate,
 *       FunctionWithReturnTypeMaybeHandleY(...),
 *       X);
 *   // code to handle non exception
 *   ...
 * }
 *
317
 * If inside a function with return type Object, use
318 319 320 321
 * RETURN_FAILURE_ON_EXCEPTION instead.
 * If inside a function with return type
 * Maybe<X> or Handle<X>, use RETURN_ON_EXCEPTION_VALUE instead.
 */
322
#define RETURN_ON_EXCEPTION(isolate, call, T) \
323
  RETURN_ON_EXCEPTION_VALUE(isolate, call, MaybeHandle<T>())
324

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
#define RETURN_FAILURE(isolate, should_throw, call) \
  do {                                              \
    if ((should_throw) == kDontThrow) {             \
      return Just(false);                           \
    } else {                                        \
      isolate->Throw(*isolate->factory()->call);    \
      return Nothing<bool>();                       \
    }                                               \
  } while (false)

#define MAYBE_RETURN(call, value)         \
  do {                                    \
    if ((call).IsNothing()) return value; \
  } while (false)

#define MAYBE_RETURN_NULL(call) MAYBE_RETURN(call, MaybeHandle<Object>())

#define MAYBE_ASSIGN_RETURN_FAILURE_ON_EXCEPTION(isolate, dst, call) \
  do {                                                               \
    Isolate* __isolate__ = (isolate);                                \
    if (!(call).To(&dst)) {                                          \
      DCHECK(__isolate__->has_pending_exception());                  \
      return ReadOnlyRoots(__isolate__).exception();                 \
    }                                                                \
  } while (false)
350

351 352 353 354 355 356 357 358 359 360 361 362 363 364
#define FOR_WITH_HANDLE_SCOPE(isolate, loop_var_type, init, loop_var,      \
                              limit_check, increment, body)                \
  do {                                                                     \
    loop_var_type init;                                                    \
    loop_var_type for_with_handle_limit = loop_var;                        \
    Isolate* for_with_handle_isolate = isolate;                            \
    while (limit_check) {                                                  \
      for_with_handle_limit += 1024;                                       \
      HandleScope loop_scope(for_with_handle_isolate);                     \
      for (; limit_check && loop_var < for_with_handle_limit; increment) { \
        body                                                               \
      }                                                                    \
    }                                                                      \
  } while (false)
365

366 367
#define FIELD_ACCESSOR(type, name)                \
  inline void set_##name(type v) { name##_ = v; } \
368 369
  inline type name() const { return name##_; }

370 371 372 373 374
// Controls for manual embedded blob lifecycle management, used by tests and
// mksnapshot.
V8_EXPORT_PRIVATE void DisableEmbeddedBlobRefcounting();
V8_EXPORT_PRIVATE void FreeCurrentEmbeddedBlob();

375 376
#ifdef DEBUG

377 378 379 380
#define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)               \
  V(CommentStatistic, paged_space_comments_statistics, \
    CommentStatistic::kMaxComments + 1)                \
  V(int, code_kind_statistics, AbstractCode::NUMBER_OF_KINDS)
381 382 383 384 385 386 387 388
#else

#define ISOLATE_INIT_DEBUG_ARRAY_LIST(V)

#endif

#define ISOLATE_INIT_ARRAY_LIST(V)                                             \
  /* SerializerDeserializer state. */                                          \
389
  V(int32_t, jsregexp_static_offsets_vector, kJSRegexpStaticOffsetsVectorSize) \
390 391 392 393 394
  V(int, bad_char_shift_table, kUC16AlphabetSize)                              \
  V(int, good_suffix_shift_table, (kBMMaxShift + 1))                           \
  V(int, suffix_table, (kBMMaxShift + 1))                                      \
  ISOLATE_INIT_DEBUG_ARRAY_LIST(V)

395
using DebugObjectCache = std::vector<Handle<HeapObject>>;
396

397 398 399 400 401 402
#define ISOLATE_INIT_LIST(V)                                                   \
  /* Assembler state. */                                                       \
  V(FatalErrorCallback, exception_behavior, nullptr)                           \
  V(OOMErrorCallback, oom_behavior, nullptr)                                   \
  V(LogEventCallback, event_logger, nullptr)                                   \
  V(AllowCodeGenerationFromStringsCallback, allow_code_gen_callback, nullptr)  \
403 404
  V(ModifyCodeGenerationFromStringsCallback, modify_code_gen_callback,         \
    nullptr)                                                                   \
405 406 407 408 409
  V(AllowWasmCodeGenerationCallback, allow_wasm_code_gen_callback, nullptr)    \
  V(ExtensionCallback, wasm_module_callback, &NoExtension)                     \
  V(ExtensionCallback, wasm_instance_callback, &NoExtension)                   \
  V(WasmStreamingCallback, wasm_streaming_callback, nullptr)                   \
  V(WasmThreadsEnabledCallback, wasm_threads_enabled_callback, nullptr)        \
410
  V(WasmLoadSourceMapCallback, wasm_load_source_map_callback, nullptr)         \
411
  V(WasmSimdEnabledCallback, wasm_simd_enabled_callback, nullptr)              \
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
  /* State for Relocatable. */                                                 \
  V(Relocatable*, relocatable_top, nullptr)                                    \
  V(DebugObjectCache*, string_stream_debug_object_cache, nullptr)              \
  V(Object, string_stream_current_security_token, Object())                    \
  V(const intptr_t*, api_external_references, nullptr)                         \
  V(AddressToIndexHashMap*, external_reference_map, nullptr)                   \
  V(HeapObjectToIndexHashMap*, root_index_map, nullptr)                        \
  V(MicrotaskQueue*, default_microtask_queue, nullptr)                         \
  V(CompilationStatistics*, turbo_statistics, nullptr)                         \
  V(CodeTracer*, code_tracer, nullptr)                                         \
  V(uint32_t, per_isolate_assert_data, 0xFFFFFFFFu)                            \
  V(PromiseRejectCallback, promise_reject_callback, nullptr)                   \
  V(const v8::StartupData*, snapshot_blob, nullptr)                            \
  V(int, code_and_metadata_size, 0)                                            \
  V(int, bytecode_and_metadata_size, 0)                                        \
  V(int, external_script_source_size, 0)                                       \
  /* true if being profiled. Causes collection of extra compile info. */       \
  V(bool, is_profiling, false)                                                 \
430 431
  /* Number of CPU profilers running on the isolate. */                        \
  V(size_t, num_cpu_profilers, 0)                                              \
432 433 434 435 436 437 438 439 440 441 442 443
  /* true if a trace is being formatted through Error.prepareStackTrace. */    \
  V(bool, formatting_stack_trace, false)                                       \
  /* Perform side effect checks on function call and API callbacks. */         \
  V(DebugInfo::ExecutionMode, debug_execution_mode, DebugInfo::kBreakpoints)   \
  /* Current code coverage mode */                                             \
  V(debug::CoverageMode, code_coverage_mode, debug::CoverageMode::kBestEffort) \
  V(debug::TypeProfileMode, type_profile_mode, debug::TypeProfileMode::kNone)  \
  V(int, last_stack_frame_info_id, 0)                                          \
  V(int, last_console_context_id, 0)                                           \
  V(v8_inspector::V8Inspector*, inspector, nullptr)                            \
  V(bool, next_v8_call_is_safe_for_termination, false)                         \
  V(bool, only_terminate_in_safe_scope, false)                                 \
444 445 446
  V(bool, detailed_source_positions_for_profiling, FLAG_detailed_line_info)    \
  V(int, embedder_wrapper_type_index, -1)                                      \
  V(int, embedder_wrapper_object_index, -1)
447

448 449 450
#define THREAD_LOCAL_TOP_ACCESSOR(type, name)                         \
  inline void set_##name(type v) { thread_local_top()->name##_ = v; } \
  inline type name() const { return thread_local_top()->name##_; }
451

452
#define THREAD_LOCAL_TOP_ADDRESS(type, name) \
453
  type* name##_address() { return &thread_local_top()->name##_; }
454

455 456 457
// HiddenFactory exists so Isolate can privately inherit from it without making
// Factory's members available to Isolate directly.
class V8_EXPORT_PRIVATE HiddenFactory : private Factory {};
458

459
class V8_EXPORT_PRIVATE Isolate final : private HiddenFactory {
460 461 462 463
  // These forward declarations are required to make the friend declarations in
  // PerIsolateThreadData work on some older versions of gcc.
  class ThreadDataTable;
  class EntryStackItem;
464

465
 public:
466
  using HandleScopeType = HandleScope;
467 468
  void* operator new(size_t) = delete;
  void operator delete(void*) = delete;
469

470 471 472 473 474 475 476 477 478
  // A thread has a PerIsolateThreadData instance for each isolate that it has
  // entered. That instance is allocated when the isolate is initially entered
  // and reused on subsequent entries.
  class PerIsolateThreadData {
   public:
    PerIsolateThreadData(Isolate* isolate, ThreadId thread_id)
        : isolate_(isolate),
          thread_id_(thread_id),
          stack_limit_(0),
479
          thread_state_(nullptr)
480
#if USE_SIMULATOR
481 482
          ,
          simulator_(nullptr)
483
#endif
484
    {
485
    }
486
    ~PerIsolateThreadData();
487 488
    Isolate* isolate() const { return isolate_; }
    ThreadId thread_id() const { return thread_id_; }
489 490 491

    FIELD_ACCESSOR(uintptr_t, stack_limit)
    FIELD_ACCESSOR(ThreadState*, thread_state)
492

493
#if USE_SIMULATOR
494
    FIELD_ACCESSOR(Simulator*, simulator)
495 496 497
#endif

    bool Matches(Isolate* isolate, ThreadId thread_id) const {
Clemens Hammacher's avatar
Clemens Hammacher committed
498
      return isolate_ == isolate && thread_id_ == thread_id;
499 500 501 502 503 504 505 506
    }

   private:
    Isolate* isolate_;
    ThreadId thread_id_;
    uintptr_t stack_limit_;
    ThreadState* thread_state_;

507
#if USE_SIMULATOR
508 509 510 511 512 513 514 515 516 517
    Simulator* simulator_;
#endif

    friend class Isolate;
    friend class ThreadDataTable;
    friend class EntryStackItem;

    DISALLOW_COPY_AND_ASSIGN(PerIsolateThreadData);
  };

518 519
  static void InitializeOncePerProcess();

520 521
  // Creates Isolate object. Must be used instead of constructing Isolate with
  // new operator.
522
  static Isolate* New(
523
      IsolateAllocationMode mode = IsolateAllocationMode::kDefault);
524 525 526 527 528 529 530

  // Deletes Isolate object. Must be used instead of delete operator.
  // Destroys the non-default isolates.
  // Sets default isolate into "has_been_disposed" state rather then destroying,
  // for legacy API reasons.
  static void Delete(Isolate* isolate);

531
  void SetUpFromReadOnlyArtifacts(std::shared_ptr<ReadOnlyArtifacts> artifacts);
532

533 534 535
  // Returns allocation mode of this isolate.
  V8_INLINE IsolateAllocationMode isolate_allocation_mode();

536 537 538
  // Page allocator that must be used for allocating V8 heap pages.
  v8::PageAllocator* page_allocator();

539 540
  // Returns the PerIsolateThreadData for the current thread (or nullptr if one
  // is not currently set).
541 542
  static PerIsolateThreadData* CurrentPerIsolateThreadData() {
    return reinterpret_cast<PerIsolateThreadData*>(
543
        base::Thread::GetThreadLocal(per_isolate_thread_data_key_));
544 545
  }

546 547
  // Returns the isolate inside which the current thread is running or nullptr.
  V8_INLINE static Isolate* TryGetCurrent() {
548
    DCHECK_EQ(true, isolate_key_created_.load(std::memory_order_relaxed));
549
    return reinterpret_cast<Isolate*>(
550
        base::Thread::GetExistingThreadLocal(isolate_key_));
551 552 553 554 555
  }

  // Returns the isolate inside which the current thread is running.
  V8_INLINE static Isolate* Current() {
    Isolate* isolate = TryGetCurrent();
556
    DCHECK_NOT_NULL(isolate);
557 558 559
    return isolate;
  }

560 561 562 563 564 565
  // Usually called by Init(), but can be called early e.g. to allow
  // testing components that require logging but not the whole
  // isolate.
  //
  // Safe to call more than once.
  void InitializeLoggingAndCounters();
566
  bool InitializeCounters();  // Returns false if already initialized.
567

568 569 570
  bool InitWithoutSnapshot();
  bool InitWithSnapshot(ReadOnlyDeserializer* read_only_deserializer,
                        StartupDeserializer* startup_deserializer);
571 572

  // True if at least one thread Enter'ed this isolate.
573
  bool IsInUse() { return entry_stack_ != nullptr; }
574

575
  void ReleaseSharedPtrs();
576

577 578
  void ClearSerializerData();

579 580
  bool LogObjectRelocation();

581 582 583 584 585 586 587 588 589 590 591
  // Initializes the current thread to run this Isolate.
  // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
  // at the same time, this should be prevented using external locking.
  void Enter();

  // Exits the current thread. The previosuly entered Isolate is restored
  // for the thread.
  // Not thread-safe. Multiple threads should not Enter/Exit the same isolate
  // at the same time, this should be prevented using external locking.
  void Exit();

592 593 594 595
  // Find the PerThread for this particular (isolate, thread) combination.
  // If one does not yet exist, allocate a new one.
  PerIsolateThreadData* FindOrAllocatePerThreadDataForThisThread();

596 597 598 599
  // Find the PerThread for this particular (isolate, thread) combination
  // If one does not yet exist, return null.
  PerIsolateThreadData* FindPerThreadDataForThisThread();

600 601 602 603
  // Find the PerThread for given (isolate, thread) combination
  // If one does not yet exist, return null.
  PerIsolateThreadData* FindPerThreadDataForThread(ThreadId thread_id);

604 605 606 607
  // Discard the PerThread for this particular (isolate, thread) combination
  // If one does not yet exist, no-op.
  void DiscardPerThreadDataForThisThread();

608
  // Mutex for serializing access to break control structures.
609
  base::RecursiveMutex* break_access() { return &break_access_; }
610

611
  Address get_address_from_id(IsolateAddressId id);
612 613

  // Access to top context (where the current function object was created).
614
  Context context() { return thread_local_top()->context_; }
615
  inline void set_context(Context context);
616
  Context* context_address() { return &thread_local_top()->context_; }
617 618

  // Access to current thread id.
619
  THREAD_LOCAL_TOP_ACCESSOR(ThreadId, thread_id)
620 621

  // Interface to pending exception.
622 623
  inline Object pending_exception();
  inline void set_pending_exception(Object exception_obj);
624
  inline void clear_pending_exception();
625

626
  bool AreWasmThreadsEnabled(Handle<Context> context);
627
  bool IsWasmSimdEnabled(Handle<Context> context);
628

629
  THREAD_LOCAL_TOP_ADDRESS(Object, pending_exception)
630

631
  inline bool has_pending_exception();
632

633
  THREAD_LOCAL_TOP_ADDRESS(Context, pending_handler_context)
634
  THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_entrypoint)
635
  THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_constant_pool)
636 637 638
  THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_fp)
  THREAD_LOCAL_TOP_ADDRESS(Address, pending_handler_sp)

639 640
  THREAD_LOCAL_TOP_ACCESSOR(bool, external_caught_exception)

641
  v8::TryCatch* try_catch_handler() {
642
    return thread_local_top()->try_catch_handler_;
643 644
  }
  bool* external_caught_exception_address() {
645
    return &thread_local_top()->external_caught_exception_;
646
  }
647

648
  THREAD_LOCAL_TOP_ADDRESS(Object, scheduled_exception)
649

650
  inline void clear_pending_message();
651
  Address pending_message_obj_address() {
652
    return reinterpret_cast<Address>(&thread_local_top()->pending_message_obj_);
653 654
  }

655
  inline Object scheduled_exception();
656 657
  inline bool has_scheduled_exception();
  inline void clear_scheduled_exception();
658

659 660
  bool IsJavaScriptHandlerOnTop(Object exception);
  bool IsExternalHandlerOnTop(Object exception);
661

662
  inline bool is_catchable_by_javascript(Object exception);
663
  inline bool is_catchable_by_wasm(Object exception);
664 665 666 667 668 669

  // JS execution stack (see frames.h).
  static Address c_entry_fp(ThreadLocalTop* thread) {
    return thread->c_entry_fp_;
  }
  static Address handler(ThreadLocalTop* thread) { return thread->handler_; }
670
  Address c_function() { return thread_local_top()->c_function_; }
671 672

  inline Address* c_entry_fp_address() {
673
    return &thread_local_top()->c_entry_fp_;
674
  }
675 676 677 678 679
  static uint32_t c_entry_fp_offset() {
    return static_cast<uint32_t>(
        OFFSET_OF(Isolate, thread_local_top()->c_entry_fp_) -
        isolate_root_bias());
  }
680
  inline Address* handler_address() { return &thread_local_top()->handler_; }
681
  inline Address* c_function_address() {
682
    return &thread_local_top()->c_function_;
683
  }
684

685
  // Bottom JS entry.
686
  Address js_entry_sp() { return thread_local_top()->js_entry_sp_; }
687
  inline Address* js_entry_sp_address() {
688
    return &thread_local_top()->js_entry_sp_;
689 690
  }

691
  std::vector<MemoryRange>* GetCodePages() const;
692

693
  void SetCodePages(std::vector<MemoryRange>* new_code_pages);
694

695
  // Returns the global object of the current context. It could be
696
  // a builtin object, or a JS global object.
697
  inline Handle<JSGlobalObject> global_object();
698 699

  // Returns the global proxy object of the current context.
700
  inline Handle<JSGlobalProxy> global_proxy();
701 702

  static int ArchiveSpacePerThread() { return sizeof(ThreadLocalTop); }
703
  void FreeThreadResources() { thread_local_top()->Free(); }
704 705 706 707 708

  // This method is called by the api after operations that may throw
  // exceptions.  If an exception was thrown and not handled by an external
  // handler the exception is scheduled to be rethrown when we return to running
  // JavaScript code.  If an exception is scheduled true is returned.
709
  bool OptionalRescheduleException(bool clear_exception);
710

711
  // Push and pop a promise and the current try-catch handler.
712
  void PushPromise(Handle<JSObject> promise);
713
  void PopPromise();
714 715 716

  // Return the relevant Promise that a throw/rejection pertains to, based
  // on the contents of the Promise stack
717 718
  Handle<Object> GetPromiseOnStackOnThrow();

719 720 721
  // Heuristically guess whether a Promise is handled by user catch handler
  bool PromiseHasUserDefinedRejectHandler(Handle<Object> promise);

722 723
  class ExceptionScope {
   public:
724 725
    // Scope currently can only be used for regular exceptions,
    // not termination exception.
726 727
    inline explicit ExceptionScope(Isolate* isolate);
    inline ~ExceptionScope();
728 729 730 731 732 733

   private:
    Isolate* isolate_;
    Handle<Object> pending_exception_;
  };

734
  void SetCaptureStackTraceForUncaughtExceptions(
735
      bool capture, int frame_limit, StackTrace::StackTraceOptions options);
736

737 738 739
  void SetAbortOnUncaughtExceptionCallback(
      v8::Isolate::AbortOnUncaughtExceptionCallback callback);

740
  enum PrintStackMode { kPrintStackConcise, kPrintStackVerbose };
741
  void PrintCurrentStackTrace(FILE* out);
742 743
  void PrintStack(StringStream* accumulator,
                  PrintStackMode mode = kPrintStackVerbose);
744
  void PrintStack(FILE* out, PrintStackMode mode = kPrintStackVerbose);
745
  Handle<String> StackTraceString();
746 747
  // Stores a stack trace in a stack-allocated temporary buffer which will
  // end up in the minidump for debugging purposes.
748 749 750 751
  V8_NOINLINE void PushStackTraceAndDie(void* ptr1 = nullptr,
                                        void* ptr2 = nullptr,
                                        void* ptr3 = nullptr,
                                        void* ptr4 = nullptr);
752 753
  Handle<FixedArray> CaptureCurrentStackTrace(
      int frame_limit, StackTrace::StackTraceOptions options);
754
  Handle<Object> CaptureSimpleStackTrace(Handle<JSReceiver> error_object,
755
                                         FrameSkipMode mode,
756
                                         Handle<Object> caller);
757 758 759
  MaybeHandle<JSReceiver> CaptureAndSetDetailedStackTrace(
      Handle<JSReceiver> error_object);
  MaybeHandle<JSReceiver> CaptureAndSetSimpleStackTrace(
760 761
      Handle<JSReceiver> error_object, FrameSkipMode mode,
      Handle<Object> caller);
762
  Handle<FixedArray> GetDetailedStackTrace(Handle<JSObject> error_object);
763

764 765
  Address GetAbstractPC(int* line, int* column);

766
  // Returns if the given context may access the given global object. If
767 768
  // the result is false, the pending exception is guaranteed to be
  // set.
769
  bool MayAccess(Handle<Context> accessing_context, Handle<JSObject> receiver);
770

771
  void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback);
772
  void ReportFailedAccessCheck(Handle<JSObject> receiver);
773 774

  // Exception throwing support. The caller should use the result
jwolfe's avatar
jwolfe committed
775
  // of Throw() as its return value.
776 777
  Object Throw(Object exception, MessageLocation* location = nullptr);
  Object ThrowIllegalOperation();
778 779

  template <typename T>
780 781
  V8_WARN_UNUSED_RESULT MaybeHandle<T> Throw(
      Handle<Object> exception, MessageLocation* location = nullptr) {
782 783 784 785
    Throw(*exception, location);
    return MaybeHandle<T>();
  }

786 787
  void ThrowAt(Handle<JSObject> exception, MessageLocation* location);

788 789 790 791
  void FatalProcessOutOfHeapMemory(const char* location) {
    heap()->FatalProcessOutOfMemory(location);
  }

792 793 794 795 796
  void set_console_delegate(debug::ConsoleDelegate* delegate) {
    console_delegate_ = delegate;
  }
  debug::ConsoleDelegate* console_delegate() { return console_delegate_; }

797 798 799 800 801 802 803
  void set_async_event_delegate(debug::AsyncEventDelegate* delegate) {
    async_event_delegate_ = delegate;
    PromiseHookStateUpdated();
  }
  void OnAsyncFunctionStateChanged(Handle<JSPromise> promise,
                                   debug::DebugAsyncActionType);

804 805
  // Re-throw an exception.  This involves no error reporting since error
  // reporting was handled when the exception was thrown originally.
806
  Object ReThrow(Object exception);
807 808 809

  // Find the correct handler for the current pending exception. This also
  // clears and returns the current pending exception.
810
  Object UnwindAndFindHandler();
811

812
  // Tries to predict whether an exception will be caught. Note that this can
813
  // only produce an estimate, because it is undecidable whether a finally
814
  // clause will consume or re-throw an exception.
815 816 817 818
  enum CatchType {
    NOT_CAUGHT,
    CAUGHT_BY_JAVASCRIPT,
    CAUGHT_BY_EXTERNAL,
819 820 821
    CAUGHT_BY_DESUGARING,
    CAUGHT_BY_PROMISE,
    CAUGHT_BY_ASYNC_AWAIT
822
  };
823
  CatchType PredictExceptionCatcher();
824

825
  void ScheduleThrow(Object exception);
826 827 828
  // Re-set pending message, script and positions reported to the TryCatch
  // back to the TLS for re-use when rethrowing.
  void RestorePendingMessageFromTryCatch(v8::TryCatch* handler);
829 830
  // Un-schedule an exception that was caught by a TryCatch handler.
  void CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler);
831
  void ReportPendingMessages();
832

833
  // Promote a scheduled exception to pending. Asserts has_scheduled_exception.
834
  Object PromoteScheduledException();
835 836

  // Attempts to compute the current source location, storing the
837 838 839
  // result in the target out parameter. The source location is attached to a
  // Message object as the location which should be shown to the user. It's
  // typically the top-most meaningful location on the stack.
840
  bool ComputeLocation(MessageLocation* target);
841 842
  bool ComputeLocationFromException(MessageLocation* target,
                                    Handle<Object> exception);
843 844
  bool ComputeLocationFromStackTrace(MessageLocation* target,
                                     Handle<Object> exception);
845

846 847
  Handle<JSMessageObject> CreateMessage(Handle<Object> exception,
                                        MessageLocation* location);
848 849
  Handle<JSMessageObject> CreateMessageOrAbort(Handle<Object> exception,
                                               MessageLocation* location);
850 851

  // Out of resource exception helpers.
852 853
  Object StackOverflow();
  Object TerminateExecution();
854
  void CancelTerminateExecution();
855

856
  void RequestInterrupt(InterruptCallback callback, void* data);
857
  void InvokeApiInterruptCallbacks();
858

859
  // Administration
860 861 862
  void Iterate(RootVisitor* v);
  void Iterate(RootVisitor* v, ThreadLocalTop* t);
  char* Iterate(RootVisitor* v, char* t);
863 864
  void IterateThread(ThreadVisitor* v, char* t);

865
  // Returns the current native context.
866
  inline Handle<NativeContext> native_context();
867
  inline NativeContext raw_native_context();
868

869 870
  Handle<Context> GetIncumbentContext();

871 872 873 874 875 876 877 878 879 880
  void RegisterTryCatchHandler(v8::TryCatch* that);
  void UnregisterTryCatchHandler(v8::TryCatch* that);

  char* ArchiveThread(char* to);
  char* RestoreThread(char* from);

  static const int kUC16AlphabetSize = 256;  // See StringSearchBase.
  static const int kBMMaxShift = 250;        // See StringSearchBase.

  // Accessors.
881 882 883 884 885 886 887 888
#define GLOBAL_ACCESSOR(type, name, initialvalue)                \
  inline type name() const {                                     \
    DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
    return name##_;                                              \
  }                                                              \
  inline void set_##name(type value) {                           \
    DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
    name##_ = value;                                             \
889 890 891 892
  }
  ISOLATE_INIT_LIST(GLOBAL_ACCESSOR)
#undef GLOBAL_ACCESSOR

893 894 895 896
#define GLOBAL_ARRAY_ACCESSOR(type, name, length)                \
  inline type* name() {                                          \
    DCHECK(OFFSET_OF(Isolate, name##_) == name##_debug_offset_); \
    return &(name##_)[0];                                        \
897 898 899 900
  }
  ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_ACCESSOR)
#undef GLOBAL_ARRAY_ACCESSOR

901 902
#define NATIVE_CONTEXT_FIELD_ACCESSOR(index, type, name) \
  inline Handle<type> name();                            \
903
  inline bool is_##name(type value);
904 905
  NATIVE_CONTEXT_FIELDS(NATIVE_CONTEXT_FIELD_ACCESSOR)
#undef NATIVE_CONTEXT_FIELD_ACCESSOR
906 907

  Bootstrapper* bootstrapper() { return bootstrapper_; }
908 909 910 911 912 913 914
  // Use for updating counters on a foreground thread.
  Counters* counters() { return async_counters().get(); }
  // Use for updating counters on a background thread.
  const std::shared_ptr<Counters>& async_counters() {
    // Make sure InitializeCounters() has been called.
    DCHECK_NOT_NULL(async_counters_.get());
    return async_counters_;
915
  }
916 917
  RuntimeProfiler* runtime_profiler() { return runtime_profiler_; }
  CompilationCache* compilation_cache() { return compilation_cache_; }
918 919 920
  Logger* logger() {
    // Call InitializeLoggingAndCounters() if logging is needed before
    // the isolate is fully initialized.
921
    DCHECK_NOT_NULL(logger_);
922 923
    return logger_;
  }
924
  StackGuard* stack_guard() { return isolate_data()->stack_guard(); }
925
  Heap* heap() { return &heap_; }
926
  ReadOnlyHeap* read_only_heap() const { return read_only_heap_; }
927 928 929 930
  static Isolate* FromHeap(Heap* heap) {
    return reinterpret_cast<Isolate*>(reinterpret_cast<Address>(heap) -
                                      OFFSET_OF(Isolate, heap_));
  }
931

932 933
  const IsolateData* isolate_data() const { return &isolate_data_; }
  IsolateData* isolate_data() { return &isolate_data_; }
934

935 936 937 938
  // Generated code can embed this address to get access to the isolate-specific
  // data (for example, roots, external references, builtins, etc.).
  // The kRootRegister is set to this value.
  Address isolate_root() const { return isolate_data()->isolate_root(); }
939 940 941
  static size_t isolate_root_bias() {
    return OFFSET_OF(Isolate, isolate_data_) + IsolateData::kIsolateRootBias;
  }
942 943 944
  static Isolate* FromRoot(Address isolate_root) {
    return reinterpret_cast<Isolate*>(isolate_root - isolate_root_bias());
  }
945

946
  RootsTable& roots_table() { return isolate_data()->roots(); }
947

948 949 950 951 952 953 954 955 956 957 958
  // A sub-region of the Isolate object that has "predictable" layout which
  // depends only on the pointer size and therefore it's guaranteed that there
  // will be no compatibility issues because of different compilers used for
  // snapshot generator and actual V8 code.
  // Thus, kRootRegister may be used to address any location that falls into
  // this region.
  // See IsolateData::AssertPredictableLayout() for details.
  base::AddressRegion root_register_addressable_region() const {
    return base::AddressRegion(reinterpret_cast<Address>(&isolate_data_),
                               sizeof(IsolateData));
  }
959

960
  Object root(RootIndex index) { return Object(roots_table()[index]); }
961 962 963 964 965

  Handle<Object> root_handle(RootIndex index) {
    return Handle<Object>(&roots_table()[index]);
  }

966 967 968 969 970
  ExternalReferenceTable* external_reference_table() {
    DCHECK(isolate_data()->external_reference_table()->is_initialized());
    return isolate_data()->external_reference_table();
  }

971
  Address* builtin_entry_table() { return isolate_data_.builtin_entry_table(); }
972
  V8_INLINE Address* builtins_table() { return isolate_data_.builtins(); }
973

974 975
  StubCache* load_stub_cache() { return load_stub_cache_; }
  StubCache* store_stub_cache() { return store_stub_cache_; }
976
  DeoptimizerData* deoptimizer_data() { return deoptimizer_data_; }
977 978 979 980
  bool deoptimizer_lazy_throw() const { return deoptimizer_lazy_throw_; }
  void set_deoptimizer_lazy_throw(bool value) {
    deoptimizer_lazy_throw_ = value;
  }
981
  void InitializeThreadLocal();
982 983 984 985 986 987
  ThreadLocalTop* thread_local_top() {
    return &isolate_data_.thread_local_top_;
  }
  ThreadLocalTop const* thread_local_top() const {
    return &isolate_data_.thread_local_top_;
  }
988 989 990 991 992 993 994 995

  static uint32_t thread_in_wasm_flag_address_offset() {
    // For WebAssembly trap handlers there is a flag in thread-local storage
    // which indicates that the executing thread executes WebAssembly code. To
    // access this flag directly from generated code, we store a pointer to the
    // flag in ThreadLocalTop in thread_in_wasm_flag_address_. This function
    // here returns the offset of that member from {isolate_root()}.
    return static_cast<uint32_t>(
996
        OFFSET_OF(Isolate, thread_local_top()->thread_in_wasm_flag_address_) -
997 998 999
        isolate_root_bias());
  }

jarin@chromium.org's avatar
jarin@chromium.org committed
1000 1001 1002
  MaterializedObjectStore* materialized_object_store() {
    return materialized_object_store_;
  }
1003 1004 1005 1006 1007

  DescriptorLookupCache* descriptor_lookup_cache() {
    return descriptor_lookup_cache_;
  }

1008 1009
  HandleScopeData* handle_scope_data() { return &handle_scope_data_; }

1010
  HandleScopeImplementer* handle_scope_implementer() {
1011
    DCHECK(handle_scope_implementer_);
1012 1013 1014
    return handle_scope_implementer_;
  }

1015
  UnicodeCache* unicode_cache() { return unicode_cache_; }
1016

1017 1018 1019
  InnerPointerToCodeCache* inner_pointer_to_code_cache() {
    return inner_pointer_to_code_cache_;
  }
1020 1021 1022

  GlobalHandles* global_handles() { return global_handles_; }

1023 1024
  EternalHandles* eternal_handles() { return eternal_handles_; }

1025 1026
  ThreadManager* thread_manager() { return thread_manager_; }

1027
#ifndef V8_INTL_SUPPORT
1028 1029 1030 1031 1032 1033 1034 1035 1036
  unibrow::Mapping<unibrow::Ecma262UnCanonicalize>* jsregexp_uncanonicalize() {
    return &jsregexp_uncanonicalize_;
  }

  unibrow::Mapping<unibrow::CanonicalizationRange>* jsregexp_canonrange() {
    return &jsregexp_canonrange_;
  }

  unibrow::Mapping<unibrow::Ecma262Canonicalize>*
1037
  regexp_macro_assembler_canonicalize() {
1038 1039
    return &regexp_macro_assembler_canonicalize_;
  }
1040 1041 1042 1043 1044
#endif  // !V8_INTL_SUPPORT

  RuntimeState* runtime_state() { return &runtime_state_; }

  Builtins* builtins() { return &builtins_; }
1045 1046 1047

  RegExpStack* regexp_stack() { return regexp_stack_; }

1048
  size_t total_regexp_code_generated() { return total_regexp_code_generated_; }
1049
  void IncreaseTotalRegexpCodeGenerated(Handle<HeapObject> code);
1050

1051
  std::vector<int>* regexp_indices() { return &regexp_indices_; }
1052

1053
  Debug* debug() { return debug_; }
1054

1055
  bool* is_profiling_address() { return &is_profiling_; }
1056 1057 1058
  CodeEventDispatcher* code_event_dispatcher() const {
    return code_event_dispatcher_.get();
  }
1059
  HeapProfiler* heap_profiler() const { return heap_profiler_; }
1060

1061
#ifdef DEBUG
1062
  static size_t non_disposed_isolates() { return non_disposed_isolates_; }
1063 1064
#endif

1065 1066 1067
  v8::internal::Factory* factory() {
    // Upcast to the privately inherited base-class using c-style casts to avoid
    // undefined behavior (as static_cast cannot cast across private bases).
1068
    // NOLINTNEXTLINE (google-readability-casting)
1069 1070
    return (v8::internal::Factory*)this;  // NOLINT(readability/casting)
  }
1071

1072
  static const int kJSRegexpStaticOffsetsVectorSize = 128;
1073

1074
  THREAD_LOCAL_TOP_ACCESSOR(ExternalCallbackScope*, external_callback_scope)
1075

1076
  THREAD_LOCAL_TOP_ACCESSOR(StateTag, current_vm_state)
1077

1078
  void SetData(uint32_t slot, void* data) {
1079
    DCHECK_LT(slot, Internals::kNumIsolateDataSlots);
1080
    isolate_data_.embedder_data_[slot] = data;
1081 1082
  }
  void* GetData(uint32_t slot) {
1083
    DCHECK_LT(slot, Internals::kNumIsolateDataSlots);
1084
    return isolate_data_.embedder_data_[slot];
1085
  }
1086

1087
  bool serializer_enabled() const { return serializer_enabled_; }
1088 1089 1090

  void enable_serializer() { serializer_enabled_ = true; }

1091
  bool snapshot_available() const {
1092
    return snapshot_blob_ != nullptr && snapshot_blob_->raw_size != 0;
1093
  }
1094

1095 1096 1097
  bool IsDead() { return has_fatal_error_; }
  void SignalFatalError() { has_fatal_error_ = true; }

1098
  bool use_optimizer();
1099

1100 1101
  bool initialized_from_snapshot() { return initialized_from_snapshot_; }

1102 1103
  bool NeedsSourcePositionsForProfiling() const;

1104
  bool NeedsDetailedOptimizedCodeLineInfo() const;
1105

1106
  bool is_best_effort_code_coverage() const {
1107
    return code_coverage_mode() == debug::CoverageMode::kBestEffort;
1108 1109 1110
  }

  bool is_precise_count_code_coverage() const {
1111
    return code_coverage_mode() == debug::CoverageMode::kPreciseCount;
1112 1113
  }

1114
  bool is_precise_binary_code_coverage() const {
1115
    return code_coverage_mode() == debug::CoverageMode::kPreciseBinary;
1116 1117
  }

1118
  bool is_block_count_code_coverage() const {
1119
    return code_coverage_mode() == debug::CoverageMode::kBlockCount;
1120 1121
  }

1122
  bool is_block_binary_code_coverage() const {
1123
    return code_coverage_mode() == debug::CoverageMode::kBlockBinary;
1124 1125 1126 1127 1128 1129
  }

  bool is_block_code_coverage() const {
    return is_block_count_code_coverage() || is_block_binary_code_coverage();
  }

1130 1131 1132 1133 1134 1135 1136 1137
  bool is_binary_code_coverage() const {
    return is_precise_binary_code_coverage() || is_block_binary_code_coverage();
  }

  bool is_count_code_coverage() const {
    return is_precise_count_code_coverage() || is_block_count_code_coverage();
  }

1138
  bool is_collecting_type_profile() const {
1139
    return type_profile_mode() == debug::TypeProfileMode::kCollect;
1140 1141
  }

1142 1143 1144 1145 1146
  // Collect feedback vectors with data for code coverage or type profile.
  // Reset the list, when both code coverage and type profile are not
  // needed anymore. This keeps many feedback vectors alive, but code
  // coverage or type profile are used for debugging only and increase in
  // memory usage is expected.
1147
  void SetFeedbackVectorsForProfilingTools(Object value);
1148

1149
  void MaybeInitializeVectorListFromHeap();
1150

1151
  double time_millis_since_init() {
1152
    return heap_.MonotonicallyIncreasingTimeInMs() - time_millis_at_init_;
1153 1154
  }

1155
  DateCache* date_cache() { return date_cache_; }
1156

1157
  void set_date_cache(DateCache* date_cache);
1158

1159 1160
#ifdef V8_INTL_SUPPORT

1161 1162
  const std::string& default_locale() { return default_locale_; }

1163 1164
  void ResetDefaultLocale() { default_locale_.clear(); }

1165 1166 1167 1168 1169
  void set_default_locale(const std::string& locale) {
    DCHECK_EQ(default_locale_.length(), 0);
    default_locale_ = locale;
  }

1170 1171 1172 1173 1174
  // enum to access the icu object cache.
  enum class ICUObjectCacheType{
      kDefaultCollator, kDefaultNumberFormat, kDefaultSimpleDateFormat,
      kDefaultSimpleDateFormatForTime, kDefaultSimpleDateFormatForDate};

1175
  icu::UMemory* get_cached_icu_object(ICUObjectCacheType cache_type);
1176
  void set_icu_object_in_cache(ICUObjectCacheType cache_type,
1177
                               std::shared_ptr<icu::UMemory> obj);
1178
  void clear_cached_icu_object(ICUObjectCacheType cache_type);
1179
  void ClearCachedIcuObjects();
1180

1181 1182
#endif  // V8_INTL_SUPPORT

1183 1184 1185
  enum class KnownPrototype { kNone, kObject, kArray, kString };

  KnownPrototype IsArrayOrObjectOrStringPrototype(Object object);
1186

1187 1188 1189 1190
  // On intent to set an element in object, make sure that appropriate
  // notifications occur if the set is on the elements of the array or
  // object prototype. Also ensure that changes to prototype chain between
  // Array and Object fire notifications.
1191 1192 1193
  void UpdateNoElementsProtectorOnSetElement(Handle<JSObject> object);
  void UpdateNoElementsProtectorOnSetLength(Handle<JSObject> object) {
    UpdateNoElementsProtectorOnSetElement(object);
1194
  }
1195 1196
  void UpdateNoElementsProtectorOnSetPrototype(Handle<JSObject> object) {
    UpdateNoElementsProtectorOnSetElement(object);
1197
  }
1198 1199
  void UpdateNoElementsProtectorOnNormalizeElements(Handle<JSObject> object) {
    UpdateNoElementsProtectorOnSetElement(object);
1200
  }
1201

1202 1203 1204
  // Returns true if array is the initial array prototype in any native context.
  bool IsAnyInitialArrayPrototype(Handle<JSArray> array);

1205
  void IterateDeferredHandles(RootVisitor* visitor);
1206 1207 1208
  void LinkDeferredHandles(DeferredHandles* deferred_handles);
  void UnlinkDeferredHandles(DeferredHandles* deferred_handles);

1209 1210 1211 1212 1213 1214
  std::unique_ptr<PersistentHandles> NewPersistentHandles();

  PersistentHandlesList* persistent_handles_list() {
    return persistent_handles_list_.get();
  }

1215
#ifdef DEBUG
1216
  bool IsDeferredHandle(Address* location);
1217 1218
#endif  // DEBUG

1219 1220
  bool concurrent_recompilation_enabled() {
    // Thread is only available with flag enabled.
1221
    DCHECK(optimizing_compile_dispatcher_ == nullptr ||
1222
           FLAG_concurrent_recompilation);
1223
    return optimizing_compile_dispatcher_ != nullptr;
1224 1225
  }

1226 1227
  OptimizingCompileDispatcher* optimizing_compile_dispatcher() {
    return optimizing_compile_dispatcher_;
1228
  }
1229 1230 1231
  // Flushes all pending concurrent optimzation jobs from the optimizing
  // compile dispatcher's queue.
  void AbortConcurrentOptimization(BlockingBehavior blocking_behavior);
1232

1233
  int id() const { return id_; }
1234

1235
  CompilationStatistics* GetTurboStatistics();
1236
  CodeTracer* GetCodeTracer();
1237

1238
  void DumpAndResetStats();
1239

1240 1241
  void* stress_deopt_count_address() { return &stress_deopt_count_; }

1242 1243
  void set_force_slow_path(bool v) { force_slow_path_ = v; }
  bool force_slow_path() const { return force_slow_path_; }
1244 1245
  bool* force_slow_path_address() { return &force_slow_path_; }

1246 1247 1248 1249
  DebugInfo::ExecutionMode* debug_execution_mode_address() {
    return &debug_execution_mode_;
  }

1250
  base::RandomNumberGenerator* random_number_generator();
1251

1252
  base::RandomNumberGenerator* fuzzer_rng();
1253

1254 1255 1256 1257
  // Generates a random number that is non-zero when masked
  // with the provided mask.
  int GenerateIdentityHash(uint32_t mask);

1258
  // Given an address occupied by a live code object, return that object.
1259
  Code FindCodeObject(Address a);
1260

1261 1262 1263 1264 1265 1266 1267 1268
  int NextOptimizationId() {
    int id = next_optimization_id_++;
    if (!Smi::IsValid(next_optimization_id_)) {
      next_optimization_id_ = 0;
    }
    return id;
  }

1269 1270 1271
  void AddNearHeapLimitCallback(v8::NearHeapLimitCallback, void* data);
  void RemoveNearHeapLimitCallback(v8::NearHeapLimitCallback callback,
                                   size_t heap_limit);
1272 1273
  void AddCallCompletedCallback(CallCompletedCallback callback);
  void RemoveCallCompletedCallback(CallCompletedCallback callback);
1274
  void FireCallCompletedCallback(MicrotaskQueue* microtask_queue);
1275

1276 1277
  void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
  void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
1278
  inline void FireBeforeCallEnteredCallback();
1279

1280
  void SetPromiseRejectCallback(PromiseRejectCallback callback);
1281
  void ReportPromiseReject(Handle<JSPromise> promise, Handle<Object> value,
1282 1283
                           v8::PromiseRejectEvent event);

1284
  void SetTerminationOnExternalTryCatch();
1285

1286 1287
  Handle<Symbol> SymbolFor(RootIndex dictionary_index, Handle<String> name,
                           bool private_symbol);
1288

1289
  void SetUseCounterCallback(v8::Isolate::UseCounterCallback callback);
1290 1291
  void CountUsage(v8::Isolate::UseCounterFeature feature);

1292
  static std::string GetTurboCfgFileName(Isolate* isolate);
1293

1294 1295
  int GetNextScriptId();

1296 1297
  int GetNextStackFrameInfoId();

1298
#if V8_SFI_HAS_UNIQUE_ID
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
  int GetNextUniqueSharedFunctionInfoId() {
    int current_id = next_unique_sfi_id_.load(std::memory_order_relaxed);
    int next_id;
    do {
      if (current_id >= Smi::kMaxValue) {
        next_id = 0;
      } else {
        next_id = current_id + 1;
      }
    } while (!next_unique_sfi_id_.compare_exchange_weak(
        current_id, next_id, std::memory_order_relaxed));
    return current_id;
  }
1312 1313
#endif

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
  Address promise_hook_address() {
    return reinterpret_cast<Address>(&promise_hook_);
  }

  Address async_event_delegate_address() {
    return reinterpret_cast<Address>(&async_event_delegate_);
  }

  Address promise_hook_or_async_event_delegate_address() {
    return reinterpret_cast<Address>(&promise_hook_or_async_event_delegate_);
1324
  }
1325

1326 1327 1328 1329 1330
  Address promise_hook_or_debug_is_active_or_async_event_delegate_address() {
    return reinterpret_cast<Address>(
        &promise_hook_or_debug_is_active_or_async_event_delegate_);
  }

1331 1332 1333 1334
  Address handle_scope_implementer_address() {
    return reinterpret_cast<Address>(&handle_scope_implementer_);
  }

1335 1336 1337 1338
  void SetAtomicsWaitCallback(v8::Isolate::AtomicsWaitCallback callback,
                              void* data);
  void RunAtomicsWaitCallback(v8::Isolate::AtomicsWaitEvent event,
                              Handle<JSArrayBuffer> array_buffer,
1339
                              size_t offset_in_bytes, int64_t value,
1340 1341 1342
                              double timeout_in_ms,
                              AtomicsWaitWakeHandle* stop_handle);

1343 1344 1345
  void SetPromiseHook(PromiseHook hook);
  void RunPromiseHook(PromiseHookType type, Handle<JSPromise> promise,
                      Handle<Object> parent);
1346
  void PromiseHookStateUpdated();
1347

1348 1349 1350
  void AddDetachedContext(Handle<Context> context);
  void CheckDetachedContextsAfterGC();

1351 1352
  void AddSharedWasmMemory(Handle<WasmMemoryObject> memory_object);

1353
  std::vector<Object>* startup_object_cache() { return &startup_object_cache_; }
1354

1355
  bool IsGeneratingEmbeddedBuiltins() const {
1356
    return builtins_constants_table_builder() != nullptr;
1357 1358
  }

1359 1360 1361
  BuiltinsConstantsTableBuilder* builtins_constants_table_builder() const {
    return builtins_constants_table_builder_;
  }
1362

1363 1364 1365 1366 1367
  // Hashes bits of the Isolate that are relevant for embedded builtins. In
  // particular, the embedded blob requires builtin Code object layout and the
  // builtins constants table to remain unchanged from build-time.
  size_t HashIsolateForEmbeddedBlob();

1368 1369
  static const uint8_t* CurrentEmbeddedBlob();
  static uint32_t CurrentEmbeddedBlobSize();
1370
  static bool CurrentEmbeddedBlobIsBinaryEmbedded();
1371

1372 1373
  // These always return the same result as static methods above, but don't
  // access the global atomic variable (and thus *might be* slightly faster).
1374 1375
  const uint8_t* embedded_blob() const;
  uint32_t embedded_blob_size() const;
1376

1377 1378 1379 1380 1381 1382 1383
  void set_array_buffer_allocator(v8::ArrayBuffer::Allocator* allocator) {
    array_buffer_allocator_ = allocator;
  }
  v8::ArrayBuffer::Allocator* array_buffer_allocator() const {
    return array_buffer_allocator_;
  }

1384 1385 1386 1387 1388 1389 1390 1391 1392
  void set_array_buffer_allocator_shared(
      std::shared_ptr<v8::ArrayBuffer::Allocator> allocator) {
    array_buffer_allocator_shared_ = std::move(allocator);
  }
  std::shared_ptr<v8::ArrayBuffer::Allocator> array_buffer_allocator_shared()
      const {
    return array_buffer_allocator_shared_;
  }

binji's avatar
binji committed
1393 1394
  FutexWaitListNode* futex_wait_list_node() { return &futex_wait_list_node_; }

1395 1396 1397
  CancelableTaskManager* cancelable_task_manager() {
    return cancelable_task_manager_;
  }
1398

1399
  const AstStringConstants* ast_string_constants() const {
1400 1401 1402
    return ast_string_constants_;
  }

1403 1404
  interpreter::Interpreter* interpreter() const { return interpreter_; }

1405 1406 1407 1408 1409 1410 1411 1412 1413
  compiler::PerIsolateCompilerCache* compiler_cache() const {
    return compiler_cache_;
  }
  void set_compiler_utils(compiler::PerIsolateCompilerCache* cache,
                          Zone* zone) {
    compiler_cache_ = cache;
    compiler_zone_ = zone;
  }

1414
  AccountingAllocator* allocator() { return allocator_; }
1415

1416 1417
  CompilerDispatcher* compiler_dispatcher() const {
    return compiler_dispatcher_;
1418 1419
  }

1420
  bool IsInAnyContext(Object object, uint32_t index);
1421

1422 1423
  void ClearKeptObjects();

1424 1425
  void SetHostImportModuleDynamicallyCallback(
      HostImportModuleDynamicallyCallback callback);
1426 1427
  MaybeHandle<JSPromise> RunHostImportModuleDynamicallyCallback(
      Handle<Script> referrer, Handle<Object> specifier);
1428

1429 1430
  void SetHostInitializeImportMetaObjectCallback(
      HostInitializeImportMetaObjectCallback callback);
1431
  Handle<JSObject> RunHostInitializeImportMetaObjectCallback(
1432
      Handle<SourceTextModule> module);
1433

1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446
  void RegisterEmbeddedFileWriter(EmbeddedFileWriterInterface* writer) {
    embedded_file_writer_ = writer;
  }

  int LookupOrAddExternallyCompiledFilename(const char* filename);
  const char* GetExternallyCompiledFilename(int index) const;
  int GetExternallyCompiledFilenameCount() const;
  // PrepareBuiltinSourcePositionMap is necessary in order to preserve the
  // builtin source positions before the corresponding code objects are
  // replaced with trampolines. Those source positions are used to
  // annotate the builtin blob with debugging information.
  void PrepareBuiltinSourcePositionMap();

1447
#if defined(V8_OS_WIN64)
1448 1449 1450
  void SetBuiltinUnwindData(
      int builtin_index,
      const win64_unwindinfo::BuiltinUnwindInfo& unwinding_info);
1451
#endif  // V8_OS_WIN64
1452

1453 1454
  void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
  MaybeHandle<Object> RunPrepareStackTraceCallback(Handle<Context>,
1455 1456
                                                   Handle<JSObject> Error,
                                                   Handle<JSArray> sites);
1457 1458
  bool HasPrepareStackTraceCallback() const;

1459
  void SetAddCrashKeyCallback(AddCrashKeyCallback callback);
1460 1461 1462 1463 1464
  void AddCrashKey(CrashKeyId id, const std::string& value) {
    if (add_crash_key_callback_) {
      add_crash_key_callback_(id, value);
    }
  }
1465

hpayer's avatar
hpayer committed
1466 1467
  void SetRAILMode(RAILMode rail_mode);

1468
  RAILMode rail_mode() { return rail_mode_.load(); }
1469 1470 1471

  double LoadStartTimeMs();

1472 1473 1474 1475 1476 1477
  void IsolateInForegroundNotification();

  void IsolateInBackgroundNotification();

  bool IsIsolateInBackground() { return is_isolate_in_background_; }

1478 1479 1480 1481 1482 1483
  void EnableMemorySavingsMode() { memory_savings_mode_active_ = true; }

  void DisableMemorySavingsMode() { memory_savings_mode_active_ = false; }

  bool IsMemorySavingsModeActive() { return memory_savings_mode_active_; }

1484
  PRINTF_FORMAT(2, 3) void PrintWithTimestamp(const char* format, ...);
1485

1486 1487 1488
  void set_allow_atomics_wait(bool set) { allow_atomics_wait_ = set; }
  bool allow_atomics_wait() { return allow_atomics_wait_; }

1489
  // Register a finalizer to be called at isolate teardown.
1490
  void RegisterManagedPtrDestructor(ManagedPtrDestructor* finalizer);
1491

1492 1493
  // Removes a previously-registered shared object finalizer.
  void UnregisterManagedPtrDestructor(ManagedPtrDestructor* finalizer);
1494

1495 1496 1497 1498 1499
  size_t elements_deletion_counter() { return elements_deletion_counter_; }
  void set_elements_deletion_counter(size_t value) {
    elements_deletion_counter_ = value;
  }

1500
  wasm::WasmEngine* wasm_engine() const { return wasm_engine_.get(); }
1501
  void SetWasmEngine(std::shared_ptr<wasm::WasmEngine> engine);
1502

1503 1504 1505 1506 1507 1508 1509 1510
  const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope() const {
    return top_backup_incumbent_scope_;
  }
  void set_top_backup_incumbent_scope(
      const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope) {
    top_backup_incumbent_scope_ = top_backup_incumbent_scope;
  }

1511
  void SetIdle(bool is_idle);
1512

1513 1514 1515
  // Changing various modes can cause differences in generated bytecode which
  // interferes with lazy source positions, so this should be called immediately
  // before such a mode change to ensure that this cannot happen.
1516
  void CollectSourcePositionsForAllBytecodeArrays();
1517

1518 1519
  void AddCodeMemoryChunk(MemoryChunk* chunk);
  void RemoveCodeMemoryChunk(MemoryChunk* chunk);
1520
  void AddCodeRange(Address begin, size_t length_in_bytes);
1521

1522 1523
  bool RequiresCodeRange() const;

1524
 private:
1525
  explicit Isolate(std::unique_ptr<IsolateAllocator> isolate_allocator);
1526
  ~Isolate();
1527

1528 1529
  bool Init(ReadOnlyDeserializer* read_only_deserializer,
            StartupDeserializer* startup_deserializer);
1530

1531
  void CheckIsolateLayout();
1532

1533 1534 1535
  void InitializeCodeRanges();
  void AddCodeMemoryRange(MemoryRange range);

1536 1537
  class ThreadDataTable {
   public:
1538
    ThreadDataTable() = default;
1539

1540
    PerIsolateThreadData* Lookup(ThreadId thread_id);
1541 1542
    void Insert(PerIsolateThreadData* data);
    void Remove(PerIsolateThreadData* data);
1543
    void RemoveAllThreads();
1544 1545

   private:
1546 1547 1548 1549 1550 1551 1552
    struct Hasher {
      std::size_t operator()(const ThreadId& t) const {
        return std::hash<int>()(t.ToInteger());
      }
    };

    std::unordered_map<ThreadId, PerIsolateThreadData*, Hasher> table_;
1553 1554 1555 1556 1557 1558
  };

  // These items form a stack synchronously with threads Enter'ing and Exit'ing
  // the Isolate. The top of the stack points to a thread which is currently
  // running the Isolate. When the stack is empty, the Isolate is considered
  // not entered by any thread and can be Disposed.
thakis's avatar
thakis committed
1559
  // If the same thread enters the Isolate more than once, the entry_count_
1560 1561 1562 1563
  // is incremented rather then a new item pushed to the stack.
  class EntryStackItem {
   public:
    EntryStackItem(PerIsolateThreadData* previous_thread_data,
1564
                   Isolate* previous_isolate, EntryStackItem* previous_item)
1565 1566 1567
        : entry_count(1),
          previous_thread_data(previous_thread_data),
          previous_isolate(previous_isolate),
1568
          previous_item(previous_item) {}
1569 1570 1571 1572 1573 1574

    int entry_count;
    PerIsolateThreadData* previous_thread_data;
    Isolate* previous_isolate;
    EntryStackItem* previous_item;

1575
   private:
1576 1577 1578
    DISALLOW_COPY_AND_ASSIGN(EntryStackItem);
  };

1579 1580
  static base::Thread::LocalStorageKey per_isolate_thread_data_key_;
  static base::Thread::LocalStorageKey isolate_key_;
1581

1582 1583
#ifdef DEBUG
  static std::atomic<bool> isolate_key_created_;
1584 1585
#endif

1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
  void Deinit();

  static void SetIsolateThreadLocals(Isolate* isolate,
                                     PerIsolateThreadData* data);

  void MarkCompactPrologue(bool is_compacting,
                           ThreadLocalTop* archived_thread_data);
  void MarkCompactEpilogue(bool is_compacting,
                           ThreadLocalTop* archived_thread_data);

  void FillCache();

1598 1599 1600 1601 1602
  // Propagate pending exception message to the v8::TryCatch.
  // If there is no external try-catch or message was successfully propagated,
  // then return true.
  bool PropagatePendingExceptionToExternalTryCatch();

1603 1604 1605
  void RunPromiseHookForAsyncEventDelegate(PromiseHookType type,
                                           Handle<JSPromise> promise);

hpayer's avatar
hpayer committed
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619
  const char* RAILModeName(RAILMode rail_mode) const {
    switch (rail_mode) {
      case PERFORMANCE_RESPONSE:
        return "RESPONSE";
      case PERFORMANCE_ANIMATION:
        return "ANIMATION";
      case PERFORMANCE_IDLE:
        return "IDLE";
      case PERFORMANCE_LOAD:
        return "LOAD";
    }
    return "";
  }

1620 1621
  void AddCrashKeysForIsolateAndHeapPointers();

1622 1623 1624 1625 1626
  // This class contains a collection of data accessible from both C++ runtime
  // and compiled code (including assembly stubs, builtins, interpreter bytecode
  // handlers and optimized code).
  IsolateData isolate_data_;

1627
  std::unique_ptr<IsolateAllocator> isolate_allocator_;
1628
  Heap heap_;
1629
  ReadOnlyHeap* read_only_heap_ = nullptr;
1630
  std::shared_ptr<ReadOnlyArtifacts> artifacts_;
1631

1632
  const int id_;
1633 1634 1635 1636 1637 1638 1639
  EntryStackItem* entry_stack_ = nullptr;
  int stack_trace_nesting_level_ = 0;
  StringStream* incomplete_message_ = nullptr;
  Address isolate_addresses_[kIsolateAddressCount + 1] = {};
  Bootstrapper* bootstrapper_ = nullptr;
  RuntimeProfiler* runtime_profiler_ = nullptr;
  CompilationCache* compilation_cache_ = nullptr;
1640
  std::shared_ptr<Counters> async_counters_;
1641
  base::RecursiveMutex break_access_;
1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
  Logger* logger_ = nullptr;
  StubCache* load_stub_cache_ = nullptr;
  StubCache* store_stub_cache_ = nullptr;
  DeoptimizerData* deoptimizer_data_ = nullptr;
  bool deoptimizer_lazy_throw_ = false;
  MaterializedObjectStore* materialized_object_store_ = nullptr;
  bool capture_stack_trace_for_uncaught_exceptions_ = false;
  int stack_trace_for_uncaught_exceptions_frame_limit_ = 0;
  StackTrace::StackTraceOptions stack_trace_for_uncaught_exceptions_options_ =
      StackTrace::kOverview;
  DescriptorLookupCache* descriptor_lookup_cache_ = nullptr;
1653
  HandleScopeData handle_scope_data_;
1654 1655 1656 1657 1658 1659 1660
  HandleScopeImplementer* handle_scope_implementer_ = nullptr;
  UnicodeCache* unicode_cache_ = nullptr;
  AccountingAllocator* allocator_ = nullptr;
  InnerPointerToCodeCache* inner_pointer_to_code_cache_ = nullptr;
  GlobalHandles* global_handles_ = nullptr;
  EternalHandles* eternal_handles_ = nullptr;
  ThreadManager* thread_manager_ = nullptr;
1661 1662
  RuntimeState runtime_state_;
  Builtins builtins_;
1663
  SetupIsolateDelegate* setup_delegate_ = nullptr;
1664
#ifndef V8_INTL_SUPPORT
1665 1666 1667 1668
  unibrow::Mapping<unibrow::Ecma262UnCanonicalize> jsregexp_uncanonicalize_;
  unibrow::Mapping<unibrow::CanonicalizationRange> jsregexp_canonrange_;
  unibrow::Mapping<unibrow::Ecma262Canonicalize>
      regexp_macro_assembler_canonicalize_;
1669
#endif  // !V8_INTL_SUPPORT
1670
  RegExpStack* regexp_stack_ = nullptr;
1671
  std::vector<int> regexp_indices_;
1672 1673 1674
  DateCache* date_cache_ = nullptr;
  base::RandomNumberGenerator* random_number_generator_ = nullptr;
  base::RandomNumberGenerator* fuzzer_rng_ = nullptr;
1675
  std::atomic<RAILMode> rail_mode_;
1676 1677 1678 1679 1680
  v8::Isolate::AtomicsWaitCallback atomics_wait_callback_ = nullptr;
  void* atomics_wait_callback_data_ = nullptr;
  PromiseHook promise_hook_ = nullptr;
  HostImportModuleDynamicallyCallback host_import_module_dynamically_callback_ =
      nullptr;
1681
  HostInitializeImportMetaObjectCallback
1682
      host_initialize_import_meta_object_callback_ = nullptr;
1683
  base::Mutex rail_mutex_;
1684
  double load_start_time_ms_ = 0;
1685

1686
#ifdef V8_INTL_SUPPORT
1687
  std::string default_locale_;
1688 1689 1690 1691 1692 1693

  struct ICUObjectCacheTypeHash {
    std::size_t operator()(ICUObjectCacheType a) const {
      return static_cast<std::size_t>(a);
    }
  };
1694
  std::unordered_map<ICUObjectCacheType, std::shared_ptr<icu::UMemory>,
1695 1696 1697
                     ICUObjectCacheTypeHash>
      icu_object_cache_;

1698 1699
#endif  // V8_INTL_SUPPORT

1700
  // Whether the isolate has been created for snapshotting.
1701
  bool serializer_enabled_ = false;
1702

1703
  // True if fatal error has been signaled for this isolate.
1704
  bool has_fatal_error_ = false;
1705

1706
  // True if this isolate was initialized from a snapshot.
1707
  bool initialized_from_snapshot_ = false;
1708

1709
  // TODO(ishell): remove
1710
  // True if ES2015 tail call elimination feature is enabled.
1711
  bool is_tail_call_elimination_enabled_ = true;
1712

1713 1714
  // True if the isolate is in background. This flag is used
  // to prioritize between memory usage and latency.
1715
  bool is_isolate_in_background_ = false;
1716

1717 1718
  // True if the isolate is in memory savings mode. This flag is used to
  // favor memory over runtime performance.
1719
  bool memory_savings_mode_active_ = false;
1720

1721
  // Time stamp at initialization.
1722
  double time_millis_at_init_ = 0;
1723

1724
#ifdef DEBUG
1725
  static std::atomic<size_t> non_disposed_isolates_;
1726

1727 1728 1729
  JSObject::SpillInformation js_spill_information_;
#endif

1730 1731
  Debug* debug_ = nullptr;
  HeapProfiler* heap_profiler_ = nullptr;
1732
  std::unique_ptr<CodeEventDispatcher> code_event_dispatcher_;
1733

1734
  const AstStringConstants* ast_string_constants_ = nullptr;
1735

1736
  interpreter::Interpreter* interpreter_ = nullptr;
1737

1738
  compiler::PerIsolateCompilerCache* compiler_cache_ = nullptr;
1739 1740
  // The following zone is for compiler-related objects that should live
  // through all compilations (and thus all JSHeapBroker instances).
1741 1742
  Zone* compiler_zone_ = nullptr;

1743
  CompilerDispatcher* compiler_dispatcher_ = nullptr;
1744

1745
  using InterruptEntry = std::pair<InterruptCallback, void*>;
1746 1747
  std::queue<InterruptEntry> api_interrupts_queue_;

1748
#define GLOBAL_BACKING_STORE(type, name, initialvalue) type name##_;
1749 1750 1751
  ISOLATE_INIT_LIST(GLOBAL_BACKING_STORE)
#undef GLOBAL_BACKING_STORE

1752
#define GLOBAL_ARRAY_BACKING_STORE(type, name, length) type name##_[length];
1753 1754 1755 1756 1757 1758 1759
  ISOLATE_INIT_ARRAY_LIST(GLOBAL_ARRAY_BACKING_STORE)
#undef GLOBAL_ARRAY_BACKING_STORE

#ifdef DEBUG
  // This class is huge and has a number of fields controlled by
  // preprocessor defines. Make sure the offsets of these fields agree
  // between compilation units.
1760
#define ISOLATE_FIELD_OFFSET(type, name, ignored) \
1761
  static const intptr_t name##_debug_offset_;
1762 1763 1764 1765 1766
  ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET)
  ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET)
#undef ISOLATE_FIELD_OFFSET
#endif

1767 1768
  DeferredHandles* deferred_handles_head_ = nullptr;
  OptimizingCompileDispatcher* optimizing_compile_dispatcher_ = nullptr;
1769

1770 1771
  std::unique_ptr<PersistentHandlesList> persistent_handles_list_;

1772
  // Counts deopt points if deopt_every_n_times is enabled.
1773
  unsigned int stress_deopt_count_ = 0;
1774

1775
  bool force_slow_path_ = false;
1776

1777 1778
  bool jitless_ = false;

1779
  int next_optimization_id_ = 0;
1780

1781
#if V8_SFI_HAS_UNIQUE_ID
1782
  std::atomic<int> next_unique_sfi_id_;
1783 1784
#endif

1785 1786
  // Vector of callbacks before a Call starts execution.
  std::vector<BeforeCallEnteredCallback> before_call_entered_callbacks_;
1787

1788 1789
  // Vector of callbacks when a Call completes.
  std::vector<CallCompletedCallback> call_completed_callbacks_;
1790

1791
  v8::Isolate::UseCounterCallback use_counter_callback_ = nullptr;
1792

1793
  std::vector<Object> startup_object_cache_;
1794

1795 1796 1797
  // Used during builtins compilation to build the builtins constants table,
  // which is stored on the root list prior to serialization.
  BuiltinsConstantsTableBuilder* builtins_constants_table_builder_ = nullptr;
1798

1799 1800 1801 1802
  void InitializeDefaultEmbeddedBlob();
  void CreateAndSetEmbeddedBlob();
  void TearDownEmbeddedBlob();

1803
  void SetEmbeddedBlob(const uint8_t* blob, uint32_t blob_size);
1804
  void ClearEmbeddedBlob();
1805

1806 1807
  const uint8_t* embedded_blob_ = nullptr;
  uint32_t embedded_blob_size_ = 0;
1808

1809
  v8::ArrayBuffer::Allocator* array_buffer_allocator_ = nullptr;
1810
  std::shared_ptr<v8::ArrayBuffer::Allocator> array_buffer_allocator_shared_;
1811

binji's avatar
binji committed
1812 1813
  FutexWaitListNode futex_wait_list_node_;

1814
  CancelableTaskManager* cancelable_task_manager_ = nullptr;
1815

1816 1817
  debug::ConsoleDelegate* console_delegate_ = nullptr;

1818 1819
  debug::AsyncEventDelegate* async_event_delegate_ = nullptr;
  bool promise_hook_or_async_event_delegate_ = false;
1820
  bool promise_hook_or_debug_is_active_or_async_event_delegate_ = false;
1821 1822
  int async_task_count_ = 0;

1823
  v8::Isolate::AbortOnUncaughtExceptionCallback
1824
      abort_on_uncaught_exception_callback_ = nullptr;
1825

1826
  bool allow_atomics_wait_ = true;
1827

1828
  base::Mutex managed_ptr_destructors_mutex_;
1829
  ManagedPtrDestructor* managed_ptr_destructors_head_ = nullptr;
1830

1831
  size_t total_regexp_code_generated_ = 0;
1832

1833 1834
  size_t elements_deletion_counter_ = 0;

1835
  std::shared_ptr<wasm::WasmEngine> wasm_engine_;
1836

1837 1838
  std::unique_ptr<TracingCpuProfilerImpl> tracing_cpu_profiler_;

1839 1840
  EmbeddedFileWriterInterface* embedded_file_writer_ = nullptr;

1841 1842 1843 1844
  // The top entry of the v8::Context::BackupIncumbentScope stack.
  const v8::Context::BackupIncumbentScope* top_backup_incumbent_scope_ =
      nullptr;

1845 1846
  PrepareStackTraceCallback prepare_stack_trace_callback_ = nullptr;

1847 1848 1849 1850 1851 1852
  // TODO(kenton@cloudflare.com): This mutex can be removed if
  // thread_data_table_ is always accessed under the isolate lock. I do not
  // know if this is the case, so I'm preserving it for now.
  base::Mutex thread_data_table_mutex_;
  ThreadDataTable thread_data_table_;

1853 1854 1855 1856 1857 1858
  // A signal-safe vector of heap pages containing code. Used with the
  // v8::Unwinder API.
  std::atomic<std::vector<MemoryRange>*> code_pages_{nullptr};
  std::vector<MemoryRange> code_pages_buffer1_;
  std::vector<MemoryRange> code_pages_buffer2_;

1859 1860 1861 1862 1863
  // Enables the host application to provide a mechanism for recording a
  // predefined set of data as crash keys to be used in postmortem debugging
  // in case of a crash.
  AddCrashKeyCallback add_crash_key_callback_ = nullptr;

1864 1865 1866 1867
  // Delete new/delete operators to ensure that Isolate::New() and
  // Isolate::Delete() are used for Isolate creation and deletion.
  void* operator new(size_t, void* ptr) { return ptr; }

1868
  friend class heap::HeapTester;
1869
  friend class TestSerializer;
1870 1871 1872 1873

  DISALLOW_COPY_AND_ASSIGN(Isolate);
};

1874 1875 1876
#undef FIELD_ACCESSOR
#undef THREAD_LOCAL_TOP_ACCESSOR

1877 1878
class PromiseOnStack {
 public:
1879 1880
  PromiseOnStack(Handle<JSObject> promise, PromiseOnStack* prev)
      : promise_(promise), prev_(prev) {}
1881 1882 1883 1884 1885 1886 1887 1888
  Handle<JSObject> promise() { return promise_; }
  PromiseOnStack* prev() { return prev_; }

 private:
  Handle<JSObject> promise_;
  PromiseOnStack* prev_;
};

1889 1890
// SaveContext scopes save the current context on the Isolate on creation, and
// restore it on destruction.
1891
class V8_EXPORT_PRIVATE SaveContext {
1892
 public:
1893
  explicit SaveContext(Isolate* isolate);
1894

1895
  ~SaveContext();
1896 1897 1898 1899

  Handle<Context> context() { return context_; }

  // Returns true if this save context is below a given JavaScript frame.
1900
  bool IsBelowFrame(StandardFrame* frame);
1901 1902

 private:
1903
  Isolate* const isolate_;
1904
  Handle<Context> context_;
1905
  Address c_entry_fp_;
1906 1907
};

1908 1909 1910 1911 1912 1913 1914
// Like SaveContext, but also switches the Context to a new one in the
// constructor.
class V8_EXPORT_PRIVATE SaveAndSwitchContext : public SaveContext {
 public:
  SaveAndSwitchContext(Isolate* isolate, Context new_context);
};

1915 1916 1917 1918 1919 1920 1921 1922
// A scope which sets the given isolate's context to null for its lifetime to
// ensure that code does not make assumptions on a context being available.
class NullContextScope : public SaveAndSwitchContext {
 public:
  explicit NullContextScope(Isolate* isolate)
      : SaveAndSwitchContext(isolate, Context()) {}
};

1923
class AssertNoContextChange {
1924 1925
#ifdef DEBUG
 public:
1926
  explicit AssertNoContextChange(Isolate* isolate);
1927
  ~AssertNoContextChange() { DCHECK(isolate_->context() == *context_); }
1928 1929

 private:
1930
  Isolate* isolate_;
1931 1932 1933
  Handle<Context> context_;
#else
 public:
1934
  explicit AssertNoContextChange(Isolate* isolate) {}
1935 1936 1937
#endif
};

1938
class ExecutionAccess {
1939 1940 1941 1942 1943 1944
 public:
  explicit ExecutionAccess(Isolate* isolate) : isolate_(isolate) {
    Lock(isolate);
  }
  ~ExecutionAccess() { Unlock(isolate_); }

1945 1946
  static void Lock(Isolate* isolate) { isolate->break_access()->Lock(); }
  static void Unlock(Isolate* isolate) { isolate->break_access()->Unlock(); }
1947 1948

  static bool TryLock(Isolate* isolate) {
1949
    return isolate->break_access()->TryLock();
1950 1951 1952 1953 1954 1955
  }

 private:
  Isolate* isolate_;
};

1956
// Support for checking for stack-overflows.
1957
class StackLimitCheck {
1958
 public:
1959
  explicit StackLimitCheck(Isolate* isolate) : isolate_(isolate) {}
1960

1961
  // Use this to check for stack-overflows in C++ code.
1962
  bool HasOverflowed() const {
1963
    StackGuard* stack_guard = isolate_->stack_guard();
1964
    return GetCurrentStackPosition() < stack_guard->real_climit();
1965
  }
1966

1967 1968 1969 1970 1971 1972
  // Use this to check for interrupt request in C++ code.
  bool InterruptRequested() {
    StackGuard* stack_guard = isolate_->stack_guard();
    return GetCurrentStackPosition() < stack_guard->climit();
  }

1973
  // Use this to check for stack-overflow when entering runtime from JS code.
1974
  bool JsHasOverflowed(uintptr_t gap = 0) const;
1975

1976 1977 1978 1979
 private:
  Isolate* isolate_;
};

1980 1981 1982 1983 1984 1985 1986
#define STACK_CHECK(isolate, result_value) \
  do {                                     \
    StackLimitCheck stack_check(isolate);  \
    if (stack_check.HasOverflowed()) {     \
      isolate->StackOverflow();            \
      return result_value;                 \
    }                                      \
1987
  } while (false)
1988

1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
class StackTraceFailureMessage {
 public:
  explicit StackTraceFailureMessage(Isolate* isolate, void* ptr1 = nullptr,
                                    void* ptr2 = nullptr, void* ptr3 = nullptr,
                                    void* ptr4 = nullptr);

  V8_NOINLINE void Print() volatile;

  static const uintptr_t kStartMarker = 0xdecade30;
  static const uintptr_t kEndMarker = 0xdecade31;
  static const int kStacktraceBufferSize = 32 * KB;

  uintptr_t start_marker_ = kStartMarker;
  void* isolate_;
  void* ptr1_;
  void* ptr2_;
  void* ptr3_;
  void* ptr4_;
  void* code_objects_[4];
  char js_stack_trace_[kStacktraceBufferSize];
  uintptr_t end_marker_ = kEndMarker;
};

2012 2013
}  // namespace internal
}  // namespace v8
2014

2015
#endif  // V8_EXECUTION_ISOLATE_H_