mirror of
https://github.com/nodejs/node.git
synced 2026-11-27 17:52:27 -05:00
src: add v8::Local specialization for MaybeStackBuffer
Long-term itch. Per v8 rules, we're not supposed to be heap allocating v8::Local's; instead we're supposed to be using v8::LocalVector. Create a specialization of MaybeStackBuffer that uses either a stack array of v8::Locals or v8::LocalVector with some additional utility improvements. Signed-off-by: James M Snell <jasnell@gmail.com> PR-URL: https://github.com/nodejs/node/pull/65159 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
This commit is contained in:
1 parent
825fcfe4d5
commit
613be79cf4
15 files changed
+161
-49
No files matched your search
+1
-1
@@ -245,7 +245,7 @@ MaybeLocal<Value> InternalMakeCallback(Environment* env,
|
||||
|
||||
Local<Context> context = env->context();
|
||||
if (use_async_hooks_trampoline) {
|
||||
MaybeStackBuffer<Local<Value>, 16> args(3 + argc);
|
||||
MaybeStackBuffer<Value, 16> args(env->isolate(), 3 + argc);
|
||||
args[0] = Number::New(env->isolate(), asyncContext.async_id);
|
||||
args[1] = resource;
|
||||
args[2] = callback;
|
||||
|
||||
+2
-2
@@ -201,12 +201,12 @@ Local<Array> AddrTTLToArray(
|
||||
Environment* env,
|
||||
const T* addrttls,
|
||||
size_t naddrttls) {
|
||||
MaybeStackBuffer<Local<Value>, 8> ttls(naddrttls);
|
||||
MaybeStackBuffer<Value, 8> ttls(env->isolate(), naddrttls);
|
||||
for (size_t i = 0; i < naddrttls; i++) {
|
||||
ttls[i] = Integer::NewFromUnsigned(env->isolate(), addrttls[i].ttl);
|
||||
}
|
||||
|
||||
return Array::New(env->isolate(), ttls.out(), naddrttls);
|
||||
return ttls.ToArray();
|
||||
}
|
||||
|
||||
int GetAnswerCountForTTLBuffer(const unsigned char* buf, int len) {
|
||||
|
||||
@@ -41,7 +41,6 @@ using ncrypto::MarkPopErrorOnReturn;
|
||||
using ncrypto::SSLPointer;
|
||||
using ncrypto::SSLSessionPointer;
|
||||
using ncrypto::X509Pointer;
|
||||
using v8::Array;
|
||||
using v8::ArrayBuffer;
|
||||
using v8::ArrayBufferView;
|
||||
using v8::BackingStore;
|
||||
@@ -1956,7 +1955,7 @@ void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
|
||||
SSL* ssl = w->ssl_.get();
|
||||
int nsig = SSL_get_shared_sigalgs(ssl, 0, nullptr, nullptr, nullptr, nullptr,
|
||||
nullptr);
|
||||
MaybeStackBuffer<Local<Value>, 16> ret_arr(nsig);
|
||||
MaybeStackBuffer<Value, 16> ret_arr(env->isolate(), nsig);
|
||||
|
||||
for (int i = 0; i < nsig; i++) {
|
||||
int hash_nid;
|
||||
@@ -2023,8 +2022,7 @@ void TLSWrap::GetSharedSigalgs(const FunctionCallbackInfo<Value>& args) {
|
||||
ret_arr[i] = OneByteString(env->isolate(), sig_with_md);
|
||||
}
|
||||
|
||||
args.GetReturnValue().Set(
|
||||
Array::New(env->isolate(), ret_arr.out(), ret_arr.length()));
|
||||
args.GetReturnValue().Set(ret_arr.ToArray());
|
||||
}
|
||||
|
||||
void TLSWrap::ExportKeyingMaterial(const FunctionCallbackInfo<Value>& args) {
|
||||
|
||||
+2
-6
@@ -11,7 +11,6 @@ namespace node {
|
||||
|
||||
using errors::TryCatchScope;
|
||||
|
||||
using v8::Array;
|
||||
using v8::Context;
|
||||
using v8::FunctionCallbackInfo;
|
||||
using v8::FunctionTemplate;
|
||||
@@ -119,17 +118,14 @@ int JSStream::DoWrite(WriteWrap* w,
|
||||
|
||||
int value_int = UV_EPROTO;
|
||||
|
||||
MaybeStackBuffer<Local<Value>, 16> bufs_arr(count);
|
||||
MaybeStackBuffer<Value, 16> bufs_arr(env()->isolate(), count);
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
if (!Buffer::Copy(env(), bufs[i].base, bufs[i].len).ToLocal(&bufs_arr[i])) {
|
||||
return value_int;
|
||||
}
|
||||
}
|
||||
|
||||
Local<Value> argv[] = {
|
||||
w->object(),
|
||||
Array::New(env()->isolate(), bufs_arr.out(), count)
|
||||
};
|
||||
Local<Value> argv[] = {w->object(), bufs_arr.ToArray()};
|
||||
|
||||
TryCatchScope try_catch(env());
|
||||
Local<Value> value;
|
||||
|
||||
+4
-5
@@ -11,7 +11,6 @@
|
||||
namespace node {
|
||||
|
||||
using errors::TryCatchScope;
|
||||
using v8::Array;
|
||||
using v8::Context;
|
||||
using v8::FunctionCallbackInfo;
|
||||
using v8::FunctionTemplate;
|
||||
@@ -98,7 +97,7 @@ ssize_t JSUDPWrap::Send(uv_buf_t* bufs,
|
||||
int64_t value_int = JS_EXCEPTION_PENDING;
|
||||
size_t total_len = 0;
|
||||
|
||||
MaybeStackBuffer<Local<Value>, 16> buffers(nbufs);
|
||||
MaybeStackBuffer<Value, 16> buffers(env()->isolate(), nbufs);
|
||||
for (size_t i = 0; i < nbufs; i++) {
|
||||
if (!Buffer::Copy(env(), bufs[i].base, bufs[i].len).ToLocal(&buffers[i])) {
|
||||
return value_int;
|
||||
@@ -110,9 +109,9 @@ ssize_t JSUDPWrap::Send(uv_buf_t* bufs,
|
||||
if (!AddressToJS(env(), addr).ToLocal(&address)) return value_int;
|
||||
|
||||
Local<Value> args[] = {
|
||||
listener()->CreateSendWrap(total_len)->object(),
|
||||
Array::New(env()->isolate(), buffers.out(), nbufs),
|
||||
address,
|
||||
listener()->CreateSendWrap(total_len)->object(),
|
||||
buffers.ToArray(),
|
||||
address,
|
||||
};
|
||||
|
||||
if (!MakeCallback(env()->onwrite_string(), arraysize(args), args)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
#include <v8.h>
|
||||
#include <concepts>
|
||||
#include <limits>
|
||||
#include <type_traits>
|
||||
@@ -32,6 +33,12 @@ concept StandardCharType =
|
||||
template <typename T>
|
||||
concept IsCallable = std::is_function<T>::value || requires { &T::operator(); };
|
||||
|
||||
// Types that can reside on V8's managed heap (v8::Value, v8::Object, etc.).
|
||||
// Used to select the MaybeStackBuffer specialization that holds handles in a
|
||||
// v8::LocalVector instead of malloc'd memory.
|
||||
template <typename T>
|
||||
concept V8Type = std::is_base_of_v<v8::Data, T>;
|
||||
|
||||
} // namespace node
|
||||
|
||||
#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
|
||||
|
||||
+3
-2
@@ -206,7 +206,7 @@ static MaybeLocal<Array> DirentListToArray(Environment* env,
|
||||
uv_dirent_t* ents,
|
||||
int num,
|
||||
enum encoding encoding) {
|
||||
MaybeStackBuffer<Local<Value>, 64> entries(num * 2);
|
||||
MaybeStackBuffer<Value, 64> entries(env->isolate(), num * 2);
|
||||
|
||||
// Return an array of all read filenames.
|
||||
int j = 0;
|
||||
@@ -222,7 +222,8 @@ static MaybeLocal<Array> DirentListToArray(Environment* env,
|
||||
entries[j++] = Integer::New(env->isolate(), ents[i].type);
|
||||
}
|
||||
|
||||
return Array::New(env->isolate(), entries.out(), j);
|
||||
CHECK_EQ(j, num * 2);
|
||||
return entries.ToArray();
|
||||
}
|
||||
|
||||
static void AfterDirRead(uv_fs_t* req) {
|
||||
|
||||
+5
-2
@@ -201,7 +201,7 @@ MaybeLocal<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
|
||||
auto cleanup = OnScopeLeave([&]() { uv_os_free_environ(items, count); });
|
||||
CHECK_EQ(uv_os_environ(&items, &count), 0);
|
||||
|
||||
MaybeStackBuffer<Local<Value>, 256> env_v(count);
|
||||
MaybeStackBuffer<Value, 256> env_v(isolate, count);
|
||||
int env_v_index = 0;
|
||||
for (int i = 0; i < count; i++) {
|
||||
#ifdef _WIN32
|
||||
@@ -216,7 +216,10 @@ MaybeLocal<Array> RealEnvStore::Enumerate(Isolate* isolate) const {
|
||||
env_v[env_v_index++] = str;
|
||||
}
|
||||
|
||||
return Array::New(isolate, env_v.out(), env_v_index);
|
||||
// We're possibly not filling the entire buffer.
|
||||
CHECK_LE(env_v_index, count);
|
||||
env_v.SetLength(env_v_index);
|
||||
return env_v.ToArray();
|
||||
}
|
||||
|
||||
std::shared_ptr<KVStore> KVStore::Clone(Isolate* isolate) const {
|
||||
|
||||
+9
-8
@@ -1585,8 +1585,8 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
|
||||
// this way for performance reasons (it's faster to generate and pass an
|
||||
// array than it is to generate and pass the object).
|
||||
|
||||
MaybeStackBuffer<Local<Value>, 64> headers_v(stream->headers_count() * 2);
|
||||
MaybeStackBuffer<Local<Value>, 32> sensitive_v(stream->headers_count());
|
||||
MaybeStackBuffer<Value, 64> headers_v(isolate, stream->headers_count() * 2);
|
||||
MaybeStackBuffer<Value, 32> sensitive_v(isolate, stream->headers_count());
|
||||
size_t sensitive_count = 0;
|
||||
|
||||
stream->TransferHeaders([&](const Http2Header& header, size_t i) {
|
||||
@@ -1603,13 +1603,14 @@ void Http2Session::HandleHeadersFrame(const nghttp2_frame* frame) {
|
||||
stream->retained_headers_length_ += stream->current_headers_length_;
|
||||
stream->current_headers_length_ = 0;
|
||||
|
||||
sensitive_v.SetLength(sensitive_count);
|
||||
Local<Value> args[] = {
|
||||
stream->object(),
|
||||
Integer::New(isolate, id),
|
||||
Integer::New(isolate, stream->headers_category()),
|
||||
Integer::New(isolate, frame->hd.flags),
|
||||
Array::New(isolate, headers_v.out(), headers_v.length()),
|
||||
Array::New(isolate, sensitive_v.out(), sensitive_count),
|
||||
stream->object(),
|
||||
Integer::New(isolate, id),
|
||||
Integer::New(isolate, stream->headers_category()),
|
||||
Integer::New(isolate, frame->hd.flags),
|
||||
headers_v.ToArray(),
|
||||
sensitive_v.ToArray(),
|
||||
};
|
||||
MakeCallback(env()->http2session_on_headers_function(),
|
||||
arraysize(args), args);
|
||||
|
||||
@@ -1093,7 +1093,7 @@ void MessagePort::PostMessage(const FunctionCallbackInfo<Value>& args) {
|
||||
"MessagePort.postMessage");
|
||||
}
|
||||
|
||||
TransferList transfer_list;
|
||||
TransferList transfer_list(env->isolate());
|
||||
if (!GetTransferList(env, context, args[1], &transfer_list)) {
|
||||
return;
|
||||
}
|
||||
@@ -1607,7 +1607,7 @@ static void StructuredClone(const FunctionCallbackInfo<Value>& args) {
|
||||
|
||||
Local<Value> value = args[0];
|
||||
|
||||
TransferList transfer_list;
|
||||
TransferList transfer_list(isolate);
|
||||
Local<Object> options = args[1].As<Object>();
|
||||
Local<Value> transfer_list_v;
|
||||
if (!options->Get(context, env->transfer_string())
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace worker {
|
||||
class MessagePortData;
|
||||
class MessagePort;
|
||||
|
||||
typedef MaybeStackBuffer<v8::Local<v8::Value>, 8> TransferList;
|
||||
typedef MaybeStackBuffer<v8::Value, 8> TransferList;
|
||||
|
||||
// Used to represent the in-flight structure of an object that is being
|
||||
// transferred or cloned using postMessage().
|
||||
|
||||
+5
-5
@@ -745,17 +745,17 @@ void Initialize(Local<Object> target,
|
||||
// Heap space names are extracted once and exposed to JavaScript to
|
||||
// avoid excessive creation of heap space name Strings.
|
||||
HeapSpaceStatistics s;
|
||||
MaybeStackBuffer<Local<Value>, 16> heap_spaces(number_of_heap_spaces);
|
||||
MaybeStackBuffer<Value, 16> heap_spaces(env->isolate(),
|
||||
number_of_heap_spaces);
|
||||
for (size_t i = 0; i < number_of_heap_spaces; i++) {
|
||||
env->isolate()->GetHeapSpaceStatistics(&s, i);
|
||||
heap_spaces[i] = String::NewFromUtf8(env->isolate(), s.space_name())
|
||||
.ToLocalChecked();
|
||||
}
|
||||
target
|
||||
->Set(
|
||||
context,
|
||||
FIXED_ONE_BYTE_STRING(env->isolate(), "kHeapSpaces"),
|
||||
Array::New(env->isolate(), heap_spaces.out(), number_of_heap_spaces))
|
||||
->Set(context,
|
||||
FIXED_ONE_BYTE_STRING(env->isolate(), "kHeapSpaces"),
|
||||
heap_spaces.ToArray())
|
||||
.Check();
|
||||
|
||||
SetMethod(context,
|
||||
|
||||
+2
-3
@@ -767,7 +767,7 @@ MaybeLocal<Array> SyncProcessRunner::BuildOutputArray() {
|
||||
CHECK(!stdio_pipes_.empty());
|
||||
|
||||
EscapableHandleScope scope(env()->isolate());
|
||||
MaybeStackBuffer<Local<Value>, 8> js_output(stdio_pipes_.size());
|
||||
MaybeStackBuffer<Value, 8> js_output(env()->isolate(), stdio_pipes_.size());
|
||||
|
||||
for (uint32_t i = 0; i < stdio_pipes_.size(); i++) {
|
||||
SyncProcessStdioPipe* h = stdio_pipes_[i].get();
|
||||
@@ -781,8 +781,7 @@ MaybeLocal<Array> SyncProcessRunner::BuildOutputArray() {
|
||||
}
|
||||
}
|
||||
|
||||
return scope.Escape(
|
||||
Array::New(env()->isolate(), js_output.out(), js_output.length()));
|
||||
return scope.Escape(js_output.ToArray());
|
||||
}
|
||||
|
||||
Maybe<int> SyncProcessRunner::ParseOptions(Local<Value> js_value) {
|
||||
|
||||
+33
-7
@@ -394,14 +394,13 @@ v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
if (isolate == nullptr) isolate = v8::Isolate::GetCurrent();
|
||||
v8::EscapableHandleScope handle_scope(isolate);
|
||||
|
||||
MaybeStackBuffer<v8::Local<v8::Value>, 128> arr(vec.size());
|
||||
arr.SetLength(vec.size());
|
||||
MaybeStackBuffer<v8::Value, 128> arr(isolate, vec.size());
|
||||
for (size_t i = 0; i < vec.size(); ++i) {
|
||||
if (!ToV8Value(context, vec[i], isolate).ToLocal(&arr[i]))
|
||||
return v8::MaybeLocal<v8::Value>();
|
||||
}
|
||||
|
||||
return handle_scope.Escape(v8::Array::New(isolate, arr.out(), arr.length()));
|
||||
return handle_scope.Escape(arr.ToArray());
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
@@ -430,8 +429,7 @@ v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
if (isolate == nullptr) isolate = v8::Isolate::GetCurrent();
|
||||
v8::EscapableHandleScope handle_scope(isolate);
|
||||
|
||||
MaybeStackBuffer<v8::Local<v8::Value>, 128> arr(vec.size());
|
||||
arr.SetLength(vec.size());
|
||||
MaybeStackBuffer<v8::Value, 128> arr(isolate, vec.size());
|
||||
auto it = vec.begin();
|
||||
for (size_t i = 0; i < vec.size(); ++i) {
|
||||
if (!ToV8Value(context, *it, isolate).ToLocal(&arr[i]))
|
||||
@@ -439,7 +437,7 @@ v8::MaybeLocal<v8::Value> ToV8Value(v8::Local<v8::Context> context,
|
||||
std::advance(it, 1);
|
||||
}
|
||||
|
||||
return handle_scope.Escape(v8::Array::New(isolate, arr.out(), arr.length()));
|
||||
return handle_scope.Escape(arr.ToArray());
|
||||
}
|
||||
|
||||
template <typename T, typename U>
|
||||
@@ -519,7 +517,14 @@ v8::Local<v8::Array> ToV8ValuePrimitiveArray(v8::Local<v8::Context> context,
|
||||
}
|
||||
|
||||
SlicedArguments::SlicedArguments(
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args, size_t start) {
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args, size_t start)
|
||||
: SlicedArguments(args.GetIsolate(), args, start) {}
|
||||
|
||||
SlicedArguments::SlicedArguments(
|
||||
v8::Isolate* isolate,
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args,
|
||||
size_t start)
|
||||
: MaybeStackBuffer<v8::Value>(isolate) {
|
||||
const size_t length = static_cast<size_t>(args.Length());
|
||||
if (start >= length) return;
|
||||
const size_t size = length - start;
|
||||
@@ -545,6 +550,27 @@ void MaybeStackBuffer<T, kStackStorageSize>::AllocateSufficientStorage(
|
||||
length_ = storage;
|
||||
}
|
||||
|
||||
template <V8Type T, size_t kStackStorageSize>
|
||||
void MaybeStackBuffer<T, kStackStorageSize>::AllocateSufficientStorage(
|
||||
size_t storage) {
|
||||
CHECK(!IsInvalidated());
|
||||
if (storage > capacity()) {
|
||||
if (!local_vector_.has_value()) {
|
||||
local_vector_.emplace(isolate_, storage);
|
||||
// Copy existing stack data into the LocalVector.
|
||||
for (size_t i = 0; i < length_; i++) {
|
||||
(*local_vector_)[i] = buf_st_[i];
|
||||
}
|
||||
} else {
|
||||
local_vector_->resize(storage);
|
||||
}
|
||||
buf_ = local_vector_->data();
|
||||
capacity_ = storage;
|
||||
}
|
||||
|
||||
length_ = storage;
|
||||
}
|
||||
|
||||
template <typename T, size_t S>
|
||||
requires(sizeof(T) == 1)
|
||||
ArrayBufferViewContents<T, S>::ArrayBufferViewContents(
|
||||
|
||||
+83
-1
@@ -526,6 +526,85 @@ class MaybeStackBuffer {
|
||||
T buf_st_[kStackStorageSize];
|
||||
};
|
||||
|
||||
template <V8Type T, size_t kStackStorageSize>
|
||||
class MaybeStackBuffer<T, kStackStorageSize> {
|
||||
public:
|
||||
using V = v8::Local<T>;
|
||||
|
||||
MaybeStackBuffer(const MaybeStackBuffer&) = delete;
|
||||
MaybeStackBuffer& operator=(const MaybeStackBuffer& other) = delete;
|
||||
|
||||
const V* out() const { return buf_; }
|
||||
V* out() { return buf_; }
|
||||
|
||||
// operator* for compatibility with `v8::String::(Utf8)Value`
|
||||
V* operator*() { return buf_; }
|
||||
const V* operator*() const { return buf_; }
|
||||
|
||||
V& operator[](size_t index) {
|
||||
CHECK_LT(index, length());
|
||||
return buf_[index];
|
||||
}
|
||||
|
||||
const V& operator[](size_t index) const {
|
||||
CHECK_LT(index, length());
|
||||
return buf_[index];
|
||||
}
|
||||
|
||||
size_t length() const { return length_; }
|
||||
|
||||
// Current maximum capacity of the buffer with which SetLength() can be used
|
||||
// without first calling AllocateSufficientStorage().
|
||||
size_t capacity() const { return capacity_; }
|
||||
|
||||
// Make sure enough space for `storage` entries is available.
|
||||
// This method can be called multiple times throughout the lifetime of the
|
||||
// buffer, but once this has been called Invalidate() cannot be used.
|
||||
// Content of the buffer in the range [0, length()) is preserved.
|
||||
void AllocateSufficientStorage(size_t storage);
|
||||
|
||||
void SetLength(size_t length) {
|
||||
// capacity() returns how much memory is actually available.
|
||||
CHECK_LE(length, capacity());
|
||||
length_ = length;
|
||||
}
|
||||
|
||||
// If the buffer is stored in a LocalVector rather than on the stack.
|
||||
bool IsAllocated() const { return !IsInvalidated() && buf_ != buf_st_; }
|
||||
|
||||
// If Invalidate() has been called.
|
||||
bool IsInvalidated() const { return buf_ == nullptr; }
|
||||
|
||||
explicit MaybeStackBuffer(v8::Isolate* isolate)
|
||||
: isolate_(isolate),
|
||||
length_(0),
|
||||
capacity_(arraysize(buf_st_)),
|
||||
buf_(buf_st_) {
|
||||
// Default to a zero-length, null-terminated buffer.
|
||||
buf_[0] = V();
|
||||
}
|
||||
|
||||
MaybeStackBuffer(v8::Isolate* isolate, size_t storage)
|
||||
: MaybeStackBuffer(isolate) {
|
||||
AllocateSufficientStorage(storage);
|
||||
}
|
||||
|
||||
// LocalVector (via optional) handles cleanup automatically.
|
||||
~MaybeStackBuffer() = default;
|
||||
|
||||
v8::Local<v8::Array> ToArray() const {
|
||||
return v8::Array::New(isolate_, buf_, length_);
|
||||
}
|
||||
|
||||
private:
|
||||
v8::Isolate* isolate_;
|
||||
size_t length_;
|
||||
size_t capacity_;
|
||||
V* buf_;
|
||||
V buf_st_[kStackStorageSize];
|
||||
std::optional<v8::LocalVector<T>> local_vector_;
|
||||
};
|
||||
|
||||
// Provides access to an ArrayBufferView's storage, either the original,
|
||||
// or for small data, a copy of it. This object's lifetime is bound to the
|
||||
// original ArrayBufferView's lifetime.
|
||||
@@ -782,10 +861,13 @@ constexpr inline bool IsBigEndian() {
|
||||
static_assert(IsLittleEndian() || IsBigEndian(),
|
||||
"Node.js does not support mixed-endian systems");
|
||||
|
||||
class SlicedArguments : public MaybeStackBuffer<v8::Local<v8::Value>> {
|
||||
class SlicedArguments : public MaybeStackBuffer<v8::Value> {
|
||||
public:
|
||||
inline explicit SlicedArguments(
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args, size_t start = 0);
|
||||
inline SlicedArguments(v8::Isolate* isolate,
|
||||
const v8::FunctionCallbackInfo<v8::Value>& args,
|
||||
size_t start = 0);
|
||||
};
|
||||
|
||||
// Convert a v8::PersistentBase, e.g. v8::Global, to a Local, with an extra
|
||||
|
||||
Reference in new issue
Block a user