Skip to content

Commit 41e09ec

Browse files
addaleaxrichardlau
authored andcommitted
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 f50b9c1 commit 41e09ec

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

lib/internal/child_process/serialization.js

+10-3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ const { StringDecoder } = require('string_decoder');
1010
const v8 = require('v8');
1111
const { isArrayBufferView } = require('internal/util/types');
1212
const assert = require('internal/assert');
13+
const { streamBaseState, kLastWriteWasAsync } = internalBinding('stream_wrap');
1314

1415
const kMessageBuffer = Symbol('kMessageBuffer');
1516
const kJSONBuffer = Symbol('kJSONBuffer');
@@ -80,10 +81,16 @@ const advanced = {
8081
const serializedMessage = ser.releaseBuffer();
8182
const sizeBuffer = Buffer.allocUnsafe(4);
8283
sizeBuffer.writeUInt32BE(serializedMessage.length);
83-
return channel.writeBuffer(req, Buffer.concat([
84+
85+
const buffer = Buffer.concat([
8486
sizeBuffer,
85-
serializedMessage
86-
]), handle);
87+
serializedMessage,
88+
]);
89+
const result = channel.writeBuffer(req, buffer, handle);
90+
// Mirror what stream_base_commons.js does for Buffer retention.
91+
if (streamBaseState[kLastWriteWasAsync])
92+
req.buffer = buffer;
93+
return result;
8794
},
8895
};
8996

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)