exports.binding = function(bindingName) { try { const { internalBinding } = require('internal/test/binding'); return internalBinding(bindingName); } catch { return process.binding(bindingName); } };
})).listen(common.PIPE, common.mustCall(() => { const binding = internalBinding('pipe_wrap'); const handle = new binding.Pipe(binding.constants.SOCKET); testInitialized(handle, 'Pipe'); const req = new binding.PipeConnectWrap(); testUninitialized(req, 'PipeConnectWrap'); req.address = common.PIPE; req.oncomplete = common.mustCall(() => handle.close()); handle.connect(req, req.address, req.oncomplete); testInitialized(req, 'PipeConnectWrap'); }));
function main({ type, argument, version, n }) { // For testing, if supplied with an empty type, default to ArrayBufferView. type = type || 'ArrayBufferView'; const { internalBinding } = require('internal/test/binding'); const util = internalBinding('util'); const types = require('internal/util/types'); const func = { native: util, js: types }[version][`is${type}`]; const arg = args[type][argument]; bench.start(); for (var i = 0; i < n; i++) { func(arg); } bench.end(n); }
function main({ len, n }) { const { internalBinding } = require('internal/test/binding'); const { HTTPParser } = internalBinding('http_parser'); const REQUEST = HTTPParser.REQUEST; const kOnHeaders = HTTPParser.kOnHeaders | 0; const kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0; const kOnBody = HTTPParser.kOnBody | 0; const kOnMessageComplete = HTTPParser.kOnMessageComplete | 0; const CRLF = '\r\n'; function processHeader(header, n) { const parser = newParser(REQUEST); bench.start(); for (var i = 0; i < n; i++) { parser.execute(header, 0, header.length); parser.reinitialize(REQUEST, i > 0); } bench.end(n); } function newParser(type) { const parser = new HTTPParser(type); parser.headers = []; parser[kOnHeaders] = function() { }; parser[kOnHeadersComplete] = function() { }; parser[kOnBody] = function() { }; parser[kOnMessageComplete] = function() { }; return parser; } let header = `GET /hello HTTP/1.1${CRLF}Content-Type: text/plain${CRLF}`; for (var i = 0; i < len; i++) { header += `X-Filler${i}: ${Math.random().toString(36).substr(2)}${CRLF}`; } header += CRLF; processHeader(Buffer.from(header), n); }
// Flags: --expose-internals --expose-gc 'use strict'; require('../common'); const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); const { WeakReference } = internalBinding('util'); let obj = { hello: 'world' }; const ref = new WeakReference(obj); assert.strictEqual(ref.get(), obj); setImmediate(() => { obj = null; global.gc(); assert.strictEqual(ref.get(), undefined); });
// Flags: --expose-internals 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); const crypto = require('crypto'); const { internalBinding } = require('internal/test/binding'); if (typeof internalBinding('crypto').scrypt !== 'function') common.skip('no scrypt support'); const good = [ // Zero-length key is legal, functions as a parameter validation check. { pass: '', salt: '', keylen: 0, N: 16, p: 1, r: 1, expected: '', }, // Test vectors from https://tools.ietf.org/html/rfc7914#page-13 that // should pass. Note that the test vector with N=1048576 is omitted // because it takes too long to complete and uses over 1 GB of memory. { pass: '', salt: '', keylen: 64,
// Flags: --expose-internals 'use strict'; const common = require('../common'); const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); const cares = internalBinding('cares_wrap'); const { UV_ENOENT } = internalBinding('uv'); const dns = require('dns'); // Stub `getnameinfo` to *always* error. cares.getnameinfo = () => UV_ENOENT; assert.throws( () => dns.lookupService('127.0.0.1', 80, common.mustNotCall()), { code: 'ENOENT', message: 'getnameinfo ENOENT 127.0.0.1', syscall: 'getnameinfo' } );
// Flags: --experimental-vm-modules --expose-internals 'use strict'; require('../common'); const fixtures = require('../common/fixtures'); const assert = require('assert'); const { types, inspect } = require('util'); const vm = require('vm'); const { internalBinding } = require('internal/test/binding'); const { JSStream } = internalBinding('js_stream'); const external = (new JSStream())._externalStream; const wasmBuffer = fixtures.readSync('test.wasm'); for (const [ value, _method ] of [ [ external, 'isExternal' ], [ new Date() ], [ (function() { return arguments; })(), 'isArgumentsObject' ], [ new Boolean(), 'isBooleanObject' ], [ new Number(), 'isNumberObject' ], [ new String(), 'isStringObject' ], [ Object(Symbol()), 'isSymbolObject' ], [ Object(BigInt(0)), 'isBigIntObject' ], [ new Error(), 'isNativeError' ], [ new RegExp() ], [ async function() {}, 'isAsyncFunction' ], [ function*() {}, 'isGeneratorFunction' ], [ (function*() {})(), 'isGeneratorObject' ], [ Promise.resolve() ], [ new Map() ], [ new Set() ], [ (new Map())[Symbol.iterator](), 'isMapIterator' ],
// Flags: --expose-internals 'use strict'; const common = require('../common'); if (common.isWindows) common.skip('Does not support wrapping sockets with fd on Windows'); const assert = require('assert'); const net = require('net'); const path = require('path'); const { internalBinding } = require('internal/test/binding'); const { Pipe, constants: PipeConstants } = internalBinding('pipe_wrap'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); function testClients(getSocketOpt, getConnectOpt, getConnectCb) { const cloneOptions = (index) => Object.assign({}, getSocketOpt(index), getConnectOpt(index)); return [ net.connect(cloneOptions(0), getConnectCb(0)), net.connect(cloneOptions(1)) .on('connect', getConnectCb(1)), net.createConnection(cloneOptions(2), getConnectCb(2)), net.createConnection(cloneOptions(3)) .on('connect', getConnectCb(3)), new net.Socket(getSocketOpt(4)).connect(getConnectOpt(4), getConnectCb(4)), new net.Socket(getSocketOpt(5)).connect(getConnectOpt(5)) .on('connect', getConnectCb(5)) ]; }
// Flags: --expose-internals --no-warnings 'use strict'; // see also test/sequential/test-async-wrap-getasyncid.js const common = require('../common'); const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); const { TTYWRAP } = internalBinding('async_wrap').Providers; const tty_wrap = internalBinding('tty_wrap'); const providers = { TTYWRAP }; // Make sure that the TTYWRAP Provider is tested. { const hooks = require('async_hooks').createHook({ init(id, type) { if (type === 'NONE') throw new Error('received a provider type of NONE'); delete providers[type]; }, }).enable(); process.on('beforeExit', common.mustCall(() => { process.removeAllListeners('uncaughtException'); hooks.disable(); const objKeys = Object.keys(providers); if (objKeys.length > 0) process._rawDebug(objKeys); assert.strictEqual(objKeys.length, 0); })); }
'use strict'; require('../common'); const assert = require('assert'); const os = require('os'); const cp = require('child_process'); if (process.argv[2] === 'child') { const { internalBinding } = require('internal/test/binding'); // This is the heart of the test. new (internalBinding('zlib').Zlib)(0).init(1, 2, 3, 4, 5); } else { const child = cp.spawnSync( `${process.execPath}`, ['--expose-internals', `${__filename}`, 'child']); assert.strictEqual(child.stdout.toString(), ''); assert.ok(child.stderr.includes( 'WARNING: You are likely using a version of node-tar or npm that ' + `is incompatible with this version of Node.js.${os.EOL}` + 'Please use either the version of npm that is bundled with Node.js, or ' + 'a version of npm (> 5.5.1 or < 5.4.0) or node-tar (> 4.0.1) that is ' + `compatible with Node.js 9 and above.${os.EOL}`)); }
'use strict'; // Flags: --expose-internals require('../common'); const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); assert.throws( function() { process.binding('test'); }, /No such module: test/ ); internalBinding('buffer');
HTTP2_HEADER_TRAILER, HTTP2_HEADER_VARY, HTTP2_HEADER_VIA, HTTP2_HEADER_WARNING, HTTP2_HEADER_WWW_AUTHENTICATE, HTTP2_HEADER_X_FRAME_OPTIONS, HTTP2_HEADER_CONNECTION, HTTP2_HEADER_UPGRADE, HTTP2_HEADER_HTTP2_SETTINGS, HTTP2_HEADER_TE, HTTP2_HEADER_TRANSFER_ENCODING, HTTP2_HEADER_HOST, HTTP2_HEADER_KEEP_ALIVE, HTTP2_HEADER_PROXY_CONNECTION } = internalBinding('http2').constants; { const headers = { 'abc': 1, ':status': 200, ':path': 'abc', 'xyz': [1, '2', { toString() { return '3'; } }, 4], 'foo': [], 'BAR': [1] }; assert.deepStrictEqual( mapToHeaders(headers), [ [ ':path', 'abc', ':status', '200', 'abc', '1', 'xyz', '1', 'xyz', '2', 'xyz', '3', 'xyz', '4', 'bar', '1', '' ].join('\0'), 8 ]
// Flags: --expose-internals 'use strict'; const { internalBinding } = require('internal/test/binding'); const common = require('../common'); const os = require('os'); const { hasSmallICU } = internalBinding('config'); if (!(common.hasIntl && hasSmallICU)) common.skip('missing Intl'); const assert = require('assert'); const { spawnSync } = require('child_process'); const expected = 'could not initialize ICU (check NODE_ICU_DATA or ' + `--icu-data-dir parameters)${os.EOL}`; { const child = spawnSync(process.execPath, ['--icu-data-dir=/', '-e', '0']); assert(child.stderr.toString().includes(expected)); } { const env = Object.assign({}, process.env, { NODE_ICU_DATA: '/' }); const child = spawnSync(process.execPath, ['-e', '0'], { env }); assert(child.stderr.toString().includes(expected)); }
// Flags: --expose-internals 'use strict'; const common = require('../common'); const Countdown = require('../common/countdown'); const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); const { observerCounts: counts } = internalBinding('performance'); const { performance, PerformanceObserver, constants } = require('perf_hooks'); const { NODE_PERFORMANCE_ENTRY_TYPE_NODE, NODE_PERFORMANCE_ENTRY_TYPE_MARK, NODE_PERFORMANCE_ENTRY_TYPE_MEASURE, NODE_PERFORMANCE_ENTRY_TYPE_GC, NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION, } = constants; assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_NODE], 0); assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MARK], 0); assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MEASURE], 0); assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_GC], 0); assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION], 0); {
// Flags: --expose-internals 'use strict'; const common = require('../common'); const assert = require('assert'); const dgram = require('dgram'); const { internalBinding } = require('internal/test/binding'); const { UV_UNKNOWN } = internalBinding('uv'); const { kStateSymbol } = require('internal/dgram'); const mockError = new Error('mock DNS error'); function getSocket(callback) { const socket = dgram.createSocket('udp4'); socket.on('message', common.mustNotCall('Should not receive any messages.')); socket.bind(common.mustCall(() => { socket[kStateSymbol].handle.lookup = function(address, callback) { process.nextTick(callback, mockError); }; callback(socket); })); return socket; } getSocket((socket) => { socket.on('error', common.mustCall((err) => { socket.close(); assert.strictEqual(err, mockError); })); socket.send('foo', socket.address().port, 'localhost');
'use strict'; const { internalBinding } = require('internal/test/binding'); const { moduleCategories: { canBeRequired } } = internalBinding('native_module'); for (const key of canBeRequired) { require(key); }
'use strict'; // Flags: --expose-internals const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const http2 = require('http2'); const { internalBinding } = require('internal/test/binding'); const { constants, Http2Stream, nghttp2ErrorString } = internalBinding('http2'); const { NghttpError } = require('internal/http2/util'); // tests error handling within additionalHeaders // - every other NGHTTP2 error from binding (should emit stream error) const specificTestKeys = []; const specificTests = []; const genericTests = Object.getOwnPropertyNames(constants) .filter((key) => ( key.indexOf('NGHTTP2_ERR') === 0 && specificTestKeys.indexOf(key) < 0 )) .map((key) => ({ ngError: constants[key], error: { code: 'ERR_HTTP2_ERROR', type: NghttpError, name: 'Error [ERR_HTTP2_ERROR]',
// Flags: --expose-internals 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const assert = require('assert'); const spawnSync = require('child_process').spawnSync; const path = require('path'); const fixtures = require('../common/fixtures'); const { internalBinding } = require('internal/test/binding'); const { fipsMode } = internalBinding('config'); const FIPS_ENABLED = 1; const FIPS_DISABLED = 0; const FIPS_ERROR_STRING = 'Error [ERR_CRYPTO_FIPS_UNAVAILABLE]: Cannot set FIPS mode in a ' + 'non-FIPS build.'; const FIPS_ERROR_STRING2 = 'Error [ERR_CRYPTO_FIPS_FORCED]: Cannot set FIPS mode, it was forced with ' + '--force-fips at startup.'; const OPTION_ERROR_STRING = 'bad option'; const CNF_FIPS_ON = fixtures.path('openssl_fips_enabled.cnf'); const CNF_FIPS_OFF = fixtures.path('openssl_fips_disabled.cnf'); let num_children_ok = 0; function compiledWithFips() { return fipsMode ? true : false; }
'use strict'; // Flags: --expose-internals const common = require('../common'); const { internalBinding } = require('internal/test/binding'); if (!common.enoughTestMem) common.skip('intensive toString tests due to memory confinements'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); const cp = require('child_process'); const kStringMaxLength = internalBinding('buffer').kStringMaxLength; if (common.isAIX && (Number(cp.execSync('ulimit -f')) * 512) < kStringMaxLength) common.skip('intensive toString tests due to file size confinements'); const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); const file = path.join(tmpdir.path, 'toobig.txt'); const stream = fs.createWriteStream(file, { flags: 'a' }); const size = kStringMaxLength / 200; const a = Buffer.alloc(size, 'a'); for (let i = 0; i < 201; i++) { stream.write(a); }
// Flags: --expose-internals 'use strict'; const common = require('../common'); const assert = require('assert'); const initHooks = require('./init-hooks'); const { checkInvocations } = require('./hook-checks'); const hooks = initHooks(); hooks.enable(); const { internalBinding } = require('internal/test/binding'); const { Zlib } = internalBinding('zlib'); const constants = require('zlib').constants; const handle = new Zlib(constants.DEFLATE); const as = hooks.activitiesOfTypes('ZLIB'); assert.strictEqual(as.length, 1); const hdl = as[0]; assert.strictEqual(hdl.type, 'ZLIB'); assert.strictEqual(typeof hdl.uid, 'number'); assert.strictEqual(typeof hdl.triggerAsyncId, 'number'); checkInvocations(hdl, { init: 1 }, 'when created handle'); // Store all buffers together so that they do not get // garbage collected. const buffers = { writeResult: new Uint32Array(2), dictionary: new Uint8Array(0), inBuf: new Uint8Array([0x78]),
// Flags: --expose-internals 'use strict'; const { internalBinding } = require('internal/test/binding'); // Monkey patch before requiring anything class DummyParser { constructor(type) { this.test_type = type; } } DummyParser.REQUEST = Symbol(); internalBinding('http_parser').HTTPParser = DummyParser; const common = require('../common'); const assert = require('assert'); const { spawn } = require('child_process'); const { parsers } = require('_http_common'); // Test _http_common was not loaded before monkey patching const parser = parsers.alloc(); assert.strictEqual(parser instanceof DummyParser, true); assert.strictEqual(parser.test_type, DummyParser.REQUEST); if (process.argv[2] !== 'child') { // Also test in a child process with IPC (specific case of https://github.com/nodejs/node/issues/23716) const child = spawn(process.execPath, [ '--expose-internals', __filename, 'child' ], { stdio: ['inherit', 'inherit', 'inherit', 'ipc']
// Flags: --expose-internals 'use strict'; require('../common'); const assert = require('assert'); const util = require('util'); const { internalBinding } = require('internal/test/binding'); const processUtil = internalBinding('util'); const opts = { showProxy: true }; let proxyObj; let called = false; const target = { [util.inspect.custom](depth, { showProxy }) { if (showProxy === false) { called = true; if (proxyObj !== this) { throw new Error('Failed'); } } return [1, 2, 3]; } }; const handler = { getPrototypeOf() { throw new Error('getPrototypeOf'); }, setPrototypeOf() { throw new Error('setPrototypeOf'); }, isExtensible() { throw new Error('isExtensible'); }, preventExtensions() { throw new Error('preventExtensions'); }, getOwnPropertyDescriptor() { throw new Error('getOwnPropertyDescriptor'); }, defineProperty() { throw new Error('defineProperty'); }, has() { throw new Error('has'); },
// Flags: --expose-internals 'use strict'; const common = require('../common'); const assert = require('assert'); const { internalBinding } = require('internal/test/binding'); const cares = internalBinding('cares_wrap'); // Stub `getaddrinfo` to *always* error. This has to be done before we load the // `dns` module to guarantee that the `dns` module uses the stub. cares.getaddrinfo = () => internalBinding('uv').UV_ENOMEM; const dns = require('dns'); const dnsPromises = dns.promises; { const err = { code: 'ERR_INVALID_ARG_TYPE', type: TypeError, message: /^The "hostname" argument must be of type string\. Received type number/ }; common.expectsError(() => dns.lookup(1, {}), err); common.expectsError(() => dnsPromises.lookup(1, {}), err); } // This also verifies different expectWarning notations. common.expectWarning({ // For 'internal/test/binding' module. 'internal/test/binding': [ 'These APIs are for internal testing only. Do not use them.' ],
// This test is designed to fail with a segmentation fault in Node.js 4.1.0 and // execute without issues in Node.js 4.1.1 and up. // Flags: --expose-internals 'use strict'; const common = require('../common'); const assert = require('assert'); const httpCommon = require('_http_common'); const { internalBinding } = require('internal/test/binding'); const is_reused_symbol = require('internal/freelist').symbols.is_reused_symbol; const { HTTPParser } = internalBinding('http_parser'); const net = require('net'); const COUNT = httpCommon.parsers.max + 1; const parsers = new Array(COUNT); for (let i = 0; i < parsers.length; i++) parsers[i] = httpCommon.parsers.alloc(); let gotRequests = 0; let gotResponses = 0; function execAndClose() { if (parsers.length === 0) return; process.stdout.write('.'); const parser = parsers.pop(); parser.reinitialize(HTTPParser.RESPONSE, parser[is_reused_symbol]); const socket = net.connect(common.PORT);
cares.getaddrinfo = () => internalBinding('uv').UV_ENOMEM;
// in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; require('../common'); const assert = require('assert'); const fs = require('fs'); const { internalBinding } = require('internal/test/binding'); const { UV_EBADF } = internalBinding('uv'); // Ensure that (read|write|append)FileSync() closes the file descriptor fs.openSync = function() { return 42; }; fs.closeSync = function(fd) { assert.strictEqual(fd, 42); close_called++; }; fs.readSync = function() { throw new Error('BAM'); }; fs.writeSync = function() { throw new Error('BAM'); };
() => { const source = 'module.exports = require("internal/bootstrap/loaders")'; const { internalBinding } = require('internal/test/binding'); internalBinding('natives').owo = source; require('owo'); }, {
// Flags: --expose-internals 'use strict'; // This verifies the error thrown by fs.watch. const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const tmpdir = require('../common/tmpdir'); const path = require('path'); const nonexistentFile = path.join(tmpdir.path, 'non-existent'); const { internalBinding } = require('internal/test/binding'); const { UV_ENODEV, UV_ENOENT } = internalBinding('uv'); tmpdir.refresh(); { const validateError = (err) => { assert.strictEqual(err.path, nonexistentFile); assert.strictEqual(err.filename, nonexistentFile); assert.strictEqual(err.syscall, 'watch'); if (err.code === 'ENOENT') { assert.strictEqual( err.message, `ENOENT: no such file or directory, watch '${nonexistentFile}'`); assert.strictEqual(err.errno, UV_ENOENT); assert.strictEqual(err.code, 'ENOENT'); } else { // AIX
// Flags: --expose-internals 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const util = require('util'); const { internalBinding } = require('internal/test/binding'); const TLSWrap = internalBinding('tls_wrap').TLSWrap; // This will abort if internal pointer is not set to nullptr. util.inspect(new TLSWrap());