deps: patch the V8 API to be backwards compatible with 6.7

PR-URL: https://github.com/nodejs/node/pull/21668
Fixes: https://github.com/I
Reviewed-By: Refael Ackermann <refack@gmail.com>
Reviewed-By: Myles Borins <myles.borins@gmail.com>
This commit is contained in:
Peter Marshall authored and Rod Vagg committed 2018-08-15 20:23:17 +10:00
1 parent 6daa4f8797
commit 5fa3ffad20
25 files changed
+326 -406

No files matched your search

+1 -1
View File
@@ -62,7 +62,7 @@ V8_PLATFORM_EXPORT bool PumpMessageLoop(
v8::Platform* platform, v8::Isolate* isolate,
MessageLoopBehavior behavior = MessageLoopBehavior::kDoNotWait);
V8_PLATFORM_EXPORT V8_DEPRECATED(
V8_PLATFORM_EXPORT V8_DEPRECATE_SOON(
"This function has become obsolete and is essentially a nop",
void EnsureEventLoopInitialized(v8::Platform* platform,
v8::Isolate* isolate));
-1
View File
@@ -99,7 +99,6 @@ class V8_EXPORT V8ContextInfo {
class V8_EXPORT V8StackTrace {
public:
virtual StringView firstNonEmptySourceURL() const = 0;
virtual bool isEmpty() const = 0;
virtual StringView topSourceURL() const = 0;
virtual int topLineNumber() const = 0;
+96 -17
View File
@@ -246,6 +246,16 @@ class PageAllocator {
*/
class Platform {
public:
/**
* This enum is used to indicate whether a task is potentially long running,
* or causes a long wait. The embedder might want to use this hint to decide
* whether to execute the task on a dedicated thread.
*/
enum ExpectedRuntime {
kShortRunningTask,
kLongRunningTask
};
virtual ~Platform() = default;
/**
@@ -280,25 +290,101 @@ class Platform {
virtual bool OnCriticalMemoryPressure(size_t length) { return false; }
/**
* Gets the number of worker threads used by
* Call(BlockingTask)OnWorkerThread(). This can be used to estimate the number
* of tasks a work package should be split into. A return value of 0 means
* that there are no worker threads available. Note that a value of 0 won't
* prohibit V8 from posting tasks using |CallOnWorkerThread|.
* Gets the number of worker threads used by GetWorkerThreadsTaskRunner() and
* CallOnWorkerThread(). This can be used to estimate the number of tasks a
* work package should be split into. A return value of 0 means that there are
* no worker threads available. Note that a value of 0 won't prohibit V8 from
* posting tasks using |CallOnWorkerThread|.
*/
virtual int NumberOfWorkerThreads() = 0;
virtual int NumberOfWorkerThreads() {
return static_cast<int>(NumberOfAvailableBackgroundThreads());
}
/**
* Deprecated. Use NumberOfWorkerThreads() instead.
* TODO(gab): Remove this when all embedders override
* NumberOfWorkerThreads() instead.
*/
V8_DEPRECATE_SOON(
"NumberOfAvailableBackgroundThreads() is deprecated, use "
"NumberOfAvailableBackgroundThreads() instead.",
virtual size_t NumberOfAvailableBackgroundThreads()) {
return 0;
}
/**
* Returns a TaskRunner which can be used to post a task on the foreground.
* This function should only be called from a foreground thread.
*/
virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner(
Isolate* isolate) = 0;
Isolate* isolate) {
// TODO(ahaas): Make this function abstract after it got implemented on all
// platforms.
return {};
}
/**
* Returns a TaskRunner which can be used to post a task on a background.
* This function should only be called from a foreground thread.
*/
V8_DEPRECATE_SOON(
"GetBackgroundTaskRunner() is deprecated, use "
"GetWorkerThreadsTaskRunner() "
"instead.",
virtual std::shared_ptr<v8::TaskRunner> GetBackgroundTaskRunner(
Isolate* isolate)) {
// TODO(gab): Remove this method when all embedders have moved to
// GetWorkerThreadsTaskRunner().
// An implementation needs to be provided here because this is called by the
// default GetWorkerThreadsTaskRunner() implementation below. In practice
// however, all code either:
// - Overrides GetWorkerThreadsTaskRunner() (thus not making this call) --
// i.e. all v8 code.
// - Overrides this method (thus not making this call) -- i.e. all
// unadapted embedders.
abort();
}
/**
* Returns a TaskRunner which can be used to post async tasks on a worker.
* This function should only be called from a foreground thread.
*/
virtual std::shared_ptr<v8::TaskRunner> GetWorkerThreadsTaskRunner(
Isolate* isolate) {
// TODO(gab): Make this function abstract after it got implemented on all
// platforms.
return GetBackgroundTaskRunner(isolate);
}
/**
* Schedules a task to be invoked on a background thread. |expected_runtime|
* indicates that the task will run a long time. The Platform implementation
* takes ownership of |task|. There is no guarantee about order of execution
* of tasks wrt order of scheduling, nor is there a guarantee about the
* thread the task will be run on.
*/
V8_DEPRECATE_SOON(
"ExpectedRuntime is deprecated, use CallOnWorkerThread() instead.",
virtual void CallOnBackgroundThread(Task* task,
ExpectedRuntime expected_runtime)) {
// An implementation needs to be provided here because this is called by the
// default implementation below. In practice however, all code either:
// - Overrides the new method (thus not making this call) -- i.e. all v8
// code.
// - Overrides this method (thus not making this call) -- i.e. all
// unadapted embedders.
abort();
}
/**
* Schedules a task to be invoked on a worker thread.
* TODO(gab): Make pure virtual when all embedders override this instead of
* CallOnBackgroundThread().
*/
virtual void CallOnWorkerThread(std::unique_ptr<Task> task) = 0;
virtual void CallOnWorkerThread(std::unique_ptr<Task> task) {
CallOnBackgroundThread(task.release(), kShortRunningTask);
}
/**
* Schedules a task that blocks the main thread to be invoked with
@@ -310,13 +396,6 @@ class Platform {
CallOnWorkerThread(std::move(task));
}
/**
* Schedules a task to be invoked on a worker thread after |delay_in_seconds|
* expires.
*/
virtual void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
double delay_in_seconds) = 0;
/**
* Schedules a task to be invoked on a foreground thread wrt a specific
* |isolate|. Tasks posted for the same isolate should be execute in order of
@@ -342,14 +421,14 @@ class Platform {
* The definition of "foreground" is opaque to V8.
*/
virtual void CallIdleOnForegroundThread(Isolate* isolate, IdleTask* task) {
// This must be overriden if |IdleTasksEnabled()|.
abort();
// TODO(ulan): Make this function abstract after V8 roll in Chromium.
}
/**
* Returns true if idle tasks are enabled for the given |isolate|.
*/
virtual bool IdleTasksEnabled(Isolate* isolate) {
// TODO(ulan): Make this function abstract after V8 roll in Chromium.
return false;
}
+1 -5
View File
@@ -54,11 +54,7 @@ namespace v8 {
*/
class V8_EXPORT TracingCpuProfiler {
public:
V8_DEPRECATE_SOON(
"The profiler is created automatically with the isolate.\n"
"No need to create it explicitly.",
static std::unique_ptr<TracingCpuProfiler> Create(Isolate*));
static std::unique_ptr<TracingCpuProfiler> Create(Isolate*);
virtual ~TracingCpuProfiler() = default;
protected:
+99 -129
View File
@@ -156,95 +156,6 @@ class GlobalHandles;
namespace wasm {
class StreamingDecoder;
} // namespace wasm
/**
* Configuration of tagging scheme.
*/
const int kApiPointerSize = sizeof(void*); // NOLINT
const int kApiDoubleSize = sizeof(double); // NOLINT
const int kApiIntSize = sizeof(int); // NOLINT
const int kApiInt64Size = sizeof(int64_t); // NOLINT
// Tag information for HeapObject.
const int kHeapObjectTag = 1;
const int kWeakHeapObjectTag = 3;
const int kHeapObjectTagSize = 2;
const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
// Tag information for Smi.
const int kSmiTag = 0;
const int kSmiTagSize = 1;
const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
template <size_t ptr_size>
struct SmiTagging;
template <int kSmiShiftSize>
V8_INLINE internal::Object* IntToSmi(int value) {
int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
uintptr_t tagged_value =
(static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
return reinterpret_cast<internal::Object*>(tagged_value);
}
// Smi constants for 32-bit systems.
template <>
struct SmiTagging<4> {
enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
static int SmiShiftSize() { return kSmiShiftSize; }
static int SmiValueSize() { return kSmiValueSize; }
V8_INLINE static int SmiToInt(const internal::Object* value) {
int shift_bits = kSmiTagSize + kSmiShiftSize;
// Throw away top 32 bits and shift down (requires >> to be sign extending).
return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return internal::IntToSmi<kSmiShiftSize>(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
// To be representable as an tagged small integer, the two
// most-significant bits of 'value' must be either 00 or 11 due to
// sign-extension. To check this we add 01 to the two
// most-significant bits, and check if the most-significant bit is 0
//
// CAUTION: The original code below:
// bool result = ((value + 0x40000000) & 0x80000000) == 0;
// may lead to incorrect results according to the C language spec, and
// in fact doesn't work correctly with gcc4.1.1 in some cases: The
// compiler may produce undefined results in case of signed integer
// overflow. The computation must be done w/ unsigned ints.
return static_cast<uintptr_t>(value) + 0x40000000U < 0x80000000U;
}
};
// Smi constants for 64-bit systems.
template <>
struct SmiTagging<8> {
enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
static int SmiShiftSize() { return kSmiShiftSize; }
static int SmiValueSize() { return kSmiValueSize; }
V8_INLINE static int SmiToInt(const internal::Object* value) {
int shift_bits = kSmiTagSize + kSmiShiftSize;
// Shift down and throw away top 32 bits.
return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return internal::IntToSmi<kSmiShiftSize>(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
// To be representable as a long smi, the value must be a 32-bit integer.
return (value == static_cast<int32_t>(value));
}
};
typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
const int kSmiMinValue = (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
const int kSmiMaxValue = -(kSmiMinValue + 1);
constexpr bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
constexpr bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
} // namespace internal
namespace debug {
@@ -1682,6 +1593,8 @@ class V8_EXPORT ScriptCompiler {
* This will return nullptr if the script cannot be serialized. The
* CachedData returned by this function should be owned by the caller.
*/
static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script,
Local<String> source);
static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
/**
@@ -1692,22 +1605,16 @@ class V8_EXPORT ScriptCompiler {
static CachedData* CreateCodeCache(
Local<UnboundModuleScript> unbound_module_script);
V8_DEPRECATED("Source string is no longer required",
static CachedData* CreateCodeCache(
Local<UnboundScript> unbound_script, Local<String> source));
/**
* Creates and returns code cache for the specified function that was
* previously produced by CompileFunctionInContext.
* This will return nullptr if the script cannot be serialized. The
* CachedData returned by this function should be owned by the caller.
*/
static CachedData* CreateCodeCacheForFunction(Local<Function> function,
Local<String> source);
static CachedData* CreateCodeCacheForFunction(Local<Function> function);
V8_DEPRECATED("Source string is no longer required",
static CachedData* CreateCodeCacheForFunction(
Local<Function> function, Local<String> source));
private:
static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
Isolate* isolate, Source* source, CompileOptions options,
@@ -2654,9 +2561,8 @@ enum class NewStringType {
*/
class V8_EXPORT String : public Name {
public:
static constexpr int kMaxLength = internal::kApiPointerSize == 4
? (1 << 28) - 16
: internal::kSmiMaxValue / 2 - 24;
static constexpr int kMaxLength =
sizeof(void*) == 4 ? (1 << 28) - 16 : (1 << 30) - 1 - 24;
enum Encoding {
UNKNOWN_ENCODING = 0x1,
@@ -4706,7 +4612,8 @@ class V8_EXPORT TypedArray : public ArrayBufferView {
/*
* The largest typed array size that can be constructed using New.
*/
static constexpr size_t kMaxLength = internal::kSmiMaxValue;
static constexpr size_t kMaxLength =
sizeof(void*) == 4 ? (1u << 30) - 1 : (1u << 31) - 1;
/**
* Number of elements in this typed array
@@ -5291,25 +5198,22 @@ class V8_EXPORT Template : public Data {
// TODO(dcarney): gcc can't handle Local below
Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>(),
AccessControl settings = DEFAULT,
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
AccessControl settings = DEFAULT);
void SetNativeDataProperty(
Local<Name> name, AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter = 0,
// TODO(dcarney): gcc can't handle Local below
Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>(),
AccessControl settings = DEFAULT,
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
AccessControl settings = DEFAULT);
/**
* Like SetNativeDataProperty, but V8 will replace the native data property
* with a real data property on first access.
*/
void SetLazyDataProperty(
Local<Name> name, AccessorNameGetterCallback getter,
Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
void SetLazyDataProperty(Local<Name> name, AccessorNameGetterCallback getter,
Local<Value> data = Local<Value>(),
PropertyAttribute attribute = None);
/**
* During template instantiation, sets the value with the intrinsic property
@@ -6033,14 +5937,12 @@ class V8_EXPORT ObjectTemplate : public Template {
Local<String> name, AccessorGetterCallback getter,
AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>(),
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
Local<AccessorSignature> signature = Local<AccessorSignature>());
void SetAccessor(
Local<Name> name, AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
Local<AccessorSignature> signature = Local<AccessorSignature>(),
SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
Local<AccessorSignature> signature = Local<AccessorSignature>());
/**
* Sets a named property handler on the object template.
@@ -6769,12 +6671,10 @@ class V8_EXPORT HeapCodeStatistics {
HeapCodeStatistics();
size_t code_and_metadata_size() { return code_and_metadata_size_; }
size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
size_t external_script_source_size() { return external_script_source_size_; }
private:
size_t code_and_metadata_size_;
size_t bytecode_and_metadata_size_;
size_t external_script_source_size_;
friend class Isolate;
};
@@ -7074,8 +6974,7 @@ class V8_EXPORT Isolate {
add_histogram_sample_callback(nullptr),
array_buffer_allocator(nullptr),
external_references(nullptr),
allow_atomics_wait(true),
only_terminate_in_safe_scope(false) {}
allow_atomics_wait(true) {}
/**
* The optional entry_hook allows the host application to provide the
@@ -7138,11 +7037,6 @@ class V8_EXPORT Isolate {
* this isolate. This can also be configured via SetAllowAtomicsWait.
*/
bool allow_atomics_wait;
/**
* Termination is postponed when there is no active SafeForTerminationScope.
*/
bool only_terminate_in_safe_scope;
};
@@ -8197,9 +8091,7 @@ class V8_EXPORT V8 {
* Returns { NULL, 0 } on failure.
* The caller acquires ownership of the data array in the return value.
*/
V8_DEPRECATED("Use SnapshotCreator",
static StartupData CreateSnapshotDataBlob(
const char* embedded_source = NULL));
static StartupData CreateSnapshotDataBlob(const char* embedded_source = NULL);
/**
* Bootstrap an isolate and a context from the cold startup blob, run the
@@ -8209,9 +8101,8 @@ class V8_EXPORT V8 {
* The caller acquires ownership of the data array in the return value.
* The argument startup blob is untouched.
*/
V8_DEPRECATED("Use SnapshotCreator",
static StartupData WarmUpSnapshotDataBlob(
StartupData cold_startup_blob, const char* warmup_source));
static StartupData WarmUpSnapshotDataBlob(StartupData cold_startup_blob,
const char* warmup_source);
/** Set the callback to invoke in case of Dcheck failures. */
static void SetDcheckErrorHandler(DcheckErrorCallback that);
@@ -9178,6 +9069,85 @@ class V8_EXPORT Locker {
namespace internal {
const int kApiPointerSize = sizeof(void*); // NOLINT
const int kApiIntSize = sizeof(int); // NOLINT
const int kApiInt64Size = sizeof(int64_t); // NOLINT
// Tag information for HeapObject.
const int kHeapObjectTag = 1;
const int kWeakHeapObjectTag = 3;
const int kHeapObjectTagSize = 2;
const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
// Tag information for Smi.
const int kSmiTag = 0;
const int kSmiTagSize = 1;
const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
template <size_t ptr_size> struct SmiTagging;
template<int kSmiShiftSize>
V8_INLINE internal::Object* IntToSmi(int value) {
int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
uintptr_t tagged_value =
(static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
return reinterpret_cast<internal::Object*>(tagged_value);
}
// Smi constants for 32-bit systems.
template <> struct SmiTagging<4> {
enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
static int SmiShiftSize() { return kSmiShiftSize; }
static int SmiValueSize() { return kSmiValueSize; }
V8_INLINE static int SmiToInt(const internal::Object* value) {
int shift_bits = kSmiTagSize + kSmiShiftSize;
// Throw away top 32 bits and shift down (requires >> to be sign extending).
return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return internal::IntToSmi<kSmiShiftSize>(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
// To be representable as an tagged small integer, the two
// most-significant bits of 'value' must be either 00 or 11 due to
// sign-extension. To check this we add 01 to the two
// most-significant bits, and check if the most-significant bit is 0
//
// CAUTION: The original code below:
// bool result = ((value + 0x40000000) & 0x80000000) == 0;
// may lead to incorrect results according to the C language spec, and
// in fact doesn't work correctly with gcc4.1.1 in some cases: The
// compiler may produce undefined results in case of signed integer
// overflow. The computation must be done w/ unsigned ints.
return static_cast<uintptr_t>(value) + 0x40000000U < 0x80000000U;
}
};
// Smi constants for 64-bit systems.
template <> struct SmiTagging<8> {
enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
static int SmiShiftSize() { return kSmiShiftSize; }
static int SmiValueSize() { return kSmiValueSize; }
V8_INLINE static int SmiToInt(const internal::Object* value) {
int shift_bits = kSmiTagSize + kSmiShiftSize;
// Shift down and throw away top 32 bits.
return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
}
V8_INLINE static internal::Object* IntToSmi(int value) {
return internal::IntToSmi<kSmiShiftSize>(value);
}
V8_INLINE static bool IsValidSmi(intptr_t value) {
// To be representable as a long smi, the value must be a 32-bit integer.
return (value == static_cast<int32_t>(value));
}
};
typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
/**
* This class exports constants and functionality from within v8 that
* is necessary to implement inline functions in the v8 api. Don't
@@ -9191,7 +9161,7 @@ class Internals {
static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
static const int kStringResourceOffset = 3 * kApiPointerSize;
static const int kOddballKindOffset = 4 * kApiPointerSize + kApiDoubleSize;
static const int kOddballKindOffset = 4 * kApiPointerSize + sizeof(double);
static const int kForeignAddressOffset = kApiPointerSize;
static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
+15 -27
View File
@@ -1726,7 +1726,7 @@ static void TemplateSetAccessor(
Template* template_obj, v8::Local<Name> name, Getter getter, Setter setter,
Data data, AccessControl settings, PropertyAttribute attribute,
v8::Local<AccessorSignature> signature, bool is_special_data_property,
bool replace_on_access, SideEffectType getter_side_effect_type) {
bool replace_on_access) {
auto info = Utils::OpenHandle(template_obj);
auto isolate = info->GetIsolate();
ENTER_V8_NO_SCRIPT_NO_EXCEPTION(isolate);
@@ -1736,8 +1736,6 @@ static void TemplateSetAccessor(
is_special_data_property, replace_on_access);
accessor_info->set_initial_property_attributes(
static_cast<i::PropertyAttributes>(attribute));
accessor_info->set_has_no_side_effect(getter_side_effect_type ==
SideEffectType::kHasNoSideEffect);
i::ApiNatives::AddNativeDataProperty(isolate, info, accessor_info);
}
@@ -1745,29 +1743,27 @@ void Template::SetNativeDataProperty(
v8::Local<String> name, AccessorGetterCallback getter,
AccessorSetterCallback setter, v8::Local<Value> data,
PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
AccessControl settings, SideEffectType getter_side_effect_type) {
AccessControl settings) {
TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
signature, true, false, getter_side_effect_type);
signature, true, false);
}
void Template::SetNativeDataProperty(
v8::Local<Name> name, AccessorNameGetterCallback getter,
AccessorNameSetterCallback setter, v8::Local<Value> data,
PropertyAttribute attribute, v8::Local<AccessorSignature> signature,
AccessControl settings, SideEffectType getter_side_effect_type) {
AccessControl settings) {
TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
signature, true, false, getter_side_effect_type);
signature, true, false);
}
void Template::SetLazyDataProperty(v8::Local<Name> name,
AccessorNameGetterCallback getter,
v8::Local<Value> data,
PropertyAttribute attribute,
SideEffectType getter_side_effect_type) {
TemplateSetAccessor(this, name, getter,
static_cast<AccessorNameSetterCallback>(nullptr), data,
DEFAULT, attribute, Local<AccessorSignature>(), true,
true, getter_side_effect_type);
PropertyAttribute attribute) {
TemplateSetAccessor(
this, name, getter, static_cast<AccessorNameSetterCallback>(nullptr),
data, DEFAULT, attribute, Local<AccessorSignature>(), true, true);
}
void Template::SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
@@ -1786,11 +1782,9 @@ void ObjectTemplate::SetAccessor(v8::Local<String> name,
AccessorSetterCallback setter,
v8::Local<Value> data, AccessControl settings,
PropertyAttribute attribute,
v8::Local<AccessorSignature> signature,
SideEffectType getter_side_effect_type) {
v8::Local<AccessorSignature> signature) {
TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
signature, i::FLAG_disable_old_api_accessors, false,
getter_side_effect_type);
signature, i::FLAG_disable_old_api_accessors, false);
}
void ObjectTemplate::SetAccessor(v8::Local<Name> name,
@@ -1798,11 +1792,9 @@ void ObjectTemplate::SetAccessor(v8::Local<Name> name,
AccessorNameSetterCallback setter,
v8::Local<Value> data, AccessControl settings,
PropertyAttribute attribute,
v8::Local<AccessorSignature> signature,
SideEffectType getter_side_effect_type) {
v8::Local<AccessorSignature> signature) {
TemplateSetAccessor(this, name, getter, setter, data, settings, attribute,
signature, i::FLAG_disable_old_api_accessors, false,
getter_side_effect_type);
signature, i::FLAG_disable_old_api_accessors, false);
}
template <typename Getter, typename Setter, typename Query, typename Descriptor,
@@ -6079,8 +6071,7 @@ HeapObjectStatistics::HeapObjectStatistics()
HeapCodeStatistics::HeapCodeStatistics()
: code_and_metadata_size_(0),
bytecode_and_metadata_size_(0),
external_script_source_size_(0) {}
bytecode_and_metadata_size_(0) {}
bool v8::V8::InitializeICU(const char* icu_data_file) {
return i::InitializeICU(icu_data_file);
@@ -8310,8 +8301,7 @@ void Isolate::Initialize(Isolate* isolate,
i::PrintF("[Initializing isolate from scratch took %0.3f ms]\n", ms);
}
}
i_isolate->set_only_terminate_in_safe_scope(
params.only_terminate_in_safe_scope);
i_isolate->set_only_terminate_in_safe_scope(false);
}
Isolate* Isolate::New(const Isolate::CreateParams& params) {
@@ -8530,8 +8520,6 @@ bool Isolate::GetHeapCodeAndMetadataStatistics(
code_statistics->code_and_metadata_size_ = isolate->code_and_metadata_size();
code_statistics->bytecode_and_metadata_size_ =
isolate->bytecode_and_metadata_size();
code_statistics->external_script_source_size_ =
isolate->external_script_source_size();
return true;
}
+9 -9
View File
@@ -154,9 +154,9 @@ class MockArrayBufferAllocator : public ArrayBufferAllocatorBase {
}
};
// Predictable v8::Platform implementation. Worker threads are disabled, idle
// tasks are disallowed, and the time reported by {MonotonicallyIncreasingTime}
// is deterministic.
// Predictable v8::Platform implementation. Background tasks and idle tasks are
// disallowed, and the time reported by {MonotonicallyIncreasingTime} is
// deterministic.
class PredictablePlatform : public Platform {
public:
explicit PredictablePlatform(std::unique_ptr<Platform> platform)
@@ -181,7 +181,12 @@ class PredictablePlatform : public Platform {
return platform_->GetForegroundTaskRunner(isolate);
}
int NumberOfWorkerThreads() override { return 0; }
std::shared_ptr<TaskRunner> GetWorkerThreadsTaskRunner(
v8::Isolate* isolate) override {
// Return the foreground task runner here, so that all tasks get executed
// sequentially in a predictable order.
return platform_->GetForegroundTaskRunner(isolate);
}
void CallOnWorkerThread(std::unique_ptr<Task> task) override {
// It's not defined when background tasks are being executed, so we can just
@@ -189,11 +194,6 @@ class PredictablePlatform : public Platform {
task->Run();
}
void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
double delay_in_seconds) override {
// Never run delayed tasks.
}
void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override {
platform_->CallOnForegroundThread(isolate, task);
}
+6 -1
View File
@@ -418,8 +418,13 @@ protocol::Response V8InspectorImpl::EvaluateScope::setTimeout(double timeout) {
if (m_isolate->IsExecutionTerminating()) {
return protocol::Response::Error("Execution was terminated");
}
std::shared_ptr<v8::TaskRunner> taskRunner =
v8::debug::GetCurrentPlatform()->GetWorkerThreadsTaskRunner(m_isolate);
if (!taskRunner) {
return protocol::Response::Error("Timeout is not supported by embedder");
}
m_cancelToken.reset(new CancelToken());
v8::debug::GetCurrentPlatform()->CallDelayedOnWorkerThread(
taskRunner->PostDelayedTask(
v8::base::make_unique<TerminateTask>(m_isolate, m_cancelToken), timeout);
return protocol::Response::OK();
}
-9
View File
@@ -215,15 +215,6 @@ std::unique_ptr<V8StackTrace> V8StackTraceImpl::clone() {
m_frames, 0, std::shared_ptr<AsyncStackTrace>(), V8StackTraceId()));
}
StringView V8StackTraceImpl::firstNonEmptySourceURL() const {
for (size_t i = 0; i < m_frames.size(); ++i) {
if (m_frames[i]->sourceURL().length()) {
return toStringView(m_frames[i]->sourceURL());
}
}
return StringView();
}
bool V8StackTraceImpl::isEmpty() const { return m_frames.empty(); }
StringView V8StackTraceImpl::topSourceURL() const {
-1
View File
@@ -64,7 +64,6 @@ class V8StackTraceImpl : public V8StackTrace {
// V8StackTrace implementation.
// This method drops the async stack trace.
std::unique_ptr<V8StackTrace> clone() override;
StringView firstNonEmptySourceURL() const override;
bool isEmpty() const override;
StringView topSourceURL() const override;
int topLineNumber() const override; // 1-based.
+6 -7
View File
@@ -193,22 +193,21 @@ std::shared_ptr<TaskRunner> DefaultPlatform::GetForegroundTaskRunner(
return foreground_task_runner_map_[isolate];
}
void DefaultPlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
std::shared_ptr<TaskRunner> DefaultPlatform::GetWorkerThreadsTaskRunner(
v8::Isolate*) {
EnsureBackgroundTaskRunnerInitialized();
worker_threads_task_runner_->PostTask(std::move(task));
return worker_threads_task_runner_;
}
void DefaultPlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
double delay_in_seconds) {
EnsureBackgroundTaskRunnerInitialized();
worker_threads_task_runner_->PostDelayedTask(std::move(task),
delay_in_seconds);
void DefaultPlatform::CallOnWorkerThread(std::unique_ptr<Task> task) {
GetWorkerThreadsTaskRunner(nullptr)->PostTask(std::move(task));
}
void DefaultPlatform::CallOnForegroundThread(v8::Isolate* isolate, Task* task) {
GetForegroundTaskRunner(isolate)->PostTask(std::unique_ptr<Task>(task));
}
void DefaultPlatform::CallDelayedOnForegroundThread(Isolate* isolate,
Task* task,
double delay_in_seconds) {
+2 -2
View File
@@ -58,9 +58,9 @@ class V8_PLATFORM_EXPORT DefaultPlatform : public NON_EXPORTED_BASE(Platform) {
int NumberOfWorkerThreads() override;
std::shared_ptr<TaskRunner> GetForegroundTaskRunner(
v8::Isolate* isolate) override;
std::shared_ptr<TaskRunner> GetWorkerThreadsTaskRunner(
v8::Isolate* isolate) override;
void CallOnWorkerThread(std::unique_ptr<Task> task) override;
void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
double delay_in_seconds) override;
void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override;
void CallDelayedOnForegroundThread(Isolate* isolate, Task* task,
double delay_in_seconds) override;
+3 -2
View File
@@ -1686,8 +1686,9 @@ class Smi: public Object {
DECL_VERIFIER(Smi)
static constexpr Smi* const kZero = nullptr;
static const int kMinValue = kSmiMinValue;
static const int kMaxValue = kSmiMaxValue;
static const int kMinValue =
(static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
static const int kMaxValue = -(kMinValue + 1);
private:
DISALLOW_IMPLICIT_CONSTRUCTORS(Smi);
-2
View File
@@ -356,8 +356,6 @@ class String : public Name {
// See include/v8.h for the definition.
static const int kMaxLength = v8::String::kMaxLength;
static_assert(kMaxLength <= (Smi::kMaxValue / 2 - kSize),
"Unexpected max String length");
// Max length for computing hash. For strings longer than this limit the
// string length is used as the hash value.
+14 -17
View File
@@ -182,6 +182,7 @@ class CompilationState {
// the CompilationState in order to cleanly clean up.
CancelableTaskManager background_task_manager_;
CancelableTaskManager foreground_task_manager_;
std::shared_ptr<v8::TaskRunner> background_task_runner_;
std::shared_ptr<v8::TaskRunner> foreground_task_runner_;
const size_t max_background_tasks_ = 0;
@@ -2729,6 +2730,7 @@ AsyncCompileJob::AsyncCompileJob(Isolate* isolate,
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate);
v8::Platform* platform = V8::GetCurrentPlatform();
foreground_task_runner_ = platform->GetForegroundTaskRunner(v8_isolate);
background_task_runner_ = platform->GetWorkerThreadsTaskRunner(v8_isolate);
// The handles for the context and promise must be deferred.
DeferredHandleScope deferred(isolate);
context_ = Handle<Context>(*context);
@@ -2937,15 +2939,12 @@ void AsyncCompileJob::DoSync(Args&&... args) {
}
void AsyncCompileJob::StartBackgroundTask() {
auto task = base::make_unique<CompileTask>(this, false);
// If --wasm-num-compilation-tasks=0 is passed, do only spawn foreground
// tasks. This is used to make timing deterministic.
if (FLAG_wasm_num_compilation_tasks > 0) {
V8::GetCurrentPlatform()->CallOnWorkerThread(std::move(task));
} else {
foreground_task_runner_->PostTask(std::move(task));
}
v8::TaskRunner* task_runner = FLAG_wasm_num_compilation_tasks > 0
? background_task_runner_.get()
: foreground_task_runner_.get();
task_runner->PostTask(base::make_unique<CompileTask>(this, false));
}
template <typename Step, typename... Args>
@@ -3423,6 +3422,7 @@ CompilationState::CompilationState(internal::Isolate* isolate, ModuleEnv& env)
v8::Isolate* v8_isolate = reinterpret_cast<v8::Isolate*>(isolate_);
v8::Platform* platform = V8::GetCurrentPlatform();
foreground_task_runner_ = platform->GetForegroundTaskRunner(v8_isolate);
background_task_runner_ = platform->GetWorkerThreadsTaskRunner(v8_isolate);
// Register task manager for clean shutdown in case of an isolate shutdown.
isolate_->wasm_engine()->Register(&background_task_manager_);
@@ -3596,17 +3596,14 @@ void CompilationState::RestartBackgroundTasks(size_t max) {
num_background_tasks_ += num_restart;
}
// If --wasm-num-compilation-tasks=0 is passed, do only spawn foreground
// tasks. This is used to make timing deterministic.
v8::TaskRunner* task_runner = FLAG_wasm_num_compilation_tasks > 0
? background_task_runner_.get()
: foreground_task_runner_.get();
for (; num_restart > 0; --num_restart) {
auto task = base::make_unique<BackgroundCompileTask>(
this, &background_task_manager_);
// If --wasm-num-compilation-tasks=0 is passed, do only spawn foreground
// tasks. This is used to make timing deterministic.
if (FLAG_wasm_num_compilation_tasks > 0) {
V8::GetCurrentPlatform()->CallOnWorkerThread(std::move(task));
} else {
foreground_task_runner_->PostTask(std::move(task));
}
task_runner->PostTask(base::make_unique<BackgroundCompileTask>(
this, &background_task_manager_));
}
}
+1
View File
@@ -160,6 +160,7 @@ class AsyncCompileJob {
Handle<Code> centry_stub_;
std::shared_ptr<v8::TaskRunner> foreground_task_runner_;
std::shared_ptr<v8::TaskRunner> background_task_runner_;
// For async compilation the AsyncCompileJob is the only finisher. For
// streaming compilation also the AsyncStreamingProcessor has to finish before
+5 -9
View File
@@ -680,22 +680,18 @@ class TestPlatform : public v8::Platform {
return old_platform_->OnCriticalMemoryPressure(length);
}
int NumberOfWorkerThreads() override {
return old_platform_->NumberOfWorkerThreads();
}
std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner(
v8::Isolate* isolate) override {
return old_platform_->GetForegroundTaskRunner(isolate);
}
void CallOnWorkerThread(std::unique_ptr<v8::Task> task) override {
old_platform_->CallOnWorkerThread(std::move(task));
std::shared_ptr<v8::TaskRunner> GetWorkerThreadsTaskRunner(
v8::Isolate* isolate) override {
return old_platform_->GetWorkerThreadsTaskRunner(isolate);
}
void CallDelayedOnWorkerThread(std::unique_ptr<v8::Task> task,
double delay_in_seconds) override {
old_platform_->CallDelayedOnWorkerThread(std::move(task), delay_in_seconds);
void CallOnWorkerThread(std::unique_ptr<v8::Task> task) override {
old_platform_->CallOnWorkerThread(std::move(task));
}
void CallOnForegroundThread(v8::Isolate* isolate, v8::Task* task) override {
+4
View File
@@ -46,6 +46,10 @@ class MockPlatformForUnmapper : public TestPlatform {
return old_platform_->NumberOfWorkerThreads();
}
size_t NumberOfAvailableBackgroundThreads() override {
return old_platform_->NumberOfAvailableBackgroundThreads();
}
private:
Task* task_;
std::vector<std::unique_ptr<Task>> worker_tasks_;
-86
View File
@@ -237,9 +237,6 @@ static void Getter(v8::Local<v8::Name> name,
info.GetReturnValue().Set(v8_str("return value"));
}
static void StringGetter(v8::Local<v8::String> name,
const v8::PropertyCallbackInfo<v8::Value>& info) {}
static void Setter(v8::Local<v8::String> name, v8::Local<v8::Value> value,
const v8::PropertyCallbackInfo<void>& info) {}
} // namespace
@@ -358,86 +355,3 @@ TEST(AccessorSetLazyDataPropertyHasNoSideEffect) {
->Int32Value(env.local())
.FromJust());
}
TEST(ObjectTemplateSetAccessorHasNoSideEffect) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> templ = v8::ObjectTemplate::New(isolate);
templ->SetAccessor(v8_str("foo"), StringGetter);
templ->SetAccessor(v8_str("foo2"), StringGetter, 0, v8::Local<v8::Value>(),
v8::AccessControl::DEFAULT, v8::PropertyAttribute::None,
v8::Local<v8::AccessorSignature>(),
v8::SideEffectType::kHasNoSideEffect);
v8::Local<v8::Object> obj = templ->NewInstance(env.local()).ToLocalChecked();
CHECK(env->Global()->Set(env.local(), v8_str("obj"), obj).FromJust());
CHECK(v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo"), true).IsEmpty());
v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2"), true).ToLocalChecked();
// Check that setter is not whitelisted.
v8::TryCatch try_catch(isolate);
CHECK(v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2 = 1"), true)
.IsEmpty());
CHECK(try_catch.HasCaught());
CHECK_NE(1, v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2"), false)
.ToLocalChecked()
->Int32Value(env.local())
.FromJust());
}
TEST(ObjectTemplateSetNativePropertyHasNoSideEffect) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> templ = v8::ObjectTemplate::New(isolate);
templ->SetNativeDataProperty(v8_str("foo"), Getter);
templ->SetNativeDataProperty(
v8_str("foo2"), Getter, 0, v8::Local<v8::Value>(),
v8::PropertyAttribute::None, v8::Local<v8::AccessorSignature>(),
v8::AccessControl::DEFAULT, v8::SideEffectType::kHasNoSideEffect);
v8::Local<v8::Object> obj = templ->NewInstance(env.local()).ToLocalChecked();
CHECK(env->Global()->Set(env.local(), v8_str("obj"), obj).FromJust());
CHECK(v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo"), true).IsEmpty());
v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2"), true).ToLocalChecked();
// Check that setter is not whitelisted.
v8::TryCatch try_catch(isolate);
CHECK(v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2 = 1"), true)
.IsEmpty());
CHECK(try_catch.HasCaught());
CHECK_NE(1, v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2"), false)
.ToLocalChecked()
->Int32Value(env.local())
.FromJust());
}
TEST(ObjectTemplateSetLazyPropertyHasNoSideEffect) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
v8::Local<v8::ObjectTemplate> templ = v8::ObjectTemplate::New(isolate);
templ->SetLazyDataProperty(v8_str("foo"), Getter);
templ->SetLazyDataProperty(v8_str("foo2"), Getter, v8::Local<v8::Value>(),
v8::PropertyAttribute::None,
v8::SideEffectType::kHasNoSideEffect);
v8::Local<v8::Object> obj = templ->NewInstance(env.local()).ToLocalChecked();
CHECK(env->Global()->Set(env.local(), v8_str("obj"), obj).FromJust());
CHECK(v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo"), true).IsEmpty());
v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2"), true).ToLocalChecked();
// Check that setter is not whitelisted.
v8::TryCatch try_catch(isolate);
CHECK(v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2 = 1"), true)
.IsEmpty());
CHECK(try_catch.HasCaught());
CHECK_NE(1, v8::debug::EvaluateGlobal(isolate, v8_str("obj.foo2"), false)
.ToLocalChecked()
->Int32Value(env.local())
.FromJust());
}
-60
View File
@@ -625,66 +625,6 @@ void RequestTermianteAndCallAPI(
AssertFinishedCodeRun(args.GetIsolate());
}
UNINITIALIZED_TEST(IsolateSafeForTerminationMode) {
v8::Isolate::CreateParams create_params;
create_params.only_terminate_in_safe_scope = true;
create_params.array_buffer_allocator = CcTest::array_buffer_allocator();
v8::Isolate* isolate = v8::Isolate::New(create_params);
i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
{
v8::Isolate::Scope isolate_scope(isolate);
v8::HandleScope handle_scope(isolate);
v8::Local<v8::ObjectTemplate> global = v8::ObjectTemplate::New(isolate);
global->Set(v8_str("terminateAndCallAPI"),
v8::FunctionTemplate::New(isolate, RequestTermianteAndCallAPI));
v8::Local<v8::Context> context = v8::Context::New(isolate, nullptr, global);
v8::Context::Scope context_scope(context);
// Should postpone termination without safe scope.
isolate->TerminateExecution();
AssertFinishedCodeRun(isolate);
{
v8::Isolate::SafeForTerminationScope safe_scope(isolate);
AssertTerminatedCodeRun(isolate);
}
AssertFinishedCodeRun(isolate);
{
isolate->TerminateExecution();
AssertFinishedCodeRun(isolate);
i::PostponeInterruptsScope p1(i_isolate,
i::StackGuard::TERMINATE_EXECUTION);
{
// SafeForTermination overrides postpone.
v8::Isolate::SafeForTerminationScope safe_scope(isolate);
AssertTerminatedCodeRun(isolate);
}
AssertFinishedCodeRun(isolate);
}
{
v8::Isolate::SafeForTerminationScope safe_scope(isolate);
// Request terminate and call API recursively.
CompileRun("terminateAndCallAPI()");
AssertTerminatedCodeRun(isolate);
}
{
i::PostponeInterruptsScope p1(i_isolate,
i::StackGuard::TERMINATE_EXECUTION);
// Request terminate and call API recursively.
CompileRun("terminateAndCallAPI()");
AssertFinishedCodeRun(isolate);
}
AssertFinishedCodeRun(isolate);
{
v8::Isolate::SafeForTerminationScope safe_scope(isolate);
AssertTerminatedCodeRun(isolate);
}
}
isolate->Dispose();
}
TEST(ErrorObjectAfterTermination) {
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(isolate);
@@ -34,6 +34,11 @@ class MockPlatform final : public TestPlatform {
return task_runner_;
}
std::shared_ptr<TaskRunner> GetWorkerThreadsTaskRunner(
v8::Isolate* isolate) override {
return task_runner_;
}
void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override {
task_runner_->PostTask(std::unique_ptr<Task>(task));
}
-1
View File
@@ -63,7 +63,6 @@ IsolateData::IsolateData(TaskRunner* task_runner,
params.array_buffer_allocator =
v8::ArrayBuffer::Allocator::NewDefaultAllocator();
params.snapshot_blob = startup_data;
params.only_terminate_in_safe_scope = true;
isolate_.reset(v8::Isolate::New(params));
isolate_->SetMicrotasksPolicy(v8::MicrotasksPolicy::kScoped);
if (with_inspector) {
+10 -2
View File
@@ -44,7 +44,11 @@
assertEquals("abcde", f("de"));
assertEquals("abcde", f("de"));
%OptimizeFunctionOnNextCall(f);
var s = "x".repeat(%StringMaxLength());
var s = "x".repeat((1 << 28) - 16);
try {
s = "x".repeat((1 << 30) - 1 - 24);
} catch (e) {
}
assertThrows(() => f(s), RangeError);
})();
@@ -89,6 +93,10 @@
assertEquals("abcde", f("de"));
assertEquals("abcde", f("de"));
%OptimizeFunctionOnNextCall(f);
var s = "x".repeat(%StringMaxLength());
var s = "x".repeat((1 << 28) - 16);
try {
s = "x".repeat((1 << 30) - 1 - 24);
} catch (e) {
}
assertThrows(() => f(s), RangeError);
})();
@@ -102,7 +102,14 @@ class MockPlatform : public v8::Platform {
std::shared_ptr<TaskRunner> GetForegroundTaskRunner(
v8::Isolate* isolate) override {
return std::make_shared<MockForegroundTaskRunner>(this);
constexpr bool is_foreground_task_runner = true;
return std::make_shared<MockTaskRunner>(this, is_foreground_task_runner);
}
std::shared_ptr<TaskRunner> GetWorkerThreadsTaskRunner(
v8::Isolate* isolate) override {
constexpr bool is_foreground_task_runner = false;
return std::make_shared<MockTaskRunner>(this, is_foreground_task_runner);
}
void CallOnWorkerThread(std::unique_ptr<Task> task) override {
@@ -110,11 +117,6 @@ class MockPlatform : public v8::Platform {
worker_tasks_.push_back(std::move(task));
}
void CallDelayedOnWorkerThread(std::unique_ptr<Task> task,
double delay_in_seconds) override {
UNREACHABLE();
}
void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override {
base::LockGuard<base::Mutex> lock(&mutex_);
foreground_tasks_.push_back(std::unique_ptr<Task>(task));
@@ -257,14 +259,19 @@ class MockPlatform : public v8::Platform {
DISALLOW_COPY_AND_ASSIGN(TaskWrapper);
};
class MockForegroundTaskRunner final : public TaskRunner {
class MockTaskRunner final : public TaskRunner {
public:
explicit MockForegroundTaskRunner(MockPlatform* platform)
: platform_(platform) {}
MockTaskRunner(MockPlatform* platform, bool is_foreground_task_runner)
: platform_(platform),
is_foreground_task_runner_(is_foreground_task_runner) {}
void PostTask(std::unique_ptr<v8::Task> task) override {
base::LockGuard<base::Mutex> lock(&platform_->mutex_);
platform_->foreground_tasks_.push_back(std::move(task));
if (is_foreground_task_runner_) {
platform_->foreground_tasks_.push_back(std::move(task));
} else {
platform_->worker_tasks_.push_back(std::move(task));
}
}
void PostDelayedTask(std::unique_ptr<Task> task,
@@ -279,10 +286,14 @@ class MockPlatform : public v8::Platform {
platform_->idle_task_ = task.release();
}
bool IdleTasksEnabled() override { return true; };
bool IdleTasksEnabled() override {
// Idle tasks are enabled only in the foreground task runner.
return is_foreground_task_runner_;
};
private:
MockPlatform* platform_;
bool is_foreground_task_runner_;
};
double time_;
@@ -258,32 +258,48 @@ class TestBackgroundTask : public Task {
} // namespace
TEST(DefaultPlatformTest, RunBackgroundTask) {
int dummy;
Isolate* isolate = reinterpret_cast<Isolate*>(&dummy);
DefaultPlatform platform;
platform.SetThreadPoolSize(1);
std::shared_ptr<TaskRunner> taskrunner =
platform.GetWorkerThreadsTaskRunner(isolate);
base::Semaphore sem(0);
bool task_executed = false;
StrictMock<TestBackgroundTask>* task =
new StrictMock<TestBackgroundTask>(&sem, &task_executed);
EXPECT_CALL(*task, Die());
platform.CallOnWorkerThread(std::unique_ptr<Task>(task));
taskrunner->PostTask(std::unique_ptr<Task>(task));
EXPECT_TRUE(sem.WaitFor(base::TimeDelta::FromSeconds(1)));
EXPECT_TRUE(task_executed);
}
TEST(DefaultPlatformTest, PostForegroundTaskAfterPlatformTermination) {
std::shared_ptr<TaskRunner> foreground_taskrunner;
{
DefaultPlatformWithMockTime platform;
TEST(DefaultPlatformTest, NoIdleTasksInBackground) {
int dummy;
Isolate* isolate = reinterpret_cast<Isolate*>(&dummy);
DefaultPlatform platform;
platform.SetThreadPoolSize(1);
std::shared_ptr<TaskRunner> taskrunner =
platform.GetWorkerThreadsTaskRunner(isolate);
EXPECT_FALSE(taskrunner->IdleTasksEnabled());
}
TEST(DefaultPlatformTest, PostTaskAfterPlatformTermination) {
std::shared_ptr<TaskRunner> foreground_taskrunner;
std::shared_ptr<TaskRunner> background_taskrunner;
{
int dummy;
Isolate* isolate = reinterpret_cast<Isolate*>(&dummy);
DefaultPlatformWithMockTime platform;
platform.SetThreadPoolSize(1);
foreground_taskrunner = platform.GetForegroundTaskRunner(isolate);
background_taskrunner = platform.GetWorkerThreadsTaskRunner(isolate);
}
// It should still be possible to post foreground tasks, even when the
// platform does not exist anymore.
// It should still be possible to post tasks, even when the platform does not
// exist anymore.
StrictMock<MockTask>* task1 = new StrictMock<MockTask>;
EXPECT_CALL(*task1, Die());
foreground_taskrunner->PostTask(std::unique_ptr<Task>(task1));
@@ -295,6 +311,10 @@ TEST(DefaultPlatformTest, PostForegroundTaskAfterPlatformTermination) {
StrictMock<MockIdleTask>* task3 = new StrictMock<MockIdleTask>;
EXPECT_CALL(*task3, Die());
foreground_taskrunner->PostIdleTask(std::unique_ptr<IdleTask>(task3));
StrictMock<MockTask>* task4 = new StrictMock<MockTask>;
EXPECT_CALL(*task4, Die());
background_taskrunner->PostTask(std::unique_ptr<Task>(task4));
}
} // namespace default_platform_unittest