Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src: migrated to new V8 ArrayBuffer API #30782

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/env-inl.h
Original file line number Diff line number Diff line change
Expand Up @@ -983,10 +983,20 @@ inline v8::MaybeLocal<v8::Object> AllocatedBuffer::ToBuffer() {
inline v8::Local<v8::ArrayBuffer> AllocatedBuffer::ToArrayBuffer() {
CHECK_NOT_NULL(env_);
uv_buf_t buf = release();
auto callback = [](void* data, size_t length, void* deleter_data){
CHECK_NOT_NULL(deleter_data);

static_cast<v8::ArrayBuffer::Allocator*>(deleter_data)
->Free(data, length);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There’s an issue with this that I didn’t realize during review, sorry … see https://bugs.chromium.org/p/v8/issues/detail?id=9908#c10 for details

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@addaleax should i force-push here or open a new PR?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thangktran I think neither. I believe @addaleax already opened a PR to fix: #30946

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Trott i checked it just now and it's actually still there.

Copy link
Member

@addaleax addaleax Dec 13, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Trott This here is a V8 API issue, #30946 fixes a different bug in our code. So there is something we need to do.

I think the 3 options here are:

  • Temporarily reverting the changes that add the v8::ArrayBuffer::Allocator::Free calls and go back to using the deprecated APIs, effectively blocking the upgrade to 8.0 or 8.1 (not sure which)
  • Modifying our embedder API to let embedders and ourselves pass a std::shared_ptr<v8::ArrayBuffer::Allocator> that is also passed to V8 and then use a pointer to that instead of a raw v8::ArrayBuffer::Allocator* (I don’t like this one, it’s quite a bit of work and complexity with little gain)
  • Implementing the V8 API suggestion in the V8 bug linked above and then using that. I think that would be the ideal one, but let’s wait for @ulan’s response in the issue first. @thangktran If this works out and you haven’t contributed to V8 before, I’m happy to help answer any questions – I know their process can be a bit unusual for those who aren’t used to it :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@addaleax : Thank you for offering me help. I'm looking forward to it :D
What is your opinion about @ulan 's alternatives? :

Before we go ahead with the new constructor, I want to discuss the feasibility of the third option:

  1. Change AllocatedBuffer [1] to allocate and keep std::unique_ptrv8::BackingStore.
  2. Add Reallocate method to ArrayBufferAllocator (the default implementation would simply allocate a new buffer).
  3. Add a static Reallocate method to v8::BackingStore that takes a unique_ptr and returns a unique_ptr. Internally it calls Reallocate of the array buffer allocator.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thangktran Thanks for the ping! I’ve commented in the issue. Basically, I’m good with Ulan’s suggestion. 👍

};
std::unique_ptr<v8::BackingStore> backing =
v8::ArrayBuffer::NewBackingStore(buf.base,
buf.len,
callback,
env_->isolate()
->GetArrayBufferAllocator());
return v8::ArrayBuffer::New(env_->isolate(),
buf.base,
buf.len,
v8::ArrayBufferCreationMode::kInternalized);
std::move(backing));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So… This looks correct and I currently don’t have any better ideas either, but maybe to give an idea about the “big picture” here:

The idea behind AllocatedBuffer is to have something that gets turned into an ArrayBuffer in the most direct way possible. In that sense, it is basically our own version of BackingStore – a wrapper class for memory tracked through the current ArrayBuffer::Allocator. A “nicer” way to fix this would be to e.g. store the data as the std::shared_ptr<BackingStore> directly instead of using a uv_buf_t. However, I think that doesn’t work currently, because we’d have no way to implement e.g. .release() for that kind of scenario.

It might be nice if we had a way to avoid free callbacks that only run v8::ArrayBuffer::Allocator::Free() like this one. That would require an V8 API change, though, and I’m not sure what the best way for that would be.

Or, alternatively, it would be nice if we could implement AllocatedBuffer in terms of std::shared_ptr<BackingStore> as mentioned above; in that case, we’d have to figure out something clever for AllocatedBuffer::release().

(To be clear, this isn’t a request to change the code here. It’s just me rambling and trying to give some context.)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll think of something and prepare a PR for this.

}

inline void Environment::ThrowError(const char* errmsg) {
Expand Down
12 changes: 11 additions & 1 deletion src/js_native_api_v8.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2612,8 +2612,18 @@ napi_status napi_create_external_arraybuffer(napi_env env,
CHECK_ARG(env, result);

v8::Isolate* isolate = env->isolate;
// The buffer will be freed with v8impl::ArrayBufferReference::New()
// below, hence this BackingStore does not need to free the buffer.
std::unique_ptr<v8::BackingStore> backing =
v8::ArrayBuffer::NewBackingStore(external_data,
byte_length,
[](void*, size_t, void*){},
nullptr);
addaleax marked this conversation as resolved.
Show resolved Hide resolved
v8::Local<v8::ArrayBuffer> buffer =
v8::ArrayBuffer::New(isolate, external_data, byte_length);
v8::ArrayBuffer::New(isolate, std::move(backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!buffer->IsExternal())
buffer->Externalize(buffer->GetBackingStore());
v8::Maybe<bool> marked = env->mark_arraybuffer_as_untransferable(buffer);
CHECK_MAYBE_NOTHING(env, marked, napi_generic_failure);

Expand Down
52 changes: 41 additions & 11 deletions src/node_buffer.cc
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ namespace node {
namespace Buffer {

using v8::ArrayBuffer;
using v8::ArrayBufferCreationMode;
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::Context;
using v8::EscapableHandleScope;
using v8::FunctionCallbackInfo;
Expand Down Expand Up @@ -127,8 +127,8 @@ CallbackInfo::CallbackInfo(Environment* env,
data_(data),
hint_(hint),
env_(env) {
ArrayBuffer::Contents obj_c = object->GetContents();
CHECK_EQ(data_, static_cast<char*>(obj_c.Data()));
std::shared_ptr<BackingStore> obj_backing = object->GetBackingStore();
CHECK_EQ(data_, static_cast<char*>(obj_backing->Data()));
if (object->ByteLength() != 0)
CHECK_NOT_NULL(data_);

Expand Down Expand Up @@ -406,7 +406,19 @@ MaybeLocal<Object> New(Environment* env,
return Local<Object>();
}

Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(), data, length);

// The buffer will be released by a CallbackInfo::New() below,
// hence this BackingStore callback is empty.
std::unique_ptr<BackingStore> backing =
ArrayBuffer::NewBackingStore(data,
length,
[](void*, size_t, void*){},
nullptr);
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(),
std::move(backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!ab->IsExternal())
ab->Externalize(ab->GetBackingStore());
addaleax marked this conversation as resolved.
Show resolved Hide resolved
if (ab->SetPrivate(env->context(),
env->arraybuffer_untransferable_private_symbol(),
True(env->isolate())).IsNothing()) {
Expand Down Expand Up @@ -465,11 +477,21 @@ MaybeLocal<Object> New(Environment* env,
}
}

Local<ArrayBuffer> ab =
ArrayBuffer::New(env->isolate(),
data,
length,
ArrayBufferCreationMode::kInternalized);
auto callback = [](void* data, size_t length, void* deleter_data){
CHECK_NOT_NULL(deleter_data);

static_cast<v8::ArrayBuffer::Allocator*>(deleter_data)
->Free(data, length);
};
std::unique_ptr<v8::BackingStore> backing =
v8::ArrayBuffer::NewBackingStore(data,
length,
callback,
env->isolate()
->GetArrayBufferAllocator());
Local<ArrayBuffer> ab = ArrayBuffer::New(env->isolate(),
std::move(backing));

return Buffer::New(env, ab, 0, length).FromMaybe(Local<Object>());
}

Expand Down Expand Up @@ -1181,8 +1203,16 @@ void Initialize(Local<Object> target,
if (NodeArrayBufferAllocator* allocator =
env->isolate_data()->node_allocator()) {
uint32_t* zero_fill_field = allocator->zero_fill_field();
Local<ArrayBuffer> array_buffer = ArrayBuffer::New(
env->isolate(), zero_fill_field, sizeof(*zero_fill_field));
std::unique_ptr<BackingStore> backing =
ArrayBuffer::NewBackingStore(zero_fill_field,
sizeof(*zero_fill_field),
[](void*, size_t, void*){},
nullptr);
Local<ArrayBuffer> array_buffer =
ArrayBuffer::New(env->isolate(), std::move(backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!array_buffer->IsExternal())
array_buffer->Externalize(array_buffer->GetBackingStore());
CHECK(target
->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(), "zeroFill"),
Expand Down
23 changes: 20 additions & 3 deletions src/node_http2.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ namespace node {

using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BackingStore;
using v8::Boolean;
using v8::Context;
using v8::Float64Array;
Expand Down Expand Up @@ -566,10 +567,18 @@ Http2Session::Http2Session(Environment* env,

{
// Make the js_fields_ property accessible to JS land.
std::unique_ptr<BackingStore> backing =
ArrayBuffer::NewBackingStore(
reinterpret_cast<uint8_t*>(&js_fields_),
kSessionUint8FieldCount,
[](void*, size_t, void*){},
nullptr);
Local<ArrayBuffer> ab =
ArrayBuffer::New(env->isolate(),
reinterpret_cast<uint8_t*>(&js_fields_),
kSessionUint8FieldCount);
ArrayBuffer::New(env->isolate(), std::move(backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!ab->IsExternal())
ab->Externalize(ab->GetBackingStore());
js_fields_ab_.Reset(env->isolate(), ab);
Local<Uint8Array> uint8_arr =
Uint8Array::New(ab, 0, kSessionUint8FieldCount);
USE(wrap->Set(env->context(), env->fields_string(), uint8_arr));
Expand All @@ -581,6 +590,14 @@ Http2Session::~Http2Session() {
Debug(this, "freeing nghttp2 session");
nghttp2_session_del(session_);
CHECK_EQ(current_nghttp2_memory_, 0);
HandleScope handle_scope(env()->isolate());
// Detach js_fields_ab_ to avoid having problem when new Http2Session
// instances are created on the same location of previous
// instances. This in turn will call ArrayBuffer::NewBackingStore()
// multiple times with the same buffer address and causing error.
// Ref: https://github.com/nodejs/node/pull/30782
Local<ArrayBuffer> ab = js_fields_ab_.Get(env()->isolate());
ab->Detach();
}

std::string Http2Session::diagnostic_name() const {
Expand Down
1 change: 1 addition & 0 deletions src/node_http2.h
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,7 @@ class Http2Session : public AsyncWrap,

// JS-accessible numeric fields, as indexed by SessionUint8Fields.
SessionJSFields js_fields_ = {};
v8::Global<v8::ArrayBuffer> js_fields_ab_;

// The session type: client or server
nghttp2_session_type session_type_;
Expand Down
49 changes: 40 additions & 9 deletions src/node_v8.cc
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ namespace node {

using v8::Array;
using v8::ArrayBuffer;
using v8::BackingStore;
using v8::Context;
using v8::FunctionCallbackInfo;
using v8::HeapCodeStatistics;
Expand Down Expand Up @@ -162,12 +163,22 @@ void Initialize(Local<Object> target,
const size_t heap_statistics_buffer_byte_length =
sizeof(*env->heap_statistics_buffer()) * kHeapStatisticsPropertiesCount;

std::unique_ptr<BackingStore> heap_statistics_backing =
ArrayBuffer::NewBackingStore(env->heap_statistics_buffer(),
heap_statistics_buffer_byte_length,
[](void*, size_t, void*){},
nullptr);
Local<ArrayBuffer> heap_statistics_ab =
ArrayBuffer::New(env->isolate(),
std::move(heap_statistics_backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!heap_statistics_ab->IsExternal())
heap_statistics_ab->Externalize(
heap_statistics_ab->GetBackingStore());
target->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(),
"heapStatisticsArrayBuffer"),
ArrayBuffer::New(env->isolate(),
env->heap_statistics_buffer(),
heap_statistics_buffer_byte_length)).Check();
heap_statistics_ab).Check();

#define V(i, _, name) \
target->Set(env->context(), \
Expand All @@ -189,12 +200,22 @@ void Initialize(Local<Object> target,
sizeof(*env->heap_code_statistics_buffer())
* kHeapCodeStatisticsPropertiesCount;

std::unique_ptr<BackingStore> heap_code_statistics_backing =
ArrayBuffer::NewBackingStore(env->heap_code_statistics_buffer(),
heap_code_statistics_buffer_byte_length,
[](void*, size_t, void*){},
nullptr);
Local<ArrayBuffer> heap_code_statistics_ab =
ArrayBuffer::New(env->isolate(),
std::move(heap_code_statistics_backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!heap_code_statistics_ab->IsExternal())
heap_code_statistics_ab->Externalize(
heap_code_statistics_ab->GetBackingStore());
target->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(),
"heapCodeStatisticsArrayBuffer"),
ArrayBuffer::New(env->isolate(),
env->heap_code_statistics_buffer(),
heap_code_statistics_buffer_byte_length))
heap_code_statistics_ab)
.Check();

#define V(i, _, name) \
Expand Down Expand Up @@ -244,12 +265,22 @@ void Initialize(Local<Object> target,
kHeapSpaceStatisticsPropertiesCount *
number_of_heap_spaces;

std::unique_ptr<BackingStore> heap_space_statistics_backing =
ArrayBuffer::NewBackingStore(env->heap_space_statistics_buffer(),
heap_space_statistics_buffer_byte_length,
[](void*, size_t, void*){},
nullptr);
Local<ArrayBuffer> heap_space_statistics_ab =
ArrayBuffer::New(env->isolate(),
std::move(heap_space_statistics_backing));
// TODO(thangktran): drop this check when V8 is pumped to 8.0 .
if (!heap_space_statistics_ab->IsExternal())
heap_space_statistics_ab->Externalize(
heap_space_statistics_ab->GetBackingStore());
target->Set(env->context(),
FIXED_ONE_BYTE_STRING(env->isolate(),
"heapSpaceStatisticsArrayBuffer"),
ArrayBuffer::New(env->isolate(),
env->heap_space_statistics_buffer(),
heap_space_statistics_buffer_byte_length))
heap_space_statistics_ab)
.Check();

#define V(i, _, name) \
Expand Down
2 changes: 2 additions & 0 deletions src/node_worker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
using node::kDisallowedInEnvironment;
using v8::Array;
using v8::ArrayBuffer;
using v8::BackingStore;
using v8::Boolean;
using v8::Context;
using v8::Float64Array;
Expand Down Expand Up @@ -622,6 +623,7 @@ void Worker::GetResourceLimits(const FunctionCallbackInfo<Value>& args) {

Local<Float64Array> Worker::GetResourceLimits(Isolate* isolate) const {
Local<ArrayBuffer> ab = ArrayBuffer::New(isolate, sizeof(resource_limits_));

memcpy(ab->GetBackingStore()->Data(),
resource_limits_,
sizeof(resource_limits_));
Expand Down
5 changes: 4 additions & 1 deletion test/addons/worker-buffer-callback/binding.cc
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ using v8::Object;
using v8::Value;

uint32_t free_call_count = 0;
char data[] = "hello";

void GetFreeCallCount(const FunctionCallbackInfo<Value>& args) {
args.GetReturnValue().Set(free_call_count);
Expand All @@ -21,6 +20,9 @@ void Initialize(Local<Object> exports,
Local<Context> context) {
Isolate* isolate = context->GetIsolate();
NODE_SET_METHOD(exports, "getFreeCallCount", GetFreeCallCount);

char* data = new char;

exports->Set(context,
v8::String::NewFromUtf8(
isolate, "buffer", v8::NewStringType::kNormal)
Expand All @@ -30,6 +32,7 @@ void Initialize(Local<Object> exports,
data,
sizeof(data),
[](char* data, void* hint) {
delete data;
free_call_count++;
},
nullptr).ToLocalChecked()).Check();
Expand Down
20 changes: 16 additions & 4 deletions test/js-native-api/test_typedarray/test_typedarray.c
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#define NAPI_EXPERIMENTAL
#include <js_native_api.h>
#include <string.h>
#include <stdlib.h>
#include "../common.h"

static napi_value Multiply(napi_env env, napi_callback_info info) {
Expand Down Expand Up @@ -74,22 +75,33 @@ static napi_value Multiply(napi_env env, napi_callback_info info) {
return output_array;
}

static void FinalizeCallback(napi_env env,
void* finalize_data,
void* finalize_hint)
{
free(finalize_data);
}

static napi_value External(napi_env env, napi_callback_info info) {
static int8_t externalData[] = {0, 1, 2};
const uint8_t nElem = 3;
int8_t* externalData = malloc(nElem*sizeof(int8_t));
externalData[0] = 0;
externalData[1] = 1;
externalData[2] = 2;

napi_value output_buffer;
NAPI_CALL(env, napi_create_external_arraybuffer(
env,
externalData,
sizeof(externalData),
NULL, // finalize_callback
nElem*sizeof(int8_t),
FinalizeCallback,
NULL, // finalize_hint
&output_buffer));

napi_value output_array;
NAPI_CALL(env, napi_create_typedarray(env,
napi_int8_array,
sizeof(externalData) / sizeof(int8_t),
nElem,
output_buffer,
0,
&output_array));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#include <stdio.h>
#include <stdlib.h>
#include <node_api.h>
#include <assert.h>
#include "../../js-native-api/common.h"

uint32_t free_call_count = 0;
char data[] = "hello";

napi_value GetFreeCallCount(napi_env env, napi_callback_info info) {
napi_value value;
Expand All @@ -13,7 +13,7 @@ napi_value GetFreeCallCount(napi_env env, napi_callback_info info) {
}

static void finalize_cb(napi_env env, void* finalize_data, void* hint) {
assert(finalize_data == data);
free(finalize_data);
free_call_count++;
}

Expand All @@ -29,6 +29,9 @@ NAPI_MODULE_INIT() {
// rather than a Node.js Buffer, since testing the latter would only test
// the same code paths and not the ones specific to N-API.
napi_value buffer;

char* data = malloc(sizeof(char));

NAPI_CALL(env, napi_create_external_arraybuffer(
env,
data,
Expand Down