Upload Kmake

This commit is contained in:
Gorochu
2026-05-26 23:36:42 -07:00
parent ba051b2f74
commit 555ec72358
41615 changed files with 13344630 additions and 1 deletions

View File

@ -0,0 +1,366 @@
'use strict';
const {
ArrayPrototypeForEach,
ArrayPrototypeJoin,
ArrayPrototypeMap,
ArrayPrototypePop,
ArrayPrototypePushApply,
ArrayPrototypeShift,
ArrayPrototypeSlice,
FunctionPrototypeBind,
Number,
Promise,
PromisePrototypeThen,
PromiseResolve,
Proxy,
RegExpPrototypeExec,
RegExpPrototypeSymbolSplit,
StringPrototypeEndsWith,
StringPrototypeSplit,
} = primordials;
const { spawn } = require('child_process');
const { EventEmitter } = require('events');
const net = require('net');
const util = require('util');
const {
setInterval: pSetInterval,
setTimeout: pSetTimeout,
} = require('timers/promises');
const {
AbortController,
} = require('internal/abort_controller');
const { 0: InspectClient, 1: createRepl } =
[
require('internal/debugger/inspect_client'),
require('internal/debugger/inspect_repl'),
];
const debuglog = util.debuglog('inspect');
const { ERR_DEBUGGER_STARTUP_ERROR } = require('internal/errors').codes;
const {
exitCodes: {
kGenericUserError,
kNoFailure,
kInvalidCommandLineArgument,
},
} = internalBinding('errors');
async function portIsFree(host, port, timeout = 3000) {
if (port === 0) return; // Binding to a random port.
const retryDelay = 150;
const ac = new AbortController();
const { signal } = ac;
pSetTimeout(timeout).then(() => ac.abort());
const asyncIterator = pSetInterval(retryDelay);
while (true) {
await asyncIterator.next();
if (signal.aborted) {
throw new ERR_DEBUGGER_STARTUP_ERROR(
`Timeout (${timeout}) waiting for ${host}:${port} to be free`);
}
const error = await new Promise((resolve) => {
const socket = net.connect(port, host);
socket.on('error', resolve);
socket.on('connect', () => {
socket.end();
resolve();
});
});
if (error?.code === 'ECONNREFUSED') {
return;
}
}
}
const debugRegex = /Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//;
async function runScript(script, scriptArgs, inspectHost, inspectPort,
childPrint) {
await portIsFree(inspectHost, inspectPort);
const args = [`--inspect-brk=${inspectPort}`, script];
ArrayPrototypePushApply(args, scriptArgs);
const child = spawn(process.execPath, args);
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', (chunk) => childPrint(chunk, 'stdout'));
child.stderr.on('data', (chunk) => childPrint(chunk, 'stderr'));
let output = '';
return new Promise((resolve) => {
function waitForListenHint(text) {
output += text;
const debug = RegExpPrototypeExec(debugRegex, output);
if (debug) {
const host = debug[1];
const port = Number(debug[2]);
child.stderr.removeListener('data', waitForListenHint);
resolve([child, port, host]);
}
}
child.stderr.on('data', waitForListenHint);
});
}
function createAgentProxy(domain, client) {
const agent = new EventEmitter();
agent.then = (then, _catch) => {
// TODO: potentially fetch the protocol and pretty-print it here.
const descriptor = {
[util.inspect.custom](depth, { stylize }) {
return stylize(`[Agent ${domain}]`, 'special');
},
};
return PromisePrototypeThen(PromiseResolve(descriptor), then, _catch);
};
return new Proxy(agent, {
__proto__: null,
get(target, name) {
if (name in target) return target[name];
return function callVirtualMethod(params) {
return client.callMethod(`${domain}.${name}`, params);
};
},
});
}
class NodeInspector {
constructor(options, stdin, stdout) {
this.options = options;
this.stdin = stdin;
this.stdout = stdout;
this.paused = true;
this.child = null;
if (options.script) {
this._runScript = FunctionPrototypeBind(
runScript, null,
options.script,
options.scriptArgs,
options.host,
options.port,
FunctionPrototypeBind(this.childPrint, this));
} else {
this._runScript =
() => PromiseResolve([null, options.port, options.host]);
}
this.client = new InspectClient();
this.domainNames = ['Debugger', 'HeapProfiler', 'Profiler', 'Runtime'];
ArrayPrototypeForEach(this.domainNames, (domain) => {
this[domain] = createAgentProxy(domain, this.client);
});
this.handleDebugEvent = (fullName, params) => {
const { 0: domain, 1: name } = StringPrototypeSplit(fullName, '.', 2);
if (domain in this) {
this[domain].emit(name, params);
}
};
this.client.on('debugEvent', this.handleDebugEvent);
const startRepl = createRepl(this);
// Handle all possible exits
process.on('exit', () => this.killChild());
const exitCodeZero = () => process.exit(kNoFailure);
process.once('SIGTERM', exitCodeZero);
process.once('SIGHUP', exitCodeZero);
(async () => {
try {
await this.run();
const repl = await startRepl();
this.repl = repl;
this.repl.on('exit', exitCodeZero);
this.paused = false;
} catch (error) {
process.nextTick(() => { throw error; });
}
})();
}
suspendReplWhile(fn) {
if (this.repl) {
this.repl.pause();
}
this.stdin.pause();
this.paused = true;
return (async () => {
try {
await fn();
this.paused = false;
if (this.repl) {
this.repl.resume();
this.repl.displayPrompt();
}
this.stdin.resume();
} catch (error) {
process.nextTick(() => { throw error; });
}
})();
}
killChild() {
this.client.reset();
if (this.child) {
this.child.kill();
this.child = null;
}
}
async run() {
this.killChild();
const { 0: child, 1: port, 2: host } = await this._runScript();
this.child = child;
this.print(`connecting to ${host}:${port} ..`, false);
for (let attempt = 0; attempt < 5; attempt++) {
debuglog('connection attempt #%d', attempt);
this.stdout.write('.');
try {
await this.client.connect(port, host);
debuglog('connection established');
this.stdout.write(' ok\n');
return;
} catch (error) {
debuglog('connect failed', error);
await pSetTimeout(1000);
}
}
this.stdout.write(' failed to connect, please retry\n');
process.exit(kGenericUserError);
}
clearLine() {
if (this.stdout.isTTY) {
this.stdout.cursorTo(0);
this.stdout.clearLine(1);
} else {
this.stdout.write('\b');
}
}
print(text, appendNewline = false) {
this.clearLine();
this.stdout.write(appendNewline ? `${text}\n` : text);
}
#stdioBuffers = { stdout: '', stderr: '' };
childPrint(text, which) {
const lines = RegExpPrototypeSymbolSplit(
/\r\n|\r|\n/g,
this.#stdioBuffers[which] + text);
this.#stdioBuffers[which] = '';
if (lines[lines.length - 1] !== '') {
this.#stdioBuffers[which] = ArrayPrototypePop(lines);
}
const textToPrint = ArrayPrototypeJoin(
ArrayPrototypeMap(lines, (chunk) => `< ${chunk}`),
'\n');
if (lines.length) {
this.print(textToPrint, true);
if (!this.paused) {
this.repl.displayPrompt(true);
}
}
if (StringPrototypeEndsWith(
textToPrint,
'Waiting for the debugger to disconnect...\n',
)) {
this.killChild();
}
}
}
function parseArgv(args) {
const target = ArrayPrototypeShift(args);
let host = '127.0.0.1';
let port = 9229;
let isRemote = false;
let script = target;
let scriptArgs = args;
const hostMatch = RegExpPrototypeExec(/^([^:]+):(\d+)$/, target);
const portMatch = RegExpPrototypeExec(/^--port=(\d+)$/, target);
if (hostMatch) {
// Connecting to remote debugger
host = hostMatch[1];
port = Number(hostMatch[2]);
isRemote = true;
script = null;
} else if (portMatch) {
// Start on custom port
port = Number(portMatch[1]);
script = args[0];
scriptArgs = ArrayPrototypeSlice(args, 1);
} else if (args.length === 1 && RegExpPrototypeExec(/^\d+$/, args[0]) !== null &&
target === '-p') {
// Start debugger against a given pid
const pid = Number(args[0]);
try {
process._debugProcess(pid);
} catch (e) {
if (e.code === 'ESRCH') {
process.stderr.write(`Target process: ${pid} doesn't exist.\n`);
process.exit(kGenericUserError);
}
throw e;
}
script = null;
isRemote = true;
}
return {
host, port, isRemote, script, scriptArgs,
};
}
function startInspect(argv = ArrayPrototypeSlice(process.argv, 2),
stdin = process.stdin,
stdout = process.stdout) {
if (argv.length < 1) {
const invokedAs = `${process.argv0} ${process.argv[1]}`;
process.stderr.write(`Usage: ${invokedAs} script.js\n` +
` ${invokedAs} <host>:<port>\n` +
` ${invokedAs} --port=<port> Use 0 for random port assignment\n` +
` ${invokedAs} -p <pid>\n`);
process.exit(kInvalidCommandLineArgument);
}
const options = parseArgv(argv);
const inspector = new NodeInspector(options, stdin, stdout);
stdin.resume();
function handleUnexpectedError(e) {
if (e.code !== 'ERR_DEBUGGER_STARTUP_ERROR') {
process.stderr.write('There was an internal error in Node.js. ' +
'Please report this bug.\n' +
`${e.message}\n${e.stack}\n`);
} else {
process.stderr.write(e.message);
process.stderr.write('\n');
}
if (inspector.child) inspector.child.kill();
process.exit(kGenericUserError);
}
process.on('uncaughtException', handleUnexpectedError);
}
exports.start = startInspect;

View File

@ -0,0 +1,356 @@
'use strict';
const {
ArrayPrototypePush,
ErrorCaptureStackTrace,
FunctionPrototypeBind,
JSONParse,
JSONStringify,
ObjectKeys,
Promise,
} = primordials;
const Buffer = require('buffer').Buffer;
const crypto = require('crypto');
const { ERR_DEBUGGER_ERROR } = require('internal/errors').codes;
const { EventEmitter } = require('events');
const http = require('http');
const { URL } = require('internal/url');
const debuglog = require('internal/util/debuglog').debuglog('inspect');
const kOpCodeText = 0x1;
const kOpCodeClose = 0x8;
const kFinalBit = 0x80;
const kReserved1Bit = 0x40;
const kReserved2Bit = 0x20;
const kReserved3Bit = 0x10;
const kOpCodeMask = 0xF;
const kMaskBit = 0x80;
const kPayloadLengthMask = 0x7F;
const kMaxSingleBytePayloadLength = 125;
const kMaxTwoBytePayloadLength = 0xFFFF;
const kTwoBytePayloadLengthField = 126;
const kEightBytePayloadLengthField = 127;
const kMaskingKeyWidthInBytes = 4;
// This guid is defined in the Websocket Protocol RFC
// https://tools.ietf.org/html/rfc6455#section-1.3
const WEBSOCKET_HANDSHAKE_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
function unpackError({ code, message }) {
const err = new ERR_DEBUGGER_ERROR(`${message}`);
err.code = code;
ErrorCaptureStackTrace(err, unpackError);
return err;
}
function validateHandshake(requestKey, responseKey) {
const expectedResponseKeyBase = requestKey + WEBSOCKET_HANDSHAKE_GUID;
const shasum = crypto.createHash('sha1');
shasum.update(expectedResponseKeyBase);
const shabuf = shasum.digest();
if (shabuf.toString('base64') !== responseKey) {
throw new ERR_DEBUGGER_ERROR(
`WebSocket secret mismatch: ${requestKey} did not match ${responseKey}`,
);
}
}
function encodeFrameHybi17(payload) {
const dataLength = payload.length;
let singleByteLength;
let additionalLength;
if (dataLength > kMaxTwoBytePayloadLength) {
singleByteLength = kEightBytePayloadLengthField;
additionalLength = Buffer.alloc(8);
let remaining = dataLength;
for (let i = 0; i < 8; ++i) {
additionalLength[7 - i] = remaining & 0xFF;
remaining >>= 8;
}
} else if (dataLength > kMaxSingleBytePayloadLength) {
singleByteLength = kTwoBytePayloadLengthField;
additionalLength = Buffer.alloc(2);
additionalLength[0] = (dataLength & 0xFF00) >> 8;
additionalLength[1] = dataLength & 0xFF;
} else {
additionalLength = Buffer.alloc(0);
singleByteLength = dataLength;
}
const header = Buffer.from([
kFinalBit | kOpCodeText,
kMaskBit | singleByteLength,
]);
const mask = Buffer.alloc(4);
const masked = Buffer.alloc(dataLength);
for (let i = 0; i < dataLength; ++i) {
masked[i] = payload[i] ^ mask[i % kMaskingKeyWidthInBytes];
}
return Buffer.concat([header, additionalLength, mask, masked]);
}
function decodeFrameHybi17(data) {
const dataAvailable = data.length;
const notComplete = { closed: false, payload: null, rest: data };
let payloadOffset = 2;
if ((dataAvailable - payloadOffset) < 0) return notComplete;
const firstByte = data[0];
const secondByte = data[1];
const final = (firstByte & kFinalBit) !== 0;
const reserved1 = (firstByte & kReserved1Bit) !== 0;
const reserved2 = (firstByte & kReserved2Bit) !== 0;
const reserved3 = (firstByte & kReserved3Bit) !== 0;
const opCode = firstByte & kOpCodeMask;
const masked = (secondByte & kMaskBit) !== 0;
const compressed = reserved1;
if (compressed) {
throw new ERR_DEBUGGER_ERROR('Compressed frames not supported');
}
if (!final || reserved2 || reserved3) {
throw new ERR_DEBUGGER_ERROR('Only compression extension is supported');
}
if (masked) {
throw new ERR_DEBUGGER_ERROR('Masked server frame - not supported');
}
let closed = false;
switch (opCode) {
case kOpCodeClose:
closed = true;
break;
case kOpCodeText:
break;
default:
throw new ERR_DEBUGGER_ERROR(`Unsupported op code ${opCode}`);
}
let payloadLength = secondByte & kPayloadLengthMask;
switch (payloadLength) {
case kTwoBytePayloadLengthField:
payloadOffset += 2;
payloadLength = (data[2] << 8) + data[3];
break;
case kEightBytePayloadLengthField:
payloadOffset += 8;
payloadLength = 0;
for (let i = 0; i < 8; ++i) {
payloadLength <<= 8;
payloadLength |= data[2 + i];
}
break;
default:
// Nothing. We already have the right size.
}
if ((dataAvailable - payloadOffset - payloadLength) < 0) return notComplete;
const payloadEnd = payloadOffset + payloadLength;
return {
payload: data.slice(payloadOffset, payloadEnd),
rest: data.slice(payloadEnd),
closed,
};
}
class Client extends EventEmitter {
constructor() {
super();
this.handleChunk = FunctionPrototypeBind(this._handleChunk, this);
this._port = undefined;
this._host = undefined;
this.reset();
}
_handleChunk(chunk) {
this._unprocessed = Buffer.concat([this._unprocessed, chunk]);
while (this._unprocessed.length > 2) {
const {
closed,
payload: payloadBuffer,
rest,
} = decodeFrameHybi17(this._unprocessed);
this._unprocessed = rest;
if (closed) {
this.reset();
return;
}
if (payloadBuffer === null || payloadBuffer.length === 0) break;
const payloadStr = payloadBuffer.toString();
debuglog('< %s', payloadStr);
const lastChar = payloadStr[payloadStr.length - 1];
if (payloadStr[0] !== '{' || lastChar !== '}') {
throw new ERR_DEBUGGER_ERROR(`Payload does not look like JSON: ${payloadStr}`);
}
let payload;
try {
payload = JSONParse(payloadStr);
} catch (parseError) {
parseError.string = payloadStr;
throw parseError;
}
const { id, method, params, result, error } = payload;
if (id) {
const handler = this._pending[id];
if (handler) {
delete this._pending[id];
handler(error, result);
}
} else if (method) {
this.emit('debugEvent', method, params);
this.emit(method, params);
} else {
throw new ERR_DEBUGGER_ERROR(`Unsupported response: ${payloadStr}`);
}
}
}
reset() {
if (this._http) {
this._http.destroy();
}
if (this._socket) {
this._socket.destroy();
}
this._http = null;
this._lastId = 0;
this._socket = null;
this._pending = {};
this._unprocessed = Buffer.alloc(0);
}
callMethod(method, params) {
return new Promise((resolve, reject) => {
if (!this._socket) {
reject(new ERR_DEBUGGER_ERROR('Use `run` to start the app again.'));
return;
}
const data = { id: ++this._lastId, method, params };
this._pending[data.id] = (error, result) => {
if (error) reject(unpackError(error));
else resolve(ObjectKeys(result).length ? result : undefined);
};
const json = JSONStringify(data);
debuglog('> %s', json);
this._socket.write(encodeFrameHybi17(Buffer.from(json)));
});
}
_fetchJSON(urlPath) {
return new Promise((resolve, reject) => {
const httpReq = http.get({
host: this._host,
port: this._port,
path: urlPath,
});
const chunks = [];
function onResponse(httpRes) {
function parseChunks() {
const resBody = Buffer.concat(chunks).toString();
if (httpRes.statusCode !== 200) {
reject(new ERR_DEBUGGER_ERROR(`Unexpected ${httpRes.statusCode}: ${resBody}`));
return;
}
try {
resolve(JSONParse(resBody));
} catch {
reject(new ERR_DEBUGGER_ERROR(`Response didn't contain JSON: ${resBody}`));
}
}
httpRes.on('error', reject);
httpRes.on('data', (chunk) => ArrayPrototypePush(chunks, chunk));
httpRes.on('end', parseChunks);
}
httpReq.on('error', reject);
httpReq.on('response', onResponse);
});
}
async connect(port, host) {
this._port = port;
this._host = host;
const urlPath = await this._discoverWebsocketPath();
return this._connectWebsocket(urlPath);
}
async _discoverWebsocketPath() {
const { 0: { webSocketDebuggerUrl } } = await this._fetchJSON('/json');
const { pathname, search } = new URL(webSocketDebuggerUrl);
return `${pathname}${search}`;
}
_connectWebsocket(urlPath) {
this.reset();
const requestKey = crypto.randomBytes(16).toString('base64');
debuglog('request WebSocket', requestKey);
const httpReq = this._http = http.request({
host: this._host,
port: this._port,
path: urlPath,
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket',
'Sec-WebSocket-Key': requestKey,
'Sec-WebSocket-Version': '13',
},
});
httpReq.on('error', (e) => {
this.emit('error', e);
});
httpReq.on('response', (httpRes) => {
if (httpRes.statusCode >= 400) {
process.stderr.write(`Unexpected HTTP code: ${httpRes.statusCode}\n`);
httpRes.pipe(process.stderr);
} else {
httpRes.pipe(process.stderr);
}
});
const handshakeListener = (res, socket) => {
validateHandshake(requestKey, res.headers['sec-websocket-accept']);
debuglog('websocket upgrade');
this._socket = socket;
socket.on('data', this.handleChunk);
socket.on('close', () => {
this.emit('close');
});
this.emit('ready');
};
return new Promise((resolve, reject) => {
this.once('error', reject);
this.once('ready', resolve);
httpReq.on('upgrade', handshakeListener);
httpReq.end();
});
}
}
module.exports = Client;

File diff suppressed because it is too large Load Diff