]> git.kaiwu.me - njs.git/log
njs.git
9 days agoFetch: free QuickJS response body chain after reading
Dmitry Volyntsev [Fri, 30 Oct 2026 03:16:10 +0000 (20:16 -0700)]
Fetch: free QuickJS response body chain after reading

Previously, Response.text(), json() and arrayBuffer() joined the body
chain into a new block of the engine pool and left both the chain
nodes and the joined copy in the pool.  The memory was released only
with the engine, so with js_context_reuse every response body read
accumulated in the pool, unaccounted by the context reuse memory
check.

Now, the chain is destroyed after the body is read.  For text() the
string is created with qjs_string_create_chb(), and for json() the
joined copy is freed after parsing.

The issue was introduced in b7f76b71 (0.9.1).

9 days agoQuickJS: free joined string with chain pool in qjs_string_create_chb()
Dmitry Volyntsev [Fri, 30 Oct 2026 03:14:34 +0000 (20:14 -0700)]
QuickJS: free joined string with chain pool in qjs_string_create_chb()

Previously, the joined string was freed with the JSContext passed as
the pool argument of the chain free function.  This only worked for
chains initialized with NJS_CHB_CTX_INIT(), where the pool is the
context itself.

Now, the chain pool is used, so the function works with chains using
any allocator.  No functional changes for existing callers.

9 days agoQuickJS: fix fs callback return value leak
Dmitry Volyntsev [Fri, 30 Oct 2026 01:40:09 +0000 (18:40 -0700)]
QuickJS: fix fs callback return value leak

Previously, the value returned by a callback passed to the callback
flavor of fs functions was never freed.  The value stayed referenced
until the runtime was freed, triggering the
"list_empty(&rt->gc_obj_list)" assertion in JS_FreeRuntime() in debug
builds and accumulating in the runtime with js_context_reuse.

The issue was introduced in 1f8f9992 (0.8.9).

9 days agoModules: fix subrequest response body leak in QuickJS
Dmitry Volyntsev [Fri, 30 Oct 2026 01:39:31 +0000 (18:39 -0700)]
Modules: fix subrequest response body leak in QuickJS

Previously, alternating r.responseText and r.responseBuffer on a
subrequest reply overwrote the cached req->response_body value
without freeing it.  The value stayed referenced until the runtime
was freed, triggering the "list_empty(&rt->gc_obj_list)" assertion
in JS_FreeRuntime() in debug builds and accumulating in the runtime
with js_context_reuse.

The fix is to free the cached value before replacing it, as is
already done for r.requestText and r.requestBuffer.

The issue was introduced in 201b1276 (0.8.6).

12 days agoWebCrypto: fix AES-CTR out-of-bounds write on empty input
Dmitry Volyntsev [Thu, 29 Oct 2026 16:17:33 +0000 (09:17 -0700)]
WebCrypto: fix AES-CTR out-of-bounds write on empty input

Previously, the AES-CTR block count helper computed the number of
blocks as "1 + (dend - 1) / dsor".  This underflows for a zero-length
input, so njs_ceil_div(0, 16) and qjs_ceiling_div(0, 16) returned
2^28 instead of 0.

The fix is to use the zero-safe "(dend + dsor - 1) / dsor" form.

The njs engine code was introduced in 7b2b7612 (0.7.0) and the
QuickJS counterpart in 75ca26f8 (0.8.10).

2 weeks agoParser: fix reference atom IDs on big-endian systems
Dmitry Volyntsev [Thu, 22 Oct 2026 04:49:20 +0000 (21:49 -0700)]
Parser: fix reference atom IDs on big-endian systems

Previously, references to local variables and function arguments
failed with ReferenceError on 64-bit big-endian systems.  The parser
overwrote a uintptr_t reference atom ID through the overlapping
uint32_t value member, replacing the high half of the ID.

The issue was introduced in 9ff881e3 (1.0.2), which moved the
reference atom ID to the start of the parser node union.

Now, reference and value payloads share a uint32_t atom ID at the same
offset, initialized in the corresponding parser paths.
This removes the redundant value-member write and makes atom ID access
independent of byte order without increasing the parser node size.

This fixes #1143.

2 weeks agoCI: split CLI and nginx checks into parallel jobs
Dmitry Volyntsev [Thu, 22 Oct 2026 23:27:06 +0000 (16:27 -0700)]
CI: split CLI and nginx checks into parallel jobs

Previously, check-pr runs all build configurations sequentially, so
an early failure prevents later configurations from being tested.

Split CLI checks into matrix configurations and nginx checks
into separate njs, QuickJS, and QuickJS-NG matrix jobs.  Disable
fail-fast and use fresh build directories without make clean.

Preserve the nginx module and SSL configure flags, sanitizer and
debug-memory settings, QuickJS-NG version, checkout action revision,
test commands, and failed-test retries.

Make engine selection explicit: njs jobs no longer auto-detect
QuickJS-NG, and the QuickJS CLI build uses an explicit library.

2 weeks agoCI: add big-endian build and tests
Dmitry Volyntsev [Thu, 22 Oct 2026 22:41:10 +0000 (15:41 -0700)]
CI: add big-endian build and tests

Previously, GitHub Actions did not test the built-in engine on
big-endian systems, leaving byte-order regressions undetected.

2 weeks agoModules: fix incremental engine build dependencies
Dmitry Volyntsev [Thu, 22 Oct 2026 00:38:04 +0000 (17:38 -0700)]
Modules: fix incremental engine build dependencies

Existing archives prevent the nested make from checking engine source
changes.  QuickJS builds also omit libnjs.a and engine headers from
the module dependencies.

Changes to engine sources are now picked up by nginx make without
rerunning configure or removing the existing libraries.

2 weeks agoModules: isolate engine builds from the standalone CLI
Dmitry Volyntsev [Thu, 22 Oct 2026 00:37:10 +0000 (17:37 -0700)]
Modules: isolate engine builds from the standalone CLI

nginx and the CLI share build artifacts and configuration.  Building
nginx replaces the CLI Makefile, while rebuilding the CLI can leave
nginx linking libraries compiled with incompatible flags.

Building nginx no longer changes the CLI configuration or libraries.
Rebuilding the CLI no longer breaks subsequent nginx builds.

2 weeks agoConfigure: fix pkg-config paths for absolute build directories
Dmitry Volyntsev [Thu, 22 Oct 2026 14:14:14 +0000 (07:14 -0700)]
Configure: fix pkg-config paths for absolute build directories

The generated njs.pc prepends the source directory to an absolute
build directory, producing invalid include and library paths.

Preserve absolute build paths and resolve only relative ones against
the source directory.  This also supports engine builds embedded in
nginx without changing the standalone CLI configuration.

2 weeks agoConfigure: allow explicit QuickJS library selection
Dmitry Volyntsev [Thu, 22 Oct 2026 00:36:28 +0000 (17:36 -0700)]
Configure: allow explicit QuickJS library selection

Independent configure runs can select different QuickJS libraries.
Allow callers to pass the selected headers and linker options without
falling back to another library.

2 weeks agoConfigure: add configure mode without a source-root Makefile
Dmitry Volyntsev [Thu, 22 Oct 2026 00:35:52 +0000 (17:35 -0700)]
Configure: add configure mode without a source-root Makefile

Configuring a separate build directory still replaces the source-root
Makefile and redirects subsequent CLI builds.  Allow embedded builds
to leave the standalone build entry point unchanged.

3 weeks agoWebCrypto: return false for wrong-length ECDSA signatures
Dmitry Volyntsev [Thu, 15 Oct 2026 06:06:08 +0000 (23:06 -0700)]
WebCrypto: return false for wrong-length ECDSA signatures

ECDSA signatures of an invalid length cause verify() to throw instead
of returning false.  njs passes an empty DER signature to
EVP_PKEY_verify(), while QuickJS rejects the length during conversion.

The njs behavior dates back to 86c202c7 (0.7.7); QuickJS rejects these
signatures since 75ca26f8 (0.8.10).

Treat a length mismatch as an invalid signature, as required by
WebCrypto ECDSA Verify, while preserving diagnostics for conversion
failures.  Test all three supported curves with invalid lengths and
a valid signature.

3 weeks agoWebCrypto: clear OpenSSL errors after a signature mismatch
Dmitry Volyntsev [Wed, 14 Oct 2026 05:18:37 +0000 (22:18 -0700)]
WebCrypto: clear OpenSSL errors after a signature mismatch

Previously, crypto.subtle.verify(false) could leave errors for an
unrelated TLS handshake or WebCrypto operation.

The fix is to clear the queue when returning false, while retaining
diagnostics for operation failures.

This fixes #1141.

3 weeks agoWebCrypto: fix algorithm availability in nginx modules
Dmitry Volyntsev [Tue, 13 Oct 2026 05:37:30 +0000 (22:37 -0700)]
WebCrypto: fix algorithm availability in nginx modules

Previously, configure probes disabled Ed25519, X25519, and AES-KW in
nginx modules because the engine is configured with --no-openssl,
although WebCrypto uses nginx's OpenSSL and these algorithms were
available.

The fix is to detect 25519 APIs from OpenSSL headers and look up AES-KW
ciphers at runtime, removing the dependency on engine configuration
and direct references to wrap functions absent in some OpenSSL flavors.

This fixes #1139.

3 weeks agoModules: treat expired shared dict entries as absent
Dmitry Volyntsev [Sat, 10 Oct 2026 01:54:41 +0000 (18:54 -0700)]
Modules: treat expired shared dict entries as absent

Expired entries are hidden by read APIs but can still be found by
write operations.  replace() can revive an expired entry, delete()
can report that it existed, and incr() can use its old value instead
of init.  Without an explicit timeout, incr() can return a value that
a subsequent get() cannot retrieve.

Use a common write-side lookup to remove expired entries and handle
them as missing in both engines.  incr() then creates a new entry
with init plus delta and the directive or explicit timeout.

Also return false instead of undefined when QuickJS delete() is
called for a missing key.

3 weeks agoModules: fix shared dict state JSON separators
Dmitry Volyntsev [Sat, 10 Oct 2026 01:40:28 +0000 (18:40 -0700)]
Modules: fix shared dict state JSON separators

When saving a shared dict zone with timeout=, expired entries are
skipped.  A comma is appended whenever another tree node follows a live
entry, even if all remaining nodes are expired.  This can leave a
trailing comma in the state file, making it invalid JSON.

Insert commas before live entries only when a previous entry has been
rendered, so skipped entries do not affect the separators.

3 weeks agoModules: initialize shared dict state entry expiration
Dmitry Volyntsev [Sat, 10 Oct 2026 01:36:20 +0000 (18:36 -0700)]
Modules: initialize shared dict state entry expiration

When a shared dict state entry omits the optional expire field, its
expiration remains uninitialized.  In a zone with timeout=, the entry
can be discarded as expired or loaded with an arbitrary expiration
instead of receiving the zone timeout.

Initialize expiration to zero before parsing the entry so an omitted
expire field is treated like an explicit zero.  The entry then receives
the zone timeout and the state file is scheduled for saving.

3 weeks agoModules: limit waiting for shared dict state save on exit
Dmitry Volyntsev [Wed, 14 Oct 2026 23:39:07 +0000 (16:39 -0700)]
Modules: limit waiting for shared dict state save on exit

If a worker dies while saving a shared dict zone state, the writing
flag remains set in shared memory and survives reloads.  Workers
with unsaved changes then receive NGX_AGAIN on every attempt and
keep rearming the save timer, so they never finish graceful shutdown.

Limit how long an exiting worker waits for an outstanding save to
60 seconds since the save started.  The shared writing flag is not
cleared and the writer is not interrupted, so a slow save is not
disturbed.  Running workers keep waiting as before.

3 weeks agoModules: track shared dict state changes per worker
Dmitry Volyntsev [Sat, 10 Oct 2026 01:32:25 +0000 (18:32 -0700)]
Modules: track shared dict state changes per worker

With frequent changes to a shared dict zone using state=, old workers
can remain in shutting down after a configuration reload and continue
consuming resources even though their changes have already been included
in another worker's snapshot.  The shared dirty flag cannot distinguish
those changes from subsequent changes made by new workers, so old
workers can keep rearming their save timers while competing for writes.

Replace the shared dirty flag with a write_id counter and record its
value locally in each worker on mutation.  Advance the shared counter
after preparing a snapshot so workers whose changes are covered can
stop retrying regardless of subsequent mutations.  On I/O failure, the
writer records the advanced counter locally to retain responsibility
for retrying the save.

3 weeks agoModules: limit shared dict state save frequency
Dmitry Volyntsev [Sat, 10 Oct 2026 01:16:25 +0000 (18:16 -0700)]
Modules: limit shared dict state save frequency

Saving shared dict zone content to file is scheduled with a maximum
rate of one write per second in each worker.  The total rate can be
larger by a factor of the number of running workers.

Postpone a zone save if the previous save was less than one second
ago, using a shared timestamp to limit the rate across all workers.

3 weeks agoModules: fix shared dict state save error ordering
Dmitry Volyntsev [Sat, 10 Oct 2026 01:03:47 +0000 (18:03 -0700)]
Modules: fix shared dict state save error ordering

On save failure, writing is cleared before dirty is restored.  Another
worker can observe a clean, idle zone and stop retrying.  If the failed
writer is exiting, it also stops retrying and the changes remain unsaved.

Set dirty first and add a memory barrier before clearing writing to
publish the need for another save before releasing the writer.

3 weeks agoModules: fixed shared dict state save stuck forever
vitalyn [Fri, 2 Oct 2026 21:50:43 +0000 (23:50 +0200)]
Modules: fixed shared dict state save stuck forever

The "dirty" and "writing" flags of a shared dict were bit fields of
the same word.  ngx_js_dict_save() clears "writing" without holding
the lock, while set(), incr(), delete() and clear() set "dirty" under
the write lock in other workers.  The two read-modify-write operations
could interleave and leave "writing" set for good.

After that, every save attempt returned NGX_AGAIN: the state file was
never written again, and the save timer, re-armed every second and not
cancelable, prevented any worker of the zone from finishing a graceful
shutdown, regardless of worker_shutdown_timeout.  The flag lives in
shared memory, so it survived reloads.

The fix is to store the flags in separate words.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This fixes #1136.

3 weeks agoModules: abort shared dict state save on close failure
Dmitry Volyntsev [Fri, 9 Oct 2026 23:03:38 +0000 (16:03 -0700)]
Modules: abort shared dict state save on close failure

A close failure may report a delayed write error.  Do not rename the
temporary file over the previous state file in this case.  Invalidate
the descriptor before cleanup to avoid closing it twice.

3 weeks agoModules: initialize shared dict state file before allocation
Dmitry Volyntsev [Fri, 9 Oct 2026 22:59:52 +0000 (15:59 -0700)]
Modules: initialize shared dict state file before allocation

Initialize the state file descriptor before allocating chain links and
buffers.  Allocation failures otherwise reach cleanup with an
uninitialized descriptor and may close an unrelated file.

3 weeks agoModules: preserve shared dict entries on failed updates
Dmitry Volyntsev [Tue, 11 Aug 2026 21:29:33 +0000 (14:29 -0700)]
Modules: preserve shared dict entries on failed updates

Shared dictionary updates temporarily remove timeout entries from the
expiration rbtree to prevent eviction while allocating a replacement.
ngx_rbtree_delete() clears the removed node key, so the failure path
reinserted the entry with a zero expiration and made its old value appear
expired.

Factor the shared-memory update into an engine-independent helper and
restore the previous expiration when allocation fails.  Keep value
conversion in the njs and QuickJS wrappers.

3 weeks agoVersion bump
Dmitry Volyntsev [Wed, 14 Oct 2026 15:24:44 +0000 (08:24 -0700)]
Version bump

5 weeks agoVersion 1.0.2 1.0.2
Dmitry Volyntsev [Wed, 30 Sep 2026 04:51:00 +0000 (21:51 -0700)]
Version 1.0.2

5 weeks agoXML: return complete attribute values
Dmitry Volyntsev [Wed, 16 Sep 2026 23:17:58 +0000 (16:17 -0700)]
XML: return complete attribute values

Previously, $attr$ returned undefined for attributes containing entity
references, while $attrs returned only the first text fragment. libxml2
canonicalization expands the complete attribute value, creating an
interpretation difference for signed XML consumers.

Use xmlNodeGetContent() for both getters in the njs and QuickJS backends.
This preserves the existing explicit-attribute lookup and makes the
JavaScript value agree with canonicalization.

5 weeks agoXML: release parser context after parsing
Dmitry Volyntsev [Wed, 16 Sep 2026 22:03:40 +0000 (15:03 -0700)]
XML: release parser context after parsing

Previously, XML parser contexts were retained with their parsed documents.
When parsing failed in the njs engine, no cleanup was registered, leaking
the context and allowing repeated malformed XML input to grow memory usage
in long-lived NGINX worker processes.

The fix is to limit parser contexts to the parse operation and release
them immediately after parsing or error reporting. The VM cleanup now owns
only the parsed document.

5 weeks agoVM: report import of a module removed after failed compilation
Dmitry Volyntsev [Wed, 30 Sep 2026 06:12:30 +0000 (23:12 -0700)]
VM: report import of a module removed after failed compilation

A module whose compilation fails is removed from the cache, but another
module compiled earlier in the same cycle may still import it.  Executing
such an import returned an error without setting an exception, so the
shell reported an unrelated TypeError.

Throw "Cannot load module" instead, and add a shell test for a cyclic
dependency of a module that fails to compile.

5 weeks agoVM: preserve dependency code after failed module compilation
Dmitry Volyntsev [Wed, 30 Sep 2026 06:06:42 +0000 (23:06 -0700)]
VM: preserve dependency code after failed module compilation

Commit fd54d52d freed all bytecode added after the parent module's
compilation checkpoint, including successfully compiled dependencies.
Those dependencies remain cached, so a later import in the same VM
executes freed bytecode.  This is reachable in the interactive shell
and in embedders that continue after a compilation error.

The fix is to remove eager bytecode cleanup while retaining removal of
the failed module from the cache so subsequent loads can retry.  Keep
the removed module and its name in the VM pool because cyclic
dependencies and code metadata can still reference them.  These
allocations are released when the VM is destroyed.

Add a shell regression test that retries a failed parent import and then
executes its cached dependency.

6 weeks agoXML: preserve node methods with matching children
Dmitry Volyntsev [Tue, 29 Sep 2026 05:23:45 +0000 (22:23 -0700)]
XML: preserve node methods with matching children

QuickJS exposes child elements as own properties, so a child named
like an XMLNode method hides the method on its prototype. Let methods
take precedence over bare child names, as on the njs engine. Keep the
child accessible through $tag$name and avoid deleting it when deleting
the method name.

Cover collisions for all XMLNode methods and prototype changes.

6 weeks agoXML: add namespace-aware node accessors
Dmitry Volyntsev [Fri, 25 Sep 2026 01:34:22 +0000 (18:34 -0700)]
XML: add namespace-aware node accessors

The existing $attr$name and $tag$name accessors compare local names
only, so x:ID and ID, or x:Issuer and Issuer, are indistinguishable.

The new XMLNode methods getAttributeNS(namespaceURI, localName) and
getChildNS(namespaceURI, localName) match both the namespace URI and
the local name.

6 weeks agoQuickJS: fix XML value leaks in "in" checks
Dmitry Volyntsev [Fri, 25 Sep 2026 01:33:48 +0000 (18:33 -0700)]
QuickJS: fix XML value leaks in "in" checks

Previously, property existence checks such as "'$attr$a' in node",
"'to' in node", or "'$tags$to' in node" created the property value and
never released it when no property descriptor was requested.  A leaked
XMLNode also held a reference to its document, so the whole document
was never freed.

Also, qjs_xml_node_make() and qjs_xml_attr_make() incremented the
document reference count before creating the object, so a failed
JS_NewObjectClass() left the document permanently referenced.

The fix is to free the value when no descriptor is requested and to
take the document reference only after the object is created.

6 weeks agoTests: tighten shell test checks
Dmitry Volyntsev [Tue, 29 Sep 2026 01:31:09 +0000 (18:31 -0700)]
Tests: tighten shell test checks

Previously, Expect treated timeouts as successful matches, and EOF
passed even if the REPL exited abnormally.  Some checks could match
the input echo alone, while completion checks required a bell that
varies between libedit versions.

The fix is to fail on timeouts, premature EOF, and abnormal exit;
check the result and prompt for Unicode input and guard against a
repeated promise rejection.  Send Unicode as ASCII escapes to work
around libedit 3.1.snap20150325-2.12 on SLES 15 SP7, which reports
a character count where the readline callback expects a byte count.

6 weeks agoQuickJS: stop tracking rejections during final report
Dmitry Volyntsev [Mon, 28 Sep 2026 22:42:40 +0000 (15:42 -0700)]
QuickJS: stop tracking rejections during final report

Converting the rejection reason to a log string may reject another
promise.  Disable the tracker before reporting so new rejections
cannot leave references in the request context after its list has
been drained.

6 weeks agoShell: fix unhandled rejection report in QuickJS
Dmitry Volyntsev [Fri, 25 Sep 2026 05:07:14 +0000 (22:07 -0700)]
Shell: fix unhandled rejection report in QuickJS

Previously, njs_engine_qjs_unhandled_rejection() kept a pointer to
the rejected promise list while converting the first rejection reason
to a string.  The conversion may call user JavaScript code, which can
reject more promises and cause the list to be reallocated.  After that,
the old pointer was used together with the new item count to free the
promise and reason values, which caused out-of-bounds reads and invalid
frees.

The fix is to take a reference to the first reason and free the list
before conversion, so that rejections created during conversion are
tracked in a new list.

The test/js/promise_rejection_tracker_recursive.t.js test is no longer
skipped for the QuickJS engine.

6 weeks agoPromise: do not track handled rejections with no list
Dmitry Volyntsev [Mon, 28 Sep 2026 22:10:03 +0000 (15:10 -0700)]
Promise: do not track handled rejections with no list

Previously, when a handled promise was reported and the rejected promise
list was NULL, the trackers fell through and added it as unhandled.  In
the interactive shell, handling a promise after its rejection had been
reported caused another, false unhandled rejection.  The QuickJS nginx
module could do the same while formatting a rejection reason.

The fix is to return for every handled notification, removing the promise
from the list only when the list exists.  Apply this to both engines in the
shell and nginx module.

6 weeks agoZlib: copy QJS dictionaries before conversion
Dmitry Volyntsev [Tue, 22 Sep 2026 04:13:22 +0000 (21:13 -0700)]
Zlib: copy QJS dictionaries before conversion

Copy dictionary bytes before converting other JavaScript arguments so their
backing storage cannot be invalidated during zlib setup.

6 weeks agoZlib: validate NJS chunk sizes
Dmitry Volyntsev [Tue, 22 Sep 2026 04:03:53 +0000 (21:03 -0700)]
Zlib: validate NJS chunk sizes

6 weeks agoTypes: declare Buffer swap64 correctly
Dmitry Volyntsev [Tue, 22 Sep 2026 04:03:48 +0000 (21:03 -0700)]
Types: declare Buffer swap64 correctly

6 weeks agoXML: guard against content allocation failure
Dmitry Volyntsev [Tue, 22 Sep 2026 04:03:48 +0000 (21:03 -0700)]
XML: guard against content allocation failure

Report a memory error when libxml cannot allocate node content instead of
passing a NULL pointer to the string conversion path.

6 weeks agoCore: avoid float padding pointer wraparound
Dmitry Volyntsev [Tue, 22 Sep 2026 03:53:54 +0000 (20:53 -0700)]
Core: avoid float padding pointer wraparound

Skip padding when the formatted float is wider than its requested field.
This prevents unsigned width subtraction from forming an invalid pointer.

6 weeks agoFS: convert QJS numeric modes safely
Dmitry Volyntsev [Tue, 22 Sep 2026 03:37:09 +0000 (20:37 -0700)]
FS: convert QJS numeric modes safely

6 weeks agoCHB: avoid overflow when enforcing the chain limit
Dmitry Volyntsev [Tue, 22 Sep 2026 03:28:29 +0000 (20:28 -0700)]
CHB: avoid overflow when enforcing the chain limit

Check the requested size against the remaining chain capacity instead of
adding it to the current total.  This prevents the size check from wrapping
and bypassing the configured chain limit.

6 weeks agoBuffer: free QJS buffers on conversion failures
Dmitry Volyntsev [Thu, 24 Sep 2026 22:53:56 +0000 (15:53 -0700)]
Buffer: free QJS buffers on conversion failures

qjs_buffer_from_string() and qjs_buffer_create() leaked the newly
allocated buffer when qjs_typed_array_data() or string decoding failed.

Also check the JS_ToCStringLen() result in qjs_buffer_from_string(), so
an allocation failure is not followed by a NULL pointer dereference.

6 weeks agoBuffer: reject oversized QJS alloc() and concat() sizes
Dmitry Volyntsev [Thu, 24 Sep 2026 22:53:30 +0000 (15:53 -0700)]
Buffer: reject oversized QJS alloc() and concat() sizes

Buffer.alloc() and Buffer.concat() converted sizes with JS_ToUint32(),
which wraps values modulo 2^32: Buffer.alloc(2 ** 32 + 16) returned a
16-byte buffer.  Use JS_ToIndex() instead, so these sizes throw a
RangeError.

In Buffer.concat(), the total length of the list could also overflow the
32-bit accumulator.  Keep it in 64 bits and check it against
QJS_BUFFER_MAX_LENGTH.  The overflow now throws a RangeError instead of a
TypeError, as in Node.js.

6 weeks agoBuffer: convert QJS array-like lengths
Dmitry Volyntsev [Tue, 22 Sep 2026 03:28:29 +0000 (20:28 -0700)]
Buffer: convert QJS array-like lengths

Convert array-like lengths through checked floating-point conversion before
applying ToLength semantics.  This avoids reading float-tagged QuickJS
numbers through the integer accessor.

The length is kept as a 64-bit value and passed to qjs_buffer_alloc()
unchanged, so an oversized length is rejected before any allocation
instead of being truncated.

6 weeks agoBuffer: check QJS allocation sizes before narrowing
Dmitry Volyntsev [Thu, 24 Sep 2026 22:48:09 +0000 (15:48 -0700)]
Buffer: check QJS allocation sizes before narrowing

Take a 64-bit size in qjs_buffer_alloc() and reject sizes above
QJS_BUFFER_MAX_LENGTH before converting them.  Previously, a caller
holding a wider size had to narrow it to size_t first, which truncated
it silently on 32-bit platforms.

6 weeks agoTests: improve compatibility with Node.js
Dmitry Volyntsev [Tue, 22 Sep 2026 03:16:38 +0000 (20:16 -0700)]
Tests: improve compatibility with Node.js

Accept RangeError from Buffer.concat() revalidation.
Remove oversized Buffer.from() cases that make Node.js allocate 4 GiB.
Expect empty Buffer.fill() values to fail.
Use fs.rm() for recursive removal under Node.js.
Check non-enumerable fs.Stats date properties directly.
Use distinct readlink fixtures for concurrently run test cases.

Known failures for js_test --binary=node are limited to module
resolution in import and XML module tests for v25.2.1 on linux.

6 weeks agoFS: fix typo during BytesRead prototype instantiation
Dmitry Volyntsev [Tue, 22 Sep 2026 02:05:31 +0000 (19:05 -0700)]
FS: fix typo during BytesRead prototype instantiation

6 weeks agoPromise: reject empty any inputs
Dmitry Volyntsev [Tue, 22 Sep 2026 04:56:00 +0000 (21:56 -0700)]
Promise: reject empty any inputs

Reject Promise.any() with an AggregateError when the input contains no
promises, as required by the promise combinator semantics.

6 weeks agoTests: update Test262 and allow unhandled rejections
Dmitry Volyntsev [Tue, 22 Sep 2026 04:55:31 +0000 (21:55 -0700)]
Tests: update Test262 and allow unhandled rejections

Track the current Test262 revision and let the Test262 runner follow the
suite's handling of rejected promises instead of imposing a separate policy.

6 weeks agoTests: rename local JavaScript test target
Dmitry Volyntsev [Tue, 22 Sep 2026 00:39:35 +0000 (17:39 -0700)]
Tests: rename local JavaScript test target

Previously, the local JavaScript tests, including WebCrypto tests, were
run by the test262 target, while the official TC39 Test262 suite was
run by njs_test262_test.

The fix is to rename the local test target to js_test and make test262
run the official suite.  The engine-specific local targets are renamed
to js_test_njs and js_test_quickjs.

6 weeks agoWebcrypto: clean up ECDSA conversion failures
Dmitry Volyntsev [Tue, 22 Sep 2026 00:04:12 +0000 (17:04 -0700)]
Webcrypto: clean up ECDSA conversion failures

While here, also report ECDSA signature encoding failures.

6 weeks agoWebcrypto: clean up AES-CTR allocation failures
Dmitry Volyntsev [Mon, 21 Sep 2026 23:23:09 +0000 (16:23 -0700)]
Webcrypto: clean up AES-CTR allocation failures

6 weeks agoWebcrypto: use constant-time HMAC verification
Dmitry Volyntsev [Mon, 21 Sep 2026 23:22:45 +0000 (16:22 -0700)]
Webcrypto: use constant-time HMAC verification

6 weeks agoWebcrypto: validate EC JWK curve type
Dmitry Volyntsev [Mon, 21 Sep 2026 23:22:24 +0000 (16:22 -0700)]
Webcrypto: validate EC JWK curve type

7 weeks agoMemory pool: cached slot index in a page
Dmitry Volyntsev [Tue, 8 Sep 2026 22:50:16 +0000 (15:50 -0700)]
Memory pool: cached slot index in a page

Previously, freeing a chunk searched the pool slots linearly to map the
chunk size back to its slot.

The fix is to keep the slot index in the page descriptor, in a byte
that was unused.

7 weeks agoMemory pool: free page counter in a cluster
Dmitry Volyntsev [Tue, 8 Sep 2026 22:48:47 +0000 (15:48 -0700)]
Memory pool: free page counter in a cluster

Previously, releasing a page walked all pages of its cluster to test
whether the whole cluster had become free.

The fix is to keep the number of free pages in the cluster block.

7 weeks agoMemory pool: junk filling only in debug builds
Dmitry Volyntsev [Tue, 8 Sep 2026 22:46:52 +0000 (15:46 -0700)]
Memory pool: junk filling only in debug builds

Previously, every freed chunk was overwritten with 0x5A in all builds,
adding a memset to each njs_mp_free() call.

The fix is to keep the junk filling under NJS_DEBUG.  Release builds no
longer poison freed chunks; nothing ever inspected the pattern.

7 weeks agoMemory pool: compare block addresses without overflow
Dmitry Volyntsev [Thu, 17 Sep 2026 23:47:35 +0000 (16:47 -0700)]
Memory pool: compare block addresses without overflow

Previously, the rbtree comparator converted the difference between two
addresses to intptr_t.  On 32-bit systems, addresses that differ by at
least 2 GiB could produce an incorrect ordering and prevent a later block
lookup from finding its cluster.

The fix is to compare the addresses directly and return -1, 0, or 1.
This fixes a pool that remained non-empty after all allocations were freed
in the x86 memory pool test.

7 weeks agoTests: memory pool unit test
Dmitry Volyntsev [Fri, 18 Sep 2026 00:11:36 +0000 (17:11 -0700)]
Tests: memory pool unit test

Previously, the memory pool was covered only indirectly by a single
flathsh configuration.

The fix is to add direct coverage for allocation, reuse, alignment, and
mixed allocation sizes across valid pool configurations.  The test uses a
smaller workload in the regular matrix and a full stress workload in the
ASan job.

Library tests are included in the standard test target.  The added ASan
configuration omits debug memory so that the complete test target and the
pool page and cluster paths are exercised.  The library-test dependency
rule is also corrected for the new test executable.

7 weeks agoAvoid undefined shifts in MurmurHash2
Dmitry Volyntsev [Thu, 17 Sep 2026 21:51:00 +0000 (14:51 -0700)]
Avoid undefined shifts in MurmurHash2

Previously, input bytes were promoted to signed int before being shifted
into a hash word.  A byte with its high bit set could make the 24-bit
shift undefined.

The fix is to cast input bytes to uint32_t before shifting.  This
preserves the hash result and avoids undefined behavior under UBSan.

7 weeks agoFetch: limit decoded chunked response bodies
Dmitry Volyntsev [Wed, 16 Sep 2026 00:45:14 +0000 (17:45 -0700)]
Fetch: limit decoded chunked response bodies

Previously, fetch allowed decoded chunked bodies to reach ten times
max_response_body_size.

The fix is to apply max_response_body_size to decoded chunks.

7 weeks agoFetch: avoid reusing framed response connections
Dmitry Volyntsev [Wed, 16 Sep 2026 00:42:55 +0000 (17:42 -0700)]
Fetch: avoid reusing framed response connections

Previously, fetch cached fixed-length responses with bytes after their
declared body. Bodyless and chunked responses with such bytes did not
complete correctly.

The fix is to close a framed response connection with unconsumed bytes
instead of adding it to the keepalive cache.

7 weeks agoFetch: honor response body framing
Dmitry Volyntsev [Wed, 16 Sep 2026 00:35:30 +0000 (17:35 -0700)]
Fetch: honor response body framing

Previously, fetch inferred body completion from Content-Length alone. This
completed close-delimited responses before EOF and conflated framing modes.

The fix is to track body framing explicitly, reject unsupported 1xx
responses, and exempt 204 and 304 representation lengths from body limits.

7 weeks agoFetch: validate response framing
Dmitry Volyntsev [Tue, 15 Sep 2026 22:46:22 +0000 (15:46 -0700)]
Fetch: validate response framing

Previously, fetch accepted conflicting Content-Length fields and a response
with both Transfer-Encoding and Content-Length.

The fix is to reject ambiguous framing to avoid interpreting the response
body inconsistently.

7 weeks agoFetch: validate response body size
Dmitry Volyntsev [Tue, 15 Sep 2026 22:45:50 +0000 (15:45 -0700)]
Fetch: validate response body size

Previously, a negative max_response_body_size could make a close-delimited
response appear as a successful empty body.

The fix is to reject the invalid option while parsing fetch arguments.

7 weeks agoModules: fix js_periodic worker affinity parsing
Dmitry Volyntsev [Tue, 15 Sep 2026 22:24:06 +0000 (15:24 -0700)]
Modules: fix js_periodic worker affinity parsing

Previously, worker_affinity parsing reused the directive option index. This
skipped options after worker_affinity in HTTP and stream configurations.

The fix is to use a separate index while parsing the affinity mask.

7 weeks agoFetch: fix QJS numeric conversion
Dmitry Volyntsev [Tue, 15 Sep 2026 22:24:06 +0000 (15:24 -0700)]
Fetch: fix QJS numeric conversion

Previously, QuickJS wrote an int64_t through ngx_int_t fetch fields.

The fix is to use the checked native conversion helper so ILP32 builds
cannot overwrite adjacent state.

8 weeks agoTypedArray: coerce length argument once on buffer construction
basavaraj-sm05 [Wed, 9 Sep 2026 06:56:41 +0000 (12:26 +0530)]
TypedArray: coerce length argument once on buffer construction

Previously, njs_typed_array_alloc() passed the length argument through
njs_value_to_index() twice, before and after the detached-buffer check,
and kept only the second result.  The argument's valueOf() was invoked
twice, which is observable.

The fix is to remove the second conversion.

8 weeks agoTest262: add a native runner for the official suite
Dmitry Volyntsev [Wed, 9 Sep 2026 01:44:42 +0000 (18:44 -0700)]
Test262: add a native runner for the official suite

8 weeks agoCI: test njs with UBSan
Dmitry Volyntsev [Sat, 12 Sep 2026 05:39:30 +0000 (22:39 -0700)]
CI: test njs with UBSan

Build and run the base njs test suite with UndefinedBehaviorSanitizer.

8 weeks agoAlign opaque values
Dmitry Volyntsev [Sun, 13 Sep 2026 19:53:30 +0000 (12:53 -0700)]
Align opaque values

Opaque values are cast to njs_value_t pointers by the public API.  Match
njs_value_t alignment while retaining the four uint32_t filler fields.

UndefinedBehaviorSanitizer reports unaligned njs_value_t accesses.

8 weeks agoCHB: avoid incompatible function pointer calls
Dmitry Volyntsev [Sat, 12 Sep 2026 05:25:53 +0000 (22:25 -0700)]
CHB: avoid incompatible function pointer calls

Use adapters for memory pool allocators instead of casting their function
pointers to the generic chain buffer callback types.

Casting does not make an indirect call through an incompatible function
pointer type valid.  UndefinedBehaviorSanitizer reports these calls.

8 weeks agoDate: avoid out-of-range conversion in timezone offset
Dmitry Volyntsev [Sat, 12 Sep 2026 05:29:38 +0000 (22:29 -0700)]
Date: avoid out-of-range conversion in timezone offset

The timezone offset helper converted a double to int64_t before checking
whether it was representable.  Check the range first.

UndefinedBehaviorSanitizer reports the out-of-range conversion.

8 weeks agoDate: fix UTC setters
Dmitry Volyntsev [Sat, 12 Sep 2026 03:33:48 +0000 (20:33 -0700)]
Date: fix UTC setters

The Date setters always converted their result as local time.  Use the
setter's UTC flag instead.

Remove the intermediate range check in njs_make_date().  TimeClip already
checks the result after local-to-UTC conversion, which can move a value
across the valid time range boundary.

8 weeks agoFix the conversion of a property key to an array index
Dmitry Volyntsev [Wed, 9 Sep 2026 01:44:05 +0000 (18:44 -0700)]
Fix the conversion of a property key to an array index

Previously, a double was converted to uint32_t before its range was tested,
so a property key that is NaN, negative or larger than 2^31 made the
conversion undefined.  UndefinedBehaviorSanitizer reported it for every VM
creation, where an environment variable name is atomized.

The fix is to test the range first and to share one njs_number_is_atom_index()
helper between the four places that repeated the pattern.

8 weeks agoVM: remove dead code introduced in fd54d52de557
Dmitry Volyntsev [Sat, 12 Sep 2026 01:45:23 +0000 (18:45 -0700)]
VM: remove dead code introduced in fd54d52de557

The lambda structure is allocated at the end of module compilation,
and if the allocation fails, lambda is NULL.  Since nothing fails after
a successful allocation, lambda is always NULL on the failed path.

Found by Coverity (CID 1701143).

2 months agoTypes: align XML declarations with API
Dmitry Volyntsev [Thu, 10 Sep 2026 22:42:06 +0000 (15:42 -0700)]
Types: align XML declarations with API

Previously, XML declarations did not accurately model XML node property
values, mutation deletion semantics, or canonicalization aliases.

The fix is to align XMLDoc and XMLNode types with the current API and
add TypeScript coverage for the supported operations.

2 months agoQuickJS: align XML tag assignment with njs
Dmitry Volyntsev [Thu, 10 Sep 2026 23:02:35 +0000 (16:02 -0700)]
QuickJS: align XML tag assignment with njs

Previously, assigning null or undefined to node.$tag$name removed
matching children in QuickJS, while the njs engine rejected every
assignment.

The fix is to distinguish property assignment from deletion in the
QuickJS exotic property handler. Assignments now throw TypeError in both
engines, while delete node.$tag$name remains supported.

2 months agoXML: retain QuickJS tag sources during copy
Dmitry Volyntsev [Thu, 10 Sep 2026 03:26:26 +0000 (20:26 -0700)]
XML: retain QuickJS tag sources during copy

2 months agoXML: mutate XML nodes in place
Dmitry Volyntsev [Thu, 10 Sep 2026 03:26:26 +0000 (20:26 -0700)]
XML: mutate XML nodes in place

Previously, text and structural mutators copied and replaced the receiver's
libxml2 node.  Existing XMLNode wrappers continued to point at the detached
original, while subsequent lookups returned the replacement.  Wrappers for
children preserved by the operation likewise pointed into the detached old
subtree.  In QuickJS, mutating the detached receiver again could dereference
the NULL result of xmlReplaceNode().

The fix is to modify the existing receiver's child list directly.  Existing
wrappers and subsequent lookups therefore continue to refer to the same
libxml2 node.  Removed child lists remain readable until the QuickJS
document or njs VM is destroyed.  A node is considered live only when
following its parent links reaches its xmlDoc.  Replacement children and
cleanup records are prepared before the live tree is modified.

Changed behaviour:
- A removed child has an undefined $parent, while its descendants retain
  their internal parent links.
- Mutating or canonicalizing a removed XMLNode throws TypeError.
- Text and attribute values must be primitive strings; null and undefined
  retain their deletion semantics.
- C14N rejects an excluding node from another document or a detached list.
- addChild() and $tags reject namespace-bearing or unsupported source trees
  before mutation.
- Named $tags assignments are consistently rejected by both engines.

While here, use an unsigned QuickJS $tags array length, support assigning
$tags on an empty njs XMLNode, and make deleting $tags from an empty node
a no-op.

2 months agoXML: create text nodes before mutation
Dmitry Volyntsev [Thu, 10 Sep 2026 00:04:47 +0000 (17:04 -0700)]
XML: create text nodes before mutation

Previously, text updates encoded content manually and then passed it to
libxml2. This duplicated libxml2 escaping rules and allocated the
encoded buffer before creating the text node.

The fix is to create a libxml2 text node from the unencoded value before
replacing the copied node's children. libxml2 now owns escaping, and a
failure leaves the original XML tree unchanged.

2 months agoGenerator: bound value preservation analysis
Dmitry Volyntsev [Fri, 4 Sep 2026 01:09:17 +0000 (18:09 -0700)]
Generator: bound value preservation analysis

Value-preservation analysis recursively examines the upcoming expression before
the generator decides whether mutable-slot operands need temporary copies.
Deeply nested binary expressions and arrays could therefore exhaust the native
stack.

Move the generator-specific predicate out of the parser API and limit its
recursive walk to 128 levels.  At the limit, conservatively require
preservation: an extra move is safe, whereas missing a deeper side effect can
change evaluation semantics.

2 months agoVM: clean up failed module compilation
Dmitry Volyntsev [Thu, 3 Sep 2026 15:53:25 +0000 (08:53 -0700)]
VM: clean up failed module compilation

Module compilation publishes a provisional module before parsing to support
recursive loading.  Remove that module on failure and release code records,
line maps, and code buffers produced after the compilation checkpoint so a
failed load does not poison subsequent lookups.

2 months agoVM: clean up failed AST serialization
Dmitry Volyntsev [Thu, 3 Sep 2026 15:53:25 +0000 (08:53 -0700)]
VM: clean up failed AST serialization

2 months agoParser: release non-global semantic state
Dmitry Volyntsev [Thu, 3 Sep 2026 15:53:14 +0000 (08:53 -0700)]
Parser: release non-global semantic state

Allocate non-global scopes, local variables, variable tree nodes, references,
and declaration arrays from the compilation pool.  The global scope and its
symbol table remain persistent for runtime lookup and later compilation.

Build closure-index arrays temporarily, then copy the finalized indexes into
VM-owned storage referenced by each lambda.  Preserve declaration-origin type
without retaining pointers to released block scopes.

2 months agoGenerator: release temporary compilation memory
Dmitry Volyntsev [Thu, 3 Sep 2026 15:53:14 +0000 (08:53 -0700)]
Generator: release temporary compilation memory

Use the parser invocation pool for generator stack entries, copied contexts,
blocks, jump patches, index caches, and traversal scratch.  Nested function
generators share the same temporary pool, while generated code and runtime
metadata remain in the VM pool.

2 months agoParser: release temporary compilation memory
Dmitry Volyntsev [Thu, 3 Sep 2026 15:53:03 +0000 (08:53 -0700)]
Parser: release temporary compilation memory

Create a pool for each parser invocation and allocate parser nodes, array-item
storage, continuations, preread tokens, and active labels from it.  Destroy the
pool after generation and on parser or generator failures.

Keep atoms, lambdas, regexp patterns, scopes, variables, bytecode, and runtime
constants in the VM pool.  Clear persistent scope AST roots before releasing
the temporary pool.

2 months agoParser: shrink variable flags
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Parser: shrink variable flags

2 months agoParser: store statement labels as atom identifiers
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Parser: store statement labels as atom identifiers

2 months agoParser: use compact active labels
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Parser: use compact active labels

2 months agoParser: reduce variable reference payload
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Parser: reduce variable reference payload

Store the atom identifier and resolved variable directly in parser nodes and
move the undefined-reference flag into the common node flags.  This removes the
separately allocated reference object and helps reduce parser nodes to the
64-byte memory-pool class.

2 months agoParser: compact array literal elements
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Parser: compact array literal elements

The generic object-property lowering used six parser nodes and several
generator continuations for each array element.  Store array values and indexes
in compact records and emit a dedicated immediate-index initializer instead.

This also avoids interning numeric element indexes and generates elements in
source order with constant continuation depth.  Keep template backing arrays
flat because template concatenation requires contiguous storage.

2 months agoFix large array literal initialization
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Fix large array literal initialization

Large literals switch to slow arrays above the fast-array capacity limit, but
the previous initialization path left their indexed values unset.  Initialize
slow arrays directly so literals above 32760 elements preserve their contents.

2 months agoTests: add parser stress benchmarks
Dmitry Volyntsev [Thu, 3 Sep 2026 00:39:41 +0000 (17:39 -0700)]
Tests: add parser stress benchmarks

Add generated workloads for large array literals, declarations, references,
closures, and labels.  These tests are intended to expose catastrophic parser
scaling and compare compilation changes; source construction and Function()
compilation are both included in the measured interval.