deps: make V8 9.4 abi-compatible with 9.0

Revert "[api] Avoid handles for const API functions"
This reverts commit aee471b2ff5b1a9e622426454885b748d226535b.

Revert "[api] Remove deprecated [Shared]ArrayBuffer API"
This reverts commit 578f6be77fc5d8af975005c2baf918e7225abb62.

Revert "[Jobs]: Cleanup in v8 platform."
This reverts commit baf2b088dd9f585aa597459f30d71431171666e2.

Revert "Skip global registration of [Shared]ArrayBuffer backing stores"
This reverts commit fcdf35e6d70d51699ece063e25dc705e80673308.

Revert "[api] Remove previously deprecated Function::GetDisplayName()."
This reverts commit 6165fef8cc9dde52973e54c915e6905221b3f8fb.

Revert "[api] Remove deprecated Symbol::Name()"
This reverts commit bbc72ef6c7d6d8e2c4dd074d7713e5c841003163.

Revert API change for HeapProfiler::TakeHeapSnapshot
This reverts a small part of 7f52e4f92d3d3ded9a1701ee2f93966075ae5004.

Revert "[cpu-profiler] Reintroduce support for context filtering"
This reverts commit 0aacfb2a6ecbeda1d1d97ca113afd8253a1b9670.

Restore new argument for TakeHeapSnapshot method
This creates a new TakeHeapSnapshotV8_92 method with the signature from
7f52e4f92d3d3ded9a1701ee2f93966075ae5004.
It is necessary because the API is used internall by V8.

Silence irrelevant warning
V8 triggers it in the Name method.

Revert "[api] Add v8::metrics::LongTaskStats for the LongTasks UKM"
This reverts commit 521ae93bf652b0cc1fec1fdd788e3b80fb72a349.

Move cage_base isolate data field
Makes 3ada6f27404b4ffd6d3e97cf15be76672f60c10d ABI-compatible.

Revert ABI-breaking change in FunctionTemplate::SetCallHandler
Reverts part of a7980d43e030ba4bdb36813d4bc99f85982bf4ee and
ad4eab00e7ec96730eb2c1b6ddcef14ba2e4becd.

Revert "[api] Support PropertyAttribute in v8::Template::Set"
This reverts commit 22a32f11f7a39e4a73105608a51ebab0ad97960f.

Revert API change for FunctionTemplate::New
This reverts the API change of 5f82dbbe534635a8b1e93f27e8fd7e68c0eaf291.

Fix some reverts
- constness of internal APIs has not external effect
- restored API function must but adapted to moved internal API.

Revert "[api] Add API for off-thread code cache deserialization"
This reverts commit f888f48e4c65e3ccfd9fd831c71c1832b957c945.

Revert "[api] Implement signature checks using instance types"
This reverts commit 7df6678c32255ec5a1b1470f1e5a7e56b3b192fa.

Revert "[api] Remove deprecated APIs"
This reverts commit 390456678a8261827cd9a1b5f0c4dc8e4328af07.

PR-URL: https://github.com/nodejs/node/pull/40285
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Jiawen Geng <technicalcute@gmail.com>
This commit is contained in:
Michaël Zasso committed 2021-10-04 13:26:55 +02:00
1 parent 5cc24e6d76
commit a3db2033d4
61 files changed
+1454 -1525

No files matched your search

+1 -1
View File
@@ -36,7 +36,7 @@
# Reset this number to 0 on major V8 upgrades.
# Increment by one for each non-official patch applied to deps/v8.
'v8_embedder_string': '-node.11',
'v8_embedder_string': '-node.12',
##### V8 defaults for Node.js #####
+2 -16
View File
@@ -36,7 +36,6 @@ const int kApiSystemPointerSize = sizeof(void*);
const int kApiDoubleSize = sizeof(double);
const int kApiInt32Size = sizeof(int32_t);
const int kApiInt64Size = sizeof(int64_t);
const int kApiSizetSize = sizeof(size_t);
// Tag information for HeapObject.
const int kHeapObjectTag = 1;
@@ -188,8 +187,6 @@ V8_EXPORT internal::Isolate* IsolateFromNeverReadOnlySpaceObject(Address obj);
// language mode is strict.
V8_EXPORT bool ShouldThrowOnError(v8::internal::Isolate* isolate);
V8_EXPORT bool CanHaveInternalField(int instance_type);
/**
* This class exports constants and functionality from within v8 that
* is necessary to implement inline functions in the v8 api. Don't
@@ -236,12 +233,8 @@ class Internals {
kIsolateFastCCallCallerFpOffset + kApiSystemPointerSize;
static const int kIsolateFastApiCallTargetOffset =
kIsolateFastCCallCallerPcOffset + kApiSystemPointerSize;
static const int kIsolateCageBaseOffset =
kIsolateFastApiCallTargetOffset + kApiSystemPointerSize;
static const int kIsolateLongTaskStatsCounterOffset =
kIsolateCageBaseOffset + kApiSystemPointerSize;
static const int kIsolateStackGuardOffset =
kIsolateLongTaskStatsCounterOffset + kApiSizetSize;
kIsolateFastApiCallTargetOffset + kApiSystemPointerSize;
static const int kIsolateRootsOffset =
kIsolateStackGuardOffset + 7 * kApiSystemPointerSize;
@@ -268,9 +261,8 @@ class Internals {
static const int kOddballType = 0x43;
static const int kForeignType = 0x46;
static const int kJSSpecialApiObjectType = 0x410;
static const int kJSApiObjectType = 0x420;
static const int kJSObjectType = 0x421;
static const int kFirstJSApiObjectType = 0x422;
static const int kLastJSApiObjectType = 0x80A;
static const int kUndefinedOddballKind = 5;
static const int kNullOddballKind = 3;
@@ -375,12 +367,6 @@ class Internals {
return *reinterpret_cast<void* const*>(addr);
}
V8_INLINE static void IncrementLongTasksStatsCounter(v8::Isolate* isolate) {
internal::Address addr = reinterpret_cast<internal::Address>(isolate) +
kIsolateLongTaskStatsCounterOffset;
++(*reinterpret_cast<size_t*>(addr));
}
V8_INLINE static internal::Address* GetRoot(v8::Isolate* isolate, int index) {
internal::Address addr = reinterpret_cast<internal::Address>(isolate) +
kIsolateRootsOffset +
+1 -28
View File
@@ -5,8 +5,7 @@
#ifndef V8_METRICS_H_
#define V8_METRICS_H_
#include "v8-internal.h" // NOLINT(build/include_directory)
#include "v8.h" // NOLINT(build/include_directory)
#include "v8.h" // NOLINT(build/include_directory)
namespace v8 {
namespace metrics {
@@ -197,32 +196,6 @@ class V8_EXPORT Recorder {
static ContextId GetContextId(Local<Context> context);
};
/**
* Experimental API intended for the LongTasks UKM (crbug.com/1173527).
* The Reset() method should be called at the start of a potential
* long task. The Get() method returns durations of V8 work that
* happened during the task.
*
* This API is experimental and may be removed/changed in the future.
*/
struct V8_EXPORT LongTaskStats {
/**
* Resets durations of V8 work for the new task.
*/
V8_INLINE static void Reset(Isolate* isolate) {
v8::internal::Internals::IncrementLongTasksStatsCounter(isolate);
}
/**
* Returns durations of V8 work that happened since the last Reset().
*/
static LongTaskStats Get(Isolate* isolate);
int64_t gc_full_atomic_wall_clock_duration_us = 0;
int64_t gc_full_incremental_wall_clock_duration_us = 0;
int64_t gc_young_wall_clock_duration_us = 0;
};
} // namespace metrics
} // namespace v8
+16 -2
View File
@@ -181,8 +181,9 @@ class JobDelegate {
/**
* Returns true if the current task is called from the thread currently
* running JobHandle::Join().
* TODO(etiennep): Make pure virtual once custom embedders implement it.
*/
virtual bool IsJoiningThread() const = 0;
virtual bool IsJoiningThread() const { return false; }
};
/**
@@ -219,14 +220,19 @@ class JobHandle {
* Forces all existing workers to yield ASAP but doesn’t wait for them.
* Warning, this is dangerous if the Job's callback is bound to or has access
* to state which may be deleted after this call.
* TODO(etiennep): Cleanup once implemented by all embedders.
*/
virtual void CancelAndDetach() = 0;
virtual void CancelAndDetach() { Cancel(); }
/**
* Returns true if there's any work pending or any worker running.
*/
virtual bool IsActive() = 0;
// TODO(etiennep): Clean up once all overrides are removed.
V8_DEPRECATED("Use !IsActive() instead.")
virtual bool IsCompleted() { return !IsActive(); }
/**
* Returns true if associated with a Job and other methods may be called.
* Returns false after Join() or Cancel() was called. This may return true
@@ -234,6 +240,10 @@ class JobHandle {
*/
virtual bool IsValid() = 0;
// TODO(etiennep): Clean up once all overrides are removed.
V8_DEPRECATED("Use IsValid() instead.")
virtual bool IsRunning() { return IsValid(); }
/**
* Returns true if job priority can be changed.
*/
@@ -262,6 +272,10 @@ class JobTask {
* it must not call back any JobHandle methods.
*/
virtual size_t GetMaxConcurrency(size_t worker_count) const = 0;
// TODO(1114823): Clean up once all overrides are removed.
V8_DEPRECATED("Use the version that takes |worker_count|.")
virtual size_t GetMaxConcurrency() const { return 0; }
};
/**
+10 -6
View File
@@ -289,8 +289,8 @@ class V8_EXPORT CpuProfilingOptions {
* interval, set via SetSamplingInterval(). If
* zero, the sampling interval will be equal to
* the profiler's sampling interval.
* \param filter_context If specified, profiles will only contain frames
* using this context. Other frames will be elided.
* \param filter_context Deprecated option to filter by context, currently a
* no-op.
*/
CpuProfilingOptions(
CpuProfilingMode mode = kLeafNodeLineNumbers,
@@ -304,13 +304,9 @@ class V8_EXPORT CpuProfilingOptions {
private:
friend class internal::CpuProfile;
bool has_filter_context() const { return !filter_context_.IsEmpty(); }
void* raw_filter_context() const;
CpuProfilingMode mode_;
unsigned max_samples_;
int sampling_interval_us_;
CopyablePersistentTraits<Context>::CopyablePersistent filter_context_;
};
/**
@@ -900,6 +896,14 @@ class V8_EXPORT HeapProfiler {
* Takes a heap snapshot and returns it.
*/
const HeapSnapshot* TakeHeapSnapshot(
ActivityControl* control = nullptr,
ObjectNameResolver* global_object_name_resolver = nullptr,
bool treat_global_objects_as_roots = true);
/**
* Takes a heap snapshot and returns it.
*/
const HeapSnapshot* TakeHeapSnapshotV8_92(
ActivityControl* control = nullptr,
ObjectNameResolver* global_object_name_resolver = nullptr,
bool treat_global_objects_as_roots = true,
+383 -77
View File
@@ -128,7 +128,6 @@ template<typename T> class PropertyCallbackInfo;
template<typename T> class ReturnValue;
namespace internal {
class BackgroundDeserializeTask;
class BasicTracedReferenceExtractor;
class ExternalString;
class FunctionCallbackArguments;
@@ -1509,7 +1508,7 @@ class V8_EXPORT UnboundScript {
*/
Local<Script> BindToCurrentContext();
int GetId() const;
int GetId();
Local<Value> GetScriptName();
/**
@@ -1721,7 +1720,7 @@ class V8_EXPORT Module : public Data {
*
* The module must be a SourceTextModule and must not have a kErrored status.
*/
int ScriptId() const;
int ScriptId();
/**
* Returns whether this module or any of its requested modules is async,
@@ -1772,6 +1771,13 @@ class V8_EXPORT Module : public Data {
*/
V8_WARN_UNUSED_RESULT Maybe<bool> SetSyntheticModuleExport(
Isolate* isolate, Local<String> export_name, Local<Value> export_value);
V8_DEPRECATED(
"Use the preceding SetSyntheticModuleExport with an Isolate parameter, "
"instead of the one that follows. The former will throw a runtime "
"error if called for an export that doesn't exist (as per spec); "
"the latter will crash with a failed CHECK().")
void SetSyntheticModuleExport(Local<String> export_name,
Local<Value> export_value);
V8_INLINE static Module* Cast(Data* data);
@@ -1812,8 +1818,6 @@ enum class ScriptType { kClassic, kModule };
*/
class V8_EXPORT ScriptCompiler {
public:
class ConsumeCodeCacheTask;
/**
* Compilation data that the embedder can cache and pass back to speed up
* future compilations. The data is produced if the CompilerOptions passed to
@@ -1857,15 +1861,12 @@ class V8_EXPORT ScriptCompiler {
*/
class Source {
public:
// Source takes ownership of both CachedData and CodeCacheConsumeTask.
// Source takes ownership of CachedData.
V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
CachedData* cached_data = nullptr,
ConsumeCodeCacheTask* consume_cache_task = nullptr);
// Source takes ownership of both CachedData and CodeCacheConsumeTask.
V8_INLINE explicit Source(
Local<String> source_string, CachedData* cached_data = nullptr,
ConsumeCodeCacheTask* consume_cache_task = nullptr);
V8_INLINE ~Source() = default;
CachedData* cached_data = nullptr);
V8_INLINE explicit Source(Local<String> source_string,
CachedData* cached_data = nullptr);
V8_INLINE ~Source();
// Ownership of the CachedData or its buffers is *not* transferred to the
// caller. The CachedData object is alive as long as the Source object is
@@ -1874,6 +1875,10 @@ class V8_EXPORT ScriptCompiler {
V8_INLINE const ScriptOriginOptions& GetResourceOptions() const;
// Prevent copying.
Source(const Source&) = delete;
Source& operator=(const Source&) = delete;
private:
friend class ScriptCompiler;
@@ -1890,8 +1895,7 @@ class V8_EXPORT ScriptCompiler {
// Cached data from previous compilation (if a kConsume*Cache flag is
// set), or hold newly generated cache data (kProduce*Cache flags) are
// set when calling a compile method.
std::unique_ptr<CachedData> cached_data;
std::unique_ptr<ConsumeCodeCacheTask> consume_cache_task;
CachedData* cached_data;
};
/**
@@ -1953,6 +1957,12 @@ class V8_EXPORT ScriptCompiler {
public:
enum Encoding { ONE_BYTE, TWO_BYTE, UTF8, WINDOWS_1252 };
#if defined(_MSC_VER) && _MSC_VER >= 1910 /* Disable on VS2015 */
V8_DEPRECATED(
"This class takes ownership of source_stream, so use the constructor "
"taking a unique_ptr to make these semantics clearer")
#endif
StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
StreamedSource(std::unique_ptr<ExternalSourceStream> source_stream,
Encoding encoding);
~StreamedSource();
@@ -1984,26 +1994,6 @@ class V8_EXPORT ScriptCompiler {
internal::ScriptStreamingData* data_;
};
/**
* A task which the embedder must run on a background thread to
* consume a V8 code cache. Returned by
* ScriptCompiler::StarConsumingCodeCache.
*/
class V8_EXPORT ConsumeCodeCacheTask final {
public:
~ConsumeCodeCacheTask();
void Run();
private:
friend class ScriptCompiler;
explicit ConsumeCodeCacheTask(
std::unique_ptr<internal::BackgroundDeserializeTask> impl);
std::unique_ptr<internal::BackgroundDeserializeTask> impl_;
};
enum CompileOptions {
kNoCompileOptions = 0,
kConsumeCodeCache,
@@ -2077,13 +2067,14 @@ class V8_EXPORT ScriptCompiler {
* This API allows to start the streaming with as little data as possible, and
* the remaining data (for example, the ScriptOrigin) is passed to Compile.
*/
V8_DEPRECATED("Use ScriptCompiler::StartStreaming instead.")
static ScriptStreamingTask* StartStreamingScript(
Isolate* isolate, StreamedSource* source,
CompileOptions options = kNoCompileOptions);
static ScriptStreamingTask* StartStreaming(
Isolate* isolate, StreamedSource* source,
ScriptType type = ScriptType::kClassic);
static ConsumeCodeCacheTask* StartConsumingCodeCache(
Isolate* isolate, std::unique_ptr<CachedData> source);
/**
* Compiles a streamed script (bound to current context).
*
@@ -2454,7 +2445,7 @@ struct SampleInfo {
StateTag vm_state; // Current VM state.
void* external_callback_entry; // External callback address if VM is
// executing an external callback.
void* context; // Incumbent native context address.
void* top_context; // Incumbent native context address.
};
struct MemoryRange {
@@ -3571,12 +3562,12 @@ class V8_EXPORT String : public Name {
/**
* Returns true if this string can be made external.
*/
bool CanMakeExternal() const;
bool CanMakeExternal();
/**
* Returns true if the strings values are equal. Same as JS ==/===.
*/
bool StringEquals(Local<String> str) const;
bool StringEquals(Local<String> str);
/**
* Converts an object to a UTF-8-encoded character array. Useful if
@@ -3656,10 +3647,12 @@ class V8_EXPORT Symbol : public Name {
/**
* Returns the description string of the symbol, or undefined if none.
*/
V8_DEPRECATE_SOON("Use Symbol::Description(isolate)")
Local<Value> Description() const;
Local<Value> Description(Isolate* isolate) const;
V8_DEPRECATED("Use Symbol::Description()")
Local<Value> Name() const { return Description(); }
/**
* Create a symbol. If description is not empty, it will be used as the
* description.
@@ -4184,7 +4177,7 @@ class V8_EXPORT Object : public Value {
Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
/** Gets the number of internal fields for this Object. */
int InternalFieldCount() const;
int InternalFieldCount();
/** Same as above, but works for PersistentBase. */
V8_INLINE static int InternalFieldCount(
@@ -4294,10 +4287,10 @@ class V8_EXPORT Object : public Value {
Local<Context> context, Local<Name> key);
/** Tests for a named lookup interceptor.*/
bool HasNamedLookupInterceptor() const;
bool HasNamedLookupInterceptor();
/** Tests for an index lookup interceptor.*/
bool HasIndexedLookupInterceptor() const;
bool HasIndexedLookupInterceptor();
/**
* Returns the identity hash for this object. The current implementation
@@ -4339,12 +4332,12 @@ class V8_EXPORT Object : public Value {
* ObjectTemplate::SetCallAsFunctionHandler method.
* When an Object is callable this method returns true.
*/
bool IsCallable() const;
bool IsCallable();
/**
* True if this object is a constructor.
*/
bool IsConstructor() const;
bool IsConstructor();
/**
* True if this object can carry information relevant to the embedder in its
@@ -4353,14 +4346,14 @@ class V8_EXPORT Object : public Value {
* V8 automatically adds internal fields at compile time, such as e.g.
* v8::ArrayBuffer.
*/
bool IsApiWrapper() const;
bool IsApiWrapper();
/**
* True if this object was created from an object template which was marked
* as undetectable. See v8::ObjectTemplate::MarkAsUndetectable for more
* information.
*/
bool IsUndetectable() const;
bool IsUndetectable();
/**
* Call an Object as a function if a callback is set by the
@@ -4419,7 +4412,7 @@ class V8_EXPORT Object : public Value {
*
* See also: v8::ObjectTemplate::SetCodeLike
*/
bool IsCodeLike(Isolate* isolate) const;
bool IsCodeLike(Isolate* isolate);
private:
Object();
@@ -4801,6 +4794,17 @@ class V8_EXPORT Function : public Object {
*/
Local<Value> GetDebugName() const;
/**
* User-defined name assigned to the "displayName" property of this function.
* Used to facilitate debugging and profiling of JavaScript code.
*/
V8_DEPRECATED(
"Use v8::Object::Get() instead to look up \"displayName\". "
"V8 and DevTools no longer use \"displayName\" in stack "
"traces, but the standard \"name\" property. "
"See http://crbug.com/1177685.")
Local<Value> GetDisplayName() const;
/**
* Returns zero based line number of function body and
* kLineOffsetNotFound if no information available.
@@ -4907,7 +4911,7 @@ class V8_EXPORT Promise : public Object {
* Returns true if the promise has at least one derived promise, and
* therefore resolve/reject handlers (including default handler).
*/
bool HasHandler() const;
bool HasHandler();
/**
* Returns the content of the [[PromiseResult]] field. The Promise must not
@@ -5021,7 +5025,7 @@ class V8_EXPORT Proxy : public Object {
public:
Local<Value> GetTarget();
Local<Value> GetHandler();
bool IsRevoked() const;
bool IsRevoked();
void Revoke();
/**
@@ -5436,6 +5440,57 @@ class V8_EXPORT ArrayBuffer : public Object {
static Allocator* NewDefaultAllocator();
};
/**
* The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
* returns an instance of this class, populated, with a pointer to data
* and byte length.
*
* The Data pointer of ArrayBuffer::Contents must be freed using the provided
* deleter, which will call ArrayBuffer::Allocator::Free if the buffer
* was allocated with ArraryBuffer::Allocator::Allocate.
*/
class V8_EXPORT Contents { // NOLINT
public:
using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
Contents()
: data_(nullptr),
byte_length_(0),
allocation_base_(nullptr),
allocation_length_(0),
allocation_mode_(Allocator::AllocationMode::kNormal),
deleter_(nullptr),
deleter_data_(nullptr) {}
void* AllocationBase() const { return allocation_base_; }
size_t AllocationLength() const { return allocation_length_; }
Allocator::AllocationMode AllocationMode() const {
return allocation_mode_;
}
void* Data() const { return data_; }
size_t ByteLength() const { return byte_length_; }
DeleterCallback Deleter() const { return deleter_; }
void* DeleterData() const { return deleter_data_; }
private:
Contents(void* data, size_t byte_length, void* allocation_base,
size_t allocation_length,
Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
void* deleter_data);
void* data_;
size_t byte_length_;
void* allocation_base_;
size_t allocation_length_;
Allocator::AllocationMode allocation_mode_;
DeleterCallback deleter_;
void* deleter_data_;
friend class ArrayBuffer;
};
/**
* Data length in bytes.
*/
@@ -5449,6 +5504,22 @@ class V8_EXPORT ArrayBuffer : public Object {
*/
static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
/**
* Create a new ArrayBuffer over an existing memory block.
* The created array buffer is by default immediately in externalized state.
* In externalized state, the memory block will not be reclaimed when a
* created ArrayBuffer is garbage-collected.
* In internalized state, the memory block will be released using
* |Allocator::Free| once all ArrayBuffers referencing it are collected by
* the garbage collector.
*/
V8_DEPRECATED(
"Use the version that takes a BackingStore. "
"See http://crbug.com/v8/9908.")
static Local<ArrayBuffer> New(
Isolate* isolate, void* data, size_t byte_length,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
/**
* Create a new ArrayBuffer with an existing backing store.
* The created array keeps a reference to the backing store until the array
@@ -5487,6 +5558,15 @@ class V8_EXPORT ArrayBuffer : public Object {
void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
void* deleter_data);
/**
* Returns true if ArrayBuffer is externalized, that is, does not
* own its memory block.
*/
V8_DEPRECATED(
"With v8::BackingStore externalized ArrayBuffers are "
"the same as ordinary ArrayBuffers. See http://crbug.com/v8/9908.")
bool IsExternal() const;
/**
* Returns true if this ArrayBuffer may be detached.
*/
@@ -5500,11 +5580,47 @@ class V8_EXPORT ArrayBuffer : public Object {
*/
void Detach();
/**
* Make this ArrayBuffer external. The pointer to underlying memory block
* and byte length are returned as |Contents| structure. After ArrayBuffer
* had been externalized, it does no longer own the memory block. The caller
* should take steps to free memory when it is no longer needed.
*
* The Data pointer of ArrayBuffer::Contents must be freed using the provided
* deleter, which will call ArrayBuffer::Allocator::Free if the buffer
* was allocated with ArrayBuffer::Allocator::Allocate.
*/
V8_DEPRECATED("Use GetBackingStore or Detach. See http://crbug.com/v8/9908.")
Contents Externalize();
/**
* Marks this ArrayBuffer external given a witness that the embedder
* has fetched the backing store using the new GetBackingStore() function.
*
* With the new lifetime management of backing stores there is no need for
* externalizing, so this function exists only to make the transition easier.
*/
V8_DEPRECATED("This will be removed together with IsExternal.")
void Externalize(const std::shared_ptr<BackingStore>& backing_store);
/**
* Get a pointer to the ArrayBuffer's underlying memory block without
* externalizing it. If the ArrayBuffer is not externalized, this pointer
* will become invalid as soon as the ArrayBuffer gets garbage collected.
*
* The embedder should make sure to hold a strong reference to the
* ArrayBuffer while accessing this pointer.
*/
V8_DEPRECATED("Use GetBackingStore. See http://crbug.com/v8/9908.")
Contents GetContents();
/**
* Get a shared pointer to the backing store of this array buffer. This
* pointer coordinates the lifetime management of the internal storage
* with any live ArrayBuffers on the heap, even across isolates. The embedder
* should not attempt to manage lifetime of the storage through other means.
*
* This function replaces both Externalize() and GetContents().
*/
std::shared_ptr<BackingStore> GetBackingStore();
@@ -5516,6 +5632,7 @@ class V8_EXPORT ArrayBuffer : public Object {
private:
ArrayBuffer();
static void CheckCast(Value* obj);
Contents GetContents(bool externalize);
};
@@ -5808,6 +5925,57 @@ class V8_EXPORT DataView : public ArrayBufferView {
*/
class V8_EXPORT SharedArrayBuffer : public Object {
public:
/**
* The contents of an |SharedArrayBuffer|. Externalization of
* |SharedArrayBuffer| returns an instance of this class, populated, with a
* pointer to data and byte length.
*
* The Data pointer of ArrayBuffer::Contents must be freed using the provided
* deleter, which will call ArrayBuffer::Allocator::Free if the buffer
* was allocated with ArraryBuffer::Allocator::Allocate.
*/
class V8_EXPORT Contents { // NOLINT
public:
using Allocator = v8::ArrayBuffer::Allocator;
using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
Contents()
: data_(nullptr),
byte_length_(0),
allocation_base_(nullptr),
allocation_length_(0),
allocation_mode_(Allocator::AllocationMode::kNormal),
deleter_(nullptr),
deleter_data_(nullptr) {}
void* AllocationBase() const { return allocation_base_; }
size_t AllocationLength() const { return allocation_length_; }
Allocator::AllocationMode AllocationMode() const {
return allocation_mode_;
}
void* Data() const { return data_; }
size_t ByteLength() const { return byte_length_; }
DeleterCallback Deleter() const { return deleter_; }
void* DeleterData() const { return deleter_data_; }
private:
Contents(void* data, size_t byte_length, void* allocation_base,
size_t allocation_length,
Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
void* deleter_data);
void* data_;
size_t byte_length_;
void* allocation_base_;
size_t allocation_length_;
Allocator::AllocationMode allocation_mode_;
DeleterCallback deleter_;
void* deleter_data_;
friend class SharedArrayBuffer;
};
/**
* Data length in bytes.
*/
@@ -5821,6 +5989,19 @@ class V8_EXPORT SharedArrayBuffer : public Object {
*/
static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
/**
* Create a new SharedArrayBuffer over an existing memory block. The created
* array buffer is immediately in externalized state unless otherwise
* specified. The memory block will not be reclaimed when a created
* SharedArrayBuffer is garbage-collected.
*/
V8_DEPRECATED(
"Use the version that takes a BackingStore. "
"See http://crbug.com/v8/9908.")
static Local<SharedArrayBuffer> New(
Isolate* isolate, void* data, size_t byte_length,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
/**
* Create a new SharedArrayBuffer with an existing backing store.
* The created array keeps a reference to the backing store until the array
@@ -5859,11 +6040,73 @@ class V8_EXPORT SharedArrayBuffer : public Object {
void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
void* deleter_data);
/**
* Create a new SharedArrayBuffer over an existing memory block. Propagate
* flags to indicate whether the underlying buffer can be grown.
*/
V8_DEPRECATED(
"Use the version that takes a BackingStore. "
"See http://crbug.com/v8/9908.")
static Local<SharedArrayBuffer> New(
Isolate* isolate, const SharedArrayBuffer::Contents&,
ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
/**
* Returns true if SharedArrayBuffer is externalized, that is, does not
* own its memory block.
*/
V8_DEPRECATED(
"With v8::BackingStore externalized SharedArrayBuffers are the same "
"as ordinary SharedArrayBuffers. See http://crbug.com/v8/9908.")
bool IsExternal() const;
/**
* Make this SharedArrayBuffer external. The pointer to underlying memory
* block and byte length are returned as |Contents| structure. After
* SharedArrayBuffer had been externalized, it does no longer own the memory
* block. The caller should take steps to free memory when it is no longer
* needed.
*
* The memory block is guaranteed to be allocated with |Allocator::Allocate|
* by the allocator specified in
* v8::Isolate::CreateParams::array_buffer_allocator.
*
*/
V8_DEPRECATED("Use GetBackingStore or Detach. See http://crbug.com/v8/9908.")
Contents Externalize();
/**
* Marks this SharedArrayBuffer external given a witness that the embedder
* has fetched the backing store using the new GetBackingStore() function.
*
* With the new lifetime management of backing stores there is no need for
* externalizing, so this function exists only to make the transition easier.
*/
V8_DEPRECATED("This will be removed together with IsExternal.")
void Externalize(const std::shared_ptr<BackingStore>& backing_store);
/**
* Get a pointer to the ArrayBuffer's underlying memory block without
* externalizing it. If the ArrayBuffer is not externalized, this pointer
* will become invalid as soon as the ArrayBuffer became garbage collected.
*
* The embedder should make sure to hold a strong reference to the
* ArrayBuffer while accessing this pointer.
*
* The memory block is guaranteed to be allocated with |Allocator::Allocate|
* by the allocator specified in
* v8::Isolate::CreateParams::array_buffer_allocator.
*/
V8_DEPRECATED("Use GetBackingStore. See http://crbug.com/v8/9908.")
Contents GetContents();
/**
* Get a shared pointer to the backing store of this array buffer. This
* pointer coordinates the lifetime management of the internal storage
* with any live ArrayBuffers on the heap, even across isolates. The embedder
* should not attempt to manage lifetime of the storage through other means.
*
* This function replaces both Externalize() and GetContents().
*/
std::shared_ptr<BackingStore> GetBackingStore();
@@ -5874,6 +6117,7 @@ class V8_EXPORT SharedArrayBuffer : public Object {
private:
SharedArrayBuffer();
static void CheckCast(Value* obj);
Contents GetContents(bool externalize);
};
@@ -6104,8 +6348,7 @@ class V8_EXPORT Template : public Data {
PropertyAttribute attributes = None);
void SetPrivate(Local<Private> name, Local<Data> value,
PropertyAttribute attributes = None);
V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value,
PropertyAttribute attributes = None);
V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
void SetAccessorProperty(
Local<Name> name,
@@ -6535,9 +6778,7 @@ class V8_EXPORT FunctionTemplate : public Template {
Local<Signature> signature = Local<Signature>(), int length = 0,
ConstructorBehavior behavior = ConstructorBehavior::kAllow,
SideEffectType side_effect_type = SideEffectType::kHasSideEffect,
const CFunction* c_function = nullptr, uint16_t instance_type = 0,
uint16_t allowed_receiver_instance_type_range_start = 0,
uint16_t allowed_receiver_instance_type_range_end = 0);
const CFunction* c_function = nullptr);
/** Creates a function template for multiple overloaded fast API calls.*/
static Local<FunctionTemplate> NewWithCFunctionOverloads(
@@ -6577,6 +6818,17 @@ class V8_EXPORT FunctionTemplate : public Template {
* API call, see the comment above the class declaration.
*/
void SetCallHandler(
FunctionCallback callback, Local<Value> data = Local<Value>(),
SideEffectType side_effect_type = SideEffectType::kHasSideEffect,
const CFunction* c_function = nullptr);
/**
* Set the call-handler callback for a FunctionTemplate. This
* callback is called whenever the function created from this
* FunctionTemplate is called. The 'c_function' represents a fast
* API call, see the comment above the class declaration.
*/
void SetCallHandlerV8_92(
FunctionCallback callback, Local<Value> data = Local<Value>(),
SideEffectType side_effect_type = SideEffectType::kHasSideEffect,
const MemorySpan<const CFunction>& c_function_overloads = {});
@@ -6994,7 +7246,7 @@ class V8_EXPORT ObjectTemplate : public Template {
* Gets the number of internal fields for objects generated from
* this template.
*/
int InternalFieldCount() const;
int InternalFieldCount();
/**
* Sets the number of internal fields for objects generated from
@@ -7005,7 +7257,7 @@ class V8_EXPORT ObjectTemplate : public Template {
/**
* Returns true if the object will be an immutable prototype exotic object.
*/
bool IsImmutableProto() const;
bool IsImmutableProto();
/**
* Makes the ObjectTemplate for an immutable prototype exotic object, with an
@@ -7023,7 +7275,7 @@ class V8_EXPORT ObjectTemplate : public Template {
* Reference: https://github.com/tc39/proposal-dynamic-code-brand-checks
*/
void SetCodeLike();
bool IsCodeLike() const;
bool IsCodeLike();
V8_INLINE static ObjectTemplate* Cast(Data* data);
@@ -8382,6 +8634,11 @@ class V8_EXPORT Isolate {
*/
int embedder_wrapper_type_index = -1;
int embedder_wrapper_object_index = -1;
V8_DEPRECATED(
"Setting this has no effect. Embedders should ignore import assertions "
"that they do not use.")
std::vector<std::string> supported_import_assertions;
};
/**
@@ -8893,6 +9150,10 @@ class V8_EXPORT Isolate {
std::unique_ptr<MeasureMemoryDelegate> delegate,
MeasureMemoryExecution execution = MeasureMemoryExecution::kDefault);
V8_DEPRECATED("Use the version with a delegate")
MaybeLocal<Promise> MeasureMemory(Local<Context> context,
MeasureMemoryMode mode);
/**
* Get a call stack sample from the isolate.
* \param state Execution state.
@@ -9570,6 +9831,13 @@ class V8_EXPORT Isolate {
* Set the callback to invoke to check if code generation from
* strings should be allowed.
*/
V8_DEPRECATED(
"Use Isolate::SetModifyCodeGenerationFromStringsCallback with "
"ModifyCodeGenerationFromStringsCallback2 instead. See "
"http://crbug.com/1096017 and TC39 Dynamic Code Brand Checks proposal "
"at https://github.com/tc39/proposal-dynamic-code-brand-checks.")
void SetModifyCodeGenerationFromStringsCallback(
ModifyCodeGenerationFromStringsCallback callback);
void SetModifyCodeGenerationFromStringsCallback(
ModifyCodeGenerationFromStringsCallback2 callback);
@@ -9917,6 +10185,30 @@ class V8_EXPORT V8 {
*/
static void ShutdownPlatform();
#if V8_OS_POSIX
/**
* Give the V8 signal handler a chance to handle a fault.
*
* This function determines whether a memory access violation can be recovered
* by V8. If so, it will return true and modify context to return to a code
* fragment that can recover from the fault. Otherwise, TryHandleSignal will
* return false.
*
* The parameters to this function correspond to those passed to a Linux
* signal handler.
*
* \param signal_number The signal number.
*
* \param info A pointer to the siginfo_t structure provided to the signal
* handler.
*
* \param context The third argument passed to the Linux signal handler, which
* points to a ucontext_t structure.
*/
V8_DEPRECATED("Use TryHandleWebAssemblyTrapPosix")
static bool TryHandleSignal(int signal_number, void* info, void* context);
#endif // V8_OS_POSIX
/**
* Activate trap-based bounds checking for WebAssembly.
*
@@ -9944,6 +10236,15 @@ class V8_EXPORT V8 {
*/
static void GetSharedMemoryStatistics(SharedMemoryStatistics* statistics);
/**
* Notifies V8 that the process is cross-origin-isolated, which enables
* defining the SharedArrayBuffer function on the global object of Contexts.
*/
V8_DEPRECATED(
"Use the command line argument --enable-sharedarraybuffer-per-context "
"together with SetSharedArrayBufferConstructorEnabledCallback")
static void SetIsCrossOriginIsolated();
private:
V8();
@@ -10616,7 +10917,7 @@ class V8_EXPORT Context : public Data {
* Returns true if code generation from strings is allowed for the context.
* For more details see AllowCodeGenerationFromStrings(bool) documentation.
*/
bool IsCodeGenerationFromStringsAllowed() const;
bool IsCodeGenerationFromStringsAllowed();
/**
* Sets the error description for the exception that is thrown when
@@ -11554,8 +11855,7 @@ int ScriptOrigin::ScriptId() const { return script_id_; }
Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
CachedData* data,
ConsumeCodeCacheTask* consume_cache_task)
CachedData* data)
: source_string(string),
resource_name(origin.ResourceName()),
resource_line_offset(origin.LineOffset()),
@@ -11563,18 +11863,21 @@ ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
resource_options(origin.Options()),
source_map_url(origin.SourceMapUrl()),
host_defined_options(origin.HostDefinedOptions()),
cached_data(data),
consume_cache_task(consume_cache_task) {}
cached_data(data) {}
ScriptCompiler::Source::Source(Local<String> string,
CachedData* data)
: source_string(string), cached_data(data) {}
ScriptCompiler::Source::~Source() {
delete cached_data;
}
ScriptCompiler::Source::Source(Local<String> string, CachedData* data,
ConsumeCodeCacheTask* consume_cache_task)
: source_string(string),
cached_data(data),
consume_cache_task(consume_cache_task) {}
const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
const {
return cached_data.get();
return cached_data;
}
const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const {
@@ -11585,11 +11888,10 @@ Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
return value ? True(isolate) : False(isolate);
}
void Template::Set(Isolate* isolate, const char* name, Local<Data> value,
PropertyAttribute attributes) {
void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
Set(String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
.ToLocalChecked(),
value, attributes);
value);
}
FunctionTemplate* FunctionTemplate::Cast(Data* data) {
@@ -11627,8 +11929,10 @@ Local<Value> Object::GetInternalField(int index) {
A obj = *reinterpret_cast<A*>(this);
// Fast path: If the object is a plain JSObject, which is the common case, we
// know where to find the internal fields and can return the value directly.
int instance_type = I::GetInstanceType(obj);
if (v8::internal::CanHaveInternalField(instance_type)) {
auto instance_type = I::GetInstanceType(obj);
if (instance_type == I::kJSObjectType ||
instance_type == I::kJSApiObjectType ||
instance_type == I::kJSSpecialApiObjectType) {
int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
A value = I::ReadRawField<A>(obj, offset);
#ifdef V8_COMPRESS_POINTERS
@@ -11654,7 +11958,9 @@ void* Object::GetAlignedPointerFromInternalField(int index) {
// Fast path: If the object is a plain JSObject, which is the common case, we
// know where to find the internal fields and can return the value directly.
auto instance_type = I::GetInstanceType(obj);
if (v8::internal::CanHaveInternalField(instance_type)) {
if (V8_LIKELY(instance_type == I::kJSObjectType ||
instance_type == I::kJSApiObjectType ||
instance_type == I::kJSSpecialApiObjectType)) {
int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
#ifdef V8_HEAP_SANDBOX
offset += I::kEmbedderDataSlotRawPayloadOffset;
+6 -8
View File
@@ -528,14 +528,12 @@ MaybeHandle<JSFunction> InstantiateFunction(
Handle<HeapObject>::cast(parent_prototype));
}
}
InstanceType function_type = JS_SPECIAL_API_OBJECT_TYPE;
if (!data->needs_access_check() &&
data->GetNamedPropertyHandler().IsUndefined(isolate) &&
data->GetIndexedPropertyHandler().IsUndefined(isolate)) {
function_type = FLAG_embedder_instance_types && data->HasInstanceType()
? static_cast<InstanceType>(data->InstanceType())
: JS_API_OBJECT_TYPE;
}
InstanceType function_type =
(!data->needs_access_check() &&
data->GetNamedPropertyHandler().IsUndefined(isolate) &&
data->GetIndexedPropertyHandler().IsUndefined(isolate))
? JS_API_OBJECT_TYPE
: JS_SPECIAL_API_OBJECT_TYPE;
Handle<JSFunction> function = ApiNatives::CreateApiFunction(
isolate, native_context, data, prototype, function_type, maybe_name);
+525 -193
View File
File diff suppressed because it is too large. Load diff
+1 -13
View File
@@ -552,20 +552,8 @@ extern class Filler extends HeapObject generates 'TNode<HeapObject>';
// but not their own class definitions:
// Like JSObject, but created from API function.
@apiExposedInstanceTypeValue(0x422)
@doNotGenerateCast
@noVerifier
@apiExposedInstanceTypeValue(0x420)
extern class JSApiObject extends JSObject generates 'TNode<JSObject>';
// TODO(gsathya): This only exists to make JSApiObject instance type into a
// range.
@apiExposedInstanceTypeValue(0x80A)
@doNotGenerateCast
@highestInstanceTypeWithinParentClassRange
@noVerifier
extern class JSLastDummyApiObject extends JSApiObject
generates 'TNode<JSObject>';
// Like JSApiObject, but requires access checks and/or has interceptors.
@apiExposedInstanceTypeValue(0x410)
extern class JSSpecialApiObject extends JSSpecialObject
+2 -35
View File
@@ -1681,37 +1681,6 @@ Handle<Script> BackgroundCompileTask::GetScript(Isolate* isolate) {
return handle(*script_, isolate);
}
BackgroundDeserializeTask::BackgroundDeserializeTask(
Isolate* isolate, std::unique_ptr<ScriptCompiler::CachedData> cached_data)
: isolate_for_local_isolate_(isolate),
cached_data_(cached_data->data, cached_data->length) {
// If the passed in cached data has ownership of the buffer, move it to the
// task.
if (cached_data->buffer_policy == ScriptCompiler::CachedData::BufferOwned &&
!cached_data_.HasDataOwnership()) {
cached_data->buffer_policy = ScriptCompiler::CachedData::BufferNotOwned;
cached_data_.AcquireDataOwnership();
}
}
void BackgroundDeserializeTask::Run() {
LocalIsolate isolate(isolate_for_local_isolate_, ThreadKind::kBackground);
UnparkedScope unparked_scope(&isolate);
LocalHandleScope handle_scope(&isolate);
Handle<SharedFunctionInfo> inner_result;
off_thread_data_ =
CodeSerializer::StartDeserializeOffThread(&isolate, &cached_data_);
}
MaybeHandle<SharedFunctionInfo> BackgroundDeserializeTask::Finish(
Isolate* isolate, Handle<String> source,
ScriptOriginOptions origin_options) {
return CodeSerializer::FinishOffThreadDeserialize(
isolate, std::move(off_thread_data_), &cached_data_, source,
origin_options);
}
// ----------------------------------------------------------------------------
// Implementation of Compiler
@@ -2836,8 +2805,7 @@ MaybeHandle<SharedFunctionInfo> CompileScriptOnBothBackgroundAndMainThread(
MaybeHandle<SharedFunctionInfo> Compiler::GetSharedFunctionInfoForScript(
Isolate* isolate, Handle<String> source,
const ScriptDetails& script_details, v8::Extension* extension,
AlignedCachedData* cached_data,
ScriptCompiler::CompileOptions compile_options,
ScriptData* cached_data, ScriptCompiler::CompileOptions compile_options,
ScriptCompiler::NoCacheReason no_cache_reason, NativesFlag natives) {
ScriptCompileTimerScope compile_timer(isolate, no_cache_reason);
@@ -2941,8 +2909,7 @@ MaybeHandle<SharedFunctionInfo> Compiler::GetSharedFunctionInfoForScript(
MaybeHandle<JSFunction> Compiler::GetWrappedFunction(
Handle<String> source, Handle<FixedArray> arguments,
Handle<Context> context, const ScriptDetails& script_details,
AlignedCachedData* cached_data,
v8::ScriptCompiler::CompileOptions compile_options,
ScriptData* cached_data, v8::ScriptCompiler::CompileOptions compile_options,
v8::ScriptCompiler::NoCacheReason no_cache_reason) {
Isolate* isolate = context->GetIsolate();
ScriptCompileTimerScope compile_timer(isolate, no_cache_reason);
+3 -22
View File
@@ -19,7 +19,6 @@
#include "src/objects/debug-objects.h"
#include "src/parsing/parse-info.h"
#include "src/parsing/pending-compilation-error-handler.h"
#include "src/snapshot/code-serializer.h"
#include "src/utils/allocation.h"
#include "src/zone/zone.h"
@@ -27,7 +26,6 @@ namespace v8 {
namespace internal {
// Forward declarations.
class AlignedCachedData;
class AstRawString;
class BackgroundCompileTask;
class IsCompiledScope;
@@ -37,6 +35,7 @@ class OptimizedCompilationJob;
class ParseInfo;
class Parser;
class RuntimeCallStats;
class ScriptData;
class TimedHistogram;
class UnoptimizedCompilationInfo;
class UnoptimizedCompilationJob;
@@ -137,7 +136,7 @@ class V8_EXPORT_PRIVATE Compiler : public AllStatic {
V8_WARN_UNUSED_RESULT static MaybeHandle<JSFunction> GetWrappedFunction(
Handle<String> source, Handle<FixedArray> arguments,
Handle<Context> context, const ScriptDetails& script_details,
AlignedCachedData* cached_data,
ScriptData* cached_data,
v8::ScriptCompiler::CompileOptions compile_options,
v8::ScriptCompiler::NoCacheReason no_cache_reason);
@@ -162,8 +161,7 @@ class V8_EXPORT_PRIVATE Compiler : public AllStatic {
static MaybeHandle<SharedFunctionInfo> GetSharedFunctionInfoForScript(
Isolate* isolate, Handle<String> source,
const ScriptDetails& script_details, v8::Extension* extension,
AlignedCachedData* cached_data,
ScriptCompiler::CompileOptions compile_options,
ScriptData* cached_data, ScriptCompiler::CompileOptions compile_options,
ScriptCompiler::NoCacheReason no_cache_reason,
NativesFlag is_natives_code);
@@ -560,23 +558,6 @@ struct ScriptStreamingData {
std::unique_ptr<BackgroundCompileTask> task;
};
class V8_EXPORT_PRIVATE BackgroundDeserializeTask {
public:
BackgroundDeserializeTask(Isolate* isolate,
std::unique_ptr<ScriptCompiler::CachedData> data);
void Run();
MaybeHandle<SharedFunctionInfo> Finish(Isolate* isolate,
Handle<String> source,
ScriptOriginOptions origin_options);
private:
Isolate* isolate_for_local_isolate_;
AlignedCachedData cached_data_;
CodeSerializer::OffThreadDeserializeData off_thread_data_;
};
} // namespace internal
} // namespace v8
+1 -2
View File
@@ -467,8 +467,7 @@ class FastCApiObject {
static bool IsValidApiObject(Local<Object> object) {
i::Address addr = *reinterpret_cast<i::Address*>(*object);
auto instance_type = i::Internals::GetInstanceType(addr);
return (base::IsInRange(instance_type, i::Internals::kFirstJSApiObjectType,
i::Internals::kLastJSApiObjectType) ||
return (instance_type == i::Internals::kJSApiObjectType ||
instance_type == i::Internals::kJSSpecialApiObjectType);
}
static FastCApiObject* UnwrapObject(Local<Object> object) {
+3 -4
View File
@@ -2842,12 +2842,11 @@ Local<ObjectTemplate> Shell::CreateOSTemplate(Isolate* isolate) {
Local<ObjectTemplate> os_template = ObjectTemplate::New(isolate);
AddOSMethods(isolate, os_template);
os_template->Set(isolate, "name",
v8::String::NewFromUtf8Literal(isolate, V8_TARGET_OS_STRING),
PropertyAttribute::ReadOnly);
v8::String::NewFromUtf8Literal(isolate,
V8_TARGET_OS_STRING));
os_template->Set(
isolate, "d8Path",
v8::String::NewFromUtf8(isolate, options.d8_path).ToLocalChecked(),
PropertyAttribute::ReadOnly);
v8::String::NewFromUtf8(isolate, options.d8_path).ToLocalChecked());
return os_template;
}
+2 -2
View File
@@ -758,10 +758,10 @@ MaybeLocal<UnboundScript> CompileInspectorScript(Isolate* v8_isolate,
i::Handle<i::String> str = Utils::OpenHandle(*source);
i::Handle<i::SharedFunctionInfo> result;
{
i::AlignedCachedData* cached_data = nullptr;
i::ScriptData* script_data = nullptr;
i::MaybeHandle<i::SharedFunctionInfo> maybe_function_info =
i::Compiler::GetSharedFunctionInfoForScript(
isolate, str, i::ScriptDetails(), nullptr, cached_data,
isolate, str, i::ScriptDetails(), nullptr, script_data,
ScriptCompiler::kNoCompileOptions,
ScriptCompiler::kNoCacheBecauseInspector,
i::FLAG_expose_inspector_scripts ? i::NOT_NATIVES_CODE
-2
View File
@@ -302,8 +302,6 @@ void HeapObject::HeapObjectVerify(Isolate* isolate) {
#undef TYPED_ARRAY_CONSTRUCTORS_SWITCH
JSFunction::cast(*this).JSFunctionVerify(isolate);
break;
case JS_LAST_DUMMY_API_OBJECT_TYPE:
UNREACHABLE();
}
}
-1
View File
@@ -261,7 +261,6 @@ void HeapObject::HeapObjectPrint(std::ostream& os) {
case THIN_ONE_BYTE_STRING_TYPE:
case UNCACHED_EXTERNAL_STRING_TYPE:
case UNCACHED_EXTERNAL_ONE_BYTE_STRING_TYPE:
case JS_LAST_DUMMY_API_OBJECT_TYPE:
// TODO(all): Handle these types too.
os << "UNKNOWN TYPE " << map().instance_type();
UNREACHABLE();
+4 -11
View File
@@ -30,7 +30,7 @@ class Isolate;
class IsolateData final {
public:
IsolateData(Isolate* isolate, Address cage_base)
: cage_base_(cage_base), stack_guard_(isolate) {}
: stack_guard_(isolate), cage_base_(cage_base) {}
IsolateData(const IsolateData&) = delete;
IsolateData& operator=(const IsolateData&) = delete;
@@ -160,10 +160,9 @@ class IsolateData final {
V(kFastCCallCallerFPOffset, kSystemPointerSize) \
V(kFastCCallCallerPCOffset, kSystemPointerSize) \
V(kFastApiCallTargetOffset, kSystemPointerSize) \
V(kCageBaseOffset, kSystemPointerSize) \
V(kLongTaskStatsCounterOffset, kSizetSize) \
V(kStackGuardOffset, StackGuard::kSizeInBytes) \
V(kRootsTableOffset, RootsTable::kEntriesCount* kSystemPointerSize) \
V(kCageBaseOffset, kSystemPointerSize) \
V(kExternalReferenceTableOffset, ExternalReferenceTable::kSizeInBytes) \
V(kThreadLocalTopOffset, ThreadLocalTop::kSizeInBytes) \
V(kBuiltinEntryTableOffset, Builtins::kBuiltinCount* kSystemPointerSize) \
@@ -200,18 +199,14 @@ class IsolateData final {
Address fast_c_call_caller_pc_ = kNullAddress;
Address fast_api_call_target_ = kNullAddress;
Address cage_base_ = kNullAddress;
// Used for implementation of LongTaskStats. Counts the number of potential
// long tasks.
size_t long_task_stats_counter_ = 0;
// Fields related to the system and JS stack. In particular, this contains
// the stack limit used by stack checks in generated code.
StackGuard stack_guard_;
RootsTable roots_;
Address cage_base_ = kNullAddress;
ExternalReferenceTable external_reference_table_;
ThreadLocalTop thread_local_top_;
@@ -272,8 +267,6 @@ void IsolateData::AssertPredictableLayout() {
STATIC_ASSERT(offsetof(IsolateData, fast_api_call_target_) ==
kFastApiCallTargetOffset);
STATIC_ASSERT(offsetof(IsolateData, cage_base_) == kCageBaseOffset);
STATIC_ASSERT(offsetof(IsolateData, long_task_stats_counter_) ==
kLongTaskStatsCounterOffset);
STATIC_ASSERT(offsetof(IsolateData, stack_guard_) == kStackGuardOffset);
#ifdef V8_HEAP_SANDBOX
STATIC_ASSERT(offsetof(IsolateData, external_pointer_table_) ==
-17
View File
@@ -3065,11 +3065,6 @@ void Isolate::CheckIsolateLayout() {
CHECK_EQ(static_cast<int>(
OFFSET_OF(Isolate, isolate_data_.fast_c_call_caller_pc_)),
Internals::kIsolateFastCCallCallerPcOffset);
CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.cage_base_)),
Internals::kIsolateCageBaseOffset);
CHECK_EQ(static_cast<int>(
OFFSET_OF(Isolate, isolate_data_.long_task_stats_counter_)),
Internals::kIsolateLongTaskStatsCounterOffset);
CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.stack_guard_)),
Internals::kIsolateStackGuardOffset);
CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, isolate_data_.roots_)),
@@ -5025,18 +5020,6 @@ MaybeLocal<v8::Context> Isolate::GetContextFromRecorderContextId(
return result->second.Get(reinterpret_cast<v8::Isolate*>(this));
}
void Isolate::UpdateLongTaskStats() {
if (last_long_task_stats_counter_ != isolate_data_.long_task_stats_counter_) {
last_long_task_stats_counter_ = isolate_data_.long_task_stats_counter_;
long_task_stats_ = v8::metrics::LongTaskStats{};
}
}
v8::metrics::LongTaskStats* Isolate::GetCurrentLongTaskStats() {
UpdateLongTaskStats();
return &long_task_stats_;
}
void Isolate::RemoveContextIdCallback(const v8::WeakCallbackInfo<void>& data) {
Isolate* isolate = reinterpret_cast<Isolate*>(data.GetIsolate());
uintptr_t context_id = reinterpret_cast<uintptr_t>(data.GetParameter());
-6
View File
@@ -1775,9 +1775,6 @@ class V8_EXPORT_PRIVATE Isolate final : private HiddenFactory {
MaybeLocal<v8::Context> GetContextFromRecorderContextId(
v8::metrics::Recorder::ContextId id);
void UpdateLongTaskStats();
v8::metrics::LongTaskStats* GetCurrentLongTaskStats();
LocalIsolate* main_thread_local_isolate() {
return main_thread_local_isolate_.get();
}
@@ -2160,9 +2157,6 @@ class V8_EXPORT_PRIVATE Isolate final : private HiddenFactory {
Persistent<v8::Context, v8::CopyablePersistentTraits<v8::Context>>>
recorder_context_id_map_;
size_t last_long_task_stats_counter_ = 0;
v8::metrics::LongTaskStats long_task_stats_;
std::vector<Object> startup_object_cache_;
// Used during builtins compilation to build the builtins constants table,
-5
View File
@@ -1385,17 +1385,12 @@ DEFINE_BOOL(stress_background_compile, false,
DEFINE_BOOL(
finalize_streaming_on_background, true,
"perform the script streaming finalization on the background thread")
DEFINE_BOOL(concurrent_cache_deserialization, true,
"enable deserializing code caches on background")
// TODO(leszeks): Parallel compile tasks currently don't support off-thread
// finalization.
DEFINE_NEG_IMPLICATION(parallel_compile_tasks, finalize_streaming_on_background)
DEFINE_BOOL(disable_old_api_accessors, false,
"Disable old-style API accessors whose setters trigger through the "
"prototype chain")
DEFINE_BOOL(
embedder_instance_types, false,
"enable type checks based on instance types provided by the embedder")
// bootstrapper.cc
DEFINE_BOOL(expose_gc, false, "expose gc extension")
+2 -2
View File
@@ -1812,8 +1812,8 @@ Handle<JSObject> Factory::CopyJSObjectWithAllocationSite(
bool is_clonable_js_type =
instance_type == JS_REG_EXP_TYPE || instance_type == JS_OBJECT_TYPE ||
instance_type == JS_ERROR_TYPE || instance_type == JS_ARRAY_TYPE ||
instance_type == JS_SPECIAL_API_OBJECT_TYPE ||
InstanceTypeChecker::IsJSApiObject(instance_type);
instance_type == JS_API_OBJECT_TYPE ||
instance_type == JS_SPECIAL_API_OBJECT_TYPE;
bool is_clonable_wasm_type = false;
#if V8_ENABLE_WEBASSEMBLY
is_clonable_wasm_type = instance_type == WASM_GLOBAL_OBJECT_TYPE ||
-15
View File
@@ -91,15 +91,6 @@ GCTracer::Scope::~Scope() {
if (thread_kind_ == ThreadKind::kMain) {
DCHECK_EQ(tracer_->heap_->isolate()->thread_id(), ThreadId::Current());
tracer_->AddScopeSample(scope_, duration_ms);
if (scope_ == ScopeId::MC_INCREMENTAL ||
scope_ == ScopeId::MC_INCREMENTAL_START ||
scope_ == MC_INCREMENTAL_FINALIZE) {
auto* long_task_stats =
tracer_->heap_->isolate()->GetCurrentLongTaskStats();
long_task_stats->gc_full_incremental_wall_clock_duration_us +=
static_cast<int64_t>(duration_ms *
base::Time::kMicrosecondsPerMillisecond);
}
} else {
tracer_->AddScopeSampleBackground(scope_, duration_ms);
}
@@ -356,9 +347,6 @@ void GCTracer::Stop(GarbageCollector collector) {
AddAllocation(current_.end_time);
double duration = current_.end_time - current_.start_time;
int64_t duration_us =
static_cast<int64_t>(duration * base::Time::kMicrosecondsPerMillisecond);
auto* long_task_stats = heap_->isolate()->GetCurrentLongTaskStats();
switch (current_.type) {
case Event::SCAVENGER:
@@ -368,7 +356,6 @@ void GCTracer::Stop(GarbageCollector collector) {
recorded_minor_gcs_survived_.Push(
MakeBytesAndDuration(current_.survived_young_object_size, duration));
FetchBackgroundMinorGCCounters();
long_task_stats->gc_young_wall_clock_duration_us += duration_us;
break;
case Event::INCREMENTAL_MARK_COMPACTOR:
current_.incremental_marking_bytes = incremental_marking_bytes_;
@@ -388,7 +375,6 @@ void GCTracer::Stop(GarbageCollector collector) {
ResetIncrementalMarkingCounters();
combined_mark_compact_speed_cache_ = 0.0;
FetchBackgroundMarkCompactCounters();
long_task_stats->gc_full_atomic_wall_clock_duration_us += duration_us;
break;
case Event::MARK_COMPACTOR:
DCHECK_EQ(0u, current_.incremental_marking_bytes);
@@ -401,7 +387,6 @@ void GCTracer::Stop(GarbageCollector collector) {
ResetIncrementalMarkingCounters();
combined_mark_compact_speed_cache_ = 0.0;
FetchBackgroundMarkCompactCounters();
long_task_stats->gc_full_atomic_wall_clock_duration_us += duration_us;
break;
case Event::START:
UNREACHABLE();
-3
View File
@@ -3341,9 +3341,6 @@ void Heap::OnMoveEvent(HeapObject target, HeapObject source,
if (target.IsSharedFunctionInfo()) {
LOG_CODE_EVENT(isolate_, SharedFunctionInfoMoveEvent(source.address(),
target.address()));
} else if (target.IsNativeContext()) {
PROFILE(isolate_,
NativeContextMoveEvent(source.address(), target.address()));
}
if (FLAG_verify_predictable) {
-1
View File
@@ -82,7 +82,6 @@ class V8_EXPORT_PRIVATE LocalHeap {
std::unique_ptr<PersistentHandles> persistent_handles);
std::unique_ptr<PersistentHandles> DetachPersistentHandles();
#ifdef DEBUG
bool HasPersistentHandles() { return !!persistent_handles_; }
bool ContainsPersistentHandle(Address* location);
bool ContainsLocalHandle(Address* location);
bool IsHandleDereferenceAllowed();
+1 -1
View File
@@ -270,7 +270,7 @@ Response V8HeapProfilerAgentImpl::takeHeapSnapshot(
progress.reset(new HeapSnapshotProgress(&m_frontend));
GlobalObjectNameResolver resolver(m_session);
const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(
const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshotV8_92(
progress.get(), &resolver, treatGlobalObjectsAsRoots.fromMaybe(true),
captureNumericValue.fromMaybe(false));
if (!snapshot) return Response::ServerError("Failed to take heap snapshot");
-6
View File
@@ -98,7 +98,6 @@ class CodeEventListener {
// Not handlified as this happens during GC. No allocation allowed.
virtual void CodeMoveEvent(AbstractCode from, AbstractCode to) = 0;
virtual void SharedFunctionInfoMoveEvent(Address from, Address to) = 0;
virtual void NativeContextMoveEvent(Address from, Address to) = 0;
virtual void CodeMovingGCEvent() = 0;
virtual void CodeDisableOptEvent(Handle<AbstractCode> code,
Handle<SharedFunctionInfo> shared) = 0;
@@ -218,11 +217,6 @@ class CodeEventDispatcher : public CodeEventListener {
listener->SharedFunctionInfoMoveEvent(from, to);
});
}
void NativeContextMoveEvent(Address from, Address to) override {
DispatchEventToListeners([=](CodeEventListener* listener) {
listener->NativeContextMoveEvent(from, to);
});
}
void CodeMovingGCEvent() override {
DispatchEventToListeners(
[](CodeEventListener* listener) { listener->CodeMovingGCEvent(); });
-3
View File
@@ -223,7 +223,6 @@ class Logger : public CodeEventListener {
Handle<String> source) override;
void CodeMoveEvent(AbstractCode from, AbstractCode to) override;
void SharedFunctionInfoMoveEvent(Address from, Address to) override;
void NativeContextMoveEvent(Address from, Address to) override {}
void CodeMovingGCEvent() override;
void CodeDisableOptEvent(Handle<AbstractCode> code,
Handle<SharedFunctionInfo> shared) override;
@@ -443,7 +442,6 @@ class V8_EXPORT_PRIVATE CodeEventLogger : public CodeEventListener {
void GetterCallbackEvent(Handle<Name> name, Address entry_point) override {}
void SetterCallbackEvent(Handle<Name> name, Address entry_point) override {}
void SharedFunctionInfoMoveEvent(Address from, Address to) override {}
void NativeContextMoveEvent(Address from, Address to) override {}
void CodeMovingGCEvent() override {}
void CodeDeoptEvent(Handle<Code> code, DeoptimizeKind kind, Address pc,
int fp_to_sp_delta, bool reuse_code) override {}
@@ -509,7 +507,6 @@ class ExternalCodeEventListener : public CodeEventListener {
void GetterCallbackEvent(Handle<Name> name, Address entry_point) override {}
void SetterCallbackEvent(Handle<Name> name, Address entry_point) override {}
void SharedFunctionInfoMoveEvent(Address from, Address to) override {}
void NativeContextMoveEvent(Address from, Address to) override {}
void CodeMoveEvent(AbstractCode from, AbstractCode to) override;
void CodeDisableOptEvent(Handle<AbstractCode> code,
Handle<SharedFunctionInfo> shared) override {}
+32 -5
View File
@@ -814,8 +814,17 @@ inline GlobalBackingStoreRegistryImpl* impl() {
void GlobalBackingStoreRegistry::Register(
std::shared_ptr<BackingStore> backing_store) {
if (!backing_store || !backing_store->buffer_start()) return;
// Only wasm memory backing stores need to be registered globally.
CHECK(backing_store->is_wasm_memory());
if (!backing_store->free_on_destruct()) {
// If the backing store buffer is managed by the embedder,
// then we don't have to guarantee that there is single unique
// BackingStore per buffer_start() because the destructor of
// of the BackingStore will be a no-op in that case.
// All Wasm memory has to be registered.
CHECK(!backing_store->is_wasm_memory());
return;
}
base::MutexGuard scope_lock(&impl()->mutex_);
if (backing_store->globally_registered_) return;
@@ -831,8 +840,6 @@ void GlobalBackingStoreRegistry::Register(
void GlobalBackingStoreRegistry::Unregister(BackingStore* backing_store) {
if (!backing_store->globally_registered_) return;
CHECK(backing_store->is_wasm_memory());
DCHECK_NOT_NULL(backing_store->buffer_start());
base::MutexGuard scope_lock(&impl()->mutex_);
@@ -844,6 +851,26 @@ void GlobalBackingStoreRegistry::Unregister(BackingStore* backing_store) {
backing_store->globally_registered_ = false;
}
std::shared_ptr<BackingStore> GlobalBackingStoreRegistry::Lookup(
void* buffer_start, size_t length) {
base::MutexGuard scope_lock(&impl()->mutex_);
TRACE_BS("BS:lookup mem=%p (%zu bytes)\n", buffer_start, length);
const auto& result = impl()->map_.find(buffer_start);
if (result == impl()->map_.end()) {
return std::shared_ptr<BackingStore>();
}
auto backing_store = result->second.lock();
CHECK_EQ(buffer_start, backing_store->buffer_start());
if (backing_store->is_wasm_memory()) {
// Grow calls to shared WebAssembly threads can be triggered from different
// workers, length equality cannot be guaranteed here.
CHECK_LE(length, backing_store->byte_length());
} else {
CHECK_EQ(length, backing_store->byte_length());
}
return backing_store;
}
void GlobalBackingStoreRegistry::Purge(Isolate* isolate) {
// We need to keep a reference to all backing stores that are inspected
// in the purging loop below. Otherwise, we might get a deadlock
@@ -857,7 +884,7 @@ void GlobalBackingStoreRegistry::Purge(Isolate* isolate) {
auto backing_store = entry.second.lock();
prevent_destruction_under_lock.emplace_back(backing_store);
if (!backing_store) continue; // skip entries where weak ptr is null
CHECK(backing_store->is_wasm_memory());
if (!backing_store->is_wasm_memory()) continue; // skip non-wasm memory
if (!backing_store->is_shared()) continue; // skip non-shared memory
SharedWasmMemoryData* shared_data =
backing_store->get_shared_wasm_memory_data();
+8 -3
View File
@@ -253,16 +253,21 @@ class V8_EXPORT_PRIVATE BackingStore : public BackingStoreBase {
#endif // V8_ENABLE_WEBASSEMBLY
};
// A global, per-process mapping from buffer addresses to backing stores
// of wasm memory objects.
// A global, per-process mapping from buffer addresses to backing stores.
// This is generally only used for dealing with an embedder that has not
// migrated to the new API which should use proper pointers to manage
// backing stores.
class GlobalBackingStoreRegistry {
public:
// Register a backing store in the global registry. A mapping from the
// {buffer_start} to the backing store object will be added. The backing
// store will automatically unregister itself upon destruction.
// Only wasm memory backing stores are supported.
static void Register(std::shared_ptr<BackingStore> backing_store);
// Look up a backing store based on the {buffer_start} pointer.
static std::shared_ptr<BackingStore> Lookup(void* buffer_start,
size_t length);
private:
friend class BackingStore;
// Unregister a backing store in the global registry.
+1 -2
View File
@@ -149,8 +149,7 @@ constexpr InstanceType LAST_STRING_TYPE =
STATIC_ASSERT((FIRST_NONSTRING_TYPE & kIsNotStringMask) != kStringTag);
STATIC_ASSERT(JS_OBJECT_TYPE == Internals::kJSObjectType);
STATIC_ASSERT(FIRST_JS_API_OBJECT_TYPE == Internals::kFirstJSApiObjectType);
STATIC_ASSERT(LAST_JS_API_OBJECT_TYPE == Internals::kLastJSApiObjectType);
STATIC_ASSERT(JS_API_OBJECT_TYPE == Internals::kJSApiObjectType);
STATIC_ASSERT(JS_SPECIAL_API_OBJECT_TYPE == Internals::kJSSpecialApiObjectType);
STATIC_ASSERT(FIRST_NONSTRING_TYPE == Internals::kFirstNonstringType);
STATIC_ASSERT(ODDBALL_TYPE == Internals::kOddballType);
+4 -9
View File
@@ -2340,11 +2340,6 @@ int JSObject::GetHeaderSize(InstanceType type,
return WasmTagObject::kHeaderSize;
#endif // V8_ENABLE_WEBASSEMBLY
default: {
// Special type check for API Objects because they are in a large variable
// instance type range.
if (InstanceTypeChecker::IsJSApiObject(type)) {
return JSObject::kHeaderSize;
}
std::stringstream ss;
ss << type;
FATAL("unexpected instance type: %s\n", ss.str().c_str());
@@ -5152,18 +5147,18 @@ bool JSObject::IsApiWrapper() {
// *_API_* types are generated through templates which can have embedder
// fields. The other types have their embedder fields added at compile time.
auto instance_type = map().instance_type();
return instance_type == JS_ARRAY_BUFFER_TYPE ||
return instance_type == JS_API_OBJECT_TYPE ||
instance_type == JS_ARRAY_BUFFER_TYPE ||
instance_type == JS_DATA_VIEW_TYPE ||
instance_type == JS_GLOBAL_OBJECT_TYPE ||
instance_type == JS_GLOBAL_PROXY_TYPE ||
instance_type == JS_SPECIAL_API_OBJECT_TYPE ||
instance_type == JS_TYPED_ARRAY_TYPE ||
InstanceTypeChecker::IsJSApiObject(instance_type);
instance_type == JS_TYPED_ARRAY_TYPE;
}
bool JSObject::IsDroppableApiWrapper() {
auto instance_type = map().instance_type();
return InstanceTypeChecker::IsJSApiObject(instance_type) ||
return instance_type == JS_API_OBJECT_TYPE ||
instance_type == JS_SPECIAL_API_OBJECT_TYPE;
}
-4
View File
@@ -112,10 +112,6 @@ VisitorId Map::GetVisitorId(Map map) {
UNREACHABLE();
}
if (InstanceTypeChecker::IsJSApiObject(map.instance_type())) {
return kVisitJSApiObject;
}
switch (instance_type) {
case BYTE_ARRAY_TYPE:
return kVisitByteArray;
-1
View File
@@ -270,7 +270,6 @@ class ZoneForwardList;
V(FreeSpaceOrFiller) \
V(FunctionContext) \
V(JSApiObject) \
V(JSLastDummyApiObject) \
V(JSPromiseConstructor) \
V(JSArrayConstructor) \
V(JSRegExpConstructor) \
-3
View File
@@ -1006,9 +1006,6 @@ ReturnType BodyDescriptorApply(InstanceType type, T1 p1, T2 p2, T3 p3, T4 p4) {
}
UNREACHABLE();
}
if (InstanceTypeChecker::IsJSApiObject(type)) {
return Op::template apply<JSObject::BodyDescriptor>(p1, p2, p3, p4);
}
switch (type) {
case EMBEDDER_DATA_ARRAY_TYPE:
+6 -21
View File
@@ -38,12 +38,10 @@ BOOL_ACCESSORS(FunctionTemplateInfo, flag, accept_any_receiver,
AcceptAnyReceiverBit::kShift)
BOOL_ACCESSORS(FunctionTemplateInfo, flag, published, PublishedBit::kShift)
BIT_FIELD_ACCESSORS(
FunctionTemplateInfo, flag, allowed_receiver_instance_type_range_start,
FunctionTemplateInfo::AllowedReceiverInstanceTypeRangeStartBits)
BIT_FIELD_ACCESSORS(
FunctionTemplateInfo, flag, allowed_receiver_instance_type_range_end,
FunctionTemplateInfo::AllowedReceiverInstanceTypeRangeEndBits)
BIT_FIELD_ACCESSORS(FunctionTemplateInfo, flag, allowed_receiver_range_start,
FunctionTemplateInfo::AllowedReceiverRangeStartBits)
BIT_FIELD_ACCESSORS(FunctionTemplateInfo, flag, allowed_receiver_range_end,
FunctionTemplateInfo::AllowedReceiverRangeEndBits)
// static
FunctionTemplateRareData FunctionTemplateInfo::EnsureFunctionTemplateRareData(
@@ -87,23 +85,10 @@ RARE_ACCESSORS(c_function_overloads, CFunctionOverloads, FixedArray,
GetReadOnlyRoots(cage_base).empty_fixed_array())
#undef RARE_ACCESSORS
int FunctionTemplateInfo::InstanceType() const {
int type = instance_type();
DCHECK(type == kNoJSApiObjectType ||
(type >= Internals::kFirstJSApiObjectType &&
type <= Internals::kLastJSApiObjectType));
return type;
}
int FunctionTemplateInfo::InstanceType() const { return instance_type(); }
void FunctionTemplateInfo::SetInstanceType(int instance_type) {
if (instance_type == 0) {
set_instance_type(kNoJSApiObjectType);
} else {
DCHECK_GT(instance_type, 0);
DCHECK_LT(Internals::kFirstJSApiObjectType + instance_type,
Internals::kLastJSApiObjectType);
set_instance_type(Internals::kFirstJSApiObjectType + instance_type);
}
set_instance_type(instance_type);
}
bool TemplateInfo::should_cache() const {
-15
View File
@@ -18,10 +18,6 @@
namespace v8 {
namespace internal {
bool FunctionTemplateInfo::HasInstanceType() {
return instance_type() != kNoJSApiObjectType;
}
Handle<SharedFunctionInfo> FunctionTemplateInfo::GetOrCreateSharedFunctionInfo(
Isolate* isolate, Handle<FunctionTemplateInfo> info,
MaybeHandle<Name> maybe_name) {
@@ -65,17 +61,6 @@ bool FunctionTemplateInfo::IsTemplateFor(Map map) const {
// There is a constraint on the object; check.
if (!map.IsJSObjectMap()) return false;
if (FLAG_embedder_instance_types) {
DCHECK_IMPLIES(allowed_receiver_instance_type_range_start() == 0,
allowed_receiver_instance_type_range_end() == 0);
if (base::IsInRange(map.instance_type(),
allowed_receiver_instance_type_range_start(),
allowed_receiver_instance_type_range_end())) {
return true;
}
}
// Fetch the constructor function of the object.
Object cons_obj = map.GetConstructor();
Object type;
+2 -6
View File
@@ -123,10 +123,8 @@ class FunctionTemplateInfo
// safely read concurrently.
DECL_BOOLEAN_ACCESSORS(published)
// This specifies the permissable range of instance type of objects that can
// be allowed to be used as receivers with the given template.
DECL_INT16_ACCESSORS(allowed_receiver_instance_type_range_start)
DECL_INT16_ACCESSORS(allowed_receiver_instance_type_range_end)
DECL_INT_ACCESSORS(allowed_receiver_range_start)
DECL_INT_ACCESSORS(allowed_receiver_range_end)
// End flag bits ---------------------
// Dispatched behavior.
@@ -159,7 +157,6 @@ class FunctionTemplateInfo
inline bool instantiated();
bool BreakAtEntry();
bool HasInstanceType();
// Helper function for cached accessors.
static base::Optional<Name> TryGetCachedPropertyName(Isolate* isolate,
@@ -177,7 +174,6 @@ class FunctionTemplateInfo
DEFINE_TORQUE_GENERATED_FUNCTION_TEMPLATE_INFO_FLAGS()
private:
static constexpr int kNoJSApiObjectType = 0;
static inline FunctionTemplateRareData EnsureFunctionTemplateRareData(
Isolate* isolate, Handle<FunctionTemplateInfo> function_template_info);
+2 -2
View File
@@ -35,8 +35,8 @@ bitfield struct FunctionTemplateInfoFlags extends uint31 {
// Allowed receiver ranges are used for instance type checking to check
// whether the receiver calling the associated JSFunction is a compatible
// receiver.
allowed_receiver_instance_type_range_start: int16: 12 bit;
allowed_receiver_instance_type_range_end: int16: 12 bit;
allowed_receiver_range_start: int32: 12 bit;
allowed_receiver_range_end: int32: 12 bit;
}
extern class FunctionTemplateInfo extends TemplateInfo {
+5 -14
View File
@@ -104,11 +104,10 @@ ProfilingScope::~ProfilingScope() {
ProfilerEventsProcessor::ProfilerEventsProcessor(
Isolate* isolate, Symbolizer* symbolizer,
ProfilerCodeObserver* code_observer, CpuProfilesCollection* profiles)
ProfilerCodeObserver* code_observer)
: Thread(Thread::Options("v8:ProfEvntProc", kProfilerStackSize)),
symbolizer_(symbolizer),
code_observer_(code_observer),
profiles_(profiles),
last_code_event_id_(0),
last_processed_code_event_id_(0),
isolate_(isolate) {
@@ -120,8 +119,9 @@ SamplingEventsProcessor::SamplingEventsProcessor(
Isolate* isolate, Symbolizer* symbolizer,
ProfilerCodeObserver* code_observer, CpuProfilesCollection* profiles,
base::TimeDelta period, bool use_precise_sampling)
: ProfilerEventsProcessor(isolate, symbolizer, code_observer, profiles),
: ProfilerEventsProcessor(isolate, symbolizer, code_observer),
sampler_(new CpuSampler(isolate, this)),
profiles_(profiles),
period_(period),
use_precise_sampling_(use_precise_sampling) {
sampler_->Start();
@@ -188,14 +188,7 @@ void ProfilerEventsProcessor::StopSynchronously() {
bool ProfilerEventsProcessor::ProcessCodeEvent() {
CodeEventsContainer record;
if (events_buffer_.Dequeue(&record)) {
if (record.generic.type == CodeEventRecord::NATIVE_CONTEXT_MOVE) {
NativeContextMoveEventRecord& nc_record =
record.NativeContextMoveEventRecord_;
profiles_->UpdateNativeContextAddressForCurrentProfiles(
nc_record.from_address, nc_record.to_address);
} else {
code_observer_->CodeEventHandlerInternal(record);
}
code_observer_->CodeEventHandlerInternal(record);
last_processed_code_event_id_ = record.generic.order;
return true;
}
@@ -209,7 +202,6 @@ void ProfilerEventsProcessor::CodeEventHandler(
case CodeEventRecord::CODE_MOVE:
case CodeEventRecord::CODE_DISABLE_OPT:
case CodeEventRecord::CODE_DELETE:
case CodeEventRecord::NATIVE_CONTEXT_MOVE:
Enqueue(evt_rec);
break;
case CodeEventRecord::CODE_DEOPT: {
@@ -232,8 +224,7 @@ void SamplingEventsProcessor::SymbolizeAndAddToProfiles(
symbolizer_->SymbolizeTickSample(record->sample);
profiles_->AddPathToCurrentProfiles(
record->sample.timestamp, symbolized.stack_trace, symbolized.src_line,
record->sample.update_stats, record->sample.sampling_interval,
reinterpret_cast<Address>(record->sample.context));
record->sample.update_stats, record->sample.sampling_interval);
}
ProfilerEventsProcessor::SampleProcessingResult
+4 -16
View File
@@ -37,14 +37,10 @@ class Symbolizer;
V(REPORT_BUILTIN, ReportBuiltinEventRecord) \
V(CODE_DELETE, CodeDeleteEventRecord)
#define VM_EVENTS_TYPE_LIST(V) \
CODE_EVENTS_TYPE_LIST(V) \
V(NATIVE_CONTEXT_MOVE, NativeContextMoveEventRecord)
class CodeEventRecord {
public:
#define DECLARE_TYPE(type, ignore) type,
enum Type { NONE = 0, VM_EVENTS_TYPE_LIST(DECLARE_TYPE) };
enum Type { NONE = 0, CODE_EVENTS_TYPE_LIST(DECLARE_TYPE) };
#undef DECLARE_TYPE
Type type;
@@ -103,13 +99,6 @@ class ReportBuiltinEventRecord : public CodeEventRecord {
V8_INLINE void UpdateCodeMap(CodeMap* code_map);
};
// Signals that a native context's address has changed.
class NativeContextMoveEventRecord : public CodeEventRecord {
public:
Address from_address;
Address to_address;
};
// A record type for sending samples from the main thread/signal handler to the
// profiling thread.
class TickSampleEventRecord {
@@ -141,7 +130,7 @@ class CodeEventsContainer {
union {
CodeEventRecord generic;
#define DECLARE_CLASS(ignore, type) type type##_;
VM_EVENTS_TYPE_LIST(DECLARE_CLASS)
CODE_EVENTS_TYPE_LIST(DECLARE_CLASS)
#undef DECLARE_CLASS
};
};
@@ -185,8 +174,7 @@ class V8_EXPORT_PRIVATE ProfilerEventsProcessor : public base::Thread,
protected:
ProfilerEventsProcessor(Isolate* isolate, Symbolizer* symbolizer,
ProfilerCodeObserver* code_observer,
CpuProfilesCollection* profiles);
ProfilerCodeObserver* code_observer);
// Called from events processing thread (Run() method.)
bool ProcessCodeEvent();
@@ -200,7 +188,6 @@ class V8_EXPORT_PRIVATE ProfilerEventsProcessor : public base::Thread,
Symbolizer* symbolizer_;
ProfilerCodeObserver* code_observer_;
CpuProfilesCollection* profiles_;
std::atomic_bool running_{true};
base::ConditionVariable running_cond_;
base::Mutex running_mutex_;
@@ -251,6 +238,7 @@ class V8_EXPORT_PRIVATE SamplingEventsProcessor
SamplingCircularQueue<TickSampleEventRecord,
kTickSampleQueueLength> ticks_buffer_;
std::unique_ptr<sampler::Sampler> sampler_;
CpuProfilesCollection* profiles_;
base::TimeDelta period_; // Samples & code events processing period.
const bool use_precise_sampling_; // Whether or not busy-waiting is used for
// low sampling intervals on Windows.
+3 -31
View File
@@ -529,12 +529,6 @@ void ProfileTree::TraverseDepthFirst(Callback* callback) {
}
}
void ContextFilter::OnMoveEvent(Address from_address, Address to_address) {
if (native_context_address() != from_address) return;
set_native_context_address(to_address);
}
using v8::tracing::TracedValue;
std::atomic<uint32_t> CpuProfile::last_id_;
@@ -559,13 +553,6 @@ CpuProfile::CpuProfile(CpuProfiler* profiler, const char* title,
value->SetDouble("startTime", start_time_.since_origin().InMicroseconds());
TRACE_EVENT_SAMPLE_WITH_ID1(TRACE_DISABLED_BY_DEFAULT("v8.cpu_profiler"),
"Profile", id_, "data", std::move(value));
DisallowHeapAllocation no_gc;
if (options_.has_filter_context()) {
i::Address raw_filter_context =
reinterpret_cast<i::Address>(options_.raw_filter_context());
context_filter_.set_native_context_address(raw_filter_context);
}
}
bool CpuProfile::CheckSubsample(base::TimeDelta source_sampling_interval) {
@@ -715,8 +702,6 @@ void CpuProfile::StreamPendingTraceEvents() {
void CpuProfile::FinishProfile() {
end_time_ = base::TimeTicks::HighResolutionNow();
// Stop tracking context movements after profiling stops.
context_filter_.set_native_context_address(kNullAddress);
StreamPendingTraceEvents();
auto value = TracedValue::Create();
// The endTime timestamp is not converted to Perfetto's clock domain and will
@@ -946,28 +931,15 @@ base::TimeDelta CpuProfilesCollection::GetCommonSamplingInterval() const {
void CpuProfilesCollection::AddPathToCurrentProfiles(
base::TimeTicks timestamp, const ProfileStackTrace& path, int src_line,
bool update_stats, base::TimeDelta sampling_interval,
Address native_context_address) {
bool update_stats, base::TimeDelta sampling_interval) {
// As starting / stopping profiles is rare relatively to this
// method, we don't bother minimizing the duration of lock holding,
// e.g. copying contents of the list to a local vector.
current_profiles_semaphore_.Wait();
const ProfileStackTrace empty_path;
for (const std::unique_ptr<CpuProfile>& profile : current_profiles_) {
// If the context filter check failed, omit the contents of the stack.
bool accepts_context =
profile->context_filter().Accept(native_context_address);
profile->AddPath(timestamp, accepts_context ? path : empty_path, src_line,
update_stats, sampling_interval);
}
current_profiles_semaphore_.Signal();
}
void CpuProfilesCollection::UpdateNativeContextAddressForCurrentProfiles(
Address from, Address to) {
current_profiles_semaphore_.Wait();
for (const std::unique_ptr<CpuProfile>& profile : current_profiles_) {
profile->context_filter().OnMoveEvent(from, to);
profile->AddPath(timestamp, path, src_line, update_stats,
sampling_interval);
}
current_profiles_semaphore_.Signal();
}
+1 -32
View File
@@ -253,31 +253,6 @@ struct CodeEntryAndLineNumber {
using ProfileStackTrace = std::vector<CodeEntryAndLineNumber>;
// Filters stack frames from sources other than a target native context.
class ContextFilter {
public:
explicit ContextFilter(Address native_context_address = kNullAddress)
: native_context_address_(native_context_address) {}
// Invoked when a native context has changed address.
void OnMoveEvent(Address from_address, Address to_address);
bool Accept(Address native_context_address) const {
if (native_context_address_ == kNullAddress) return true;
return (native_context_address & ~kHeapObjectTag) ==
native_context_address_;
}
// Update the context's tracked address based on VM-thread events.
void set_native_context_address(Address address) {
native_context_address_ = address;
}
Address native_context_address() const { return native_context_address_; }
private:
Address native_context_address_;
};
class ProfileTree;
class V8_EXPORT_PRIVATE ProfileNode {
@@ -433,7 +408,6 @@ class CpuProfile {
base::TimeTicks start_time() const { return start_time_; }
base::TimeTicks end_time() const { return end_time_; }
CpuProfiler* cpu_profiler() const { return profiler_; }
ContextFilter& context_filter() { return context_filter_; }
void UpdateTicksScale();
@@ -445,7 +419,6 @@ class CpuProfile {
const char* title_;
const CpuProfilingOptions options_;
std::unique_ptr<DiscardedSamplesDelegate> delegate_;
ContextFilter context_filter_;
base::TimeTicks start_time_;
base::TimeTicks end_time_;
std::deque<SampleInfo> samples_;
@@ -553,11 +526,7 @@ class V8_EXPORT_PRIVATE CpuProfilesCollection {
void AddPathToCurrentProfiles(base::TimeTicks timestamp,
const ProfileStackTrace& path, int src_line,
bool update_stats,
base::TimeDelta sampling_interval,
Address native_context_address = kNullAddress);
// Called from profile generator thread.
void UpdateNativeContextAddressForCurrentProfiles(Address from, Address to);
base::TimeDelta sampling_interval);
// Limits the number of profiles that can be simultaneously collected.
static const int kMaxSimultaneousProfiles = 100;
-7
View File
@@ -303,13 +303,6 @@ void ProfilerListener::CodeMoveEvent(AbstractCode from, AbstractCode to) {
DispatchCodeEvent(evt_rec);
}
void ProfilerListener::NativeContextMoveEvent(Address from, Address to) {
CodeEventsContainer evt_rec(CodeEventRecord::NATIVE_CONTEXT_MOVE);
evt_rec.NativeContextMoveEventRecord_.from_address = from;
evt_rec.NativeContextMoveEventRecord_.to_address = to;
DispatchCodeEvent(evt_rec);
}
void ProfilerListener::CodeDisableOptEvent(Handle<AbstractCode> code,
Handle<SharedFunctionInfo> shared) {
CodeEventsContainer evt_rec(CodeEventRecord::CODE_DISABLE_OPT);
-1
View File
@@ -59,7 +59,6 @@ class V8_EXPORT_PRIVATE ProfilerListener : public CodeEventListener,
Handle<String> source) override;
void CodeMoveEvent(AbstractCode from, AbstractCode to) override;
void SharedFunctionInfoMoveEvent(Address from, Address to) override {}
void NativeContextMoveEvent(Address from, Address to) override;
void CodeMovingGCEvent() override {}
void CodeDisableOptEvent(Handle<AbstractCode> code,
Handle<SharedFunctionInfo> shared) override;
-9
View File
@@ -177,7 +177,6 @@ DISABLE_ASAN void TickSample::Init(Isolate* v8_isolate,
pc = regs.pc;
frames_count = static_cast<unsigned>(info.frames_count);
has_external_callback = info.external_callback_entry != nullptr;
context = info.context;
if (has_external_callback) {
external_callback_entry = info.external_callback_entry;
} else if (frames_count) {
@@ -210,7 +209,6 @@ bool TickSample::GetStackSample(Isolate* v8_isolate, RegisterState* regs,
sample_info->frames_count = 0;
sample_info->vm_state = isolate->current_vm_state();
sample_info->external_callback_entry = nullptr;
sample_info->context = nullptr;
if (sample_info->vm_state == GC) return true;
i::Address js_entry_sp = isolate->js_entry_sp();
@@ -280,13 +278,6 @@ bool TickSample::GetStackSample(Isolate* v8_isolate, RegisterState* regs,
reinterpret_cast<i::Address>(regs->lr),
js_entry_sp);
Context top_context = isolate->context();
if (top_context.ptr() != i::Context::kNoContext &&
top_context.ptr() != i::Context::kInvalidContext) {
NativeContext top_native_context = top_context.native_context();
sample_info->context = reinterpret_cast<void*>(top_native_context.ptr());
}
if (it.done()) return true;
size_t i = 0;
-1
View File
@@ -90,7 +90,6 @@ struct V8_EXPORT TickSample {
static const unsigned kMaxFramesCountLog2 = 8;
static const unsigned kMaxFramesCount = (1 << kMaxFramesCountLog2) - 1;
void* stack[kMaxFramesCount]; // Call stack.
void* context = nullptr; // Address of the incumbent native context.
unsigned frames_count : kMaxFramesCountLog2; // Number of captured frames.
bool has_external_callback : 1;
bool update_stats : 1; // Whether the sample should update aggregated stats.
-1
View File
@@ -1393,7 +1393,6 @@ RUNTIME_FUNCTION(Runtime_EnableCodeLoggingForTesting) {
Handle<String> source) final {}
void CodeMoveEvent(AbstractCode from, AbstractCode to) final {}
void SharedFunctionInfoMoveEvent(Address from, Address to) final {}
void NativeContextMoveEvent(Address from, Address to) final {}
void CodeMovingGCEvent() final {}
void CodeDisableOptEvent(Handle<AbstractCode> code,
Handle<SharedFunctionInfo> shared) final {}
+98 -206
View File
@@ -6,13 +6,10 @@
#include <memory>
#include "src/base/logging.h"
#include "src/base/platform/elapsed-timer.h"
#include "src/base/platform/platform.h"
#include "src/codegen/macro-assembler.h"
#include "src/common/globals.h"
#include "src/debug/debug.h"
#include "src/handles/maybe-handles.h"
#include "src/handles/persistent-handles.h"
#include "src/heap/heap-inl.h"
#include "src/heap/local-factory-inl.h"
@@ -21,7 +18,6 @@
#include "src/logging/log.h"
#include "src/logging/runtime-call-stats-scope.h"
#include "src/objects/objects-inl.h"
#include "src/objects/shared-function-info.h"
#include "src/objects/slots.h"
#include "src/objects/visitors.h"
#include "src/snapshot/object-deserializer.h"
@@ -32,7 +28,7 @@
namespace v8 {
namespace internal {
AlignedCachedData::AlignedCachedData(const byte* data, int length)
ScriptData::ScriptData(const byte* data, int length)
: owns_data_(false), rejected_(false), data_(data), length_(length) {
if (!IsAligned(reinterpret_cast<intptr_t>(data), kPointerAlignment)) {
byte* copy = NewArray<byte>(length);
@@ -78,24 +74,24 @@ ScriptCompiler::CachedData* CodeSerializer::Serialize(
source, script->origin_options()));
DisallowGarbageCollection no_gc;
cs.reference_map()->AddAttachedReference(*source);
AlignedCachedData* cached_data = cs.SerializeSharedFunctionInfo(info);
ScriptData* script_data = cs.SerializeSharedFunctionInfo(info);
if (FLAG_profile_deserialization) {
double ms = timer.Elapsed().InMillisecondsF();
int length = cached_data->length();
int length = script_data->length();
PrintF("[Serializing to %d bytes took %0.3f ms]\n", length, ms);
}
ScriptCompiler::CachedData* result =
new ScriptCompiler::CachedData(cached_data->data(), cached_data->length(),
new ScriptCompiler::CachedData(script_data->data(), script_data->length(),
ScriptCompiler::CachedData::BufferOwned);
cached_data->ReleaseDataOwnership();
delete cached_data;
script_data->ReleaseDataOwnership();
delete script_data;
return result;
}
AlignedCachedData* CodeSerializer::SerializeSharedFunctionInfo(
ScriptData* CodeSerializer::SerializeSharedFunctionInfo(
Handle<SharedFunctionInfo> info) {
DisallowGarbageCollection no_gc;
@@ -231,8 +227,6 @@ void CodeSerializer::SerializeGeneric(Handle<HeapObject> heap_object) {
serializer.Serialize();
}
namespace {
#ifndef V8_TARGET_ARCH_ARM
// NOTE(mmarchini): when FLAG_interpreted_frames_native_stack is on, we want to
// create duplicates of InterpreterEntryTrampoline for the deserialized
@@ -274,40 +268,110 @@ void CreateInterpreterDataForDeserializedCode(Isolate* isolate,
}
#endif // V8_TARGET_ARCH_ARM
namespace {
class StressOffThreadDeserializeThread final : public base::Thread {
public:
explicit StressOffThreadDeserializeThread(Isolate* isolate,
AlignedCachedData* cached_data)
const SerializedCodeData* scd)
: Thread(
base::Thread::Options("StressOffThreadDeserializeThread", 2 * MB)),
isolate_(isolate),
cached_data_(cached_data) {}
scd_(scd) {}
MaybeHandle<SharedFunctionInfo> maybe_result() const { return maybe_result_; }
void Run() final {
LocalIsolate local_isolate(isolate_, ThreadKind::kBackground);
UnparkedScope unparked_scope(&local_isolate);
LocalHandleScope handle_scope(&local_isolate);
off_thread_data_ =
CodeSerializer::StartDeserializeOffThread(&local_isolate, cached_data_);
MaybeHandle<SharedFunctionInfo> local_maybe_result =
OffThreadObjectDeserializer::DeserializeSharedFunctionInfo(
&local_isolate, scd_, &scripts_);
maybe_result_ =
local_isolate.heap()->NewPersistentMaybeHandle(local_maybe_result);
persistent_handles_ = local_isolate.heap()->DetachPersistentHandles();
}
MaybeHandle<SharedFunctionInfo> Finalize(Isolate* isolate,
Handle<String> source,
ScriptOriginOptions origin_options) {
return CodeSerializer::FinishOffThreadDeserialize(
isolate, std::move(off_thread_data_), cached_data_, source,
origin_options);
void Finalize(Isolate* isolate) {
Handle<WeakArrayList> list = isolate->factory()->script_list();
for (Handle<Script> script : scripts_) {
DCHECK(persistent_handles_->Contains(script.location()));
list = WeakArrayList::AddToEnd(isolate, list,
MaybeObjectHandle::Weak(script));
}
isolate->heap()->SetRootScriptList(*list);
Handle<SharedFunctionInfo> result;
if (maybe_result_.ToHandle(&result)) {
maybe_result_ = handle(*result, isolate);
}
}
private:
Isolate* isolate_;
AlignedCachedData* cached_data_;
CodeSerializer::OffThreadDeserializeData off_thread_data_;
const SerializedCodeData* scd_;
MaybeHandle<SharedFunctionInfo> maybe_result_;
std::vector<Handle<Script>> scripts_;
std::unique_ptr<PersistentHandles> persistent_handles_;
};
} // namespace
MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
Isolate* isolate, ScriptData* cached_data, Handle<String> source,
ScriptOriginOptions origin_options) {
base::ElapsedTimer timer;
if (FLAG_profile_deserialization || FLAG_log_function_events) timer.Start();
HandleScope scope(isolate);
SerializedCodeData::SanityCheckResult sanity_check_result =
SerializedCodeData::CHECK_SUCCESS;
const SerializedCodeData scd = SerializedCodeData::FromCachedData(
cached_data, SerializedCodeData::SourceHash(source, origin_options),
&sanity_check_result);
if (sanity_check_result != SerializedCodeData::CHECK_SUCCESS) {
if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
DCHECK(cached_data->rejected());
isolate->counters()->code_cache_reject_reason()->AddSample(
sanity_check_result);
return MaybeHandle<SharedFunctionInfo>();
}
// Deserialize.
MaybeHandle<SharedFunctionInfo> maybe_result;
if (FLAG_stress_background_compile) {
StressOffThreadDeserializeThread thread(isolate, &scd);
CHECK(thread.Start());
thread.Join();
thread.Finalize(isolate);
maybe_result = thread.maybe_result();
// Fix-up result script source.
Handle<SharedFunctionInfo> result;
if (maybe_result.ToHandle(&result)) {
Script::cast(result->script()).set_source(*source);
}
} else {
maybe_result = ObjectDeserializer::DeserializeSharedFunctionInfo(
isolate, &scd, source);
}
Handle<SharedFunctionInfo> result;
if (!maybe_result.ToHandle(&result)) {
// Deserializing may fail if the reservations cannot be fulfilled.
if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
return MaybeHandle<SharedFunctionInfo>();
}
if (FLAG_profile_deserialization) {
double ms = timer.Elapsed().InMillisecondsF();
int length = cached_data->length();
PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
}
void FinalizeDeserialization(Isolate* isolate,
Handle<SharedFunctionInfo> result,
const base::ElapsedTimer& timer) {
const bool log_code_creation =
isolate->logger()->is_listening_to_code_events() ||
isolate->is_profiling() ||
@@ -367,159 +431,6 @@ void FinalizeDeserialization(Isolate* isolate,
Handle<Script> script(Script::cast(result->script()), isolate);
Script::InitLineEnds(isolate, script);
}
}
} // namespace
MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
Isolate* isolate, AlignedCachedData* cached_data, Handle<String> source,
ScriptOriginOptions origin_options) {
if (FLAG_stress_background_compile) {
StressOffThreadDeserializeThread thread(isolate, cached_data);
CHECK(thread.Start());
thread.Join();
return thread.Finalize(isolate, source, origin_options);
// TODO(leszeks): Compare off-thread deserialized data to on-thread.
}
base::ElapsedTimer timer;
if (FLAG_profile_deserialization || FLAG_log_function_events) timer.Start();
HandleScope scope(isolate);
SerializedCodeData::SanityCheckResult sanity_check_result =
SerializedCodeData::CHECK_SUCCESS;
const SerializedCodeData scd = SerializedCodeData::FromCachedData(
cached_data, SerializedCodeData::SourceHash(source, origin_options),
&sanity_check_result);
if (sanity_check_result != SerializedCodeData::CHECK_SUCCESS) {
if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
DCHECK(cached_data->rejected());
isolate->counters()->code_cache_reject_reason()->AddSample(
sanity_check_result);
return MaybeHandle<SharedFunctionInfo>();
}
// Deserialize.
MaybeHandle<SharedFunctionInfo> maybe_result =
ObjectDeserializer::DeserializeSharedFunctionInfo(isolate, &scd, source);
Handle<SharedFunctionInfo> result;
if (!maybe_result.ToHandle(&result)) {
// Deserializing may fail if the reservations cannot be fulfilled.
if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
return MaybeHandle<SharedFunctionInfo>();
}
if (FLAG_profile_deserialization) {
double ms = timer.Elapsed().InMillisecondsF();
int length = cached_data->length();
PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
}
FinalizeDeserialization(isolate, result, timer);
return scope.CloseAndEscape(result);
}
CodeSerializer::OffThreadDeserializeData
CodeSerializer::StartDeserializeOffThread(LocalIsolate* local_isolate,
AlignedCachedData* cached_data) {
OffThreadDeserializeData result;
DCHECK(!local_isolate->heap()->HasPersistentHandles());
SerializedCodeData::SanityCheckResult sanity_check_result =
SerializedCodeData::CHECK_SUCCESS;
const SerializedCodeData scd =
SerializedCodeData::FromCachedDataWithoutSource(cached_data,
&sanity_check_result);
if (sanity_check_result != SerializedCodeData::CHECK_SUCCESS) {
// Exit early but don't report yet, we'll re-check this when finishing on
// the main thread
DCHECK(cached_data->rejected());
return result;
}
MaybeHandle<SharedFunctionInfo> local_maybe_result =
OffThreadObjectDeserializer::DeserializeSharedFunctionInfo(
local_isolate, &scd, &result.scripts);
result.maybe_result =
local_isolate->heap()->NewPersistentMaybeHandle(local_maybe_result);
result.persistent_handles = local_isolate->heap()->DetachPersistentHandles();
return result;
}
MaybeHandle<SharedFunctionInfo> CodeSerializer::FinishOffThreadDeserialize(
Isolate* isolate, OffThreadDeserializeData&& data,
AlignedCachedData* cached_data, Handle<String> source,
ScriptOriginOptions origin_options) {
base::ElapsedTimer timer;
if (FLAG_profile_deserialization || FLAG_log_function_events) timer.Start();
HandleScope scope(isolate);
// Check again now that we have the source.
SerializedCodeData::SanityCheckResult sanity_check_result =
SerializedCodeData::CHECK_SUCCESS;
const SerializedCodeData scd = SerializedCodeData::FromCachedData(
cached_data, SerializedCodeData::SourceHash(source, origin_options),
&sanity_check_result);
if (sanity_check_result != SerializedCodeData::CHECK_SUCCESS) {
// The only case where the deserialization result could exist despite a
// check failure is on a source mismatch, since we can't test for this
// off-thread.
DCHECK_IMPLIES(!data.maybe_result.is_null(),
sanity_check_result == SerializedCodeData::SOURCE_MISMATCH);
if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
DCHECK(cached_data->rejected());
isolate->counters()->code_cache_reject_reason()->AddSample(
sanity_check_result);
return MaybeHandle<SharedFunctionInfo>();
}
Handle<SharedFunctionInfo> result;
if (!data.maybe_result.ToHandle(&result)) {
// Deserializing may fail if the reservations cannot be fulfilled.
if (FLAG_profile_deserialization) {
PrintF("[Off-thread deserializing failed]\n");
}
return MaybeHandle<SharedFunctionInfo>();
}
// Change the result persistent handle into a regular handle.
DCHECK(data.persistent_handles->Contains(result.location()));
result = handle(*result, isolate);
// Fix up the source on the script. This should be the only deserialized
// script, and the off-thread deserializer should have set its source to
// the empty string.
DCHECK_EQ(data.scripts.size(), 1);
DCHECK_EQ(result->script(), *data.scripts[0]);
DCHECK_EQ(Script::cast(result->script()).source(),
ReadOnlyRoots(isolate).empty_string());
Script::cast(result->script()).set_source(*source);
// Fix up the script list to include the newly deserialized script.
Handle<WeakArrayList> list = isolate->factory()->script_list();
for (Handle<Script> script : data.scripts) {
DCHECK(data.persistent_handles->Contains(script.location()));
list =
WeakArrayList::AddToEnd(isolate, list, MaybeObjectHandle::Weak(script));
}
isolate->heap()->SetRootScriptList(*list);
if (FLAG_profile_deserialization) {
double ms = timer.Elapsed().InMillisecondsF();
int length = cached_data->length();
PrintF("[Finishing off-thread deserialize from %d bytes took %0.3f ms]\n",
length, ms);
}
FinalizeDeserialization(isolate, result, timer);
return scope.CloseAndEscape(result);
}
@@ -556,23 +467,16 @@ SerializedCodeData::SerializedCodeData(const std::vector<byte>* payload,
SerializedCodeData::SanityCheckResult SerializedCodeData::SanityCheck(
uint32_t expected_source_hash) const {
SanityCheckResult result = SanityCheckWithoutSource();
if (result != CHECK_SUCCESS) return result;
uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
if (source_hash != expected_source_hash) return SOURCE_MISMATCH;
return CHECK_SUCCESS;
}
SerializedCodeData::SanityCheckResult
SerializedCodeData::SanityCheckWithoutSource() const {
if (this->size_ < kHeaderSize) return INVALID_HEADER;
uint32_t magic_number = GetMagicNumber();
if (magic_number != kMagicNumber) return MAGIC_NUMBER_MISMATCH;
uint32_t version_hash = GetHeaderValue(kVersionHashOffset);
uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
uint32_t flags_hash = GetHeaderValue(kFlagHashOffset);
uint32_t payload_length = GetHeaderValue(kPayloadLengthOffset);
uint32_t c = GetHeaderValue(kChecksumOffset);
if (version_hash != Version::Hash()) return VERSION_MISMATCH;
if (source_hash != expected_source_hash) return SOURCE_MISMATCH;
if (flags_hash != FlagList::Hash()) return FLAGS_MISMATCH;
uint32_t max_payload_length = this->size_ - kHeaderSize;
if (payload_length > max_payload_length) return LENGTH_MISMATCH;
@@ -592,9 +496,9 @@ uint32_t SerializedCodeData::SourceHash(Handle<String> source,
}
// Return ScriptData object and relinquish ownership over it to the caller.
AlignedCachedData* SerializedCodeData::GetScriptData() {
ScriptData* SerializedCodeData::GetScriptData() {
DCHECK(owns_data_);
AlignedCachedData* result = new AlignedCachedData(data_, size_);
ScriptData* result = new ScriptData(data_, size_);
result->AcquireDataOwnership();
owns_data_ = false;
data_ = nullptr;
@@ -609,11 +513,11 @@ base::Vector<const byte> SerializedCodeData::Payload() const {
return base::Vector<const byte>(payload, length);
}
SerializedCodeData::SerializedCodeData(AlignedCachedData* data)
SerializedCodeData::SerializedCodeData(ScriptData* data)
: SerializedData(const_cast<byte*>(data->data()), data->length()) {}
SerializedCodeData SerializedCodeData::FromCachedData(
AlignedCachedData* cached_data, uint32_t expected_source_hash,
ScriptData* cached_data, uint32_t expected_source_hash,
SanityCheckResult* rejection_result) {
DisallowGarbageCollection no_gc;
SerializedCodeData scd(cached_data);
@@ -625,17 +529,5 @@ SerializedCodeData SerializedCodeData::FromCachedData(
return scd;
}
SerializedCodeData SerializedCodeData::FromCachedDataWithoutSource(
AlignedCachedData* cached_data, SanityCheckResult* rejection_result) {
DisallowGarbageCollection no_gc;
SerializedCodeData scd(cached_data);
*rejection_result = scd.SanityCheckWithoutSource();
if (*rejection_result != CHECK_SUCCESS) {
cached_data->Reject();
return SerializedCodeData(nullptr, 0);
}
return scd;
}
} // namespace internal
} // namespace v8
+10 -36
View File
@@ -12,16 +12,14 @@
namespace v8 {
namespace internal {
class PersistentHandles;
class V8_EXPORT_PRIVATE AlignedCachedData {
class V8_EXPORT_PRIVATE ScriptData {
public:
AlignedCachedData(const byte* data, int length);
~AlignedCachedData() {
ScriptData(const byte* data, int length);
~ScriptData() {
if (owns_data_) DeleteArray(data_);
}
AlignedCachedData(const AlignedCachedData&) = delete;
AlignedCachedData& operator=(const AlignedCachedData&) = delete;
ScriptData(const ScriptData&) = delete;
ScriptData& operator=(const ScriptData&) = delete;
const byte* data() const { return data_; }
int length() const { return length_; }
@@ -29,8 +27,6 @@ class V8_EXPORT_PRIVATE AlignedCachedData {
void Reject() { rejected_ = true; }
bool HasDataOwnership() const { return owns_data_; }
void AcquireDataOwnership() {
DCHECK(!owns_data_);
owns_data_ = true;
@@ -50,36 +46,17 @@ class V8_EXPORT_PRIVATE AlignedCachedData {
class CodeSerializer : public Serializer {
public:
struct OffThreadDeserializeData {
private:
friend class CodeSerializer;
MaybeHandle<SharedFunctionInfo> maybe_result;
std::vector<Handle<Script>> scripts;
std::unique_ptr<PersistentHandles> persistent_handles;
};
CodeSerializer(const CodeSerializer&) = delete;
CodeSerializer& operator=(const CodeSerializer&) = delete;
V8_EXPORT_PRIVATE static ScriptCompiler::CachedData* Serialize(
Handle<SharedFunctionInfo> info);
AlignedCachedData* SerializeSharedFunctionInfo(
Handle<SharedFunctionInfo> info);
ScriptData* SerializeSharedFunctionInfo(Handle<SharedFunctionInfo> info);
V8_WARN_UNUSED_RESULT static MaybeHandle<SharedFunctionInfo> Deserialize(
Isolate* isolate, AlignedCachedData* cached_data, Handle<String> source,
Isolate* isolate, ScriptData* cached_data, Handle<String> source,
ScriptOriginOptions origin_options);
V8_WARN_UNUSED_RESULT static OffThreadDeserializeData
StartDeserializeOffThread(LocalIsolate* isolate,
AlignedCachedData* cached_data);
V8_WARN_UNUSED_RESULT static MaybeHandle<SharedFunctionInfo>
FinishOffThreadDeserialize(Isolate* isolate, OffThreadDeserializeData&& data,
AlignedCachedData* cached_data,
Handle<String> source,
ScriptOriginOptions origin_options);
uint32_t source_hash() const { return source_hash_; }
protected:
@@ -129,18 +106,16 @@ class SerializedCodeData : public SerializedData {
static const uint32_t kHeaderSize = POINTER_SIZE_ALIGN(kUnalignedHeaderSize);
// Used when consuming.
static SerializedCodeData FromCachedData(AlignedCachedData* cached_data,
static SerializedCodeData FromCachedData(ScriptData* cached_data,
uint32_t expected_source_hash,
SanityCheckResult* rejection_result);
static SerializedCodeData FromCachedDataWithoutSource(
AlignedCachedData* cached_data, SanityCheckResult* rejection_result);
// Used when producing.
SerializedCodeData(const std::vector<byte>* payload,
const CodeSerializer* cs);
// Return ScriptData object and relinquish ownership over it to the caller.
AlignedCachedData* GetScriptData();
ScriptData* GetScriptData();
base::Vector<const byte> Payload() const;
@@ -148,7 +123,7 @@ class SerializedCodeData : public SerializedData {
ScriptOriginOptions origin_options);
private:
explicit SerializedCodeData(AlignedCachedData* data);
explicit SerializedCodeData(ScriptData* data);
SerializedCodeData(const byte* data, int size)
: SerializedData(const_cast<byte*>(data), size) {}
@@ -157,7 +132,6 @@ class SerializedCodeData : public SerializedData {
}
SanityCheckResult SanityCheck(uint32_t expected_source_hash) const;
SanityCheckResult SanityCheckWithoutSource() const;
};
} // namespace internal
-2
View File
@@ -3535,8 +3535,6 @@ void CompilationStateImpl::WaitForCompilationEvent(
return done_->load(std::memory_order_relaxed);
}
bool IsJoiningThread() const override { return true; }
void NotifyConcurrencyIncrease() override { UNIMPLEMENTED(); }
uint8_t GetTaskId() override { return kMainTaskId; }
+2 -4
View File
@@ -414,9 +414,7 @@ int RegisterThreadedTest::count_ = 0;
bool IsValidUnwrapObject(v8::Object* object) {
i::Address addr = *reinterpret_cast<i::Address*>(object);
auto instance_type = i::Internals::GetInstanceType(addr);
return (v8::base::IsInRange(instance_type,
i::Internals::kFirstJSApiObjectType,
i::Internals::kLastJSApiObjectType) ||
instance_type == i::Internals::kJSObjectType ||
return (instance_type == i::Internals::kJSObjectType ||
instance_type == i::Internals::kJSApiObjectType ||
instance_type == i::Internals::kJSSpecialApiObjectType);
}
+6 -73
View File
@@ -7295,18 +7295,6 @@ TEST(Regress10900) {
CcTest::CollectAllAvailableGarbage();
}
namespace {
void GenerateGarbage() {
const char* source =
"let roots = [];"
"for (let i = 0; i < 100; i++) roots.push(new Array(1000).fill(0));"
"roots.push(new Array(1000000).fill(0));"
"roots;";
CompileRun(source);
}
} // anonymous namespace
TEST(Regress11181) {
FLAG_always_compact = true;
CcTest::InitializeVM();
@@ -7314,71 +7302,16 @@ TEST(Regress11181) {
v8::tracing::TracingCategoryObserver::ENABLED_BY_NATIVE,
std::memory_order_relaxed);
v8::HandleScope scope(CcTest::isolate());
GenerateGarbage();
const char* source =
"let roots = [];"
"for (let i = 0; i < 100; i++) roots.push(new Array(1000).fill(0));"
"roots.push(new Array(1000000).fill(0));"
"roots;";
CompileRun(source);
CcTest::CollectAllAvailableGarbage();
TracingFlags::runtime_stats.store(0, std::memory_order_relaxed);
}
TEST(LongTaskStatsFullAtomic) {
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(CcTest::isolate());
GenerateGarbage();
v8::metrics::LongTaskStats::Reset(isolate);
CHECK_EQ(0u, v8::metrics::LongTaskStats::Get(isolate)
.gc_full_atomic_wall_clock_duration_us);
for (int i = 0; i < 10; ++i) {
CcTest::CollectAllAvailableGarbage();
}
CHECK_LT(0u, v8::metrics::LongTaskStats::Get(isolate)
.gc_full_atomic_wall_clock_duration_us);
v8::metrics::LongTaskStats::Reset(isolate);
CHECK_EQ(0u, v8::metrics::LongTaskStats::Get(isolate)
.gc_full_atomic_wall_clock_duration_us);
}
TEST(LongTaskStatsFullIncremental) {
if (!FLAG_incremental_marking) return;
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(CcTest::isolate());
GenerateGarbage();
v8::metrics::LongTaskStats::Reset(isolate);
CHECK_EQ(0u, v8::metrics::LongTaskStats::Get(isolate)
.gc_full_incremental_wall_clock_duration_us);
for (int i = 0; i < 10; ++i) {
heap::SimulateIncrementalMarking(CcTest::heap());
CcTest::CollectAllAvailableGarbage();
}
CHECK_LT(0u, v8::metrics::LongTaskStats::Get(isolate)
.gc_full_incremental_wall_clock_duration_us);
v8::metrics::LongTaskStats::Reset(isolate);
CHECK_EQ(0u, v8::metrics::LongTaskStats::Get(isolate)
.gc_full_incremental_wall_clock_duration_us);
}
TEST(LongTaskStatsYoung) {
if (FLAG_single_generation) return;
CcTest::InitializeVM();
v8::Isolate* isolate = CcTest::isolate();
v8::HandleScope scope(CcTest::isolate());
GenerateGarbage();
v8::metrics::LongTaskStats::Reset(isolate);
CHECK_EQ(
0u,
v8::metrics::LongTaskStats::Get(isolate).gc_young_wall_clock_duration_us);
for (int i = 0; i < 10; ++i) {
CcTest::CollectGarbage(NEW_SPACE);
}
CHECK_LT(
0u,
v8::metrics::LongTaskStats::Get(isolate).gc_young_wall_clock_duration_us);
v8::metrics::LongTaskStats::Reset(isolate);
CHECK_EQ(
0u,
v8::metrics::LongTaskStats::Get(isolate).gc_young_wall_clock_duration_us);
}
} // namespace heap
} // namespace internal
} // namespace v8
+181 -8
View File
@@ -48,11 +48,31 @@ Local<TypedArray> CreateAndCheck(Local<v8::ArrayBuffer> ab, int byteOffset,
std::shared_ptr<v8::BackingStore> Externalize(Local<v8::ArrayBuffer> ab) {
std::shared_ptr<v8::BackingStore> backing_store = ab->GetBackingStore();
// Keep the tests until the deprecated functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
ab->Externalize(backing_store);
CHECK(ab->IsExternal());
#if __clang__
#pragma clang diagnostic pop
#endif
return backing_store;
}
std::shared_ptr<v8::BackingStore> Externalize(Local<v8::SharedArrayBuffer> ab) {
std::shared_ptr<v8::BackingStore> backing_store = ab->GetBackingStore();
// Keep the tests until the deprecated functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
ab->Externalize(backing_store);
CHECK(ab->IsExternal());
#if __clang__
#pragma clang diagnostic pop
#endif
return backing_store;
}
@@ -131,6 +151,46 @@ THREADED_TEST(ArrayBuffer_JSInternalToExternal) {
CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}
THREADED_TEST(ArrayBuffer_External) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::base::ScopedVector<uint8_t> my_data(100);
memset(my_data.begin(), 0, 100);
// Keep the tests until the deprecated functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
Local<v8::ArrayBuffer> ab3 =
v8::ArrayBuffer::New(isolate, my_data.begin(), 100);
CheckInternalFieldsAreZero(ab3);
CHECK_EQ(100, ab3->ByteLength());
CHECK(ab3->IsExternal());
#if __clang__
#pragma clang diagnostic pop
#endif
CHECK(env->Global()->Set(env.local(), v8_str("ab3"), ab3).FromJust());
v8::Local<v8::Value> result = CompileRun("ab3.byteLength");
CHECK_EQ(100, result->Int32Value(env.local()).FromJust());
result = CompileRun(
"var u8_b = new Uint8Array(ab3);"
"u8_b[0] = 0xBB;"
"u8_b[1] = 0xCC;"
"u8_b.length");
CHECK_EQ(100, result->Int32Value(env.local()).FromJust());
CHECK_EQ(0xBB, my_data[0]);
CHECK_EQ(0xCC, my_data[1]);
my_data[0] = 0xCC;
my_data[1] = 0x11;
result = CompileRun("u8_b[0] + u8_b[1]");
CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}
THREADED_TEST(ArrayBuffer_DisableDetach) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
@@ -234,6 +294,37 @@ THREADED_TEST(ArrayBuffer_DetachingScript) {
CheckDataViewIsDetached(dv);
}
// TODO(v8:9380) the Contents data structure should be deprecated.
THREADED_TEST(ArrayBuffer_AllocationInformation) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
const size_t ab_size = 1024;
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, ab_size);
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
v8::ArrayBuffer::Contents contents(ab->GetContents());
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
// Array buffers should have normal allocation mode.
CHECK_EQ(contents.AllocationMode(),
v8::ArrayBuffer::Allocator::AllocationMode::kNormal);
// The allocation must contain the buffer (normally they will be equal, but
// this is not required by the contract).
CHECK_NOT_NULL(contents.AllocationBase());
const uintptr_t alloc =
reinterpret_cast<uintptr_t>(contents.AllocationBase());
const uintptr_t data = reinterpret_cast<uintptr_t>(contents.Data());
CHECK_LE(alloc, data);
CHECK_LE(data + contents.ByteLength(), alloc + contents.AllocationLength());
}
THREADED_TEST(ArrayBuffer_ExternalizeEmpty) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
@@ -252,6 +343,7 @@ THREADED_TEST(ArrayBuffer_ExternalizeEmpty) {
// marked as is_external or not.
USE(u8a->Buffer());
CHECK(ab->IsExternal());
CHECK_EQ(2, backing_store->ByteLength());
}
@@ -290,6 +382,35 @@ THREADED_TEST(SharedArrayBuffer_ApiInternalToExternal) {
CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}
THREADED_TEST(ArrayBuffer_ExternalReused) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::base::ScopedVector<uint8_t> data(100);
Local<v8::ArrayBuffer> ab1 = v8::ArrayBuffer::New(isolate, data.begin(), 100);
std::shared_ptr<v8::BackingStore> bs1 = ab1->GetBackingStore();
ab1->Detach();
Local<v8::ArrayBuffer> ab2 = v8::ArrayBuffer::New(isolate, data.begin(), 100);
std::shared_ptr<v8::BackingStore> bs2 = ab2->GetBackingStore();
CHECK_EQ(bs1->Data(), bs2->Data());
}
THREADED_TEST(SharedArrayBuffer_ExternalReused) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::base::ScopedVector<uint8_t> data(100);
Local<v8::SharedArrayBuffer> ab1 =
v8::SharedArrayBuffer::New(isolate, data.begin(), 100);
std::shared_ptr<v8::BackingStore> bs1 = ab1->GetBackingStore();
Local<v8::SharedArrayBuffer> ab2 =
v8::SharedArrayBuffer::New(isolate, data.begin(), 100);
std::shared_ptr<v8::BackingStore> bs2 = ab2->GetBackingStore();
CHECK_EQ(bs1->Data(), bs2->Data());
}
THREADED_TEST(SharedArrayBuffer_JSInternalToExternal) {
i::FLAG_harmony_sharedarraybuffer = true;
LocalContext env;
@@ -331,6 +452,64 @@ THREADED_TEST(SharedArrayBuffer_JSInternalToExternal) {
CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}
THREADED_TEST(SharedArrayBuffer_External) {
i::FLAG_harmony_sharedarraybuffer = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
v8::base::ScopedVector<uint8_t> my_data(100);
memset(my_data.begin(), 0, 100);
Local<v8::SharedArrayBuffer> ab3 =
v8::SharedArrayBuffer::New(isolate, my_data.begin(), 100);
CheckInternalFieldsAreZero(ab3);
CHECK_EQ(100, static_cast<int>(ab3->ByteLength()));
CHECK(ab3->IsExternal());
CHECK(env->Global()->Set(env.local(), v8_str("ab3"), ab3).FromJust());
v8::Local<v8::Value> result = CompileRun("ab3.byteLength");
CHECK_EQ(100, result->Int32Value(env.local()).FromJust());
result = CompileRun(
"var u8_b = new Uint8Array(ab3);"
"u8_b[0] = 0xBB;"
"u8_b[1] = 0xCC;"
"u8_b.length");
CHECK_EQ(100, result->Int32Value(env.local()).FromJust());
CHECK_EQ(0xBB, my_data[0]);
CHECK_EQ(0xCC, my_data[1]);
my_data[0] = 0xCC;
my_data[1] = 0x11;
result = CompileRun("u8_b[0] + u8_b[1]");
CHECK_EQ(0xDD, result->Int32Value(env.local()).FromJust());
}
// TODO(v8:9380) the Contents data structure should be deprecated.
THREADED_TEST(SharedArrayBuffer_AllocationInformation) {
i::FLAG_harmony_sharedarraybuffer = true;
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope handle_scope(isolate);
const size_t ab_size = 1024;
Local<v8::SharedArrayBuffer> ab =
v8::SharedArrayBuffer::New(isolate, ab_size);
v8::SharedArrayBuffer::Contents contents(ab->GetContents());
// Array buffers should have normal allocation mode.
CHECK_EQ(contents.AllocationMode(),
v8::ArrayBuffer::Allocator::AllocationMode::kNormal);
// The allocation must contain the buffer (normally they will be equal, but
// this is not required by the contract).
CHECK_NOT_NULL(contents.AllocationBase());
const uintptr_t alloc =
reinterpret_cast<uintptr_t>(contents.AllocationBase());
const uintptr_t data = reinterpret_cast<uintptr_t>(contents.Data());
CHECK_LE(alloc, data);
CHECK_LE(data + contents.ByteLength(), alloc + contents.AllocationLength());
}
THREADED_TEST(SkipArrayBufferBackingStoreDuringGC) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
@@ -338,12 +517,9 @@ THREADED_TEST(SkipArrayBufferBackingStoreDuringGC) {
// Make sure the pointer looks like a heap object
uint8_t* store_ptr = reinterpret_cast<uint8_t*>(i::kHeapObjectTag);
auto backing_store = v8::ArrayBuffer::NewBackingStore(
store_ptr, 8, [](void*, size_t, void*) {}, nullptr);
// Create ArrayBuffer with pointer-that-cannot-be-visited in the backing store
Local<v8::ArrayBuffer> ab =
v8::ArrayBuffer::New(isolate, std::move(backing_store));
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, store_ptr, 8);
// Should not crash
CcTest::CollectGarbage(i::NEW_SPACE); // in survivor space now
@@ -364,15 +540,12 @@ THREADED_TEST(SkipArrayBufferDuringScavenge) {
Local<v8::Object> tmp = v8::Object::New(isolate);
uint8_t* store_ptr =
reinterpret_cast<uint8_t*>(*reinterpret_cast<uintptr_t*>(*tmp));
auto backing_store = v8::ArrayBuffer::NewBackingStore(
store_ptr, 8, [](void*, size_t, void*) {}, nullptr);
// Make `store_ptr` point to from space
CcTest::CollectGarbage(i::NEW_SPACE);
// Create ArrayBuffer with pointer-that-cannot-be-visited in the backing store
Local<v8::ArrayBuffer> ab =
v8::ArrayBuffer::New(isolate, std::move(backing_store));
Local<v8::ArrayBuffer> ab = v8::ArrayBuffer::New(isolate, store_ptr, 8);
// Should not crash,
// i.e. backing store pointer should not be treated as a heap object pointer
-54
View File
@@ -29312,57 +29312,3 @@ TEST(TestSetSabConstructorEnabledCallback) {
sab_constructor_enabled_value = true;
CHECK(i_isolate->IsSharedArrayBufferConstructorEnabled(i_context));
}
namespace {
void NodeTypeCallback(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::Number::New(isolate, 1));
}
} // namespace
TEST(EmbedderInstanceTypes) {
LocalContext env;
v8::Isolate* isolate = env->GetIsolate();
v8::HandleScope scope(isolate);
i::FLAG_embedder_instance_types = true;
Local<FunctionTemplate> node = FunctionTemplate::New(isolate);
Local<ObjectTemplate> proto_template = node->PrototypeTemplate();
Local<FunctionTemplate> nodeType = v8::FunctionTemplate::New(
isolate, NodeTypeCallback, Local<Value>(),
v8::Signature::New(isolate, node), 0, v8::ConstructorBehavior::kThrow,
v8::SideEffectType::kHasSideEffect, nullptr, 0, 1, 3);
proto_template->SetAccessorProperty(
String::NewFromUtf8Literal(isolate, "nodeType"), nodeType);
Local<FunctionTemplate> element = FunctionTemplate::New(
isolate, nullptr, Local<Value>(), Local<v8::Signature>(), 0,
v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasSideEffect,
nullptr, 1);
element->Inherit(node);
Local<FunctionTemplate> html_element = FunctionTemplate::New(
isolate, nullptr, Local<Value>(), Local<v8::Signature>(), 0,
v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasSideEffect,
nullptr, 2);
html_element->Inherit(element);
Local<FunctionTemplate> div_element = FunctionTemplate::New(
isolate, nullptr, Local<Value>(), Local<v8::Signature>(), 0,
v8::ConstructorBehavior::kAllow, v8::SideEffectType::kHasSideEffect,
nullptr, 3);
div_element->Inherit(html_element);
CHECK(env->Global()
->Set(env.local(), v8_str("div"),
div_element->GetFunction(env.local())
.ToLocalChecked()
->NewInstance(env.local())
.ToLocalChecked())
.FromJust());
CompileRun("var x = div.nodeType;");
Local<Value> res =
env->Global()->Get(env.local(), v8_str("x")).ToLocalChecked();
CHECK_EQ(1, res->ToInt32(env.local()).ToLocalChecked()->Value());
}
+3 -140
View File
@@ -551,8 +551,7 @@ class ProfilerHelper {
v8::Local<v8::Function> function, v8::Local<v8::Value> argv[], int argc,
unsigned min_js_samples = 0, unsigned min_external_samples = 0,
ProfilingMode mode = ProfilingMode::kLeafNodeLineNumbers,
unsigned max_samples = v8::CpuProfilingOptions::kNoSampleLimit,
v8::Local<v8::Context> context = v8::Local<v8::Context>());
unsigned max_samples = v8::CpuProfilingOptions::kNoSampleLimit);
v8::CpuProfiler* profiler() { return profiler_; }
@@ -565,12 +564,11 @@ v8::CpuProfile* ProfilerHelper::Run(v8::Local<v8::Function> function,
v8::Local<v8::Value> argv[], int argc,
unsigned min_js_samples,
unsigned min_external_samples,
ProfilingMode mode, unsigned max_samples,
v8::Local<v8::Context> context) {
ProfilingMode mode, unsigned max_samples) {
v8::Local<v8::String> profile_name = v8_str("my_profile");
profiler_->SetSamplingInterval(50);
profiler_->StartProfiling(profile_name, {mode, max_samples, 0, context});
profiler_->StartProfiling(profile_name, {mode, max_samples, 0});
v8::internal::CpuProfiler* iprofiler =
reinterpret_cast<v8::internal::CpuProfiler*>(profiler_);
@@ -3819,141 +3817,6 @@ TEST(Bug9151StaleCodeEntries) {
CHECK(callback);
}
// Tests that functions from other contexts aren't recorded when filtering for
// another context.
TEST(ContextIsolation) {
i::FLAG_allow_natives_syntax = true;
LocalContext execution_env;
i::HandleScope scope(CcTest::i_isolate());
// Install CollectSample callback for more deterministic sampling.
v8::Local<v8::FunctionTemplate> func_template = v8::FunctionTemplate::New(
execution_env.local()->GetIsolate(), CallCollectSample);
v8::Local<v8::Function> func =
func_template->GetFunction(execution_env.local()).ToLocalChecked();
func->SetName(v8_str("CallCollectSample"));
execution_env->Global()
->Set(execution_env.local(), v8_str("CallCollectSample"), func)
.FromJust();
ProfilerHelper helper(execution_env.local());
CompileRun(R"(
function optimized() {
CallCollectSample();
}
function unoptimized() {
CallCollectSample();
}
function start() {
// Test optimized functions
%PrepareFunctionForOptimization(optimized);
optimized();
optimized();
%OptimizeFunctionOnNextCall(optimized);
optimized();
// Test unoptimized functions
%NeverOptimizeFunction(unoptimized);
unoptimized();
// Test callback
CallCollectSample();
}
)");
v8::Local<v8::Function> function =
GetFunction(execution_env.local(), "start");
v8::CpuProfile* same_context_profile = helper.Run(
function, nullptr, 0, 0, 0, v8::CpuProfilingMode::kLeafNodeLineNumbers,
v8::CpuProfilingOptions::kNoSampleLimit, execution_env.local());
const v8::CpuProfileNode* root = same_context_profile->GetTopDownRoot();
const v8::CpuProfileNode* start_node = FindChild(root, "start");
CHECK(start_node);
const v8::CpuProfileNode* optimized_node = FindChild(start_node, "optimized");
CHECK(optimized_node);
const v8::CpuProfileNode* unoptimized_node =
FindChild(start_node, "unoptimized");
CHECK(unoptimized_node);
const v8::CpuProfileNode* callback_node =
FindChild(start_node, "CallCollectSample");
CHECK(callback_node);
{
LocalContext filter_env;
v8::CpuProfile* diff_context_profile = helper.Run(
function, nullptr, 0, 0, 0, v8::CpuProfilingMode::kLeafNodeLineNumbers,
v8::CpuProfilingOptions::kNoSampleLimit, filter_env.local());
const v8::CpuProfileNode* diff_root =
diff_context_profile->GetTopDownRoot();
// Ensure that no children were recorded (including callbacks, builtins).
CHECK(!FindChild(diff_root, "start"));
}
}
// Tests that when a native context that's being filtered is moved, we continue
// to track its execution.
TEST(ContextFilterMovedNativeContext) {
if (i::FLAG_enable_third_party_heap) return;
i::FLAG_allow_natives_syntax = true;
i::FLAG_manual_evacuation_candidates_selection = true;
LocalContext env;
i::HandleScope scope(CcTest::i_isolate());
{
// Install CollectSample callback for more deterministic sampling.
v8::Local<v8::FunctionTemplate> sample_func_template =
v8::FunctionTemplate::New(env.local()->GetIsolate(), CallCollectSample);
v8::Local<v8::Function> sample_func =
sample_func_template->GetFunction(env.local()).ToLocalChecked();
sample_func->SetName(v8_str("CallCollectSample"));
env->Global()
->Set(env.local(), v8_str("CallCollectSample"), sample_func)
.FromJust();
// Install a function that triggers the native context to be moved.
v8::Local<v8::FunctionTemplate> move_func_template =
v8::FunctionTemplate::New(
env.local()->GetIsolate(),
[](const v8::FunctionCallbackInfo<v8::Value>& info) {
i::Isolate* isolate =
reinterpret_cast<i::Isolate*>(info.GetIsolate());
i::heap::ForceEvacuationCandidate(
i::Page::FromHeapObject(isolate->raw_native_context()));
CcTest::CollectAllGarbage();
});
v8::Local<v8::Function> move_func =
move_func_template->GetFunction(env.local()).ToLocalChecked();
move_func->SetName(v8_str("ForceNativeContextMove"));
env->Global()
->Set(env.local(), v8_str("ForceNativeContextMove"), move_func)
.FromJust();
ProfilerHelper helper(env.local());
CompileRun(R"(
function start() {
ForceNativeContextMove();
CallCollectSample();
}
)");
v8::Local<v8::Function> function = GetFunction(env.local(), "start");
v8::CpuProfile* profile = helper.Run(
function, nullptr, 0, 0, 0, v8::CpuProfilingMode::kLeafNodeLineNumbers,
v8::CpuProfilingOptions::kNoSampleLimit, env.local());
const v8::CpuProfileNode* root = profile->GetTopDownRoot();
const v8::CpuProfileNode* start_node = FindChild(root, "start");
CHECK(start_node);
// Verify that after moving the native context, CallCollectSample is still
// recorded.
const v8::CpuProfileNode* callback_node =
FindChild(start_node, "CallCollectSample");
CHECK(callback_node);
}
}
enum class EntryCountMode { kAll, kOnlyInlined };
// Count the number of unique source positions.
+1 -1
View File
@@ -516,7 +516,7 @@ TEST(HeapSnapshotHeapNumbersCaptureNumericValue) {
"a = 1; // a is Smi\n"
"b = 2.5; // b is HeapNumber");
const v8::HeapSnapshot* snapshot =
heap_profiler->TakeHeapSnapshot(nullptr, nullptr, true, true);
heap_profiler->TakeHeapSnapshotV8_92(nullptr, nullptr, true, true);
CHECK(ValidateSnapshot(snapshot));
const v8::HeapGraphNode* global = GetGlobalObject(snapshot);
const v8::HeapGraphNode* a =
+22 -22
View File
@@ -1572,7 +1572,7 @@ int CountBuiltins() {
static Handle<SharedFunctionInfo> CompileScript(
Isolate* isolate, Handle<String> source,
const ScriptDetails& script_details, AlignedCachedData* cached_data,
const ScriptDetails& script_details, ScriptData* cached_data,
v8::ScriptCompiler::CompileOptions options) {
return Compiler::GetSharedFunctionInfoForScript(
isolate, source, script_details, nullptr, cached_data, options,
@@ -1582,7 +1582,7 @@ static Handle<SharedFunctionInfo> CompileScript(
static Handle<SharedFunctionInfo> CompileScriptAndProduceCache(
Isolate* isolate, Handle<String> source,
const ScriptDetails& script_details, AlignedCachedData** out_cached_data,
const ScriptDetails& script_details, ScriptData** script_data,
v8::ScriptCompiler::CompileOptions options) {
Handle<SharedFunctionInfo> sfi =
Compiler::GetSharedFunctionInfoForScript(
@@ -1593,8 +1593,8 @@ static Handle<SharedFunctionInfo> CompileScriptAndProduceCache(
ScriptCompiler::CreateCodeCache(ToApiHandle<UnboundScript>(sfi)));
uint8_t* buffer = NewArray<uint8_t>(cached_data->length);
MemCopy(buffer, cached_data->data, cached_data->length);
*out_cached_data = new i::AlignedCachedData(buffer, cached_data->length);
(*out_cached_data)->AcquireDataOwnership();
*script_data = new i::ScriptData(buffer, cached_data->length);
(*script_data)->AcquireDataOwnership();
return sfi;
}
@@ -1620,7 +1620,7 @@ TEST(CodeSerializerWithProfiler) {
CHECK(!orig_source.is_identical_to(copy_source));
CHECK(orig_source->Equals(*copy_source));
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
ScriptDetails default_script_details;
Handle<SharedFunctionInfo> orig = CompileScriptAndProduceCache(
@@ -1663,7 +1663,7 @@ void TestCodeSerializerOnePlusOneImpl(bool verify_builtins_count = true) {
CHECK(!orig_source.is_identical_to(copy_source));
CHECK(orig_source->Equals(*copy_source));
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
ScriptDetails default_script_details;
Handle<SharedFunctionInfo> orig = CompileScriptAndProduceCache(
@@ -1723,7 +1723,7 @@ TEST(CodeSerializerPromotedToCompilationCache) {
const char* source = "1 + 1";
Handle<String> src = isolate->factory()->NewStringFromAsciiChecked(source);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<FixedArray> default_host_defined_options =
isolate->factory()->NewFixedArray(2);
@@ -1867,9 +1867,9 @@ TEST(CodeSerializerInternalizedString) {
Handle<JSObject> global(isolate->context().global_object(), isolate);
i::AlignedCachedData* cached_data = nullptr;
i::ScriptData* script_data = nullptr;
Handle<SharedFunctionInfo> orig = CompileScriptAndProduceCache(
isolate, orig_source, ScriptDetails(), &cached_data,
isolate, orig_source, ScriptDetails(), &script_data,
v8::ScriptCompiler::kNoCompileOptions);
Handle<JSFunction> orig_fun =
Factory::JSFunctionBuilder{isolate, orig, isolate->native_context()}
@@ -1883,7 +1883,7 @@ TEST(CodeSerializerInternalizedString) {
Handle<SharedFunctionInfo> copy;
{
DisallowCompilation no_compile_expected(isolate);
copy = CompileScript(isolate, copy_source, ScriptDetails(), cached_data,
copy = CompileScript(isolate, copy_source, ScriptDetails(), script_data,
v8::ScriptCompiler::kConsumeCodeCache);
}
CHECK_NE(*orig, *copy);
@@ -1902,7 +1902,7 @@ TEST(CodeSerializerInternalizedString) {
CHECK(Handle<String>::cast(copy_result)->Equals(*expected));
CHECK_EQ(builtins_count, CountBuiltins());
delete cached_data;
delete script_data;
}
TEST(CodeSerializerLargeCodeObject) {
@@ -1926,7 +1926,7 @@ TEST(CodeSerializerLargeCodeObject) {
isolate->factory()->NewStringFromUtf8(source).ToHandleChecked();
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig =
CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache,
@@ -1993,7 +1993,7 @@ TEST(CodeSerializerLargeCodeObjectWithIncrementalMarking) {
}
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig =
CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache,
@@ -2058,7 +2058,7 @@ TEST(CodeSerializerLargeStrings) {
.ToHandleChecked();
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig =
CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache,
@@ -2132,7 +2132,7 @@ TEST(CodeSerializerThreeBigStrings) {
.ToHandleChecked();
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig =
CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache,
@@ -2251,7 +2251,7 @@ TEST(CodeSerializerExternalString) {
.ToHandleChecked();
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig = CompileScriptAndProduceCache(
isolate, source_string, ScriptDetails(), &cache,
@@ -2315,7 +2315,7 @@ TEST(CodeSerializerLargeExternalString) {
.ToHandleChecked();
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig =
CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache,
@@ -2369,7 +2369,7 @@ TEST(CodeSerializerExternalScriptName) {
CHECK(!name->IsInternalizedString());
Handle<JSObject> global(isolate->context().global_object(), isolate);
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
Handle<SharedFunctionInfo> orig = CompileScriptAndProduceCache(
isolate, source_string, ScriptDetails(name), &cache,
@@ -2737,11 +2737,11 @@ TEST(Regress503552) {
HandleScope scope(isolate);
Handle<String> source = isolate->factory()->NewStringFromAsciiChecked(
"function f() {} function g() {}");
AlignedCachedData* cached_data = nullptr;
ScriptData* script_data = nullptr;
Handle<SharedFunctionInfo> shared = CompileScriptAndProduceCache(
isolate, source, ScriptDetails(), &cached_data,
isolate, source, ScriptDetails(), &script_data,
v8::ScriptCompiler::kNoCompileOptions);
delete cached_data;
delete script_data;
heap::SimulateIncrementalMarking(isolate->heap());
@@ -4126,7 +4126,7 @@ TEST(WeakArraySerializationInCodeCache) {
Handle<String> src = isolate->factory()
->NewStringFromUtf8(base::CStrVector(source))
.ToHandleChecked();
AlignedCachedData* cache = nullptr;
ScriptData* cache = nullptr;
ScriptDetails script_details(src);
CompileScriptAndProduceCache(isolate, src, script_details, &cache,
+24
View File
@@ -71,6 +71,30 @@ TEST(CopyContentsView) {
TestArrayBufferViewContents(&env, true);
}
TEST(AllocateNotExternal) {
LocalContext env;
v8::HandleScope scope(env->GetIsolate());
void* memory = reinterpret_cast<Isolate*>(env->GetIsolate())
->array_buffer_allocator()
->Allocate(1024);
// Keep the test until the functions are removed.
#if __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated"
#endif
v8::Local<v8::ArrayBuffer> buffer =
v8::ArrayBuffer::New(env->GetIsolate(), memory, 1024,
v8::ArrayBufferCreationMode::kInternalized);
CHECK(!buffer->IsExternal());
#if __clang__
#pragma clang diagnostic pop
#endif
CHECK_EQ(memory, buffer->GetBackingStore()->Data());
}
void TestSpeciesProtector(char* code,
bool invalidates_species_protector = true) {
v8::Isolate::CreateParams create_params;
-1
View File
@@ -202,7 +202,6 @@ v8_source_set("unittests_sources") {
"../../testing/gmock-support.h",
"../../testing/gtest-support.h",
"api/access-check-unittest.cc",
"api/deserialize-unittest.cc",
"api/exception-unittest.cc",
"api/interceptor-unittest.cc",
"api/isolate-unittest.cc",
-236
View File
@@ -1,236 +0,0 @@
// Copyright 2021 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "include/libplatform/libplatform.h"
#include "include/v8-platform.h"
#include "include/v8.h"
#include "test/unittests/test-utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace v8 {
class DeserializeTest : public testing::Test {
public:
class IsolateAndContextScope {
public:
explicit IsolateAndContextScope(DeserializeTest* test)
: test_(test),
isolate_wrapper_(kNoCounters),
isolate_scope_(isolate_wrapper_.isolate()),
handle_scope_(isolate_wrapper_.isolate()),
context_(Context::New(isolate_wrapper_.isolate())),
context_scope_(context_) {
CHECK_NULL(test->isolate_);
CHECK(test->context_.IsEmpty());
test->isolate_ = isolate_wrapper_.isolate();
test->context_ = context_;
}
~IsolateAndContextScope() {
test_->isolate_ = nullptr;
test_->context_ = {};
}
private:
DeserializeTest* test_;
v8::IsolateWrapper isolate_wrapper_;
v8::Isolate::Scope isolate_scope_;
v8::HandleScope handle_scope_;
v8::Local<v8::Context> context_;
v8::Context::Scope context_scope_;
};
Local<String> NewString(const char* val) {
return String::NewFromUtf8(isolate(), val).ToLocalChecked();
}
Local<Value> RunGlobalFunc(const char* name) {
Local<Value> func_val =
context()->Global()->Get(context(), NewString(name)).ToLocalChecked();
CHECK(func_val->IsFunction());
Local<Function> func = Local<Function>::Cast(func_val);
return func->Call(context(), Undefined(isolate()), 0, nullptr)
.ToLocalChecked();
}
Isolate* isolate() { return isolate_; }
v8::Local<v8::Context> context() { return context_.ToLocalChecked(); }
private:
Isolate* isolate_ = nullptr;
v8::MaybeLocal<v8::Context> context_;
};
// Check that deserialization works.
TEST_F(DeserializeTest, Deserialize) {
std::unique_ptr<v8::ScriptCompiler::CachedData> cached_data;
{
IsolateAndContextScope scope(this);
Local<String> source_code = NewString("function foo() { return 42; }");
Local<Script> script =
Script::Compile(context(), source_code).ToLocalChecked();
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("foo"), Integer::New(isolate(), 42));
cached_data.reset(
ScriptCompiler::CreateCodeCache(script->GetUnboundScript()));
}
{
IsolateAndContextScope scope(this);
Local<String> source_code = NewString("function foo() { return 42; }");
ScriptCompiler::Source source(source_code, cached_data.release());
Local<Script> script =
ScriptCompiler::Compile(context(), &source,
ScriptCompiler::kConsumeCodeCache)
.ToLocalChecked();
CHECK(!source.GetCachedData()->rejected);
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("foo"), v8::Integer::New(isolate(), 42));
}
}
// Check that deserialization with a different script rejects the cache but
// still works via standard compilation.
TEST_F(DeserializeTest, DeserializeRejectsDifferentSource) {
std::unique_ptr<v8::ScriptCompiler::CachedData> cached_data;
{
IsolateAndContextScope scope(this);
Local<String> source_code = NewString("function foo() { return 42; }");
Local<Script> script =
Script::Compile(context(), source_code).ToLocalChecked();
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("foo"), Integer::New(isolate(), 42));
cached_data.reset(
ScriptCompiler::CreateCodeCache(script->GetUnboundScript()));
}
{
IsolateAndContextScope scope(this);
// The source hash is based on the source length, so have to make sure that
// this is different here.
Local<String> source_code = NewString("function bar() { return 142; }");
ScriptCompiler::Source source(source_code, cached_data.release());
Local<Script> script =
ScriptCompiler::Compile(context(), &source,
ScriptCompiler::kConsumeCodeCache)
.ToLocalChecked();
CHECK(source.GetCachedData()->rejected);
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("bar"), v8::Integer::New(isolate(), 142));
}
}
class DeserializeThread : public base::Thread {
public:
explicit DeserializeThread(ScriptCompiler::ConsumeCodeCacheTask* task)
: Thread(base::Thread::Options("DeserializeThread")), task_(task) {}
void Run() override { task_->Run(); }
std::unique_ptr<ScriptCompiler::ConsumeCodeCacheTask> TakeTask() {
return std::move(task_);
}
private:
std::unique_ptr<ScriptCompiler::ConsumeCodeCacheTask> task_;
};
// Check that off-thread deserialization works.
TEST_F(DeserializeTest, OffThreadDeserialize) {
std::unique_ptr<v8::ScriptCompiler::CachedData> cached_data;
{
IsolateAndContextScope scope(this);
Local<String> source_code = NewString("function foo() { return 42; }");
Local<Script> script =
Script::Compile(context(), source_code).ToLocalChecked();
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("foo"), Integer::New(isolate(), 42));
cached_data.reset(
ScriptCompiler::CreateCodeCache(script->GetUnboundScript()));
}
{
IsolateAndContextScope scope(this);
DeserializeThread deserialize_thread(
ScriptCompiler::StartConsumingCodeCache(
isolate(), std::make_unique<ScriptCompiler::CachedData>(
cached_data->data, cached_data->length,
ScriptCompiler::CachedData::BufferNotOwned)));
CHECK(deserialize_thread.Start());
deserialize_thread.Join();
Local<String> source_code = NewString("function foo() { return 42; }");
ScriptCompiler::Source source(source_code, cached_data.release(),
deserialize_thread.TakeTask().release());
Local<Script> script =
ScriptCompiler::Compile(context(), &source,
ScriptCompiler::kConsumeCodeCache)
.ToLocalChecked();
CHECK(!source.GetCachedData()->rejected);
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("foo"), v8::Integer::New(isolate(), 42));
}
}
// Check that off-thread deserialization works.
TEST_F(DeserializeTest, OffThreadDeserializeRejectsDifferentSource) {
std::unique_ptr<v8::ScriptCompiler::CachedData> cached_data;
{
IsolateAndContextScope scope(this);
Local<String> source_code = NewString("function foo() { return 42; }");
Local<Script> script =
Script::Compile(context(), source_code).ToLocalChecked();
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("foo"), Integer::New(isolate(), 42));
cached_data.reset(
ScriptCompiler::CreateCodeCache(script->GetUnboundScript()));
}
{
IsolateAndContextScope scope(this);
DeserializeThread deserialize_thread(
ScriptCompiler::StartConsumingCodeCache(
isolate(), std::make_unique<ScriptCompiler::CachedData>(
cached_data->data, cached_data->length,
ScriptCompiler::CachedData::BufferNotOwned)));
CHECK(deserialize_thread.Start());
deserialize_thread.Join();
Local<String> source_code = NewString("function bar() { return 142; }");
ScriptCompiler::Source source(source_code, cached_data.release(),
deserialize_thread.TakeTask().release());
Local<Script> script =
ScriptCompiler::Compile(context(), &source,
ScriptCompiler::kConsumeCodeCache)
.ToLocalChecked();
CHECK(source.GetCachedData()->rejected);
CHECK(!script->Run(context()).IsEmpty());
CHECK_EQ(RunGlobalFunc("bar"), v8::Integer::New(isolate(), 142));
}
}
} // namespace v8
+76 -77
View File
@@ -156,82 +156,81 @@ INSTANCE_TYPES = {
191: "JS_MODULE_NAMESPACE_TYPE",
1040: "JS_SPECIAL_API_OBJECT_TYPE",
1041: "JS_PRIMITIVE_WRAPPER_TYPE",
1058: "JS_API_OBJECT_TYPE",
2058: "JS_LAST_DUMMY_API_OBJECT_TYPE",
2059: "JS_BOUND_FUNCTION_TYPE",
2060: "JS_FUNCTION_TYPE",
2061: "BIGINT64_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2062: "BIGUINT64_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2063: "FLOAT32_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2064: "FLOAT64_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2065: "INT16_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2066: "INT32_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2067: "INT8_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2068: "UINT16_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2069: "UINT32_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2070: "UINT8_CLAMPED_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2071: "UINT8_TYPED_ARRAY_CONSTRUCTOR_TYPE",
2072: "JS_ARRAY_CONSTRUCTOR_TYPE",
2073: "JS_PROMISE_CONSTRUCTOR_TYPE",
2074: "JS_REG_EXP_CONSTRUCTOR_TYPE",
2075: "JS_ARRAY_ITERATOR_PROTOTYPE_TYPE",
2076: "JS_ITERATOR_PROTOTYPE_TYPE",
2077: "JS_MAP_ITERATOR_PROTOTYPE_TYPE",
2078: "JS_OBJECT_PROTOTYPE_TYPE",
2079: "JS_PROMISE_PROTOTYPE_TYPE",
2080: "JS_REG_EXP_PROTOTYPE_TYPE",
2081: "JS_SET_ITERATOR_PROTOTYPE_TYPE",
2082: "JS_SET_PROTOTYPE_TYPE",
2083: "JS_STRING_ITERATOR_PROTOTYPE_TYPE",
2084: "JS_TYPED_ARRAY_PROTOTYPE_TYPE",
2085: "JS_MAP_KEY_ITERATOR_TYPE",
2086: "JS_MAP_KEY_VALUE_ITERATOR_TYPE",
2087: "JS_MAP_VALUE_ITERATOR_TYPE",
2088: "JS_SET_KEY_VALUE_ITERATOR_TYPE",
2089: "JS_SET_VALUE_ITERATOR_TYPE",
2090: "JS_GENERATOR_OBJECT_TYPE",
2091: "JS_ASYNC_FUNCTION_OBJECT_TYPE",
2092: "JS_ASYNC_GENERATOR_OBJECT_TYPE",
2093: "JS_DATA_VIEW_TYPE",
2094: "JS_TYPED_ARRAY_TYPE",
2095: "JS_MAP_TYPE",
2096: "JS_SET_TYPE",
2097: "JS_WEAK_MAP_TYPE",
2098: "JS_WEAK_SET_TYPE",
2099: "JS_ARGUMENTS_OBJECT_TYPE",
2100: "JS_ARRAY_TYPE",
2101: "JS_ARRAY_BUFFER_TYPE",
2102: "JS_ARRAY_ITERATOR_TYPE",
2103: "JS_ASYNC_FROM_SYNC_ITERATOR_TYPE",
2104: "JS_COLLATOR_TYPE",
2105: "JS_CONTEXT_EXTENSION_OBJECT_TYPE",
2106: "JS_DATE_TYPE",
2107: "JS_DATE_TIME_FORMAT_TYPE",
2108: "JS_DISPLAY_NAMES_TYPE",
2109: "JS_ERROR_TYPE",
2110: "JS_FINALIZATION_REGISTRY_TYPE",
2111: "JS_LIST_FORMAT_TYPE",
2112: "JS_LOCALE_TYPE",
2113: "JS_MESSAGE_OBJECT_TYPE",
2114: "JS_NUMBER_FORMAT_TYPE",
2115: "JS_PLURAL_RULES_TYPE",
2116: "JS_PROMISE_TYPE",
2117: "JS_REG_EXP_TYPE",
2118: "JS_REG_EXP_STRING_ITERATOR_TYPE",
2119: "JS_RELATIVE_TIME_FORMAT_TYPE",
2120: "JS_SEGMENT_ITERATOR_TYPE",
2121: "JS_SEGMENTER_TYPE",
2122: "JS_SEGMENTS_TYPE",
2123: "JS_STRING_ITERATOR_TYPE",
2124: "JS_V8_BREAK_ITERATOR_TYPE",
2125: "JS_WEAK_REF_TYPE",
2126: "WASM_GLOBAL_OBJECT_TYPE",
2127: "WASM_INSTANCE_OBJECT_TYPE",
2128: "WASM_MEMORY_OBJECT_TYPE",
2129: "WASM_MODULE_OBJECT_TYPE",
2130: "WASM_TABLE_OBJECT_TYPE",
2131: "WASM_TAG_OBJECT_TYPE",
2132: "WASM_VALUE_OBJECT_TYPE",
1042: "JS_ARRAY_ITERATOR_PROTOTYPE_TYPE",
1043: "JS_ITERATOR_PROTOTYPE_TYPE",
1044: "JS_MAP_ITERATOR_PROTOTYPE_TYPE",
1045: "JS_OBJECT_PROTOTYPE_TYPE",
1046: "JS_PROMISE_PROTOTYPE_TYPE",
1047: "JS_REG_EXP_PROTOTYPE_TYPE",
1048: "JS_SET_ITERATOR_PROTOTYPE_TYPE",
1049: "JS_SET_PROTOTYPE_TYPE",
1050: "JS_STRING_ITERATOR_PROTOTYPE_TYPE",
1051: "JS_TYPED_ARRAY_PROTOTYPE_TYPE",
1052: "JS_GENERATOR_OBJECT_TYPE",
1053: "JS_ASYNC_FUNCTION_OBJECT_TYPE",
1054: "JS_ASYNC_GENERATOR_OBJECT_TYPE",
1055: "JS_ARGUMENTS_OBJECT_TYPE",
1056: "JS_API_OBJECT_TYPE",
1058: "JS_BOUND_FUNCTION_TYPE",
1059: "JS_FUNCTION_TYPE",
1060: "BIGINT64_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1061: "BIGUINT64_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1062: "FLOAT32_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1063: "FLOAT64_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1064: "INT16_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1065: "INT32_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1066: "INT8_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1067: "UINT16_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1068: "UINT32_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1069: "UINT8_CLAMPED_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1070: "UINT8_TYPED_ARRAY_CONSTRUCTOR_TYPE",
1071: "JS_ARRAY_CONSTRUCTOR_TYPE",
1072: "JS_PROMISE_CONSTRUCTOR_TYPE",
1073: "JS_REG_EXP_CONSTRUCTOR_TYPE",
1074: "JS_MAP_KEY_ITERATOR_TYPE",
1075: "JS_MAP_KEY_VALUE_ITERATOR_TYPE",
1076: "JS_MAP_VALUE_ITERATOR_TYPE",
1077: "JS_SET_KEY_VALUE_ITERATOR_TYPE",
1078: "JS_SET_VALUE_ITERATOR_TYPE",
1079: "JS_DATA_VIEW_TYPE",
1080: "JS_TYPED_ARRAY_TYPE",
1081: "JS_MAP_TYPE",
1082: "JS_SET_TYPE",
1083: "JS_WEAK_MAP_TYPE",
1084: "JS_WEAK_SET_TYPE",
1085: "JS_ARRAY_TYPE",
1086: "JS_ARRAY_BUFFER_TYPE",
1087: "JS_ARRAY_ITERATOR_TYPE",
1088: "JS_ASYNC_FROM_SYNC_ITERATOR_TYPE",
1089: "JS_COLLATOR_TYPE",
1090: "JS_CONTEXT_EXTENSION_OBJECT_TYPE",
1091: "JS_DATE_TYPE",
1092: "JS_DATE_TIME_FORMAT_TYPE",
1093: "JS_DISPLAY_NAMES_TYPE",
1094: "JS_ERROR_TYPE",
1095: "JS_FINALIZATION_REGISTRY_TYPE",
1096: "JS_LIST_FORMAT_TYPE",
1097: "JS_LOCALE_TYPE",
1098: "JS_MESSAGE_OBJECT_TYPE",
1099: "JS_NUMBER_FORMAT_TYPE",
1100: "JS_PLURAL_RULES_TYPE",
1101: "JS_PROMISE_TYPE",
1102: "JS_REG_EXP_TYPE",
1103: "JS_REG_EXP_STRING_ITERATOR_TYPE",
1104: "JS_RELATIVE_TIME_FORMAT_TYPE",
1105: "JS_SEGMENT_ITERATOR_TYPE",
1106: "JS_SEGMENTER_TYPE",
1107: "JS_SEGMENTS_TYPE",
1108: "JS_STRING_ITERATOR_TYPE",
1109: "JS_V8_BREAK_ITERATOR_TYPE",
1110: "JS_WEAK_REF_TYPE",
1111: "WASM_GLOBAL_OBJECT_TYPE",
1112: "WASM_INSTANCE_OBJECT_TYPE",
1113: "WASM_MEMORY_OBJECT_TYPE",
1114: "WASM_MODULE_OBJECT_TYPE",
1115: "WASM_TABLE_OBJECT_TYPE",
1116: "WASM_TAG_OBJECT_TYPE",
1117: "WASM_VALUE_OBJECT_TYPE",
}
# List of known V8 maps.
@@ -391,7 +390,7 @@ KNOWN_MAPS = {
("read_only_space", 0x05fa9): (82, "StoreHandler2Map"),
("read_only_space", 0x05fd1): (82, "StoreHandler3Map"),
("map_space", 0x02119): (1057, "ExternalMap"),
("map_space", 0x02141): (2113, "JSMessageObjectMap"),
("map_space", 0x02141): (1098, "JSMessageObjectMap"),
}
# List of known V8 objects.