Skip to content

Commit 717a8b6

Browse files
addaleaxdanielleadams
authored andcommittedMay 31, 2021
child_process: retain reference to data with advanced serialization
Do the same thing we do for other streams, and retain a reference to the Buffer that was sent over IPC while the write request is active, so that it doesn’t get garbage collected while the data is still in flight. (This is a good example of why it’s a bad idea that we’re not re-using the general streams implementation for IPC and instead maintain separate usage of the low-level I/O primitives.) Fixes: #34797 PR-URL: #38728 Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Minwoo Jung <[email protected]>
1 parent 7a9d0fd commit 717a8b6

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed
 

‎lib/internal/child_process/serialization.js

+9-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const { StringDecoder } = require('string_decoder');
1212
const v8 = require('v8');
1313
const { isArrayBufferView } = require('internal/util/types');
1414
const assert = require('internal/assert');
15+
const { streamBaseState, kLastWriteWasAsync } = internalBinding('stream_wrap');
1516

1617
const kMessageBuffer = Symbol('kMessageBuffer');
1718
const kJSONBuffer = Symbol('kJSONBuffer');
@@ -82,10 +83,16 @@ const advanced = {
8283
const serializedMessage = ser.releaseBuffer();
8384
const sizeBuffer = Buffer.allocUnsafe(4);
8485
sizeBuffer.writeUInt32BE(serializedMessage.length);
85-
return channel.writeBuffer(req, Buffer.concat([
86+
87+
const buffer = Buffer.concat([
8688
sizeBuffer,
8789
serializedMessage,
88-
]), handle);
90+
]);
91+
const result = channel.writeBuffer(req, buffer, handle);
92+
// Mirror what stream_base_commons.js does for Buffer retention.
93+
if (streamBaseState[kLastWriteWasAsync])
94+
req.buffer = buffer;
95+
return result;
8996
},
9097
};
9198

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
const child_process = require('child_process');
5+
6+
// Regression test for https://github.com/nodejs/node/issues/34797
7+
const eightMB = 8 * 1024 * 1024;
8+
9+
if (process.argv[2] === 'child') {
10+
for (let i = 0; i < 4; i++) {
11+
process.send(new Uint8Array(eightMB).fill(i));
12+
}
13+
} else {
14+
const child = child_process.spawn(process.execPath, [__filename, 'child'], {
15+
stdio: ['inherit', 'inherit', 'inherit', 'ipc'],
16+
serialization: 'advanced'
17+
});
18+
const received = [];
19+
child.on('message', common.mustCall((chunk) => {
20+
assert.deepStrictEqual(chunk, new Uint8Array(eightMB).fill(chunk[0]));
21+
22+
received.push(chunk[0]);
23+
if (received.length === 4) {
24+
assert.deepStrictEqual(received, [0, 1, 2, 3]);
25+
}
26+
}, 4));
27+
}

0 commit comments

Comments
 (0)