Skip to content
Open
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
9 changes: 9 additions & 0 deletions src/histogram.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3211,6 +3211,15 @@ void HistogramImpl::DoImport(const FunctionCallbackInfo<Value>& args) {
static_cast<const uint8_t*>(backing->Data()) + input->ByteOffset();
size_t len = input->ByteLength();

// Another thread can write to a SharedArrayBuffer while it is parsed, so
// parse a private copy instead.
std::unique_ptr<uint8_t[]> data_copy;
if (input->Buffer()->IsSharedArrayBuffer() && len > 0) {
data_copy = std::make_unique_for_overwrite<uint8_t[]>(len);
memcpy(data_copy.get(), data, len);
data = data_copy.get();
}

auto histogram = Histogram::Import(data, len);
if (!histogram) {
THROW_ERR_INVALID_ARG_VALUE(env, "Invalid histogram export data");
Expand Down
33 changes: 33 additions & 0 deletions test/parallel/test-perf-hooks-histogram-import-shared.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'use strict';

require('../common');
const assert = require('node:assert');
const { createHistogram, importHistogram } = require('node:perf_hooks');
const kInvalid = { code: 'ERR_INVALID_ARG_VALUE' };

{
// Data in a SharedArrayBuffer, including a sliced view, imports the same way
// as data in an ArrayBuffer.
const h = createHistogram();
h.record(1);
h.record(42);
h.record(1000);
const exported = h.export();

for (const offset of [0, 3]) {
const sab = new SharedArrayBuffer(exported.length + offset + 5);
new Uint8Array(sab).fill(0xff);
const view = new Uint8Array(sab, offset, exported.length);
view.set(exported);
const imported = importHistogram(view);
assert.deepStrictEqual(imported.export(), exported);

// Later writes do not change the imported histogram.
view.fill(0);
assert.deepStrictEqual(imported.export(), exported);
assert.throws(() => importHistogram(view), kInvalid);
}

assert.throws(
() => importHistogram(new Uint8Array(new SharedArrayBuffer(0))), kInvalid);
}