Skip to content

Commit

Permalink
worker: fix crash when SharedArrayBuffer outlives creating thread
Browse files Browse the repository at this point in the history
Keep a reference to the `ArrayBuffer::Allocator` alive for at least
as long as a `SharedArrayBuffer` allocated by it lives.

Refs: #28788
Fixes: #28777
Fixes: #28773

PR-URL: #29190
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Colin Ihrig <[email protected]>
  • Loading branch information
addaleax authored and targos committed Aug 20, 2019
1 parent c5edeb9 commit d4e397a
Show file tree
Hide file tree
Showing 6 changed files with 83 additions and 9 deletions.
13 changes: 8 additions & 5 deletions src/node_worker.cc
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ Worker::Worker(Environment* env,
per_isolate_opts_(per_isolate_opts),
exec_argv_(exec_argv),
platform_(env->isolate_data()->platform()),
array_buffer_allocator_(ArrayBufferAllocator::Create()),
start_profiler_idle_notifier_(env->profiler_idle_notifier_started()),
thread_id_(Environment::AllocateThreadId()),
env_vars_(env->env_vars()) {
Expand Down Expand Up @@ -102,17 +103,20 @@ bool Worker::is_stopped() const {
return stopped_;
}

std::shared_ptr<ArrayBufferAllocator> Worker::array_buffer_allocator() {
return array_buffer_allocator_;
}

// This class contains data that is only relevant to the child thread itself,
// and only while it is running.
// (Eventually, the Environment instance should probably also be moved here.)
class WorkerThreadData {
public:
explicit WorkerThreadData(Worker* w)
: w_(w),
array_buffer_allocator_(ArrayBufferAllocator::Create()) {
: w_(w) {
CHECK_EQ(uv_loop_init(&loop_), 0);

Isolate* isolate = NewIsolate(array_buffer_allocator_.get(), &loop_);
Isolate* isolate = NewIsolate(w->array_buffer_allocator_.get(), &loop_);
CHECK_NOT_NULL(isolate);

{
Expand All @@ -124,7 +128,7 @@ class WorkerThreadData {
isolate_data_.reset(CreateIsolateData(isolate,
&loop_,
w_->platform_,
array_buffer_allocator_.get()));
w->array_buffer_allocator_.get()));
CHECK(isolate_data_);
if (w_->per_isolate_opts_)
isolate_data_->set_options(std::move(w_->per_isolate_opts_));
Expand Down Expand Up @@ -166,7 +170,6 @@ class WorkerThreadData {
private:
Worker* const w_;
uv_loop_t loop_;
std::unique_ptr<ArrayBufferAllocator> array_buffer_allocator_;
DeleteFnPtr<IsolateData, FreeIsolateData> isolate_data_;

friend class Worker;
Expand Down
2 changes: 2 additions & 0 deletions src/node_worker.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class Worker : public AsyncWrap {
SET_SELF_SIZE(Worker)

bool is_stopped() const;
std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator();

static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void CloneParentEnvVars(
Expand All @@ -59,6 +60,7 @@ class Worker : public AsyncWrap {
std::vector<std::string> argv_;

MultiIsolatePlatform* platform_;
std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator_;
v8::Isolate* isolate_ = nullptr;
bool start_profiler_idle_notifier_;
uv_thread_t tid_;
Expand Down
17 changes: 14 additions & 3 deletions src/sharedarraybuffer_metadata.cc
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#include "sharedarraybuffer_metadata.h"

#include "base_object-inl.h"
#include "memory_tracker-inl.h"
#include "node_errors.h"
#include "node_worker.h"
#include "util-inl.h"

#include <utility>
Expand Down Expand Up @@ -91,8 +93,16 @@ SharedArrayBufferMetadata::ForSharedArrayBuffer(
return nullptr;
}

// If the SharedArrayBuffer is coming from a Worker, we need to make sure
// that the corresponding ArrayBuffer::Allocator lives at least as long as
// the SharedArrayBuffer itself.
worker::Worker* w = env->worker_context();
std::shared_ptr<v8::ArrayBuffer::Allocator> allocator =
w != nullptr ? w->array_buffer_allocator() : nullptr;

SharedArrayBuffer::Contents contents = source->Externalize();
SharedArrayBufferMetadataReference r(new SharedArrayBufferMetadata(contents));
SharedArrayBufferMetadataReference r(
new SharedArrayBufferMetadata(contents, allocator));
if (r->AssignToSharedArrayBuffer(env, context, source).IsNothing())
return nullptr;
return r;
Expand All @@ -114,8 +124,9 @@ Maybe<bool> SharedArrayBufferMetadata::AssignToSharedArrayBuffer(
}

SharedArrayBufferMetadata::SharedArrayBufferMetadata(
const SharedArrayBuffer::Contents& contents)
: contents_(contents) { }
const SharedArrayBuffer::Contents& contents,
std::shared_ptr<v8::ArrayBuffer::Allocator> allocator)
: contents_(contents), allocator_(allocator) { }

SharedArrayBufferMetadata::~SharedArrayBufferMetadata() {
contents_.Deleter()(contents_.Data(),
Expand Down
5 changes: 4 additions & 1 deletion src/sharedarraybuffer_metadata.h
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@ class SharedArrayBufferMetadata
SharedArrayBufferMetadata(const SharedArrayBufferMetadata&) = delete;

private:
explicit SharedArrayBufferMetadata(const v8::SharedArrayBuffer::Contents&);
SharedArrayBufferMetadata(
const v8::SharedArrayBuffer::Contents&,
std::shared_ptr<v8::ArrayBuffer::Allocator>);

// Attach a lifetime tracker object with a reference count to `target`.
v8::Maybe<bool> AssignToSharedArrayBuffer(
Expand All @@ -55,6 +57,7 @@ class SharedArrayBufferMetadata
v8::Local<v8::SharedArrayBuffer> target);

v8::SharedArrayBuffer::Contents contents_;
std::shared_ptr<v8::ArrayBuffer::Allocator> allocator_;
};

} // namespace worker
Expand Down
33 changes: 33 additions & 0 deletions test/parallel/test-worker-arraybuffer-zerofill.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';
require('../common');
const assert = require('assert');
const { Worker } = require('worker_threads');

// Make sure that allocating uninitialized ArrayBuffers in one thread does not
// affect the zero-initialization in other threads.

const w = new Worker(`
const { parentPort } = require('worker_threads');
function post() {
const uint32array = new Uint32Array(64);
parentPort.postMessage(uint32array.reduce((a, b) => a + b));
}
setInterval(post, 0);
`, { eval: true });

function allocBuffers() {
Buffer.allocUnsafe(32 * 1024 * 1024);
}

const interval = setInterval(allocBuffers, 0);

let messages = 0;
w.on('message', (sum) => {
assert.strictEqual(sum, 0);
if (messages++ === 100) {
clearInterval(interval);
w.terminate();
}
});
22 changes: 22 additions & 0 deletions test/parallel/test-worker-sharedarraybuffer-from-worker-thread.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
'use strict';
const common = require('../common');
const assert = require('assert');
const { Worker } = require('worker_threads');

// Regression test for https://github.com/nodejs/node/issues/28777
// Make sure that SharedArrayBuffers created in Worker threads are accessible
// after the creating thread ended.

const w = new Worker(`
const { parentPort } = require('worker_threads');
const sharedArrayBuffer = new SharedArrayBuffer(4);
parentPort.postMessage(sharedArrayBuffer);
`, { eval: true });

let sharedArrayBuffer;
w.once('message', common.mustCall((message) => sharedArrayBuffer = message));
w.once('exit', common.mustCall(() => {
const uint8array = new Uint8Array(sharedArrayBuffer);
uint8array[0] = 42;
assert.deepStrictEqual(uint8array, new Uint8Array([42, 0, 0, 0]));
}));

0 comments on commit d4e397a

Please sign in to comment.