A package.json that exists but cannot be read was treated the same as
one that is not there: the read failure returned no config and
resolution continued as if the package had none. Fields such as
"exports" and "type" silently disappear, so a specifier can resolve to
a different file than the package declares, while an unparsable
package.json already throws ERR_INVALID_PACKAGE_CONFIG.
Keep treating ENOENT and ENOTDIR as "no package config here", and
report any other read failure with the underlying error.
Fixes: https://github.com/nodejs/node/issues/65220
Signed-off-by: Paul Bouchon <mail@bitpshr.net>
PR-URL: https://github.com/nodejs/node/pull/65223
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
TaskQueue became a std::priority_queue when worker tasks started to
honor v8::TaskPriority. Its comparator returns false for entry types
without a priority member, and for entries of equal priority, on the
assumption that the heap then keeps insertion order. It does not: three
tasks pushed A, B, C pop as A, C, B, and larger batches come out in
heap order. That affects the per-isolate foreground task queue (tasks
of one priority no longer run in the order they were posted), the
foreground delayed task queue, and the delayed task scheduler of the
worker thread task runner, whose local queue is drained in one batch:
when v8 posts a delayed worker task shortly before the platform shuts
down, the StopTask pushed by Stop() can run before a ScheduleTask that
was pushed earlier, that ScheduleTask then starts a timer on the
scheduler's loop after all timers were supposed to be stopped, and
Shutdown() blocks in uv_thread_join() until the delay (e.g. the 8 s of
the memory reducer) expires.
Give every queued item a sequence number and use it as the tie
breaker, so that tasks of equal priority, and tasks without one, come
out in FIFO order again; higher priorities still come first. PopAll()
now returns the tasks in that order instead of handing out the heap.
Signed-off-by: Shelley Vohr <shelley.vohr@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65353
Refs: https://github.com/nodejs/node/pull/58047
Refs: https://github.com/nodejs/node/pull/61999
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
An incoming stream was destroyed unless the session had an onstream
callback, even when session-level stream callbacks (onheaders et al)
were registered and the negotiated application (HTTP/3) would drive
the stream through them. Users had to register stub onstream handlers
just to keep their streams alive.
Destroy an incoming stream only when the session has no consumer for
it at all: no onstream callback, and no session-level stream callbacks
runnable on the negotiated application (checked via the existing
headersSupported session state, computed when the application is
selected from ALPN). Sessions with no consumers keep the current
destroy-and-warn behavior so unconsumed streams cannot accumulate and
hold flow control credit.
On HTTP/3 sessions only bidirectional request streams reach this path;
control and QPACK streams are consumed internally by nghttp3 and are
never exposed to JavaScript.
Fixes: https://github.com/nodejs/node/issues/64192
Signed-off-by: Naman Trivedi <trivenay@amazon.com>
PR-URL: https://github.com/nodejs/node/pull/65335
Fixes: https://github.com/nodejs/node/issues/64192
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
setInt8() through setUint64() require IsNumber() before any range check
and reject anything else with ERR_INVALID_ARG_VALUE, but setFloat32()
and setFloat64() call ToNumber() and write whatever it returns, so a
string, a boolean or a plain object is converted instead of rejected
and a typo such as '1,5' stores NaN in native memory with no error at
the call site. The same double is type-checked when it is passed as a
call argument: ToFFIArgument() requires IsNumber() and otherwise throws
"Argument %s must be a double".
The coercion also discards a pending exception. When ToNumber() fails
because the value has a valueOf() that throws, the branch throws
ERR_INVALID_ARG_VALUE on top of the exception V8 has already scheduled,
so the original error never reaches the caller, whereas
DataView.prototype.setFloat64() and Buffer.prototype.writeDoubleLE()
both propagate it.
Check IsNumber() instead, matching the wording of the integer setters
and of ToFFIArgument(). The check runs before any conversion, so
valueOf() is never invoked and there is no pending exception left to
discard. This was the only ToNumber(context) call in src/.
Signed-off-by: Soul Lee <alus20x@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65342
Fixes: https://github.com/nodejs/node/issues/65341
Refs: https://github.com/nodejs/node/pull/62858
Refs: https://github.com/nodejs/node/pull/64614
Refs: https://github.com/nodejs/node/pull/64691
Refs: https://github.com/nodejs/node/pull/65032
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com>
Reject offsets outside the destination buffer before subtracting from
its length in SlowWriteString. Normalize wrapper arguments once so
validated values reach the native binding.
Signed-off-by: Matteo Collina <hello@matteocollina.com>
PR-URL: https://github.com/nodejs/node/pull/65043
Reviewed-By: Robert Nagy <ronagy@icloud.com>
fs.readFile(path) took four libuv thread pool round trips for a typical
small file -- open, fstat, read and close, each its own uv_fs request
with its own queue wait, completion callback and JS/C++ crossing -- and
fs.promises.readFile(path) did the same through a FileHandle. For the
small files applications read most, the round trips are the cost, and
each occupies a slot in the pool that concurrent dns.lookup(), fs and
crypto work is also queueing for.
Add ReadFileJob (an AsyncWrap + ThreadPoolWork) that performs
open + fstat + read-to-EOF + close as one pool task and reports the
whole content, or, when the file turns out to be larger than one chunk
(kReadFileBufferLength, 512 KiB), stops after fstat() and hands the fd
and size back so that the existing chunked reader continues unchanged
(large reads stay interleaved and abortable between chunks, and still
save the fstat round trip). fs.readFile() and fs.promises.readFile()
use it for path arguments without a user buffer; file descriptors,
FileHandles, options.buffer and an active VFS keep their paths.
Behavior is otherwise kept: same bytes for every size and encoding;
open failures report syscall 'open' with the path, read failures
'read'; permission errors are delivered through the callback/promise
as before; an abort that arrives while the read is in flight still
wins; the job is an FSREQCALLBACK resource for async_hooks; a handed
back fd is tracked exactly like one from a plain open().
Tests that asserted the internal open/fstat/read/close request chain,
used readFile() as a proxy for an fstat trace event, or injected
faults through FileHandle.prototype for path-based reads are adjusted
to keep testing what they test (a file just over one chunk where the
chain shape matters, fs.fstat() for the fstat trace, a larger file so
the FileHandle path is taken).
fs.readFile() of 4 KiB files at concurrency 64 goes from ~51k to ~306k
files per second, and a mixed stat/readFile/dns.lookup burst from ~66k
to ~312k operations per second.
Signed-off-by: Shelley Vohr <shelley.vohr@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65327
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
StringBytes::Write() already used simdutf to encode one-byte strings
as UTF-8 but sent every two-byte (UTF-16) string through
v8::String::WriteUtf8V2(), which is several times slower. That path
is behind Buffer.from(string), buf.write(), fs.write*() with string
data and every string written to a libuv stream, and JSON.stringify()
output is a two-byte string as soon as any value in the payload is
outside Latin-1.
Encode two-byte strings with simdutf as well whenever their UTF-8 form
is guaranteed to fit in the target: well-formed input is converted
directly, and input with unpaired surrogates is converted from a copy
passed through simdutf::to_well_formed_utf16(), which replaces each
unpaired surrogate with U+FFFD exactly like kReplaceInvalidUtf8 (this
mirrors what TextEncoder already does). Writes that have to truncate
at a character boundary keep using WriteUtf8V2(), so their output is
byte-for-byte unchanged, and so do strings of up to 32 code units, for
which V8 is already as fast (the same threshold TextEncoder uses).
buf.write() of a 2 KiB two-byte string improves ~5x (astral-heavy and
lone-surrogate strings ~3.5x and ~5x), Buffer.from() of a 64 KiB JSON
string ~2.7x; one-byte strings are unaffected.
Signed-off-by: Shelley Vohr <shelley.vohr@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65324
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Daniel Lemire <daniel@lemire.me>
Reviewed-By: James M Snell <jasnell@gmail.com>
StringDecoder used v8::String::NewFromUtf8() for UTF-8, while
Buffer#toString() goes through StringBytes::Encode(), which has
simdutf-backed ASCII, Latin-1 and UTF-16 paths and only falls back
to NewFromUtf8() for input that contains invalid sequences. Route
the decoder through the same function, so streams with
setEncoding('utf8') and readline decode at the same speed as
Buffer#toString(). U+FFFD replacement is unchanged because invalid
input still ends up in NewFromUtf8(), and the ERR_STRING_TOO_LONG
check is kept explicit so over-long input fails as before.
benchmark/string_decoder/string-decoder.js (encoding=utf8) and a
readline-over-pipe workload improve by 2-3x for chunks >= 1 KiB;
64 KiB newline-delimited JSON round trips over child stdio improve
by ~30% on the reading side alone.
Signed-off-by: Shelley Vohr <shelley.vohr@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65324
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
Reviewed-By: Gürgün Dayıoğlu <hey@gurgun.day>
Reviewed-By: Daniel Lemire <daniel@lemire.me>
Reviewed-By: James M Snell <jasnell@gmail.com>
Long-term itch. Per v8 rules, we're not supposed to be
heap allocating v8::Local's; instead we're supposed to
be using v8::LocalVector. Create a specialization of
MaybeStackBuffer that uses either a stack array of
v8::Locals or v8::LocalVector with some additional
utility improvements.
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65159
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
InvokeCallback tested `args[i] == nullptr` and mapped the argument to
JS `null`. `args` is libffi's avalue array, and libffi always points
each slot at its own storage for the corresponding argument, so the
slot pointers are never null and the branch never ran.
The check also read as a guarantee the code does not provide: a NULL
pointer argument surfaces as the BigInt `0n`, because ToJSArgument
converts `ffi_type_pointer` values with BigInt::NewFromUnsigned. Drop
the branch rather than reimplementing it in ToJSArgument, which would
change behavior by making pointer parameters arrive as either a BigInt
or `null`.
Signed-off-by: Trivikram Kamat <16024985+trivikr@users.noreply.github.com>
Assisted-by: claude:opus-5
PR-URL: https://github.com/nodejs/node/pull/64998
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
SQLite requires that an authorizer callback not modify the connection
that invoked it, and counts sqlite3_prepare_v2() and sqlite3_step() as
modifications. node:sqlite let the callback call prepare(), exec(), the
statement execution methods, and other connection-mutating APIs on the
same DatabaseSync. Track authorizer depth on DatabaseSync with an RAII
guard around the callback and throw ERR_INVALID_STATE from the affected
entry points while it is on the stack. Covering every authorizer
invocation, including the re-prepare that SQLite can run during
sqlite3_step(), exposed a second and distinct hazard: reentering a
statement that is currently being stepped is a use-after-free rather
than a contract violation, since finalizing it frees the virtual machine
under sqlite3_step() and re-running it resets that machine
mid-execution. Any callback SQLite invokes during execution can reach
it, so a user-defined function is enough. Track the statements currently
being stepped and reject reentry into only those, which leaves a
user-defined function free to prepare, run, and finalize its own helper
statements.
Signed-off-by: Trevor Burnham <trevorburnham@gmail.com>
Fixes: https://github.com/nodejs/node/issues/63207
Assisted-by: claude:opus-5
PR-URL: https://github.com/nodejs/node/pull/65156
Reviewed-By: Xuguang Mei <meixuguang@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
Our inspector implementation dispatches inspector messages from
a V8 interrupt handler, so they could be handled during an arbitrary
point of JS execution where re-calling into another irrelevant JS
code is not safe.
This patch tracks V8 interrupt state in this case and rewrite the
async hook toggling as state reconciliation, so requests only record
the desired state, which is applied once calling into JS is possible
and safe, and the actual invocation is deferred to an immediate when
inside an interrupt. This simplifies the previous mechanism and
makes re-entracy and early termination safer.
Drive-by: skip installing command line API extensions during
teardown when calling into JS is no longer safe.
Signed-off-by: Joyee Cheung <joyeec9h3@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65028
Refs: https://issues.chromium.org/u/1/issues/42212250
Refs: https://chromium-review.googlesource.com/c/v8/v8/+/8173727
Refs: https://github.com/nodejs/node/pull/26935
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
While the Options objects are not a significant overhead,
they still waste a few hundred bytes due to sloppy definition
and alignment issues. Tighten it up and shave off a couple
hundred wasted bytes.
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65145
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Daniel Lemire <daniel@lemire.me>
Detached ArrayBuffers were rejected with ERR_INVALID_ARG_VALUE, but
detached views were not: typed arrays exported zero bytes and DataViews
threw a bare TypeError from byteLength.
Track detachment in ArrayBufferViewContents::Read() and skip the JS
length check for detached buffers, so every detached input is rejected.
Signed-off-by: Kamat, Trivikram <16024985+trivikr@users.noreply.github.com>
Assisted-by: codex:gpt-5.6-sol
PR-URL: https://github.com/nodejs/node/pull/65086
Fixes: https://github.com/nodejs/node/issues/65085
Reviewed-By: Paolo Insogna <paolo@cowtech.it>
Most of the PermissionBase subclasses used the identical
simple pattern. Rather than define a bunch of individual
identical permissions, use a single utility definition.
Special cases like FsPermission are still possible but
the simple case is kept... well, simple.
Signed-off-by: James M Snell <jasnell@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65158
Reviewed-By: Xuguang Mei <meixuguang@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Several improvements:
1. In histogram-inl, Add previous locked only this->mutex while
reading the other's fields unsafely.
2. In histogram.cc, PrepareCB now uses ContainerOf
3. In histogram.cc, BigInt value range is checked
4. In histogram.js, simplified impl and reduced duplication
5. In event_loop_delay.js, use a more consistent constructor
Adds new analytical APIs to Histogram
* histogram.ccdf(value)
* histogram.cdf(value)
* histogram.countAt(value)
* histogram.ksTest(other)
* histogram.kurtosis
* histogram.linearBuckets(stepSize)
* histogram.logBuckets(first, base)
* histogram.percentilesAt(percentiles)
* histogram.shewness
On RecordableHistogram
* histogram.recordCorrected(val, expectedInterval)
* histogram.subtract(other)
Signed-off-by: James M Snell <jasnell@gmail.com>
Assisted-by: Opencode/Opus
PR-URL: https://github.com/nodejs/node/pull/65024
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>