From 7029bcbec3d634f5d629bced8ef07be1fc78222f Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:34:00 +0000 Subject: [PATCH 01/11] ffi: share scalar trampoline helpers between platforms The loong64, ppc64, riscv64, and s390x fast trampoline emitters each duplicated the signature validation, executable memory allocation, cache flush and mprotect sequence, trampoline release, and (for the fixed-width 32-bit ISAs) the instruction word emitters. Move them into a shared scalar_trampoline.h header so each platform file only contains its architecture-specific instruction encoding. Assisted-by: Claude --- node.gyp | 1 + src/ffi/platforms/loong64.cc | 92 +++---------------- src/ffi/platforms/ppc64.cc | 92 +++---------------- src/ffi/platforms/riscv64.cc | 92 +++---------------- src/ffi/platforms/s390x.cc | 80 +++-------------- src/ffi/platforms/scalar_trampoline.h | 123 ++++++++++++++++++++++++++ 6 files changed, 174 insertions(+), 306 deletions(-) create mode 100644 src/ffi/platforms/scalar_trampoline.h diff --git a/node.gyp b/node.gyp index a462a9e9f2e4..ed790d532264 100644 --- a/node.gyp +++ b/node.gyp @@ -517,6 +517,7 @@ 'src/ffi/data.h', 'src/ffi/fast.cc', 'src/ffi/fast.h', + 'src/ffi/platforms/scalar_trampoline.h', 'src/ffi/jit_memory.cc', 'src/ffi/jit_memory.h', 'src/ffi/types.cc', diff --git a/src/ffi/platforms/loong64.cc b/src/ffi/platforms/loong64.cc index dda579b6c63f..bac66187266c 100644 --- a/src/ffi/platforms/loong64.cc +++ b/src/ffi/platforms/loong64.cc @@ -4,30 +4,20 @@ #if defined(__loongarch64) -#include -#include +#include "ffi/platforms/scalar_trampoline.h" #include namespace { using node::ffi::FastFFIType; - -bool IsFloatType(FastFFIType type) { - return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; -} - -bool IsNarrowType(FastFFIType type) { - switch (type) { - case FastFFIType::kInt8: - case FastFFIType::kUint8: - case FastFFIType::kInt16: - case FastFFIType::kUint16: - return true; - default: - return false; - } -} +using node::ffi::scalar_trampoline::AllocateCode; +using node::ffi::scalar_trampoline::CanCreate; +using node::ffi::scalar_trampoline::Emit32; +using node::ffi::scalar_trampoline::Emit64; +using node::ffi::scalar_trampoline::FinalizeCode; +using node::ffi::scalar_trampoline::FreeTrampoline; +using node::ffi::scalar_trampoline::IsFloatType; uint32_t Or(unsigned rd, unsigned rj, unsigned rk) { return (0x2au << 15) | (rk << 10) | (rj << 5) | rd; @@ -47,30 +37,6 @@ uint32_t Jirl(unsigned rd, unsigned rj, int imm16) { (rj << 5) | rd; } -void Emit32(uint32_t** cursor, uint32_t value) { - *(*cursor)++ = value; -} - -void Emit64(uint32_t** cursor, uint64_t value) { - uint64_t* slot = reinterpret_cast(*cursor); - *slot = value; - *cursor += 2; -} - -void* AllocateCode(size_t code_size) { - void* code = mmap(nullptr, - code_size, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON, - -1, - 0); - return code == MAP_FAILED ? nullptr : code; -} - -void FreeCode(void* code, size_t code_size) { - munmap(code, code_size); -} - } // namespace extern "C" bool node_ffi_create_fast_trampoline( @@ -79,32 +45,15 @@ extern "C" bool node_ffi_create_fast_trampoline( size_t argc, node::ffi::FastFFIType result, node::ffi::FastFFITrampoline* out) { - if (config.target == nullptr || out == nullptr || IsNarrowType(result)) { - return false; - } - - size_t gp_count = 0; - size_t fp_count = 0; - for (size_t i = 0; i < argc; i++) { - if (args[i] == FastFFIType::kBuffer) { - return false; - } - if (IsFloatType(args[i])) { - fp_count++; - } else { - gp_count++; - } - } - // LoongArch64 passes integer arguments in a0..a7. V8's receiver occupies a0, // so user GP arguments arrive in a1..a7 and are shifted down before the tail // branch. FP arguments are already in fa0..fa7. - if (gp_count > 7 || fp_count > 8) { + size_t gp_count; + if (!CanCreate(config, args, argc, result, out, 7, 8, &gp_count)) { return false; } - constexpr size_t kCodeSize = 256; - void* code = AllocateCode(kCodeSize); + void* code = AllocateCode(); if (code == nullptr) { return false; } @@ -130,27 +79,12 @@ extern "C" bool node_ffi_create_fast_trampoline( const size_t written = reinterpret_cast(cursor) - static_cast(code); - __builtin___clear_cache(static_cast(code), - static_cast(code) + written); - - if (mprotect(code, kCodeSize, PROT_READ | PROT_EXEC) != 0) { - FreeCode(code, kCodeSize); - return false; - } - - out->code = code; - out->size = kCodeSize; - return true; + return FinalizeCode(code, written, out); } extern "C" void node_ffi_free_fast_trampoline( node::ffi::FastFFITrampoline* trampoline) { - if (trampoline == nullptr || trampoline->code == nullptr) { - return; - } - FreeCode(trampoline->code, trampoline->size); - trampoline->code = nullptr; - trampoline->size = 0; + FreeTrampoline(trampoline); } #endif // defined(__loongarch64) diff --git a/src/ffi/platforms/ppc64.cc b/src/ffi/platforms/ppc64.cc index 52808abac894..156de1c0f011 100644 --- a/src/ffi/platforms/ppc64.cc +++ b/src/ffi/platforms/ppc64.cc @@ -8,30 +8,20 @@ __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) && \ !defined(_AIX) -#include -#include +#include "ffi/platforms/scalar_trampoline.h" #include namespace { using node::ffi::FastFFIType; - -bool IsFloatType(FastFFIType type) { - return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; -} - -bool IsNarrowType(FastFFIType type) { - switch (type) { - case FastFFIType::kInt8: - case FastFFIType::kUint8: - case FastFFIType::kInt16: - case FastFFIType::kUint16: - return true; - default: - return false; - } -} +using node::ffi::scalar_trampoline::AllocateCode; +using node::ffi::scalar_trampoline::CanCreate; +using node::ffi::scalar_trampoline::Emit32; +using node::ffi::scalar_trampoline::Emit64; +using node::ffi::scalar_trampoline::FinalizeCode; +using node::ffi::scalar_trampoline::FreeTrampoline; +using node::ffi::scalar_trampoline::IsFloatType; uint32_t Or(unsigned ra, unsigned rs, unsigned rb) { return (31u << 26) | (rs << 21) | (ra << 16) | (rb << 11) | (444u << 1); @@ -59,30 +49,6 @@ uint32_t Ld(unsigned rt, unsigned ra, unsigned offset) { return (58u << 26) | (rt << 21) | (ra << 16) | (offset & 0xfffcu); } -void Emit32(uint32_t** cursor, uint32_t value) { - *(*cursor)++ = value; -} - -void Emit64(uint32_t** cursor, uint64_t value) { - uint64_t* slot = reinterpret_cast(*cursor); - *slot = value; - *cursor += 2; -} - -void* AllocateCode(size_t code_size) { - void* code = mmap(nullptr, - code_size, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON, - -1, - 0); - return code == MAP_FAILED ? nullptr : code; -} - -void FreeCode(void* code, size_t code_size) { - munmap(code, code_size); -} - } // namespace extern "C" bool node_ffi_create_fast_trampoline( @@ -91,32 +57,15 @@ extern "C" bool node_ffi_create_fast_trampoline( size_t argc, node::ffi::FastFFIType result, node::ffi::FastFFITrampoline* out) { - if (config.target == nullptr || out == nullptr || IsNarrowType(result)) { - return false; - } - - size_t gp_count = 0; - size_t fp_count = 0; - for (size_t i = 0; i < argc; i++) { - if (args[i] == FastFFIType::kBuffer) { - return false; - } - if (IsFloatType(args[i])) { - fp_count++; - } else { - gp_count++; - } - } - // ELFv2 PPC64LE passes integer arguments in r3..r10. V8's receiver occupies // r3, so the scalar-only fast path keeps user GP arguments in r4..r10 and // shifts them down before tail-branching to the native target. - if (gp_count > 7 || fp_count > 8) { + size_t gp_count; + if (!CanCreate(config, args, argc, result, out, 7, 8, &gp_count)) { return false; } - constexpr size_t kCodeSize = 256; - void* code = AllocateCode(kCodeSize); + void* code = AllocateCode(); if (code == nullptr) { return false; } @@ -153,27 +102,12 @@ extern "C" bool node_ffi_create_fast_trampoline( const size_t written = reinterpret_cast(cursor) - static_cast(code); - __builtin___clear_cache(static_cast(code), - static_cast(code) + written); - - if (mprotect(code, kCodeSize, PROT_READ | PROT_EXEC) != 0) { - FreeCode(code, kCodeSize); - return false; - } - - out->code = code; - out->size = kCodeSize; - return true; + return FinalizeCode(code, written, out); } extern "C" void node_ffi_free_fast_trampoline( node::ffi::FastFFITrampoline* trampoline) { - if (trampoline == nullptr || trampoline->code == nullptr) { - return; - } - FreeCode(trampoline->code, trampoline->size); - trampoline->code = nullptr; - trampoline->size = 0; + FreeTrampoline(trampoline); } #else diff --git a/src/ffi/platforms/riscv64.cc b/src/ffi/platforms/riscv64.cc index 841b0db85f68..4fa138a1df1e 100644 --- a/src/ffi/platforms/riscv64.cc +++ b/src/ffi/platforms/riscv64.cc @@ -4,30 +4,20 @@ #if defined(__riscv) && __riscv_xlen == 64 -#include -#include +#include "ffi/platforms/scalar_trampoline.h" #include namespace { using node::ffi::FastFFIType; - -bool IsFloatType(FastFFIType type) { - return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; -} - -bool IsNarrowType(FastFFIType type) { - switch (type) { - case FastFFIType::kInt8: - case FastFFIType::kUint8: - case FastFFIType::kInt16: - case FastFFIType::kUint16: - return true; - default: - return false; - } -} +using node::ffi::scalar_trampoline::AllocateCode; +using node::ffi::scalar_trampoline::CanCreate; +using node::ffi::scalar_trampoline::Emit32; +using node::ffi::scalar_trampoline::Emit64; +using node::ffi::scalar_trampoline::FinalizeCode; +using node::ffi::scalar_trampoline::FreeTrampoline; +using node::ffi::scalar_trampoline::IsFloatType; uint32_t Addi(unsigned rd, unsigned rs1, int imm) { return ((static_cast(imm) & 0xfff) << 20) | (rs1 << 15) | @@ -48,30 +38,6 @@ uint32_t Jalr(unsigned rd, unsigned rs1, int imm) { (rd << 7) | 0x67; } -void Emit32(uint32_t** cursor, uint32_t value) { - *(*cursor)++ = value; -} - -void Emit64(uint32_t** cursor, uint64_t value) { - uint64_t* slot = reinterpret_cast(*cursor); - *slot = value; - *cursor += 2; -} - -void* AllocateCode(size_t code_size) { - void* code = mmap(nullptr, - code_size, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON, - -1, - 0); - return code == MAP_FAILED ? nullptr : code; -} - -void FreeCode(void* code, size_t code_size) { - munmap(code, code_size); -} - } // namespace extern "C" bool node_ffi_create_fast_trampoline( @@ -80,32 +46,15 @@ extern "C" bool node_ffi_create_fast_trampoline( size_t argc, node::ffi::FastFFIType result, node::ffi::FastFFITrampoline* out) { - if (config.target == nullptr || out == nullptr || IsNarrowType(result)) { - return false; - } - - size_t gp_count = 0; - size_t fp_count = 0; - for (size_t i = 0; i < argc; i++) { - if (args[i] == FastFFIType::kBuffer) { - return false; - } - if (IsFloatType(args[i])) { - fp_count++; - } else { - gp_count++; - } - } - // RISC-V LP64D passes integer arguments in a0..a7. V8's receiver occupies // a0, so user GP arguments arrive in a1..a7 and are shifted down before the // tail branch. FP arguments are already in fa0..fa7. - if (gp_count > 7 || fp_count > 8) { + size_t gp_count; + if (!CanCreate(config, args, argc, result, out, 7, 8, &gp_count)) { return false; } - constexpr size_t kCodeSize = 256; - void* code = AllocateCode(kCodeSize); + void* code = AllocateCode(); if (code == nullptr) { return false; } @@ -131,27 +80,12 @@ extern "C" bool node_ffi_create_fast_trampoline( const size_t written = reinterpret_cast(cursor) - static_cast(code); - __builtin___clear_cache(static_cast(code), - static_cast(code) + written); - - if (mprotect(code, kCodeSize, PROT_READ | PROT_EXEC) != 0) { - FreeCode(code, kCodeSize); - return false; - } - - out->code = code; - out->size = kCodeSize; - return true; + return FinalizeCode(code, written, out); } extern "C" void node_ffi_free_fast_trampoline( node::ffi::FastFFITrampoline* trampoline) { - if (trampoline == nullptr || trampoline->code == nullptr) { - return; - } - FreeCode(trampoline->code, trampoline->size); - trampoline->code = nullptr; - trampoline->size = 0; + FreeTrampoline(trampoline); } #endif // defined(__riscv) && __riscv_xlen == 64 diff --git a/src/ffi/platforms/s390x.cc b/src/ffi/platforms/s390x.cc index 5ec44d9e486d..b4cc94edf48c 100644 --- a/src/ffi/platforms/s390x.cc +++ b/src/ffi/platforms/s390x.cc @@ -4,30 +4,18 @@ #if defined(__s390x__) -#include -#include +#include "ffi/platforms/scalar_trampoline.h" #include namespace { using node::ffi::FastFFIType; - -bool IsFloatType(FastFFIType type) { - return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; -} - -bool IsNarrowType(FastFFIType type) { - switch (type) { - case FastFFIType::kInt8: - case FastFFIType::kUint8: - case FastFFIType::kInt16: - case FastFFIType::kUint16: - return true; - default: - return false; - } -} +using node::ffi::scalar_trampoline::AllocateCode; +using node::ffi::scalar_trampoline::CanCreate; +using node::ffi::scalar_trampoline::FinalizeCode; +using node::ffi::scalar_trampoline::FreeTrampoline; +using node::ffi::scalar_trampoline::IsFloatType; uint32_t Lgr(unsigned r1, unsigned r2) { return 0xb9040000u | (r1 << 4) | r2; @@ -69,20 +57,6 @@ void Emit64(uint8_t** cursor, uint64_t value) { } } -void* AllocateCode(size_t code_size) { - void* code = mmap(nullptr, - code_size, - PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANON, - -1, - 0); - return code == MAP_FAILED ? nullptr : code; -} - -void FreeCode(void* code, size_t code_size) { - munmap(code, code_size); -} - } // namespace extern "C" bool node_ffi_create_fast_trampoline( @@ -91,32 +65,15 @@ extern "C" bool node_ffi_create_fast_trampoline( size_t argc, node::ffi::FastFFIType result, node::ffi::FastFFITrampoline* out) { - if (config.target == nullptr || out == nullptr || IsNarrowType(result)) { - return false; - } - - size_t gp_count = 0; - size_t fp_count = 0; - for (size_t i = 0; i < argc; i++) { - if (args[i] == FastFFIType::kBuffer) { - return false; - } - if (IsFloatType(args[i])) { - fp_count++; - } else { - gp_count++; - } - } - // Linux s390x passes integer arguments in r2..r6. V8's receiver occupies r2, // so user GP arguments arrive in r3..r6 and are shifted down before the tail // branch. FP arguments are already in f0, f2, f4, and f6. - if (gp_count > 4 || fp_count > 4) { + size_t gp_count; + if (!CanCreate(config, args, argc, result, out, 4, 4, &gp_count)) { return false; } - constexpr size_t kCodeSize = 256; - void* code = AllocateCode(kCodeSize); + void* code = AllocateCode(); if (code == nullptr) { return false; } @@ -139,27 +96,12 @@ extern "C" bool node_ffi_create_fast_trampoline( Emit64(&cursor, reinterpret_cast(config.target)); const size_t written = cursor - static_cast(code); - __builtin___clear_cache(static_cast(code), - static_cast(code) + written); - - if (mprotect(code, kCodeSize, PROT_READ | PROT_EXEC) != 0) { - FreeCode(code, kCodeSize); - return false; - } - - out->code = code; - out->size = kCodeSize; - return true; + return FinalizeCode(code, written, out); } extern "C" void node_ffi_free_fast_trampoline( node::ffi::FastFFITrampoline* trampoline) { - if (trampoline == nullptr || trampoline->code == nullptr) { - return; - } - FreeCode(trampoline->code, trampoline->size); - trampoline->code = nullptr; - trampoline->size = 0; + FreeTrampoline(trampoline); } #endif // defined(__s390x__) diff --git a/src/ffi/platforms/scalar_trampoline.h b/src/ffi/platforms/scalar_trampoline.h new file mode 100644 index 000000000000..e10087c17010 --- /dev/null +++ b/src/ffi/platforms/scalar_trampoline.h @@ -0,0 +1,123 @@ +#pragma once + +#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS + +// Shared helpers for the POSIX platforms whose fast FFI trampoline only shifts +// scalar GP arguments down by one register (dropping V8's receiver) and then +// tail-branches to the native target: loong64, ppc64, riscv64 and s390x. + +#include "ffi/fast.h" + +#include + +#include +#include + +namespace node::ffi::scalar_trampoline { + +// Size of the executable mapping allocated for each trampoline. +constexpr size_t kCodeSize = 256; + +inline bool IsFloatType(FastFFIType type) { + return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; +} + +inline bool IsNarrowType(FastFFIType type) { + switch (type) { + case FastFFIType::kInt8: + case FastFFIType::kUint8: + case FastFFIType::kInt16: + case FastFFIType::kUint16: + return true; + default: + return false; + } +} + +// Validates the signature for the scalar-only fast path. Returns false when +// the trampoline cannot be generated, either because the inputs are invalid, +// the result needs narrowing, an argument is a buffer, or there are more GP or +// FP arguments than the platform passes in registers. +inline bool CanCreate(const FastFFITrampolineConfig& config, + const FastFFIType* args, + size_t argc, + FastFFIType result, + const FastFFITrampoline* out, + size_t max_gp_args, + size_t max_fp_args, + size_t* gp_count_out) { + if (config.target == nullptr || out == nullptr || IsNarrowType(result)) { + return false; + } + + size_t gp_count = 0; + size_t fp_count = 0; + for (size_t i = 0; i < argc; i++) { + if (args[i] == FastFFIType::kBuffer) { + return false; + } + if (IsFloatType(args[i])) { + fp_count++; + } else { + gp_count++; + } + } + + if (gp_count > max_gp_args || fp_count > max_fp_args) { + return false; + } + *gp_count_out = gp_count; + return true; +} + +inline void* AllocateCode() { + void* code = mmap(nullptr, + kCodeSize, + PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANON, + -1, + 0); + return code == MAP_FAILED ? nullptr : code; +} + +// Flushes the instruction cache for the `written` bytes emitted at `code`, +// makes the mapping executable and stores it in `out`. On failure the mapping +// is released and false is returned. +inline bool FinalizeCode(void* code, size_t written, FastFFITrampoline* out) { + __builtin___clear_cache(static_cast(code), + static_cast(code) + written); + + if (mprotect(code, kCodeSize, PROT_READ | PROT_EXEC) != 0) { + munmap(code, kCodeSize); + return false; + } + + out->code = code; + out->size = kCodeSize; + return true; +} + +inline void FreeTrampoline(FastFFITrampoline* trampoline) { + if (trampoline == nullptr || trampoline->code == nullptr) { + return; + } + munmap(trampoline->code, trampoline->size); + trampoline->code = nullptr; + trampoline->size = 0; +} + +// Word emitters for platforms with fixed-width 32-bit, native-endian +// instructions. The 64-bit literal must be 8-byte aligned by the caller. +inline void Emit32(uint32_t** cursor, uint32_t value) { + *(*cursor)++ = value; +} + +inline void Emit64(uint32_t** cursor, uint64_t value) { + uint64_t* slot = reinterpret_cast(*cursor); + *slot = value; + *cursor += 2; +} + +} // namespace node::ffi::scalar_trampoline + +#endif // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS From bbadafb82ff507996334064d95cf76b3a3d4a494 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:36:29 +0000 Subject: [PATCH 02/11] ffi: share x64 instruction emitters between SysV and Win64 The System V and Win64 halves of the x64 fast trampoline emitter each defined identical copies of the register constants, the byte/word emitters, the REX/ModRM, mov, call, jmp, stack adjustment, and ret encoders, and the narrow return normalization helpers. Define them once ahead of the ABI-specific code. Assisted-by: Claude --- src/ffi/platforms/x64.cc | 334 +++++++++++++-------------------------- 1 file changed, 114 insertions(+), 220 deletions(-) diff --git a/src/ffi/platforms/x64.cc b/src/ffi/platforms/x64.cc index f9700ac0211b..155240d39f01 100644 --- a/src/ffi/platforms/x64.cc +++ b/src/ffi/platforms/x64.cc @@ -2,54 +2,37 @@ #include "ffi/fast.h" -#if defined(__x86_64__) && !defined(_WIN32) +#if (defined(__x86_64__) && !defined(_WIN32)) || defined(_M_X64) +#if defined(_WIN32) +#include +#else #include #include +#endif #include #include +// Instruction emitters and register numbers shared by the System V and Win64 +// trampolines. namespace { using node::ffi::FastFFIType; -// System V x86_64 argument registers in ABI order. V8 Fast API calls enter the -// trampoline with the JS receiver in the first GP slot (rdi), so user GP -// arguments arrive shifted by one register: rsi, rdx, rcx, r8, r9. constexpr unsigned kRax = 0; constexpr unsigned kRcx = 1; constexpr unsigned kRdx = 2; constexpr unsigned kRsp = 4; -constexpr unsigned kRsi = 6; -constexpr unsigned kRdi = 7; constexpr unsigned kR8 = 8; constexpr unsigned kR9 = 9; constexpr unsigned kR11 = 11; -constexpr unsigned kIncomingGPRegisters[] = {kRsi, kRdx, kRcx, kR8, kR9}; -constexpr unsigned kTargetGPRegisters[] = {kRdi, kRsi, kRdx, kRcx, kR8, kR9}; - -// Floating-point values use xmmN registers in the SysV x86_64 ABI. The receiver -// consumes only a GP register, so FP arguments are already in the target ABI -// locations and the trampoline only needs to shuffle GP arguments. bool IsFloatType(FastFFIType type) { return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; } -// The current scalar implementation only distinguishes FP from non-FP ABI -// classes; non-FP values are carried in GP registers. -bool IsGPType(FastFFIType type) { - return !IsFloatType(type); -} - -// kBuffer means V8 passes the original JS value; the trampoline must call back -// into C++ to convert it to a native pointer before invoking the target. -bool IsPointerValueType(FastFFIType type) { - return type == FastFFIType::kBuffer; -} - void Emit8(uint8_t** cursor, uint8_t value) { *(*cursor)++ = value; } @@ -93,15 +76,6 @@ void EmitMovImm64(uint8_t** cursor, unsigned reg, uintptr_t value) { Emit64(cursor, value); } -void EmitMovImm32(uint8_t** cursor, unsigned reg, uint32_t value) { - // Load the buffer helper's uint32_t argument index into edx. - if (reg >= 8) { - EmitRex(cursor, false, 0, reg); - } - Emit8(cursor, 0xb8 | (reg & 7)); - Emit32(cursor, value); -} - void EmitCall(uint8_t** cursor, unsigned reg) { // call *reg. All targets are absolute addresses first loaded into r11. EmitRex(cursor, true, 0, reg); @@ -117,6 +91,111 @@ void EmitJmp(uint8_t** cursor, unsigned reg) { EmitModRM(cursor, 4, reg); } +void EmitRet(uint8_t** cursor) { + Emit8(cursor, 0xc3); +} + +void EmitSubRsp(uint8_t** cursor, unsigned value) { + // Reserve stack spill space with `sub rsp, imm32`. The caller keeps the value + // 16-byte aligned so nested calls preserve the ABI stack alignment rule. + EmitRex(cursor, true, 5, kRsp); + Emit8(cursor, 0x81); + Emit8(cursor, 0xec); + Emit32(cursor, value); +} + +void EmitAddRsp(uint8_t** cursor, unsigned value) { + // Release stack spill space with `add rsp, imm32`, matching EmitSubRsp(). + EmitRex(cursor, true, 0, kRsp); + Emit8(cursor, 0x81); + Emit8(cursor, 0xc4); + Emit32(cursor, value); +} + +void EmitNarrowInstruction(uint8_t** cursor, uint8_t opcode, unsigned reg) { + // movsx/movzx reg32, reg8/reg16. Writing the 32-bit destination also clears + // the upper 32 bits, which is the ABI-normal form V8 observes. + EmitRex(cursor, false, reg, reg); + Emit8(cursor, 0x0f); + Emit8(cursor, opcode); + EmitModRM(cursor, reg, reg); +} + +// Native small integer returns may leave upper bits unspecified. Normalize them +// before V8 observes the result. Arguments do not need the same treatment: the +// C ABI passes narrow integer arguments in integer registers and the callee +// consumes the declared low 8/16 bits. +bool EmitNarrowReturn(uint8_t** cursor, FastFFIType type, unsigned reg) { + switch (type) { + case FastFFIType::kUint8: + EmitNarrowInstruction(cursor, 0xb6, reg); + return true; + case FastFFIType::kInt8: + EmitNarrowInstruction(cursor, 0xbe, reg); + return true; + case FastFFIType::kUint16: + EmitNarrowInstruction(cursor, 0xb7, reg); + return true; + case FastFFIType::kInt16: + EmitNarrowInstruction(cursor, 0xbf, reg); + return true; + default: + return false; + } +} + +bool NeedsNarrow(FastFFIType type) { + switch (type) { + case FastFFIType::kUint8: + case FastFFIType::kInt8: + case FastFFIType::kUint16: + case FastFFIType::kInt16: + return true; + default: + return false; + } +} + +} // namespace + +#if defined(__x86_64__) && !defined(_WIN32) + +namespace { + +// System V x86_64 argument registers in ABI order. V8 Fast API calls enter the +// trampoline with the JS receiver in the first GP slot (rdi), so user GP +// arguments arrive shifted by one register: rsi, rdx, rcx, r8, r9. +constexpr unsigned kRsi = 6; +constexpr unsigned kRdi = 7; + +constexpr unsigned kIncomingGPRegisters[] = {kRsi, kRdx, kRcx, kR8, kR9}; +constexpr unsigned kTargetGPRegisters[] = {kRdi, kRsi, kRdx, kRcx, kR8, kR9}; + +// Floating-point values use xmmN registers in the SysV x86_64 ABI. The receiver +// consumes only a GP register, so FP arguments are already in the target ABI +// locations and the trampoline only needs to shuffle GP arguments. +// +// The current scalar implementation only distinguishes FP from non-FP ABI +// classes; non-FP values are carried in GP registers. +bool IsGPType(FastFFIType type) { + return !IsFloatType(type); +} + +// kBuffer means V8 passes the original JS value; the trampoline must call back +// into C++ to convert it to a native pointer before invoking the target. +bool IsPointerValueType(FastFFIType type) { + return type == FastFFIType::kBuffer; +} + +void EmitMovImm32(uint8_t** cursor, unsigned reg, uint32_t value) { + // Load the buffer helper's uint32_t argument index into edx. + if (reg >= 8) { + EmitRex(cursor, false, 0, reg); + } + Emit8(cursor, 0xb8 | (reg & 7)); + Emit32(cursor, value); +} + bool EmitJmpRel32(uint8_t** cursor, uintptr_t target) { // jmp rel32 is shorter than movabs+jmp and avoids an indirect branch. It is // only usable when the native target is within the signed 32-bit displacement @@ -147,27 +226,6 @@ void EmitPopRbp(uint8_t** cursor) { Emit8(cursor, 0x5d); } -void EmitRet(uint8_t** cursor) { - Emit8(cursor, 0xc3); -} - -void EmitSubRsp(uint8_t** cursor, unsigned value) { - // Reserve stack spill space with `sub rsp, imm32`. The caller keeps the value - // 16-byte aligned so nested calls preserve the SysV stack alignment rule. - EmitRex(cursor, true, 5, kRsp); - Emit8(cursor, 0x81); - Emit8(cursor, 0xec); - Emit32(cursor, value); -} - -void EmitAddRsp(uint8_t** cursor, unsigned value) { - // Release stack spill space with `add rsp, imm32`, matching EmitSubRsp(). - EmitRex(cursor, true, 0, kRsp); - Emit8(cursor, 0x81); - Emit8(cursor, 0xc4); - Emit32(cursor, value); -} - void EmitStackMemory(uint8_t** cursor, unsigned reg, unsigned offset) { // Address [rsp + offset]. x86_64 requires a SIB byte whenever rsp is the base // register; offsets fit in the small fixed spill frame used by this emitter. @@ -226,50 +284,6 @@ void EmitXorEax(uint8_t** cursor) { Emit8(cursor, 0xc0); } -void EmitNarrowInstruction(uint8_t** cursor, uint8_t opcode, unsigned reg) { - // movsx/movzx reg32, reg8/reg16. Writing the 32-bit destination also clears - // the upper 32 bits, which is the ABI-normal form V8 observes. - EmitRex(cursor, false, reg, reg); - Emit8(cursor, 0x0f); - Emit8(cursor, opcode); - EmitModRM(cursor, reg, reg); -} - -// Native small integer returns may leave upper bits unspecified. Normalize them -// before V8 observes the result. Arguments do not need the same treatment: the -// C ABI passes narrow integer arguments in integer registers and the callee -// consumes the declared low 8/16 bits. -bool EmitNarrowReturn(uint8_t** cursor, FastFFIType type, unsigned reg) { - switch (type) { - case FastFFIType::kUint8: - EmitNarrowInstruction(cursor, 0xb6, reg); - return true; - case FastFFIType::kInt8: - EmitNarrowInstruction(cursor, 0xbe, reg); - return true; - case FastFFIType::kUint16: - EmitNarrowInstruction(cursor, 0xb7, reg); - return true; - case FastFFIType::kInt16: - EmitNarrowInstruction(cursor, 0xbf, reg); - return true; - default: - return false; - } -} - -bool NeedsNarrow(FastFFIType type) { - switch (type) { - case FastFFIType::kUint8: - case FastFFIType::kInt8: - case FastFFIType::kUint16: - case FastFFIType::kInt16: - return true; - default: - return false; - } -} - // Stack adjustment must preserve the platform's 16-byte SP alignment rule. unsigned Align16(unsigned value) { return (value + 15) & ~15; @@ -590,62 +604,14 @@ extern "C" void node_ffi_free_fast_trampoline( #elif defined(_M_X64) -#include - -#include - namespace { -using node::ffi::FastFFIType; - -constexpr unsigned kRax = 0; -constexpr unsigned kRcx = 1; -constexpr unsigned kRdx = 2; -constexpr unsigned kRsp = 4; -constexpr unsigned kR8 = 8; -constexpr unsigned kR9 = 9; -constexpr unsigned kR11 = 11; - constexpr unsigned kWin64GPRegisters[] = {kRcx, kRdx, kR8, kR9}; -bool IsFloatType(FastFFIType type) { - return type == FastFFIType::kFloat32 || type == FastFFIType::kFloat64; -} - bool IsBufferType(FastFFIType type) { return type == FastFFIType::kBuffer; } -void Emit8(uint8_t** cursor, uint8_t value) { - *(*cursor)++ = value; -} - -void Emit32(uint8_t** cursor, uint32_t value) { - for (unsigned i = 0; i < 4; i++) { - Emit8(cursor, (value >> (i * 8)) & 0xff); - } -} - -void Emit64(uint8_t** cursor, uint64_t value) { - for (unsigned i = 0; i < 8; i++) { - Emit8(cursor, (value >> (i * 8)) & 0xff); - } -} - -void EmitRex(uint8_t** cursor, bool wide, unsigned reg, unsigned rm) { - Emit8(cursor, 0x40 | (wide ? 0x08 : 0) | ((reg >> 3) << 2) | (rm >> 3)); -} - -void EmitModRM(uint8_t** cursor, unsigned reg, unsigned rm) { - Emit8(cursor, 0xc0 | ((reg & 7) << 3) | (rm & 7)); -} - -void EmitMov(uint8_t** cursor, unsigned dst, unsigned src) { - EmitRex(cursor, true, src, dst); - Emit8(cursor, 0x89); - EmitModRM(cursor, src, dst); -} - void EmitMovaps(uint8_t** cursor, unsigned dst, unsigned src) { // movaps xmm_dst, xmm_src. Used only for register-to-register argument // shuffles; it preserves the payload bits for both f32 and f64 arguments. @@ -655,80 +621,6 @@ void EmitMovaps(uint8_t** cursor, unsigned dst, unsigned src) { EmitModRM(cursor, dst, src); } -void EmitMovImm64(uint8_t** cursor, unsigned reg, uintptr_t value) { - EmitRex(cursor, true, 0, reg); - Emit8(cursor, 0xb8 | (reg & 7)); - Emit64(cursor, value); -} - -void EmitCall(uint8_t** cursor, unsigned reg) { - EmitRex(cursor, true, 0, reg); - Emit8(cursor, 0xff); - EmitModRM(cursor, 2, reg); -} - -void EmitJmp(uint8_t** cursor, unsigned reg) { - EmitRex(cursor, true, 0, reg); - Emit8(cursor, 0xff); - EmitModRM(cursor, 4, reg); -} - -void EmitSubRsp(uint8_t** cursor, unsigned value) { - EmitRex(cursor, true, 5, kRsp); - Emit8(cursor, 0x81); - Emit8(cursor, 0xec); - Emit32(cursor, value); -} - -void EmitAddRsp(uint8_t** cursor, unsigned value) { - EmitRex(cursor, true, 0, kRsp); - Emit8(cursor, 0x81); - Emit8(cursor, 0xc4); - Emit32(cursor, value); -} - -void EmitRet(uint8_t** cursor) { - Emit8(cursor, 0xc3); -} - -void EmitNarrowInstruction(uint8_t** cursor, uint8_t opcode, unsigned reg) { - EmitRex(cursor, false, reg, reg); - Emit8(cursor, 0x0f); - Emit8(cursor, opcode); - EmitModRM(cursor, reg, reg); -} - -bool EmitNarrowReturn(uint8_t** cursor, FastFFIType type, unsigned reg) { - switch (type) { - case FastFFIType::kUint8: - EmitNarrowInstruction(cursor, 0xb6, reg); - return true; - case FastFFIType::kInt8: - EmitNarrowInstruction(cursor, 0xbe, reg); - return true; - case FastFFIType::kUint16: - EmitNarrowInstruction(cursor, 0xb7, reg); - return true; - case FastFFIType::kInt16: - EmitNarrowInstruction(cursor, 0xbf, reg); - return true; - default: - return false; - } -} - -bool NeedsNarrow(FastFFIType type) { - switch (type) { - case FastFFIType::kUint8: - case FastFFIType::kInt8: - case FastFFIType::kUint16: - case FastFFIType::kInt16: - return true; - default: - return false; - } -} - void FreeCode(void* code, size_t code_size) { VirtualFree(code, 0, MEM_RELEASE); } @@ -813,4 +705,6 @@ extern "C" void node_ffi_free_fast_trampoline( #endif // defined(_M_X64) +#endif // x86_64 SysV or Win64 + #endif // HAVE_FFI From 5cbf711313eb6fe3ec60ac99a877033662743c8a Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:38:02 +0000 Subject: [PATCH 03/11] node-api: share error creation and throw helpers napi_create_error(), napi_create_type_error(), napi_create_range_error() and node_api_create_syntax_error() differed only in the v8::Exception factory used, as did the corresponding napi_throw_*() functions. Move the bodies into internal CreateError() and ThrowError() helpers that take the factory. The exported functions and their signatures are unchanged, so there is no ABI impact. Assisted-by: Claude --- src/js_native_api_v8.cc | 143 +++++++++++++--------------------------- 1 file changed, 44 insertions(+), 99 deletions(-) diff --git a/src/js_native_api_v8.cc b/src/js_native_api_v8.cc index ba1ab6f18511..403e9a6878b3 100644 --- a/src/js_native_api_v8.cc +++ b/src/js_native_api_v8.cc @@ -1988,10 +1988,15 @@ static inline napi_status set_error_code(napi_env env, return napi_ok; } -napi_status NAPI_CDECL napi_create_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result) { +using ErrorFactory = v8::Local (*)(v8::Local message, + v8::Local options); + +// Shared implementation of napi_create_error() and its typed variants. +static inline napi_status CreateError(napi_env env, + ErrorFactory factory, + napi_value code, + napi_value msg, + napi_value* result) { CHECK_ENV_NOT_IN_GC(env); CHECK_ARG(env, msg); CHECK_ARG(env, result); @@ -2000,7 +2005,7 @@ napi_status NAPI_CDECL napi_create_error(napi_env env, RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); v8::Local error_obj = - v8::Exception::Error(message_value.As()); + factory(message_value.As(), v8::Local()); STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); *result = v8impl::JsValueFromV8LocalValue(error_obj); @@ -2008,64 +2013,52 @@ napi_status NAPI_CDECL napi_create_error(napi_env env, return napi_clear_last_error(env); } -napi_status NAPI_CDECL napi_create_type_error(napi_env env, - napi_value code, - napi_value msg, - napi_value* result) { - CHECK_ENV_NOT_IN_GC(env); - CHECK_ARG(env, msg); - CHECK_ARG(env, result); - - v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); - RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); +// Shared implementation of napi_throw_error() and its typed variants. +static inline napi_status ThrowError(napi_env env, + ErrorFactory factory, + const char* code, + const char* msg) { + NAPI_PREAMBLE(env); - v8::Local error_obj = - v8::Exception::TypeError(message_value.As()); - STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); + v8::Isolate* isolate = env->isolate; + v8::Local str; + CHECK_NEW_FROM_UTF8(env, str, msg); - *result = v8impl::JsValueFromV8LocalValue(error_obj); + v8::Local error_obj = factory(str, v8::Local()); + STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); + isolate->ThrowException(error_obj); + // any VM calls after this point and before returning + // to the javascript invoker will fail return napi_clear_last_error(env); } +napi_status NAPI_CDECL napi_create_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + return CreateError(env, v8::Exception::Error, code, msg, result); +} + +napi_status NAPI_CDECL napi_create_type_error(napi_env env, + napi_value code, + napi_value msg, + napi_value* result) { + return CreateError(env, v8::Exception::TypeError, code, msg, result); +} + napi_status NAPI_CDECL napi_create_range_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { - CHECK_ENV_NOT_IN_GC(env); - CHECK_ARG(env, msg); - CHECK_ARG(env, result); - - v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); - RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); - - v8::Local error_obj = - v8::Exception::RangeError(message_value.As()); - STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); - - *result = v8impl::JsValueFromV8LocalValue(error_obj); - - return napi_clear_last_error(env); + return CreateError(env, v8::Exception::RangeError, code, msg, result); } napi_status NAPI_CDECL node_api_create_syntax_error(napi_env env, napi_value code, napi_value msg, napi_value* result) { - CHECK_ENV_NOT_IN_GC(env); - CHECK_ARG(env, msg); - CHECK_ARG(env, result); - - v8::Local message_value = v8impl::V8LocalValueFromJsValue(msg); - RETURN_STATUS_IF_FALSE(env, message_value->IsString(), napi_string_expected); - - v8::Local error_obj = - v8::Exception::SyntaxError(message_value.As()); - STATUS_CALL(set_error_code(env, error_obj, code, nullptr)); - - *result = v8impl::JsValueFromV8LocalValue(error_obj); - - return napi_clear_last_error(env); + return CreateError(env, v8::Exception::SyntaxError, code, msg, result); } napi_status NAPI_CDECL napi_typeof(napi_env env, @@ -2231,73 +2224,25 @@ napi_status NAPI_CDECL napi_throw(napi_env env, napi_value error) { napi_status NAPI_CDECL napi_throw_error(napi_env env, const char* code, const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local error_obj = v8::Exception::Error(str); - STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); + return ThrowError(env, v8::Exception::Error, code, msg); } napi_status NAPI_CDECL napi_throw_type_error(napi_env env, const char* code, const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local error_obj = v8::Exception::TypeError(str); - STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); + return ThrowError(env, v8::Exception::TypeError, code, msg); } napi_status NAPI_CDECL napi_throw_range_error(napi_env env, const char* code, const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local error_obj = v8::Exception::RangeError(str); - STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); + return ThrowError(env, v8::Exception::RangeError, code, msg); } napi_status NAPI_CDECL node_api_throw_syntax_error(napi_env env, const char* code, const char* msg) { - NAPI_PREAMBLE(env); - - v8::Isolate* isolate = env->isolate; - v8::Local str; - CHECK_NEW_FROM_UTF8(env, str, msg); - - v8::Local error_obj = v8::Exception::SyntaxError(str); - STATUS_CALL(set_error_code(env, error_obj, nullptr, code)); - - isolate->ThrowException(error_obj); - // any VM calls after this point and before returning - // to the javascript invoker will fail - return napi_clear_last_error(env); + return ThrowError(env, v8::Exception::SyntaxError, code, msg); } napi_status NAPI_CDECL napi_is_error(napi_env env, From 50518aa47d05d8e53ccd4f75c421a50878f8e1c2 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:38:46 +0000 Subject: [PATCH 04/11] ffi: share callback lookup between callback methods DynamicLibrary::UnregisterCallback(), RefCallback(), and UnrefCallback() each duplicated the closed-library check, pointer argument validation, and callback map lookup. Move them into a shared FindCallback() helper. Assisted-by: Claude --- src/node_ffi.cc | 110 +++++++++++++++--------------------------------- src/node_ffi.h | 13 +++++- 2 files changed, 46 insertions(+), 77 deletions(-) diff --git a/src/node_ffi.cc b/src/node_ffi.cc index b8127587d4e5..aa0b3dac72ca 100644 --- a/src/node_ffi.cc +++ b/src/node_ffi.cc @@ -1339,25 +1339,27 @@ void DynamicLibrary::RegisterCallback(const FunctionCallbackInfo& args) { args.GetReturnValue().Set(BigInt::NewFromUnsigned(isolate, ret)); } -void DynamicLibrary::UnregisterCallback( - const FunctionCallbackInfo& args) { +DynamicLibrary* DynamicLibrary::FindCallback( + const FunctionCallbackInfo& args, + bool require_function, + CallbackMap::iterator* out) { Environment* env = Environment::GetCurrent(args); DynamicLibrary* lib = Unwrap(args.This()); if (lib->is_closed()) { THROW_ERR_FFI_LIBRARY_CLOSED(env); - return; + return nullptr; } if (args.Length() < 1 || !args[0]->IsBigInt()) { THROW_ERR_INVALID_ARG_TYPE(env, "The first argument must be a bigint"); - return; + return nullptr; } uintptr_t raw_ptr; if (!GetValidatedPointerAddress(env, args[0], "first argument") .To(&raw_ptr)) { - return; + return nullptr; } void* ptr = reinterpret_cast(raw_ptr); @@ -1365,6 +1367,27 @@ void DynamicLibrary::UnregisterCallback( if (existing == lib->callbacks_.end()) { THROW_ERR_INVALID_ARG_VALUE(env, "Callback not found"); + return nullptr; + } + + // The callback function may already have been collected after a previous + // unrefCallback() call. The persistent handle is empty in that case, and + // ClearWeak() or SetWeak() on an empty handle dereferences a null slot. + // There is also no function left to make strong again. + if (require_function && existing->second->fn.IsEmpty()) { + THROW_ERR_INVALID_ARG_VALUE(env, "Callback not found"); + return nullptr; + } + + *out = existing; + return lib; +} + +void DynamicLibrary::UnregisterCallback( + const FunctionCallbackInfo& args) { + CallbackMap::iterator existing; + DynamicLibrary* lib = FindCallback(args, false, &existing); + if (lib == nullptr) { return; } @@ -1377,82 +1400,17 @@ void DynamicLibrary::UnregisterCallback( } void DynamicLibrary::RefCallback(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args); - DynamicLibrary* lib = Unwrap(args.This()); - - if (lib->is_closed()) { - THROW_ERR_FFI_LIBRARY_CLOSED(env); - return; - } - - if (args.Length() < 1 || !args[0]->IsBigInt()) { - THROW_ERR_INVALID_ARG_TYPE(env, "The first argument must be a bigint"); - return; - } - - uintptr_t raw_ptr; - if (!GetValidatedPointerAddress(env, args[0], "first argument") - .To(&raw_ptr)) { - return; - } - - void* ptr = reinterpret_cast(raw_ptr); - auto existing = lib->callbacks_.find(ptr); - - if (existing == lib->callbacks_.end()) { - THROW_ERR_INVALID_ARG_VALUE(env, "Callback not found"); - return; + CallbackMap::iterator existing; + if (FindCallback(args, true, &existing) != nullptr) { + existing->second->fn.ClearWeak(); } - - // The callback function may already have been collected after a previous - // unrefCallback() call. The persistent handle is empty in that case, and - // ClearWeak() on an empty handle dereferences a null slot. There is also no - // function left to make strong again. - if (existing->second->fn.IsEmpty()) { - THROW_ERR_INVALID_ARG_VALUE(env, "Callback not found"); - return; - } - - existing->second->fn.ClearWeak(); } void DynamicLibrary::UnrefCallback(const FunctionCallbackInfo& args) { - Environment* env = Environment::GetCurrent(args); - DynamicLibrary* lib = Unwrap(args.This()); - - if (lib->is_closed()) { - THROW_ERR_FFI_LIBRARY_CLOSED(env); - return; - } - - if (args.Length() < 1 || !args[0]->IsBigInt()) { - THROW_ERR_INVALID_ARG_TYPE(env, "The first argument must be a bigint"); - return; + CallbackMap::iterator existing; + if (FindCallback(args, true, &existing) != nullptr) { + existing->second->fn.SetWeak(); } - - uintptr_t raw_ptr; - if (!GetValidatedPointerAddress(env, args[0], "first argument") - .To(&raw_ptr)) { - return; - } - - void* ptr = reinterpret_cast(raw_ptr); - auto existing = lib->callbacks_.find(ptr); - - if (existing == lib->callbacks_.end()) { - THROW_ERR_INVALID_ARG_VALUE(env, "Callback not found"); - return; - } - - // The callback function may already have been collected by a previous - // unrefCallback() call. The persistent handle is empty in that case, and - // SetWeak() on an empty handle dereferences a null slot. - if (existing->second->fn.IsEmpty()) { - THROW_ERR_INVALID_ARG_VALUE(env, "Callback not found"); - return; - } - - existing->second->fn.SetWeak(); } Local DynamicLibrary::GetConstructorTemplate( diff --git a/src/node_ffi.h b/src/node_ffi.h index 86737273e284..969491ff5450 100644 --- a/src/node_ffi.h +++ b/src/node_ffi.h @@ -158,6 +158,17 @@ class DynamicLibrary : public BaseObject { SET_SELF_SIZE(DynamicLibrary) private: + using CallbackMap = std::unordered_map>; + + // Validates that args[0] is a pointer to a callback registered with the + // receiving library and stores its entry in `out`. When `require_function` + // is true, a callback whose function has already been collected is also + // rejected. Returns the library, or nullptr after throwing. + static DynamicLibrary* FindCallback( + const v8::FunctionCallbackInfo& args, + bool require_function, + CallbackMap::iterator* out); + void Close(); v8::Maybe ResolveSymbol(Environment* env, const std::string& name); struct PreparedFunction { @@ -194,7 +205,7 @@ class DynamicLibrary : public BaseObject { // FFIFunctionInfo. std::unordered_map> function_wrappers_; std::shared_ptr> pointer_functions_; - std::unordered_map> callbacks_; + CallbackMap callbacks_; }; void GetInt8(const v8::FunctionCallbackInfo& args); From 38934d6e70055d30d3dbd92ea4dbbaf3e79b54ac Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:41:56 +0000 Subject: [PATCH 05/11] inspector: share required event parameter extraction The network and DOM storage agents repeated the same pattern dozens of times: read a property with an ObjectGet*() helper and throw a "Missing in event" TypeError if it was absent. Add ObjectGetRequired() overloads that combine the two, move the duplicated ThrowEventError() into inspector_object_utils, and use them throughout both agents. Error messages are unchanged. Assisted-by: Claude --- src/inspector/dom_storage_agent.cc | 55 ++----- src/inspector/inspector_object_utils.cc | 56 +++++++ src/inspector/inspector_object_utils.h | 34 ++++ src/inspector/network_agent.cc | 196 ++++++------------------ 4 files changed, 149 insertions(+), 192 deletions(-) diff --git a/src/inspector/dom_storage_agent.cc b/src/inspector/dom_storage_agent.cc index 7d3ce9dc5d06..6fd431aa5af7 100644 --- a/src/inspector/dom_storage_agent.cc +++ b/src/inspector/dom_storage_agent.cc @@ -17,11 +17,6 @@ using v8::Local; using v8::Object; using v8::Value; -static void ThrowEventError(v8::Isolate* isolate, const std::string& message) { - isolate->ThrowException(v8::Exception::TypeError( - v8::String::NewFromUtf8(isolate, message.c_str()).ToLocalChecked())); -} - std::unique_ptr createStorageIdFromObject( Local context, Local storage_id_obj) { protocol::String security_origin; @@ -176,10 +171,8 @@ protocol::DispatchResponse DOMStorageAgent::clear( void DOMStorageAgent::domStorageItemAdded(Local context, Local params) { - Isolate* isolate = env_->isolate(); Local storage_id_obj; - if (!ObjectGetObject(context, params, "storageId").ToLocal(&storage_id_obj)) { - ThrowEventError(isolate, "Missing storageId in event"); + if (!ObjectGetRequired(context, params, "storageId", &storage_id_obj)) { return; } @@ -190,13 +183,9 @@ void DOMStorageAgent::domStorageItemAdded(Local context, } protocol::String key; - if (!ObjectGetProtocolString(context, params, "key").To(&key)) { - ThrowEventError(isolate, "Missing key in event"); - return; - } protocol::String new_value; - if (!ObjectGetProtocolString(context, params, "newValue").To(&new_value)) { - ThrowEventError(isolate, "Missing newValue in event"); + if (!ObjectGetRequired(context, params, "key", &key) || + !ObjectGetRequired(context, params, "newValue", &new_value)) { return; } frontend_->domStorageItemAdded(std::move(storage_id), key, new_value); @@ -204,10 +193,8 @@ void DOMStorageAgent::domStorageItemAdded(Local context, void DOMStorageAgent::domStorageItemRemoved(Local context, Local params) { - Isolate* isolate = env_->isolate(); Local storage_id_obj; - if (!ObjectGetObject(context, params, "storageId").ToLocal(&storage_id_obj)) { - ThrowEventError(isolate, "Missing storageId in event"); + if (!ObjectGetRequired(context, params, "storageId", &storage_id_obj)) { return; } std::unique_ptr storage_id = @@ -218,8 +205,7 @@ void DOMStorageAgent::domStorageItemRemoved(Local context, } protocol::String key; - if (!ObjectGetProtocolString(context, params, "key").To(&key)) { - ThrowEventError(isolate, "Missing key in event"); + if (!ObjectGetRequired(context, params, "key", &key)) { return; } frontend_->domStorageItemRemoved(std::move(storage_id), key); @@ -227,10 +213,8 @@ void DOMStorageAgent::domStorageItemRemoved(Local context, void DOMStorageAgent::domStorageItemUpdated(Local context, Local params) { - Isolate* isolate = env_->isolate(); Local storage_id_obj; - if (!ObjectGetObject(context, params, "storageId").ToLocal(&storage_id_obj)) { - ThrowEventError(isolate, "Missing storageId in event"); + if (!ObjectGetRequired(context, params, "storageId", &storage_id_obj)) { return; } @@ -242,18 +226,11 @@ void DOMStorageAgent::domStorageItemUpdated(Local context, } protocol::String key; - if (!ObjectGetProtocolString(context, params, "key").To(&key)) { - ThrowEventError(isolate, "Missing key in event"); - return; - } protocol::String old_value; - if (!ObjectGetProtocolString(context, params, "oldValue").To(&old_value)) { - ThrowEventError(isolate, "Missing oldValue in event"); - return; - } protocol::String new_value; - if (!ObjectGetProtocolString(context, params, "newValue").To(&new_value)) { - ThrowEventError(isolate, "Missing newValue in event"); + if (!ObjectGetRequired(context, params, "key", &key) || + !ObjectGetRequired(context, params, "oldValue", &old_value) || + !ObjectGetRequired(context, params, "newValue", &new_value)) { return; } frontend_->domStorageItemUpdated( @@ -262,10 +239,8 @@ void DOMStorageAgent::domStorageItemUpdated(Local context, void DOMStorageAgent::domStorageItemsCleared(Local context, Local params) { - Isolate* isolate = env_->isolate(); Local storage_id_obj; - if (!ObjectGetObject(context, params, "storageId").ToLocal(&storage_id_obj)) { - ThrowEventError(isolate, "Missing storageId in event"); + if (!ObjectGetRequired(context, params, "storageId", &storage_id_obj)) { return; } std::unique_ptr storage_id = @@ -282,14 +257,10 @@ void DOMStorageAgent::registerStorage(Local context, Isolate* isolate = env_->isolate(); HandleScope handle_scope(isolate); bool is_local_storage; - if (!ObjectGetBool(context, params, "isLocalStorage").To(&is_local_storage)) { - ThrowEventError(isolate, "Missing isLocalStorage in event"); - return; - } Local storage_map_obj; - if (!ObjectGetObject(context, params, "storageMap") - .ToLocal(&storage_map_obj)) { - ThrowEventError(isolate, "Missing storageMap in event"); + if (!ObjectGetRequired( + context, params, "isLocalStorage", &is_local_storage) || + !ObjectGetRequired(context, params, "storageMap", &storage_map_obj)) { return; } StorageMap& storage_map = diff --git a/src/inspector/inspector_object_utils.cc b/src/inspector/inspector_object_utils.cc index 8acfcbbd5c1e..2e79d7113d1b 100644 --- a/src/inspector/inspector_object_utils.cc +++ b/src/inspector/inspector_object_utils.cc @@ -98,5 +98,61 @@ MaybeLocal ObjectGetObject(Local context, return handle_scope.Escape(value.As()); } +void ThrowEventError(Isolate* isolate, const std::string& message) { + isolate->ThrowException(v8::Exception::TypeError( + String::NewFromUtf8(isolate, message.c_str()).ToLocalChecked())); +} + +static bool ThrowMissing(const char* prefix, const char* property) { + ThrowEventError(Isolate::GetCurrent(), + std::string("Missing ") + prefix + property + " in event"); + return false; +} + +bool ObjectGetRequired(Local context, + Local object, + const char* property, + protocol::String* out, + const char* prefix) { + return ObjectGetProtocolString(context, object, property).To(out) || + ThrowMissing(prefix, property); +} + +bool ObjectGetRequired(Local context, + Local object, + const char* property, + double* out, + const char* prefix) { + return ObjectGetDouble(context, object, property).To(out) || + ThrowMissing(prefix, property); +} + +bool ObjectGetRequired(Local context, + Local object, + const char* property, + int* out, + const char* prefix) { + return ObjectGetInt(context, object, property).To(out) || + ThrowMissing(prefix, property); +} + +bool ObjectGetRequired(Local context, + Local object, + const char* property, + bool* out, + const char* prefix) { + return ObjectGetBool(context, object, property).To(out) || + ThrowMissing(prefix, property); +} + +bool ObjectGetRequired(Local context, + Local object, + const char* property, + Local* out, + const char* prefix) { + return ObjectGetObject(context, object, property).ToLocal(out) || + ThrowMissing(prefix, property); +} + } // namespace inspector } // namespace node diff --git a/src/inspector/inspector_object_utils.h b/src/inspector/inspector_object_utils.h index f69933a8bb55..30669caf0695 100644 --- a/src/inspector/inspector_object_utils.h +++ b/src/inspector/inspector_object_utils.h @@ -2,6 +2,7 @@ #define SRC_INSPECTOR_INSPECTOR_OBJECT_UTILS_H_ #include +#include #include "node/inspector/protocol/Protocol.h" namespace node { @@ -33,6 +34,39 @@ v8::MaybeLocal ObjectGetObject(v8::Local context, v8::Local object, const char* property); +// Throws a TypeError with the given message, used to report malformed +// protocol event parameters. +void ThrowEventError(v8::Isolate* isolate, const std::string& message); + +// Like the ObjectGet*() helpers above, but for required properties: on failure +// a TypeError "Missing in event" is thrown and false is +// returned. +bool ObjectGetRequired(v8::Local context, + v8::Local object, + const char* property, + protocol::String* out, + const char* prefix = ""); +bool ObjectGetRequired(v8::Local context, + v8::Local object, + const char* property, + double* out, + const char* prefix = ""); +bool ObjectGetRequired(v8::Local context, + v8::Local object, + const char* property, + int* out, + const char* prefix = ""); +bool ObjectGetRequired(v8::Local context, + v8::Local object, + const char* property, + bool* out, + const char* prefix = ""); +bool ObjectGetRequired(v8::Local context, + v8::Local object, + const char* property, + v8::Local* out, + const char* prefix = ""); + } // namespace inspector } // namespace node #endif // SRC_INSPECTOR_INSPECTOR_OBJECT_UTILS_H_ diff --git a/src/inspector/network_agent.cc b/src/inspector/network_agent.cc index ace8ba522871..bbd8912b4796 100644 --- a/src/inspector/network_agent.cc +++ b/src/inspector/network_agent.cc @@ -24,11 +24,6 @@ using v8::Value; constexpr size_t kDefaultMaxTotalBufferSize = 100 * 1024 * 1024; // 100MB -static void ThrowEventError(v8::Isolate* isolate, const std::string& message) { - isolate->ThrowException(v8::Exception::TypeError( - v8::String::NewFromUtf8(isolate, message.c_str()).ToLocalChecked())); -} - // Create a protocol::Network::Headers from the v8 object. std::unique_ptr NetworkAgent::createHeadersFromObject(v8::Local context, @@ -70,20 +65,13 @@ std::unique_ptr NetworkAgent::createRequestFromObject(v8::Local context, Local request) { HandleScope handle_scope(Isolate::GetCurrent()); - Isolate* isolate = env_->isolate(); protocol::String url; - if (!ObjectGetProtocolString(context, request, "url").To(&url)) { - ThrowEventError(isolate, "Missing request.url in event"); - return {}; - } protocol::String method; - if (!ObjectGetProtocolString(context, request, "method").To(&method)) { - ThrowEventError(isolate, "Missing request.method in event"); - return {}; - } Local headers_obj; - if (!ObjectGetObject(context, request, "headers").ToLocal(&headers_obj)) { - ThrowEventError(isolate, "Missing request.headers in event"); + if (!ObjectGetRequired(context, request, "url", &url, "request.") || + !ObjectGetRequired(context, request, "method", &method, "request.") || + !ObjectGetRequired( + context, request, "headers", &headers_obj, "request.")) { return {}; } std::unique_ptr headers = @@ -107,26 +95,16 @@ std::unique_ptr NetworkAgent::createResponseFromObject(v8::Local context, Local response) { HandleScope handle_scope(Isolate::GetCurrent()); - Isolate* isolate = env_->isolate(); protocol::String url; - if (!ObjectGetProtocolString(context, response, "url").To(&url)) { - ThrowEventError(isolate, "Missing response.url in event"); - return {}; - } int status; - if (!ObjectGetInt(context, response, "status").To(&status)) { - ThrowEventError(isolate, "Missing response.status in event"); - return {}; - } protocol::String statusText; - if (!ObjectGetProtocolString(context, response, "statusText") - .To(&statusText)) { - ThrowEventError(isolate, "Missing response.statusText in event"); - return {}; - } Local headers_obj; - if (!ObjectGetObject(context, response, "headers").ToLocal(&headers_obj)) { - ThrowEventError(isolate, "Missing response.headers in event"); + if (!ObjectGetRequired(context, response, "url", &url, "response.") || + !ObjectGetRequired(context, response, "status", &status, "response.") || + !ObjectGetRequired( + context, response, "statusText", &statusText, "response.") || + !ObjectGetRequired( + context, response, "headers", &headers_obj, "response.")) { return {}; } std::unique_ptr headers = @@ -154,21 +132,14 @@ std::unique_ptr NetworkAgent::createWebSocketResponse(v8::Local context, Local response) { HandleScope handle_scope(Isolate::GetCurrent()); - Isolate* isolate = env_->isolate(); int status; - if (!ObjectGetInt(context, response, "status").To(&status)) { - ThrowEventError(isolate, "Missing response.status in event"); - return {}; - } protocol::String statusText; - if (!ObjectGetProtocolString(context, response, "statusText") - .To(&statusText)) { - ThrowEventError(isolate, "Missing response.statusText in event"); - return {}; - } Local headers_obj; - if (!ObjectGetObject(context, response, "headers").ToLocal(&headers_obj)) { - ThrowEventError(isolate, "Missing response.headers in event"); + if (!ObjectGetRequired(context, response, "status", &status, "response.") || + !ObjectGetRequired( + context, response, "statusText", &statusText, "response.") || + !ObjectGetRequired( + context, response, "headers", &headers_obj, "response.")) { return {}; } std::unique_ptr headers = @@ -208,15 +179,10 @@ NetworkAgent::NetworkAgent( void NetworkAgent::webSocketCreated(v8::Local context, v8::Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } protocol::String url; - if (!ObjectGetProtocolString(context, params, "url").To(&url)) { - ThrowEventError(isolate, "Missing url in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "url", &url)) { return; } std::unique_ptr initiator = @@ -230,15 +196,10 @@ void NetworkAgent::webSocketCreated(v8::Local context, void NetworkAgent::webSocketClosed(v8::Local context, v8::Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp)) { return; } frontend_->webSocketClosed(request_id, timestamp); @@ -246,20 +207,12 @@ void NetworkAgent::webSocketClosed(v8::Local context, void NetworkAgent::webSocketHandshakeResponseReceived( v8::Local context, v8::Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); - return; - } Local response_obj; - if (!ObjectGetObject(context, params, "response").ToLocal(&response_obj)) { - ThrowEventError(isolate, "Missing response in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp) || + !ObjectGetRequired(context, params, "response", &response_obj)) { return; } auto response = createWebSocketResponse(context, response_obj); @@ -431,27 +384,18 @@ protocol::DispatchResponse NetworkAgent::loadNetworkResource( void NetworkAgent::requestWillBeSent(v8::Local context, v8::Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); - return; - } double wall_time; - if (!ObjectGetDouble(context, params, "wallTime").To(&wall_time)) { - ThrowEventError(isolate, "Missing wallTime in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp) || + !ObjectGetRequired(context, params, "wallTime", &wall_time)) { return; } protocol::String charset = ObjectGetProtocolString(context, params, "charset").FromMaybe(""); Local request_obj; - if (!ObjectGetObject(context, params, "request").ToLocal(&request_obj)) { - ThrowEventError(isolate, "Missing request in event"); + if (!ObjectGetRequired(context, params, "request", &request_obj)) { return; } std::unique_ptr request = @@ -487,25 +431,14 @@ void NetworkAgent::requestWillBeSent(v8::Local context, void NetworkAgent::responseReceived(v8::Local context, v8::Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); - return; - } protocol::String type; - if (!ObjectGetProtocolString(context, params, "type").To(&type)) { - ThrowEventError(isolate, "Missing type in event"); - return; - } Local response_obj; - if (!ObjectGetObject(context, params, "response").ToLocal(&response_obj)) { - ThrowEventError(isolate, "Missing response in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp) || + !ObjectGetRequired(context, params, "type", &type) || + !ObjectGetRequired(context, params, "response", &response_obj)) { return; } auto response = createResponseFromObject(context, response_obj); @@ -525,25 +458,14 @@ void NetworkAgent::responseReceived(v8::Local context, void NetworkAgent::loadingFailed(v8::Local context, v8::Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); - return; - } protocol::String type; - if (!ObjectGetProtocolString(context, params, "type").To(&type)) { - ThrowEventError(isolate, "Missing type in event"); - return; - } protocol::String error_text; - if (!ObjectGetProtocolString(context, params, "errorText").To(&error_text)) { - ThrowEventError(isolate, "Missing errorText in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp) || + !ObjectGetRequired(context, params, "type", &type) || + !ObjectGetRequired(context, params, "errorText", &error_text)) { return; } @@ -554,15 +476,10 @@ void NetworkAgent::loadingFailed(v8::Local context, void NetworkAgent::loadingFinished(v8::Local context, Local params) { - Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp)) { return; } @@ -586,8 +503,7 @@ void NetworkAgent::dataSent(v8::Local context, v8::Local params) { Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id)) { return; } @@ -605,18 +521,11 @@ void NetworkAgent::dataSent(v8::Local context, } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); - return; - } int data_length; - if (!ObjectGetInt(context, params, "dataLength").To(&data_length)) { - ThrowEventError(isolate, "Missing dataLength in event"); - return; - } Local data_obj; - if (!ObjectGetObject(context, params, "data").ToLocal(&data_obj)) { - ThrowEventError(isolate, "Missing data in event"); + if (!ObjectGetRequired(context, params, "timestamp", ×tamp) || + !ObjectGetRequired(context, params, "dataLength", &data_length) || + !ObjectGetRequired(context, params, "data", &data_obj)) { return; } if (!data_obj->IsUint8Array()) { @@ -632,29 +541,16 @@ void NetworkAgent::dataReceived(v8::Local context, v8::Local params) { Isolate* isolate = env_->isolate(); protocol::String request_id; - if (!ObjectGetProtocolString(context, params, "requestId").To(&request_id)) { - ThrowEventError(isolate, "Missing requestId in event"); - return; - } double timestamp; - if (!ObjectGetDouble(context, params, "timestamp").To(×tamp)) { - ThrowEventError(isolate, "Missing timestamp in event"); - return; - } int data_length; - if (!ObjectGetInt(context, params, "dataLength").To(&data_length)) { - ThrowEventError(isolate, "Missing dataLength in event"); - return; - } int encoded_data_length; - if (!ObjectGetInt(context, params, "encodedDataLength") - .To(&encoded_data_length)) { - ThrowEventError(isolate, "Missing encodedDataLength in event"); - return; - } Local data_obj; - if (!ObjectGetObject(context, params, "data").ToLocal(&data_obj)) { - ThrowEventError(isolate, "Missing data in event"); + if (!ObjectGetRequired(context, params, "requestId", &request_id) || + !ObjectGetRequired(context, params, "timestamp", ×tamp) || + !ObjectGetRequired(context, params, "dataLength", &data_length) || + !ObjectGetRequired( + context, params, "encodedDataLength", &encoded_data_length) || + !ObjectGetRequired(context, params, "data", &data_obj)) { return; } if (!data_obj->IsUint8Array()) { From 43f99b05fe065bacca828e3640739b3b8953d67d Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:44:00 +0000 Subject: [PATCH 06/11] src: share method template setup in util.cc The SetMethod(), SetFastMethod(), SetMethodNoSideEffect(), SetProtoMethod(), SetInstanceMethod(), and SetProto*Dispose() variants each repeated the same function template construction, internalized name string creation, and installation code, differing only in side effect type, receiver signature, and target. Factor that into a small set of internal helpers. Assisted-by: Claude --- src/util.cc | 395 +++++++++++++++++++++++----------------------------- 1 file changed, 176 insertions(+), 219 deletions(-) diff --git a/src/util.cc b/src/util.cc index 179474928626..9671379d3335 100644 --- a/src/util.cc +++ b/src/util.cc @@ -305,44 +305,98 @@ Local NewFunctionTemplate( c_function); } +namespace { + +// kInternalized strings are created in the old space. +Local NewMethodName(Isolate* isolate, const std::string_view name) { + return v8::String::NewFromUtf8(isolate, + name.data(), + v8::NewStringType::kInternalized, + name.size()) + .ToLocalChecked(); +} + +// Creates the template for a non-constructible method. When `receiver` is not +// empty, calls are restricted to instances of it via a receiver signature. +Local NewMethodTemplate( + Isolate* isolate, + v8::FunctionCallback callback, + v8::SideEffectType side_effect_type, + const v8::CFunction* c_function = nullptr, + Local receiver = {}) { + return NewFunctionTemplate(isolate, + callback, + receiver.IsEmpty() + ? Local() + : v8::Signature::New(isolate, receiver), + v8::ConstructorBehavior::kThrow, + side_effect_type, + c_function); +} + +Local NewMethodTemplate( + Isolate* isolate, + v8::FunctionCallback slow_callback, + v8::SideEffectType side_effect_type, + const v8::MemorySpan& methods) { + return FunctionTemplate::NewWithCFunctionOverloads( + isolate, + slow_callback, + Local(), + Local(), + 0, + v8::ConstructorBehavior::kThrow, + side_effect_type, + methods); +} + +// Instantiates `t` in `context` and installs it on `that` as `name`. +void SetMethodFromTemplate(Local context, + Local that, + const std::string_view name, + Local t, + bool set_function_name) { + Isolate* isolate = Isolate::GetCurrent(); + Local function = t->GetFunction(context).ToLocalChecked(); + Local name_string = NewMethodName(isolate, name); + that->Set(context, name_string, function).Check(); + if (set_function_name) { + function->SetName(name_string); // NODE_SET_METHOD() compatibility. + } +} + +// Installs `t` on the prototype or instance template of `that` as `name`. +void SetClassMethodFromTemplate(Isolate* isolate, + Local that, + const std::string_view name, + Local t) { + Local name_string = NewMethodName(isolate, name); + that->Set(name_string, t); + t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. +} + +} // namespace + void SetMethod(Local context, Local that, const std::string_view name, v8::FunctionCallback callback) { - Isolate* isolate = Isolate::GetCurrent(); - Local function = - NewFunctionTemplate(isolate, - callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect) - ->GetFunction(context) - .ToLocalChecked(); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(context, name_string, function).Check(); - function->SetName(name_string); // NODE_SET_METHOD() compatibility. + SetMethodFromTemplate( + context, + that, + name, + NewMethodTemplate( + Isolate::GetCurrent(), callback, v8::SideEffectType::kHasSideEffect), + true); } void SetMethod(v8::Isolate* isolate, v8::Local that, const std::string_view name, v8::FunctionCallback callback) { - Local t = - NewFunctionTemplate(isolate, - callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(name_string, t); + that->Set( + NewMethodName(isolate, name), + NewMethodTemplate(isolate, callback, v8::SideEffectType::kHasSideEffect)); } void SetFastMethod(Isolate* isolate, @@ -350,19 +404,11 @@ void SetFastMethod(Isolate* isolate, const std::string_view name, v8::FunctionCallback slow_callback, const v8::CFunction* c_function) { - Local t = - NewFunctionTemplate(isolate, - slow_callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect, - c_function); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(name_string, t); + that->Set(NewMethodName(isolate, name), + NewMethodTemplate(isolate, + slow_callback, + v8::SideEffectType::kHasSideEffect, + c_function)); } void SetFastMethod(Local context, @@ -370,21 +416,14 @@ void SetFastMethod(Local context, const std::string_view name, v8::FunctionCallback slow_callback, const v8::CFunction* c_function) { - Isolate* isolate = Isolate::GetCurrent(); - Local function = - NewFunctionTemplate(isolate, - slow_callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect, - c_function) - ->GetFunction(context) - .ToLocalChecked(); - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(context, name_string, function).Check(); + SetMethodFromTemplate(context, + that, + name, + NewMethodTemplate(Isolate::GetCurrent(), + slow_callback, + v8::SideEffectType::kHasSideEffect, + c_function), + false); } void SetFastMethodNoSideEffect(Local context, @@ -392,21 +431,14 @@ void SetFastMethodNoSideEffect(Local context, const std::string_view name, v8::FunctionCallback slow_callback, const v8::CFunction* c_function) { - Isolate* isolate = Isolate::GetCurrent(); - Local function = - NewFunctionTemplate(isolate, - slow_callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect, - c_function) - ->GetFunction(context) - .ToLocalChecked(); - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(context, name_string, function).Check(); + SetMethodFromTemplate(context, + that, + name, + NewMethodTemplate(Isolate::GetCurrent(), + slow_callback, + v8::SideEffectType::kHasNoSideEffect, + c_function), + false); } void SetFastMethodNoSideEffect(Isolate* isolate, @@ -414,19 +446,11 @@ void SetFastMethodNoSideEffect(Isolate* isolate, const std::string_view name, v8::FunctionCallback slow_callback, const v8::CFunction* c_function) { - Local t = - NewFunctionTemplate(isolate, - slow_callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect, - c_function); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(name_string, t); + that->Set(NewMethodName(isolate, name), + NewMethodTemplate(isolate, + slow_callback, + v8::SideEffectType::kHasNoSideEffect, + c_function)); } void SetFastMethod(Isolate* isolate, @@ -434,22 +458,10 @@ void SetFastMethod(Isolate* isolate, const std::string_view name, v8::FunctionCallback slow_callback, const v8::MemorySpan& methods) { - Local t = FunctionTemplate::NewWithCFunctionOverloads( - isolate, - slow_callback, - Local(), - Local(), - 0, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect, - methods); - - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(name_string, t); + that->Set( + NewMethodName(isolate, name), + NewMethodTemplate( + isolate, slow_callback, v8::SideEffectType::kHasSideEffect, methods)); } void SetFastMethodNoSideEffect( @@ -458,22 +470,11 @@ void SetFastMethodNoSideEffect( const std::string_view name, v8::FunctionCallback slow_callback, const v8::MemorySpan& methods) { - Local t = FunctionTemplate::NewWithCFunctionOverloads( - isolate, - slow_callback, - Local(), - Local(), - 0, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect, - methods); - - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(name_string, t); + that->Set(NewMethodName(isolate, name), + NewMethodTemplate(isolate, + slow_callback, + v8::SideEffectType::kHasNoSideEffect, + methods)); } void SetFastMethodNoSideEffect( @@ -482,149 +483,105 @@ void SetFastMethodNoSideEffect( const std::string_view name, v8::FunctionCallback slow_callback, const v8::MemorySpan& methods) { - Isolate* isolate = Isolate::GetCurrent(); - Local function = FunctionTemplate::NewWithCFunctionOverloads( - isolate, - slow_callback, - Local(), - Local(), - 0, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect, - methods) - ->GetFunction(context) - .ToLocalChecked(); - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(context, name_string, function).Check(); + SetMethodFromTemplate(context, + that, + name, + NewMethodTemplate(Isolate::GetCurrent(), + slow_callback, + v8::SideEffectType::kHasNoSideEffect, + methods), + false); } void SetMethodNoSideEffect(Local context, Local that, const std::string_view name, v8::FunctionCallback callback) { - Isolate* isolate = Isolate::GetCurrent(); - Local function = - NewFunctionTemplate(isolate, - callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect) - ->GetFunction(context) - .ToLocalChecked(); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(context, name_string, function).Check(); - function->SetName(name_string); // NODE_SET_METHOD() compatibility. + SetMethodFromTemplate(context, + that, + name, + NewMethodTemplate(Isolate::GetCurrent(), + callback, + v8::SideEffectType::kHasNoSideEffect), + true); } void SetMethodNoSideEffect(Isolate* isolate, Local that, const std::string_view name, v8::FunctionCallback callback) { - Local t = - NewFunctionTemplate(isolate, - callback, - Local(), - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->Set(name_string, t); + that->Set(NewMethodName(isolate, name), + NewMethodTemplate( + isolate, callback, v8::SideEffectType::kHasNoSideEffect)); } void SetProtoDispose(v8::Isolate* isolate, v8::Local that, v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate, that); - Local t = - NewFunctionTemplate(isolate, - callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - that->PrototypeTemplate()->Set(v8::Symbol::GetDispose(isolate), t); + that->PrototypeTemplate()->Set( + v8::Symbol::GetDispose(isolate), + NewMethodTemplate(isolate, + callback, + v8::SideEffectType::kHasSideEffect, + nullptr, + that)); } void SetProtoAsyncDispose(v8::Isolate* isolate, v8::Local that, v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate, that); - Local t = - NewFunctionTemplate(isolate, - callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - that->PrototypeTemplate()->Set(v8::Symbol::GetAsyncDispose(isolate), t); + that->PrototypeTemplate()->Set( + v8::Symbol::GetAsyncDispose(isolate), + NewMethodTemplate(isolate, + callback, + v8::SideEffectType::kHasSideEffect, + nullptr, + that)); } void SetProtoMethod(v8::Isolate* isolate, Local that, const std::string_view name, v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate, that); - Local t = - NewFunctionTemplate(isolate, - callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->PrototypeTemplate()->Set(name_string, t); - t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. + SetClassMethodFromTemplate( + isolate, + that->PrototypeTemplate(), + name, + NewMethodTemplate(isolate, + callback, + v8::SideEffectType::kHasSideEffect, + nullptr, + that)); } void SetProtoMethodNoSideEffect(v8::Isolate* isolate, Local that, const std::string_view name, v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate, that); - Local t = - NewFunctionTemplate(isolate, - callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasNoSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->PrototypeTemplate()->Set(name_string, t); - t->SetClassName(name_string); // NODE_SET_PROTOTYPE_METHOD() compatibility. + SetClassMethodFromTemplate( + isolate, + that->PrototypeTemplate(), + name, + NewMethodTemplate(isolate, + callback, + v8::SideEffectType::kHasNoSideEffect, + nullptr, + that)); } void SetInstanceMethod(v8::Isolate* isolate, Local that, const std::string_view name, v8::FunctionCallback callback) { - Local signature = v8::Signature::New(isolate, that); - Local t = - NewFunctionTemplate(isolate, - callback, - signature, - v8::ConstructorBehavior::kThrow, - v8::SideEffectType::kHasSideEffect); - // kInternalized strings are created in the old space. - const v8::NewStringType type = v8::NewStringType::kInternalized; - Local name_string = - v8::String::NewFromUtf8(isolate, name.data(), type, name.size()) - .ToLocalChecked(); - that->InstanceTemplate()->Set(name_string, t); - t->SetClassName(name_string); + SetClassMethodFromTemplate( + isolate, + that->InstanceTemplate(), + name, + NewMethodTemplate(isolate, + callback, + v8::SideEffectType::kHasSideEffect, + nullptr, + that)); } void SetConstructorFunction(Local context, From ae38b3be874827c3bad354d9c3f578670dc978d8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:44:18 +0000 Subject: [PATCH 07/11] module: add missing return in ImportMetaResolveLazyGetter When the creation context of the import.meta object has no associated Realm, the getter threw ERR_INVALID_INVOCATION but then fell through and dereferenced the null Realm. Return after throwing, as the other error paths in the getter already do. Assisted-by: Claude --- src/module_wrap.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 444d31337531..97923b414970 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -1250,6 +1250,7 @@ static void ImportMetaResolveLazyGetter( Realm* realm = Realm::GetCurrent(context); if (realm == nullptr) { THROW_ERR_INVALID_INVOCATION(isolate); + return; } Local initializer = realm->host_import_meta_resolve_initializer(); if (initializer.IsEmpty()) { From 12ff91e6add7346349deac3e060174505877af61 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:44:52 +0000 Subject: [PATCH 08/11] module: share holder creation context lookup in import.meta getters ImportMetaResolveLazyGetter() and PathHelpersLazyGetter() duplicated the code that retrieves the creation context from the holder object. Move it into a shared GetHolderCreationContext() helper. Assisted-by: Claude --- src/module_wrap.cc | 38 +++++++++++++++++--------------------- 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 97923b414970..5b4900cfd177 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -1233,18 +1233,26 @@ void ModuleWrap::SetImportMetaResolveInitializer( realm->set_host_import_meta_resolve_initializer(initializer); } +// The import.meta lazy getters have no JavaScript function representation and +// are not invoked in the creation context. When they are invoked in a vm +// context, `Realm::GetCurrent(info)` returns nullptr, so retrieve the creation +// context via the holder object instead. Throws and returns false on failure. +static bool GetHolderCreationContext(const PropertyCallbackInfo& info, + Local* context) { + Local receiver_val = info.Holder(); + if (!receiver_val->IsObject() || + !receiver_val.As()->GetCreationContext().ToLocal(context)) { + THROW_ERR_INVALID_INVOCATION(info.GetIsolate()); + return false; + } + return true; +} + static void ImportMetaResolveLazyGetter( Local name, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - Local receiver_val = info.Holder(); - if (!receiver_val->IsObject()) { - THROW_ERR_INVALID_INVOCATION(isolate); - return; - } - Local receiver = receiver_val.As(); Local context; - if (!receiver->GetCreationContext().ToLocal(&context)) { - THROW_ERR_INVALID_INVOCATION(isolate); + if (!GetHolderCreationContext(info, &context)) { return; } Realm* realm = Realm::GetCurrent(context); @@ -1273,20 +1281,8 @@ static void ImportMetaResolveLazyGetter( static void PathHelpersLazyGetter(Local name, const PropertyCallbackInfo& info) { Isolate* isolate = info.GetIsolate(); - // This getter has no JavaScript function representation and is not - // invoked in the creation context. - // When this getter is invoked in a vm context, the `Realm::GetCurrent(info)` - // returns a nullptr and retrieve the creation context via `this` object and - // get the creation Realm. - Local receiver_val = info.Holder(); - if (!receiver_val->IsObject()) { - THROW_ERR_INVALID_INVOCATION(isolate); - return; - } - Local receiver = receiver_val.As(); Local context; - if (!receiver->GetCreationContext().ToLocal(&context)) { - THROW_ERR_INVALID_INVOCATION(isolate); + if (!GetHolderCreationContext(info, &context)) { return; } Environment* env = Environment::GetCurrent(context); From 9a4d86f60564372f68fe5bb3854ac662d7895c75 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:45:58 +0000 Subject: [PATCH 09/11] report: look up exclusion options inside WriteNodeReport() All three callers of report::WriteNodeReport() computed the excludeNetwork and excludeEnv options the same way, falling back to the process-wide defaults when there is no Environment. Do that once inside WriteNodeReport() instead. Assisted-by: Claude --- src/node_report.cc | 77 ++++++++++++---------------------------------- 1 file changed, 19 insertions(+), 58 deletions(-) diff --git a/src/node_report.cc b/src/node_report.cc index 6f06be301743..f2d6ae3d80fd 100644 --- a/src/node_report.cc +++ b/src/node_report.cc @@ -62,9 +62,7 @@ static void WriteNodeReport(Isolate* isolate, std::string_view filename, std::ostream& out, Local error, - bool compact, - bool exclude_network = false, - bool exclude_env = false); + bool compact); static void PrintVersionInformation(JSONWriter* writer, bool exclude_network = false); static void PrintJavaScriptErrorStack(JSONWriter* writer, @@ -98,9 +96,18 @@ static void WriteNodeReport(Isolate* isolate, std::string_view filename, std::ostream& out, Local error, - bool compact, - bool exclude_network, - bool exclude_env) { + bool compact) { + // The report exclusion options are per-environment, so fall back to the + // process-wide defaults when there is no environment. + const bool exclude_network = env != nullptr + ? env->options()->report_exclude_network + : per_process::cli_options->per_isolate + ->per_env->report_exclude_network; + const bool exclude_env = + env != nullptr + ? env->report_exclude_env() + : per_process::cli_options->per_isolate->per_env->report_exclude_env; + // Obtain the current time and the pid. TIME_TYPE tm_struct; DiagnosticFilename::LocalTime(&tm_struct); @@ -921,24 +928,8 @@ std::string TriggerNodeReport(Isolate* isolate, compact = per_process::cli_options->report_compact; } - bool exclude_network = env != nullptr ? env->options()->report_exclude_network - : per_process::cli_options->per_isolate - ->per_env->report_exclude_network; - bool exclude_env = - env != nullptr - ? env->report_exclude_env() - : per_process::cli_options->per_isolate->per_env->report_exclude_env; - - report::WriteNodeReport(isolate, - env, - message, - trigger, - filename, - *outstream, - error, - compact, - exclude_network, - exclude_env); + report::WriteNodeReport( + isolate, env, message, trigger, filename, *outstream, error, compact); // Do not close stdout/stderr, only close files we opened. if (outfile.is_open()) { @@ -989,23 +980,8 @@ void GetNodeReport(Isolate* isolate, if (isolate != nullptr) { env = Environment::GetCurrent(isolate); } - bool exclude_network = env != nullptr ? env->options()->report_exclude_network - : per_process::cli_options->per_isolate - ->per_env->report_exclude_network; - bool exclude_env = - env != nullptr - ? env->report_exclude_env() - : per_process::cli_options->per_isolate->per_env->report_exclude_env; - report::WriteNodeReport(isolate, - env, - message, - trigger, - "", - out, - error, - false, - exclude_network, - exclude_env); + report::WriteNodeReport( + isolate, env, message, trigger, "", out, error, false); } // External function to trigger a report, writing to a supplied stream. @@ -1018,23 +994,8 @@ void GetNodeReport(Environment* env, if (env != nullptr) { isolate = env->isolate(); } - bool exclude_network = env != nullptr ? env->options()->report_exclude_network - : per_process::cli_options->per_isolate - ->per_env->report_exclude_network; - bool exclude_env = - env != nullptr - ? env->report_exclude_env() - : per_process::cli_options->per_isolate->per_env->report_exclude_env; - report::WriteNodeReport(isolate, - env, - message, - trigger, - "", - out, - error, - false, - exclude_network, - exclude_env); + report::WriteNodeReport( + isolate, env, message, trigger, "", out, error, false); } } // namespace node From 74319e9465fc57a896b9de876a3815d7dc792ebd Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:46:35 +0000 Subject: [PATCH 10/11] permission: share fast path for permission.has() FastHas() duplicated the scope parsing in FastHasResource(). Move the shared logic into FastHasImpl(), with FastHas() passing an empty resource. Assisted-by: Claude --- src/permission/permission.cc | 61 +++++++++++++++--------------------- 1 file changed, 26 insertions(+), 35 deletions(-) diff --git a/src/permission/permission.cc b/src/permission/permission.cc index 53d3a7657440..36b4f4a26efe 100644 --- a/src/permission/permission.cc +++ b/src/permission/permission.cc @@ -166,37 +166,12 @@ static void Has(const FunctionCallbackInfo& args) { return args.GetReturnValue().Set(env->permission()->is_granted(env, scope)); } -static bool FastHas(Local receiver, - Local scope_arg, - // NOLINTNEXTLINE(runtime/references) This is V8 api. - FastApiCallbackOptions& options) { - TRACK_V8_FAST_API_CALL("permission.has"); - auto isolate = options.isolate; - v8::HandleScope handle_scope(isolate); - auto context = isolate->GetCurrentContext(); - - Environment* env = Environment::GetCurrent(context); - - Local str; - if (!scope_arg->ToString(context).ToLocal(&str)) { - return false; - } - Utf8Value utf8_scope(isolate, str); - PermissionScope scope = - Permission::StringToPermission(utf8_scope.ToStringView()); - if (scope == PermissionScope::kPermissionsRoot) { - return false; - } - - return env->permission()->is_granted(env, scope); -} - -static bool FastHasResource( - Local receiver, - Local scope_arg, - Local resource_arg, - // NOLINTNEXTLINE(runtime/references) This is V8 api. - FastApiCallbackOptions& options) { +// Shared implementation of the fast paths below. An empty `resource_arg` +// checks the scope only. +static bool FastHasImpl(Local scope_arg, + Local resource_arg, + // NOLINTNEXTLINE(runtime/references) This is V8 api. + FastApiCallbackOptions& options) { TRACK_V8_FAST_API_CALL("permission.has"); auto isolate = options.isolate; v8::HandleScope handle_scope(isolate); @@ -215,10 +190,10 @@ static bool FastHasResource( return false; } - // The JS wrapper always calls this with 2 arguments, passing undefined - // when no resource was given, so this path (unlike Has()) has to check - // for that explicitly and fall back to the scope-only check. - if (resource_arg->IsUndefined()) { + // The JS wrapper always calls FastHasResource() with 2 arguments, passing + // undefined when no resource was given, so this path (unlike Has()) has to + // check for that explicitly and fall back to the scope-only check. + if (resource_arg.IsEmpty() || resource_arg->IsUndefined()) { return env->permission()->is_granted(env, scope); } @@ -233,6 +208,22 @@ static bool FastHasResource( return env->permission()->is_granted(env, scope, resource.ToStringView()); } +static bool FastHas(Local receiver, + Local scope_arg, + // NOLINTNEXTLINE(runtime/references) This is V8 api. + FastApiCallbackOptions& options) { + return FastHasImpl(scope_arg, Local(), options); +} + +static bool FastHasResource( + Local receiver, + Local scope_arg, + Local resource_arg, + // NOLINTNEXTLINE(runtime/references) This is V8 api. + FastApiCallbackOptions& options) { + return FastHasImpl(scope_arg, resource_arg, options); +} + static CFunction fast_has_methods_[] = {CFunction::Make(FastHas), CFunction::Make(FastHasResource)}; From 88b79b87c1bd709e899430244106056b888536b8 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Sun, 15 Nov 2026 18:49:55 +0000 Subject: [PATCH 11/11] src: share send handle setup in StreamBase write paths StreamBase::WriteBuffer() and WriteString() duplicated the code that creates a request object when needed and attaches the handle being sent over an IPC pipe. Move it into a shared PrepareSendHandle() helper. Assisted-by: Claude --- src/stream_base.cc | 80 +++++++++++++++++++++------------------------- 1 file changed, 36 insertions(+), 44 deletions(-) diff --git a/src/stream_base.cc b/src/stream_base.cc index 8592ca269a0c..392f6dbfe383 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -344,6 +344,36 @@ int StreamBase::Writev(const FunctionCallbackInfo& args) { return FinishWrite(args, res, lazy_req); } +// Prepares `send_handle_obj` to be sent over an IPC pipe. Sending a handle +// requires a request object up front to reference it, so one is created if +// `*req_wrap_obj` is empty. Returns 0 on success or an error code. +static int PrepareSendHandle(Environment* env, + Local send_handle_obj, + Local* req_wrap_obj, + uv_stream_t** send_handle) { + if (req_wrap_obj->IsEmpty()) { + if (!env->write_wrap_template() + ->InstanceTemplate() + ->NewInstance(env->context()) + .ToLocal(req_wrap_obj)) { + return UV_EBUSY; + } + StreamReq::ResetObject(*req_wrap_obj); + } + + HandleWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL); + *send_handle = reinterpret_cast(wrap->GetHandle()); + // Reference LibuvStreamWrap instance to prevent it from being garbage + // collected before `AfterWrite` is called. + if ((*req_wrap_obj) + ->Set(env->context(), env->handle_string(), send_handle_obj) + .IsNothing()) { + return -1; + } + return 0; +} + int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { CHECK(args[1]->IsUint8Array()); @@ -359,29 +389,9 @@ int StreamBase::WriteBuffer(const FunctionCallbackInfo& args) { uv_stream_t* send_handle = nullptr; if (args[2]->IsObject() && IsIPCPipe()) { - Local send_handle_obj = args[2].As(); - - if (lazy_req) { - // Sending a handle requires a request object up front to reference it. - if (!env->write_wrap_template() - ->InstanceTemplate() - ->NewInstance(env->context()) - .ToLocal(&req_wrap_obj)) { - return UV_EBUSY; - } - StreamReq::ResetObject(req_wrap_obj); - } - - HandleWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL); - send_handle = reinterpret_cast(wrap->GetHandle()); - // Reference LibuvStreamWrap instance to prevent it from being garbage - // collected before `AfterWrite` is called. - if (req_wrap_obj->Set(env->context(), - env->handle_string(), - send_handle_obj).IsNothing()) { - return -1; - } + const int err = PrepareSendHandle( + env, args[2].As(), &req_wrap_obj, &send_handle); + if (err != 0) return err; } StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj); @@ -471,27 +481,9 @@ int StreamBase::WriteString(const FunctionCallbackInfo& args) { uv_stream_t* send_handle = nullptr; if (IsIPCPipe() && !send_handle_obj.IsEmpty()) { - if (lazy_req && req_wrap_obj.IsEmpty()) { - // Sending a handle requires a request object up front to reference it. - if (!env->write_wrap_template() - ->InstanceTemplate() - ->NewInstance(env->context()) - .ToLocal(&req_wrap_obj)) { - return UV_EBUSY; - } - StreamReq::ResetObject(req_wrap_obj); - } - - HandleWrap* wrap; - ASSIGN_OR_RETURN_UNWRAP(&wrap, send_handle_obj, UV_EINVAL); - send_handle = reinterpret_cast(wrap->GetHandle()); - // Reference LibuvStreamWrap instance to prevent it from being garbage - // collected before `AfterWrite` is called. - if (req_wrap_obj->Set(env->context(), - env->handle_string(), - send_handle_obj).IsNothing()) { - return -1; - } + const int err = + PrepareSendHandle(env, send_handle_obj, &req_wrap_obj, &send_handle); + if (err != 0) return err; } StreamWriteResult res = Write(&buf, 1, send_handle, req_wrap_obj, try_write);