node/test/parallel/test-buffer-alloc-unsafe-is-uninitialized.js
Joyee Cheung 1f6b681bf2 src: fix timing of snapshot serialize callback
Previously the addAfterUserSerailizeCallback() wasn't
ready to be used for building the built-in snapshot.
This patch initializes the callbacks at the time
lib/internal/v8/start_snapshot.js is loaded, so that
these callbacks get run correctly when building the
built-in snapshot.

Currently when building the built-in snapshot,
addAfterUserSerializeCallback() is only used by createUnsafeBuffer(),
other usages can only come from user-land snapshots,
which is covered by tests, but what gets run by the
built-in snapshot building process is less visible, and the
path used by createUnsafeBuffer() isn't reliably visible in user
land either. This adds an internal usage counter in debug builds
to verify this path when building the built-in snapshot.

PR-URL: https://github.com/nodejs/node/pull/60434
Fixes: https://github.com/nodejs/node/issues/60423
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Richard Lau <richard.lau@ibm.com>
2025-10-28 00:15:55 +00:00

24 lines
1.3 KiB
JavaScript

// Flags: --expose-internals
// Verifies that Buffer.allocUnsafe() indeed allocates uninitialized memory by checking
// the usage count of the relevant native allocator code path.
'use strict';
const common = require('../common');
if (!common.isDebug) {
common.skip('Only works in debug mode');
}
const { internalBinding } = require('internal/test/binding');
const { getGenericUsageCount } = internalBinding('debug');
const assert = require('assert');
const initialUninitializedCount = getGenericUsageCount('NodeArrayBufferAllocator.Allocate.Uninitialized');
const initialZeroFilledCount = getGenericUsageCount('NodeArrayBufferAllocator.Allocate.ZeroFilled');
Buffer.allocUnsafe(Buffer.poolSize + 1);
// We can't reliably check the contents of the buffer here because the OS or memory allocator
// used might zero-fill memory for us, or they might happen to return reused memory that was
// previously used by a process that zero-filled it. So instead we just check the usage counts.
const newUninitializedCount = getGenericUsageCount('NodeArrayBufferAllocator.Allocate.Uninitialized');
const newZeroFilledCount = getGenericUsageCount('NodeArrayBufferAllocator.Allocate.ZeroFilled');
assert.notStrictEqual(newUninitializedCount, initialUninitializedCount);
assert.strictEqual(newZeroFilledCount, initialZeroFilledCount);