diff --git a/.configurations/configuration.dsc.yaml b/.configurations/configuration.dsc.yaml index 8c637d7dae81..5d8cd5177823 100644 --- a/.configurations/configuration.dsc.yaml +++ b/.configurations/configuration.dsc.yaml @@ -5,11 +5,11 @@ properties: - resource: Microsoft.WinGet.DSC/WinGetPackage id: pythonPackage directives: - description: Install Python 3.14 + description: Install Python 3.15 module: Microsoft.WinGet.DSC allowPrerelease: true settings: - id: Python.Python.3.14 + id: Python.Python.3.15 source: winget - resource: Microsoft.WinGet.DSC/WinGetPackage id: vsPackage diff --git a/.configurations/configuration.vsBuildTools.dsc.yaml b/.configurations/configuration.vsBuildTools.dsc.yaml index 3e3a51ca9026..a9b1a3aba83a 100644 --- a/.configurations/configuration.vsBuildTools.dsc.yaml +++ b/.configurations/configuration.vsBuildTools.dsc.yaml @@ -5,11 +5,11 @@ properties: - resource: Microsoft.WinGet.DSC/WinGetPackage id: pythonPackage directives: - description: Install Python 3.14 + description: Install Python 3.15 module: Microsoft.WinGet.DSC allowPrerelease: true settings: - id: Python.Python.3.14 + id: Python.Python.3.15 source: winget - resource: Microsoft.WinGet.DSC/WinGetPackage id: vsPackage diff --git a/.configurations/configuration.vsEnterprise.dsc.yaml b/.configurations/configuration.vsEnterprise.dsc.yaml index 124a391b7843..488b1fd3e59c 100644 --- a/.configurations/configuration.vsEnterprise.dsc.yaml +++ b/.configurations/configuration.vsEnterprise.dsc.yaml @@ -5,11 +5,11 @@ properties: - resource: Microsoft.WinGet.DSC/WinGetPackage id: pythonPackage directives: - description: Install Python 3.14 + description: Install Python 3.15 module: Microsoft.WinGet.DSC allowPrerelease: true settings: - id: Python.Python.3.14 + id: Python.Python.3.15 source: winget - resource: Microsoft.WinGet.DSC/WinGetPackage id: vsPackage diff --git a/.configurations/configuration.vsProfessional.dsc.yaml b/.configurations/configuration.vsProfessional.dsc.yaml index 7d2a8b36984c..f819ec6652f8 100644 --- a/.configurations/configuration.vsProfessional.dsc.yaml +++ b/.configurations/configuration.vsProfessional.dsc.yaml @@ -5,11 +5,11 @@ properties: - resource: Microsoft.WinGet.DSC/WinGetPackage id: pythonPackage directives: - description: Install Python 3.14 + description: Install Python 3.15 module: Microsoft.WinGet.DSC allowPrerelease: true settings: - id: Python.Python.3.14 + id: Python.Python.3.15 source: winget - resource: Microsoft.WinGet.DSC/WinGetPackage id: vsPackage diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index c59b56360161..033e677a56b2 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -57,7 +57,8 @@ jobs: [ -z "$FILTER" ] || FILTER_IF_SET=" / $FILTER" COMMENT_BODY="Benchmark GHA (${CATEGORIES}${FILTER_IF_SET}): ${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" echo "COMMENT_BODY=$COMMENT_BODY" >> "$GITHUB_OUTPUT" - echo "COMMENT_URL=$(gh pr comment -R "${REPO:-$GITHUB_REPOSITORY}" "$PR_ID" --body "$COMMENT_BODY")" >> "$GITHUB_OUTPUT" + COMMENT_URL=$(gh pr comment -R "${REPO:-$GITHUB_REPOSITORY}" "$PR_ID" --body "$COMMENT_BODY") + echo "COMMENT_URL=$COMMENT_URL" >> "$GITHUB_OUTPUT" env: CATEGORIES: ${{ inputs.category }} FILTER: ${{ inputs.filter }} diff --git a/.github/workflows/build-shared.yml b/.github/workflows/build-shared.yml index c212880acf1f..823f3aeaaeab 100644 --- a/.github/workflows/build-shared.yml +++ b/.github/workflows/build-shared.yml @@ -57,10 +57,22 @@ jobs: with: extra_nix_config: sandbox = true + - name: Build Cachix + if: ${{ inputs.runner == 'macos-15-intel' }} + id: build_cachix + run: | + nix-build --no-out-link -I "nixpkgs=$TAR_DIR/tools/nix/pkgs.nix" -E '(import {}).cachix' + { + printf "BIN=" + nix-instantiate --eval --raw -I "nixpkgs=$TAR_DIR/tools/nix/pkgs.nix" -E 'with (import {});lib.getExe cachix' + printf '\n' + } >> "$GITHUB_OUTPUT" + - uses: cachix/cachix-action@38b082610b782e7e93e209c35fd730d399dee866 # v17 with: name: nodejs authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} + cachixBin: ${{ steps.build_cachix.outputs.BIN || '' }} - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 if: inputs.v8-nar diff --git a/.github/workflows/build-tarball.yml b/.github/workflows/build-tarball.yml index 009b753f4faf..c1deb4acd294 100644 --- a/.github/workflows/build-tarball.yml +++ b/.github/workflows/build-tarball.yml @@ -103,6 +103,7 @@ jobs: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} steps: - name: Install Clang ${{ env.CLANG_VERSION }} uses: $/.github/actions/install-clang @@ -117,7 +118,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Download tarball uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: diff --git a/.github/workflows/coverage-linux-without-intl.yml b/.github/workflows/coverage-linux-without-intl.yml index 889500fd43d6..e08305a71ff8 100644 --- a/.github/workflows/coverage-linux-without-intl.yml +++ b/.github/workflows/coverage-linux-without-intl.yml @@ -41,6 +41,7 @@ env: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} permissions: contents: read @@ -66,7 +67,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Install gcovr run: pip install gcovr==7.2 - name: Configure diff --git a/.github/workflows/coverage-linux.yml b/.github/workflows/coverage-linux.yml index 5b8c91973aa1..b59050216ad8 100644 --- a/.github/workflows/coverage-linux.yml +++ b/.github/workflows/coverage-linux.yml @@ -41,6 +41,7 @@ env: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} permissions: contents: read @@ -66,7 +67,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Install gcovr run: pip install gcovr==7.2 - name: Configure diff --git a/.github/workflows/coverage-windows.yml b/.github/workflows/coverage-windows.yml index fe2f2bcc6f75..fd2a219459ab 100644 --- a/.github/workflows/coverage-windows.yml +++ b/.github/workflows/coverage-windows.yml @@ -84,7 +84,7 @@ jobs: run: choco install nasm - name: Install Rust ${{ env.RUSTC_VERSION }} run: | - rustup override set "$RUSTC_VERSION" + rustup override set "$Env:RUSTC_VERSION" rustup --version - name: Build run: ./vcbuild.bat clang-cl v8temporal diff --git a/.github/workflows/daily-wpt-fyi.yml b/.github/workflows/daily-wpt-fyi.yml index 9b7916e17d12..4eb725149dcb 100644 --- a/.github/workflows/daily-wpt-fyi.yml +++ b/.github/workflows/daily-wpt-fyi.yml @@ -27,9 +27,19 @@ jobs: matrix: ${{ steps.query.outputs.matrix }} steps: - id: query + # Explicit bash enables pipefail so jq cannot hide a failed curl. + shell: bash run: | - matrix=$(curl -s https://raw.githubusercontent.com/nodejs/Release/refs/heads/main/schedule.json | jq -c --arg now "$(date +%Y-%m-%d)" '[with_entries(select(.value.end > $now and .value.start < $now)) | keys[] | ltrimstr("v") | tonumber] + ["latest-nightly"]') - echo "matrix=$matrix" >> "$GITHUB_OUTPUT" + { + printf 'matrix=' + curl -fsSL https://github.com/nodejs/Release/raw/HEAD/schedule.json \ + | jq -Mrc --arg now "$(date +%Y-%m-%d)" ' + [ + with_entries(select(.value.end > $now and .value.start < $now)) + | keys[] + | ltrimstr("v") | tonumber + ] + ["latest-nightly"]' + } >> "$GITHUB_OUTPUT" report: needs: - collect-versions diff --git a/.github/workflows/daily.yml b/.github/workflows/daily.yml index 9fb09d56bbba..ebf9b1648acc 100644 --- a/.github/workflows/daily.yml +++ b/.github/workflows/daily.yml @@ -28,3 +28,18 @@ jobs: sudo apt-get update && sudo apt-get install ninja-build -y ./configure --enable-lto --ninja ninja -C out/Release + + # Once main builds, tell nodejs/devcontainer to publish new nightly images from the same commit. + # Its build workflow listens for this `node-daily` event. + trigger-devcontainer: + needs: build-lto + if: github.repository == 'nodejs/node' && github.ref == 'refs/heads/main' + runs-on: ubuntu-slim + steps: + - name: Dispatch a nodejs/devcontainer build + run: | + gh api repos/nodejs/devcontainer/dispatches \ + -f event_type=node-daily \ + -f "client_payload[sha]=$GITHUB_SHA" + env: + GH_TOKEN: ${{ secrets.GH_USER_TOKEN }} diff --git a/.github/workflows/lint-release-proposal.yml b/.github/workflows/lint-release-proposal.yml index 989a57cd8851..3ab7ab2c1af3 100644 --- a/.github/workflows/lint-release-proposal.yml +++ b/.github/workflows/lint-release-proposal.yml @@ -92,19 +92,23 @@ jobs: - name: Validate CHANGELOG id: releaser-info run: | + HAS_ERROR= EXPECTED_CHANGELOG_TITLE_INTRO="## $COMMIT_SUBJECT, @" echo "Expected CHANGELOG section title: $EXPECTED_CHANGELOG_TITLE_INTRO" CHANGELOG_PATH="doc/changelogs/CHANGELOG_V${MAJOR}.md" - CHANGELOG_TITLE="$(grep "$EXPECTED_CHANGELOG_TITLE_INTRO" "$CHANGELOG_PATH")" + CHANGELOG_TITLE="$(grep "$EXPECTED_CHANGELOG_TITLE_INTRO" "$CHANGELOG_PATH" || true)" echo "Actual: $CHANGELOG_TITLE" - [ "${CHANGELOG_TITLE%%@*}@" = "$EXPECTED_CHANGELOG_TITLE_INTRO" ] + if [ "${CHANGELOG_TITLE%%@*}@" != "$EXPECTED_CHANGELOG_TITLE_INTRO" ]; then + echo "::error file=$CHANGELOG_PATH,title=Release proposal linter::Cannot find CHANGELOG section title starting with $EXPECTED_CHANGELOG_TITLE_INTRO" + HAS_ERROR=1 + fi gh api \ -H "Accept: application/vnd.github+json" \ -H "X-GitHub-Api-Version: 2022-11-28" \ --jq '.commits.[] | { smallSha: .sha[0:10] } + (.commit.message|capture("^(?.+)\n\n(.*\n)*PR-URL: (?<prURL>.+)(\n|$)"))' \ "/repos/${GITHUB_REPOSITORY}/compare/v${MAJOR}.x...$GITHUB_SHA" --paginate \ | node tools/actions/lint-release-proposal-commit-list.mjs "$CHANGELOG_PATH" "$GITHUB_SHA" \ - | while IFS= read -r PR_URL; do + | { while IFS= read -r PR_URL; do DONT_LAND_LABEL="dont-land-on-v${MAJOR}.x" LTS_WATCH_LABEL="lts-watch-v${MAJOR}.x" gh pr view \ --json labels,url \ --jq ' @@ -114,8 +118,9 @@ jobs: error("\(.url) has the \(env.LTS_WATCH_LABEL) label, please remove the label now that the PR is included in a release proposal") end ' \ - "$PR_URL" > /dev/null - done + "$PR_URL" > /dev/null || HAS_LABEL_ERROR=1 + done; [ -z "$HAS_LABEL_ERROR" ]; } || HAS_ERROR=1 + [ -z "$HAS_ERROR" ] shell: bash # See https://docs.github.com/en/actions/writing-workflows/workflow-syntax-for-github-actions#exit-codes-and-error-action-preference, we want the pipefail option. env: COMMIT_SUBJECT: ${{ steps.commit-message-parse.outputs.COMMIT_SUBJECT }} diff --git a/.github/workflows/stress-test.yml b/.github/workflows/stress-test.yml index ac18a17fd0c7..67767881aacf 100644 --- a/.github/workflows/stress-test.yml +++ b/.github/workflows/stress-test.yml @@ -52,7 +52,9 @@ jobs: # test lib-only or test-only deflaking changes. This should be able to pick up cache from # test-linux.yml and test-macos.yml running on the main branch. SCCACHE_GHA_ENABLED: 'true' + SCCACHE_GHA_RW_MODE: READ_ONLY SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: sccache steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -78,7 +80,7 @@ jobs: - name: Set up sccache uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 # This is needed due to https://github.com/nodejs/build/issues/3878 - name: Cleanup if: runner.os == 'macOS' diff --git a/.github/workflows/test-internet.yml b/.github/workflows/test-internet.yml index 978b163d9709..2475b2b7cf77 100644 --- a/.github/workflows/test-internet.yml +++ b/.github/workflows/test-internet.yml @@ -46,6 +46,7 @@ env: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} permissions: contents: read @@ -71,7 +72,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Build run: make build-ci -j4 V=1 CONFIG_FLAGS="--error-on-warn" - name: Test Internet diff --git a/.github/workflows/test-linux-perfetto.yml b/.github/workflows/test-linux-perfetto.yml index 1a8e3ca4daf7..d4c57766e7d4 100644 --- a/.github/workflows/test-linux-perfetto.yml +++ b/.github/workflows/test-linux-perfetto.yml @@ -27,6 +27,7 @@ env: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} RUSTC_VERSION: '1.88' permissions: @@ -58,7 +59,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Build working-directory: node run: make build-ci -j4 V=1 CONFIG_FLAGS="--error-on-warn --v8-enable-temporal-support --with-perfetto" diff --git a/.github/workflows/test-linux-quic.yml b/.github/workflows/test-linux-quic.yml index be18b278b785..cf34b28ba91b 100644 --- a/.github/workflows/test-linux-quic.yml +++ b/.github/workflows/test-linux-quic.yml @@ -38,6 +38,7 @@ env: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} RUSTC_VERSION: '1.88' permissions: @@ -69,7 +70,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Build working-directory: node run: make build-ci -j4 V=1 CONFIG_FLAGS="--error-on-warn --v8-enable-temporal-support --experimental-quic" diff --git a/.github/workflows/test-linux.yml b/.github/workflows/test-linux.yml index abfe41254d94..6d549481c905 100644 --- a/.github/workflows/test-linux.yml +++ b/.github/workflows/test-linux.yml @@ -46,6 +46,7 @@ env: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} clang++-19 SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} RUSTC_VERSION: '1.88' permissions: @@ -81,7 +82,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 - name: Build working-directory: node run: make build-ci -j4 V=1 CONFIG_FLAGS="--error-on-warn --v8-enable-temporal-support" diff --git a/.github/workflows/test-macos.yml b/.github/workflows/test-macos.yml index a2651522e5ca..2dde824af97d 100644 --- a/.github/workflows/test-macos.yml +++ b/.github/workflows/test-macos.yml @@ -84,6 +84,7 @@ jobs: CXX: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} g++ SCCACHE_GHA_ENABLED: ${{ github.base_ref == 'main' || github.ref_name == 'main' }} SCCACHE_IDLE_TIMEOUT: '0' + CARGO_BUILD_RUSTC_WRAPPER: ${{ (github.base_ref == 'main' || github.ref_name == 'main') && 'sccache' || '' }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: @@ -104,7 +105,7 @@ jobs: if: github.base_ref == 'main' || github.ref_name == 'main' uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11 with: - version: v0.17.0 + version: v0.19.0 # The `npm ci` for this step fails a lot as part of the Test step. Run it # now so that we don't have to wait 2 hours for the Build step to pass # first before that failure happens. (And if there's something about diff --git a/.github/workflows/test-shared.yml b/.github/workflows/test-shared.yml index 73254d292ec1..897c702af78c 100644 --- a/.github/workflows/test-shared.yml +++ b/.github/workflows/test-shared.yml @@ -230,14 +230,15 @@ jobs: - name: Collect matrix of support OpenSSL versions id: query run: | - echo "matrix=$( + { + printf 'matrix=' nix-instantiate --eval --strict --json -E " let matrix = import $TAR_DIR/tools/nix/openssl-matrix.nix {}; in builtins.map (attr: { inherit attr; inherit (builtins.getAttr attr matrix) name; }) (builtins.attrNames matrix) " - )" >> "$GITHUB_OUTPUT" + } >> "$GITHUB_OUTPUT" # Builds and tests Node.js with shared libraries against every supported # OpenSSL release version available in the repo-pinned nixpkgs. The default diff --git a/.github/workflows/v8-backport-comment.yml b/.github/workflows/v8-backport-comment.yml new file mode 100644 index 000000000000..66dfe12055f7 --- /dev/null +++ b/.github/workflows/v8-backport-comment.yml @@ -0,0 +1,82 @@ +name: Comment on V8 backports to the main branch + +on: + pull_request_target: + types: [opened] + branches: [main] + +permissions: + contents: read + +jobs: + comment: + name: Comment on V8 backports to the main branch + # A triager/collaborator can add the v8-backport-to-main label when opening the pull + # request to skip the comment when it is already known to meet the criteria. + if: >- + github.run_attempt == 1 && + github.event.pull_request.user.type != 'Bot' && + github.repository == 'nodejs/node' && + !startsWith(github.event.pull_request.title, 'Revert ') && + !contains(github.event.pull_request.labels.*.name, 'v8-backport-to-main') + runs-on: ubuntu-slim + permissions: + pull-requests: write + steps: + - name: Check whether the pull request is a backport of individual V8 patches + id: check + env: + GH_TOKEN: ${{ github.token }} + NUMBER: ${{ github.event.pull_request.number }} + run: | + # Major and patch updates to V8 would update deps/v8/include/v8-version.h, + # while individual backports do not. + # The API lists at most 3000 files sorted by path. The version header + # should appear early enough to show up within the limit even for major updates. + gh api --paginate \ + "/repos/$GITHUB_REPOSITORY/pulls/$NUMBER/files?per_page=100" > files.json + files=$(jq -r '.[].filename' files.json) + if printf '%s\n' "$files" | grep -q '^deps/v8/' && + ! printf '%s\n' "$files" | grep -qx 'deps/v8/include/v8-version.h'; then + echo 'is_backport=true' >> "$GITHUB_OUTPUT" + else + echo 'is_backport=false' >> "$GITHUB_OUTPUT" + fi + # Check if the patch bumps v8_embedder_string in common.gypi. + if jq -r '.[] | select(.filename == "common.gypi") | .patch // ""' files.json | + grep -q '^+.*v8_embedder_string'; then + echo 'bumps_embedder_string=true' >> "$GITHUB_OUTPUT" + else + echo 'bumps_embedder_string=false' >> "$GITHUB_OUTPUT" + fi + + - name: Comment with V8 backport guidance + if: steps.check.outputs.is_backport == 'true' + env: + GH_TOKEN: ${{ github.token }} + NUMBER: ${{ github.event.pull_request.number }} + BUMPS_EMBEDDER_STRING: ${{ steps.check.outputs.bumps_embedder_string }} + # GitHub renders line breaks as-is, so keep each paragraph on a single line. + MESSAGE: |- + Hi! This pull request changes `deps/v8` on the `main` branch without updating the V8 version, so you are likely submitting a backport of individual V8 patches. + + In general we recommend waiting for a V8 patch to be included in the next V8 major version update instead of fast-tracking it, since individual backports add audit cost and can delay the major update. + + A patch may be backported to `main` when at least one of these criteria applies: + + * It fixes a build issue on a platform or toolchain supported on `main`. + * It fixes a security issue. + * It unblocks a pending V8 update, for example by adjusting how the Node.js code uses a V8 API so that it works with the future update. + + If the patch has demonstrated real-world urgency and impact that justifies landing it before the next V8 major version update, it's recommended to backport it to the release staging branches like `v<MAJOR>.x-staging` (see [Criteria for backporting](https://github.com/nodejs/node/blob/HEAD/doc/contributing/backporting-to-release-lines.md#criteria-for-backporting) to decide what release line to target) instead of `main`. + + Please explain in the pull request description which of these criteria applies. Otherwise, consider closing this pull request and waiting for the next V8 update instead of fast-tracking a backport. See [Backporting patches to `main`](https://github.com/nodejs/node/blob/HEAD/doc/contributing/maintaining/maintaining-V8.md#backporting-patches-to-main) for details. + EMBEDDER_STRING_MESSAGE: |- + Additional note: This pull request does not appear to bump `v8_embedder_string` in `common.gypi`. Backports of V8 patches should increment it. `git node v8 backport` from [`@node-core/utils`](https://github.com/nodejs/node-core-utils) does this automatically. + run: | + { + printf '%s\n' "$MESSAGE" + if [ "$BUMPS_EMBEDDER_STRING" != 'true' ]; then + printf '\n%s\n' "$EMBEDDER_STRING_MESSAGE" + fi + } | gh pr comment "$NUMBER" --repo "$GITHUB_REPOSITORY" --body-file - diff --git a/.mailmap b/.mailmap index 73c585d1a6ea..115b8d15a92c 100644 --- a/.mailmap +++ b/.mailmap @@ -106,6 +106,8 @@ Chew Choon Keat <choonkeat@gmail.com> Chris Andrews <cpandrews8@gmail.com> Chris Johnson <chris.s.johnson4@gmail.com> Chris Young <chris.young@tinder.com> <chris.young@gotinder.com> +Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com> +Christian Aurich Zanettini Martins <christian.aurichzm@gmail.com> <christian@bridge.ufsc.br> Christian Clauss <cclauss@me.com> Christian Clauss <cclauss@me.com> <cclauss@bluewin.ch> Christophe Naud-Dulude <christophe.naud.dulude@gmail.com> @@ -180,6 +182,7 @@ FangDun Cai <cfddream@gmail.com> Fangshi He <hefangshi@gmail.com> Farid Neshat <FaridN_SOAD@yahoo.com> Fatah N <nfatah41@gmail.com> +Fatih Güzel <fatihguzeldev@gmail.com> Fedor Indutny <fedor@indutny.com> <fedor.indutny@gmail.com> Felix Böhm <felixboehm55@googlemail.com> <me@feedic.com> Felix Geisendörfer <felix@debuggable.com> diff --git a/BUILDING.md b/BUILDING.md index 5ab3b7bb971f..03671aeba98f 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -796,7 +796,7 @@ easily. These files will install the following [WinGet](https://learn.microsoft.com/en-us/windows/package-manager/winget/) packages: * Git for Windows with the `git` and Unix tools added to the `PATH` -* `Python 3.14` +* `Python 3.15` * `Visual Studio 2022` (Build Tools, Community, Professional or Enterprise Edition) and "Desktop development with C++" workload, Clang and ClangToolset optional components * `Rust Toolchain MSVC` @@ -813,7 +813,7 @@ The following Desired State Configuration (DSC) files are available: Use one of the above DSC files with [winget configure](https://learn.microsoft.com/en-us/windows/package-manager/winget/configure#configure-subcommands) -in a PowerShell Terminal to install Node.js prerequisites. +in an Administrator PowerShell terminal to install Node.js prerequisites. For example, using the DSC file for Visual Studio Community Edition, execute the following command line: ```powershell diff --git a/CHANGELOG.md b/CHANGELOG.md index 9158593408cd..38441004a454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,7 +43,8 @@ release. </tr> <tr> <td valign="top"> -<b><a href="doc/changelogs/CHANGELOG_V27.md#27.0.0-alpha.0.1.1">27.0.0-alpha.0.1.1</a></b><br/> +<b><a href="doc/changelogs/CHANGELOG_V27.md#27.0.0-alpha.0.2.0">27.0.0-alpha.0.2.0</a></b><br/> +<a href="doc/changelogs/CHANGELOG_V27.md#27.0.0-alpha.0.1.1">27.0.0-alpha.0.1.1</a><br/> <a href="doc/changelogs/CHANGELOG_V27.md#27.0.0-alpha.0.1.0">27.0.0-alpha.0.1.0</a><br/> <a href="doc/changelogs/CHANGELOG_V27.md#27.0.0-alpha.0.0.0">27.0.0-alpha.0.0.0</a><br/> </td> diff --git a/Makefile b/Makefile index cd732faeec2d..5c1cdda86148 100644 --- a/Makefile +++ b/Makefile @@ -180,16 +180,26 @@ endif with-code-cache test-code-cache: $(warning '$@' target is a noop) -out/Makefile: config.gypi common.gypi node.gyp \ +# config.status writes out/Makefile together with config.gypi, but make may +# still see out/Makefile as stale right after that. Rerun it only when +# out/Makefile is missing (as after `make clean`) or not newer. Shells with +# whole-second -nt then rerun on a tie instead of leaving it stale. +out/Makefile: config.gypi + @if [ "$@" -nt "$<" ]; then :; \ + elif [ -x config.status ]; then \ + export PATH="$(NO_BIN_OVERRIDE_PATH)" && ./config.status; \ + else \ + echo Missing or stale $@, please run ./configure; \ + exit 1; \ + fi + +# node_version.h is listed because the N-API version is taken from there +# and included in config.gypi +config.gypi: configure configure.py src/node_version.h common.gypi node.gyp \ deps/*/*.gyp \ tools/v8_gypfiles/toolchain.gypi \ tools/v8_gypfiles/features.gypi \ tools/v8_gypfiles/inspector.gypi tools/v8_gypfiles/v8.gyp - $(PYTHON) tools/gyp_node.py -f make -Dpython=$(PYTHON) - -# node_version.h is listed because the N-API version is taken from there -# and included in config.gypi -config.gypi: configure configure.py src/node_version.h @if [ -x config.status ]; then \ export PATH="$(NO_BIN_OVERRIDE_PATH)" && ./config.status; \ else \ diff --git a/benchmark/abort_controller/abort-signal-throw-if-aborted.js b/benchmark/abort_controller/abort-signal-throw-if-aborted.js new file mode 100644 index 000000000000..bf14d40b9c60 --- /dev/null +++ b/benchmark/abort_controller/abort-signal-throw-if-aborted.js @@ -0,0 +1,43 @@ +'use strict'; +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + n: [5e7], + kind: ['controller', 'timeout', 'any', 'mixed'], +}); + +const kSignals = 16; + +function createSignal(kind, i, controllers) { + switch (kind) { + case 'controller': { + const controller = new AbortController(); + controllers.push(controller); + return controller.signal; + } + case 'timeout': + return AbortSignal.timeout(1e9); + case 'any': { + const controller = new AbortController(); + controllers.push(controller); + return AbortSignal.any([controller.signal, AbortSignal.timeout(1e9)]); + } + case 'mixed': + return createSignal(['controller', 'timeout', 'any'][i % 3], i, controllers); + default: + throw new Error('Invalid kind'); + } +} + +function main({ n, kind }) { + // Keep the controllers alive so that composite signals keep their sources. + const controllers = []; + const signals = []; + for (let i = 0; i < kSignals; ++i) + signals.push(createSignal(kind, i, controllers)); + + bench.start(); + for (let i = 0; i < n; ++i) + signals[i % kSignals].throwIfAborted(); + bench.end(n); +} diff --git a/benchmark/buffers/buffer-read.js b/benchmark/buffers/buffer-read.js index 19570a6b9241..9d5a19d6a5aa 100644 --- a/benchmark/buffers/buffer-read.js +++ b/benchmark/buffers/buffer-read.js @@ -1,5 +1,6 @@ 'use strict'; const common = require('../common.js'); +const assert = require('assert'); const { Buffer } = require('buffer'); const types = [ @@ -32,10 +33,12 @@ function main({ n, buffer, type }) { const fn = `read${type}`; buff.writeDoubleLE(0, 0); + let result; bench.start(); for (let i = 0; i !== n; i++) { - buff[fn](0); + result = buff[fn](0); } bench.end(n); + assert.notStrictEqual(result, undefined); } diff --git a/benchmark/diagnostics_channel/threadpool-work.js b/benchmark/diagnostics_channel/threadpool-work.js new file mode 100644 index 000000000000..2674729023e4 --- /dev/null +++ b/benchmark/diagnostics_channel/threadpool-work.js @@ -0,0 +1,69 @@ +'use strict'; + +const assert = require('node:assert'); +const crypto = require('node:crypto'); +const dc = require('node:diagnostics_channel'); +const fs = require('node:fs'); +const zlib = require('node:zlib'); +const common = require('../common.js'); +const tmpdir = require('../../test/common/tmpdir'); + +const bench = common.createBenchmark(main, { + n: [1e3, 1e4], + mode: ['subscribed', 'unsubscribed'], + operation: ['crypto', 'zlib', 'readFile', 'writeFile'], +}); + +function main({ n, mode, operation }) { + const subscriber = () => {}; + const type = { + crypto: 'crypto', + zlib: 'zlib', + readFile: 'fs.readfile', + writeFile: 'fs.writefile', + }[operation]; + assert(type); + const channel = `uv.threadpool.work.${type}`; + if (mode === 'subscribed') { + dc.subscribe(channel, subscriber); + } else if (mode === 'unsubscribed') { + dc.subscribe(channel, subscriber); + dc.unsubscribe(channel, subscriber); + } + + tmpdir.refresh(); + const file = tmpdir.resolve('file'); + const data = Buffer.alloc(1024, 'x'); + fs.writeFileSync(file, data); + + const operations = { + crypto(callback) { + crypto.pbkdf2('secret', 'salt', 1, 32, 'sha256', callback); + }, + zlib(callback) { + zlib.gzip(data, callback); + }, + readFile(callback) { + fs.readFile(file, callback); + }, + writeFile(callback) { + fs.writeFile(file, data, callback); + }, + }; + + let completed = 0; + bench.start(); + run(); + + function run() { + operations[operation]((err) => { + assert.ifError(err); + if (++completed < n) return run(); + + bench.end(n); + if (mode === 'subscribed') { + dc.unsubscribe(channel, subscriber); + } + }); + } +} diff --git a/benchmark/error/error.js b/benchmark/error/error.js index c856f3e07f6b..b4b5292d0412 100644 --- a/benchmark/error/error.js +++ b/benchmark/error/error.js @@ -9,6 +9,7 @@ const bench = common.createBenchmark(main, { function main({ n }) { bench.start(); for (let i = 0; i < n; ++i) + // eslint-disable-next-line no-restricted-syntax new Error('test'); bench.end(n); } diff --git a/benchmark/fs/bench-accessSync.js b/benchmark/fs/bench-accessSync.js index 0be0ca799d3a..b4bc2a06a442 100644 --- a/benchmark/fs/bench-accessSync.js +++ b/benchmark/fs/bench-accessSync.js @@ -48,7 +48,7 @@ function main({ n, type, method }) { path = tmpdir.resolve(`.non-existing-file-${process.pid}`); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } if (method === 'access') { diff --git a/benchmark/fs/bench-chmodSync.js b/benchmark/fs/bench-chmodSync.js index 87b45c06b507..97903db7b931 100644 --- a/benchmark/fs/bench-chmodSync.js +++ b/benchmark/fs/bench-chmodSync.js @@ -36,6 +36,6 @@ function main({ n, type }) { bench.end(n); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-chownSync.js b/benchmark/fs/bench-chownSync.js index 18e2bd35d526..bcd83a342644 100644 --- a/benchmark/fs/bench-chownSync.js +++ b/benchmark/fs/bench-chownSync.js @@ -49,6 +49,6 @@ function main({ n, type, method }) { break; } default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-existsSync.js b/benchmark/fs/bench-existsSync.js index f9da2765b130..2b04eeb5167d 100644 --- a/benchmark/fs/bench-existsSync.js +++ b/benchmark/fs/bench-existsSync.js @@ -27,7 +27,7 @@ function main({ n, type }) { path = tmpdir.resolve(`.non-existing-file-${process.pid}`); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/fs/bench-fchmodSync.js b/benchmark/fs/bench-fchmodSync.js index 4ada8a6f5d8b..7023d0d1ff94 100644 --- a/benchmark/fs/bench-fchmodSync.js +++ b/benchmark/fs/bench-fchmodSync.js @@ -28,7 +28,7 @@ function main({ n, type }) { files = new Array(n).fill(tmpdir.resolve(`.non-existing-file-${Date.now()}`)); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } const fds = files.map((x) => { diff --git a/benchmark/fs/bench-fsyncSync.js b/benchmark/fs/bench-fsyncSync.js index fc7ef2926679..672d91e369e4 100644 --- a/benchmark/fs/bench-fsyncSync.js +++ b/benchmark/fs/bench-fsyncSync.js @@ -24,7 +24,7 @@ function main({ n, type }) { fd = 1 << 30; break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/fs/bench-linkSync.js b/benchmark/fs/bench-linkSync.js index ead39c338fe6..cb004837d26c 100644 --- a/benchmark/fs/bench-linkSync.js +++ b/benchmark/fs/bench-linkSync.js @@ -45,6 +45,6 @@ function main({ n, type }) { break; } default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-mkdirSync.js b/benchmark/fs/bench-mkdirSync.js index 1db1c5878776..08698b427eef 100644 --- a/benchmark/fs/bench-mkdirSync.js +++ b/benchmark/fs/bench-mkdirSync.js @@ -29,7 +29,7 @@ function main({ n, type, recursive }) { files = new Array(n).fill(__dirname); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/fs/bench-mkdtempSync.js b/benchmark/fs/bench-mkdtempSync.js index afb342366bbf..1e287493b6fe 100644 --- a/benchmark/fs/bench-mkdtempSync.js +++ b/benchmark/fs/bench-mkdtempSync.js @@ -27,7 +27,7 @@ function main({ n, type }) { prefix = tmpdir.resolve('non-existent', 'foo', 'bar'); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/fs/bench-openSync.js b/benchmark/fs/bench-openSync.js index b17c0a1e67f8..26ea1300b9ba 100644 --- a/benchmark/fs/bench-openSync.js +++ b/benchmark/fs/bench-openSync.js @@ -33,7 +33,7 @@ function main({ n, type }) { path = tmpdir.resolve(`.non-existing-file-${process.pid}`); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } runBench({ n, path }); diff --git a/benchmark/fs/bench-opendirSync.js b/benchmark/fs/bench-opendirSync.js index f24faa5d5e69..2ea68192b587 100644 --- a/benchmark/fs/bench-opendirSync.js +++ b/benchmark/fs/bench-opendirSync.js @@ -25,7 +25,7 @@ function main({ n, type }) { files = [tmpdir.resolve(`.non-existing-file-${Date.now()}`)]; break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/fs/bench-readSync.js b/benchmark/fs/bench-readSync.js index a75d1750002f..fea37f4c43c9 100644 --- a/benchmark/fs/bench-readSync.js +++ b/benchmark/fs/bench-readSync.js @@ -38,7 +38,7 @@ function main({ n, type }) { fd = 1 << 30; break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } const buffer = Buffer.alloc(bufferSize); diff --git a/benchmark/fs/bench-readlinkSync.js b/benchmark/fs/bench-readlinkSync.js index 9b3bbceb42e9..57a5611b9f3e 100644 --- a/benchmark/fs/bench-readlinkSync.js +++ b/benchmark/fs/bench-readlinkSync.js @@ -49,6 +49,6 @@ function main({ n, type }) { break; } default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-rmdirSync.js b/benchmark/fs/bench-rmdirSync.js index 481034392743..71002d41c5a1 100644 --- a/benchmark/fs/bench-rmdirSync.js +++ b/benchmark/fs/bench-rmdirSync.js @@ -37,6 +37,6 @@ function main({ n, type }) { break; } default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-symlinkSync.js b/benchmark/fs/bench-symlinkSync.js index 92ceb3579a42..c8864527463a 100644 --- a/benchmark/fs/bench-symlinkSync.js +++ b/benchmark/fs/bench-symlinkSync.js @@ -46,6 +46,6 @@ function main({ n, type }) { break; } default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-timesSync.js b/benchmark/fs/bench-timesSync.js index 8ea879a63ef9..09d5a3891c0b 100644 --- a/benchmark/fs/bench-timesSync.js +++ b/benchmark/fs/bench-timesSync.js @@ -56,6 +56,6 @@ function main({ n, type, func }) { break; } default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/fs/bench-unlinkSync.js b/benchmark/fs/bench-unlinkSync.js index 8b992198c8d3..9b134aa678c5 100644 --- a/benchmark/fs/bench-unlinkSync.js +++ b/benchmark/fs/bench-unlinkSync.js @@ -28,7 +28,7 @@ function main({ n, type }) { files = new Array(n).fill(tmpdir.resolve(`.non-existing-file-${Date.now()}`)); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/fs/bench_fdatasyncSync.js b/benchmark/fs/bench_fdatasyncSync.js index 9aedb0a314fb..cd6babadeeeb 100644 --- a/benchmark/fs/bench_fdatasyncSync.js +++ b/benchmark/fs/bench_fdatasyncSync.js @@ -24,7 +24,7 @@ function main({ n, type }) { fd = 1 << 30; break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } bench.start(); diff --git a/benchmark/module/module-require-builtin.js b/benchmark/module/module-require-builtin.js new file mode 100644 index 000000000000..f68df90bb66c --- /dev/null +++ b/benchmark/module/module-require-builtin.js @@ -0,0 +1,17 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + prefix: ['', 'node:'], + n: [1e6], +}); + +function main({ prefix, n }) { + const ids = ['fs', 'path', 'util', 'events'].map((id) => `${prefix}${id}`); + bench.start(); + for (let i = 0; i < n; i++) { + require(ids[i % ids.length]); + } + bench.end(n); +} diff --git a/benchmark/module/parse-package-json.js b/benchmark/module/parse-package-json.js new file mode 100644 index 000000000000..ec05340cc428 --- /dev/null +++ b/benchmark/module/parse-package-json.js @@ -0,0 +1,59 @@ +'use strict'; + +// Parses the package.json files found under deps/ with the internal +// parsePackageJSON() binding, grouped by file size. + +const common = require('../common.js'); +const fs = require('fs'); +const path = require('path'); + +const buckets = { + '0-512': [0, 512], + '512-1024': [512, 1024], + '1024-2048': [1024, 2048], + '2048+': [2048, Infinity], +}; + +const bench = common.createBenchmark(main, { + size: Object.keys(buckets), + n: [1e6], +}, { + flags: ['--expose-internals'], +}); + +function loadCorpus(parsePackageJSON) { + const deps = path.resolve(__dirname, '../../deps'); + const seen = new Set(); + const corpus = []; + for (const entry of fs.readdirSync(deps, { recursive: true })) { + if (path.basename(entry) !== 'package.json') continue; + const source = fs.readFileSync(path.join(deps, entry)); + const key = source.toString('latin1'); + if (seen.has(key)) continue; + seen.add(key); + try { + parsePackageJSON(source, '/benchmark/package.json'); + } catch { + continue; // Skip test fixtures that are not valid package configs. + } + corpus.push(source); + } + return corpus; +} + +function main({ size, n }) { + const { internalBinding } = require('internal/test/binding'); + const { parsePackageJSON } = internalBinding('modules'); + const [min, max] = buckets[size]; + const files = loadCorpus(parsePackageJSON) + .filter((source) => source.length >= min && source.length < max); + if (files.length === 0) { + throw new Error(`no package.json under deps/ in the ${size} bucket`); + } + + bench.start(); + for (let i = 0; i < n; i++) { + parsePackageJSON(files[i % files.length], '/benchmark/package.json'); + } + bench.end(n); +} diff --git a/benchmark/url/url-searchparams-parse-no-equals.js b/benchmark/url/url-searchparams-parse-no-equals.js new file mode 100644 index 000000000000..51675d51ca42 --- /dev/null +++ b/benchmark/url/url-searchparams-parse-no-equals.js @@ -0,0 +1,20 @@ +'use strict'; +const common = require('../common.js'); +const assert = require('node:assert'); + +const bench = common.createBenchmark(main, { + pair: ['a', 'a=b'], + pairs: [1e3, 1e5], + n: [100], +}); + +function main({ pair, pairs, n }) { + const input = `${pair}&`.repeat(pairs); + let params; + bench.start(); + for (let i = 0; i < n; i++) { + params = new URLSearchParams(input); + } + bench.end(n); + assert.strictEqual(params.size, pairs); +} diff --git a/benchmark/util/inspect.js b/benchmark/util/inspect.js index 8e453b9e226e..43062daff871 100644 --- a/benchmark/util/inspect.js +++ b/benchmark/util/inspect.js @@ -2,6 +2,7 @@ const util = require('util'); const common = require('../common.js'); +const assert = require('node:assert'); const opts = { showHidden: { showHidden: true }, @@ -14,11 +15,14 @@ const bench = common.createBenchmark(main, { 'Object', 'Object_empty', 'Object_deep_ln', + 'Object_large', 'String', 'String_complex', 'String_boxed', 'Date', 'Set', + 'Set_large', + 'Map', 'Error', 'Array', 'TypedArray', @@ -29,11 +33,14 @@ const bench = common.createBenchmark(main, { }); function benchmark(n, obj, options) { + let output; bench.start(); for (let i = 0; i < n; i += 1) { - util.inspect(obj, options); + output = util.inspect(obj, options); } bench.end(n); + assert.strictEqual(typeof output, 'string'); + assert.notStrictEqual(output.length, 0); } function main({ method, n, option }) { @@ -61,6 +68,13 @@ function main({ method, n, option }) { g: 'seventh' } } } }; benchmark(n, obj, options || { depth: Infinity }); break; + case 'Object_large': + obj = {}; + for (let i = 0; i < 50; i++) { + obj[`key${i}`] = i; + } + benchmark(n, obj, options); + break; case 'String': benchmark(n, 'Simple string', options); break; @@ -77,6 +91,20 @@ function main({ method, n, option }) { obj = new Set([5, 3]); benchmark(n, obj, options); break; + case 'Set_large': + obj = new Set(); + for (let i = 0; i < 50; i++) { + obj.add(i); + } + benchmark(n, obj, options); + break; + case 'Map': + obj = new Map(); + for (let i = 0; i < 50; i++) { + obj.set(i, i); + } + benchmark(n, obj, options); + break; case 'Error': benchmark(n, new Error('error'), options); break; diff --git a/benchmark/v8/heap-profile-stop.js b/benchmark/v8/heap-profile-stop.js new file mode 100644 index 000000000000..f5c2592d5557 --- /dev/null +++ b/benchmark/v8/heap-profile-stop.js @@ -0,0 +1,27 @@ +'use strict'; + +const common = require('../common.js'); +const assert = require('node:assert'); +const { startHeapProfile } = require('node:v8'); + +const bench = common.createBenchmark(main, { + n: [1e4, 1e5], +}, { + test: { n: 1e3 }, +}); + +function main({ n }) { + const handle = startHeapProfile({ sampleInterval: 64 }); + // Keep the sampled allocations alive until after stop(). + const retained = globalThis.retained = new Array(n); + for (let i = 0; i < n; i++) { + retained[i] = new Array(16).fill(i); + } + + bench.start(); + const profile = handle.stop(); + bench.end(1); + + assert.ok(JSON.parse(profile).samples.length > 0); + globalThis.retained = undefined; +} diff --git a/benchmark/webstorage/getItem.js b/benchmark/webstorage/getItem.js index f92ee0318ff6..b82960a6f489 100644 --- a/benchmark/webstorage/getItem.js +++ b/benchmark/webstorage/getItem.js @@ -70,6 +70,6 @@ function main({ n, type }) { bench.end(n); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/webstorage/removeItem.js b/benchmark/webstorage/removeItem.js index 0de686d45a3d..738ae8a24262 100644 --- a/benchmark/webstorage/removeItem.js +++ b/benchmark/webstorage/removeItem.js @@ -70,6 +70,6 @@ function main({ n, type }) { bench.end(n); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/benchmark/webstorage/setItem.js b/benchmark/webstorage/setItem.js index 5d88a39ef52a..fa53bab20df6 100644 --- a/benchmark/webstorage/setItem.js +++ b/benchmark/webstorage/setItem.js @@ -58,6 +58,6 @@ function main({ n, type }) { bench.end(n); break; default: - new Error('Invalid type'); + throw new Error('Invalid type'); } } diff --git a/common.gypi b/common.gypi index aee557e5e044..474505ca14a2 100644 --- a/common.gypi +++ b/common.gypi @@ -235,7 +235,8 @@ # frames otherwise, even with --call-graph dwarf. 'cflags': [ '-fno-omit-frame-pointer' ], }], - ['OS=="linux" or OS=="openharmony"', { + # PGO settings are specific to Node, not addons built with node-gyp. + ['(OS=="linux" or OS=="openharmony") and configuring_node', { 'conditions': [ ['enable_pgo_generate=="true"', { 'cflags': ['<(pgo_generate)'], @@ -247,7 +248,7 @@ },], ], },], - ['OS=="mac"', { + ['OS=="mac" and configuring_node', { 'conditions': [ ['enable_pgo_generate=="true"', { 'xcode_settings': { @@ -312,7 +313,7 @@ },], ], 'target_conditions': [ - ['_toolset=="target"', { + ['_toolset=="target" and <(configuring_node)', { 'conditions': [ ['enable_pgo_generate=="true"', { 'msvs_settings': { diff --git a/deps/ada/ada.cpp b/deps/ada/ada.cpp index fd558881bf05..31f7a35c4a60 100644 --- a/deps/ada/ada.cpp +++ b/deps/ada/ada.cpp @@ -1,34 +1,24 @@ -/* auto-generated on 2026-07-27 16:10:09 -0400. Do not edit! */ +/* auto-generated on 2026-11-19 15:19:30 -0500. Do not edit! */ /* begin file src/ada.cpp */ #include "ada.h" /* begin file src/checkers.cpp */ #include <algorithm> #include <array> +#include <cstddef> +#include <cstdint> #include <string_view> namespace ada::checkers { ada_really_inline constexpr bool is_ipv4(std::string_view view) noexcept { // The string is not empty and does not contain upper case ASCII characters. - // - // Optimization. To be considered as a possible ipv4, the string must end - // with 'x' or a lowercase hex character. - // Most of the time, this will be false so this simple check will save a lot - // of effort. + if (!last_label_may_be_a_number(view)) { + return false; + } // If the address ends with a dot, we need to prune it (special case). if (view.ends_with('.')) { view.remove_suffix(1); - if (view.empty()) { - return false; - } - } - char last_char = view.back(); - bool possible_ipv4 = (last_char >= '0' && last_char <= '9') || - (last_char >= 'a' && last_char <= 'f') || - last_char == 'x'; - if (!possible_ipv4) { - return false; } // From the last character, find the last dot. size_t last_dot = view.rfind('.'); @@ -138,7 +128,7 @@ ada_really_inline constexpr bool verify_dns_length( ADA_PUSH_DISABLE_ALL_WARNINGS /* begin file src/ada_idna.cpp */ -/* auto-generated on 2026-07-12 20:34:08 -0400. Do not edit! */ +/* auto-generated on 2026-11-19 15:08:48 -0500. Do not edit! */ /* begin file src/idna.cpp */ /* begin file src/unicode_transcoding.cpp */ /* begin file include/ada/idna/unicode_transcoding.h */ @@ -381,8 +371,9 @@ bool map(std::u32string_view input, std::u32string& out); // code; compression only affects on-disk size and one-time init. // // Thread-safe without mutex: atomic CAS + spin-wait. ensure_tables() returns -// false if initialization fails (OOM, corrupt blob); callers must treat that -// as a hard error and not touch table pointers. +// false if initialization fails. A corrupt blob stays failed for the process. +// An allocation failure is not latched: a later call tries again. Callers +// must treat a false return as a hard error and not touch table pointers. /* begin file src/raw_inflate.hpp */ // Minimal raw DEFLATE inflater (RFC 1951), enough for zlib raw streams. @@ -669,3956 +660,4148 @@ inline size_t inflate_raw(const uint8_t* src, size_t src_len, uint8_t* dst, #include <cstdint> #include <cstddef> namespace ada::idna::table_blob { -constexpr size_t uncompressed_size = 224608; -constexpr size_t compressed_size = 62377; -constexpr uint32_t uncompressed_crc32 = 0x6F4A6B2Eu; -constexpr size_t decomposition_block_rows = 67; +constexpr size_t uncompressed_size = 216077; +constexpr size_t compressed_size = 65331; +constexpr uint32_t uncompressed_crc32 = 0xC16EA7DEu; +constexpr size_t decomposition_block_rows = 70; constexpr size_t decomposition_block_cols = 257; -constexpr size_t ccc_block_rows = 67; +constexpr size_t ccc_block_rows = 69; constexpr size_t ccc_block_cols = 256; -constexpr size_t composition_block_rows = 67; +constexpr size_t composition_block_rows = 27; constexpr size_t composition_block_cols = 257; -constexpr size_t id_continue_count = 1418; -constexpr size_t id_start_count = 776; -constexpr size_t dir_table_count = 1449; -constexpr size_t combining_range_count = 290; +constexpr size_t id_continue_count = 1437; +constexpr size_t id_start_count = 789; +constexpr size_t dir_table_count = 1608; +constexpr size_t combining_range_count = 333; +constexpr size_t joining_table_count = 533; // Offsets into the decompressed buffer: constexpr size_t off_idna_stage1 = 0; -constexpr size_t count_idna_stage1 = 3282; -constexpr size_t off_idna_stage2 = 6564; -constexpr size_t count_idna_stage2 = 11456; -constexpr size_t off_idna_bool_blocks = 29480; +constexpr size_t count_idna_stage1 = 4081; +constexpr size_t off_idna_stage2 = 8162; +constexpr size_t count_idna_stage2 = 11712; +constexpr size_t off_idna_bool_blocks = 31592; constexpr size_t count_idna_bool_blocks = 225; -constexpr size_t off_idna_utf8_mappings = 31280; -constexpr size_t count_idna_utf8_mappings = 17383; -constexpr size_t off_decomposition_index = 48663; +constexpr size_t off_idna_utf8_mappings = 33392; +constexpr size_t count_idna_utf8_mappings = 17651; +constexpr size_t off_decomposition_index = 51043; constexpr size_t count_decomposition_index = 4352; -constexpr size_t off_decomposition_block = 53016; -constexpr size_t count_decomposition_block = 17219; -constexpr size_t off_decomposition_data = 87456; -constexpr size_t count_decomposition_data = 9102; -constexpr size_t off_ccc_index = 123864; +constexpr size_t off_decomposition_block = 55396; +constexpr size_t count_decomposition_block = 17990; +constexpr size_t off_decomposition_data = 91376; +constexpr size_t count_decomposition_data = 9255; +constexpr size_t off_ccc_index = 128396; constexpr size_t count_ccc_index = 4352; -constexpr size_t off_ccc_block = 128216; -constexpr size_t count_ccc_block = 17152; -constexpr size_t off_composition_index = 145368; +constexpr size_t off_ccc_block = 132748; +constexpr size_t count_ccc_block = 17664; +constexpr size_t off_composition_index = 150412; constexpr size_t count_composition_index = 4352; -constexpr size_t off_composition_block = 149720; -constexpr size_t count_composition_block = 17219; -constexpr size_t off_composition_data = 184160; -constexpr size_t count_composition_data = 1883; -constexpr size_t off_id_continue_flat = 191692; -constexpr size_t count_id_continue_flat = 2836; -constexpr size_t off_id_start_flat = 203036; -constexpr size_t count_id_start_flat = 1552; -constexpr size_t off_dir_start = 209244; -constexpr size_t count_dir_start = 1449; -constexpr size_t off_dir_final = 215040; -constexpr size_t count_dir_final = 1449; -constexpr size_t off_dir_value = 220836; -constexpr size_t count_dir_value = 1449; -constexpr size_t off_combining_flat = 222288; -constexpr size_t count_combining_flat = 580; +constexpr size_t off_composition_block = 154764; +constexpr size_t count_composition_block = 6939; +constexpr size_t off_composition_data = 168644; +constexpr size_t count_composition_data = 1923; +constexpr size_t off_id_continue_flat = 176336; +constexpr size_t count_id_continue_flat = 2874; +constexpr size_t off_id_start_flat = 187832; +constexpr size_t count_id_start_flat = 1578; +constexpr size_t off_dir_start = 194144; +constexpr size_t count_dir_start = 1608; +constexpr size_t off_dir_final = 200576; +constexpr size_t count_dir_final = 1608; +constexpr size_t off_dir_value = 207008; +constexpr size_t count_dir_value = 1608; +constexpr size_t off_combining_flat = 208616; +constexpr size_t count_combining_flat = 666; +constexpr size_t off_joining_start = 211280; +constexpr size_t count_joining_start = 533; +constexpr size_t off_joining_final = 213412; +constexpr size_t count_joining_final = 533; +constexpr size_t off_joining_value = 215544; +constexpr size_t count_joining_value = 533; alignas(8) inline constexpr uint8_t compressed[] = { -0xec,0x9c,0x09,0x40,0x53,0xc7,0xda,0xfe,0x5f,0x08,0x98,0x28,0x4b,0x4c,0xc2,0x12, -0x14,0x09,0x12,0x42,0x12,0x76,0x12,0x20,0xec,0x09,0xd0,0xdd,0x56,0xdb,0xda,0xdd, -0x5b,0x5b,0x97,0x6a,0xdd,0xad,0xb6,0xda,0xc5,0x96,0x23,0xbb,0xa2,0xe0,0xbe,0xb0, -0x8a,0xa8,0xa8,0x88,0x08,0xa8,0xec,0xcb,0x2d,0x2a,0x62,0xad,0x88,0xa8,0xdd,0xeb, -0x56,0x36,0x6d,0x6b,0x5b,0xdb,0xda,0xd6,0x96,0xfc,0x9f,0x73,0x12,0xd4,0xb6,0xf6, -0xb6,0xb7,0xcb,0xfd,0xbe,0xfb,0xfd,0x9b,0xe1,0x37,0x33,0xe7,0x9c,0x99,0x79,0xde, -0x79,0xcf,0x9c,0x73,0x66,0x4e,0x00,0x62,0x88,0x0c,0xc4,0x50,0x33,0x91,0x85,0xc1, -0x82,0xb1,0x68,0xb6,0x20,0x4b,0x83,0x25,0x63,0x49,0x4c,0xb3,0x25,0xf1,0x0c,0x3c, -0x86,0xd7,0xcc,0x23,0x2b,0x83,0x15,0x63,0xd5,0x6c,0x45,0xd6,0x16,0x8c,0x25,0x63, -0xb0,0x26,0x86,0xc7,0x58,0x31,0xd6,0xcc,0x20,0x86,0xcf,0x08,0x98,0xc1,0xcc,0x10, -0xc6,0x86,0x21,0x86,0xb1,0xb6,0x65,0x9a,0xad,0x69,0x90,0x61,0x90,0x1d,0x63,0xcf, -0x08,0x19,0x66,0xd0,0x50,0x46,0xc4,0x88,0x19,0x09,0xe3,0xc0,0x38,0x32,0x4e,0x8c, -0x33,0x23,0x65,0x5c,0x98,0xe6,0x41,0xc3,0x18,0xe2,0x1b,0xf8,0x0c,0xbf,0x99,0x4f, -0x82,0xe1,0xa8,0x47,0x8c,0x41,0xc0,0x08,0xa0,0x27,0x20,0x6e,0xcb,0x95,0x19,0xc1, -0xb8,0x31,0x32,0xc6,0x9d,0x19,0xc9,0xd0,0x60,0xd3,0xbe,0x1f,0x07,0x0f,0x46,0xce, -0x78,0x32,0x0a,0xc6,0x30,0xd8,0x8b,0x61,0x06,0xcb,0x19,0x25,0xa3,0x62,0xd4,0x8c, -0x37,0xe3,0xc3,0xf8,0x32,0x7e,0x8c,0x3f,0x13,0xc0,0x04,0xa2,0x54,0x10,0xd0,0x30, -0x5a,0x26,0x98,0x69,0x1e,0x1c,0xc2,0xd0,0x10,0xc3,0x10,0x66,0x08,0x54,0x86,0x90, -0x8d,0xc1,0x86,0xb1,0x69,0xb6,0x21,0x5b,0x83,0x2d,0x63,0xdb,0x6c,0x4b,0x76,0x06, -0xbb,0x50,0x86,0xb1,0x6b,0xb6,0x23,0x7b,0xd8,0x62,0x6f,0xd2,0x60,0xcc,0xa9,0x8e, -0x69,0xb6,0x27,0xa1,0x41,0x78,0x2b,0x3b,0x6e,0x15,0x18,0x61,0x33,0x5b,0x76,0x28, -0x31,0x61,0xa6,0xbe,0x0d,0x65,0x86,0x36,0x0f,0x25,0x51,0x38,0x63,0x10,0x45,0x30, -0x91,0xd8,0x13,0xc5,0x30,0xa2,0x66,0x11,0x89,0x0d,0x62,0x46,0xdc,0x2c,0x26,0x49, -0x34,0x63,0x90,0x30,0x92,0x66,0x09,0x39,0x18,0x1c,0x62,0x18,0xc6,0xa1,0xd9,0x81, -0x1c,0x0d,0x8e,0x8c,0x63,0xb3,0x23,0x39,0x19,0x9c,0x7e,0xab,0xee,0xdf,0xe1,0xef, -0xf0,0x77,0xf8,0x6b,0x82,0x9e,0x31,0x5c,0xcf,0xc7,0x32,0x8c,0x53,0xb3,0x53,0x1c, -0x43,0xce,0x06,0x67,0xc6,0xb9,0xd9,0x39,0x9e,0x41,0x9e,0xb9,0x0d,0xdc,0x0e,0xee, -0x60,0xee,0x64,0xee,0x42,0x7a,0x37,0x73,0x0f,0x43,0x52,0x83,0x74,0xd4,0xdf,0xde, -0xfb,0x0b,0xc3,0xbd,0xcc,0x7d,0xcc,0xe8,0xbf,0x03,0x17,0x18,0x69,0xb3,0x94,0x5c, -0x0c,0x2e,0x8c,0x4b,0xb3,0x0b,0x0d,0x33,0x0c,0x63,0x86,0x35,0x0f,0xa3,0xe1,0x86, -0xe1,0xcc,0xf0,0xe6,0xe1,0xe4,0x6a,0x70,0x65,0x5c,0x9b,0x5d,0x69,0x84,0x61,0x04, -0x33,0xa2,0x79,0x04,0xb9,0x19,0xdc,0x18,0xb7,0x66,0x37,0x92,0x19,0x64,0x63,0x98, -0xfb,0xe1,0xc9,0x07,0x98,0x07,0x11,0x8f,0x65,0x1e,0xe2,0xda,0x7a,0x98,0x79,0x84, -0x79,0x94,0x79,0x8c,0x79,0x9c,0x79,0x82,0x61,0x64,0x78,0x66,0xca,0xc8,0x7d,0x1c, -0x63,0x70,0x67,0xdc,0xff,0x71,0xdd,0xf7,0x77,0x32,0x4f,0x32,0xcd,0xee,0xa3,0x99, -0xf1,0xcc,0x53,0xcc,0xd3,0xcc,0x04,0x66,0x22,0x33,0x89,0x99,0xcc,0x3c,0xc3,0x4c, -0x61,0xa6,0x32,0xcf,0x32,0xd3,0x98,0xe9,0xcc,0x0c,0x66,0x26,0xda,0x22,0x66,0x16, -0x43,0x23,0x67,0x33,0x73,0x18,0xc3,0xc8,0xb9,0x5c,0xeb,0xcf,0x31,0xf3,0x98,0xf9, -0xcc,0x38,0xe6,0x79,0xe6,0x05,0x66,0x01,0x8e,0x2f,0x64,0x5e,0x64,0x5e,0x62,0x5e, -0x66,0x5e,0x41,0x7e,0x11,0xf3,0x2a,0xf3,0x1a,0x93,0xc0,0x30,0xcc,0x62,0x26,0x91, -0x49,0x62,0x92,0xb1,0x2f,0x05,0xa4,0x72,0x35,0xd3,0xf0,0xec,0x24,0x26,0x9d,0x59, -0xc2,0x2c,0x65,0x32,0x98,0x65,0xdc,0xbe,0xe5,0x6c,0xdf,0x47,0x66,0x32,0x59,0xcc, -0x0a,0x66,0x25,0xb3,0x0a,0xc7,0x57,0x33,0x6b,0x30,0x3f,0x58,0xcb,0xac,0xc3,0x91, -0xf5,0xcc,0x06,0x66,0x23,0x93,0x8d,0x5c,0x0e,0x93,0xcb,0xe4,0x31,0xf9,0x66,0x6f, -0x15,0x30,0x9b,0x98,0x42,0x66,0x33,0x53,0xf4,0x2f,0xc7,0xd7,0x24,0xce,0xfe,0x2d, -0xe6,0xad,0xad,0x7f,0xfa,0x39,0xdb,0xc6,0x14,0xff,0xea,0x18,0xdf,0xce,0xec,0xf8, -0x1f,0xbc,0xc2,0x1e,0xb8,0xc5,0xbe,0x65,0xff,0x27,0xaf,0x9f,0x25,0xbf,0xb3,0xde, -0x4f,0xbd,0x23,0x67,0x76,0x32,0x25,0xcc,0x2e,0xe4,0x4a,0x99,0xdd,0xb7,0x54,0x68, -0x1e,0x49,0x1e,0x65,0x38,0xbe,0x87,0x29,0x67,0x2a,0xfe,0x3f,0xb9,0x53,0x57,0x32, -0x7b,0x39,0x5f,0x15,0xff,0x7d,0xa7,0xfe,0x51,0xd8,0x77,0xdd,0x43,0xfb,0x99,0xaa, -0x9b,0xfc,0xb5,0xfc,0x4f,0x53,0x20,0xa6,0x9a,0x31,0x78,0xfc,0xcf,0xf5,0xd0,0xbc, -0x2a,0xf2,0xb8,0x79,0x34,0xd4,0x30,0xb5,0x4c,0x1d,0x37,0xa7,0xda,0x6a,0xde,0xa3, -0x62,0xea,0x99,0x66,0x0f,0x92,0x1b,0xe4,0xc4,0x34,0xa0,0x56,0x23,0xf6,0x35,0x99, -0x9e,0x6b,0xf2,0x66,0x39,0x79,0x1a,0x3c,0x19,0xcf,0x66,0x4f,0x52,0x18,0x14,0x8c, -0xa2,0x59,0x41,0x5e,0x06,0x2f,0xc6,0xab,0xd9,0x8b,0x94,0x06,0xe5,0xad,0x46,0x5b, -0xf3,0x6f,0xb0,0xeb,0x9f,0x03,0xcf,0x4d,0x65,0xb3,0xf2,0x75,0xa4,0x2d,0xcc,0x81, -0xeb,0xc7,0x0e,0x32,0x87,0x7e,0x52,0xba,0xd5,0x9c,0x1e,0x36,0xa7,0x6d,0xe6,0xf4, -0x88,0x59,0xf1,0x0d,0x86,0x54,0x47,0x7f,0x41,0xe9,0x4d,0xe6,0x18,0xe2,0x76,0xf3, -0x96,0x41,0xc5,0xa8,0x9a,0x55,0xc7,0xaf,0x1f,0xf5,0x41,0xed,0x0e,0xe6,0x04,0x43, -0x6a,0x83,0x9a,0x51,0x77,0x32,0xcd,0x6a,0xf2,0xbe,0xd5,0x7d,0xe5,0xc7,0xe1,0xa4, -0x39,0x3d,0xc5,0x9c,0x66,0xde,0x62,0xde,0x66,0xde,0xb9,0xe9,0xd8,0xbb,0xcc,0x7b, -0xcc,0xfb,0x5c,0xee,0x03,0xc6,0xe0,0xfd,0xef,0xde,0xbf,0xfe,0x0e,0x7f,0x87,0xbf, -0xc3,0xdf,0xe1,0xef,0xf0,0xaf,0xc2,0xb3,0xff,0x6b,0x2c,0xf9,0xf0,0xbf,0xd0,0x7b, -0x75,0xff,0xdf,0x8c,0x93,0x33,0xb7,0xd8,0x17,0xf5,0xe7,0xae,0xfb,0xbd,0x9b,0xbd, -0xc9,0xc7,0xe0,0xc3,0xf8,0x34,0xfb,0x90,0xaf,0xc1,0x97,0xf1,0xfd,0x63,0xeb,0x97, -0xff,0x3d,0xe1,0xec,0xdf,0xf7,0x19,0x2e,0x2c,0x61,0x8c,0x46,0x0b,0xe2,0x91,0x35, -0xf1,0x69,0x30,0xd9,0x90,0x1d,0x09,0x49,0x44,0x12,0x72,0x24,0x67,0x72,0xa1,0xe1, -0x34,0x82,0x64,0x34,0x92,0xe4,0xa4,0x20,0x25,0xa9,0xc9,0x87,0xfc,0x28,0x80,0x82, -0x48,0x4b,0xc6,0x3f,0xed,0xd3,0xff,0x07,0x43,0xc8,0x4f,0x6c,0xd1,0x11,0xdb,0x23, -0x36,0x47,0x88,0x23,0xb9,0x9c,0x9e,0x62,0x29,0x9e,0xee,0xe4,0xf2,0xf7,0xd0,0x68, -0xf4,0xca,0x68,0xbc,0x9f,0x1e,0xa1,0x7f,0x20,0x9d,0x48,0xcf,0xd0,0xb3,0x34,0x83, -0x66,0xd3,0x73,0xf4,0x3c,0x2d,0xa4,0x97,0xe9,0x55,0x38,0x26,0x89,0x52,0x69,0x09, -0x2d,0xa3,0x2c,0x5a,0x45,0x6b,0x69,0x03,0xe5,0x50,0x3e,0x15,0xd2,0x16,0x94,0x2f, -0xa6,0x9d,0x54,0x4a,0x7b,0xa8,0x92,0xf6,0x53,0xcd,0x9f,0xe0,0x87,0x7a,0xb4,0xd1, -0x04,0x5e,0x07,0x07,0xc1,0x61,0xf0,0x06,0x38,0x06,0x3a,0xc0,0x49,0xf0,0x16,0x78, -0x17,0x7c,0x00,0xce,0x82,0x0b,0xa0,0x1b,0xf4,0x81,0x8f,0xc1,0x65,0xf0,0x05,0xf8, -0x0a,0x7c,0x03,0xae,0x81,0x7e,0xd6,0x0f,0x16,0x46,0xa3,0x15,0x10,0x58,0x08,0x2c, -0x6c,0x90,0xda,0x5b,0xb0,0x8a,0x22,0xc4,0x0e,0xc0,0x19,0x0c,0xb3,0x18,0x66,0xe1, -0x86,0x74,0x24,0xf0,0x04,0x4a,0xe0,0x6d,0xe1,0x8f,0x38,0x08,0x04,0x03,0x1d,0x88, -0x00,0xd1,0xc0,0x00,0xe2,0xc1,0x1d,0xe0,0x6e,0x70,0x2f,0x18,0x03,0x1e,0x04,0x0f, -0x83,0xc7,0xc0,0x38,0x30,0x1e,0x4c,0x00,0x93,0xc1,0x54,0x30,0x1d,0xcc,0x02,0x73, -0xc1,0x7c,0x8b,0x05,0x88,0x5f,0x02,0x8b,0x80,0x02,0x56,0x26,0x58,0x24,0x22,0x97, -0x02,0xd2,0x2d,0x32,0x10,0x67,0x5a,0xac,0xb4,0x58,0xc3,0x59,0xba,0xde,0x22,0xdb, -0x22,0xcf,0x62,0x13,0xf2,0x45,0x16,0xdb,0x10,0xef,0xb0,0xd8,0x65,0x51,0x66,0x61, -0xf2,0x5b,0x85,0xc5,0x3e,0xe4,0xaa,0x2d,0xea,0x10,0x37,0x82,0x7f,0x82,0x03,0x16, -0xad,0x88,0x8f,0x70,0x25,0xde,0x44,0x7c,0xdc,0xa2,0x13,0xf1,0x69,0x8b,0x77,0x2c, -0xde,0x47,0x7a,0x06,0x9c,0xb7,0xe8,0x32,0xd7,0xef,0xb5,0xf8,0xf1,0x79,0xb8,0x64, -0xc1,0x86,0xcb,0x5c,0xf8,0x82,0x0b,0x5f,0xa1,0xc4,0x37,0xe0,0x1a,0xe8,0x07,0x16, -0x96,0xf0,0x26,0xe0,0x83,0x21,0x96,0x6c,0x1d,0x3b,0xc4,0x43,0x81,0x04,0x38,0x01, -0x17,0xe0,0x0a,0x64,0xc0,0x03,0x28,0xb8,0x52,0x2a,0x4b,0x36,0xf8,0x20,0xef,0x6f, -0x19,0x64,0x19,0x8c,0x54,0x07,0x22,0x40,0x34,0x30,0x80,0x78,0x70,0x07,0xb8,0x1b, -0xdc,0x0b,0xc6,0x80,0x07,0xc1,0xc3,0xe0,0x31,0x30,0x0e,0x8c,0x07,0x13,0xc0,0x64, -0x30,0x15,0x4c,0x07,0xb3,0xc0,0x5c,0x30,0x1f,0x2c,0x00,0x2f,0x81,0x45,0x20,0x01, -0x24,0x82,0x14,0x90,0x0e,0x32,0x2c,0x7f,0xdc,0xd7,0x4c,0xcb,0x55,0xd8,0xb3,0xd6, -0x72,0x03,0xb7,0x3f,0x17,0x71,0x81,0xe5,0x66,0xcb,0xad,0x96,0xdb,0x91,0x2b,0x01, -0xbb,0x41,0x39,0xd8,0x6b,0x69,0xfc,0xaf,0xff,0x08,0xa9,0xca,0x52,0x82,0x3b,0x58, -0xad,0x65,0x83,0x65,0xb3,0xa5,0x1f,0xee,0x5e,0x7f,0xac,0xbd,0x16,0xcb,0x56,0xcb, -0x37,0x2c,0xdb,0x2d,0x3b,0x2d,0xdf,0xe2,0xbc,0xb3,0xcd,0xc2,0x19,0x77,0xc7,0x00, -0x7a,0xef,0x77,0xfa,0xea,0x43,0xcb,0x73,0xa8,0xf9,0x91,0x65,0x8f,0xe5,0xc7,0xb7, -0x68,0x81,0xfe,0xf0,0x1d,0xe6,0x32,0x5a,0xfd,0x02,0x7c,0x05,0xbe,0xb1,0x34,0xdd, -0x6f,0xaf,0x0d,0x28,0x59,0x5a,0xf0,0x06,0xee,0xa3,0xf1,0x64,0xc5,0x1b,0xc2,0xb3, -0xe3,0x0d,0xe5,0x49,0x78,0x4e,0xd8,0xeb,0x02,0x5c,0x79,0x32,0x1e,0x46,0x32,0x4f, -0xc1,0x53,0xf1,0x7c,0x78,0xfe,0xbc,0x20,0x5e,0x30,0x4f,0xc7,0xfb,0xd8,0x32,0x82, -0x17,0xcd,0xbb,0x93,0x0c,0xbc,0x78,0xde,0x1d,0xbc,0xbb,0x79,0xf7,0xa2,0xe4,0x18, -0xde,0x83,0xbc,0x87,0x79,0x8f,0xf1,0xc6,0xf1,0xc6,0xf3,0x26,0xf0,0x26,0xf3,0xa6, -0xf2,0xfe,0x9c,0xb3,0x37,0x1d,0xda,0x3a,0xb4,0xec,0x8a,0x16,0x1f,0x83,0x16,0xc6, -0x3c,0x98,0x0b,0xe6,0x83,0x05,0xe0,0x25,0xb0,0x08,0x24,0x80,0x44,0x90,0x02,0xd2, -0x41,0x06,0xc8,0x04,0x11,0xb0,0x6f,0x0c,0x52,0x1d,0xec,0x37,0x1a,0x57,0x82,0x31, -0xbc,0x35,0x9c,0x75,0xeb,0x79,0xd9,0xbc,0x3c,0xde,0x26,0x5e,0x11,0x6f,0x1b,0x6f, -0x07,0x6f,0x17,0xaf,0x8c,0x57,0xc1,0xdb,0xc7,0xab,0xe6,0xd5,0xf1,0x1a,0x79,0xff, -0xe4,0x1d,0xe0,0xb5,0xf2,0x8e,0xf0,0xde,0xe4,0x1d,0xe7,0x75,0xf2,0x4e,0xf3,0xde, -0xe1,0xbd,0xcf,0x3b,0xc3,0x3b,0xcf,0xeb,0xe2,0xf5,0xf2,0x2e,0xf1,0x3e,0xe5,0x7d, -0xce,0xfb,0x92,0x77,0x95,0xf7,0x1d,0xef,0x07,0x1e,0xdc,0x66,0x35,0xc8,0x6a,0xb0, -0x95,0xad,0x95,0xd0,0x4a,0x6c,0xe5,0x68,0x25,0xb5,0x1a,0x6e,0xe5,0x66,0x35,0xd2, -0xca,0xd3,0x4a,0x69,0xe5,0x6d,0xe5,0x67,0xf5,0x57,0x8f,0xef,0x40,0x28,0x68,0x41, -0x28,0x08,0x07,0x51,0x40,0x0f,0xe2,0xc0,0xed,0xe0,0x2e,0x30,0x0a,0x8c,0x06,0x0f, -0x80,0x87,0xc0,0xa3,0xe0,0x09,0xf0,0x24,0x78,0xfa,0x16,0x16,0x4e,0xc2,0xbe,0x29, -0x60,0x1a,0x98,0x09,0xe6,0x80,0x79,0xe0,0x05,0xf0,0x22,0x78,0x05,0xbc,0x06,0x16, -0x83,0x64,0x90,0x06,0x96,0x82,0xe5,0x60,0x05,0x58,0x0d,0xd6,0x81,0x8d,0x20,0x17, -0x14,0x80,0xcd,0x60,0x2b,0xd8,0x0e,0x4a,0xc0,0x6e,0x50,0x0e,0xf6,0x5a,0x55,0x21, -0xae,0x05,0x0d,0xa0,0x19,0xb4,0x80,0x43,0xa0,0x8d,0xb3,0xec,0x28,0xe2,0x76,0x70, -0x02,0x9c,0x02,0x6f,0x83,0xf7,0xc0,0x87,0xe0,0x1c,0xf8,0x08,0xf4,0x80,0x8b,0xe0, -0x13,0xf0,0x19,0xb8,0x02,0xbe,0x06,0xdf,0x82,0xef,0xd9,0x56,0x80,0xa5,0xb5,0xd1, -0x68,0x0d,0x04,0xc0,0x06,0xd8,0x03,0x11,0x70,0x00,0xce,0x60,0x18,0x18,0x01,0xdc, -0x81,0x1c,0x78,0x01,0x35,0xf0,0x05,0x01,0x40,0x03,0x42,0x40,0x18,0x88,0x04,0x31, -0x20,0x16,0xdc,0x06,0xee,0x04,0xf7,0x80,0xfb,0xc0,0xfd,0x60,0x2c,0x78,0x04,0x3c, -0x6e,0xcd,0x5e,0x6f,0xff,0xb0,0x7e,0xca,0x7a,0xa2,0xf5,0x33,0xd6,0xcf,0x5a,0xcf, -0xb0,0x9e,0x6d,0xfd,0x9c,0xf5,0xf3,0xd6,0x0b,0xad,0x5f,0xb6,0x7e,0xd5,0x9a,0xb1, -0x4e,0xb2,0x4e,0xb5,0x5e,0x62,0xbd,0xcc,0x3a,0xcb,0x7a,0x95,0xf5,0x5a,0xeb,0x0d, -0xd6,0x39,0xd6,0xf9,0xd6,0x85,0xd6,0x5b,0xac,0x8b,0xad,0x77,0x5a,0x97,0x5a,0xef, -0xb1,0xae,0xb4,0xde,0x6f,0x5d,0x63,0x5d,0x6f,0xdd,0x64,0xfd,0xba,0xf5,0x41,0xeb, -0xc3,0xd6,0x6f,0x58,0xb3,0x57,0xea,0x5f,0xf9,0x39,0x66,0x7d,0x63,0x56,0x36,0x90, -0xfb,0xbf,0xf2,0xe9,0xb4,0x7e,0xdb,0xfa,0x03,0xeb,0xf3,0xd6,0x7f,0xac,0x95,0x1e, -0xeb,0x4f,0xad,0xbf,0xb2,0xfe,0xde,0x9a,0x37,0x68,0xc8,0x20,0xd1,0x20,0xe9,0xa0, -0x3f,0x77,0x26,0xfc,0x63,0xdf,0xff,0x7c,0x76,0x7c,0x63,0x8f,0x6c,0x90,0xd7,0xa0, -0x7e,0xa3,0xdf,0xa0,0x9f,0xd6,0xfe,0x7d,0x9a,0x3f,0x3d,0xcf,0x37,0xf4,0xfe,0xfd, -0x96,0xfb,0x6f,0xb1,0x1d,0x3c,0x88,0x8d,0x23,0x07,0xdd,0xdc,0x62,0xff,0xaf,0xea, -0xfd,0xb4,0xcf,0xa6,0x10,0x37,0xe8,0xee,0x41,0xf7,0x0f,0x62,0xf7,0x3e,0x3a,0xe8, -0xa7,0xde,0xf9,0xf7,0x57,0x1b,0xff,0xca,0xff,0xb7,0x2a,0x39,0xb0,0x35,0x7e,0xd0, -0x33,0x83,0xfa,0x6f,0xe9,0xc9,0xdf,0x6f,0xc1,0x5f,0xf7,0x99,0x39,0xc8,0xf8,0x0b, -0xe7,0xb7,0xff,0xfa,0x39,0xea,0xff,0x17,0xe7,0xf0,0xb7,0x9d,0xf5,0x5f,0xae,0x35, -0x7f,0xd0,0xbf,0x1e,0x7d,0xbf,0xd4,0x42,0xff,0x2f,0xfa,0xf0,0xe5,0x41,0x8b,0x07, -0xfd,0x19,0xeb,0xc7,0x5f,0xfa,0xa4,0x0f,0xfa,0x4f,0xde,0x9b,0x96,0x0d,0xfa,0x79, -0x8f,0x57,0x5f,0xdf,0x97,0x7d,0x3d,0x57,0x78,0x3d,0xb7,0xfd,0x17,0xed,0x2b,0x1b, -0xf4,0xf3,0x6b,0x6a,0x3f,0xf6,0x35,0x0c,0x3a,0x30,0xe8,0x8d,0x41,0xa7,0x06,0xbd, -0xff,0x93,0x9a,0xdd,0xbf,0xa1,0xa7,0x9f,0xdc,0xc2,0xbe,0x2f,0xaf,0xef,0xbb,0x76, -0x3d,0x67,0xc9,0x1f,0xc8,0x0d,0xe6,0xff,0x52,0x5b,0x43,0xf9,0x7f,0xe6,0x93,0xc5, -0x99,0x3f,0x9c,0x2f,0xe3,0xcb,0xf9,0x4a,0xbe,0x0f,0x3f,0x80,0xaf,0xe5,0xeb,0xf8, -0x91,0x7c,0x3d,0x3f,0x9e,0x7f,0x27,0x7f,0x14,0x7f,0x0c,0x7f,0x2c,0xff,0x51,0xfe, -0x38,0xfe,0x53,0xfc,0x49,0xfc,0xa9,0xfc,0x19,0xfc,0x39,0xfc,0xf9,0xfc,0x85,0xfc, -0x57,0xf8,0x09,0xfc,0x24,0x7e,0x1a,0x3f,0x83,0x9f,0xc5,0x5f,0xcd,0x5f,0xcf,0xcf, -0xe1,0x17,0xf0,0x8b,0xf8,0xc5,0xfc,0x12,0x7e,0xbf,0xb1,0x8c,0x7f,0x63,0x64,0x54, -0xf2,0xff,0xca,0xab,0xb3,0x8a,0xff,0x67,0xb4,0x42,0x44,0x64,0xfc,0xaf,0xf9,0xb0, -0xfe,0xac,0xe3,0x37,0xf1,0x5b,0xf8,0xad,0xfc,0x37,0xf8,0xed,0xfc,0xfe,0xff,0xe0, -0xec,0xe2,0xdf,0xf3,0x14,0x5d,0xff,0xfc,0xda,0x3d,0xfc,0x8f,0x7e,0x4e,0x63,0x65, -0xf1,0x1d,0x8f,0x5d,0x43,0x0c,0xc2,0xba,0x41,0x6b,0xd5,0xc9,0x7f,0x8b,0x7f,0xb3, -0xc2,0x7b,0xfc,0x33,0xfc,0x0b,0xfc,0x1e,0xfe,0x25,0xfe,0x65,0xfe,0x15,0xfe,0x55, -0xfe,0x35,0xbe,0x91,0xcf,0x13,0xf0,0x05,0x55,0x7c,0x1b,0x81,0x50,0x20,0x11,0x38, -0x0b,0x86,0x0b,0x64,0x02,0xb9,0x40,0x29,0xf0,0x11,0x04,0x08,0xb4,0x02,0x9d,0x20, -0x52,0xa0,0x17,0xc4,0x0b,0xee,0x14,0x8c,0x12,0x8c,0x11,0x8c,0x15,0x3c,0x2a,0x18, -0x27,0x78,0x4a,0x30,0x49,0x30,0x55,0x30,0x43,0x30,0x47,0x30,0x5f,0xb0,0x50,0xf0, -0x8a,0x20,0x41,0xc0,0xb6,0x9c,0x24,0x48,0x13,0x64,0x08,0xfe,0x2a,0x7f,0x5b,0xd0, -0xf3,0xc4,0x83,0xf7,0xd8,0xf7,0x8a,0xeb,0x2d,0x7e,0xfa,0x5e,0x11,0x73,0x6d,0x9a, -0x6f,0x29,0xc3,0xba,0x9c,0x7d,0xaf,0xe8,0x47,0x16,0x94,0x25,0x58,0x25,0x58,0x2b, -0xe0,0x71,0xef,0x21,0xd9,0xb7,0x3e,0x1b,0x05,0x76,0x28,0xe5,0x88,0xd2,0xfe,0x16, -0x23,0x28,0xdd,0x22,0x57,0xb0,0x49,0x20,0xe3,0x4a,0x6f,0x11,0x54,0x58,0xf8,0xd0, -0x76,0x81,0x69,0x55,0xca,0xae,0x39,0x45,0x68,0x87,0x7d,0x3b,0xc9,0xee,0xb9,0x97, -0xdb,0xf3,0xcb,0x76,0x5d,0xfd,0x53,0x56,0xa6,0xbb,0x04,0xd6,0x54,0x26,0x58,0x45, -0x1b,0x05,0x36,0x54,0x21,0xd8,0x27,0xa8,0x16,0xec,0xb2,0xd8,0x61,0x51,0x27,0x68, -0x14,0xbc,0x2e,0x38,0x28,0x38,0x2c,0x38,0x2a,0x68,0x17,0x9c,0x10,0xec,0xb3,0x38, -0x25,0x78,0x5b,0x50,0x6d,0xf1,0x9e,0xe0,0x43,0xc1,0x11,0x8b,0x73,0x82,0xcd,0x96, -0xa7,0x2d,0x3e,0x12,0xbc,0x63,0xb1,0xd5,0x52,0x4b,0xbd,0x82,0x4b,0x82,0xf3,0x16, -0x3a,0xde,0xa7,0x38,0x03,0x5f,0x80,0xaf,0xc1,0x77,0xa0,0x1f,0x58,0x0e,0x36,0x1a, -0x07,0x81,0x21,0xc0,0x1e,0x88,0x81,0x13,0x18,0x06,0xdc,0x80,0x07,0xf0,0x02,0xde, -0xc0,0x1f,0x68,0x40,0x28,0x88,0x00,0x31,0x20,0x0e,0xdc,0x01,0xee,0x01,0xa3,0xc1, -0x83,0xe0,0x11,0xf0,0x04,0x18,0x0f,0x26,0x82,0x29,0x60,0x3a,0x98,0x0d,0xe6,0x81, -0x05,0xe0,0x65,0xf0,0x1a,0x48,0x04,0xa9,0x60,0x29,0xc8,0x04,0xab,0xc0,0x3a,0x90, -0x0d,0xf2,0xc1,0x66,0xb0,0x0d,0xec,0x04,0xbb,0x41,0x05,0xd8,0x0f,0x6a,0x41,0x23, -0x78,0x1d,0x1c,0x02,0x47,0xc0,0x31,0x70,0x02,0x9c,0x06,0xef,0x82,0x0f,0xc1,0x79, -0xd0,0x0d,0x2e,0x82,0x4f,0xc1,0x17,0xe0,0x6b,0xf0,0x1d,0xe8,0x07,0x96,0x43,0xd0, -0x7f,0x30,0x04,0xd8,0x03,0x31,0x70,0x1a,0x72,0xc3,0xfb,0xc3,0x86,0xb0,0xaa,0xf0, -0x05,0xf6,0x8d,0x04,0x0a,0xa0,0x06,0x7e,0x20,0x08,0x84,0x80,0x70,0x10,0x0d,0x62, -0xc1,0xed,0xe0,0x6e,0x70,0x1f,0x78,0x00,0x3c,0x0c,0x1e,0x07,0x4f,0x82,0x09,0xe0, -0x19,0x30,0x0d,0xcc,0x02,0xcf,0x81,0x17,0xc0,0x4b,0xe0,0x55,0xb0,0x18,0xa4,0x80, -0x25,0x60,0x39,0x58,0x09,0xd6,0x82,0x8d,0x20,0x0f,0x14,0x82,0xad,0x60,0x07,0x28, -0x05,0xe5,0x60,0x1f,0xa8,0x01,0x0d,0xe0,0x9f,0xe0,0x20,0x68,0x03,0x6f,0x82,0x0e, -0x70,0x0a,0xbc,0x03,0x3e,0x18,0xf2,0xf3,0x91,0x75,0x6e,0x48,0xd7,0x90,0xbe,0x21, -0x9f,0x0c,0xf9,0x7c,0xc8,0x57,0x43,0xbe,0x1d,0xf2,0xc3,0x90,0x9f,0xde,0x77,0x2c, -0x6c,0xac,0x6d,0x06,0xdb,0xd8,0xd9,0x88,0x6c,0x1c,0x6d,0x6e,0x75,0xff,0x71,0xb1, -0x19,0x61,0x33,0xd2,0x46,0x61,0xa3,0xb6,0xf1,0xb3,0x09,0xb2,0x09,0xb1,0xf9,0xe9, -0xf1,0x70,0x9b,0x68,0x9b,0x58,0x9b,0xdb,0x6d,0xee,0xb6,0xb9,0xcf,0xe6,0x01,0x9b, -0x87,0x6d,0x7e,0xda,0xfe,0xe3,0x36,0x4f,0xda,0x4c,0xb0,0x79,0xc6,0x66,0x9a,0xcd, -0xac,0x5b,0xb6,0xdf,0x6f,0x7c,0x0e,0xfb,0x5f,0x00,0x2f,0x81,0x57,0x7f,0xd6,0xfe, -0x62,0x9b,0x14,0x9b,0x25,0x36,0xcb,0x6d,0x56,0xda,0xac,0xb5,0xd9,0x68,0x93,0x87, -0xe3,0x43,0x70,0xc5,0x0d,0x05,0x12,0xe0,0x04,0x5c,0x80,0x2b,0x90,0x71,0xef,0x9e, -0x0a,0x6d,0x8a,0x6d,0x4a,0x6d,0x2a,0x6d,0x6a,0x6c,0x9a,0x6c,0x0e,0xda,0xbc,0x61, -0xf3,0xd3,0xed,0x0e,0x9b,0xb7,0x6c,0x3e,0xb0,0xb9,0x60,0xd3,0x67,0x73,0xd9,0xe6, -0x2b,0x9b,0x6b,0x3f,0xdb,0xb6,0xb0,0xe5,0xdb,0xda,0xd9,0x4a,0x6c,0x5d,0x6c,0x65, -0xb6,0x0a,0x5b,0x1f,0xdb,0x9f,0x6e,0xb3,0x36,0x05,0xd9,0xea,0x6c,0xa3,0x6c,0xd9, -0xbe,0xc4,0xda,0xde,0x69,0x3b,0xca,0x76,0x8c,0xed,0x10,0x9e,0xce,0x76,0xac,0xed, -0xc7,0x96,0x63,0x6d,0x1f,0xb5,0x1d,0x67,0x3b,0xc1,0x76,0xaa,0xed,0x4c,0xee,0xf8, -0x73,0xb6,0x0b,0x6d,0x87,0xf2,0x5e,0xb1,0x95,0xf0,0xa6,0xda,0x26,0xd8,0xa6,0xd8, -0x66,0xd8,0x9a,0x7a,0xb5,0xd2,0x76,0xc0,0x17,0x6b,0x6c,0x37,0xd8,0xe6,0xda,0xb2, -0x6f,0xc8,0x36,0xd9,0x6e,0xb3,0xdd,0x65,0x3e,0x5e,0x61,0x3b,0xd0,0xff,0x7d,0xb6, -0x35,0xb6,0x0d,0xb6,0xae,0xbc,0x7f,0xda,0x1e,0xb4,0xb5,0xe2,0xbd,0xc1,0xd5,0x7b, -0xd3,0xb6,0xd3,0xf6,0x6d,0xae,0xfd,0x0f,0x6c,0x2f,0xd8,0xba,0xf0,0x7a,0x6c,0x65, -0xbc,0x4e,0xdb,0x78,0xba,0x64,0xcb,0x7e,0x7f,0x71,0xab,0x60,0x7a,0xee,0x98,0x34, -0x2f,0xdb,0xde,0xf0,0xee,0x15,0xdb,0x7f,0xbd,0xae,0x30,0xfe,0xc2,0xb7,0x23,0x57, -0x6d,0xfb,0x51,0x53,0x60,0x27,0xb4,0xbb,0x3e,0x4e,0x90,0x73,0xb5,0xfb,0x69,0x2b, -0xee,0x76,0x72,0x3b,0x2f,0xbb,0x5f,0xbe,0xef,0xa9,0x7f,0x72,0x2c,0xe4,0xc6,0x83, -0x92,0x6e,0xa8,0xde,0xb4,0x93,0x42,0xed,0x44,0xdc,0x91,0x30,0xbb,0x08,0xbb,0x28, -0xbb,0x18,0x3b,0x83,0x5d,0x9c,0xdd,0x6d,0x76,0x77,0xd8,0xdd,0x63,0x77,0xaf,0xdd, -0x68,0xbb,0xe1,0x38,0x3e,0x9a,0xd8,0xef,0x67,0x6e,0x7d,0x1c,0xe3,0x1d,0xcf,0x83, -0x11,0x14,0x80,0x67,0x82,0xf0,0xfa,0xd3,0x43,0xc6,0x7d,0x1f,0x75,0xeb,0xe7,0xef, -0xfd,0x76,0xff,0xde,0x9d,0x7c,0xac,0xdd,0xa3,0x76,0xd6,0x34,0x0e,0xb5,0x9e,0xb2, -0x9b,0x64,0x97,0xc7,0x7e,0x63,0x61,0xc7,0x3e,0xad,0x4c,0xe1,0x2b,0x3c,0xb5,0x44, -0x50,0x75,0x86,0x1f,0x87,0xd3,0x0c,0xae,0x6d,0xd3,0x37,0x62,0x6c,0x60,0xb7,0x66, -0xdb,0x3d,0x67,0xf7,0x02,0xf6,0xb3,0xdf,0x89,0x4d,0xe0,0x99,0x52,0x47,0x7a,0x8e, -0xfb,0x4e,0x0d,0xb3,0x60,0xee,0x5b,0xb5,0x17,0xed,0x5c,0xd0,0x87,0x45,0x76,0x09, -0x76,0x89,0x76,0x29,0xf0,0x07,0x56,0x17,0x76,0x77,0xe3,0x59,0xa5,0xe2,0xdd,0xcd, -0x5b,0x76,0xdd,0x5e,0x3e,0xf7,0xec,0x63,0x9f,0x92,0x37,0xdb,0xb7,0xc2,0x6e,0x9d, -0x5d,0xae,0x5d,0x91,0xdd,0x0e,0xbb,0x32,0xbb,0x7d,0x76,0x75,0x76,0xff,0xb4,0x6b, -0xb5,0x7b,0xd3,0xae,0xd3,0xee,0x1d,0xbb,0x33,0x76,0x5d,0x76,0x97,0xd0,0xda,0x67, -0x76,0x57,0xec,0xae,0xda,0xf9,0xd0,0x77,0x76,0x3f,0xd8,0x59,0xd8,0x0f,0xb2,0x0f, -0xa0,0xc1,0xf6,0xb6,0xf6,0xce,0xdc,0x77,0x7a,0x2e,0xf4,0x6b,0xc7,0xcd,0x73,0x72, -0xfb,0x1b,0x8a,0x0e,0xf6,0x3f,0x5d,0x3d,0xfc,0x37,0x7e,0x86,0xd9,0x8f,0x44,0x3f, -0x7c,0xec,0x35,0xf6,0xff,0x69,0xe5,0x28,0x7b,0xc3,0x1f,0xd6,0xfc,0xed,0xeb,0xd7, -0x5b,0x5c,0x3d,0xf6,0x77,0xda,0xdf,0x63,0x7f,0x9f,0xfd,0xfd,0xf6,0x63,0xed,0x1f, -0xb1,0x7f,0xdc,0xfe,0x1f,0xf6,0x4f,0xd9,0x4f,0xb4,0x7f,0xc6,0x7e,0x9a,0xfd,0x2c, -0xfb,0xe7,0xec,0x5f,0xb0,0x7f,0xc9,0xfe,0x55,0xfb,0xc5,0xf6,0x29,0xf6,0x4b,0xec, -0x33,0xed,0x57,0xdb,0x6f,0xb0,0xcf,0xb3,0xdf,0x6c,0x5f,0x6c,0xbf,0xcb,0xbe,0xdc, -0x7e,0xbf,0x7d,0x9d,0xfd,0x6f,0xd5,0x6d,0xb6,0x3f,0x60,0x7f,0xd8,0xfe,0xa8,0xfd, -0x71,0xfb,0x93,0xf6,0x6f,0xdb,0xbf,0x6f,0x7f,0xd6,0xfe,0x23,0xfb,0x5e,0xfb,0x8f, -0xed,0x3f,0xb3,0xff,0xd2,0xfe,0x1b,0xfb,0xef,0xed,0x49,0x68,0x25,0x14,0x08,0x6d, -0x85,0x43,0x85,0x0e,0x42,0xa9,0xd0,0x55,0xe8,0x2e,0xf4,0x14,0xfe,0x9e,0x6f,0x9a, -0x7f,0x4f,0x9d,0x50,0xbb,0x3f,0x7e,0x16,0x55,0x42,0xe3,0xff,0xa9,0x4f,0x88,0x30, -0x5c,0x18,0xf5,0x27,0xf6,0xc9,0xf0,0x27,0xb5,0x75,0x87,0xf0,0x1e,0xe1,0x68,0xe1, -0x83,0xc2,0x47,0x84,0x4f,0x08,0xc7,0x0b,0x27,0x0a,0xa7,0x08,0xa7,0x0b,0x67,0x0b, -0xe7,0x09,0x17,0x08,0x5f,0x16,0xbe,0x26,0x4c,0x14,0xa6,0x0a,0x97,0x0a,0x33,0x85, -0xab,0x84,0xeb,0x84,0xd9,0xc2,0x7c,0xe1,0x66,0xe1,0x36,0xe1,0x4e,0xe1,0x6e,0x61, -0x85,0x70,0xbf,0xb0,0x56,0xd8,0x28,0x7c,0x5d,0x78,0x48,0x78,0x44,0x78,0x4c,0x78, -0x42,0x78,0x5a,0xf8,0xae,0xf0,0x43,0xe1,0x79,0x61,0xb7,0xf0,0xa2,0xf0,0x53,0xe1, -0x17,0xc2,0xaf,0x85,0xdf,0x09,0xfb,0x85,0x96,0x43,0xff,0x6a,0xbf,0x0e,0x82,0xc2, -0x90,0xa1,0x76,0x43,0x45,0x9c,0x92,0x03,0x62,0x29,0x70,0x05,0xab,0xb0,0x06,0xc8, -0x12,0xec,0xc2,0x7c,0xde,0x9d,0x3b,0xe6,0xf9,0x23,0x5b,0x24,0x18,0xaf,0xaa,0xa1, -0x3e,0x43,0xfd,0xb1,0x57,0x03,0x42,0x41,0x04,0x88,0x01,0x71,0xe0,0x0e,0x70,0x0f, -0x18,0x0d,0x1e,0x04,0x8f,0x80,0x27,0xc0,0x78,0x30,0x11,0x4c,0x01,0xd3,0xc1,0x6c, -0x30,0x0f,0x2c,0x00,0x2f,0x83,0xd7,0x40,0x22,0x48,0x05,0x4b,0x41,0x26,0x6b,0x09, -0x58,0x07,0xb2,0x41,0x3e,0xd8,0x0c,0xb6,0x81,0x9d,0x60,0x37,0xa8,0x00,0xfb,0x41, -0x2d,0x68,0x04,0xaf,0x83,0x43,0xe0,0x08,0x38,0x06,0x4e,0x80,0xd3,0xe0,0x5d,0xf0, -0x21,0x38,0x0f,0xba,0xc1,0x45,0xf0,0x29,0xf8,0xe2,0x67,0x5e,0xfe,0x1a,0x7b,0xbe, -0xbb,0xbe,0xb7,0x7f,0xa8,0xf1,0x3f,0xf6,0xbe,0xf3,0xc7,0x77,0x29,0x4b,0x91,0xf1, -0x77,0xbd,0xfd,0xfb,0xad,0x6f,0xb8,0x07,0x89,0xfe,0x3b,0xae,0xfe,0x21,0xa2,0x5f, -0xf2,0x80,0xbd,0x48,0x2c,0x72,0x12,0x0d,0x13,0xb9,0x89,0x3c,0x44,0x5e,0x22,0x6f, -0x91,0xbf,0x48,0x23,0x0a,0x15,0x45,0x88,0x62,0x44,0x71,0xa2,0x3b,0x44,0xf7,0x88, -0x46,0x8b,0x1e,0x14,0x3d,0x22,0x7a,0x42,0x34,0x5e,0x34,0x51,0x34,0x45,0x34,0x5d, -0x34,0x5b,0x34,0x4f,0xb4,0x40,0xf4,0xb2,0xe8,0x35,0x51,0xa2,0x28,0x55,0xb4,0x54, -0x94,0x29,0x5a,0x25,0x5a,0x27,0xca,0x16,0xe5,0x8b,0x36,0x8b,0xb6,0x89,0x76,0x8a, -0x76,0x8b,0x2a,0x44,0xfb,0x45,0xb5,0xa2,0x46,0xd1,0xeb,0xa2,0x43,0xa2,0x23,0xa2, -0x63,0xa2,0x13,0xa2,0xd3,0xa2,0x77,0x45,0x1f,0x8a,0xce,0x8b,0xba,0x45,0x17,0x45, -0x9f,0x8a,0xbe,0x10,0x7d,0x2d,0xfa,0x4e,0xd4,0x2f,0xb2,0x14,0x0f,0x12,0x0f,0x11, -0xdb,0x8b,0xc5,0x62,0x27,0xf1,0x30,0xb1,0x9b,0xd8,0x43,0xec,0x25,0xf6,0x16,0xfb, -0x8b,0x35,0xe2,0x50,0x71,0x84,0x38,0x46,0x1c,0x27,0xbe,0x43,0x7c,0x8f,0x78,0xb4, -0xf8,0x41,0xf1,0x23,0xe2,0x27,0xc4,0xe3,0xc5,0x13,0xc5,0x53,0xc4,0xd3,0xc5,0xb3, -0xc5,0xf3,0xc4,0x0b,0xc4,0x2f,0x8b,0x5f,0x13,0x27,0x8a,0x53,0xc5,0x4b,0xc5,0x99, -0xe2,0x55,0xe2,0x75,0xe2,0x6c,0x71,0xbe,0x78,0xb3,0x78,0x9b,0x78,0xa7,0x78,0xb7, -0xb8,0x42,0xbc,0x5f,0x5c,0x2b,0x6e,0x14,0xbf,0x2e,0x3e,0x24,0x3e,0x22,0x3e,0x26, -0x3e,0x21,0x3e,0x2d,0x7e,0x57,0xfc,0xa1,0xf8,0xbc,0xb8,0x5b,0x7c,0x51,0xfc,0xa9, -0xf8,0x0b,0xf1,0xd7,0xe2,0xef,0xc4,0xfd,0x62,0x4b,0xc9,0x20,0xc9,0x10,0x89,0xbd, -0x44,0x2c,0x71,0x92,0x0c,0x93,0xb8,0x49,0x3c,0x24,0x5e,0x12,0x6f,0x89,0xbf,0x44, -0x23,0x09,0x95,0x44,0x48,0x62,0x24,0x71,0x92,0x3b,0x24,0xf7,0x48,0x46,0x4b,0x1e, -0x94,0x3c,0x22,0x79,0x42,0x32,0x5e,0x32,0x51,0x32,0x45,0x32,0x5d,0x32,0x5b,0x32, -0x4f,0xb2,0x40,0xf2,0xb2,0xe4,0x35,0x49,0xa2,0x24,0x55,0xb2,0x54,0x92,0x29,0x59, -0x25,0x59,0x27,0xc9,0x96,0xe4,0x4b,0x36,0x4b,0xb6,0x49,0x76,0x4a,0x76,0x4b,0x2a, -0x24,0xfb,0x25,0xb5,0x92,0x46,0xc9,0xeb,0x92,0x43,0x92,0x23,0x92,0x63,0x92,0x13, -0x92,0xd3,0x92,0x77,0x25,0x1f,0x4a,0xce,0x4b,0xba,0x25,0x17,0x25,0x9f,0x4a,0xbe, -0x90,0x7c,0x2d,0xf9,0x4e,0xd2,0x2f,0xb1,0x74,0x18,0xe4,0x30,0xc4,0xc1,0xde,0x41, -0xec,0xe0,0xe4,0x30,0xcc,0xc1,0xcd,0xc1,0xc3,0xc1,0xcb,0xc1,0xdb,0xc1,0xdf,0x41, -0xe3,0x10,0xea,0x10,0xe1,0x10,0xe3,0x10,0xe7,0x70,0x87,0xc3,0x3d,0x0e,0xa3,0x1d, -0x1e,0x74,0x78,0xc4,0xe1,0x09,0x87,0xf1,0x0e,0x13,0x1d,0xfa,0x8d,0x7f,0x7e,0x60, -0x57,0x08,0x53,0x1c,0xfe,0x33,0xa3,0xf0,0x59,0xe8,0x4c,0x17,0xcd,0x74,0x98,0xeb, -0xf0,0x47,0xae,0x6e,0xf6,0xf3,0xbc,0xc3,0x4b,0x5c,0x1b,0xaf,0x39,0xfc,0x77,0x3f, -0x95,0x53,0x1c,0xfe,0xea,0xfb,0x62,0xbf,0x71,0x99,0xc3,0x0a,0x87,0x35,0x0e,0x1b, -0x1c,0x72,0x1d,0x36,0x39,0x6c,0x71,0xd8,0xee,0xb0,0xcb,0x61,0x8f,0xc3,0x5e,0x87, -0x6a,0x87,0x7a,0x87,0x66,0x87,0x03,0x0e,0x87,0x1d,0x8e,0x3a,0x1c,0x77,0x38,0xe9, -0xf0,0xb6,0xc3,0xfb,0x0e,0x67,0x1d,0x3e,0x72,0xe8,0x75,0xf8,0xd8,0xe1,0x33,0x87, -0x2f,0x1d,0xbe,0x71,0xf8,0xde,0x81,0x1c,0xad,0x1c,0x05,0x8e,0xb6,0x8e,0x43,0x1d, -0x1d,0x1c,0xa5,0x8e,0xae,0x8e,0xee,0x8e,0x9e,0x8e,0x2a,0x47,0x5f,0xc7,0x40,0xc7, -0x60,0xc7,0x30,0xc7,0x28,0x47,0x83,0xe3,0x6d,0x8e,0x77,0x39,0xde,0xeb,0x78,0xbf, -0xe3,0x43,0x8e,0x44,0x8f,0x39,0xfe,0xc3,0xf1,0x69,0xc7,0xc9,0x8e,0xcf,0x3a,0xce, -0x74,0x9c,0xeb,0xf8,0xbc,0xe3,0x8b,0x8e,0x8b,0x1c,0x19,0xc7,0x64,0xc7,0x74,0xc7, -0x65,0x8e,0x2b,0x1c,0xd7,0x38,0x6e,0x70,0xcc,0x75,0xdc,0xe4,0xb8,0xc5,0x71,0xbb, -0xe3,0x2e,0xc7,0x3d,0x8e,0x7b,0x1d,0xab,0x1d,0xeb,0x1d,0x9b,0x1d,0x0f,0x38,0x1e, -0x76,0x3c,0xea,0x78,0xdc,0xf1,0xa4,0xe3,0xdb,0x8e,0xef,0x3b,0x9e,0x75,0xfc,0xc8, -0xb1,0xd7,0xf1,0x63,0xc7,0xcf,0x1c,0xbf,0x74,0xfc,0xc6,0xf1,0x7b,0x47,0x93,0x57, -0xec,0x71,0x67,0x22,0x27,0x2b,0x27,0x81,0x93,0xad,0xd3,0x50,0x27,0x07,0x27,0x37, -0x91,0xd4,0xc9,0xd5,0xc9,0xdd,0xc9,0xd3,0xc9,0xff,0x0f,0xdf,0x7f,0x55,0x4e,0xfe, -0x4e,0xc1,0x4e,0x11,0x4e,0x06,0xa7,0x3b,0x9c,0xee,0x75,0x7a,0xd0,0xe9,0x31,0xa7, -0xf1,0x4e,0x93,0x9d,0xa6,0x3b,0xcd,0x75,0x5a,0xe0,0xb4,0xc8,0x29,0xd1,0x29,0xdd, -0x29,0xd3,0x69,0x8d,0x53,0xb6,0xd3,0x26,0xa7,0x6d,0x4e,0xbb,0x9c,0x2a,0x9c,0xaa, -0x9d,0x1a,0x9d,0x0e,0x38,0x1d,0x71,0x3a,0xee,0x74,0xda,0xe9,0x8c,0x53,0xbf,0xb1, -0xd7,0xe9,0x53,0xa7,0x2f,0x9d,0xbe,0x73,0x22,0xe7,0x41,0xce,0xb6,0xce,0x62,0x67, -0xa9,0xb3,0x9b,0xb3,0xa7,0xb3,0xb7,0x73,0xa0,0x73,0xa8,0x73,0x94,0x73,0x9c,0xf3, -0x5d,0xce,0xa3,0x9d,0x1f,0x72,0x7e,0xc2,0xf9,0x69,0xe7,0x29,0xce,0x33,0x9d,0xe7, -0x39,0xbf,0xe8,0xfc,0x9a,0x73,0xb2,0xf3,0x52,0xe7,0x15,0xce,0xeb,0x9c,0x73,0x9d, -0x37,0x3b,0x6f,0x77,0xde,0xed,0xbc,0xd7,0xb9,0xd6,0xb9,0xd9,0xf9,0x80,0xb3,0x93, -0xf8,0xb0,0xf3,0x4f,0xed,0x3b,0xea,0x7c,0xdc,0xb9,0xd3,0xf9,0xb4,0xf3,0x3b,0xce, -0xef,0x3b,0x9f,0x71,0x3e,0xef,0xdc,0xe5,0xdc,0xeb,0x7c,0xc9,0xf9,0x53,0xe7,0xcf, -0x9d,0xbf,0x74,0xbe,0xea,0xfc,0x9d,0xf3,0x32,0x9c,0xd9,0x2d,0x38,0xa7,0xec,0x59, -0x7c,0x9f,0x3b,0x7f,0x37,0xce,0xde,0x0f,0xce,0x16,0x52,0x6b,0xe9,0x60,0xa9,0x9d, -0x54,0x24,0x75,0x94,0xba,0x48,0x47,0x48,0x47,0x4a,0x15,0x52,0xb5,0xd4,0x4f,0x1a, -0x24,0x0d,0x91,0x46,0x49,0xe3,0xa5,0x37,0x7c,0x7b,0xa7,0x74,0x94,0x74,0x8c,0x34, -0x42,0x34,0x56,0x3a,0x5d,0xa4,0xc1,0xbd,0x76,0x3c,0xee,0xc2,0xdb,0x24,0x4b,0x45, -0xde,0xe2,0x47,0xa5,0xe3,0xa4,0x4f,0x49,0x27,0x49,0xa7,0x4a,0x67,0x48,0xe7,0x48, -0xe7,0x4b,0x17,0x4a,0x5f,0x91,0x6e,0x16,0x25,0x48,0x93,0xa4,0x69,0xd2,0x0c,0x69, -0x96,0x74,0xb5,0x74,0xbd,0x34,0x47,0x6a,0x3a,0x37,0x05,0xd2,0x22,0x69,0xb1,0xb4, -0x44,0x5a,0x26,0xad,0x94,0x56,0x49,0xeb,0xa4,0x4d,0xd2,0x16,0x69,0xab,0xf4,0x88, -0xf4,0x4d,0xe9,0x71,0x69,0xa7,0xf4,0xb4,0xf4,0x1d,0xe9,0xfb,0xd2,0x33,0xd2,0xf3, -0xd2,0x2e,0x69,0xaf,0xf4,0x92,0xf4,0x53,0xe9,0xe7,0xd2,0x2f,0xa5,0xdf,0x4a,0xfb, -0xa5,0x3c,0x17,0x81,0x8b,0x9d,0x8b,0xd8,0xc5,0xd9,0xc5,0xd5,0x65,0xa4,0x8b,0xd2, -0xc5,0xcf,0x45,0xeb,0x12,0xea,0x12,0xe1,0x12,0xed,0x12,0xeb,0x72,0xbb,0xcb,0xdd, -0x2e,0xf7,0xb9,0x3c,0xe0,0xf2,0xb0,0xcb,0xe3,0x2e,0x4f,0xba,0x4c,0x70,0x79,0xc6, -0x65,0x9a,0xcb,0x2c,0x97,0xe7,0x5c,0x5e,0x70,0x79,0xc9,0xe5,0x55,0x97,0xc5,0x2e, -0x29,0x2e,0x4b,0x5c,0x96,0xbb,0xac,0x74,0x59,0xeb,0xb2,0xd1,0x25,0xcf,0xa5,0xd0, -0x65,0xab,0xcb,0x0e,0x97,0x52,0x97,0x72,0x97,0x7d,0x2e,0x35,0x2e,0x0d,0x2e,0xff, -0x74,0x39,0xe8,0xd2,0xe6,0xf2,0xa6,0x4b,0x87,0xcb,0x29,0x97,0x77,0x5c,0x3e,0x70, -0x39,0xe7,0xd2,0xe5,0xd2,0xe7,0xf2,0x89,0xcb,0xe7,0x2e,0x5f,0xb9,0x7c,0xeb,0xf2, -0x83,0x8b,0xd5,0x30,0xd1,0x30,0xb7,0x61,0x3e,0xc3,0x42,0x86,0xc5,0x0d,0xbb,0x77, -0xd8,0x23,0xc3,0xa6,0x0c,0x9b,0x3f,0xec,0xd5,0x61,0x69,0xc3,0x56,0x0e,0xcb,0x1f, -0x56,0x32,0x6c,0xdf,0xb0,0xa6,0x61,0x87,0x86,0x1d,0x1f,0xf6,0xc1,0xb0,0x8b,0xc3, -0x3e,0x1f,0x66,0x31,0xdc,0x61,0xb8,0xe7,0x70,0xff,0xe1,0x31,0xc3,0x47,0x0f,0x1f, -0x37,0xfc,0x99,0xe1,0x73,0x86,0xbf,0x34,0x3c,0x75,0xf8,0xba,0xe1,0x45,0xc3,0x4b, -0x87,0x57,0x0d,0xff,0xe7,0xf0,0xc3,0xc3,0xdb,0x87,0x9f,0x1e,0xfe,0xc1,0xf0,0x9e, -0xe1,0x9f,0x0f,0xb7,0x70,0xb5,0x71,0x95,0xba,0xaa,0x5c,0x35,0xae,0xe1,0xae,0x06, -0xd7,0xfb,0x5d,0x9f,0x74,0x9d,0xe5,0xba,0xd0,0x35,0xcd,0x35,0xd3,0x75,0x83,0xeb, -0x66,0xd7,0x5d,0xae,0xfb,0x5d,0x9b,0x5d,0xdf,0x74,0x7d,0xcb,0xf5,0x43,0xd7,0x5e, -0xd7,0x2f,0x5c,0xbf,0x77,0x1d,0x3c,0x42,0x32,0x62,0xc4,0x08,0xe5,0x08,0xdd,0x88, -0xdb,0x46,0x8c,0x1a,0x31,0x6e,0xc4,0xc4,0x11,0x73,0x46,0x2c,0x1a,0x91,0x3a,0x62, -0xc5,0x88,0xec,0x11,0xc5,0x23,0x76,0x8f,0xa8,0x1e,0x71,0x70,0xc4,0xd1,0x11,0xef, -0x8f,0xe8,0x1e,0x71,0x69,0xc4,0x67,0x23,0xbe,0x1a,0xf1,0xdd,0x08,0xe3,0x08,0x2b, -0xb7,0xc1,0x6e,0xf6,0x6e,0x12,0x37,0xa9,0x9b,0x9b,0x9b,0xa7,0x9b,0xb7,0x5b,0xa0, -0x5b,0xa8,0x5b,0x94,0x5b,0x9c,0xdb,0x5d,0x6e,0xa3,0xdd,0x1e,0x72,0x7b,0xc2,0xed, -0x69,0xb7,0x29,0x6e,0x33,0xdd,0xe6,0xb9,0x2d,0x70,0x7b,0xc9,0x6d,0x91,0x1b,0xe3, -0x96,0xe4,0x96,0xea,0xb6,0xc4,0x6d,0xb9,0xdb,0x4a,0xb7,0x35,0x6e,0x39,0x6e,0x9b, -0xdd,0x76,0xb8,0xed,0x71,0x6b,0x70,0x6b,0x76,0x6b,0x71,0x6b,0x75,0x3b,0xe2,0xf6, -0xa6,0xdb,0x71,0xb7,0x4e,0xb7,0xd3,0x6e,0xef,0xba,0x9d,0x71,0x3b,0xef,0xd6,0xe5, -0xd6,0xe7,0xf6,0x89,0xdb,0x67,0x6e,0x57,0xdc,0xbe,0x76,0xfb,0xce,0xad,0xdf,0xcd, -0x52,0x36,0x48,0x36,0x44,0x66,0x27,0x1b,0x2a,0x93,0xc8,0x9c,0x64,0x2e,0xb2,0x11, -0x32,0x77,0x99,0x5c,0xe6,0x25,0xf3,0x96,0xf9,0xcb,0x82,0x64,0x21,0xb2,0x70,0x59, -0xb4,0xcc,0x20,0xbb,0x4d,0x76,0x8f,0xac,0xc1,0xed,0x01,0xd9,0xc3,0xb2,0xc7,0x65, -0x4f,0xca,0x26,0xc8,0xa6,0xc9,0xe6,0xc9,0x5e,0x90,0xbd,0x28,0x5b,0x24,0x4b,0x90, -0x25,0xca,0x52,0x64,0x4b,0x64,0xcb,0x40,0x96,0x6c,0x95,0x6c,0xad,0x6c,0xa3,0x2c, -0x17,0x14,0xc8,0x8a,0x64,0xfd,0xc6,0x62,0xd9,0x4e,0x59,0xa9,0x6c,0x0f,0x72,0x55, -0xb2,0x5a,0x59,0x83,0xac,0x59,0xd6,0x22,0x3b,0x84,0xf6,0xdb,0x64,0x47,0x65,0xed, -0xb2,0x13,0xb2,0xd3,0xb2,0xe3,0x6e,0xef,0xc8,0x3e,0x90,0x9d,0x43,0x89,0x8f,0x64, -0xbd,0xb2,0x4b,0xb2,0x4f,0x65,0x9f,0xcb,0xbe,0x94,0x7d,0x27,0x23,0x77,0x6b,0xf7, -0x21,0xee,0x42,0x77,0x07,0x77,0x17,0x77,0x37,0x77,0xb9,0xbb,0xca,0xdd,0xcf,0x5d, -0xeb,0x1e,0xee,0xae,0x77,0xbf,0xdd,0x7d,0x94,0xfb,0x03,0xee,0x8f,0xba,0x3f,0xe9, -0x3e,0xc9,0x7d,0x9a,0xfb,0x1c,0xf7,0x17,0xdc,0x5f,0x71,0x5f,0xec,0x9e,0xe6,0xbe, -0xdc,0x7d,0xb5,0xfb,0x46,0xf7,0x02,0xf7,0xad,0xee,0x25,0xee,0xe5,0xee,0xfb,0xdc, -0x8d,0xc6,0x1a,0xd0,0x00,0xfe,0x09,0x0e,0x82,0x4e,0xbe,0xd1,0xd8,0x86,0xf4,0x4d, -0xd0,0x01,0x4e,0x81,0x77,0xc0,0x07,0xe0,0x1c,0xe8,0x02,0x7d,0xe0,0x13,0xf0,0x39, -0xf8,0x0a,0x7c,0x0b,0x7e,0x00,0x16,0x23,0x8d,0x46,0x6b,0x30,0x78,0xe4,0x6f,0xbb, -0xff,0xd8,0xa1,0x9c,0x08,0x38,0x02,0x17,0x30,0x02,0x8c,0x04,0x0a,0xa0,0x06,0x7e, -0x20,0x08,0x84,0x80,0x70,0x10,0x0d,0x62,0x81,0x9b,0x95,0xa7,0xd5,0xff,0x96,0xa7, -0xd8,0xed,0xb0,0xe7,0x6e,0x70,0x1f,0x78,0x00,0x3c,0x0c,0x1e,0x07,0x4f,0x9a,0x7d, -0x30,0x01,0xe9,0x33,0x60,0x1a,0x98,0x05,0x9e,0x03,0x2f,0x80,0x97,0xc0,0xab,0x60, -0x31,0x48,0x01,0x4b,0xc0,0x72,0xb0,0x12,0xac,0x05,0x1b,0x41,0x1e,0x28,0x04,0x5b, -0xc1,0x0e,0x50,0x0a,0xca,0xc1,0x3e,0x50,0x03,0x1a,0xc0,0x3f,0xc1,0x41,0xd0,0x06, -0xde,0x04,0x1d,0xe0,0x14,0x78,0xc7,0xcc,0x8f,0x3f,0x1f,0x60,0xcf,0x39,0xd0,0x35, -0xb2,0x0f,0xf1,0x27,0xe0,0x73,0xf0,0x15,0xf8,0xf6,0x7a,0xd9,0x1f,0x90,0xab,0xe6, -0xbe,0x1b,0xb3,0xf0,0xc0,0xf9,0xf4,0x30,0x7f,0xa7,0x8d,0xd4,0x0e,0x88,0x80,0x23, -0x70,0x01,0x23,0xc0,0x48,0xa0,0x00,0x6a,0xe0,0x07,0xaa,0x2c,0x37,0x0a,0xf6,0x09, -0x82,0x3c,0xea,0xd0,0x42,0xb0,0x87,0xce,0xe3,0x75,0x41,0x84,0x47,0x0c,0xf6,0xc7, -0x81,0x3b,0xc0,0x3d,0x60,0x34,0x78,0x10,0x3c,0x02,0x9e,0x00,0xe3,0x3d,0x3e,0x14, -0x4c,0xf4,0x98,0x82,0xdc,0x74,0x30,0xdb,0xe3,0x39,0xc4,0x2f,0x80,0x97,0xc0,0xab, -0x60,0x31,0x48,0x01,0x4b,0xc0,0x72,0xb0,0xd2,0xe3,0xb7,0xce,0xf0,0x14,0x64,0x4d, -0x36,0x34,0x92,0xd6,0x70,0xbd,0xf8,0x8a,0x22,0x2c,0xfe,0x8c,0x73,0x7e,0xdf,0xc8, -0x0d,0x1e,0x43,0x86,0xe6,0x7a,0xfc,0xfc,0xc8,0x26,0x8f,0x9b,0xd7,0x61,0x45,0x1e, -0xc5,0x1e,0x25,0x1e,0x65,0x1e,0x95,0x1e,0x55,0x1e,0x75,0x1e,0x4d,0x1e,0x2d,0x1e, -0xad,0x1e,0x6f,0x78,0xb4,0x7b,0x74,0x7a,0xbc,0xe5,0xf1,0x9e,0xc7,0x19,0x8f,0x0b, -0x1e,0x3d,0x1e,0x97,0x3c,0x2e,0x7b,0x5c,0xf1,0xb8,0xea,0x71,0xcd,0xc3,0xe8,0xc1, -0x93,0xf3,0xe5,0x36,0x72,0xa1,0x5c,0x22,0x77,0x96,0x0f,0x97,0xcb,0xe4,0x72,0xb9, -0x52,0xee,0x23,0x0f,0x90,0x6b,0xe5,0x3a,0x79,0xa4,0x5c,0x2f,0x8f,0x97,0xdf,0x29, -0x1f,0x25,0x1f,0x23,0x1f,0x2b,0x7f,0x54,0x3e,0x4e,0xfe,0x94,0x7c,0x92,0x7c,0xaa, -0x7c,0x86,0x7c,0x8e,0x7c,0xbe,0x7c,0xa1,0xfc,0x15,0x79,0x82,0x3c,0x49,0x9e,0x26, -0xcf,0x90,0x67,0xc9,0x57,0xcb,0xd7,0xcb,0x73,0xe4,0x05,0xf2,0x22,0x79,0xb1,0xbc, -0x44,0x5e,0x26,0xaf,0x94,0x57,0xc9,0xeb,0xe4,0x4d,0xf2,0x16,0x79,0xab,0xfc,0x0d, -0x79,0xbb,0xbc,0x53,0xfe,0x96,0xfc,0x3d,0xf9,0x19,0xf9,0x05,0x79,0x8f,0x3c,0x55, -0x72,0x49,0x7e,0x59,0x7e,0x45,0x7e,0x55,0x3e,0x1e,0xf3,0xec,0x6b,0xf2,0x6d,0x12, -0xa3,0x9c,0xe7,0xc9,0xf7,0xb4,0xf1,0x14,0x7a,0x4a,0x3c,0x9d,0x3d,0x87,0x7b,0xca, -0x3c,0xe5,0x9e,0x4a,0x4f,0x1f,0xcf,0x00,0x4f,0xad,0xa7,0xce,0x33,0xd2,0x53,0xef, -0x19,0xef,0x79,0xa7,0xe7,0x28,0xcf,0x31,0x9e,0x63,0x3d,0x1f,0xf5,0x1c,0xe7,0xf9, -0x94,0xe7,0x24,0xcf,0xa9,0x9e,0x33,0x3c,0xe7,0x78,0xce,0xf7,0x5c,0xe8,0xf9,0x8a, -0x67,0x82,0x67,0x92,0x67,0x9a,0x67,0x86,0x67,0x96,0xe7,0x6a,0xcf,0xf5,0x9e,0x39, -0x9e,0x05,0x9e,0xfd,0xe2,0x22,0xcf,0x62,0xcf,0x12,0xcf,0x32,0xcf,0x4a,0xcf,0x2a, -0xcf,0x3a,0xcf,0x26,0xcf,0x16,0xcf,0x56,0xcf,0x37,0x3c,0x3d,0x1c,0xda,0x3d,0x3b, -0x3d,0xdf,0xf2,0x7c,0xcf,0xf3,0x8c,0xe7,0x05,0xcf,0x1e,0xcf,0x4b,0x9e,0x97,0x3d, -0xaf,0x78,0x5e,0xf5,0xbc,0xe6,0x69,0xf4,0xe4,0x29,0xf8,0x0a,0x1b,0x85,0x50,0x21, -0x51,0x38,0x2b,0x86,0x2b,0x64,0x0a,0xb9,0x42,0xa9,0xf0,0x51,0x04,0x28,0xb4,0x0a, -0x9d,0x42,0xee,0x19,0xa9,0xd0,0x2b,0xe2,0x15,0x77,0x2a,0x46,0x29,0xc6,0x28,0xc6, -0x2a,0x1e,0x55,0x8c,0x53,0x3c,0xa5,0x98,0xa4,0x98,0xaa,0x98,0xa1,0x98,0xa3,0x98, -0xaf,0x58,0xa8,0x78,0x45,0x91,0xa0,0x48,0x52,0xa4,0x29,0x32,0x25,0x19,0x8a,0x2c, -0xc5,0x6a,0xc5,0x7a,0x45,0x8e,0xa2,0x40,0x51,0xa4,0x28,0x56,0x94,0x28,0xca,0x14, -0x95,0x8a,0x2a,0x45,0x9d,0xa2,0x49,0xd1,0xa2,0xd8,0x2c,0x6a,0x55,0xbc,0xa1,0x68, -0x57,0x74,0x2a,0xde,0x52,0xbc,0xa7,0x38,0xa3,0xb8,0xa0,0x78,0x44,0xd4,0xa3,0xb8, -0xa4,0xb8,0xac,0xb8,0xa2,0xb8,0xaa,0xb8,0xa6,0x30,0x2a,0x78,0x5e,0x7c,0x2f,0x1b, -0x2f,0xa1,0x97,0xc4,0xcb,0xd9,0x6b,0xb8,0x97,0xcc,0x4b,0xee,0xa5,0xf4,0xf2,0xf1, -0x0a,0xf0,0xd2,0x7a,0xe9,0xbc,0x22,0xbd,0x92,0x14,0x7a,0xaf,0x78,0xaf,0x3b,0xbd, -0x46,0x79,0x8d,0xf1,0x1a,0xeb,0xf5,0xa8,0xd7,0x38,0xaf,0x78,0xc5,0x53,0x5e,0x93, -0xbc,0xa6,0x7a,0xcd,0xf0,0x9a,0xe3,0x35,0xdf,0x6b,0xa1,0xd7,0x2b,0x5e,0x09,0x5e, -0x49,0x5e,0x69,0x5e,0x19,0x5e,0x59,0x5e,0xab,0xbd,0xd6,0x7b,0xe5,0x78,0x15,0x78, -0x15,0x79,0x15,0x7b,0x95,0x78,0xc9,0x3d,0xcb,0xbc,0x2a,0xbd,0xaa,0xbc,0xea,0xbc, -0x9e,0x70,0x68,0xf2,0x6a,0xf1,0x6a,0xf5,0x7a,0xc3,0xab,0xdd,0xab,0xd3,0xeb,0x2d, -0xaf,0xf7,0xbc,0xce,0x78,0x5d,0xf0,0xea,0xf1,0xba,0xe4,0x35,0x4a,0x7a,0xd9,0xeb, -0x8a,0xd7,0x55,0xaf,0x6b,0x5e,0x46,0x2f,0x9e,0x92,0xaf,0xb4,0x51,0x0a,0x95,0xa3, -0x14,0x12,0xa5,0xb3,0x72,0xb8,0x52,0xa6,0x94,0x2b,0x95,0x4a,0x1f,0x65,0x80,0x52, -0xab,0xd4,0x29,0x23,0x95,0x7a,0x65,0xbc,0x72,0xb3,0xe4,0x4e,0xe5,0x28,0xe5,0x18, -0xe5,0x58,0xe5,0xa3,0xca,0x71,0xca,0xa7,0x94,0x93,0x94,0x53,0x95,0x33,0x94,0x73, -0x94,0xf3,0x95,0x0b,0x95,0x1f,0x8a,0x5f,0x51,0x26,0x28,0x93,0x94,0x69,0xca,0x0c, -0x65,0x96,0x72,0xb5,0x72,0xbd,0x32,0x47,0x59,0xa0,0x2c,0x52,0x16,0x2b,0x4b,0x94, -0x65,0xca,0x4a,0x65,0x95,0xf2,0x1e,0x49,0x9d,0xf2,0x11,0x49,0x93,0xb2,0x45,0xd9, -0xaa,0x64,0xc7,0xf1,0x1b,0x88,0xdb,0xb9,0x5c,0xa7,0xf2,0x2d,0xe5,0x7b,0xca,0x33, -0xca,0x0b,0xca,0x1e,0xe5,0x25,0xe5,0x65,0xe5,0x15,0xe5,0x77,0x62,0xa3,0xf1,0x2a, -0x8e,0x5d,0xe3,0x8e,0x1b,0x95,0x3c,0x95,0xf9,0x4d,0xbe,0xca,0x46,0x25,0x54,0x49, -0x54,0xce,0xaa,0xe1,0x2a,0x99,0x4a,0xae,0x52,0xaa,0x7c,0x54,0x01,0x2a,0xad,0x4a, -0xa7,0x8a,0x54,0xe9,0x55,0xf1,0xaa,0x3b,0x55,0xa3,0x54,0x8d,0xa2,0x31,0xaa,0xb1, -0xaa,0x47,0x55,0xe3,0x54,0x4f,0xa9,0x26,0xa9,0xa6,0xaa,0x66,0xa8,0xe6,0xa8,0xe6, -0xab,0x16,0xaa,0x5e,0x51,0x25,0xa8,0x92,0x54,0x69,0xaa,0xa7,0xa4,0x19,0xaa,0x2c, -0xd5,0x6a,0xd5,0x7a,0xd5,0x1c,0x69,0x8e,0xaa,0x40,0x55,0xa4,0x2a,0x56,0x95,0xa8, -0x24,0x5e,0x65,0xaa,0x4a,0x55,0x95,0xaa,0x4e,0xd5,0xa4,0x6a,0x41,0x68,0x55,0xbd, -0xa1,0x6a,0x57,0x75,0xaa,0xde,0x52,0xbd,0xa7,0x3a,0xa3,0xba,0xa0,0x32,0x2a,0x7b, -0x54,0x97,0x54,0x97,0x55,0x57,0x54,0x57,0x55,0xdf,0xab,0xb8,0xef,0x62,0xd4,0x56, -0x6a,0x81,0xda,0x56,0x3d,0x54,0xed,0xa0,0x96,0xaa,0x5d,0xd5,0x3a,0x95,0xbb,0xda, -0x53,0xad,0x52,0xbf,0xa1,0xf4,0x55,0x07,0xaa,0x83,0xd5,0x61,0xea,0x28,0xb5,0x41, -0x7d,0x9b,0xfa,0x2e,0xf5,0xbd,0xea,0xfb,0xd5,0x0f,0xa9,0x1f,0x53,0x3f,0xaa,0xfa, -0x87,0x7a,0x9c,0xea,0x69,0xf5,0x64,0xf5,0xb3,0xea,0x99,0xea,0xb9,0xea,0x76,0xe5, -0x42,0xcf,0xe7,0xd5,0x2f,0xaa,0xe3,0xc4,0x69,0x8a,0x4e,0xaf,0x45,0x6a,0x46,0xbd, -0x50,0x95,0xac,0x7e,0x45,0x95,0xae,0x5e,0xa6,0x5e,0xa1,0x7e,0x4b,0xb9,0x46,0xbd, -0x41,0x9d,0xab,0xde,0xa4,0xde,0xa2,0x7e,0x4f,0xb9,0x5d,0xbd,0x4b,0xbd,0x47,0xbd, -0x57,0x5d,0xad,0xae,0x57,0x97,0xa8,0x9a,0xd5,0x07,0xd4,0x12,0xaf,0xc3,0xea,0x3a, -0xd5,0x51,0xf5,0x71,0xf5,0x49,0xf5,0xdb,0xea,0xf7,0xd5,0xed,0xaa,0xb3,0xea,0x6b, -0xca,0x8f,0xd4,0x9d,0xaa,0x48,0x45,0xaf,0xfa,0x2d,0xd5,0xc7,0xea,0x33,0xaa,0xcf, -0xd4,0x5f,0xaa,0xbf,0x51,0x7f,0xaf,0x26,0xef,0x1e,0xd5,0x65,0xa5,0x95,0xf7,0x25, -0x95,0xc0,0xfb,0xb2,0xca,0xd6,0x7b,0xbc,0xc3,0x50,0x6f,0x47,0xef,0x61,0xde,0x32, -0x6f,0xb9,0xb7,0xd2,0xdb,0xc7,0x3b,0xd0,0x3b,0xc4,0x3b,0xc2,0x3b,0xc6,0xfb,0xcf, -0x5c,0xff,0xc6,0x79,0xdf,0xee,0x7d,0x97,0xf7,0x28,0xef,0x31,0xde,0x63,0x11,0x7e, -0xa9,0xd4,0x23,0xde,0xe3,0xbc,0x9f,0xf6,0x7e,0xc6,0x7b,0xfa,0x4d,0x25,0xe6,0x78, -0x63,0x1d,0xea,0xfd,0x92,0xf7,0x22,0xbb,0x14,0xbb,0x45,0xde,0x09,0xde,0x89,0xde, -0x29,0xde,0xe9,0xde,0x19,0xde,0xb7,0xd9,0x65,0x7a,0xaf,0xf6,0xde,0xe0,0x5d,0xe0, -0xbd,0xcd,0xbb,0xc4,0x7b,0x8f,0xf7,0x3e,0xef,0x5a,0xef,0x26,0xef,0x03,0xde,0x6d, -0xde,0xc7,0x50,0xbb,0xd3,0xfb,0x6d,0xef,0x0f,0xbc,0xcf,0x7b,0xf7,0x20,0xff,0x31, -0xf8,0xdc,0xfb,0x6b,0xc4,0xd7,0xbc,0xc9,0xa7,0xdf,0x68,0xed,0x33,0xc4,0x47,0xe8, -0xe3,0xe0,0xe3,0xe2,0xe3,0xe6,0x23,0xf7,0x51,0xf9,0xf8,0xf9,0x68,0x7c,0x74,0x08, -0x11,0xe6,0x10,0x6d,0x0e,0x06,0x73,0x88,0x37,0x87,0x3b,0xcc,0xe1,0x6e,0x73,0xb8, -0xd7,0x1c,0xc6,0x98,0xc3,0x83,0xe6,0xf0,0xb0,0x39,0x3c,0x66,0x0e,0xe3,0xcc,0x61, -0x3c,0xc2,0x04,0x84,0xc9,0x08,0x53,0x11,0xa6,0x23,0xcc,0x42,0x98,0x6b,0x0e,0xf3, -0xcd,0x61,0x81,0x39,0xbc,0x64,0x0e,0x8b,0x10,0x12,0xcc,0x21,0x11,0x21,0xc5,0x1c, -0xd2,0xcd,0x21,0x03,0x21,0x13,0xe1,0x8f,0x3f,0x6d,0x56,0xfa,0x98,0xc2,0x1a,0x84, -0xf5,0x08,0xd9,0x08,0x1f,0x58,0xe7,0xf9,0xe4,0xf9,0x6c,0x42,0x28,0x42,0xd8,0x66, -0x0e,0x3b,0x10,0x76,0x21,0x94,0x23,0xec,0x47,0xa8,0x43,0x68,0x46,0x38,0x88,0x70, -0x84,0x0b,0xed,0x5c,0x38,0x69,0x0e,0x6f,0xf9,0xbc,0xef,0x73,0x0e,0xdb,0xdd,0x3e, -0x97,0x7c,0x3e,0xf3,0xf9,0xca,0xe7,0x3b,0x1f,0xa3,0x8f,0x95,0xef,0x60,0x5f,0x7b, -0x5f,0x89,0xaf,0xd4,0x77,0x84,0xaf,0x87,0xaf,0xd2,0xd7,0xd7,0x37,0xc8,0x37,0xd4, -0x37,0xd2,0xd7,0xe0,0x7b,0xbb,0xef,0x3d,0xbe,0x63,0x7c,0x1f,0xf2,0x7d,0xdc,0x77, -0xbc,0xef,0x24,0xdf,0x67,0x7d,0x67,0xf9,0xce,0xf3,0x5d,0xe8,0xbb,0xc8,0x77,0xb1, -0x6f,0xaa,0x6f,0x86,0xef,0x0a,0xdf,0xb5,0xbe,0xd9,0xbe,0x05,0xbe,0x5b,0x7c,0x77, -0xf8,0xee,0xf6,0xad,0xf4,0xad,0xf6,0x6d,0xf0,0x7d,0xdd,0xb7,0xd5,0xf7,0xa8,0x6f, -0x87,0xef,0x69,0xdf,0xf7,0x7c,0xcf,0xfa,0x76,0xf9,0x5e,0xf4,0xbd,0xec,0xfb,0xa5, -0xef,0xb7,0xbe,0xfd,0xbe,0x3c,0x3f,0x81,0x9f,0x9d,0x9f,0xd8,0xcf,0xd9,0xcf,0xd5, -0x6f,0xa4,0x9f,0x97,0x9f,0x8f,0x5f,0xa0,0x5f,0x88,0x5f,0x84,0x9f,0xde,0xef,0x36, -0xbf,0xbb,0xfd,0x46,0xfb,0x8d,0xf5,0x7b,0xcc,0xef,0x49,0xbf,0x89,0x7e,0x53,0xfd, -0x66,0xfa,0x3d,0xe7,0xb7,0xc0,0xef,0x15,0x3f,0xc6,0x2f,0xc5,0x6f,0xa9,0x5f,0x96, -0xdf,0x1a,0xbf,0x8d,0x7e,0xf9,0x7e,0x45,0x7e,0xdb,0xfd,0x76,0xfb,0xed,0xf5,0xab, -0xf5,0x6b,0xf6,0x3b,0xe4,0x77,0xd4,0xaf,0xc3,0xef,0x9c,0xcf,0x69,0x3f,0xb6,0x27, -0xef,0xf9,0x9d,0xf5,0xfb,0xce,0xa7,0xcb,0x8f,0xed,0xc9,0x45,0xbf,0xcb,0x7e,0x52, -0xdf,0x2f,0xfd,0xd8,0x9e,0x7c,0xeb,0xd7,0xef,0xe7,0xeb,0xcb,0xf3,0x67,0x7b,0xc3, -0x5a,0x65,0xb2,0x68,0xc0,0x16,0x93,0x15,0x02,0xff,0x08,0x3f,0x3b,0x7f,0xb1,0xff, -0x63,0x7e,0xce,0xfe,0xac,0x7a,0x91,0x9f,0xab,0xff,0x48,0xff,0xa5,0x7e,0x5e,0xfe, -0xac,0x2e,0xeb,0x2d,0x1f,0xff,0x73,0x3e,0x81,0xfe,0x03,0xde,0x0a,0xf1,0x1f,0xf0, -0x55,0x84,0xbf,0xef,0x4d,0x3e,0xba,0xd9,0x43,0x7a,0xff,0x9b,0x7d,0xf4,0x73,0x0f, -0xb1,0xde,0xb9,0xe1,0x97,0x01,0x9f,0xdc,0xe6,0x3f,0xe0,0x91,0x01,0x6f,0xdc,0xed, -0xcf,0xfa,0x62,0xb4,0xff,0x80,0x27,0xc6,0x72,0x96,0xb0,0x36,0x98,0xd4,0x1f,0xf3, -0x9f,0xe5,0xfb,0xa4,0xff,0x44,0xff,0xa9,0xfe,0x6c,0x3b,0xae,0x5c,0x0d,0xb6,0xd4, -0x4c,0xff,0xf9,0xfe,0x2f,0xfb,0x2f,0xf6,0x4f,0xf5,0xcf,0xf0,0x5f,0xe1,0xbf,0xd6, -0x3f,0xdb,0xbf,0xc0,0x7f,0x8b,0xff,0x0e,0xff,0xdd,0xfe,0x95,0xfe,0xd5,0xfe,0x0d, -0xfe,0xaf,0xfb,0xb7,0xfa,0x1f,0xf5,0xef,0xf0,0x3f,0xed,0xff,0x9e,0xff,0x59,0xff, -0x2e,0xff,0x8b,0xfe,0x97,0xd1,0xca,0x97,0xfe,0xdf,0xfa,0xf7,0xfb,0xf3,0x02,0x7e, -0x6f,0xbd,0x81,0xed,0x27,0x61,0xcf,0x5a,0xb3,0x37,0x4c,0xfb,0xd8,0x51,0x22,0x08, -0x10,0x04,0xfc,0xa6,0xf5,0x41,0x80,0x03,0xc2,0xf0,0x00,0x8f,0x00,0x75,0x40,0x60, -0x80,0x2e,0x20,0x06,0xe1,0xf6,0x80,0x7b,0x03,0xc6,0x06,0x3c,0x11,0x30,0x21,0xe0, -0x59,0x84,0x39,0x01,0x0b,0x10,0x5e,0x45,0x48,0x0e,0xc8,0x40,0x58,0x15,0xb0,0x11, -0x61,0x13,0x42,0x71,0xc0,0x6e,0x84,0x7d,0x08,0xf5,0x01,0x2d,0x01,0x47,0x02,0x3a, -0x10,0xde,0x0e,0x38,0x13,0xd0,0x1d,0xf0,0x49,0xc0,0x97,0x08,0xd7,0x02,0x2c,0x03, -0x07,0x07,0x0e,0x0d,0x74,0x0e,0xc4,0xd2,0x31,0x50,0x81,0xe0,0x8b,0xa0,0x0d,0x8c, -0x08,0x8c,0x0d,0xbc,0x2b,0x70,0x4c,0xe0,0x23,0x81,0x4f,0x06,0xb2,0x36,0x4c,0x0e, -0x9c,0x11,0x38,0x2f,0xf0,0xa5,0x40,0x26,0x30,0x0d,0x21,0x33,0x70,0x6d,0x60,0x6e, -0x60,0x11,0xc2,0xce,0xc0,0xf2,0xc0,0xea,0xc0,0xa6,0xc0,0x43,0x81,0x6f,0x06,0x9e, -0x0c,0x7c,0x2f,0xf0,0x7c,0x60,0x5f,0xe0,0x67,0x81,0x57,0x03,0xfb,0x03,0xad,0x83, -0x6c,0x83,0x24,0x41,0xc3,0x82,0x46,0x06,0xa9,0x82,0x02,0x82,0x42,0x83,0xa2,0x83, -0xae,0x05,0x0c,0x0e,0xbc,0x2d,0x68,0x54,0xd0,0x83,0x41,0x8f,0x07,0x3d,0x1d,0x34, -0x15,0x3c,0x18,0x34,0x3b,0xe8,0x85,0xa0,0x45,0x41,0x49,0x41,0x4b,0xb1,0x7d,0x04, -0xd6,0xaf,0x0c,0xda,0x10,0xf4,0xfb,0xbf,0x09,0xbd,0x75,0x28,0x08,0xda,0x16,0x54, -0x1a,0xb4,0x3f,0xa8,0x29,0xe8,0x70,0x50,0x47,0xd0,0xbb,0x41,0x17,0x82,0x3e,0x0e, -0xba,0x12,0xe4,0xa8,0x51,0x68,0x7e,0xfa,0x9b,0x7e,0xb7,0xfe,0xf8,0x6b,0x02,0x35, -0xfd,0xc6,0x60,0x8d,0xd1,0x32,0x54,0x13,0xa6,0x89,0xd0,0xc4,0x68,0xfe,0xbd,0x6f, -0x10,0xf0,0x84,0xd1,0xdc,0xa1,0xb9,0x07,0x81,0xfd,0x7d,0x86,0x7b,0x35,0xa3,0x35, -0xf7,0x6b,0x1e,0xd2,0x3c,0xa6,0xf9,0x87,0xe6,0x69,0xcd,0x64,0x0d,0xfb,0x5d,0xf1, -0xb3,0x9a,0x99,0x9a,0xb9,0x9a,0xe7,0x39,0x7b,0x5e,0xd4,0xbc,0xac,0x71,0xb5,0x33, -0x85,0x7b,0xb8,0x5a,0x26,0x7d,0xe8,0x58,0x06,0x43,0x3f,0x54,0x13,0xf7,0xa3,0x76, -0x16,0x69,0x5e,0xd3,0x30,0x9a,0xdb,0xec,0x12,0x35,0xc9,0x9a,0x54,0xcd,0x3d,0x76, -0xfd,0xc6,0x74,0xcd,0x52,0xcd,0x32,0x4d,0xe6,0x75,0x2b,0x57,0x68,0xd6,0x68,0x36, -0xa2,0xed,0x3c,0xec,0x29,0xd4,0x6c,0xd5,0xec,0xd4,0xec,0xd6,0x54,0x6a,0xaa,0x34, -0xf5,0x9a,0x66,0xcd,0x41,0x4d,0x9b,0xe6,0x98,0xa6,0x03,0xe1,0x24,0xc2,0x5b,0x08, -0xef,0x22,0x7c,0x60,0x0e,0x67,0x11,0x2e,0x98,0x43,0x37,0x42,0x9f,0x39,0x7c,0x6c, -0x0e,0x97,0xcd,0xe1,0x0b,0x73,0xf8,0xca,0x1c,0xbe,0x41,0xb8,0x86,0xd0,0x8f,0x60, -0xa1,0xb5,0xd0,0x5a,0x99,0x03,0xdf,0x1c,0x86,0x98,0x83,0x9d,0x39,0x0c,0x35,0x07, -0x89,0x39,0x38,0x99,0x83,0x8b,0x39,0xb8,0x9a,0x83,0xcc,0x1c,0x3c,0xcc,0x41,0x61, -0x0e,0x2a,0x73,0xf0,0x31,0x07,0x7f,0x73,0x08,0x42,0x60,0x9f,0x06,0xc1,0x5a,0x53, -0xd0,0x21,0x44,0x21,0xc4,0x22,0xdc,0x81,0x60,0xfa,0x4d,0x95,0x7e,0x63,0xa8,0x66, -0x94,0x76,0x11,0xe7,0xb5,0xd7,0x34,0xf7,0x69,0x59,0xef,0xb2,0x1e,0xf5,0xd7,0x24, -0x6a,0xa6,0x38,0x8c,0xd1,0xde,0xea,0xf7,0x53,0xd8,0xd1,0x90,0x0c,0x6f,0xa7,0xe2, -0x8c,0x64,0x6a,0x7e,0xcf,0x37,0xd4,0x2f,0x6a,0xd2,0x71,0xa6,0x1f,0xd0,0xde,0xa3, -0x79,0xc3,0xf6,0xf7,0xd4,0xbf,0x57,0x33,0x56,0x3b,0x5a,0xf3,0xb0,0xf6,0x51,0xed, -0x38,0xed,0x14,0x07,0x76,0x04,0x05,0x6a,0x9e,0xd2,0x7e,0xeb,0x32,0x49,0x3b,0x55, -0x3b,0x43,0x3b,0x47,0x3b,0x5f,0xbb,0x50,0xfb,0x8a,0x36,0x41,0x9b,0xa4,0x4d,0xd3, -0xfe,0x55,0x6f,0xd0,0x32,0xb4,0x59,0xda,0xd5,0x5a,0xa2,0x3f,0xf2,0x7e,0xd9,0x34, -0x46,0x6f,0x7e,0xcb,0xcc,0x6e,0xdf,0xfc,0xa6,0x99,0xdd,0xbe,0xf9,0x6d,0x33,0xbb, -0x6d,0x7a,0xe3,0x6c,0xaa,0xbb,0x5e,0x9b,0xad,0xcd,0xd3,0x46,0xd2,0x26,0x6d,0x91, -0x76,0x1b,0xce,0xe9,0x4e,0xed,0x6e,0x6d,0x85,0x76,0xbf,0xb6,0x56,0xdb,0xa8,0x7d, -0x5d,0xfb,0xeb,0xf7,0x87,0x43,0xda,0x37,0xb4,0xc7,0xb5,0xa7,0xb4,0xef,0x6a,0xcf, -0x68,0x3f,0xd2,0xf6,0x69,0x3f,0xd5,0x5e,0xd1,0x7e,0xa3,0xfd,0x41,0x6b,0x19,0xcc, -0x0f,0xb6,0x0d,0x16,0x05,0x3b,0x05,0x0f,0x0f,0x76,0x0f,0x56,0x04,0x7b,0x07,0x07, -0x04,0x07,0x07,0x87,0x07,0xc7,0x04,0xc7,0x07,0xdf,0x15,0x7c,0x5f,0xf0,0x83,0xc1, -0x8f,0x06,0xff,0x23,0x78,0x42,0xf0,0x94,0xe0,0x19,0xc1,0x73,0x83,0x5f,0x08,0x7e, -0x39,0x38,0x21,0x38,0x39,0x78,0x49,0xf0,0x7f,0xfa,0xf7,0xa9,0x7f,0xed,0x3b,0xd0, -0xcc,0xe0,0xd5,0xc1,0x1b,0x82,0xf3,0x82,0x37,0x07,0x17,0x07,0xef,0x0a,0x2e,0x0f, -0xde,0x1f,0x5c,0x17,0xdc,0x1c,0x7c,0x30,0xf8,0x48,0x70,0x7b,0xf0,0xc9,0xe0,0x77, -0x82,0x3f,0x0c,0xbe,0x10,0xdc,0x1b,0xfc,0x49,0xf0,0x17,0xc1,0x57,0x83,0xbf,0x0f, -0xb6,0x08,0x19,0x14,0x62,0x13,0x32,0x34,0xc4,0x31,0x64,0x58,0x88,0x2c,0xc4,0x33, -0x44,0x1d,0xe2,0x1f,0xa2,0x0d,0x09,0x0b,0x89,0x0e,0xf9,0xb3,0xbf,0xa5,0xf8,0xab, -0xda,0xfb,0xe9,0xdd,0x39,0x2e,0xe4,0xce,0x90,0x7b,0x43,0x1e,0x08,0x79,0x24,0x64, -0x5c,0xc8,0xd3,0x21,0xcf,0x84,0x4c,0x0f,0x99,0x13,0xf2,0x3c,0x7a,0xf3,0x52,0xc8, -0x6b,0x21,0x49,0x21,0xe9,0x21,0xcb,0x43,0x56,0x85,0xac,0x0f,0xc9,0x0d,0x29,0x0c, -0xd9,0x16,0x52,0x12,0xb2,0x27,0x64,0x5f,0x48,0x6d,0x48,0x13,0x8e,0x1f,0x08,0x69, -0x0b,0x39,0x16,0xd2,0x19,0xf2,0x76,0xc8,0x07,0x21,0xe7,0xb1,0xdd,0x13,0xf2,0x71, -0x48,0xff,0xaf,0x7e,0x1f,0xfc,0xdb,0x8e,0xf7,0xff,0xe8,0x37,0xf6,0x3e,0x0f,0xf9, -0x32,0xe4,0x79,0xba,0x1a,0x92,0x60,0xd1,0x6f,0xfc,0x2e,0xe4,0x87,0x10,0x8b,0x50, -0xab,0x50,0xf6,0x6f,0xe0,0xf9,0xa1,0x36,0xa1,0xf6,0xa1,0xa2,0xd0,0xd9,0x1e,0x0e, -0xa1,0x45,0x16,0xce,0xa1,0x5f,0xd1,0xb0,0xd0,0x11,0xa1,0xee,0xa1,0xf2,0x50,0xaf, -0xd0,0x20,0x0f,0x75,0xa8,0x7f,0xa8,0x26,0x34,0x24,0x34,0x22,0x34,0x3a,0xb4,0x98, -0xe2,0x42,0x6f,0x0f,0x1d,0x49,0x77,0x85,0x8e,0x0a,0x15,0x0d,0xbd,0x3f,0xf4,0x80, -0xc5,0xd8,0xd0,0x47,0x42,0x1f,0x0f,0x7d,0x32,0xf4,0xb8,0xc5,0xd3,0xa1,0xfd,0xc6, -0xc9,0xa1,0x53,0x43,0xa7,0x87,0xce,0x0a,0x9d,0x1b,0x3a,0x3f,0x74,0x41,0xe8,0x4b, -0xa1,0xaf,0x85,0xde,0xf0,0x50,0x52,0x68,0x7a,0xe8,0xf2,0xd0,0x55,0xa1,0xeb,0x43, -0x73,0x43,0x0b,0x43,0xb7,0x85,0x96,0x84,0xee,0x09,0xdd,0x17,0x5a,0x1b,0xda,0x14, -0x7a,0x20,0xb4,0x2d,0xf4,0x58,0x68,0x67,0xe8,0xdb,0xa1,0x1f,0x84,0x9e,0x0f,0xed, -0x09,0xfd,0x38,0xf4,0xf3,0xd0,0xaf,0x43,0xaf,0x85,0x92,0xce,0x5a,0x37,0x44,0x27, -0xd4,0x39,0xe8,0x5c,0x74,0x6e,0x3a,0xb9,0x4e,0xa5,0xf3,0xd3,0x69,0x74,0x3a,0x5d, -0x94,0x2e,0x56,0x77,0x87,0x6e,0x94,0xee,0x7e,0xdd,0xc3,0xba,0x27,0x74,0x4f,0xe9, -0x26,0xeb,0xa6,0xe9,0x66,0xeb,0xe6,0xeb,0x5e,0xd4,0xbd,0xaa,0xfb,0xfd,0xdf,0xc0, -0x27,0xea,0xd2,0x74,0xcb,0x74,0x2b,0x75,0xeb,0x74,0x39,0xba,0x4d,0xba,0xad,0xba, -0x9d,0xba,0x32,0xdd,0x5e,0x5d,0x8d,0xae,0x51,0xd7,0xa2,0x3b,0xac,0x7b,0x53,0x77, -0x42,0xf7,0x96,0xee,0x7d,0xdd,0x39,0x5d,0xb7,0xee,0x92,0xee,0xf7,0x8c,0xa8,0x3f, -0x3a,0xbf,0xf8,0x4c,0xf7,0x95,0xee,0x3b,0x9d,0x51,0x67,0x15,0x36,0x38,0xcc,0x3e, -0x4c,0x12,0x26,0x0d,0x1b,0x11,0xe6,0x11,0xa6,0x0c,0xf3,0x0d,0x0b,0x0a,0x0b,0x0d, -0x8b,0x0c,0x33,0x84,0xdd,0x1e,0x76,0x4f,0xd8,0x98,0xb0,0x87,0xc2,0x1e,0x0f,0x1b, -0x1f,0x36,0x29,0xec,0xd9,0xb0,0x59,0x61,0xf3,0xc2,0x16,0x86,0x2d,0x0a,0x5b,0x1c, -0x96,0x1a,0x96,0x11,0xb6,0x22,0x6c,0x6d,0x58,0x76,0x58,0x41,0xd8,0x96,0xb0,0x1d, -0x61,0xbb,0xc3,0x2a,0xc3,0xaa,0xc3,0x1a,0xc2,0x5e,0x0f,0x6b,0x0d,0x3b,0x1a,0xd6, -0x11,0x76,0x3a,0xec,0xbd,0xb0,0xb3,0x61,0x5d,0x61,0x17,0xc3,0x2e,0x87,0x7d,0x19, -0xf6,0x6d,0x58,0x7f,0x18,0x2f,0x5c,0x10,0x6e,0x17,0x2e,0x0e,0x77,0x0e,0x77,0x0d, -0x1f,0x19,0xee,0x15,0xee,0x13,0xfe,0x3f,0xf7,0x97,0x1c,0xa6,0x10,0x18,0x1e,0x12, -0x1e,0x11,0xae,0x0f,0xbf,0x2d,0xfc,0xee,0xf0,0xd1,0xe1,0x63,0xc3,0x1f,0x0b,0x7f, -0x32,0x7c,0x62,0xf8,0xd4,0xf0,0x99,0xe1,0xcf,0x85,0x2f,0x08,0x7f,0x25,0x9c,0x09, -0x4f,0x09,0x5f,0x1a,0x9e,0x15,0xbe,0x26,0x7c,0x63,0x78,0x7e,0x78,0x51,0xf8,0xf6, -0xf0,0x5f,0x3b,0x47,0xbf,0x3e,0x3e,0x6e,0xde,0xff,0xf3,0xdf,0x3e,0xfd,0x73,0xfe, -0xfe,0xeb,0xd6,0x7f,0xd3,0xf0,0x7b,0x7e,0x17,0xed,0xe7,0xf3,0x87,0x1f,0xff,0xc6, -0xee,0xef,0xff,0x94,0x86,0xef,0x0f,0x6f,0x0a,0x3f,0x1a,0xfe,0x4e,0x78,0x77,0xf8, -0x95,0xf0,0xdf,0xf6,0xf7,0x2c,0xbf,0xfc,0x57,0x2d,0xff,0xc9,0x0f,0x45,0x0c,0x8e, -0x10,0x47,0xc8,0x22,0x7c,0x23,0xc2,0x23,0xfe,0xfa,0xdf,0x02,0xfa,0x57,0xe1,0x3f, -0xf5,0x3b,0x89,0x7f,0xbc,0x4e,0xbf,0xf1,0x7f,0x97,0x6d,0xfd,0x46,0xb6,0x0e,0xeb, -0x43,0x3b,0x2e,0x66,0xeb,0xb0,0xe9,0x40,0x1d,0xf6,0x9b,0x87,0x5b,0xeb,0xf4,0x1b, -0x6d,0xc0,0x8f,0x75,0xfa,0x8d,0xff,0xf3,0xbe,0xee,0x37,0xde,0xf0,0xb5,0xa9,0x3f, -0x37,0xd7,0xf9,0x69,0x7f,0x7e,0xff,0xd8,0xb9,0x59,0xe7,0x46,0x9d,0x7e,0xe3,0x08, -0x1a,0xf8,0xc6,0xe6,0xcf,0xd1,0xf9,0xbb,0xce,0xdf,0x75,0xfe,0x53,0x75,0xee,0x88, -0xb8,0x3b,0x82,0x1d,0xbb,0xbf,0xfe,0xdf,0x62,0x74,0xbc,0x1f,0xff,0xb7,0x98,0x7b, -0x23,0x7e,0xbd,0xce,0x98,0x9f,0xd4,0xb9,0x3f,0xc2,0x1f,0xe5,0x22,0xb0,0x7d,0x2f, -0x8e,0xff,0xad,0xf9,0x7f,0x4b,0x73,0x3e,0x02,0x3b,0x96,0x6e,0x35,0x77,0xfa,0xb3, -0xf7,0xfd,0x7b,0x2b,0xb9,0x5b,0xaf,0xba,0xfb,0x7f,0x56,0xf7,0xc6,0xfc,0xe2,0xe7, -0xff,0x3f,0xc8,0xf4,0xdf,0x83,0x6e,0xfd,0xbf,0x83,0x46,0x72,0xff,0x35,0x68,0xc4, -0xc8,0xb7,0xad,0x2a,0x78,0xd5,0xbc,0xcf,0xac,0x36,0x5a,0xed,0xb5,0xba,0x75,0x0b, -0x6c,0x7d,0xde,0x8f,0xea,0xb2,0xff,0x75,0x68,0x26,0xea,0x95,0xf1,0xde,0xe4,0xad, -0xb6,0xea,0x70,0xcf,0xb5,0xfa,0x2d,0xf3,0x9f,0x87,0x22,0x1e,0x8f,0x18,0x1f,0x31, -0x29,0xe2,0xd9,0x88,0x59,0x11,0xf3,0x22,0x16,0x46,0x2c,0x8a,0x58,0x1c,0x91,0x1a, -0x91,0x11,0xb1,0x22,0x62,0x6d,0x44,0x76,0x44,0x41,0xc4,0x96,0x88,0x1d,0x11,0xbb, -0x23,0x2a,0x23,0xaa,0x23,0x1a,0x22,0x5e,0x8f,0x68,0x8d,0x38,0x1a,0xd1,0x11,0x71, -0x3a,0xe2,0xbd,0x88,0xb3,0x11,0x5d,0x11,0x17,0x23,0x2e,0x47,0x7c,0x19,0xf1,0xed, -0x1f,0x9a,0xc1,0xb1,0xef,0x18,0x2f,0x6b,0xbe,0xd1,0xf4,0x1b,0x83,0xb4,0x16,0xda, -0x2f,0x34,0x43,0xb5,0xc1,0xdc,0xbb,0x3d,0xf6,0x7d,0x9e,0x95,0xd6,0x49,0xeb,0xaa, -0x1d,0xa2,0x95,0x69,0xfb,0x35,0x7c,0x2d,0xfb,0xe6,0xf1,0x2b,0xcd,0x35,0x8d,0x9d, -0x56,0xa2,0x75,0xd1,0xf6,0x47,0x2c,0xf2,0xb1,0x88,0xb4,0x8a,0xec,0x37,0xb2,0xf5, -0xfb,0x8d,0xfe,0xdc,0xbb,0x9e,0x2f,0xd8,0x77,0xb5,0xb7,0xaa,0x6f,0x1c,0xa8,0x8f, -0xd9,0x0a,0xb6,0x5c,0x7e,0xf4,0x66,0xe8,0xf2,0xf5,0xb7,0xa5,0xa6,0xfa,0x78,0x02, -0x03,0x53,0xfd,0x7e,0xe3,0x40,0x7d,0xf6,0xf8,0xcd,0xf5,0x17,0xf9,0xf4,0x1b,0x7f, -0xae,0x6f,0xb2,0xbf,0xdf,0xf8,0xaf,0xf4,0x4d,0xf6,0xe3,0xb9,0x8e,0xda,0x03,0xfd, -0x67,0xdf,0x57,0x0e,0xf4,0x9f,0xd5,0xff,0xd5,0xfe,0x5f,0xb7,0xfe,0xe7,0xfe,0xfb, -0xf7,0xea,0xf3,0x23,0x87,0x44,0xda,0x45,0x0e,0x8d,0x94,0x44,0x3a,0x45,0xba,0x44, -0xba,0x46,0xca,0x22,0x3d,0x22,0x6f,0x9c,0x9f,0xdf,0xf3,0x77,0x3e,0x8a,0x48,0x6b, -0x3c,0x21,0x4a,0x65,0x7e,0x91,0xbf,0x6f,0xcd,0x14,0x18,0xb9,0x44,0xa6,0x8d,0x0c, -0x8d,0x0c,0x8f,0x8c,0x8e,0xfc,0x5d,0x7f,0x9b,0x12,0x19,0x1f,0x79,0x47,0xe4,0x9f, -0xb3,0x92,0xb8,0x3b,0xf2,0xaf,0x5d,0x85,0xdc,0x1b,0x39,0x36,0x72,0x9a,0xcb,0x2f, -0x1f,0x1f,0x22,0x7e,0x22,0x72,0x7c,0xe4,0xc4,0x48,0x2f,0xd1,0x94,0xc8,0xe9,0x91, -0xee,0x4e,0xb3,0x23,0xe7,0x45,0x2e,0x88,0x2c,0xf1,0x7a,0x39,0xf2,0xb5,0xc8,0xc4, -0xc8,0xd4,0xc8,0xa5,0x91,0x99,0x91,0xd9,0xe2,0x55,0x91,0xeb,0x22,0xb3,0x23,0xf3, -0x23,0x37,0x47,0x6e,0x8b,0xb4,0x17,0x91,0xd3,0xce,0xc8,0x02,0xa9,0xad,0x53,0x91, -0x74,0x77,0xe4,0xcb,0x92,0x8a,0xc8,0xfd,0x91,0xb5,0x91,0x8d,0x91,0xaf,0x47,0x8e, -0x93,0x6a,0xc4,0x87,0x22,0x8f,0x44,0x1e,0x8b,0x3c,0x11,0x39,0xd0,0xfe,0xe9,0xc8, -0xb3,0x91,0x17,0x23,0xbf,0x8c,0xec,0x8f,0x14,0x44,0x89,0xa3,0x5c,0xa3,0xbc,0xa2, -0x7e,0xac,0x1f,0x18,0x15,0x1c,0xf5,0x5b,0xd7,0xcf,0x7f,0xf5,0xfa,0xfb,0xf7,0x7c, -0x6e,0x7d,0xcf,0xbf,0xa1,0x1f,0x16,0x15,0x15,0x65,0x88,0xba,0x2d,0xea,0xee,0x28, -0x99,0xea,0xbe,0xa8,0x07,0xa2,0x1e,0x8e,0x7a,0x3c,0x4a,0xae,0x7a,0x32,0x6a,0x42, -0xd4,0x33,0x51,0x4a,0xd5,0xf4,0xa8,0xd9,0x51,0xf3,0xa2,0x16,0x44,0xbd,0x12,0x95, -0x10,0x95,0x18,0x99,0x14,0x95,0x1e,0xb5,0x2c,0x6a,0x45,0xd4,0x9a,0x28,0x2b,0xf5, -0x86,0xa8,0xd1,0xa2,0xbc,0xa8,0xc2,0xa8,0xad,0x51,0x3b,0xa2,0x8e,0x44,0x96,0x46, -0x95,0x47,0x49,0xd5,0xec,0x6f,0x79,0xb8,0xaa,0xf7,0x45,0xd5,0x44,0x8d,0x55,0x34, -0x44,0x69,0x55,0xff,0x8c,0x3a,0x18,0xd5,0x16,0xf5,0x26,0x17,0x3a,0xa2,0x4e,0x47, -0xbd,0x1b,0xf5,0x61,0xd4,0xf9,0xa8,0x9e,0xa8,0x4b,0x51,0x97,0xa3,0xae,0x44,0x5d, -0x8d,0xba,0x16,0x65,0x8c,0xe2,0x45,0xf3,0xa3,0x6d,0xa2,0x85,0xd1,0x92,0x68,0x67, -0x04,0x4f,0xf5,0xf0,0x68,0x59,0xb4,0x3c,0x5a,0x19,0x1d,0xa9,0xf2,0x89,0x0e,0x88, -0xd6,0x46,0xe7,0x28,0x75,0xd1,0x91,0xd1,0xfa,0xe8,0xf8,0xe8,0x3b,0xa3,0x47,0x45, -0x8f,0x89,0x1e,0x1b,0xfd,0x68,0xf4,0x3f,0xa2,0x9f,0x8e,0x9e,0x1c,0x3d,0x25,0xf2, -0xd9,0xe8,0x99,0xd1,0x73,0xa3,0x5f,0x88,0x7e,0x39,0xfa,0xb5,0xe8,0xc4,0xe8,0xd4, -0xe8,0xa5,0xd1,0x99,0xd1,0xab,0xa2,0xd7,0x45,0x67,0x23,0xe4,0x47,0x17,0x45,0x17, -0x47,0xc7,0x2b,0x4a,0xa2,0xcb,0xa2,0xf7,0x46,0x57,0x47,0xd7,0x47,0xef,0x17,0x35, -0x47,0x1f,0x88,0x6e,0x14,0x1d,0x8e,0x3e,0x1a,0x7d,0x3c,0xfa,0x54,0xf4,0x3b,0xd1, -0x1f,0x46,0x9f,0x8f,0xee,0x8e,0xbe,0x18,0xfd,0x69,0xf4,0x17,0xd1,0x5f,0x47,0x7f, -0x17,0xdd,0x1f,0x6d,0x19,0x33,0x28,0x66,0x48,0x8c,0x30,0x46,0x12,0xe3,0x1c,0x33, -0x3c,0x66,0xbe,0xa7,0x2c,0xa6,0x5b,0xe4,0x19,0xe3,0x19,0xa3,0x8e,0xf1,0x43,0x08, -0x8a,0x09,0x89,0x89,0x88,0xd1,0xc7,0xc4,0xc7,0xdc,0x19,0x33,0x2a,0x66,0x4c,0xcc, -0xd8,0x98,0x47,0x63,0xc6,0xc5,0x3c,0x15,0x33,0x29,0x66,0x8c,0x6a,0x6a,0xcc,0xcc, -0x98,0xb9,0x31,0xcf,0xc7,0x3c,0xa4,0x7e,0x3e,0xe6,0xc5,0x98,0x47,0x55,0x8b,0x62, -0x98,0x98,0xe4,0x98,0xf4,0x98,0x71,0x2a,0xbe,0xe7,0xb2,0x98,0x15,0x31,0x6b,0x62, -0x36,0xc4,0xe4,0xc6,0x6c,0x8a,0xd9,0x12,0xb3,0x23,0xa6,0x34,0xa6,0x3c,0x66,0x5f, -0x4c,0x4d,0x4c,0x43,0xcc,0xeb,0x31,0x87,0x62,0x8e,0xc4,0x1c,0x8b,0x39,0x11,0x73, -0x3a,0xe6,0xdd,0x98,0x0f,0x63,0xce,0xc7,0x3c,0xa5,0xea,0x8e,0xb9,0x18,0x73,0x39, -0xe6,0x4a,0xcc,0xd5,0x98,0x6b,0x31,0x53,0x55,0xc6,0x18,0x9e,0x9e,0xaf,0xb7,0xd1, -0x0b,0xf5,0x12,0xbd,0xb3,0x7e,0xb8,0x9e,0xfd,0x5d,0x14,0x99,0x5e,0xae,0x57,0xea, -0x7d,0xf4,0x81,0xfa,0x60,0x7d,0x98,0x3e,0x4a,0x3f,0x43,0x65,0xd0,0xdf,0xae,0xbf, -0x5b,0x7f,0x9f,0x5e,0xe6,0xfd,0x80,0xfe,0x61,0xfd,0xe3,0xfa,0x27,0xf5,0x13,0xf4, -0x53,0xf4,0xd3,0xf5,0xb3,0xf5,0xf3,0xf4,0x0b,0xf5,0xaf,0xe8,0x13,0xf4,0x49,0xfa, -0x34,0x45,0x9a,0x3e,0x43,0xbf,0x42,0xbf,0x56,0x9f,0xad,0xcf,0xd7,0x17,0xe9,0x8b, -0xf5,0x25,0xfa,0x32,0x7d,0xa5,0x7e,0x8e,0xaa,0xd3,0xab,0x4a,0x5f,0xa7,0x6f,0xd2, -0xb7,0xe8,0x0f,0xeb,0x8f,0xea,0x8f,0xeb,0x4f,0xea,0x19,0xf5,0xdb,0xfa,0xf7,0xf5, -0xe7,0xf4,0x5d,0xfa,0x3e,0xfd,0xa7,0xfa,0x2b,0xfa,0xab,0xfa,0x64,0xf5,0x35,0xbd, -0x51,0xcf,0x33,0xf0,0x0d,0x36,0x06,0xa1,0x41,0x62,0x90,0x1a,0x5c,0x0d,0x23,0x0d, -0x0a,0x83,0xb7,0x61,0x99,0xda,0xdf,0xa0,0x31,0xe8,0x0c,0x91,0x06,0xbd,0xe1,0x36, -0xc3,0xdd,0x86,0xfb,0x0c,0x0f,0x18,0x1e,0x36,0x3c,0x8e,0xf0,0xa4,0x61,0x82,0x61, -0x8d,0xfa,0x19,0xc3,0x34,0xc3,0x2c,0xc3,0x73,0x86,0x17,0x0c,0x2f,0x1b,0x5e,0x33, -0x8c,0x51,0x24,0x19,0xd2,0x0d,0xcb,0x0c,0x2b,0x0d,0xeb,0x0c,0x39,0x86,0x02,0xc3, -0x2e,0x75,0x91,0x61,0xbb,0xa1,0xd4,0x50,0x61,0xa8,0x32,0xd4,0x21,0xec,0x51,0x2b, -0xbd,0x9b,0x0c,0x2d,0x86,0x56,0xc3,0x1b,0x86,0xe3,0x86,0x3a,0xcf,0x6a,0xf5,0x49, -0xc3,0xdb,0x86,0xf5,0xaa,0x0f,0x0c,0xe7,0x0d,0x97,0x94,0x3d,0x86,0x4b,0x86,0x22, -0xd5,0x65,0xc3,0x15,0xc3,0x55,0xc3,0xf7,0x08,0x16,0xb1,0xd6,0xb1,0x83,0x63,0xed, -0x63,0xc5,0xb1,0x4e,0xb1,0xc3,0x62,0x65,0xb1,0xf2,0x58,0x65,0xac,0x4f,0x6c,0x40, -0xac,0x36,0x36,0x2c,0x36,0x2a,0xd6,0x10,0x7b,0x5b,0xec,0x5d,0xb1,0xf7,0xc6,0xde, -0x1f,0xfb,0x70,0xec,0x13,0xb1,0xe3,0x63,0x27,0xc5,0x4e,0x8d,0x9d,0x19,0x3b,0x37, -0xb6,0x4e,0xf5,0x7c,0xec,0x4b,0xb1,0xaf,0xc5,0x26,0xc6,0xa6,0xc5,0x66,0xc4,0xae, -0x88,0x5d,0x13,0xbb,0x21,0x36,0x37,0x76,0x53,0xec,0x96,0xd8,0xed,0xb1,0xa5,0xb1, -0x15,0xb1,0x55,0xb1,0xea,0x98,0xfa,0xd8,0xe6,0xd8,0x03,0xb1,0x87,0x63,0x8f,0xc6, -0x1e,0x8f,0x3d,0x19,0xfb,0x76,0xec,0xfb,0xb1,0x67,0x63,0x3f,0x8a,0xed,0x8d,0x5d, -0xad,0xf8,0x24,0xf6,0xf3,0xd8,0xaf,0x62,0xbf,0x8d,0xfd,0x21,0xd6,0x22,0xae,0x55, -0x65,0x1d,0x37,0x38,0xce,0x2e,0x4e,0x14,0xe7,0x18,0x37,0x2c,0x4e,0x16,0xe7,0x19, -0xa7,0x8a,0xf3,0x8d,0x0b,0x8c,0x0b,0x8e,0x0b,0x8f,0x8b,0x8e,0x8b,0x8b,0xbb,0x23, -0xee,0x9e,0xb8,0x31,0x71,0x0f,0xc5,0x3d,0x16,0x57,0xec,0xf9,0x8f,0xb8,0xa7,0xe3, -0x26,0xc7,0x3d,0x1b,0x37,0x33,0x6e,0x6e,0xdc,0x49,0xf5,0xf3,0x71,0x2f,0xc6,0x2d, -0x8a,0x63,0xe2,0x92,0xe3,0xd2,0xe3,0x96,0xc5,0xad,0x88,0x1b,0x2d,0x59,0x13,0xb7, -0x31,0x2e,0x2f,0xae,0x30,0x6e,0x6b,0xdc,0x8e,0xb8,0xd2,0xb8,0x8a,0xb8,0xaa,0xb8, -0xba,0xb8,0xa6,0xb8,0x5e,0xf5,0xc7,0xea,0xe9,0x92,0x96,0xb8,0xc3,0x71,0x47,0xe3, -0x8e,0xc7,0x9d,0x8c,0x7b,0x3b,0xee,0x83,0xb8,0xf3,0x71,0xdd,0x71,0x17,0xe3,0x3e, -0x8d,0xbb,0x12,0xf7,0x99,0xfa,0x6a,0xdc,0xf7,0x71,0x16,0xf1,0xd6,0xf1,0x83,0xe3, -0xed,0xe2,0xc5,0xf1,0x4e,0xf1,0xc3,0xe2,0xdd,0xe2,0x3d,0xe2,0xbd,0xe2,0xbd,0xe3, -0xfd,0xe3,0xb5,0xf1,0xba,0xf8,0xc8,0x78,0x7d,0xfc,0x6d,0xf1,0x77,0xc5,0xdf,0x1b, -0x7f,0x7f,0xfc,0x43,0xf1,0x8f,0xc7,0x8f,0x8f,0x9f,0x18,0x3f,0x25,0x7e,0x7a,0xfc, -0x9c,0xf8,0xf9,0xf1,0x02,0x6f,0x81,0xf7,0x8b,0xf1,0x8b,0xe2,0x17,0xc7,0xa7,0xc4, -0x2f,0x89,0x5f,0x1e,0xbf,0x32,0x7e,0x6d,0xfc,0xc6,0xf8,0xbc,0x78,0x5b,0xef,0xcd, -0xf1,0xdb,0xe2,0x77,0xc6,0xef,0x8e,0xaf,0x88,0xdf,0x1f,0x5f,0x17,0xdf,0x14,0x7f, -0x20,0xbe,0x2d,0xde,0xdb,0xe1,0x58,0x7c,0x84,0xc3,0x89,0xf8,0xd3,0xf1,0xef,0xc6, -0x7f,0x18,0x3f,0xda,0xe1,0x7c,0xfc,0x9f,0xf1,0xfb,0x47,0x3f,0x7a,0x1b,0xc7,0xe6, -0xd2,0x64,0xd4,0x6c,0x34,0x5e,0x36,0xef,0x39,0xc3,0xc5,0x7a,0xf3,0x56,0xcf,0xcd, -0x77,0x36,0x1e,0xfd,0x68,0xaf,0xde,0x98,0x80,0x78,0x8c,0x91,0xfb,0xbf,0x42,0xcc, -0xf5,0x52,0xd7,0xd8,0xff,0x20,0x50,0xf0,0xad,0xd1,0xf8,0xc3,0xc1,0x2b,0x9f,0x36, -0x61,0xeb,0x87,0x4f,0xae,0x34,0x45,0x5a,0x50,0xbb,0x91,0xd7,0xff,0x29,0xb7,0xff, -0x93,0x2b,0x1f,0xb7,0x46,0x9f,0x96,0xb6,0x1a,0x5b,0x5a,0xa3,0x17,0xb3,0xda,0x7c, -0xe3,0x99,0x1f,0xb0,0xdf,0x78,0xe5,0x4c,0xf4,0xd3,0xba,0x76,0xb6,0x2d,0x6e,0xfb, -0x32,0xbb,0x3d,0xb7,0xdd,0x68,0x4f,0xdc,0x36,0x6b,0xdc,0x0f,0x9f,0x19,0xdb,0x91, -0x7e,0x6a,0x4c,0xf8,0x1e,0x4a,0x01,0x09,0xc9,0x4f,0x19,0x9b,0x8d,0xae,0xac,0x5d, -0x42,0xae,0x5f,0x67,0x8c,0x7c,0x2e,0x8d,0x4e,0x88,0xe6,0x2a,0x70,0x31,0xbb,0x91, -0x60,0xb6,0x2e,0xda,0x78,0x53,0x1f,0x64,0x6c,0xa7,0xcc,0x33,0x69,0xd9,0xcd,0xaf, -0x5d,0xd1,0x39,0x18,0x91,0x40,0x6c,0xb3,0xc6,0x33,0xec,0xff,0x85,0x41,0x6f,0x79, -0xa6,0xb2,0xc6,0xeb,0xff,0x47,0x49,0xcf,0xee,0x4f,0x30,0x0a,0x8d,0xc2,0xcf,0xb9, -0x4d,0x99,0xc9,0x3f,0x42,0xae,0xd5,0x56,0x73,0xa1,0x76,0x73,0xca,0x1a,0x50,0xc0, -0xb5,0xa1,0x37,0x7b,0x4f,0xc8,0xd9,0x7b,0xd3,0x47,0xf8,0x99,0x39,0xf3,0x8d,0xf1, -0xc2,0x4d,0xe7,0x07,0x8a,0x26,0xcf,0x9b,0xfe,0xcb,0x34,0x4e,0x03,0xdd,0xdc,0x74, -0x93,0x3b,0xd7,0x3c,0x25,0x98,0x3f,0xd7,0x8d,0xe3,0xde,0x51,0xdf,0xf8,0x70,0xd6, -0x9a,0x7b,0x99,0x70,0xf3,0xfb,0x58,0xe1,0xf5,0xf1,0x60,0x4a,0x65,0x46,0x9e,0xbe, -0xd9,0xdc,0x57,0xa3,0x90,0xe1,0xf6,0x34,0x19,0x5b,0xcc,0x7d,0x30,0xd5,0xd6,0x1b, -0xaf,0x98,0xfe,0x83,0x00,0x7d,0xc3,0x6e,0xbf,0xf6,0xda,0x6b,0x74,0x43,0xd9,0x54, -0x57,0xc8,0xfe,0xa7,0xe5,0x6f,0x06,0x14,0xcc,0x6f,0x81,0x2f,0x73,0x8d,0x54,0xa1, -0x8c,0xfe,0xa6,0x71,0xc8,0x4f,0xe3,0x92,0x2c,0xf6,0xa0,0xcc,0xe2,0xc6,0xfb,0x62, -0xfd,0x0d,0x8b,0xb9,0xbe,0x73,0x7f,0x01,0x2c,0x3c,0x7b,0xfd,0x1c,0xb0,0x71,0x93, -0xc9,0xe5,0xfa,0x1b,0xb5,0xe8,0x46,0xc7,0xb8,0x5e,0x63,0xbf,0x9e,0x1b,0x3e,0x4d, -0x2b,0xcd,0xc5,0xb9,0x4e,0x30,0xc6,0x81,0x37,0xd3,0xba,0x6f,0x4c,0xe2,0xc6,0x24, -0x93,0x77,0xaf,0xdb,0x85,0xf3,0xf1,0x3d,0x97,0x99,0xf3,0xd9,0x65,0xb8,0x52,0x9f, -0x86,0x91,0x61,0x71,0xf3,0x1b,0x6e,0xae,0xa1,0x6f,0x06,0xbc,0xa9,0xef,0x37,0x99, -0xcc,0x9a,0xc5,0x73,0xa3,0x7e,0x1c,0xb7,0xb8,0xf9,0xed,0x37,0xff,0x7b,0xb3,0x7d, -0xf0,0xef,0x8f,0xde,0x8c,0x9b,0x3c,0x17,0xc9,0xa3,0xef,0x4d,0x35,0xbe,0xbf,0x7e, -0x96,0x07,0xac,0xe1,0xce,0x11,0xeb,0x77,0xf6,0x90,0x7e,0xe0,0x62,0x3b,0xc3,0x27, -0x6e,0xb4,0xf2,0xae,0x5f,0xba,0x74,0xe3,0xec,0xb2,0xef,0x37,0x4d,0x57,0xa3,0xb9, -0x19,0x7c,0x12,0x1a,0xe0,0x80,0x81,0xff,0x47,0xc4,0x37,0xf2,0x4c,0xd7,0xe9,0x27, -0xd7,0x0a,0xc2,0x17,0x9f,0x6d,0x97,0xa1,0xfc,0x28,0xce,0x4f,0xc6,0xad,0x57,0x9b, -0x2c,0x06,0x99,0x94,0x2f,0xb3,0x75,0x59,0x9b,0x6f,0xf4,0x43,0xcf,0xb6,0xcc,0x43, -0x34,0xe0,0x27,0xee,0xca,0x10,0x9a,0x8e,0xf7,0xb0,0x67,0x29,0xe1,0xc7,0x6f,0xfd, -0xcd,0x7f,0xb9,0xcd,0x67,0x12,0xbe,0x98,0xc3,0xb6,0xff,0x6d,0x02,0x5d,0x37,0x89, -0xcc,0x2e,0xfe,0x5e,0x66,0xd2,0x31,0xde,0xf8,0xef,0x14,0x37,0x19,0xce,0x1d,0x33, -0xb5,0xc7,0x63,0xb5,0x7f,0x30,0x5d,0x52,0x37,0xc6,0x34,0x1a,0xe9,0xc7,0x35,0xc0, -0x75,0x37,0x61,0x2f,0x6b,0x6f,0x13,0x5b,0x26,0xe1,0xda,0x80,0x77,0x84,0x03,0x6d, -0x99,0xae,0x6f,0xae,0x81,0x56,0xd3,0x10,0x1e,0xf8,0x98,0xaf,0x2f,0x23,0xcf,0xe4, -0xdf,0x04,0x19,0x09,0x6f,0xf9,0xfd,0x05,0x9f,0x06,0x46,0x80,0xf9,0xaa,0x32,0x19, -0xd3,0x72,0xbd,0x40,0x02,0xa7,0xa9,0xd7,0x63,0x1e,0x68,0xbc,0x06,0x93,0xce,0x1a, -0xaf,0x8f,0x35,0x53,0x8b,0xc6,0x34,0x73,0x49,0xe6,0xc6,0x37,0x25,0x32,0x4a,0x20, -0xf3,0x65,0xcb,0x18,0x6f,0xb8,0x10,0x9f,0xcb,0x73,0x4c,0xaa,0x56,0xc8,0x2b,0xe9, -0xb3,0xeb,0x57,0xcd,0xc0,0xb5,0x21,0xfc,0xde,0x74,0x7d,0x58,0xd0,0xcd,0xf7,0xee, -0x84,0x7e,0x73,0x6b,0x66,0x5d,0xf3,0x15,0x69,0xea,0xbf,0x90,0xbe,0xe9,0x37,0xfd, -0xaf,0xe7,0x84,0xb3,0xac,0x07,0x98,0x9b,0x7a,0x29,0x43,0x0b,0x2d,0x37,0x8f,0xce, -0xeb,0xbd,0x4f,0xa2,0x1f,0xdf,0x81,0xd2,0x4c,0x63,0xd7,0x34,0x9a,0x13,0xe6,0x18, -0x13,0x0a,0xcc,0x66,0xc3,0xdb,0x2d,0x37,0xff,0x9f,0x16,0xd3,0x47,0x36,0x90,0x33, -0x9b,0xc5,0x33,0xd9,0x94,0x30,0x30,0x2f,0x37,0xed,0x6e,0x36,0x95,0xf9,0x1c,0x76, -0x98,0xee,0xcf,0x42,0x0b,0x1a,0x18,0x41,0xec,0x79,0xbd,0x7e,0x8d,0xe3,0x0e,0xca, -0x33,0x5f,0x61,0xdc,0x1e,0x0c,0xcb,0x81,0xbb,0x6e,0xc2,0x39,0xdc,0x6b,0xd9,0xab, -0xd5,0x78,0xf5,0xfa,0xed,0xef,0xc6,0x77,0x6a,0x37,0xee,0xe1,0x34,0x81,0x26,0xd2, -0x24,0x9a,0x4c,0xcf,0xd0,0x14,0x9a,0x4a,0xcf,0xd2,0x34,0x9a,0x4e,0x33,0x68,0x26, -0xcd,0xa2,0xd9,0x34,0x87,0xe6,0xd2,0x73,0x34,0x8f,0xe6,0xd3,0xf3,0xf4,0x02,0x2d, -0xa0,0x85,0xf4,0x22,0xbd,0x44,0x2f,0x93,0x3b,0xb9,0x1f,0x4d,0x07,0xc9,0xa4,0xc1, -0xd2,0xd1,0xfd,0xe8,0x62,0x3a,0x56,0x8f,0xa4,0x18,0x2b,0xc9,0xa0,0xf3,0x8b,0x93, -0x83,0xb9,0x18,0x87,0xb8,0x7c,0xcb,0x26,0x6a,0x29,0xa4,0x96,0xcd,0xd4,0x52,0x44, -0x2d,0x5b,0xa8,0x65,0x2b,0xb5,0x6c,0xa3,0x96,0x62,0x6a,0xd9,0x4e,0x2d,0x3b,0xa8, -0x65,0x27,0xb5,0x94,0x50,0xcb,0x2e,0x6a,0x29,0xa5,0x96,0xdd,0xd4,0x52,0x46,0x2d, -0x7b,0xa8,0xa5,0x9c,0x5a,0x2a,0xa8,0xa5,0x92,0x5a,0xf6,0x52,0xcb,0x3e,0x6a,0xd9, -0x4f,0x2d,0xd5,0xd4,0x52,0x43,0x2d,0xb5,0xd4,0x52,0x47,0x2d,0xf5,0xd4,0xd2,0x40, -0x2d,0x8d,0x74,0x60,0x31,0x1d,0x48,0xa2,0x03,0x29,0x74,0x20,0x8d,0x0e,0x2c,0xa1, -0x03,0x19,0x74,0x60,0x39,0x1d,0xc8,0xa2,0x03,0x2b,0xe9,0xc0,0x6a,0x3a,0xb0,0x96, -0x0e,0xac,0xa7,0x03,0x1b,0xe9,0x40,0x0e,0x1d,0xc8,0xa3,0x03,0x05,0x74,0xa0,0x90, -0x0e,0x14,0xd1,0x81,0xad,0x74,0xa0,0x98,0x0e,0xec,0xa0,0x03,0x25,0x74,0xa0,0x94, -0x0e,0x94,0xd1,0xb4,0xa3,0x69,0x34,0x6d,0x3a,0x1d,0xd8,0x47,0x07,0xaa,0xe8,0x40, -0x2d,0x1d,0xa8,0xa7,0x03,0x8d,0x34,0xf3,0xf5,0x2a,0x3a,0x98,0x48,0x07,0x93,0xe9, -0x60,0x2a,0x1d,0x4c,0xa7,0x23,0xf5,0xb3,0xe9,0x60,0x06,0x1d,0x5c,0x4e,0x07,0xb3, -0xe8,0xe0,0x4a,0x3a,0xb8,0x9a,0x0e,0xae,0xa5,0x83,0xeb,0xe9,0xe0,0x46,0x3a,0x98, -0x43,0x07,0xf3,0xe8,0x60,0x01,0x1d,0x2c,0xa4,0x83,0x45,0x74,0x70,0x2b,0x1d,0x2c, -0xa6,0x83,0x3b,0xe8,0x60,0x09,0x1d,0x2c,0xa5,0x83,0x65,0x74,0xb0,0x9c,0x0e,0x56, -0xd2,0xc1,0x7d,0x74,0xb0,0x8a,0x5a,0x9a,0xe8,0x60,0x2d,0x1d,0xac,0xa7,0x83,0x8d, -0xd4,0xb6,0x9a,0x0e,0x25,0xd1,0xa1,0x14,0x6a,0x5b,0x43,0x87,0xd2,0xa9,0x6d,0x1d, -0xb5,0xad,0xa7,0x43,0xcb,0xa8,0x35,0x8f,0xda,0x36,0x52,0x5b,0x0e,0x1d,0x5a,0x45, -0x6d,0x9b,0xa8,0xad,0x88,0xda,0x76,0x50,0xdb,0x76,0x3a,0x84,0x9d,0x65,0xd4,0x56, -0x41,0x6d,0xfb,0xe8,0x50,0x21,0x1d,0x2a,0xa2,0x43,0x5b,0xe9,0x08,0x43,0x87,0xb6, -0xd3,0x11,0xb4,0x53,0x4a,0x47,0xd2,0xe9,0xd0,0x1e,0x3a,0xb2,0x94,0x8e,0x64,0xd0, -0xa1,0xbd,0x74,0x68,0x3f,0x1d,0x59,0x45,0x87,0x6a,0xe8,0x50,0x03,0x4d,0x86,0xde, -0xcc,0xe9,0x34,0x7b,0x3a,0xb5,0x66,0x52,0xeb,0x0a,0x6a,0x5d,0x45,0xad,0x6b,0xa8, -0x75,0x1d,0xb5,0x6e,0xa0,0xd6,0x6c,0x6a,0xcd,0xa5,0xd6,0x02,0x6a,0x2d,0xa4,0xd6, -0x22,0x6a,0xdd,0x4a,0xad,0xc5,0xd4,0xba,0x83,0x5a,0x4b,0xa8,0xb5,0x94,0x5a,0xcb, -0x68,0xf2,0xcb,0xd4,0x0a,0xc9,0xb5,0x74,0xa8,0x89,0x5a,0x6b,0xa8,0xb5,0x8e,0x5a, -0x1b,0xa8,0xb5,0x89,0x0e,0x2f,0xa6,0xc3,0x49,0x74,0x38,0x85,0x0e,0xa7,0xd1,0xe1, -0x25,0x74,0x38,0x83,0x0e,0x2f,0xa7,0xc3,0x59,0x74,0x78,0x25,0x1d,0x5e,0x4d,0x87, -0xd7,0xd2,0xe1,0xf5,0x74,0x78,0x23,0x1d,0xce,0xa1,0xc3,0x79,0x74,0xb8,0x80,0x0e, -0xe5,0xd3,0xe1,0x22,0x3a,0xbc,0x95,0x0e,0x17,0xd3,0xe1,0x1d,0x74,0xb8,0x84,0x0e, -0x97,0xd2,0xe1,0x32,0x3a,0x5c,0x4e,0x87,0x2b,0xe9,0x7c,0x39,0x0e,0xd4,0xd3,0xa1, -0x6c,0xe4,0xb6,0x51,0x5b,0x22,0x1d,0x62,0xe8,0xc8,0x12,0x3a,0xb2,0x8c,0xda,0xd2, -0xa8,0x6d,0x09,0xb5,0x65,0x50,0xdb,0x72,0x6a,0xcb,0xa2,0x36,0x1c,0xad,0xa1,0xb6, -0x3a,0x3a,0xb2,0x18,0x03,0x2f,0x15,0xa4,0x81,0xa5,0x60,0x3b,0x48,0x02,0x19,0x74, -0x64,0x2d,0x1d,0x65,0x08,0x83,0xf3,0xe8,0x6a,0x3a,0x9a,0xce,0x0e,0xd2,0x1a,0x7a, -0xb3,0x9c,0xde,0xac,0xa4,0x23,0xc8,0x54,0x91,0x3b,0xb6,0x23,0xa9,0xbd,0x92,0x1d, -0xcc,0xec,0xd1,0x5d,0x84,0x33,0x7e,0xac,0x94,0x8e,0xed,0xa6,0x63,0x65,0xd4,0xbe, -0x8c,0xda,0x97,0x53,0x7b,0x26,0x1d,0x2b,0xa7,0x63,0x15,0x74,0xac,0x92,0x8e,0xed, -0xa5,0x63,0xfb,0xe8,0xd8,0x7e,0x3a,0x86,0x62,0xd5,0x74,0xac,0x96,0x8e,0xd5,0xd1, -0xb1,0x06,0x3a,0xd6,0x48,0xc7,0x9a,0xa8,0x9d,0xa1,0xf6,0xc5,0xd4,0x9e,0x44,0xed, -0xc9,0xd4,0x9e,0x42,0xed,0xa9,0xd4,0x9e,0x46,0xed,0xe9,0xd4,0xbe,0x84,0xda,0x97, -0x52,0x7b,0x06,0xb5,0xaf,0xa7,0xf6,0x8d,0xd4,0x9e,0x43,0xed,0x79,0xd4,0x5e,0x40, -0xed,0x85,0xd4,0x5e,0x44,0xed,0x5b,0xa9,0xbd,0x98,0xda,0x77,0x50,0x7b,0x09,0xb5, -0x97,0x52,0x3b,0x74,0xab,0xa9,0xbd,0x8e,0xde,0xc4,0x4f,0x3d,0xbd,0xd9,0x40,0x1d, -0x2b,0xa8,0x63,0x25,0x75,0xac,0xa2,0x8e,0xd5,0xd4,0xb1,0x86,0x3a,0xd6,0x52,0xc7, -0x3a,0xea,0x58,0x4f,0x1d,0x1b,0xa8,0x63,0x23,0x75,0x64,0x53,0x47,0x0e,0x75,0xe4, -0x52,0x47,0x1e,0x75,0xe4,0x53,0x47,0x01,0x1d,0xdf,0x43,0xc7,0xcb,0xe9,0x78,0x05, -0x1d,0xaf,0xa4,0xe3,0x7b,0xe9,0xf8,0x3e,0x3a,0xbe,0x9f,0x8e,0x57,0xd1,0xf1,0x6a, -0x3a,0x5e,0x43,0xc7,0x6b,0xe9,0x78,0x1d,0x1d,0xaf,0xa7,0xe3,0x0d,0x74,0xbc,0x91, -0x8e,0x37,0x51,0x07,0x43,0x1d,0x8b,0xa9,0x23,0x91,0x3a,0x92,0xa8,0x23,0x99,0x3a, -0x52,0xa8,0x23,0x95,0x3a,0xd2,0xa8,0x23,0x9d,0x3a,0x96,0x50,0xc7,0x52,0xea,0xc8, -0xa0,0x8e,0x65,0xd4,0xb1,0x9c,0x3a,0x32,0xa9,0x23,0x8b,0x3a,0x0a,0xa9,0xa3,0x88, -0x3a,0xb6,0x52,0x47,0x31,0x75,0xec,0xa0,0x8e,0x12,0xea,0x28,0xa5,0x8e,0x32,0xea, -0x28,0xa7,0x8e,0x4a,0xea,0xd8,0x47,0x1d,0x55,0xd4,0x51,0x43,0x1d,0x75,0xd4,0x01, -0xe3,0x9b,0xe8,0xc4,0x62,0x3a,0x91,0x41,0x27,0x96,0xd3,0x89,0x2c,0x3a,0xb1,0x92, -0x4e,0xac,0xa6,0x13,0x6b,0xe9,0xc4,0x7a,0x3a,0xb1,0x91,0x4e,0xe4,0xd0,0x89,0x3c, -0x3a,0x51,0x40,0x27,0x0a,0xe9,0x44,0x11,0x9d,0xd8,0x4a,0x27,0x8a,0xe9,0xc4,0x0e, -0x3a,0x51,0x42,0x27,0x4a,0xe9,0x44,0x19,0x9d,0x28,0xa7,0x13,0x95,0x74,0x62,0x1f, -0x9d,0xa8,0xa2,0x13,0x35,0x74,0xa2,0x8e,0x4e,0x34,0xd0,0x89,0x26,0xea,0xcc,0xa2, -0xce,0x44,0xea,0x4c,0xa6,0xce,0x54,0xea,0x4c,0xa7,0xce,0xa5,0xd4,0xb9,0x8c,0x3a, -0x33,0xa9,0x73,0x25,0x75,0xae,0xa6,0xce,0xb5,0xd4,0xb9,0x9e,0x3a,0x37,0x52,0x67, -0x0e,0x75,0xe6,0x51,0x67,0x01,0x75,0x16,0x52,0x67,0x11,0x75,0x6e,0xa5,0xce,0x62, -0xea,0xdc,0x41,0x9d,0x25,0xd4,0x59,0x4a,0x9d,0x65,0xd4,0x59,0x4e,0x9d,0x95,0xd4, -0xb9,0x8f,0x3a,0xab,0xa8,0xb3,0x86,0x3a,0xeb,0xa8,0xb3,0x81,0x3a,0x9b,0xe8,0xe4, -0x62,0x3a,0x99,0x44,0x27,0x53,0xe8,0x64,0x1a,0x9d,0x5c,0x42,0x27,0x33,0xe8,0xe4, -0x72,0x3a,0x99,0x45,0x27,0x57,0xd2,0xc9,0xd5,0x74,0x72,0x2d,0x9d,0x5c,0x4f,0x27, -0x37,0xd2,0xc9,0x1c,0x3a,0x99,0x47,0x27,0x0b,0xe8,0x64,0x21,0x9d,0x2c,0xa2,0x93, -0x5b,0xe9,0x64,0x31,0x9d,0xdc,0x41,0x27,0x4b,0xe8,0x64,0x29,0x9d,0x2c,0xa3,0x53, -0x85,0x74,0x6a,0x33,0x9d,0x2a,0xa2,0x53,0x5b,0xe8,0xd4,0x56,0x3a,0xb5,0x8d,0x4e, -0x15,0xd3,0xa9,0xed,0x74,0x6a,0x07,0x9d,0xda,0x49,0xa7,0x4a,0xe8,0xd4,0x2e,0x3a, -0x55,0x4a,0xa7,0x76,0xd3,0x29,0x14,0xde,0x43,0xa7,0xca,0xe9,0x54,0x05,0x9d,0xaa, -0xa4,0x53,0x7b,0xe9,0xd4,0x3e,0x3a,0xb5,0x9f,0x4e,0x55,0xd1,0xa9,0x6a,0x3a,0x55, -0x43,0xa7,0x6a,0xe9,0x54,0x1d,0x9d,0xaa,0xa7,0x53,0x0d,0x74,0xaa,0x91,0x4e,0x35, -0xd1,0x69,0x86,0x4e,0x2f,0xa6,0xd3,0x89,0x74,0x3a,0x89,0x4e,0x27,0xd3,0xe9,0x14, -0x3a,0x9d,0x0a,0x15,0xec,0x78,0xbb,0xf8,0x9d,0xbd,0xf4,0x4e,0x3a,0xa2,0xf7,0xd2, -0xd8,0xdc,0x52,0x44,0x67,0xb7,0xac,0x3d,0xbb,0xa5,0x1e,0xc9,0x3a,0x53,0xb2,0xde, -0x94,0xe4,0x9a,0x92,0x42,0x53,0xb2,0xd9,0x94,0x94,0x98,0x92,0x32,0x2e,0xd9,0x56, -0x78,0x76,0x1b,0x9b,0x6c,0x36,0x25,0x65,0x5c,0xb2,0xbd,0xe2,0xec,0x76,0x36,0xa9, -0x36,0x25,0xeb,0x4c,0xc9,0x7a,0x53,0x92,0x6b,0x4a,0x4a,0xb8,0x64,0x57,0xe1,0xd9, -0x5d,0x6c,0xb2,0x99,0x4b,0x6a,0x96,0x9f,0xad,0xae,0xa0,0xb3,0x75,0xcb,0xcf,0xd6, -0x22,0xa9,0x2d,0x39,0x5b,0xbb,0xd1,0x94,0x14,0xd2,0xd9,0xfa,0x0c,0x3a,0xdb,0x90, -0x78,0xb6,0xb1,0x0a,0xc9,0x32,0x53,0xb2,0xd2,0x94,0xac,0x33,0x25,0x39,0xa6,0x84, -0x39,0xdb,0xb8,0x0f,0x49,0xf9,0xd9,0x86,0x0a,0x53,0x82,0xce,0x35,0x56,0x9c,0x6d, -0x64,0xb8,0x04,0x3b,0xb8,0x5c,0xe5,0x40,0x62,0xde,0x31,0xb0,0x7f,0x15,0xd7,0x48, -0x63,0xae,0x29,0x29,0x34,0x25,0xdb,0x4c,0x49,0x89,0x29,0x59,0xc1,0x0a,0x9c,0xdf, -0xcb,0x80,0xc5,0x20,0x11,0x24,0x81,0x64,0x90,0x02,0x52,0x41,0x1a,0x48,0x07,0x4b, -0xc0,0x52,0x90,0x01,0x96,0x81,0xe5,0x20,0x13,0x64,0x81,0x15,0x60,0x25,0x58,0x05, -0x56,0x83,0x35,0x60,0x2d,0x58,0x07,0xd6,0x83,0x0d,0x60,0x23,0xc0,0xad,0x6e,0x6f, -0x0e,0xc8,0x05,0x79,0x20,0x1f,0x14,0x80,0x4d,0xa0,0x10,0x6c,0x06,0x45,0x60,0x0b, -0xd8,0x0a,0x8a,0x41,0x29,0x9d,0x4b,0xca,0xa5,0x73,0x59,0x7b,0x40,0x39,0xa8,0x00, -0x95,0x60,0x2f,0xd8,0x47,0x17,0x37,0x66,0xd0,0xb9,0x8a,0xa5,0x28,0xb3,0x02,0xac, -0x04,0xab,0xc0,0x6a,0xb0,0x06,0xac,0x05,0xeb,0xc0,0x7a,0xb0,0x01,0x6c,0x04,0xd9, -0x20,0x07,0xe4,0x81,0x7c,0x50,0x00,0x36,0x81,0x42,0xb0,0x19,0x14,0x81,0x2d,0x60, -0x2b,0xd8,0x06,0x8a,0xc1,0x76,0xb0,0x03,0xec,0x04,0x25,0x60,0x17,0x60,0xed,0xda, -0x0d,0xca,0x00,0x6c,0x4b,0x82,0x6d,0x49,0xb0,0x2d,0x09,0xb6,0x25,0xc1,0xb6,0xa4, -0x7d,0x60,0x3f,0xa8,0x02,0xd5,0xa0,0x06,0xd4,0x82,0x06,0xd0,0x08,0x9a,0xa8,0x6d, -0x05,0xb5,0xc1,0x62,0x78,0xbd,0x0d,0x1d,0x84,0xb3,0xce,0xc1,0x59,0xe7,0xe0,0x98, -0x73,0xe8,0x7c,0x1b,0x9e,0x85,0x6b,0xa9,0xad,0x80,0xda,0x0a,0xa9,0x0d,0x9b,0x90, -0xde,0x87,0x27,0x00,0x1e,0x95,0x10,0xde,0x9f,0x42,0x47,0x70,0xa4,0x9c,0xda,0xf6, -0x50,0x5b,0x25,0xb5,0xed,0xa5,0xb6,0x6a,0x3a,0x82,0x27,0x08,0x8c,0x83,0x73,0x8f, -0xac,0xa0,0x23,0x68,0xb8,0x7a,0x31,0x48,0x02,0x29,0x20,0x0d,0x2c,0x01,0x70,0x57, -0xf5,0x72,0x90,0x05,0xd8,0x32,0x70,0x55,0x35,0xdc,0x54,0x0d,0xe5,0x6a,0xb8,0xa7, -0x1a,0xae,0xa9,0x86,0x05,0xd5,0x70,0x4b,0x35,0x5c,0x52,0x0d,0x77,0x54,0xc3,0x15, -0xd5,0x70,0x43,0x35,0x5c,0x50,0x0d,0x85,0x6a,0x58,0x50,0x8d,0x6e,0x57,0xa3,0xcb, -0xd5,0xe8,0x6e,0x35,0xba,0x5a,0x8d,0x6e,0x56,0xa3,0x8b,0xd5,0x75,0x00,0x5d,0xac, -0x6e,0xa2,0x73,0x35,0xd0,0xaf,0x81,0x7e,0x0d,0xf4,0x6b,0xa0,0x5f,0x03,0xfd,0x1a, -0xe8,0xd7,0x40,0xbf,0x06,0xfa,0x35,0xd0,0xaf,0x81,0x7e,0x0d,0xf4,0x6b,0xa0,0x5f, -0x03,0xfd,0x1a,0xe8,0xd7,0x40,0xbf,0x06,0xfa,0x35,0xd0,0xaf,0x81,0x7e,0x0d,0xf4, -0x6b,0xa0,0x5f,0x03,0xfd,0x1a,0xe8,0xd7,0x40,0xbf,0x06,0xfa,0x35,0xd0,0xaf,0x81, -0x7e,0x0d,0xf4,0x6b,0xa0,0x5f,0x03,0xfd,0x1a,0xe8,0xd7,0x40,0xbf,0x06,0xfa,0xb5, -0xd0,0xaf,0x85,0x7e,0x2d,0xf4,0x6b,0xa1,0x5f,0x0b,0xfd,0x5a,0xe8,0xd7,0x42,0xbf, -0x16,0xfa,0xb5,0xd0,0xaf,0x85,0x7e,0xed,0x5a,0x9a,0x70,0xa4,0x91,0x5a,0x20,0x89, -0x8b,0xf3,0x5c,0x2d,0x24,0x6b,0x21,0x59,0x0b,0xc9,0x5a,0x48,0xd6,0x42,0xb2,0x16, -0x92,0xb5,0x90,0xac,0x85,0x64,0x2d,0x24,0x6b,0x21,0x59,0x0b,0xc9,0x5a,0x48,0xd6, -0x42,0xb2,0x16,0x92,0xb5,0x90,0xac,0x83,0x64,0x1d,0x24,0xeb,0x20,0x59,0x07,0xc9, -0x3a,0x48,0xd6,0x41,0xb2,0x0e,0x92,0x75,0x90,0xac,0x83,0x64,0x1d,0x24,0xeb,0xd0, -0xe5,0x3a,0x74,0xb9,0x0e,0x5d,0xae,0x43,0x97,0xeb,0xd0,0xe5,0x3a,0xe8,0xd7,0x41, -0xbf,0x0e,0xfa,0x75,0xd0,0xaf,0x83,0x7e,0x1d,0xf4,0xeb,0xa0,0x5f,0x07,0xfd,0x3a, -0xe8,0xd7,0x41,0xbf,0x0e,0xfa,0x75,0xd0,0xaf,0x83,0x7e,0x1d,0xf4,0xeb,0xa0,0x5f, -0x07,0xfd,0x3a,0xe8,0xd7,0x33,0x00,0x36,0xd4,0x27,0x02,0xd8,0x51,0x9f,0x0c,0x60, -0x4b,0x7d,0x2a,0x80,0x3d,0xf5,0xb8,0x4a,0xea,0x61,0x43,0x3d,0xae,0x92,0x7a,0xd8, -0x51,0x8f,0xab,0xa4,0x1e,0xb6,0xd4,0xe3,0x0a,0xa8,0x87,0x76,0x3d,0xae,0x80,0x7a, -0xe8,0xd7,0xe3,0x0a,0xa8,0x87,0x0d,0xf5,0xb8,0x02,0xea,0x61,0x47,0x3d,0x46,0x78, -0x3d,0xb4,0xeb,0x31,0xc2,0xeb,0xa1,0x5f,0x8f,0x11,0x5e,0x0f,0x1b,0xea,0x31,0xc2, -0xeb,0x61,0x47,0x03,0x74,0x1b,0xa0,0xdb,0x00,0xdd,0x06,0xe8,0x36,0x40,0xb7,0x01, -0xba,0x0d,0xd0,0x6a,0x80,0x4e,0x03,0x34,0x1a,0xd0,0xdf,0x06,0xe8,0x34,0x40,0xa7, -0x01,0x3a,0x0d,0xd0,0x69,0x80,0x4e,0x03,0x74,0x1a,0xa0,0xd3,0xc0,0xea,0x30,0x98, -0xa7,0xa0,0x07,0x5c,0x9c,0xc8,0xc5,0x49,0x5c,0x9c,0xcc,0xc5,0x29,0x5c,0x9c,0xca, -0xc5,0x69,0x5c,0xbc,0x89,0x8b,0x0b,0xb9,0x78,0x33,0x17,0x17,0x71,0xf1,0x16,0x2e, -0xde,0xca,0xc5,0xdb,0xb8,0xb8,0x98,0x8d,0x1b,0xb8,0xf2,0x0d,0x5c,0xf9,0x06,0xae, -0x7c,0x03,0x57,0xbe,0x81,0x2b,0xdf,0xc0,0x95,0x6f,0xe0,0xca,0x37,0x98,0xca,0xef, -0x41,0x7c,0xac,0x9c,0x8d,0x76,0xb1,0xdb,0x8d,0xfb,0xb9,0x18,0xde,0x68,0x2c,0x67, -0x8f,0x62,0x3a,0xb5,0x9a,0xdc,0xdf,0x4c,0x64,0xa7,0x55,0x6f,0xb2,0x7d,0xdf,0xcb, -0x16,0xad,0x62,0xa3,0xdd,0x6c,0xc9,0x26,0xce,0x56,0xdc,0xbd,0x71,0x84,0x2d,0x8b, -0x39,0x1a,0x1b,0xb3,0xf3,0xb8,0xd5,0x28,0x7f,0x0c,0xa7,0xa3,0x89,0x85,0x75,0xd3, -0x7e,0xec,0x5c,0xc3,0x15,0x58,0xc3,0x15,0x58,0xc3,0x16,0x80,0x52,0x13,0x7c,0xd6, -0xc4,0xfa,0x0c,0x77,0x8f,0xa6,0xad,0xdc,0x04,0x8e,0xa1,0xa7,0xb1,0x5d,0x8f,0xb6, -0xdb,0x97,0xb0,0x51,0x26,0xa7,0xc5,0xd9,0xd6,0x50,0xcd,0x1e,0x61,0xab,0xd3,0x79, -0x66,0x05,0x52,0x4c,0x34,0x99,0x0a,0xfc,0x98,0x13,0x53,0x6e,0x1f,0x7e,0xcc,0x09, -0x9b,0x1b,0x39,0x12,0x05,0x53,0x88,0x5d,0xc2,0x8e,0xa4,0x91,0xfa,0x1b,0x45,0xd9, -0xd2,0x81,0x14,0x4c,0x21,0x14,0x4a,0x3a,0x0a,0xa3,0x70,0xf2,0xa1,0xf3,0xe9,0xab, -0x28,0x9a,0x54,0xa4,0xa6,0x79,0xf3,0x69,0x42,0xc0,0x24,0x30,0x9f,0x5e,0xdf,0x33, -0x89,0x26,0x05,0xcc,0x01,0x2f,0x20,0x3f,0x85,0x66,0xcf,0xa1,0xf9,0xb3,0xe8,0xf9, -0x67,0x66,0xd2,0xf3,0xb3,0xe8,0x7c,0x4a,0x26,0xbd,0xb5,0x82,0xde,0x5a,0x49,0x6f, -0xad,0xa2,0xb7,0x56,0xd3,0x94,0x09,0x2f,0xa2,0x95,0x95,0xdc,0xca,0x49,0xc7,0xc5, -0xe1,0x5c,0x1c,0x14,0xc8,0x25,0x5a,0xd2,0x70,0x31,0x9b,0x0f,0xe1,0xf2,0x21,0xdc, -0xf2,0x2a,0x84,0x82,0xb9,0x98,0xdd,0x1f,0x4a,0x21,0x5c,0xcc,0xe6,0xc3,0xb8,0xa3, -0x61,0xdc,0x9e,0x30,0xd2,0x71,0x31,0xbb,0x9f,0xa6,0x4d,0xc3,0x0f,0x58,0x40,0x0b, -0xa6,0xe1,0x87,0x03,0x9b,0x2f,0xd2,0x8b,0xd3,0xf0,0x33,0x8d,0xce,0xa7,0x26,0x53, -0x20,0x27,0x75,0x3e,0xbd,0x04,0x3f,0xe6,0xc4,0x94,0xdb,0x8d,0x1f,0x73,0xc2,0xe6, -0x2e,0x30,0xe9,0x60,0x09,0xb1,0x36,0x62,0xe5,0xa7,0xa1,0x20,0x18,0x88,0xc5,0x1f, -0xcc,0x81,0x15,0xe8,0x05,0x34,0xc3,0x49,0x13,0x48,0xaa,0x20,0x35,0xa9,0x34,0x40, -0x0b,0x82,0x41,0x08,0x08,0x05,0x3a,0x10,0x06,0xc2,0x41,0x50,0x20,0x1b,0xb1,0x25, -0x83,0xd8,0xa2,0x41,0x6c,0xd9,0x20,0xb6,0x70,0x10,0x5b,0x3a,0x88,0x2d,0x1e,0xc4, -0x96,0x0f,0x62,0x2b,0x04,0xb1,0x35,0x34,0x6c,0x8d,0x09,0x60,0x22,0x98,0x04,0x26, -0x83,0x67,0xc0,0x14,0x30,0x15,0x3c,0x0b,0xa6,0x81,0xe9,0x60,0x06,0x98,0x09,0x66, -0x81,0xd9,0x60,0x0e,0x98,0x0b,0x9e,0x03,0xf3,0xc0,0x7c,0xf0,0x3c,0x78,0x01,0x2c, -0x00,0x0b,0xc1,0x8b,0xe0,0x25,0xf0,0xb2,0xfa,0x86,0x1b,0x58,0x4f,0x44,0x44,0x44, -0x53,0x34,0xfb,0x13,0x4d,0xe7,0x4b,0xf2,0x8e,0x56,0xd3,0xf9,0x3d,0x7b,0x40,0x39, -0xc0,0x48,0xda,0x83,0xe1,0xb5,0x67,0x2f,0xc0,0x70,0xda,0xb3,0x1f,0x54,0x01,0xb6, -0x4c,0x0d,0xa8,0x05,0x75,0xa0,0x1e,0x34,0x80,0x46,0xd0,0x84,0xd5,0x0e,0xa6,0x1b, -0xe5,0x98,0x6e,0x94,0x63,0xba,0x51,0x8e,0xe9,0x46,0x39,0xa6,0x1b,0xe5,0x98,0x6e, -0x94,0x63,0xba,0x51,0x8e,0xe9,0x46,0x39,0xa6,0x1b,0xe5,0x98,0x6e,0x94,0x63,0xba, -0x51,0x8e,0xe9,0x46,0x39,0xa6,0x1b,0xe5,0x98,0x6e,0x94,0x63,0xba,0x51,0x8e,0xe9, -0x46,0x39,0xa6,0x1b,0xe5,0x98,0x6e,0x94,0x63,0xba,0x51,0x8e,0xe9,0x46,0x39,0x86, -0x7a,0x39,0xa6,0x1b,0xe5,0x98,0x6e,0x94,0x63,0xba,0x51,0x8e,0xe9,0x46,0x39,0xa6, -0x1b,0xe5,0xec,0xca,0x0a,0xd3,0x8d,0x72,0x4c,0x37,0xca,0x31,0xdd,0x28,0xc7,0x74, -0xa3,0x1c,0xd3,0x8d,0x72,0x3c,0x51,0x71,0x4f,0xdd,0xd7,0x40,0x6d,0xb0,0xaa,0x7c, -0x3b,0xd8,0x09,0x76,0x01,0x76,0x55,0xb6,0x9f,0x0e,0xe3,0xd9,0x0c,0x1b,0x2b,0x60, -0x63,0x05,0xec,0xab,0x80,0x6d,0x15,0xb0,0xab,0x02,0x36,0x55,0xc0,0x9e,0x0a,0xd8, -0x52,0x01,0x3b,0x2a,0x60,0x43,0x05,0xf4,0x2b,0xa0,0x5d,0x01,0xdd,0x0a,0x68,0x56, -0x40,0xaf,0x02,0x5a,0x15,0xd0,0xa9,0xc0,0x94,0xa6,0x02,0xd3,0x99,0x0a,0x4c,0x65, -0x2a,0x30,0x95,0xa9,0xd8,0x01,0x30,0xb4,0x2a,0x4a,0x41,0x19,0x80,0x0f,0x2b,0xa0, -0x58,0x01,0xdf,0x55,0xc0,0x6f,0x15,0xf0,0x59,0x05,0xfc,0x55,0x01,0xab,0x2a,0xe0, -0xa7,0x4a,0xe8,0x57,0x42,0xbf,0x12,0xfa,0x95,0xd0,0xaf,0x84,0x7e,0x25,0xf4,0x2b, -0xa1,0x5f,0x09,0xfd,0x4a,0xe8,0x57,0x42,0xbf,0x12,0xfa,0x95,0xd0,0xaf,0x84,0x7e, -0x25,0xf4,0x2b,0xa1,0x5f,0x09,0xfd,0x4a,0xe8,0x57,0x42,0xbf,0x12,0x3d,0xab,0xc4, -0x58,0xae,0x84,0xd6,0xbe,0x42,0xea,0x2e,0x5b,0x4e,0x7d,0x8d,0x05,0xf4,0x51,0x35, -0x03,0xb6,0x83,0xfd,0xa0,0x89,0x3e,0xc2,0xf3,0xf7,0x23,0x3c,0x2b,0x3f,0xaa,0x5d, -0x06,0x36,0x81,0x5a,0xea,0x4a,0x6e,0xa2,0xae,0x94,0xad,0xa0,0x84,0xba,0x52,0x13, -0xc1,0x3a,0x80,0x7c,0xda,0x26,0xb0,0x8f,0xba,0xd2,0x19,0xea,0x5a,0x9a,0x43,0x5d, -0x19,0x35,0xd4,0xb5,0x6c,0x2d,0xc8,0x06,0xd5,0xd4,0xb5,0x7c,0x31,0xc8,0x05,0x3b, -0xa8,0x2b,0x13,0xf5,0x32,0xf7,0x53,0x57,0x56,0x3a,0x28,0xa2,0xae,0x9c,0xf5,0xd4, -0x95,0x5b,0x40,0x5d,0x45,0x68,0x67,0x0b,0x8e,0x6d,0x59,0x0a,0x50,0x77,0x4b,0x31, -0x75,0x6d,0xad,0xa4,0xae,0xd2,0x15,0xd4,0xb5,0x1b,0xed,0x96,0xa1,0x9d,0x3d,0x59, -0x60,0x33,0x40,0xbe,0x7c,0x37,0x28,0xa7,0xae,0x2a,0xe8,0x55,0xc1,0xa6,0x2a,0x36, -0xdf,0x48,0x5d,0x35,0x15,0x00,0xb6,0xe2,0x99,0xdf,0x55,0xb7,0x17,0x60,0x1f,0x66, -0xd8,0x5d,0x78,0xc0,0x75,0x35,0xa0,0x2d,0x3c,0x70,0xba,0x1a,0xd0,0x6e,0x53,0x12, -0x75,0xa7,0xa7,0x83,0xfd,0xd4,0xbd,0x24,0x83,0xba,0xd7,0x94,0x81,0xbd,0xd4,0xbd, -0x2e,0x0d,0xac,0x07,0x5b,0x40,0x0d,0x75,0xaf,0xdf,0x04,0xb6,0x52,0x77,0xce,0x1e, -0xea,0xce,0x45,0xf9,0xdc,0xed,0xd4,0xbd,0x0b,0xfb,0x4a,0x37,0x03,0x1c,0xdf,0x5d, -0x09,0x1f,0xa2,0x7e,0xd9,0x1a,0x90,0x43,0xdd,0xb0,0xb1,0x7b,0x0f,0xf2,0xb8,0x0e, -0x7a,0x16,0x97,0x50,0x4f,0xfa,0x4e,0xb0,0x1f,0xd4,0x81,0x26,0xea,0x59,0x92,0x06, -0x36,0x82,0x1c,0xea,0x59,0xba,0x8b,0x7a,0x32,0x93,0xc1,0x12,0xea,0x59,0x9d,0x0b, -0xb6,0x51,0xcf,0x9a,0x0d,0xa0,0x00,0x6c,0x07,0x7b,0xa8,0x67,0x5d,0x06,0x58,0x45, -0x3d,0x1b,0xd1,0xc6,0xc6,0x06,0xea,0xc9,0xde,0x0d,0xd0,0x4e,0x0e,0xd2,0x02,0xb4, -0x51,0xb0,0x19,0x54,0x52,0xcf,0x96,0x5a,0xea,0xd9,0x56,0x0d,0x1a,0xa9,0x67,0x07, -0xb4,0x4b,0x50,0xaf,0xa4,0x86,0x7a,0x30,0x8a,0x7b,0x2a,0xb1,0x1f,0x0f,0xe7,0x1e, -0x3c,0x80,0x7b,0x1a,0x97,0x82,0x06,0xea,0x65,0x16,0x83,0x65,0x60,0x15,0xa8,0xa4, -0xde,0xc5,0x4d,0xd4,0x9b,0xb8,0x84,0x7a,0xd3,0x8a,0xc0,0x4e,0x80,0x7d,0x69,0xf5, -0xd4,0x9b,0x8e,0x32,0xe9,0x39,0xa0,0x80,0x7a,0x97,0xec,0x06,0x15,0xa0,0x9a,0x7a, -0x37,0x2e,0x07,0x25,0xd4,0x5b,0xc8,0x00,0x94,0x29,0x44,0xbd,0xad,0x8d,0xd4,0xbb, -0x2d,0x83,0x7a,0x8b,0xd1,0xe6,0x76,0xec,0xc7,0xf5,0xdf,0x8b,0xeb,0xb8,0x17,0xd7, -0x63,0x6f,0x39,0xea,0xe0,0x5a,0xe8,0xdd,0xb7,0x05,0xec,0xa1,0xde,0xfd,0x68,0x1f, -0x93,0xa9,0xde,0xba,0xa5,0xd4,0xdb,0x88,0xf6,0xf1,0x18,0xed,0xc5,0xf2,0xa3,0x2f, -0x71,0x25,0xf5,0xa5,0x2c,0xa1,0xbe,0xb4,0x54,0xb0,0x0c,0x60,0x7b,0x6d,0x15,0xf5, -0xad,0x63,0xa8,0x6f,0x43,0x2e,0xf5,0x65,0xef,0x07,0x35,0xd4,0x97,0xb3,0x9d,0xfa, -0xf2,0x70,0x2c,0x2f,0x1f,0x6c,0x06,0x3b,0xa8,0xaf,0x20,0x03,0x94,0x82,0x4a,0xea, -0xdb,0xb4,0x98,0xfa,0x36,0xa3,0x4c,0x51,0x0e,0x28,0xa0,0xbe,0x6d,0xeb,0xc0,0x46, -0xb0,0x8b,0xfa,0x76,0x62,0x7f,0xc9,0x06,0x80,0xfd,0xbb,0xb6,0x82,0x32,0x50,0x01, -0xea,0xa9,0xaf,0x34,0x9b,0xfa,0x2a,0xb1,0x0f,0xf3,0xc8,0x3e,0x8c,0xa1,0x3e,0x4c, -0xfe,0xfa,0x30,0xa9,0xeb,0xc3,0x44,0xae,0x0f,0x13,0xb7,0x3e,0x4c,0xda,0xfa,0x30, -0xd1,0xea,0xc3,0x24,0xab,0xaf,0x3e,0x13,0xac,0x06,0x9b,0x00,0xca,0x34,0x2c,0x05, -0xab,0x70,0x3d,0xb1,0xd7,0x14,0x6c,0x6d,0xdc,0x44,0xfe,0x78,0x4e,0xac,0xc2,0xc8, -0x4f,0x06,0x29,0xe4,0x7e,0x21,0x71,0x23,0x1b,0x65,0xd3,0x85,0xc4,0xf4,0x0b,0x89, -0x4b,0x91,0x54,0x5e,0x48,0x4a,0xa7,0x73,0xc9,0x98,0x32,0x25,0x63,0xca,0x94,0x8a, -0x99,0x7d,0x32,0xa6,0x0e,0xa9,0x58,0x54,0xa4,0x62,0x9a,0x97,0x8c,0xe9,0x53,0x32, -0xa6,0x4f,0xc9,0x98,0x3e,0xa5,0xe2,0xf1,0x9f,0x8a,0x89,0x46,0x2a,0x26,0x10,0xa9, -0x98,0x76,0xa5,0x62,0xda,0x95,0x8a,0x69,0x57,0x32,0x16,0x31,0xc9,0x98,0xd2,0x25, -0x63,0x4a,0x97,0xcc,0xb6,0x85,0xe9,0x41,0x32,0xa6,0x9a,0xc9,0x58,0x08,0x25,0x63, -0xba,0x99,0xbc,0x0c,0x60,0xca,0x99,0x9c,0x09,0x30,0xed,0x4c,0xc6,0x1c,0x23,0x19, -0x73,0x8c,0x64,0x4c,0xfb,0x52,0x50,0x36,0x05,0xd3,0xaf,0x14,0x4c,0xbf,0x52,0x30, -0xfd,0xc2,0xd5,0x7d,0x2e,0x05,0xd3,0xaf,0x14,0x4c,0xbf,0x52,0xb0,0xd0,0x49,0xc1, -0x94,0x33,0x05,0x36,0xe1,0x8a,0x3f,0x97,0x02,0x9b,0x52,0x60,0x53,0x0a,0x16,0x3a, -0x29,0x98,0x7e,0xa6,0xc0,0x9e,0x14,0xd8,0x93,0x02,0x7b,0x52,0x60,0x4f,0x0a,0xec, -0x49,0x61,0xed,0xc1,0x34,0x32,0x19,0x53,0xbc,0x34,0xd8,0x93,0x06,0x7b,0x70,0x16, -0xcf,0xa5,0x41,0x3b,0x0d,0x53,0xbf,0x34,0x4c,0xfb,0xd2,0x30,0xcd,0x4d,0xc6,0x1a, -0x27,0x0d,0xd3,0xdc,0x34,0x4c,0x73,0x93,0x91,0x26,0x63,0xf1,0x95,0x8c,0xa9,0x4d, -0x32,0x6c,0x49,0x86,0x2d,0xc9,0xd0,0x4f,0x86,0x76,0x32,0x74,0x93,0xa1,0x9b,0xcc, -0xfa,0x02,0xba,0xc9,0xd0,0x4d,0x86,0x5e,0x32,0xa6,0x9a,0x29,0xf0,0x59,0x0a,0x34, -0x52,0xd8,0xf6,0x61,0x47,0x1a,0x6b,0x07,0xda,0x4f,0xc1,0xe2,0x2e,0x05,0x1a,0x78, -0x9e,0x9f,0x4b,0x65,0xfd,0x06,0x1b,0x52,0xd1,0xdf,0x54,0xf4,0x37,0x15,0xb6,0xa5, -0x42,0x2b,0xb5,0x10,0x77,0xb9,0x25,0xb8,0xfb,0xe4,0x20,0x5d,0x0a,0x4a,0x01,0xae, -0x98,0x35,0x15,0x48,0x71,0xe7,0xc3,0x6a,0xa9,0x6b,0x0b,0xee,0x56,0xb9,0x7b,0x48, -0x85,0x93,0xa3,0x66,0xe3,0x44,0x2e,0x4e,0xe2,0xe2,0x14,0x2e,0x4e,0xe5,0xe2,0x34, -0x2e,0x5e,0xc2,0xc5,0x19,0x5c,0xbc,0x8c,0x8b,0x33,0xb9,0x38,0x8b,0x8b,0x57,0x70, -0xf1,0x4a,0x2e,0x5e,0x85,0xf8,0xe2,0x1e,0xb6,0xcd,0x4b,0x89,0x1b,0xd8,0x38,0x63, -0x0b,0x1b,0xe7,0xd5,0xb3,0x71,0x71,0x3a,0x1b,0xef,0x59,0x83,0xf8,0xe3,0xc4,0x5d, -0x6c,0xbc,0x36,0x99,0x8d,0xf3,0xd9,0x16,0x3e,0xde,0xb3,0x9d,0x8d,0x6b,0xf6,0x22, -0xfe,0x24,0x89,0x6d,0xe1,0x93,0x65,0xac,0xd6,0x27,0x6b,0xd9,0x76,0x3e,0x2e,0x62, -0x5b,0xf8,0x78,0xc3,0x96,0x8f,0x37,0x25,0x9b,0x32,0x9f,0xe4,0xb0,0x19,0xdc,0xda, -0xd9,0xb8,0x76,0x19,0x97,0x67,0xed,0x44,0xb7,0xb9,0x3d,0xac,0x4a,0x57,0x4a,0x29, -0xb7,0x3f,0x89,0xcb,0x97,0xb0,0xf9,0x9a,0x3c,0x36,0xbf,0x7c,0x31,0x62,0xdc,0xf2, -0x10,0xe3,0x46,0xc6,0xe6,0xf7,0xec,0xe5,0xf6,0xb0,0x36,0xe0,0xb2,0x64,0xcb,0xe4, -0x16,0xb0,0x7b,0xd6,0x6f,0x65,0xe3,0x4d,0x3b,0xb9,0xa3,0x6c,0xfb,0x3d,0x5b,0x1a, -0xd9,0xa3,0x2b,0x96,0xb3,0xf9,0x25,0x35,0x88,0x7b,0x2b,0x0a,0xd9,0xfc,0x56,0xae, -0xe5,0xa5,0x6c,0x3b,0x1f,0xd5,0x15,0xb1,0xf9,0x95,0xac,0xcd,0x5d,0xa5,0xdb,0xd8, -0xa3,0x39,0xec,0x9e,0x8f,0xea,0x59,0xdd,0xde,0xca,0x34,0xce,0x86,0x35,0x5c,0x2d, -0xce,0xc2,0x7a,0x56,0x11,0xb7,0x26,0x2e,0xae,0x54,0x53,0xd7,0x5a,0x3c,0x0d,0x6a, -0xea,0xa9,0x67,0x77,0x16,0xcd,0x7d,0xfe,0x19,0xd2,0x04,0x91,0x46,0x43,0x1a,0xcc, -0x17,0x83,0x49,0x83,0x99,0x62,0x28,0x69,0x74,0xa4,0x09,0x23,0x4d,0x38,0x69,0x03, -0x49,0x1b,0x44,0x5a,0x0d,0x69,0xb5,0xa4,0x0d,0x26,0x6d,0x08,0xc1,0xff,0x04,0xef, -0x13,0x7c,0x4f,0xf0,0x3c,0xc1,0xef,0x04,0xaf,0x13,0x7c,0x4e,0xf0,0x38,0xc1,0xdf, -0x04,0x6f,0x13,0x7c,0x4d,0xf0,0x34,0xc1,0xcf,0x04,0x2f,0x63,0x5f,0xf5,0xc5,0xca, -0x4d,0x04,0x57,0x7f,0x9c,0x87,0xad,0xec,0x3d,0x78,0x30,0xae,0xc1,0x03,0x91,0x1d, -0x3e,0x49,0x78,0x68,0xe6,0x11,0xfc,0x80,0x87,0x04,0x6e,0xe8,0x5b,0xf0,0xe0,0x59, -0xb1,0x1c,0x37,0xfa,0x1a,0xdc,0xf8,0x0a,0x09,0x7d,0xc7,0xc3,0x11,0x37,0xe6,0x62, -0xf6,0x06,0x8f,0x1b,0xda,0x62,0x0c,0xaf,0xe4,0x9d,0xb8,0x2d,0xe0,0xc1,0x52,0x89, -0x1b,0xd2,0x26,0x3c,0x6c,0xb1,0x1a,0xeb,0x4a,0xdd,0x88,0x07,0x0b,0x1e,0x8c,0x55, -0xdb,0xf0,0x80,0xc4,0x83,0x6a,0x59,0x1d,0x1e,0x80,0x78,0x48,0x96,0xe2,0xe1,0x90, -0x53,0x84,0x32,0xb8,0x71,0x63,0x02,0x00,0xdf,0x60,0x88,0xe6,0x92,0x36,0x94,0xb4, -0x3a,0xd2,0x62,0xda,0x1b,0x4e,0xc1,0x98,0x9d,0x07,0x51,0xb0,0x86,0x82,0xb5,0x14, -0x1c,0x4c,0xc1,0x98,0x23,0x87,0x52,0xb0,0x8e,0x82,0xc3,0x28,0x38,0x9c,0x42,0x30, -0x59,0x65,0x1f,0x61,0x1a,0x36,0xd2,0xb2,0x51,0x30,0x1b,0x85,0xb0,0x51,0x28,0x1b, -0xe9,0xd8,0x28,0x8c,0x8d,0xc2,0xd9,0x28,0x28,0x90,0x8b,0xb9,0x3a,0x41,0x5c,0xa5, -0x67,0xa7,0xd2,0x33,0xf3,0xc0,0x02,0x9a,0xf9,0xfc,0x64,0xdc,0xbb,0x36,0x83,0x2d, -0x60,0x1b,0xd8,0x0e,0x76,0x82,0x12,0x50,0x0a,0xca,0x40,0x39,0x7b,0x7f,0x03,0xfb, -0x40,0x15,0xa8,0x01,0x75,0xa0,0x01,0x34,0xd1,0x85,0xa4,0xc5,0x20,0x19,0xa4,0x12, -0x7b,0x13,0xbc,0x90,0x84,0xfb,0x61,0x52,0x06,0x58,0x06,0x96,0x83,0x4c,0x90,0x05, -0x56,0x81,0xb5,0x60,0x03,0xc8,0x01,0xf9,0xa0,0x00,0x6c,0x02,0x85,0x00,0x76,0x24, -0xc1,0x8e,0x24,0xd8,0x91,0x04,0x3b,0x92,0x76,0x00,0xd8,0x92,0x04,0x5b,0x92,0x76, -0x01,0xd8,0x93,0x04,0x7b,0x92,0xf6,0x00,0xd8,0x94,0x84,0x8b,0xbc,0x6e,0x4b,0xd7, -0xaa,0x65,0x6c,0x17,0x2e,0x24,0xad,0xbc,0x90,0x54,0xcf,0xe9,0xb3,0x1b,0x25,0x50, -0xba,0x90,0x58,0x68,0xda,0xc0,0xbd,0x39,0xdb,0xd4,0xcb,0xcd,0x5c,0x19,0xb6,0x6f, -0x5b,0x60,0x22,0x7b,0x24,0x71,0x8f,0x69,0xa3,0x92,0xeb,0x46,0xe2,0xb6,0x0b,0x89, -0x3b,0xb0,0xc1,0x3a,0x02,0xfd,0x44,0xf7,0xb9,0x0a,0x4b,0xb8,0x6d,0xe4,0x12,0xd1, -0x6e,0x3d,0xeb,0x21,0xae,0x6a,0x8d,0x29,0x57,0xcf,0xf5,0x00,0x87,0xd8,0x76,0x38, -0xdf,0xc1,0xf4,0x0b,0x49,0x49,0x26,0x63,0xb0,0x51,0x8a,0xdd,0xa6,0x7a,0xbb,0xb8, -0x8d,0x4a,0x53,0xae,0x92,0xf3,0x40,0xe2,0x6e,0x6c,0x70,0x09,0x6b,0x10,0x5b,0x08, -0x25,0xb6,0x5e,0xaf,0xb1,0x9b,0xeb,0x0b,0x73,0xfd,0x48,0xa9,0x39,0x81,0xe1,0x9c, -0xca,0xa6,0x81,0xed,0xa4,0x42,0x53,0xff,0x4d,0xdd,0x33,0xed,0x2a,0xbb,0x6e,0xc5, -0x8d,0xc2,0xe6,0x1c,0x57,0x92,0x35,0xa4,0x8c,0x15,0x48,0xac,0xe7,0x8c,0x2f,0x35, -0x6d,0x97,0x72,0x2d,0x2d,0x67,0xcf,0x3c,0xd7,0xe9,0x1a,0xd3,0xf3,0xad,0x84,0x3b, -0xb3,0x6c,0x0e,0x47,0xf3,0xd8,0xf1,0xc0,0x56,0xe2,0x1a,0xe0,0x36,0x38,0x1f,0x5e, -0x77,0x47,0x15,0xd7,0x05,0xb3,0x83,0xeb,0xae,0x3b,0xd8,0x94,0x63,0x47,0x09,0x33, -0xd0,0x76,0x52,0x1a,0x37,0xac,0x92,0x96,0x98,0xce,0xb4,0xc9,0xae,0xa4,0xa5,0xa6, -0x71,0x93,0x39,0xd0,0x85,0xa4,0x2c,0xce,0x44,0x76,0x9c,0x71,0x67,0xfa,0xa6,0x96, -0x4c,0x67,0x9e,0x3d,0xb2,0x82,0xcb,0xed,0x32,0x35,0xb4,0x86,0x3d,0xdf,0x38,0x89, -0x66,0x9f,0xb0,0xdb,0x65,0xd7,0x73,0xac,0xc4,0x6a,0xd3,0x16,0x3b,0x50,0x06,0xce, -0xd8,0x12,0xd3,0x76,0xd1,0xc0,0x58,0x4a,0x5a,0xc7,0xee,0x46,0x67,0x12,0x8b,0x07, -0x0a,0x27,0x99,0x06,0x48,0xd2,0x06,0xb6,0xb9,0xc4,0xa6,0x81,0x11,0xc5,0x0e,0xb1, -0x06,0x2e,0x61,0xcf,0xe3,0x2a,0xae,0x00,0xeb,0xb2,0x64,0xd3,0x3e,0xd3,0x70,0x61, -0x73,0x30,0xbd,0x1a,0xb9,0x8d,0x5c,0x8e,0xbd,0x7c,0xf2,0x06,0x06,0x20,0xab,0x97, -0xcb,0x55,0x62,0x73,0x39,0x26,0x99,0x3c,0xee,0xd0,0x12,0xd3,0x0e,0xb3,0x94,0x29, -0xc7,0x1e,0xcd,0x1f,0x38,0x05,0xa5,0x03,0x1b,0x5c,0x81,0x7c,0xae,0x33,0x59,0xa6, -0x5c,0x09,0x77,0x15,0xb3,0xb9,0x4a,0xee,0xb4,0x14,0x9b,0xaa,0x16,0x0c,0x9c,0x6b, -0xd3,0x06,0x77,0xa5,0x15,0x70,0x27,0x6d,0xc5,0x75,0xa1,0x42,0x6e,0x6c,0x72,0xc9, -0xf5,0x13,0x73,0xf3,0x38,0x4b,0xda,0x32,0x70,0x7d,0x98,0x73,0xec,0xbe,0x6d,0xa6, -0x8b,0x8e,0xb8,0xb6,0x92,0xae,0x17,0xdd,0x69,0xba,0xa0,0x4b,0x58,0xf7,0xb3,0xa3, -0x99,0xcd,0xd5,0x73,0x0e,0xe6,0xae,0x6f,0xd3,0x6d,0xc0,0x74,0x59,0x60,0x4e,0x55, -0x61,0x6a,0x61,0x60,0x04,0x07,0xf6,0xc0,0x7d,0x41,0x6c,0xa4,0x61,0x23,0x2d,0x1b, -0x05,0xb3,0x51,0x08,0x1b,0x85,0xb2,0x91,0x8e,0x8d,0xc2,0xd8,0x28,0x9c,0x2b,0x6c, -0xaa,0xc2,0xd5,0x09,0xe2,0x2a,0x05,0x71,0xb5,0x82,0xb8,0x6a,0x41,0x5c,0xbd,0x20, -0xae,0x62,0x10,0x57,0x33,0x88,0xab,0x1a,0xc4,0xd5,0xd5,0x70,0x75,0x35,0x26,0x3d, -0xae,0xae,0x86,0xab,0xab,0xe1,0xea,0x3e,0x3b,0x77,0x02,0x4d,0x9e,0x40,0x13,0x5e, -0xa0,0x89,0x13,0xe6,0xd1,0x9c,0x05,0x34,0x77,0x12,0x4d,0x9e,0x85,0x1f,0x0d,0xd0, -0xd2,0xb4,0x17,0xf0,0x3c,0xab,0xec,0x4e,0x5f,0x41,0xdd,0x1b,0x4a,0xd9,0xbb,0x13, -0xd6,0x40,0xec,0x93,0xa0,0x7b,0x43,0x66,0x37,0x56,0x82,0x78,0xb0,0x74,0xd5,0x67, -0x7d,0x54,0x9f,0xcd,0x3e,0x59,0xd0,0xd2,0xec,0x09,0x74,0xac,0x7e,0x02,0xcd,0x9a, -0x40,0x33,0xf0,0x33,0x91,0x66,0x4d,0xa4,0xa9,0x13,0x69,0xd2,0x84,0x99,0x34,0x83, -0x8d,0xe6,0x4e,0xa1,0xd9,0x53,0x50,0x82,0x65,0x2a,0xcd,0x9a,0x4a,0x33,0xa6,0xd2, -0xb3,0x2f,0xd3,0x0c,0x30,0x0b,0x4c,0x05,0xcf,0x83,0x63,0xf5,0x33,0x69,0xd6,0x4c, -0x9a,0x8c,0x5a,0x33,0x69,0xca,0x2c,0x9a,0x3d,0x0b,0xbb,0x66,0xd1,0xac,0x59,0x34, -0x69,0x16,0xcd,0x60,0x33,0x1a,0xe4,0x34,0x84,0x9f,0x19,0x6c,0x02,0x3b,0x27,0x01, -0xfc,0xcc,0x60,0x93,0xf3,0xe9,0x6b,0xe7,0x9b,0x62,0x1c,0x87,0x51,0xb3,0xc0,0x54, -0x30,0x6f,0xc2,0x64,0x16,0xee,0xb0,0x39,0xd5,0xd0,0xdc,0xf9,0x34,0x7b,0x3e,0x9a, -0x47,0x8d,0xf9,0x34,0x77,0x01,0xcd,0x5e,0x80,0x8d,0x05,0x34,0x6b,0x01,0xcd,0x80, -0x2f,0x16,0xd2,0xec,0x85,0xd8,0x5e,0x48,0xb3,0x16,0xd2,0x0c,0xfc,0xb4,0x2f,0xa1, -0x59,0x60,0xe2,0x73,0x34,0x69,0x12,0x4d,0x9a,0x4c,0x93,0xd0,0x08,0xfa,0x30,0x19, -0xdd,0x7c,0x89,0x9e,0x9d,0x00,0x6f,0xd2,0xb4,0xd9,0x34,0x63,0x06,0xcd,0x78,0x9e, -0x66,0xce,0xa2,0x99,0xb3,0x69,0xe6,0x9c,0xa9,0x34,0xf3,0x45,0x9a,0x35,0x0d,0x5d, -0x9a,0x03,0x0f,0x3c,0x4b,0x73,0xe7,0xce,0xa2,0xb9,0xf3,0x68,0x3e,0x7e,0x16,0xd0, -0xc2,0x89,0xb4,0x00,0x6d,0xcc,0xa2,0x09,0x5c,0x1c,0xc4,0x2e,0xeb,0x34,0x6c,0xa4, -0x65,0xa3,0x60,0x36,0x0a,0x61,0xa3,0x50,0x36,0xd2,0xb1,0x51,0x18,0x1b,0x85,0xb3, -0x11,0x9e,0x85,0x6c,0xcc,0xd5,0x09,0xe2,0x2a,0x05,0x71,0xb5,0x82,0xb8,0x6a,0x41, -0x5c,0xbd,0x20,0xae,0x62,0x10,0x57,0x33,0x88,0xab,0x1a,0xc4,0xd5,0xd5,0x70,0x75, -0x35,0x26,0x3d,0xae,0xae,0x86,0xab,0xab,0xe1,0xea,0x6a,0xb8,0xba,0x1a,0xae,0xae, -0x86,0xab,0xab,0xe1,0xea,0x6a,0xb8,0xba,0x5a,0xae,0xae,0x96,0xab,0x3b,0x15,0x67, -0xf5,0xe2,0xc6,0xc5,0x20,0x09,0xa4,0x80,0x34,0xb0,0x04,0x2c,0x07,0x59,0x60,0x25, -0x58,0x0d,0xd6,0x82,0xf5,0x60,0x23,0xc8,0x01,0x79,0xa0,0x00,0x14,0x82,0x22,0xb0, -0x15,0x14,0x83,0x1d,0xa0,0x04,0x94,0xd2,0xc5,0x6c,0xb4,0x9b,0x8d,0x76,0xb3,0xd1, -0x6e,0x36,0xda,0xcd,0x46,0xbb,0xd9,0x19,0x00,0x6d,0x67,0xa3,0xed,0x6c,0xb4,0x9d, -0x8d,0xb6,0xb3,0xd1,0x76,0x36,0xda,0xce,0x46,0xdb,0xd9,0x68,0x3b,0x17,0xed,0xe5, -0xa2,0xbd,0x5c,0xb4,0x97,0x8b,0xf6,0x72,0xd1,0x5e,0x2e,0xda,0xcb,0x2d,0x03,0x95, -0x60,0x1f,0xa8,0x02,0x35,0xa0,0x0e,0x34,0x80,0x26,0xba,0x98,0x07,0xbd,0x3c,0xe8, -0xe5,0x41,0x2f,0x0f,0x7a,0x79,0xd0,0xcb,0x83,0x5e,0x1e,0xf4,0xf2,0xa0,0x87,0xa5, -0xdd,0xc5,0x3c,0xe8,0xe5,0x41,0x2f,0x0f,0x7a,0x79,0xd0,0xcb,0x83,0x5e,0x1e,0xfa, -0x92,0x87,0xbe,0xe4,0xa1,0x2f,0x79,0xd0,0xce,0x83,0x76,0x1e,0xb4,0xb1,0xfc,0xbb, -0x98,0x07,0xed,0x3c,0x68,0xe7,0x41,0x3b,0xaf,0x16,0xd4,0xd3,0xb9,0x7d,0xd0,0xcd, -0x83,0x5e,0x3e,0xf4,0xf2,0xa1,0x97,0x0f,0xbd,0x7c,0xe8,0xe5,0x2f,0x03,0xd0,0xc8, -0x87,0x46,0x3e,0xda,0xcf,0x47,0xfb,0xf9,0x68,0x3f,0x1f,0xed,0xe7,0xa3,0xfd,0x7c, -0xb4,0x9f,0x8f,0xf6,0xf3,0xd1,0x7e,0x3e,0xda,0xcf,0xdf,0x41,0x6d,0xbb,0xe8,0x48, -0x3e,0x1d,0x41,0xe5,0x52,0xb6,0x12,0x3a,0x96,0x8f,0x8e,0xe5,0x43,0x20,0x1f,0x1d, -0xcb,0x47,0xc7,0xf2,0x21,0x54,0x00,0xa1,0x02,0x56,0x08,0x2b,0x8d,0xfd,0x99,0xc8, -0xa7,0x83,0xa5,0xd4,0xb6,0x05,0x09,0xfa,0x56,0x80,0xbe,0x15,0x40,0xb7,0x00,0x4d, -0x14,0xa0,0x6f,0x05,0xd0,0x2e,0x80,0x36,0x96,0xf2,0x87,0x20,0x5f,0xb0,0x9f,0x2e, -0xee,0x42,0xab,0xa5,0xab,0xe8,0x08,0x96,0x6c,0x99,0x58,0x12,0x65,0x62,0x89,0x96, -0x89,0x65,0x51,0x26,0x96,0x45,0x99,0x58,0xa2,0x65,0x62,0x89,0x96,0x89,0x25,0x5a, -0x26,0x96,0x48,0x99,0x58,0xa2,0x65,0x62,0x99,0x94,0x89,0x25,0x5a,0x26,0x96,0x4a, -0x99,0x58,0x2a,0x65,0x62,0xa9,0x94,0x89,0xa5,0x52,0x26,0x96,0x4a,0x99,0x58,0xa2, -0x65,0x62,0x69,0x94,0x89,0xa5,0x51,0x26,0x96,0x68,0x99,0x58,0xa2,0x65,0x62,0x89, -0x96,0x89,0xe5,0x53,0x66,0x15,0xa8,0x06,0x35,0xa0,0x16,0xd4,0x01,0x78,0x2c,0xb3, -0x01,0x34,0x82,0x26,0x3a,0x97,0x85,0x25,0x56,0x16,0x96,0xa5,0x59,0x58,0x92,0x66, -0x61,0x29,0x9a,0x85,0x25,0x55,0x16,0x96,0x54,0x59,0x58,0x6e,0x66,0x61,0xe9,0x95, -0x85,0xa5,0x55,0x16,0x96,0x9a,0x59,0x58,0x6a,0x66,0x61,0xa9,0x99,0x85,0xa5,0x58, -0x16,0xec,0xce,0xc2,0x72,0x2f,0x0b,0x4b,0xcd,0x2c,0x2c,0x35,0xb3,0xb0,0xf4,0xca, -0xc2,0xd2,0x2b,0x0b,0xcb,0xbf,0x2c,0x38,0x25,0x0b,0x4b,0xc3,0xac,0x75,0x00,0x4b, -0xb5,0x2c,0x2c,0xd5,0xb2,0xb0,0x54,0xcb,0xc2,0x12,0x36,0x2b,0x07,0xb0,0xdf,0xed, -0x61,0x39,0x98,0x85,0x25,0x5a,0x16,0x96,0x86,0x59,0xe8,0x7f,0x16,0xfa,0x9f,0x85, -0xfe,0x67,0xa1,0xff,0x59,0xe8,0x7f,0x16,0xfa,0x9f,0x85,0xfe,0x67,0xa1,0xff,0x59, -0xe8,0x7f,0x16,0xfa,0x9f,0x85,0xfe,0x67,0xa1,0xff,0x59,0xe8,0x7f,0x16,0xfa,0x9f, -0x85,0xfe,0x67,0x95,0x51,0x6f,0x79,0x3a,0x75,0xe7,0xec,0xc5,0x7c,0x19,0x29,0x16, -0xee,0x1f,0x55,0x57,0x60,0x4e,0xbd,0x95,0xba,0xb6,0x62,0x9e,0xbd,0x0e,0x73,0xe8, -0xad,0xd8,0x9f,0xc6,0xbe,0x58,0xd9,0x41,0x3d,0x8d,0x29,0xd4,0xbb,0xa1,0x89,0x7a, -0xf3,0x6b,0xa9,0xb7,0xa8,0x9a,0xfa,0x12,0xb3,0xa8,0x7b,0x7b,0x22,0x75,0xef,0xcd, -0xa1,0x9e,0xa4,0x8d,0xd4,0x03,0x9b,0x7a,0x57,0x60,0xd1,0x8f,0xe5,0x70,0x5f,0x71, -0x39,0xe6,0xfd,0x89,0x98,0x83,0xef,0xa3,0xee,0x5d,0xc9,0xd4,0xc3,0xbe,0x20,0xd9, -0x50,0x4a,0x7d,0xd5,0xf9,0xd4,0xb5,0x0f,0xf7,0xef,0xa6,0x12,0xea,0x5d,0xbf,0x9c, -0x7a,0xb7,0x6e,0xa1,0xee,0x0c,0xf6,0xa5,0xca,0x06,0xea,0xdd,0x54,0x40,0x5d,0x75, -0x4b,0xb1,0x36,0x58,0x4f,0xdd,0xfb,0x76,0x52,0x4f,0x46,0x3d,0xf5,0x61,0xa6,0xf2, -0x51,0x63,0x2a,0xe6,0xfc,0x55,0xd4,0x95,0x91,0x4f,0xdd,0xab,0x93,0xa9,0xbb,0x64, -0x35,0xda,0x5b,0x81,0xb9,0x7e,0x31,0xda,0x4c,0xa5,0xde,0x8d,0xb9,0xd4,0x5b,0x55, -0x46,0x7d,0xb9,0x15,0xd4,0x57,0x8a,0xb4,0xaa,0x96,0x7a,0x36,0x2f,0xc3,0x7a,0xa2, -0x89,0x7a,0xf6,0x6f,0xa2,0x5e,0xf8,0xbf,0x6f,0x59,0x32,0xf5,0x96,0xac,0xa3,0xae, -0x22,0x68,0xd4,0xc3,0x9e,0x72,0xec,0x5f,0xdc,0x88,0xb5,0xc7,0x66,0xea,0x29,0x5a, -0x8a,0xfe,0x27,0x52,0x5f,0x0e,0x34,0x8a,0x36,0x50,0x57,0xf9,0x66,0xf4,0x6b,0x35, -0x75,0x57,0x65,0x53,0x77,0x7d,0x16,0xf5,0xec,0x2d,0xa3,0x9e,0x6a,0xac,0x47,0x36, -0x66,0xc0,0x86,0x55,0xd4,0x9b,0x88,0x34,0x2d,0x17,0x40,0x63,0x7b,0x2e,0x34,0x1a, -0xa1,0x51,0x8e,0xe3,0xfb,0xa8,0x77,0x37,0x83,0xfe,0x64,0x41,0xab,0x11,0xbe,0xac, -0xa1,0xae,0xb2,0x62,0xea,0x66,0x56,0x51,0x4f,0x66,0x1a,0xf5,0xac,0xdd,0x83,0xb5, -0xca,0x7a,0xe8,0xd5,0xa1,0x4f,0x4d,0xd4,0xd5,0xb8,0x03,0x65,0x96,0x63,0x6d,0xb3, -0x8c,0xba,0xd7,0x56,0x43,0x67,0x33,0x7c,0x9f,0x44,0x5d,0x85,0xf9,0xd4,0x93,0x8b, -0x35,0xcc,0x4a,0xf8,0x65,0x27,0xd6,0x4a,0xbb,0x6b,0xa9,0xbb,0x02,0xe7,0x21,0x03, -0x3a,0x19,0x5b,0xa9,0x1b,0x63,0xbe,0x67,0xed,0x56,0xf8,0x77,0x37,0xd6,0x55,0x58, -0x23,0xa5,0x2d,0xa1,0xee,0xcd,0x8b,0xa9,0xa7,0x12,0xfe,0x58,0x82,0x73,0x5a,0xb2, -0x8a,0xfa,0xd2,0xb0,0xf4,0xcb,0xd8,0x47,0x5d,0x2b,0x71,0x0e,0xea,0x76,0x51,0xf7, -0xfa,0x14,0xf8,0x1c,0xfd,0xdd,0x82,0x73,0xb3,0x0e,0xe7,0x61,0x07,0xd2,0xda,0xf5, -0xd4,0x57,0x97,0x89,0xf3,0x9f,0x8a,0xf5,0x54,0x15,0xf5,0x36,0x40,0x1f,0xab,0xb9, -0xee,0x54,0x9c,0x9f,0x74,0xf4,0x63,0x15,0xdb,0xff,0x22,0xea,0x49,0xc1,0x5a,0x6d, -0x15,0x28,0x5e,0x4a,0x3d,0x55,0x18,0x2b,0x8b,0xa1,0x51,0xbf,0x8d,0x7a,0x57,0xef, -0xa6,0x3e,0xa6,0x88,0xfa,0x96,0x2f,0xa5,0xae,0x74,0xac,0xbf,0x96,0x62,0x4d,0xb6, -0xaa,0x01,0x63,0x21,0x1d,0xe3,0x83,0xd5,0x5d,0x42,0x5d,0x4d,0x38,0xff,0xcb,0xf1, -0x68,0xde,0xbd,0x9b,0x7a,0xf6,0x40,0x1f,0xe3,0x01,0x2b,0x0b,0xea,0xca,0x81,0x6f, -0xf6,0xa3,0x5f,0x0c,0xfc,0x87,0x6b,0xaf,0x67,0x25,0x3b,0xbe,0xb2,0xd1,0x76,0x2a, -0xf5,0xa5,0xef,0xc5,0xb9,0xd8,0x4f,0x7d,0x79,0xe9,0x58,0xf3,0x6d,0x80,0xaf,0x32, -0xa8,0x67,0x1b,0xb4,0x52,0xb1,0x3f,0xbb,0x9a,0xba,0xb1,0xa2,0xf9,0xa8,0x16,0x63, -0x22,0x29,0x1b,0xfe,0x85,0x0f,0xf6,0x34,0x51,0xf7,0x3a,0x8c,0xbf,0xb4,0x4c,0x8c, -0xd3,0x44,0xd8,0x85,0x71,0xb3,0xb8,0x9e,0xba,0xb3,0x51,0x7f,0x03,0x8e,0x2f,0x85, -0x7f,0xf2,0x60,0x43,0x41,0x25,0xc6,0xd5,0x62,0xea,0xae,0x85,0xe6,0x0a,0xf4,0x67, -0x2d,0xea,0x14,0x96,0xc0,0xef,0x2b,0xa8,0x0f,0x3e,0xef,0x4e,0x87,0xc6,0xc6,0x6a, -0xea,0x62,0x4a,0xa8,0x6b,0x2f,0xd6,0x98,0x55,0x3b,0xd1,0x4f,0xac,0x3f,0xa1,0xdf, -0x9d,0x82,0x71,0xb7,0x09,0xfe,0xca,0x86,0x6e,0x3a,0x7c,0xbe,0x02,0xfe,0x2d,0xc7, -0xb9,0xd8,0x80,0x71,0x92,0x07,0x1f,0x6e,0xde,0x8e,0xf3,0xb8,0x15,0xed,0xa6,0x52, -0xcf,0x7a,0x8c,0xa9,0x06,0xac,0x69,0x8b,0x30,0x0e,0x8a,0x0a,0xd1,0x17,0xf8,0x75, -0x19,0x6c,0x64,0x5f,0x10,0xaf,0xc8,0x83,0x9d,0x18,0xbb,0xab,0x30,0xde,0xd7,0xd7, -0xfe,0x3f,0xf6,0xde,0x06,0xa8,0xa9,0x6b,0xed,0xfb,0x5e,0x51,0x50,0xa2,0x50,0x82, -0x82,0x82,0x82,0x05,0x25,0x0a,0x96,0x40,0x52,0x93,0x96,0x20,0xb4,0xa0,0xa0,0x04, -0x12,0xbe,0xa3,0x44,0x41,0xa1,0x05,0x4c,0x20,0x91,0x04,0x12,0x20,0x90,0x40,0x02, -0x49,0x48,0x42,0x62,0x49,0x05,0x0a,0x2d,0xb4,0xa0,0xa0,0x60,0xc1,0x8a,0x10,0x05, -0x0b,0x56,0xee,0x91,0xe7,0x96,0x3e,0x32,0x23,0x33,0x72,0x17,0x5a,0x79,0x47,0x4e, -0x09,0xc2,0x3d,0xf2,0x0e,0xcc,0xc8,0x8c,0xcc,0xc8,0xcc,0xbb,0x56,0xd8,0xf6,0xf5, -0x9c,0xe7,0x9c,0xfb,0x7c,0xf5,0x9c,0xe7,0x7c,0x90,0x5f,0xd7,0x7f,0xed,0xf5,0xb1, -0xf7,0x5e,0xeb,0xba,0xae,0xb5,0xf6,0x8e,0x61,0xa6,0xf0,0x7a,0xd0,0x7e,0xdd,0xf0, -0xba,0x77,0xbe,0x02,0xb3,0x70,0x97,0x9d,0xbd,0x5d,0x05,0xd7,0x42,0x3b,0x78,0xd6, -0x09,0x7d,0x7c,0x13,0xc6,0x4d,0x95,0x02,0x3c,0x2b,0x6f,0x00,0x73,0x5d,0xd0,0x0e, -0xdf,0x2a,0xc0,0x9c,0xe1,0x16,0xbc,0x3f,0xbc,0x8e,0x16,0xae,0xcd,0x3b,0x57,0x60, -0x4c,0xc0,0xb5,0xd0,0x03,0xe3,0xfa,0x3a,0xf4,0x6f,0x2f,0x9c,0xc3,0xe7,0xd0,0x3f, -0xe8,0x1f,0xda,0xe0,0x13,0xcf,0xf2,0xed,0x45,0x18,0x1f,0x0a,0x60,0xf9,0x0c,0xa6, -0x16,0xe8,0xcb,0x86,0x5e,0x18,0x2b,0x30,0xb6,0x0c,0x70,0x6d,0x7d,0x01,0x7d,0xd9, -0x3a,0x00,0xd7,0x08,0x2c,0xb7,0xc1,0x71,0x5f,0xf9,0x04,0xda,0xbb,0x0e,0xde,0x13, -0xc6,0x58,0x3d,0x8c,0xf1,0xaf,0xe1,0xfa,0x56,0xc0,0x54,0x01,0xd7,0xf3,0x65,0xb8, -0xa6,0x2e,0x43,0x9b,0xb6,0xc2,0xef,0xe0,0xb7,0xa0,0x0f,0xe0,0x77,0xab,0xf9,0xcf, -0x6f,0x43,0xbf,0x40,0xdb,0x56,0x5c,0x85,0xf7,0x80,0xf7,0x82,0x6b,0xd8,0x52,0x05, -0xfd,0x6a,0x44,0xfb,0x06,0xfc,0x1e,0x0f,0xd7,0xa5,0xa5,0xa1,0x1d,0xde,0x17,0xde, -0x1b,0xda,0xc6,0xd2,0x0d,0xd7,0x79,0x79,0x0d,0xb4,0x23,0xb4,0x93,0x06,0xda,0xab, -0xf2,0x26,0x8c,0x79,0xb8,0x7f,0x40,0x5b,0xcd,0xc2,0x27,0xe7,0xec,0x25,0x38,0x7e, -0xf3,0x6d,0x30,0xdb,0x87,0x62,0x0e,0xda,0x4f,0x0d,0xe3,0x45,0x0b,0x7d,0x53,0x0d, -0x8f,0x2f,0x99,0xe0,0x18,0xa1,0xbf,0xe0,0x5e,0xf4,0xac,0x0d,0xda,0xae,0x0d,0x8e, -0xf3,0x8a,0x11,0x26,0xe8,0xef,0x0e,0x68,0x9f,0x6b,0x30,0xf6,0xbf,0x81,0x79,0x1f, -0xec,0xd3,0x0f,0x8f,0x07,0x6f,0x82,0x39,0x05,0xdc,0xab,0x2a,0xbb,0xe0,0x7a,0x80, -0x7e,0x30,0x7d,0x06,0xe6,0x5a,0xab,0xc1,0xdc,0x95,0x3a,0x30,0xd7,0x09,0xd7,0x55, -0x27,0xac,0xeb,0xb9,0x08,0xe6,0x7a,0x61,0x9c,0xde,0x85,0x71,0xf6,0x05,0xf4,0xc1, -0x57,0xdf,0xc1,0x58,0x83,0x31,0xa2,0x34,0x83,0xc5,0xd6,0xaa,0xeb,0x60,0x4e,0x0b, -0x0d,0xde,0x77,0x05,0x6e,0x3c,0x70,0x11,0xc1,0x41,0xcf,0xdc,0x85,0x13,0x51,0xab, -0x61,0x19,0xe6,0x55,0xd0,0xf8,0x55,0xd0,0x09,0xb5,0xb5,0x70,0xb2,0x0d,0xd0,0xc0, -0xd0,0xc1,0x97,0x7a,0xe0,0x66,0xa9,0x82,0xa9,0x06,0x58,0x3a,0x60,0xb9,0x13,0x4e, -0xfa,0xdb,0x4f,0x61,0x82,0xed,0x83,0x30,0x60,0xee,0x76,0xc1,0xc0,0xad,0x87,0x06, -0x80,0x93,0x57,0xc1,0xc5,0xac,0x6e,0x86,0x01,0x07,0x17,0x1b,0x7c,0x60,0xcc,0x56, -0x37,0x82,0x59,0xd3,0xa7,0xd0,0x20,0x75,0x70,0xf3,0xfb,0x02,0x06,0x14,0xcc,0xbf, -0x85,0xf9,0xb7,0x30,0xf0,0x15,0xd0,0x41,0xf0,0xf1,0xfa,0x4c,0x6b,0x06,0xcf,0xf4, -0x70,0x23,0x32,0x75,0x83,0x67,0x35,0x30,0xc8,0x6a,0xbe,0x05,0xcf,0xea,0x61,0x30, -0xd5,0x7f,0x05,0x9d,0x09,0x37,0x60,0xb8,0x89,0x3f,0x6b,0x82,0x4e,0x6d,0x82,0x86, -0xb8,0x0c,0x37,0xa6,0x6b,0xb0,0x5f,0x37,0xec,0x63,0x86,0x6d,0x03,0xd0,0xa9,0x46, -0xe8,0x54,0xb4,0xe1,0x37,0xc1,0xc9,0xb7,0x41,0x23,0x5c,0x81,0x1b,0xe7,0x35,0xb8, -0x99,0x7f,0x0d,0x03,0xee,0x6b,0x68,0xa8,0xeb,0x70,0x13,0x1c,0x80,0x0e,0x57,0xc2, -0x4d,0x54,0xd3,0x00,0xe6,0x75,0xd0,0x30,0x0d,0xd0,0xe9,0xf0,0xb1,0x3b,0xdf,0x5c, -0x05,0xe6,0x3b,0x3f,0x05,0x8b,0x97,0x5a,0xf4,0x48,0x54,0x60,0xf1,0x32,0x7c,0x46, -0xfd,0x7c,0xbd,0x09,0xcc,0x28,0xa0,0x99,0x14,0xfd,0x60,0xb1,0x4d,0xa7,0x83,0xd2, -0x53,0x0d,0x16,0xaf,0xc2,0xb0,0x9b,0x1f,0xac,0x00,0xf3,0x77,0x2f,0x80,0xac,0x2c, -0x90,0xc5,0x03,0x59,0xf0,0xbd,0x19,0x65,0x30,0xcf,0x17,0x83,0xf1,0x5e,0xf4,0xc7, -0x4b,0xbd,0xe8,0x8f,0x9e,0x7a,0xd1,0xdf,0x39,0xdd,0x5d,0x2b,0x76,0x81,0x1f,0x1a, -0xfe,0xab,0x17,0xfc,0x70,0xf3,0xbf,0x6e,0x83,0x1f,0x2e,0x81,0x1f,0x6a,0xc0,0x0f, -0x5f,0x80,0x1f,0x1a,0xc1,0x0f,0x4d,0xe0,0x87,0x76,0xf0,0xc3,0x35,0xf0,0x43,0xc7, -0x0f,0x4a,0x24,0xe5,0x50,0xfe,0x6b,0xc0,0x7a,0x0c,0x33,0x58,0xaa,0x46,0x67,0x54, -0xff,0x57,0x1f,0x92,0x01,0xf0,0x83,0x09,0xc9,0xa7,0x48,0x2e,0x22,0xa9,0x41,0x52, -0x8b,0xa4,0x0e,0x49,0x3d,0x92,0x06,0x24,0x9f,0x23,0xf9,0x02,0x49,0x23,0x92,0x2f, -0x91,0x34,0x23,0x69,0x41,0x72,0x19,0x49,0x2b,0x92,0x2b,0x48,0xae,0x22,0x69,0x47, -0xd2,0x81,0xe4,0xda,0xda,0x45,0xfb,0xd1,0xdd,0xbe,0x43,0x57,0xf9,0x0e,0x75,0x86, -0x52,0x0d,0x47,0x3c,0xd9,0x0d,0x26,0xbf,0x05,0x93,0x77,0xc1,0x8f,0x0a,0x30,0x79, -0x07,0x4c,0x7e,0x07,0x26,0xfb,0xc1,0x8f,0xad,0xe0,0xc7,0x2b,0xe0,0x47,0x15,0xf8, -0xb1,0x02,0xfc,0xa8,0x01,0x3f,0x56,0x82,0x1f,0x8d,0xe0,0x47,0x03,0xf8,0xf1,0x02, -0xf8,0x51,0x0b,0x7e,0xac,0x07,0x3f,0x9a,0xc0,0x8f,0x1d,0xe0,0xc7,0x6f,0xc0,0x8f, -0x3d,0xe0,0xc7,0x6e,0xf0,0xe3,0x1d,0xf0,0xe3,0xb7,0xe0,0x27,0x05,0xf8,0x49,0x09, -0x7e,0xbc,0x0b,0x7e,0xfa,0x14,0xfc,0x74,0x11,0xfc,0xd8,0x05,0x7e,0xaa,0x04,0x3f, -0x69,0xc0,0x4f,0x5a,0xf0,0x53,0x15,0xf8,0x49,0x0d,0x7e,0xd2,0x81,0x9f,0xaa,0xc1, -0xa4,0x0e,0x4c,0x5c,0x99,0xb8,0x0a,0xe5,0xa7,0x5a,0x28,0x93,0x5a,0x74,0x54,0x89, -0x44,0x83,0xc4,0x5a,0xac,0x46,0x0d,0xb0,0xb7,0x01,0x75,0xed,0x44,0xd2,0x85,0x6a, -0xd4,0x48,0xf4,0x60,0xa2,0x1d,0xd5,0xb5,0xa3,0xba,0xf6,0x89,0xeb,0x50,0x50,0x43, -0x3b,0xba,0x6e,0x3b,0x6a,0xbd,0x86,0x5a,0xaf,0xa1,0xd6,0x6b,0xa8,0xf5,0x1a,0x6a, -0xbd,0x86,0x5a,0xaf,0xa1,0xd6,0xaf,0x51,0xeb,0xd7,0xa8,0xee,0x6b,0x54,0xf7,0x35, -0xaa,0xeb,0x44,0x9d,0x3b,0x51,0x5d,0x17,0x6a,0xed,0x42,0x47,0xd7,0xd1,0xd1,0x75, -0xd4,0x70,0x1d,0x15,0x7b,0x50,0xb1,0x07,0x15,0x7b,0xd0,0x45,0x7b,0x50,0x9d,0x19, -0x15,0xcd,0xe8,0xe8,0x16,0x6a,0xbd,0x85,0x8a,0xb7,0x50,0xeb,0x2d,0x54,0x77,0x1b, -0x15,0x6f,0xa3,0xa3,0x3e,0x24,0xfd,0xa8,0x4b,0x3f,0x3a,0xba,0x83,0x8e,0xee,0xc0, -0xa3,0x49,0x25,0x3c,0x82,0xd2,0x85,0xe4,0x3a,0x14,0x6b,0x1d,0x1c,0x15,0x14,0x3d, -0x98,0x2c,0x47,0x0d,0xe5,0xa8,0xae,0x1c,0xd5,0x95,0xa3,0xba,0x0a,0x68,0x38,0x28, -0x9d,0x48,0xba,0x90,0xc0,0xd3,0x2a,0x26,0x55,0x48,0xd4,0x48,0x74,0x48,0x60,0x3f, -0x15,0xea,0xa2,0x42,0x5d,0x54,0xa8,0x8b,0x0a,0xb5,0xaa,0x50,0xab,0x0a,0xb5,0xaa, -0x51,0xab,0x1a,0xb5,0xaa,0x51,0xab,0x1a,0xb5,0xaa,0x51,0xab,0x1a,0xb5,0x6a,0x50, -0xab,0x06,0xb5,0x6a,0x50,0xab,0x06,0xb5,0x6a,0x50,0xab,0x06,0xb5,0x56,0xa2,0xd6, -0x4a,0x54,0x57,0x89,0xea,0x2a,0x51,0x9d,0x1e,0xd5,0xe9,0xd1,0x19,0x7a,0x74,0x86, -0x1e,0xb5,0xea,0x51,0xab,0x1e,0x59,0xf7,0xc6,0xe4,0x0d,0x30,0xd1,0x0d,0x65,0x52, -0x07,0xc5,0x73,0xd2,0x30,0x69,0x82,0x6a,0xb4,0xea,0x05,0xab,0x7e,0x62,0xd5,0x6a, -0xab,0x9a,0x50,0xef,0x2b,0x13,0xdd,0x48,0x6e,0x22,0x7f,0x6b,0x90,0x97,0xbb,0x91, -0xdc,0x44,0x0e,0xd6,0x20,0xb7,0x76,0x23,0xb9,0x89,0x3c,0xaa,0x41,0x1e,0xed,0x46, -0x72,0x13,0x39,0x53,0x83,0xa6,0x74,0x15,0x8d,0xbc,0x1b,0xc9,0x4d,0x34,0x68,0x0d, -0x1a,0x56,0x37,0x92,0x9b,0x68,0x44,0x28,0xca,0x90,0x93,0xae,0x4c,0x56,0xa2,0xeb, -0x55,0xa2,0xab,0x54,0x22,0x67,0x5a,0xed,0x54,0x89,0xce,0xa8,0x44,0xf3,0xba,0x81, -0x3a,0x57,0xa2,0x8b,0x56,0x22,0x7f,0x43,0xe9,0x45,0xde,0xeb,0x45,0xad,0x0a,0xeb, -0xc0,0x61,0xf6,0xc9,0x5a,0x86,0x86,0x0e,0x7d,0xad,0x43,0xa2,0x47,0x6e,0xd6,0x21, -0xd1,0x23,0x37,0xeb,0x90,0xe8,0xd1,0x15,0x74,0x48,0xf4,0xe8,0x0a,0x3a,0x24,0x7a, -0x14,0x68,0x3a,0x24,0x28,0x02,0xd1,0x51,0x27,0x3a,0xba,0x8e,0x8e,0xae,0xa3,0x23, -0x33,0x3a,0x32,0xa3,0xa3,0x5b,0xe8,0xe8,0x96,0xf5,0x5c,0x14,0x3b,0xbd,0x28,0xb2, -0x7a,0xd1,0x1c,0x7a,0xd1,0xd4,0x7b,0x90,0x98,0x91,0xdc,0x42,0x72,0x75,0xb2,0xca, -0xba,0x06,0xac,0x61,0xbf,0x16,0xd0,0xd7,0xd6,0x42,0xfa,0xda,0x5a,0x28,0x5f,0xb3, -0xfa,0xdf,0x9a,0x75,0xad,0x65,0xd7,0xad,0xd1,0x8f,0x4a,0x5d,0xd6,0x10,0xb0,0x66, -0x3a,0x6b,0xbc,0xaf,0x85,0x7d,0xe7,0x5a,0xe0,0x77,0xae,0xcd,0xc1,0xda,0xb3,0x67, -0xed,0x2a,0x3d,0xd6,0xe8,0x41,0x4b,0x01,0x5b,0x0c,0x56,0x1b,0xad,0xdd,0xaf,0x77, -0x6d,0x46,0xbd,0x6b,0x77,0xe8,0x5d,0x6b,0xbb,0xb5,0x36,0xeb,0x5b,0x6b,0x63,0xb9, -0xbd,0x76,0xb1,0xdb,0x6b,0x6d,0xb7,0xd7,0xee,0xde,0xbf,0x36,0xf8,0xfe,0xb5,0xca, -0xfe,0xb5,0xb1,0xdc,0x59,0x2b,0xdd,0x59,0xeb,0x72,0x67,0x2d,0x5e,0x95,0xd6,0xab, -0xa0,0x45,0x82,0xad,0x15,0x6b,0x9c,0x5b,0xef,0x6e,0xcd,0xf4,0x6b,0x99,0xce,0xba, -0x20,0xd6,0x96,0xc4,0xf5,0xb5,0xa5,0x80,0x45,0x7f,0x17,0xb6,0x12,0xac,0x2b,0x60, -0xed,0x04,0xb5,0x75,0xb6,0x28,0x5b,0xab,0xbc,0xbe,0xd6,0xe5,0xfa,0x5a,0xa9,0x13, -0x85,0x49,0xe5,0xda,0x0a,0xaa,0x5c,0xbb,0x9f,0x66,0xed,0x74,0xcd,0xda,0x8d,0x34, -0x6b,0xe7,0x69,0xac,0xc6,0x42,0x8b,0xc7,0xba,0xa4,0xd6,0x86,0xab,0x5f,0x9b,0x43, -0xfb,0x9a,0x7f,0xaf,0xad,0x99,0xe7,0xda,0x9a,0x59,0xaf,0xbd,0xae,0xbc,0xbe,0xb6, -0x55,0x59,0xa7,0x79,0x6d,0x6d,0xee,0x9d,0x6b,0xa5,0xce,0x35,0xd3,0x75,0xbe,0x76, -0x8e,0xb5,0xa7,0x79,0x2d,0x80,0x7a,0xd7,0xb2,0x5b,0xaf,0x27,0xdd,0x69,0xcd,0xd6, -0xee,0xae,0x5f,0xab,0xd4,0xaf,0x55,0xea,0xd7,0x2a,0xd5,0x6b,0x59,0xf9,0xeb,0x35, -0xdf,0xb5,0x16,0xb8,0xd6,0x52,0xc5,0x2f,0x1b,0x01,0xb6,0x47,0xbc,0xbe,0xa6,0x7a, -0xad,0x4d,0xbd,0x36,0x16,0xbd,0x75,0xbf,0xc4,0x6c,0x86,0x32,0xe5,0xda,0x38,0xdb, -0xd7,0xda,0x7a,0xd6,0xce,0xd3,0xac,0x4d,0xd3,0x3c,0xa9,0x82,0xcf,0x05,0x78,0x3f, -0x94,0xc1,0x20,0x55,0x59,0x17,0x1b,0x3c,0xa8,0xb0,0x2e,0xef,0x35,0x27,0x4c,0x7c, -0x63,0xed,0xb8,0xb6,0x4f,0x76,0xc3,0xe0,0xd2,0xc2,0xbd,0x0d,0x96,0x54,0xd6,0xa5, -0x38,0xa9,0x85,0x35,0x2a,0x6b,0xb8,0x59,0x37,0xb3,0xb5,0xcc,0xf3,0xf5,0xc5,0x3c, -0x5f,0x77,0xf4,0xfc,0xff,0x3b,0x76,0x4e,0xaa,0x3c,0x91,0x58,0xfb,0xc0,0xdb,0x75, -0xff,0x64,0x40,0x87,0xc0,0x0f,0xfc,0xac,0x50,0x82,0x20,0xe0,0x05,0x3e,0x84,0x47, -0x75,0x30,0x7d,0x06,0x7e,0xa3,0x40,0x7f,0x56,0x75,0x11,0x9c,0x05,0x25,0x40,0x0e, -0x6b,0x6a,0x60,0x82,0x2f,0x0e,0x8a,0x6a,0x98,0x4c,0x30,0xe9,0x61,0xaa,0x82,0xc9, -0x00,0x93,0x11,0xa6,0x0b,0x30,0x7d,0x02,0x4e,0x83,0x54,0xb0,0x0f,0xec,0x07,0x07, -0x01,0x09,0x04,0x83,0x0f,0x40,0x0a,0xf0,0x06,0x44,0x10,0x0a,0x77,0xb2,0x2a,0xb4, -0x33,0x54,0xa1,0x0d,0x0f,0x6d,0x77,0x68,0xb3,0xb3,0x6e,0x1c,0x68,0xbf,0xb3,0x6e, -0x1d,0x68,0xcb,0xb3,0x6e,0x1e,0x68,0xd7,0x43,0x07,0x68,0xfb,0xfb,0x14,0x1d,0x40, -0x03,0xb5,0x80,0x89,0x4b,0x60,0xe2,0x32,0x98,0x68,0x05,0x13,0x6d,0x70,0xb3,0x02, -0xe8,0x89,0xd9,0x0e,0x26,0x3a,0x60,0x50,0xc0,0x3d,0x09,0x58,0x9f,0x53,0x00,0xad, -0x2b,0x68,0x32,0xb4,0xbf,0x02,0xb4,0x01,0xf6,0xc0,0x40,0x80,0x66,0x81,0x71,0x00, -0x17,0x13,0x7c,0xf0,0x40,0xdb,0xc1,0xb5,0x02,0x1d,0x03,0x0d,0x0f,0x5d,0x07,0xd0, -0x93,0x02,0x05,0x27,0xb0,0x5a,0x13,0xac,0xb9,0xf5,0x12,0x92,0xcb,0x48,0xda,0x90, -0x5c,0x05,0x7b,0xc1,0x01,0x10,0x00,0xce,0x00,0x19,0x28,0x05,0xbf,0xb9,0xa2,0x86, -0x09,0xfd,0xa2,0x83,0x7e,0xe9,0x41,0x3f,0xa4,0x5c,0x86,0xa9,0x0d,0xa6,0xab,0x30, -0xa1,0x7f,0xc8,0x85,0xe5,0x0a,0x58,0x86,0xef,0xd6,0x3f,0x57,0x54,0x80,0xb5,0x7f, -0xd2,0x45,0x3f,0x28,0x34,0x00,0xf4,0xc3,0xf8,0x7f,0x5c,0x02,0xff,0x71,0x19,0xfc, -0x47,0x27,0xf8,0x8f,0x2b,0xe0,0x3f,0xda,0xc0,0x6f,0xe0,0x29,0xbf,0xa9,0x29,0x07, -0xbf,0x81,0x5f,0xdb,0x7e,0xa3,0x31,0xc1,0xf4,0x29,0x4c,0x17,0xc1,0x6f,0xea,0x9a, -0xc1,0x6f,0x3e,0xab,0x02,0x8b,0xd5,0xd5,0xed,0x48,0x3a,0x90,0x5c,0x43,0xf2,0x35, -0x92,0x4e,0x24,0x5d,0x48,0xae,0x23,0xf9,0x06,0xc9,0x0d,0x24,0xdd,0x48,0x6e,0x22, -0xe9,0x41,0xd2,0x8b,0xc4,0x8c,0xe4,0x16,0x92,0xdb,0x48,0xfa,0x90,0xf4,0x23,0xb9, -0x83,0xe4,0x5b,0x24,0x03,0x48,0x06,0x91,0xdc,0x45,0xf2,0x1d,0x14,0x93,0x02,0x89, -0x12,0x49,0x39,0x92,0x0a,0x24,0x2a,0x24,0x6a,0x24,0x1a,0x24,0x95,0x48,0xb4,0x48, -0x74,0x48,0xf4,0x48,0xd0,0x98,0x4d,0x06,0x24,0x46,0x24,0x17,0x90,0x7c,0x02,0xe5, -0x62,0x3d,0x92,0x06,0x24,0x9f,0x23,0xf9,0x02,0x49,0x23,0x92,0x26,0x24,0x5f,0x22, -0xf9,0x0a,0x49,0x33,0x92,0x16,0x24,0x97,0x90,0x5c,0x46,0xd2,0x8a,0xa4,0x0d,0xc9, -0x15,0x24,0x57,0x91,0x20,0xbb,0x5c,0x44,0x76,0xb9,0x88,0xec,0x72,0x11,0xd9,0xe5, -0x22,0xb2,0xcb,0x45,0x64,0x97,0x8b,0xc8,0x2e,0x17,0x91,0x5d,0x2e,0x22,0xbb,0x5c, -0x44,0x76,0xb9,0x88,0xec,0x72,0x11,0xd9,0xe5,0x22,0xb2,0xcb,0x45,0x64,0x97,0x8b, -0xc8,0x2e,0x17,0x91,0x5d,0x2e,0x22,0xbb,0x5c,0x44,0x76,0xb9,0x88,0xec,0x72,0x11, -0xd9,0xa5,0xee,0x33,0x24,0x68,0xe0,0x75,0x68,0xe0,0x75,0x68,0xe0,0x75,0x68,0xe0, -0x75,0x68,0xe0,0x75,0x68,0xe0,0x75,0x68,0xe0,0x75,0x68,0xe0,0x75,0x68,0xe0,0x75, -0x68,0xe0,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68, -0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc, -0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75,0x68,0xcc,0x75, -0x68,0xb8,0x75,0x68,0xb8,0x75,0x68,0xb8,0x75,0x68,0xb8,0x75,0x68,0xb8,0x75,0x68, -0xb8,0x75,0x68,0xb8,0x75,0xd6,0x91,0x0e,0x80,0xff,0x5d,0x0d,0xfe,0xb7,0x09,0x7c, -0xdf,0x00,0xbe,0xbf,0x0c,0xfe,0xbb,0xeb,0x0a,0xf8,0xbe,0x0d,0x7c,0xdf,0x0a,0xa6, -0x6f,0x99,0xc0,0x48,0x3d,0x18,0xf9,0x12,0x7c,0xdf,0x01,0x46,0x2e,0x81,0xef,0xbf, -0x00,0xdf,0x37,0x82,0x91,0xab,0xe0,0x7b,0x15,0xf8,0xfe,0x1a,0xf8,0x1e,0x0e,0xa1, -0x69,0x40,0x05,0xfe,0xfb,0xcb,0x0b,0x60,0xe4,0x3a,0x3a,0x56,0x83,0xef,0x2f,0xa0, -0x5c,0x03,0x46,0x6e,0x81,0x91,0xdb,0x60,0xe4,0x0e,0x2a,0x69,0xc1,0xc8,0x5d,0xf0, -0x7d,0x3b,0xf8,0xfe,0x0a,0xbc,0x36,0x3c,0xf9,0x2a,0xf8,0x4d,0x77,0x37,0xf8,0xfe, -0x13,0xf0,0x7d,0x0b,0xf8,0x1e,0x5e,0xb5,0x1e,0xfc,0xa7,0x02,0xfc,0xa7,0x12,0xfc, -0x67,0x39,0xea,0xad,0x47,0x82,0x0c,0xd3,0x83,0x82,0xa8,0x07,0x05,0x51,0x0f,0x0a, -0xa2,0x1e,0x14,0x44,0x3d,0x28,0x88,0x7a,0x50,0x10,0xf5,0xa0,0x20,0xea,0x41,0x41, -0xd4,0x83,0x82,0xa8,0x07,0x05,0x51,0x0f,0x0a,0xa2,0x1e,0x14,0x44,0x3d,0x28,0x88, -0x7a,0x50,0x10,0xf5,0xa0,0x20,0xea,0x41,0x41,0x84,0xbe,0xa2,0x54,0xf7,0x98,0x90, -0x7c,0x8a,0xe4,0x22,0x92,0x1a,0x24,0xb5,0x48,0xea,0x90,0x20,0x9f,0xf5,0x20,0x9f, -0xf5,0x20,0x9f,0xf5,0x20,0x9f,0xf5,0x20,0x9f,0xf5,0x20,0x9f,0xf5,0x20,0x9f,0xf5, -0x58,0x87,0x86,0x7c,0xd6,0x83,0x7c,0xd6,0x83,0x7c,0xd6,0x83,0x82,0xad,0x07,0x39, -0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae, -0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07, -0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x39,0xae,0x07,0x05,0x9b,0x19,0x15, -0xcd,0xa8,0x68,0xb6,0x16,0x91,0x33,0xcd,0xc8,0x99,0x66,0xe4,0x4c,0x33,0x72,0xa6, -0x19,0x39,0xd3,0x8c,0x9c,0x69,0x46,0xce,0x34,0xa3,0xd8,0x33,0x23,0x8f,0x9a,0xd1, -0x9a,0x34,0xa3,0x35,0x69,0x46,0x6b,0xd2,0x8c,0xd6,0xe4,0x2d,0x64,0xce,0x5b,0xc8, -0x9c,0xb7,0x90,0x39,0x6f,0x21,0x73,0xde,0x42,0xe6,0xbc,0x05,0xcd,0x69,0xba,0xac, -0x40,0xa2,0x44,0x52,0x8e,0xa4,0x02,0x89,0x0a,0x89,0xb5,0x55,0x83,0xa4,0x12,0x89, -0x16,0x89,0x0e,0x89,0x1e,0x49,0x15,0x12,0x03,0x12,0x23,0x92,0x0b,0x48,0x3e,0x41, -0x52,0x8d,0xc4,0x84,0xe4,0x53,0x24,0x17,0x91,0xd4,0x20,0xa9,0x45,0x52,0x87,0xe4, -0x33,0x24,0xf5,0x48,0x1a,0x90,0x7c,0x8e,0xe4,0x0b,0x24,0x8d,0x48,0x9a,0x90,0x7c, -0x89,0x04,0x1a,0xbb,0xae,0xbf,0x19,0x49,0x0b,0x92,0x4b,0x48,0x2e,0x23,0x69,0x45, -0xd2,0x86,0xe4,0x0a,0x92,0xab,0x48,0xda,0x91,0x74,0x20,0xb9,0x86,0xe4,0x6b,0x24, -0x9d,0x48,0xba,0x90,0x5c,0x47,0xf2,0x0d,0x92,0x1b,0x48,0xba,0x91,0xdc,0x44,0xd2, -0x83,0xa4,0x17,0x89,0x19,0xc9,0x2d,0x24,0xb7,0x91,0xf4,0x21,0xe9,0x47,0x72,0x07, -0xc9,0xb7,0x48,0x06,0x90,0x0c,0x22,0xb9,0x8b,0x04,0x5a,0xb7,0xee,0x0e,0x6a,0xb8, -0x83,0x1a,0xee,0xa0,0x86,0x3b,0xa8,0xe1,0x0e,0x6a,0xf8,0x56,0x81,0x44,0x89,0xa4, -0x1c,0x49,0x05,0x12,0x15,0x12,0x35,0x12,0x0d,0x92,0x4a,0x24,0x5a,0x24,0x3a,0x24, -0x7a,0x24,0x55,0x48,0x0c,0x48,0x8c,0x48,0x2e,0x20,0xf9,0x04,0x49,0x35,0x12,0x13, -0x92,0x4f,0x91,0x40,0xc3,0x36,0xa9,0x3f,0x83,0xa9,0x0d,0x1d,0xd4,0xff,0xd6,0x01, -0x4c,0xd7,0xdf,0x2c,0x7c,0xf3,0x66,0xe1,0xc6,0x9b,0x85,0xee,0x37,0x0b,0xd0,0x20, -0x4d,0x9a,0x7e,0xec,0x4a,0x9a,0x3b,0xaf,0x0f,0xfa,0xdf,0xb8,0xe4,0x5a,0xed,0xeb, -0x42,0xff,0x1b,0xd7,0xff,0xa5,0xe5,0x1b,0x70,0xbf,0x1b,0x3c,0xb8,0x0d,0x7e,0xa3, -0xad,0x84,0x09,0xce,0xfd,0xcb,0xd6,0x4b,0x48,0x2e,0x23,0x69,0x45,0xd2,0x86,0xe4, -0x0a,0x92,0xab,0x48,0xda,0x91,0x74,0x20,0xb9,0x86,0xe4,0x6b,0x24,0x9d,0x48,0xba, -0x90,0x5c,0x47,0xf2,0x0d,0x92,0x1b,0x48,0xba,0x91,0xdc,0x44,0xd2,0x83,0xa4,0x17, -0x89,0x19,0xc9,0x2d,0x24,0xb7,0x91,0xf4,0x21,0xe9,0x47,0x72,0x07,0xc9,0xb7,0x48, -0x06,0x90,0x0c,0x22,0xb9,0x8b,0x04,0x3a,0xe8,0xcb,0x36,0x05,0x12,0x25,0x12,0x34, -0xc8,0x36,0xf8,0x60,0xbf,0x0e,0x7e,0x6c,0x01,0x93,0xdf,0x00,0xb2,0x1f,0xa0,0xf8, -0x81,0x77,0xfd,0xc0,0x21,0x3f,0x40,0xf5,0x03,0x34,0x3f,0xf0,0x9e,0x1f,0x78,0xdf, -0x0f,0x04,0xfa,0x01,0x3a,0x7a,0xe9,0xa9,0xc9,0x47,0x2f,0x35,0x85,0xc5,0x80,0x5b, -0x00,0xf2,0x33,0x40,0x7e,0x3e,0x10,0x0a,0x0b,0x40,0xe1,0xc7,0x40,0x00,0xff,0xcb, -0x00,0x82,0x3c,0x90,0x91,0x0d,0x7e,0x56,0x7e,0xfb,0xb3,0xb2,0xca,0xfa,0x1b,0x7f, -0x39,0xfa,0x9b,0xcd,0xcf,0x80,0xe5,0x13,0xf4,0x47,0x1c,0x95,0xc0,0xd2,0xfa,0x39, -0x98,0xbb,0x7a,0x19,0xcc,0xdc,0x69,0x05,0xb3,0xf5,0xcd,0xe0,0x99,0xaa,0x05,0x58, -0x74,0x46,0x60,0xb9,0x6b,0x00,0x16,0x8d,0x11,0xcc,0xc2,0xad,0xdc,0xa2,0x6d,0x02, -0xcf,0xcc,0xe5,0x60,0xee,0x66,0x07,0xb0,0x5c,0x86,0x65,0xf8,0xf4,0x9d,0x1d,0xa8, -0x01,0xb3,0xfa,0x5a,0x30,0x6b,0xac,0x05,0xf3,0x4a,0x3d,0x98,0x35,0x54,0x82,0x59, -0xdd,0x45,0xf0,0xec,0x8a,0x12,0x3c,0xeb,0x40,0xff,0xd4,0xa8,0x05,0xb3,0x77,0x14, -0xe0,0x59,0x0d,0xbc,0x9f,0xee,0x26,0xb0,0xc0,0x9d,0x7f,0x5e,0x8d,0xde,0xb2,0x6a, -0x66,0x1b,0x3b,0xd7,0xde,0xc3,0x6a,0x66,0xfa,0x74,0xaf,0x8f,0xee,0x18,0xb0,0x23, -0xcb,0xf5,0xd7,0x75,0xcf,0xca,0xfb,0xb1,0x23,0x78,0xe1,0xd7,0x75,0x5f,0x7c,0xf6, -0xba,0x5f,0x55,0xd3,0xeb,0xd6,0x5a,0x6b,0x9d,0xe5,0x2e,0x9a,0xd5,0x37,0x60,0xa6, -0x6f,0x10,0xa6,0x3e,0x30,0xd3,0x0f,0xed,0xd9,0xac,0xba,0x04,0x66,0x06,0x9b,0xc1, -0xcc,0xdd,0x6f,0x81,0x45,0x51,0x0e,0x2c,0x4a,0x38,0x34,0xf8,0x26,0x63,0x41,0xbf, -0xa1,0x7f,0x0a,0x57,0x76,0x73,0x3d,0xac,0x50,0xa3,0x3f,0x11,0x6a,0x85,0x09,0xfa, -0xac,0xb9,0xa6,0x11,0xb6,0xf4,0xc3,0x02,0x0c,0x88,0xe6,0xda,0x2a,0x68,0x05,0x78, -0x5d,0x4d,0x2b,0x98,0xf9,0x16,0x59,0x04,0x06,0x43,0x47,0xe5,0x57,0xd0,0x24,0xf0, -0xcd,0xe8,0x22,0xca,0xe1,0x75,0x75,0x1a,0x98,0x6e,0x83,0x9f,0x6b,0xd0,0x9f,0xd4, -0xaa,0x61,0x82,0x65,0xa3,0x0e,0xa6,0xcf,0x61,0x82,0xd3,0x37,0x0e,0xc2,0x04,0xdd, -0xdc,0xdc,0xde,0x09,0x9e,0x29,0xa1,0xfd,0x3e,0xd1,0xc3,0x04,0x77,0x94,0x66,0xf4, -0x77,0x44,0x9f,0x7c,0x0d,0x53,0x37,0x34,0x18,0x3c,0x0b,0x8e,0xc8,0x02,0xdf,0x6f, -0x2c,0xf0,0x9d,0xc4,0x62,0x6a,0x87,0xe5,0x4b,0xc0,0x02,0x9f,0xf0,0x96,0x9a,0x6a, -0x60,0xa9,0xbd,0x08,0x13,0xec,0x5f,0xa7,0x82,0x09,0x9e,0x03,0x9f,0xac,0x96,0xcf, -0xe0,0x8c,0x1a,0xeb,0x60,0x82,0x43,0x6c,0x30,0xc1,0xd4,0x0b,0x1d,0x74,0x1d,0x58, -0xbe,0xba,0x00,0x13,0x3c,0x6e,0x86,0x8e,0xfc,0x12,0x4e,0xa1,0x19,0x3a,0xa0,0x19, -0xde,0xe3,0x12,0x1c,0x7e,0x0b,0x7c,0x19,0xb1,0x5c,0x86,0x15,0x97,0x6f,0x43,0xef, -0xc3,0x9b,0xc2,0x25,0x61,0x69,0x83,0xcb,0xa2,0xe5,0x73,0x18,0xfd,0x2d,0x5f,0x5c, -0x03,0x96,0xab,0x9d,0xc0,0xd2,0xfe,0x05,0x4c,0x57,0xe1,0x71,0x3d,0xb0,0x74,0x5c, -0x01,0x3f,0x7f,0x71,0x1d,0xa6,0x01,0x60,0xe9,0x84,0x43,0xeb,0x84,0x81,0xdb,0x72, -0x15,0x1e,0x7c,0x53,0x01,0x13,0xec,0xf0,0x0d,0x5c,0x00,0x2d,0x9d,0xe8,0xe0,0x3b, -0x60,0xb9,0x01,0xaf,0x39,0x78,0x11,0xfc,0xfc,0xa5,0x12,0x58,0xba,0x9b,0x81,0x05, -0x3e,0x43,0x2d,0x37,0xe1,0x06,0xd2,0x72,0x1b,0xde,0xd8,0x5c,0x81,0x0e,0xae,0xc0, -0x03,0x38,0x4c,0x33,0x9c,0x06,0x7c,0x4c,0x58,0x6e,0xc3,0x98,0xbb,0x7d,0x09,0xfc, -0xdc,0xfc,0x0d,0xcc,0xa1,0xb1,0xfa,0xe0,0xd4,0xa1,0x17,0x2d,0x70,0x0f,0xfd,0xb9, -0x05,0x8e,0xec,0x92,0x06,0x5a,0xbb,0x05,0x76,0xbc,0x03,0x8d,0x77,0x07,0xce,0xfb, -0x0e,0x5c,0x61,0xd7,0x2e,0xa0,0x7f,0x13,0x34,0x74,0x83,0x39,0x2d,0xbc,0xd1,0x00, -0x3c,0x1d,0x3d,0x1c,0x2e,0xeb,0xe1,0x92,0xbb,0x52,0x09,0x2d,0x8f,0x7e,0x4f,0x18, -0xfc,0x1a,0xd6,0x42,0x9b,0xdd,0x85,0xe5,0xef,0xa0,0x2d,0xbe,0x83,0x76,0xfa,0x0e, -0x06,0x6f,0xb9,0x12,0xfc,0x0c,0x57,0xe4,0xcf,0xad,0x70,0x97,0xbf,0xf4,0x05,0x8c, -0x64,0xb8,0x12,0x66,0xd5,0xe8,0xdf,0x45,0x0d,0x30,0xdd,0x01,0xb3,0x9a,0x9b,0x30, -0xc1,0x15,0xa1,0xf9,0x06,0xcc,0x56,0xa2,0x7f,0x9c,0x47,0x3f,0x4a,0x7c,0x01,0x23, -0xbc,0x09,0x46,0x7d,0x37,0x98,0xad,0x82,0xe7,0x18,0xe1,0x2e,0x78,0xa9,0x13,0x9e, -0x60,0x18,0x84,0x15,0x03,0xb0,0xa2,0x1d,0xcc,0x5e,0xa8,0x00,0xb3,0x9f,0xc0,0x9d, -0xe5,0xd2,0x37,0xb0,0x57,0xf5,0x25,0x58,0x50,0xc3,0x4a,0x38,0x8f,0xf6,0xeb,0x60, -0xd6,0xd4,0x01,0xd3,0x5d,0x30,0xfb,0x29,0xbc,0x8a,0x09,0x06,0x4c,0x47,0x27,0x98, -0xad,0x85,0x2e,0xb9,0x0c,0xbf,0x8a,0xcc,0x7e,0x76,0x19,0xcc,0x7e,0xd1,0x07,0x66, -0x1b,0x74,0xe0,0xe7,0x4e,0xf8,0xae,0x0d,0x0d,0xfd,0xf3,0xd7,0xd0,0x62,0xf0,0x85, -0xda,0xa2,0x81,0x0b,0xad,0x51,0x01,0x66,0x3f,0x6f,0x04,0x73,0xe5,0x5d,0x60,0xe6, -0x93,0x06,0x58,0x6e,0x01,0xb3,0x4d,0x70,0x68,0x4d,0x17,0xd1,0x3f,0x88,0x42,0x03, -0x75,0xe9,0xc0,0xec,0x57,0x70,0xec,0x5f,0xc2,0x3b,0xb6,0x40,0xdb,0x5c,0x36,0x75, -0x81,0xd9,0x4b,0x17,0xc0,0x6c,0xf3,0x57,0x60,0xb6,0x15,0x0e,0x18,0xee,0x2d,0xb3, -0x57,0xe0,0x5d,0xae,0x5e,0x03,0xb3,0xd7,0xa0,0xaf,0x2f,0x7f,0x0e,0x0b,0x5f,0x7f, -0x01,0x7e,0xbe,0x51,0x0f,0x66,0x3b,0xe1,0x73,0xed,0xf2,0xa5,0xab,0x60,0xb6,0x0b, -0x7e,0x4d,0xea,0x86,0x67,0x75,0x41,0x13,0x5c,0x87,0x67,0x5e,0x87,0x9b,0xd6,0xe5, -0x6b,0xc8,0x7f,0xbd,0xf0,0x79,0x70,0xf9,0x6b,0x78,0x07,0xd8,0xbc,0x78,0xf9,0x26, -0x9c,0xf1,0xcd,0xef,0xc0,0x2c,0x7c,0xc3,0x99,0xed,0x86,0xe7,0xf5,0xd6,0xc1,0x04, -0x27,0x67,0x86,0x93,0x84,0xef,0x03,0xb3,0xe8,0x91,0x7e,0x19,0xfd,0x28,0xd0,0xdb, -0x0b,0x66,0xfb,0xa0,0x1d,0xe1,0x83,0xef,0xe7,0xde,0x1e,0x30,0x8b,0x1e,0x35,0x97, -0xe1,0xd3,0x63,0xf6,0x36,0xf4,0xc4,0x20,0xdc,0x53,0x2f,0x0f,0xc2,0x85,0x78,0xf9, -0x2e,0xbc,0xe7,0x77,0x1a,0xf0,0x4c,0xd1,0x0f,0x13,0x1c,0xd4,0xad,0x3a,0xb8,0x58, -0xf4,0x30,0x0d,0xc2,0x74,0x1b,0x3c,0x83,0xf3,0x86,0x8b,0xb3,0x0d,0x3c,0x53,0xc3, -0x0b,0xb7,0xea,0x2e,0x83,0x67,0x1a,0xe8,0xbd,0xd6,0x0b,0xe8,0x6f,0xb8,0xdb,0xc1, -0x33,0x1d,0xf4,0x46,0x6b,0xbd,0x16,0x3c,0xd3,0xc3,0x4d,0x07,0x6e,0x4c,0x8b,0xad, -0x8d,0xe8,0x1f,0xd3,0x9b,0x6b,0xc0,0x33,0xe3,0x1d,0xf0,0xec,0x02,0xdc,0xfd,0xee, -0xa0,0x3f,0xe7,0x86,0xdf,0x6c,0xee,0xf4,0x81,0x67,0xf0,0xd5,0xff,0x99,0xa9,0x11, -0x3c,0xfb,0x54,0x0d,0x9e,0x5d,0x84,0x5f,0x04,0x07,0xbe,0x80,0x5b,0x15,0xf4,0x5b, -0xeb,0x8d,0x5b,0xf0,0x00,0xc6,0x77,0xeb,0x4d,0x14,0x5e,0x9a,0xaf,0xc0,0xb3,0x7a, -0x74,0xe5,0xbb,0x2d,0x48,0x60,0x6c,0xb5,0x29,0x55,0xe0,0xe7,0xef,0x06,0xc0,0x8c, -0x02,0x3e,0x2c,0xdb,0xe0,0x17,0x23,0x28,0xf0,0x19,0xd0,0xa6,0x6a,0x40,0xd2,0x03, -0x9e,0x35,0xa2,0xdf,0xcf,0xe0,0x69,0x70,0xdd,0xcd,0x28,0x35,0x60,0xa6,0x1c,0xbe, -0x67,0xb4,0xa1,0x1f,0x5e,0x5a,0x2e,0x80,0x19,0xf8,0xe5,0x6a,0xb1,0xad,0x1e,0x3e, -0x6f,0xda,0x3e,0x87,0xaf,0x1a,0x6d,0x5f,0xc0,0xbb,0x5f,0xfd,0x1a,0xcc,0xa8,0xbe, -0x81,0x9b,0x26,0x9c,0x6b,0x07,0x7c,0xba,0xb6,0xb5,0xc1,0x07,0x44,0xdb,0xb5,0xab, -0xe0,0xd9,0xd7,0xd7,0xc1,0x0c,0x7a,0x68,0xb5,0x5d,0x87,0x73,0xfc,0x06,0x9a,0xe6, -0x1b,0x1d,0xac,0x80,0xdb,0x52,0xdb,0x4d,0x38,0x47,0xf8,0x02,0x39,0xa3,0x87,0x1b, -0x36,0x7c,0xb5,0x7b,0x06,0xdf,0xfb,0x9e,0xf5,0xc2,0x67,0x48,0xdb,0x5d,0xd8,0xcb, -0x0c,0x77,0x73,0x03,0xdc,0x85,0x6f,0xc3,0x29,0xf6,0x95,0x83,0x67,0xfd,0x6a,0x58, -0x86,0x0f,0xa7,0x2b,0xd0,0x4c,0x8b,0x57,0x74,0x95,0x60,0xc6,0x08,0xc7,0x7a,0xa5, -0xaa,0x01,0x3c,0x1b,0x84,0x4f,0xa5,0x2b,0x86,0xbb,0xe0,0xd9,0xdd,0x5a,0xf0,0xec, -0x3b,0x54,0x40,0xdf,0x6d,0xae,0xd4,0x5c,0x06,0x73,0x4a,0xf8,0xb2,0x73,0x05,0xbe, -0xef,0xcf,0xc1,0x0d,0x6b,0xf1,0xb2,0xf1,0x2b,0x18,0x74,0xb5,0x30,0xf8,0x6e,0x82, -0x39,0x55,0x05,0x98,0xa9,0xae,0x82,0xf9,0x5d,0x60,0xb9,0x06,0x6d,0x7c,0xe5,0xcb, -0xab,0x48,0xe0,0xd1,0xe5,0x0b,0x28,0x16,0x2f,0xc0,0x20,0xd5,0xaa,0xc0,0xdc,0xdd, -0x2f,0xc1,0x8c,0xe9,0x6b,0x30,0xa7,0x37,0xc1,0x04,0xfb,0xeb,0xd1,0x1f,0x58,0xf6, -0xc0,0x1c,0x2e,0x59,0x6b,0x3e,0x08,0xe6,0xaa,0xa0,0x29,0xae,0x74,0x0e,0x80,0x39, -0x43,0x13,0x98,0x33,0xc2,0xdb,0x5e,0xe8,0x82,0xc7,0x28,0x87,0x8d,0x9f,0x5c,0x85, -0x75,0x17,0x61,0xae,0x87,0xc9,0x00,0x13,0xf4,0xf7,0x15,0xe8,0x9f,0xc5,0x2b,0x70, -0xe3,0x58,0xbc,0x02,0x5f,0x99,0x67,0x6a,0xe0,0xf5,0xe1,0x77,0xa3,0x39,0xf8,0xad, -0x68,0xae,0x06,0x1a,0xfa,0x2a,0xea,0x5b,0x0b,0xfd,0x78,0x65,0xa0,0x13,0xcc,0xd4, -0x36,0xc1,0x04,0x1d,0x77,0xe5,0x2e,0x7c,0x54,0x5f,0xad,0x80,0x06,0xab,0x85,0xfd, -0x1b,0xaa,0x61,0x82,0x97,0x6e,0xe8,0x00,0x73,0x9f,0xa3,0xa4,0x05,0x73,0x8d,0x17, -0xc0,0xdc,0x17,0x97,0x60,0x0e,0x27,0xdc,0x04,0xfb,0x7c,0x09,0x1d,0xf7,0xd9,0x67, -0x60,0xee,0xab,0x16,0x30,0xd7,0xac,0x84,0xc7,0xfd,0x60,0xae,0x05,0x5a,0xe4,0x2a, -0x3a,0x11,0xbe,0x34,0xce,0xc1,0xb7,0xc2,0x99,0x7a,0x33,0xcc,0xe1,0x2e,0xf2,0x29, -0x5c,0x21,0x57,0x2f,0xc1,0x40,0xbe,0xda,0x76,0x05,0xcc,0x7c,0x7e,0x17,0xcc,0x7c, -0x51,0x09,0xe6,0xae,0xa1,0xee,0x37,0xe1,0xf5,0x6e,0xc2,0xeb,0xc1,0xaf,0x10,0x73, -0xbd,0x5f,0x80,0x39,0xf4,0xb6,0x7c,0x75,0x00,0xbe,0x42,0x34,0x37,0x43,0x0b,0xa1, -0x9f,0xdb,0x6e,0xc1,0xc9,0xdf,0x86,0x26,0x6e,0x86,0x57,0x9c,0xfb,0x16,0xbe,0x9d, -0xb6,0x7f,0xf6,0x29,0x92,0x2e,0x30,0x5f,0x5e,0x03,0xe6,0x2b,0xba,0xc1,0xbc,0x0a, -0xbe,0x69,0xb5,0x37,0x5e,0x87,0x07,0x5f,0x80,0x79,0x6d,0x1f,0x98,0xaf,0xfa,0x0c, -0xa6,0x7a,0x30,0xaf,0x1b,0x00,0xf3,0x9f,0xf4,0x83,0xf9,0x6a,0x18,0xee,0xed,0xdf, -0xdc,0x01,0xf3,0x75,0x30,0xe6,0xae,0xc0,0x07,0x32,0xfa,0x86,0xd5,0x0e,0xef,0x35, -0x73,0xf5,0x0a,0x98,0xff,0x02,0x6e,0xd2,0xb7,0x6e,0x82,0xf9,0x46,0x18,0x7b,0x1d, -0x68,0xf1,0x74,0x68,0x3f,0x07,0x33,0x1d,0x30,0xb8,0x3a,0xe0,0x33,0xf9,0x2b,0x38, -0xcc,0x8e,0x6a,0x3d,0x98,0xb9,0x06,0xa3,0xb8,0xe3,0xd3,0x3a,0x30,0xdf,0x0c,0xdf, -0x7f,0x3a,0xd0,0xe3,0xfa,0x32,0x7c,0x76,0x76,0xf6,0x80,0x79,0xf8,0x42,0x34,0x7f, -0xe5,0x2a,0x98,0xbf,0x5a,0x0e,0x13,0x9c,0xdd,0x37,0x70,0xf9,0x77,0x74,0xde,0x00, -0xf3,0xdd,0x0a,0x30,0xdf,0x03,0x9f,0xb6,0xf0,0xfb,0xcd,0x0c,0xfc,0x22,0x31,0x6f, -0x86,0x81,0x70,0x0d,0xfd,0x66,0xde,0x03,0x17,0xca,0x35,0x15,0xbc,0xd5,0x35,0x2d, -0xec,0x7b,0x0d,0x46,0xc0,0x8c,0x19,0x5e,0xf9,0xdb,0xbb,0x60,0x1e,0x7e,0x3f,0x9b, -0x1f,0xf8,0x04,0x26,0xe8,0xad,0x6b,0xf5,0x0a,0x00,0x70,0x1b,0x36,0xda,0xd8,0x6e, -0xda,0xbc,0xd9,0x0e,0xbf,0x65,0xab,0xbd,0xc3,0x5b,0x8e,0x9b,0x7f,0xf9,0x10,0x36, -0x3b,0x6d,0xdb,0xee,0xec,0xb2,0x63,0xa7,0xab,0xb5,0xe8,0xb6,0x79,0xd7,0x6e,0x77, -0x8f,0x3d,0x6f,0x7b,0x7a,0x6d,0xfe,0xbb,0x7f,0xf6,0xee,0x83,0xe2,0xfd,0xab,0x5e, -0x92,0xb8,0xff,0x80,0x8f,0xef,0xc1,0x77,0xb0,0x92,0xdf,0xeb,0x6a,0x92,0xff,0xe6, -0x00,0x32,0x05,0x1e,0xbc,0xbb,0xf9,0x9f,0xf3,0x73,0x68,0x33,0x95,0xf6,0xde,0xfb, -0x81,0xaf,0x8b,0xf4,0x37,0xdb,0x82,0x0e,0x6f,0x0e,0x0e,0xf9,0xe0,0x75,0xe9,0xc3, -0xcd,0xff,0xc6,0x9f,0xd0,0xb0,0x23,0x9b,0xd7,0x3f,0xeb,0x9f,0xf5,0xcf,0xfa,0x67, -0xfd,0xb3,0xfe,0x59,0xff,0xac,0x7f,0xd6,0x3f,0xeb,0x9f,0xf5,0xcf,0xfa,0x67,0xfd, -0xf3,0xef,0xf3,0x01,0x36,0xeb,0xfc,0x55,0xd8,0x02,0xbb,0xdf,0x02,0x0f,0x08,0xc0, -0x09,0x38,0x63,0xb8,0x00,0x77,0x88,0x07,0xf0,0x02,0x44,0x40,0x02,0x64,0x08,0x05, -0xd0,0x41,0x08,0x08,0x05,0x61,0x80,0x05,0x38,0x20,0x03,0xc2,0x07,0x62,0x20,0x03, -0x2a,0x60,0x00,0x35,0x90,0x46,0xd0,0x0a,0x3a,0x41,0x2f,0x18,0x00,0xf7,0xc1,0x43, -0xf0,0x18,0x3c,0x81,0xcc,0x80,0xe7,0xe0,0x05,0x78,0x05,0x6c,0x70,0xf6,0x56,0x9c, -0x71,0xee,0x38,0x6f,0x9c,0x1f,0x8e,0x6a,0x25,0x18,0x17,0x8e,0x63,0xe2,0x92,0x70, -0x29,0xb8,0x0c,0x08,0x1f,0x27,0xc6,0xc9,0x70,0x2a,0x9c,0x01,0x57,0x83,0x6b,0xc4, -0xb5,0xe2,0x3a,0x21,0xbd,0xb8,0x01,0xdc,0x7d,0xdc,0x43,0xdc,0x63,0xdc,0x13,0x2b, -0x33,0xb8,0xe7,0xb8,0x17,0xb8,0x57,0x38,0x9b,0x0d,0x36,0x1b,0xec,0x21,0xce,0x1b, -0xdc,0x37,0x78,0x6f,0xf0,0xdb,0x40,0xdd,0x10,0xbc,0x21,0x7c,0x03,0x73,0x43,0xd2, -0x86,0x94,0x0d,0x19,0x1b,0xf8,0x1b,0xc4,0x1b,0x64,0x1b,0x54,0x1b,0x0c,0x56,0x6a, -0x36,0x34,0x6e,0x68,0xdd,0xd0,0xb9,0xa1,0x77,0xc3,0xc0,0x86,0xfb,0x1b,0x1e,0x6e, -0x78,0xbc,0xe1,0xc9,0x86,0x99,0x0d,0xcf,0x37,0xbc,0xd8,0xf0,0x6a,0x83,0xcd,0x46, -0xfb,0x8d,0xce,0x1b,0xdd,0x37,0x7a,0x6f,0xf4,0xb3,0x42,0xdd,0x18,0xbc,0x31,0x7c, -0x23,0x73,0x63,0xd2,0xc6,0x94,0x8d,0x19,0x1b,0xf9,0x1b,0xc5,0x1b,0x25,0x1b,0xe5, -0x1b,0x55,0x1b,0x0d,0x1b,0x6b,0x36,0x36,0x6e,0x6c,0x85,0x74,0x6e,0xec,0xdd,0x38, -0xb0,0xf1,0xfe,0xc6,0x87,0x1b,0xc7,0x37,0x4e,0x6d,0x9c,0xb1,0xf2,0x7c,0xe3,0x8b, -0x8d,0xaf,0x36,0xda,0xd8,0xd8,0xdb,0xb8,0xd8,0xb8,0x5b,0xf1,0xb6,0xf1,0xb3,0xa1, -0xda,0x04,0xdb,0x84,0xdb,0x30,0xad,0x24,0xd9,0xa4,0xd8,0x64,0xd8,0xf0,0x6d,0xc4, -0x36,0x32,0x1b,0x95,0x8d,0xc1,0xa6,0xc6,0xa6,0xd1,0xa6,0xd5,0xa6,0xd3,0xa6,0xd7, -0x66,0xc0,0xe6,0xbe,0xcd,0x43,0x9b,0xc7,0x36,0x4f,0xac,0xcc,0xd8,0x3c,0xb7,0x79, -0x61,0xf3,0xca,0xc6,0xc6,0xd6,0xde,0xd6,0xd9,0xd6,0xdd,0xd6,0xdb,0xd6,0xcf,0x96, -0x6a,0x1b,0x6c,0x1b,0x6e,0xcb,0xb4,0x4d,0xb2,0x4d,0xb1,0xcd,0xb0,0xe5,0xdb,0x8a, -0x6d,0x65,0xb6,0x2a,0x5b,0x83,0x6d,0xad,0x6d,0xfd,0x5f,0x4d,0xb3,0x6d,0xfb,0xff, -0xc0,0x0d,0xdb,0xbe,0x3f,0x89,0x7e,0xdb,0x61,0xdb,0x31,0xdb,0x29,0x5b,0x8b,0xed, -0x82,0xed,0xb2,0xed,0xaa,0xad,0xed,0x26,0xfb,0x4d,0xce,0x9b,0xdc,0x37,0x79,0x6f, -0xf2,0xdb,0x44,0xdd,0x14,0xbc,0x29,0x7c,0x13,0x73,0x53,0xf2,0xa6,0x8c,0x4d,0xc2, -0x4d,0xb2,0x4d,0xda,0x4d,0x35,0x9b,0x9a,0x37,0x75,0x42,0xfa,0x36,0xdd,0xdf,0xf4, -0x68,0xd3,0x93,0x4d,0x33,0x9b,0x9e,0x5b,0x79,0xb1,0xe9,0xd5,0x26,0x9b,0xcd,0xf6, -0x9b,0x9d,0x37,0xbb,0x6f,0xf6,0xd9,0x4c,0xdd,0x1c,0xbc,0x39,0x7c,0x33,0x6b,0x33, -0x7b,0x73,0xea,0xe6,0x8c,0xcd,0xfc,0xcd,0x62,0x2b,0xb2,0xcd,0xaa,0xcd,0xd5,0x9b, -0x1b,0x37,0xb7,0x6e,0xee,0xdc,0xdc,0xbb,0x79,0x00,0x72,0x7f,0xf3,0xc3,0xcd,0x8f, -0x37,0x3f,0xd9,0x3c,0xb3,0xf9,0xf9,0xe6,0x17,0x9b,0x5f,0x6d,0xb6,0xb1,0xb3,0xb7, -0x73,0xb6,0x73,0xb7,0xf3,0xb6,0xf3,0xb3,0xa3,0xda,0x05,0xdb,0x85,0xdb,0x31,0xed, -0x92,0xec,0x52,0xec,0x32,0xec,0xf8,0x76,0x62,0x3b,0x99,0x9d,0xca,0xce,0x60,0x57, -0x63,0xd7,0x68,0xa5,0xd5,0xae,0xf3,0xb7,0xe8,0xb5,0x1b,0xb0,0xbb,0x6f,0xf7,0xd0, -0x6e,0xc2,0x6e,0xc6,0x6e,0xd1,0xee,0x95,0x9d,0x0d,0xde,0x1e,0xef,0x8a,0xf7,0xc6, -0xfb,0xe1,0xa9,0xff,0xa6,0xd0,0xf0,0x74,0x7c,0x08,0x3e,0x0c,0x1f,0x81,0x67,0xe0, -0x59,0xf8,0x78,0x3c,0x1b,0x9f,0xfc,0x57,0xc1,0xc1,0xa7,0xe3,0x79,0x78,0x11,0x5e, -0x8a,0x57,0xe2,0xb5,0x10,0x1d,0xde,0x88,0x37,0xe1,0x6b,0xf1,0x0d,0xf8,0xc6,0x7f, -0x5a,0x9a,0xf1,0xad,0x90,0x76,0xfc,0x8d,0xbf,0x31,0xbd,0xbf,0x60,0xc6,0x0f,0x60, -0xdc,0xfb,0x85,0x21,0xfc,0xf7,0xf8,0x47,0xf8,0x09,0xfc,0x13,0xfc,0x0c,0xfe,0x39, -0xfe,0x05,0xe4,0x15,0xc4,0x66,0x8b,0xfd,0x16,0xd7,0xbf,0x00,0xcf,0x2d,0x3e,0x5b, -0xc8,0x5b,0x02,0xb7,0x84,0x6e,0x89,0xdc,0x92,0xf4,0x17,0x90,0xb2,0x25,0x63,0x0b, -0x7f,0x8b,0x78,0x8b,0x6c,0x8b,0x7c,0x8b,0x72,0x8b,0x7a,0x8b,0x7e,0xcb,0xa7,0x5b, -0x1a,0xb6,0x34,0x6d,0x69,0xfe,0xb3,0x69,0xd9,0xd2,0xb6,0xa5,0x63,0x4b,0xe7,0x96, -0xae,0x2d,0xdd,0x5b,0x7a,0xad,0x98,0xb7,0xf4,0xfd,0x0e,0xf7,0xb6,0x3c,0x80,0x3c, -0xc2,0x98,0xf8,0x85,0xa7,0x5b,0xe6,0xb6,0x2c,0xfe,0x5e,0x5e,0xfe,0x95,0x80,0xad, -0x7f,0x0e,0x76,0x5b,0x09,0x10,0x57,0x0c,0xcf,0x5f,0xf0,0xd9,0x4a,0xde,0x1a,0xf8, -0x67,0x12,0xba,0x35,0xf2,0x1f,0x90,0xb8,0xad,0xc9,0xff,0x03,0x69,0x5b,0xb9,0x5b, -0x85,0x5b,0x8b,0xac,0x28,0xb6,0x6a,0xad,0x54,0x6f,0xad,0xdf,0xda,0xbc,0xb5,0x7d, -0xeb,0x8d,0xad,0x7d,0x56,0xee,0x6d,0x7d,0xb0,0xf5,0xd1,0xd6,0x89,0xad,0x4f,0xb7, -0xce,0x59,0x59,0xdc,0xfa,0x72,0x2b,0xb0,0xb7,0xb3,0x27,0xd8,0xbb,0xda,0x7b,0xda, -0xfb,0xd8,0x93,0xed,0x03,0xed,0x43,0xed,0x23,0xad,0xc4,0xd9,0x27,0xaf,0xf3,0x07, -0xe1,0xd8,0xa7,0xad,0xf3,0x17,0xc1,0xb5,0x17,0xda,0x17,0xd9,0x2b,0xec,0xb5,0xff, -0xc0,0xe8,0xec,0x4d,0xf6,0x0d,0xf6,0x2d,0xf6,0xed,0xff,0x60,0xdc,0x80,0xf4,0xfd, -0x51,0xee,0xfd,0xcd,0x00,0xeb,0x9f,0x7f,0xf3,0xcf,0xdf,0x22,0xaa,0x1e,0xfc,0x0e, -0x8f,0xac,0x4c,0xfc,0x4a,0x3c,0xb5,0x9f,0xb3,0x5f,0xb4,0x7f,0x69,0x0f,0x1c,0xec, -0x1c,0x08,0x0e,0xae,0xff,0xa2,0x78,0x3a,0xf8,0xfc,0x11,0xc8,0x0e,0x81,0x90,0xd0, -0x7f,0x1a,0x22,0xad,0xc4,0xfd,0x2a,0x24,0x3b,0xa4,0x39,0x70,0xad,0x08,0xd7,0xf9, -0x17,0xa4,0xc8,0x8a,0xc2,0x41,0xfb,0x47,0xa8,0x76,0xa8,0xff,0xbb,0xd2,0xfc,0x77, -0xa4,0xdd,0xe1,0x86,0x43,0xdf,0xbf,0x2d,0xf7,0xfe,0xcd,0x78,0xf0,0x5b,0x3c,0x72, -0x98,0x80,0x3c,0x75,0x78,0xfe,0x6f,0xce,0x0b,0x87,0x57,0x0e,0x36,0x6f,0xad,0xf3, -0x87,0xb0,0x87,0x38,0xbf,0xe5,0xf9,0x96,0xcf,0x3f,0x0d,0xbe,0x6f,0x91,0xff,0xad, -0xa1,0xbc,0x15,0xf8,0x2b,0x43,0x7f,0x2b,0xec,0xad,0xc8,0xbf,0x29,0x8c,0xb7,0x98, -0x7f,0x57,0x92,0x7e,0x0f,0x29,0xbf,0x90,0xf1,0x0b,0xfc,0x5f,0x10,0xff,0x41,0x64, -0xbf,0x07,0x15,0xc4,0xf0,0x56,0xed,0x5b,0xcd,0x6f,0x75,0xbc,0xd5,0xfb,0x3b,0x0c, -0xfc,0x09,0xdc,0xff,0x3d,0x3c,0xfc,0x85,0xc7,0xbf,0xf0,0xe4,0x17,0x66,0xfe,0x20, -0xcf,0xff,0x85,0x79,0xb1,0xce,0x3f,0x09,0xcb,0x6f,0xbd,0xfc,0xbd,0x00,0x47,0xe0, -0x68,0x07,0x21,0x40,0x5c,0x21,0x9e,0x18,0x3e,0xbf,0x3a,0x64,0x48,0xa0,0x95,0x50, -0xc7,0x48,0x48,0xdc,0x3a,0xff,0x62,0xc4,0x3b,0xb2,0x1d,0x39,0x8e,0x29,0x8e,0xa9, -0x8e,0xe9,0x8e,0x99,0x8e,0x3c,0x47,0x81,0xa3,0xc8,0x51,0xe2,0x28,0x75,0x94,0x3b, -0x2a,0x1d,0xd5,0x8e,0x5a,0x47,0x9d,0xa3,0xd1,0xd1,0xe4,0x58,0xeb,0xd8,0xe0,0xd8, -0xe4,0xd8,0xe2,0xd8,0xe6,0xd8,0xe1,0xd8,0xe5,0xd8,0xed,0x68,0x76,0xec,0x77,0x1c, -0x74,0x1c,0x72,0x1c,0x76,0x1c,0x71,0x1c,0x75,0x7c,0xe4,0x38,0xe6,0x38,0xee,0x38, -0xe9,0x38,0xe5,0x38,0xed,0x68,0x71,0x9c,0x77,0x5c,0x70,0x5c,0x72,0x5c,0x76,0x5c, -0x71,0x5c,0x75,0xc4,0x11,0x6c,0x09,0x78,0x82,0x03,0xc1,0x89,0xe0,0x42,0x70,0x23, -0x78,0x10,0xbc,0x08,0x44,0x82,0x2f,0x81,0x44,0xa0,0x10,0x68,0x04,0x3a,0x21,0x84, -0x10,0xfa,0x07,0x09,0x23,0x84,0xff,0x0a,0x44,0x10,0x18,0x04,0x16,0x21,0x9e,0xc0, -0x26,0x70,0x08,0xa9,0x84,0x74,0x42,0x26,0x81,0x47,0x10,0x10,0x44,0x04,0x09,0x41, -0x4a,0x90,0x13,0x94,0x04,0x35,0x41,0x47,0x30,0x12,0x4c,0x84,0x5a,0x42,0x03,0xa1, -0x89,0xd0,0x42,0x68,0x23,0x74,0x10,0xba,0x08,0xdd,0x04,0x33,0xa1,0x9f,0x30,0x48, -0x18,0x22,0x0c,0x13,0x46,0x08,0xa3,0x84,0x31,0xc2,0x38,0x61,0xe2,0x1f,0x80,0xa7, -0x84,0x39,0xc2,0x22,0xe1,0x25,0x01,0x38,0xd9,0x39,0x11,0x9c,0x5c,0x9d,0xbc,0x9d, -0xc8,0x4e,0x81,0x4e,0xa1,0x4e,0x91,0x4e,0x71,0x4e,0xc9,0x4e,0x69,0x4e,0x5c,0x27, -0xa1,0x53,0x91,0x93,0xc2,0xc9,0xe0,0x54,0xef,0xd4,0xea,0x74,0xc3,0xa9,0xcf,0xe9, -0x9e,0xd3,0x03,0xa7,0x47,0x4e,0x4f,0x9c,0xe6,0x9c,0x16,0x9d,0x5e,0x3a,0x81,0x6d, -0x76,0xdb,0x08,0xdb,0x5c,0xb7,0x79,0x6e,0xf3,0xd9,0x46,0xde,0x16,0xb8,0x2d,0x74, -0x5b,0xe4,0xb6,0xb8,0x6d,0xc9,0xdb,0xd2,0xb6,0x71,0xb7,0x89,0xb7,0x29,0xb6,0x69, -0xb7,0x55,0x6f,0xab,0xdf,0xd6,0xbc,0xad,0x7d,0xdb,0x8d,0x6d,0x7d,0xdb,0xee,0x6d, -0x7b,0xb8,0x6d,0x62,0xdb,0xd3,0x6d,0x73,0xdb,0x16,0xb7,0xbd,0xdc,0x06,0xb6,0xdb, -0x6d,0x27,0x6c,0x77,0xdd,0xee,0xb9,0xdd,0x67,0x3b,0x79,0x7b,0xe0,0xf6,0xd0,0xed, -0x91,0xdb,0xe3,0xb6,0x27,0x6f,0x4f,0xdb,0xce,0xdd,0x2e,0xde,0xae,0xd8,0x6e,0xd8, -0x5e,0xbf,0xbd,0x75,0xfb,0x8d,0xed,0x03,0xdb,0x1f,0x6c,0x7f,0xb4,0x7d,0x62,0xfb, -0xd3,0xed,0x73,0xdb,0x17,0xb7,0xbf,0xdc,0x0e,0x9c,0xed,0x9c,0x9d,0x9d,0x3d,0x9d, -0x7d,0x9c,0xc9,0xce,0x81,0xce,0xa1,0xce,0x91,0xce,0x71,0xce,0x29,0xce,0x5c,0x67, -0xb1,0xb3,0xc2,0xd9,0xe0,0x5c,0xef,0xdc,0xec,0xdc,0xee,0x7c,0xc3,0xb9,0xcf,0xf9, -0x9e,0xf3,0x03,0xe7,0x47,0xce,0x13,0xce,0x4f,0x9d,0xe7,0x9c,0x17,0x9d,0x5f,0x3a, -0x03,0x17,0x3b,0x17,0x67,0x17,0x4f,0x17,0x3f,0x97,0x40,0x97,0x50,0x97,0x48,0x97, -0x38,0x97,0x64,0x97,0x34,0x17,0xae,0x8b,0xd0,0xa5,0xc8,0x45,0xe1,0xa2,0x75,0xa9, -0x76,0xa9,0x77,0x69,0x76,0x69,0x77,0xb9,0xe1,0xd2,0xe7,0x72,0xcf,0xe5,0x81,0xcb, -0x23,0x97,0x09,0x97,0xa7,0x2e,0x73,0x2e,0x8b,0x2e,0x2f,0x5d,0xc0,0x0e,0xbb,0x1d, -0x84,0x1d,0xae,0x3b,0x3c,0x77,0xf8,0xee,0x78,0x77,0x47,0xe0,0x2f,0x84,0xee,0x88, -0xdc,0x11,0xb7,0x23,0x79,0x47,0xc6,0x0e,0xe1,0x0e,0xd9,0x0e,0xed,0x8e,0x9a,0x1d, -0xcd,0x3b,0x3a,0x77,0xf4,0xed,0xb8,0xbf,0xe3,0xd1,0x8e,0x27,0x3b,0xe6,0x76,0xbc, -0xd8,0x01,0x76,0xda,0xef,0x74,0xdd,0xe9,0xbd,0x93,0xbc,0x33,0x78,0x67,0xe4,0xce, -0xb8,0x9d,0xc9,0x3b,0xd3,0x76,0x72,0x77,0x0a,0x77,0x16,0xed,0x54,0xed,0xac,0xde, -0xd9,0xb8,0xb3,0x7d,0x67,0xef,0xce,0x7b,0x3b,0x1f,0xee,0x9c,0xd8,0x39,0xb3,0x73, -0x71,0xe7,0xcb,0x9d,0xc0,0xd5,0xce,0x95,0xe0,0xea,0xea,0xea,0xe9,0xea,0xe3,0x4a, -0x76,0x0d,0x76,0x8d,0x74,0x4d,0x72,0x4d,0x73,0xe5,0xbb,0x16,0xb9,0xaa,0x5c,0xab, -0x5d,0x1b,0x5d,0xdb,0x5d,0x7b,0x5d,0xef,0xb9,0x3e,0x74,0x9d,0x70,0x9d,0x71,0x5d, -0x74,0x7d,0xe5,0x6a,0xe7,0xe6,0xec,0xe6,0xe9,0xe6,0xe3,0x46,0x76,0x0b,0x74,0x0b, -0x75,0x63,0xba,0x25,0xbb,0x65,0xb8,0x09,0xdd,0x64,0x6e,0x5a,0xb7,0x1a,0xb7,0x66, -0xb7,0x4e,0xb7,0x3e,0xb7,0x7b,0x6e,0x0f,0xdc,0x1e,0xb9,0x4d,0xb8,0x3d,0x75,0x9b, -0x73,0x5b,0x74,0x7b,0xf9,0x3b,0x80,0x5d,0x76,0xbb,0x9c,0x77,0x79,0xee,0xf2,0xdb, -0x15,0xb8,0x2b,0x7c,0x57,0xdc,0xae,0xe4,0x5d,0x69,0xbb,0xf8,0xbb,0x8a,0x76,0xa9, -0x76,0x55,0xef,0x6a,0xdc,0xd5,0xbe,0xeb,0xc6,0xae,0xbe,0x5d,0xf7,0x77,0x3d,0xda, -0xf5,0x64,0xd7,0x9c,0x95,0xc5,0x5d,0x2f,0x77,0xd9,0xec,0x26,0xec,0x76,0xdf,0xed, -0x63,0x85,0xbc,0x3b,0x70,0x77,0xf8,0xee,0xb8,0xdd,0x29,0xbb,0xb9,0xbb,0xc5,0xbb, -0x15,0xbb,0xb5,0xbb,0xab,0x77,0x37,0xee,0x6e,0xdf,0xdd,0xbb,0xfb,0xde,0xee,0x87, -0xbb,0x27,0x76,0x3f,0xdd,0x3d,0xb7,0xfb,0xc5,0x6e,0xe0,0x6e,0xef,0xee,0xea,0xee, -0xed,0x4e,0x76,0x0f,0x74,0x0f,0x75,0x67,0xba,0x27,0xbb,0x67,0xb8,0x0b,0xdd,0x65, -0xee,0x5a,0xf7,0x6a,0xf7,0x7a,0xf7,0x56,0xf7,0x1b,0xee,0x03,0xee,0x0f,0xac,0x3c, -0x72,0x9f,0x70,0x9f,0x71,0x5f,0x74,0x7f,0xe5,0x6e,0xe7,0x81,0x20,0x78,0xb8,0x7a, -0x78,0x7b,0x90,0x3d,0x82,0x3d,0x22,0x3d,0x92,0x3c,0xd2,0x20,0x5c,0x88,0x18,0xa2, -0x80,0x18,0x3c,0x6a,0x3c,0x1a,0x3d,0xda,0x3d,0x7a,0x3d,0xee,0x79,0x3c,0xf4,0x98, -0xf0,0x98,0xf1,0x78,0xee,0xf1,0xc2,0x03,0xec,0xb1,0xdf,0xe3,0xba,0xc7,0x7b,0x0f, -0x79,0x4f,0xf0,0x9e,0xf0,0x3d,0xcc,0x3d,0x49,0x7b,0x52,0xf6,0x64,0xec,0xe1,0xef, -0x11,0xef,0x91,0xed,0x51,0xed,0x31,0xec,0xa9,0xd9,0xd3,0xb8,0xa7,0x75,0x4f,0xa7, -0x95,0xbe,0x3d,0xf7,0xf7,0x3c,0xde,0x33,0xb3,0xe7,0xc5,0x1e,0x9b,0xb7,0x9d,0xdf, -0xf6,0x7e,0x9b,0xfc,0x76,0xf0,0xdb,0xcc,0xb7,0x53,0xde,0xe6,0xbf,0x2d,0x7b,0xdb, -0xf0,0x76,0xe3,0xdb,0xed,0x6f,0xf7,0xbe,0x7d,0xff,0xed,0xc7,0x6f,0xcf,0xbc,0xfd, -0xe2,0x6d,0x1b,0x4f,0x67,0x4f,0x4f,0x4f,0x3f,0xcf,0x60,0x4f,0xa6,0x67,0x8a,0x27, -0xdf,0x53,0xe6,0x69,0xf0,0xac,0xf7,0x6c,0xf5,0xec,0xf5,0xbc,0xef,0xf9,0xd8,0x73, -0xc6,0xf3,0x85,0xa7,0x8d,0x17,0xc1,0xcb,0xdd,0xcb,0xcf,0x2b,0xd8,0x8b,0xe9,0x95, -0xe2,0xc5,0xf7,0x92,0x79,0xa9,0xbc,0x0c,0x5e,0xf5,0x5e,0xcd,0x5e,0x9d,0x90,0x5e, -0xaf,0x7b,0x5e,0x0f,0xbc,0x1e,0x79,0x4d,0x78,0x3d,0xf5,0x9a,0xf7,0x5a,0xf4,0x5a, -0xf6,0x5a,0xf5,0xda,0xb4,0xd7,0x7e,0xaf,0xeb,0x5e,0xcf,0xbd,0x7e,0x10,0xea,0xde, -0xd0,0xbd,0x91,0x7b,0xe3,0xf6,0x26,0xef,0x4d,0xdb,0x9b,0xbd,0x37,0x6f,0x6f,0xf1, -0x5e,0xc5,0x5e,0xed,0xde,0xea,0xbd,0x8d,0x7b,0xdb,0xad,0xdc,0xd8,0x3b,0xb0,0xf7, -0xfe,0xde,0x87,0x7b,0x1f,0xef,0x7d,0xb2,0xf7,0xff,0xd9,0x3b,0xbb,0xf7,0xff,0xdd, -0xfb,0x62,0xef,0xab,0xbd,0x36,0xfb,0x08,0xfb,0xdc,0xf7,0x79,0xef,0xf3,0xdb,0x47, -0xdd,0x17,0xba,0x2f,0x72,0x5f,0xdc,0xbe,0xe4,0x7d,0x69,0xfb,0xb2,0xf7,0xe5,0xed, -0x2b,0xda,0x27,0xb3,0xa2,0xdd,0x57,0xbd,0xaf,0x11,0xd2,0xba,0xef,0xc6,0xbe,0xbe, -0x7d,0xf7,0xf6,0x3d,0xd8,0xf7,0x68,0xdf,0x8f,0xfb,0xa6,0xf6,0xcd,0xec,0x9b,0x85, -0xfc,0xf7,0xbe,0x85,0x7d,0x4b,0xfb,0x96,0xf7,0xad,0xec,0x5b,0xdd,0x87,0xf3,0xb6, -0xf5,0xc6,0x7b,0x3b,0x78,0x13,0xde,0xc0,0xc9,0xdb,0xf9,0x17,0x5c,0xbc,0xdd,0xff, -0x00,0x1e,0xde,0x5e,0xde,0xbe,0xde,0xd4,0xdf,0x81,0xe6,0x1d,0x68,0x85,0xee,0x1d, -0xe6,0xcd,0xf4,0x66,0x79,0xb3,0xbd,0xd3,0x30,0xd2,0xbd,0xb9,0xde,0x3c,0x6f,0xe1, -0xef,0x20,0xf2,0x96,0x7a,0x2b,0xbd,0xb5,0x7f,0x10,0x9d,0x77,0xfd,0x6f,0xd1,0xe0, -0xdd,0xf8,0x47,0x68,0xf2,0x6e,0xf1,0x6e,0x85,0xb4,0x79,0x77,0x78,0x77,0x79,0x77, -0x7b,0x9b,0xbd,0xfb,0xbd,0x07,0xbd,0x87,0xbc,0x87,0xbd,0x47,0xbc,0x47,0xbd,0xc7, -0xbc,0xc7,0xbd,0x27,0xbd,0xa7,0xbc,0xa7,0xbd,0x2d,0xde,0xf3,0xde,0x0b,0xde,0x4b, -0xde,0xcb,0xde,0x2b,0xde,0xab,0xde,0x38,0xa2,0x2d,0x11,0x4f,0x74,0x20,0x12,0x88, -0x4e,0x44,0x17,0xa2,0x1b,0xd1,0x83,0xe8,0x45,0x24,0x12,0x7d,0x89,0x24,0x22,0x85, -0x48,0x23,0xd2,0x89,0x21,0xc4,0x30,0x62,0xf8,0xef,0x25,0x82,0xc8,0xfc,0xa7,0x82, -0x05,0xe1,0x10,0x33,0x89,0x3c,0xa2,0x90,0x28,0x22,0xca,0x89,0x3a,0xa2,0x81,0x68, -0x24,0xd6,0x12,0x1b,0x88,0x4d,0xc4,0x16,0x62,0x1b,0xb1,0x83,0xd8,0x45,0xec,0x26, -0x9a,0x89,0xfd,0xc4,0x01,0xe2,0x20,0x71,0x88,0xf8,0x00,0x32,0x42,0x1c,0x25,0x8e, -0x11,0xc7,0x89,0x93,0xc4,0x27,0x90,0x29,0xa2,0x85,0xb8,0x44,0x7c,0x49,0x5c,0x21, -0xbe,0x82,0x80,0xfd,0xb8,0xfd,0x36,0x10,0xbb,0xfd,0x4e,0xfb,0x5d,0xf6,0xbb,0xee, -0x77,0xdb,0xef,0xb1,0xdf,0x6b,0xbf,0xf7,0x7e,0xe2,0x7e,0xdf,0xfd,0xa4,0xfd,0x94, -0xfd,0xb4,0xfd,0xf4,0xfd,0x21,0xfb,0x43,0xf7,0x87,0xed,0x67,0xed,0x8f,0xdf,0xcf, -0xde,0xcf,0xd9,0x9f,0xba,0x3f,0x0d,0x23,0x7d,0x7f,0xe6,0x7e,0xde,0x7e,0xc1,0x7e, -0xd1,0x7e,0xf1,0x1b,0x48,0xf6,0x2b,0xf7,0x1b,0xf7,0x37,0xed,0xef,0xd8,0x6f,0xde, -0x3f,0xb4,0x7f,0x74,0xff,0xe4,0x7e,0xcb,0xfe,0xa5,0xfd,0xab,0xfb,0xf1,0x07,0x5c, -0x0e,0x78,0x1d,0x20,0x1d,0xa0,0x1d,0xa0,0x1f,0x08,0x3b,0xc0,0x3a,0xc0,0x3e,0xc0, -0x39,0x90,0x7e,0x40,0x70,0x40,0x7e,0x40,0x7d,0x40,0x77,0xc0,0x74,0xa0,0xe9,0x40, -0xcb,0x81,0xb6,0x03,0x1d,0x07,0xba,0x0e,0x74,0x1f,0xe8,0x3f,0x30,0x7c,0x60,0xf4, -0xc0,0xd8,0x81,0xc9,0x03,0x96,0x03,0xcb,0x07,0x56,0x0f,0xe0,0x7c,0xf0,0x3e,0x2e, -0x3e,0x6e,0x3e,0x1e,0x3e,0x5e,0x3e,0xde,0xff,0x07,0x44,0x1f,0xf2,0x1f,0x25,0xd0, -0x27,0xf4,0x4f,0x22,0xf2,0xaf,0x22,0xce,0x27,0xd9,0x27,0xed,0xef,0x08,0xf7,0x17, -0x84,0x56,0x8a,0xfe,0x4c,0x14,0x10,0xed,0x2f,0xe8,0x7c,0x4c,0x3e,0x8d,0x3e,0x4d, -0x3e,0x6d,0x3e,0x37,0xfe,0x28,0x7d,0x56,0xee,0x59,0x79,0x00,0x79,0xf4,0x67,0x31, -0x01,0x79,0xfa,0x7b,0x99,0xf3,0x59,0xf4,0x79,0xe9,0x03,0x7c,0xed,0xac,0x10,0x7c, -0x5d,0xad,0x78,0xfa,0xfa,0xfc,0x16,0x64,0xdf,0x40,0x2b,0xa1,0xbe,0x91,0x56,0xe2, -0x7c,0x93,0x7f,0x15,0xd2,0x7c,0xb9,0xbe,0x42,0xdf,0xa2,0xbf,0x39,0x0a,0x5f,0xad, -0x6f,0xb5,0x6f,0xfd,0x6f,0xd1,0xec,0xdb,0xee,0x7b,0xc3,0xb7,0xef,0xff,0x1a,0x03, -0xbe,0xf7,0xd6,0x59,0xe7,0xef,0xc4,0x90,0xef,0xb0,0xef,0x88,0xef,0xa8,0xef,0x98, -0xef,0xb8,0xef,0xa4,0xef,0x94,0xef,0xb4,0xaf,0xc5,0x77,0xc1,0x77,0xd9,0x77,0xd5, -0xd7,0xf6,0xa0,0xc3,0x41,0x97,0x83,0x1e,0x07,0x89,0x07,0x49,0x07,0x69,0x07,0x43, -0x0e,0x32,0x0e,0xb2,0x0f,0xa6,0x1f,0x14,0x1c,0x94,0x1e,0x54,0x1f,0x34,0x1d,0x6c, -0x3a,0xd8,0x71,0xb0,0xff,0xe0,0xc8,0xc1,0xc9,0x83,0xf3,0x07,0x57,0x0e,0xe2,0xdf, -0x71,0x7b,0xc7,0xf7,0x1d,0xfa,0x3b,0x8c,0x77,0x38,0xef,0xa4,0xbf,0xc3,0x7b,0x47, -0xf4,0x8e,0xf4,0x1d,0xe5,0x3b,0xba,0x77,0x4c,0xef,0x34,0xbc,0xd3,0xf2,0x4e,0xd7, -0x3b,0xfd,0xef,0x0c,0xbf,0x33,0xf6,0xce,0xd4,0x3b,0xf3,0xef,0x2c,0xbf,0x83,0xf3, -0x73,0xf0,0x73,0xf3,0x23,0xfa,0x51,0xfc,0x42,0xfc,0x18,0x7e,0x6c,0xbf,0x74,0x3f, -0x81,0x9f,0xd4,0x4f,0xed,0x67,0xf2,0x6b,0xf2,0xeb,0xf0,0x33,0xfb,0x0d,0xf9,0x8d, -0xfa,0x4d,0xfa,0x59,0xfc,0x96,0xfc,0x56,0xfd,0xf0,0x24,0x17,0x92,0x17,0x89,0x44, -0xa2,0x93,0x22,0x48,0xf1,0xa4,0x54,0x52,0x3a,0x29,0x93,0xc4,0x23,0x09,0x48,0x22, -0x92,0x84,0x24,0x25,0xc9,0x49,0x4a,0x92,0x9a,0xa4,0x23,0x19,0x49,0x26,0x52,0x2d, -0xa9,0x81,0xd4,0x44,0x6a,0x21,0xb5,0x91,0x3a,0x48,0x5d,0xa4,0x6e,0x92,0x99,0xd4, -0x4f,0x1a,0x24,0x0d,0x91,0x86,0x49,0x23,0xa4,0x51,0xd2,0x18,0x69,0x9c,0x34,0x49, -0x9a,0x22,0x4d,0x93,0x2c,0xa4,0x79,0xd2,0x02,0x69,0x89,0xb4,0x4c,0x5a,0x21,0xad, -0x92,0x70,0xfe,0xb6,0xfe,0x78,0x7f,0x07,0x7f,0x27,0x7f,0x17,0x7f,0x37,0x7f,0x0f, -0x7f,0x2f,0x7f,0xa2,0xbf,0xaf,0x3f,0xc9,0x9f,0xfc,0x2b,0x40,0xf1,0x0f,0xfd,0x97, -0x22,0xcc,0x9f,0xe5,0xcf,0xf6,0x4f,0xfb,0x17,0x82,0xbb,0xce,0x5f,0x05,0xcf,0x5f, -0xe0,0x2f,0x5c,0xe7,0x5f,0x1e,0x91,0xbf,0x78,0x9d,0x75,0xfe,0x86,0x48,0xfc,0x8b, -0xfe,0x29,0x90,0xfa,0xcb,0xfe,0x00,0x72,0x88,0xd2,0x5f,0xed,0xaf,0xf3,0x37,0xfa, -0x9b,0xfc,0x6b,0xfd,0x1b,0xfc,0x9b,0xfc,0x5b,0xfc,0xdb,0xfc,0x3b,0xfc,0xbb,0xfc, -0xbb,0xfd,0xcd,0xfe,0xfd,0xfe,0x83,0xfe,0x43,0xfe,0xc3,0xfe,0x23,0xfe,0xa3,0xfe, -0x63,0xfe,0xe3,0xfe,0x93,0xfe,0x53,0xfe,0xd3,0xfe,0x16,0xff,0x79,0xff,0x05,0xff, -0x25,0xff,0x65,0xff,0x15,0xff,0x55,0x7f,0x5c,0x80,0x6d,0x00,0x3e,0xc0,0x21,0xc0, -0x29,0xc0,0x25,0xc0,0x2d,0xc0,0x23,0xc0,0x2b,0x80,0x18,0xe0,0x1b,0x40,0x0a,0xa0, -0x04,0xd0,0x02,0xe8,0x01,0x21,0x01,0x61,0x01,0x11,0x01,0x8c,0x00,0x56,0x40,0x7c, -0x00,0x3b,0x80,0x13,0x90,0x1a,0x90,0x1e,0x90,0x19,0xc0,0x0b,0x10,0x04,0x88,0x02, -0x24,0x01,0xd2,0x00,0x79,0x80,0x32,0x40,0x1d,0xa0,0x0b,0x30,0x06,0x98,0x02,0x6a, -0x03,0x1a,0x02,0x9a,0x02,0x5a,0x02,0xda,0x02,0x3a,0x02,0xba,0x02,0xba,0x03,0xcc, -0x01,0xfd,0x01,0x83,0x01,0x43,0x01,0xc3,0x01,0x23,0x01,0xa3,0x01,0x63,0x01,0xe3, -0x01,0x93,0x01,0x53,0x01,0xd3,0x01,0x96,0x80,0xf9,0x80,0x85,0x80,0xa5,0x80,0xe5, -0x80,0x95,0x80,0xd5,0x00,0x1c,0xd9,0x96,0x8c,0x27,0x3b,0x90,0x9d,0xc8,0x2e,0x64, -0x37,0xb2,0x07,0xd9,0x8b,0x4c,0x24,0xfb,0x92,0x49,0x64,0x0a,0x99,0x46,0xa6,0x93, -0x43,0xc8,0x61,0xe4,0x08,0x32,0x83,0xcc,0x22,0xc7,0x93,0xd9,0x64,0x0e,0x39,0x95, -0x9c,0x4e,0xce,0x24,0xf3,0xc8,0x02,0xb2,0x88,0x2c,0x21,0x4b,0xc9,0x72,0xb2,0x92, -0xac,0x26,0xeb,0xc8,0x46,0xb2,0x89,0x5c,0x4b,0x6e,0x20,0x37,0x91,0x5b,0xc8,0x6d, -0xe4,0x0e,0x72,0x17,0xb9,0x9b,0x6c,0x26,0xf7,0x93,0x07,0xc9,0x43,0xe4,0x61,0xf2, -0x08,0x79,0x94,0x3c,0x46,0x1e,0x27,0x4f,0x92,0xa7,0xc8,0xd3,0x64,0x0b,0x79,0x9e, -0xbc,0x40,0x5e,0x22,0x2f,0x93,0x57,0xc8,0xab,0x64,0x1c,0xc5,0x96,0x82,0xa7,0x38, -0x50,0x9c,0x28,0x2e,0x14,0x37,0x8a,0x07,0xc5,0x8b,0x42,0xa4,0xf8,0x52,0x48,0x14, -0x0a,0x85,0x46,0xa1,0x53,0x42,0x28,0x61,0x94,0x08,0x0a,0x83,0xc2,0xa2,0xc4,0x53, -0xd8,0x14,0x0e,0x25,0x95,0x92,0x4e,0xc9,0xa4,0xf0,0x28,0x02,0x8a,0x88,0x22,0xa1, -0x48,0x29,0x72,0x8a,0x92,0xa2,0xa6,0xe8,0x28,0x46,0x8a,0x89,0x52,0x4b,0x69,0xa0, -0x34,0x51,0x5a,0x28,0x6d,0x94,0x0e,0x4a,0x17,0xa5,0x9b,0x62,0xa6,0xf4,0x53,0x06, -0x29,0x43,0x94,0x61,0xca,0x08,0x65,0x94,0x32,0x46,0x79,0xfc,0x37,0x60,0x1c,0x32, -0xf1,0x77,0x63,0x92,0xf2,0x84,0x32,0x45,0x99,0xa6,0x58,0x28,0x73,0x7f,0x02,0x8b, -0x90,0x97,0x10,0xf0,0x2e,0x78,0xd7,0x0e,0x42,0x80,0xb8,0x42,0x3c,0x21,0x3e,0x10, -0x32,0x24,0x10,0x12,0x0a,0x89,0xb4,0x12,0x07,0x49,0x86,0xa4,0xfd,0x16,0xdc,0x77, -0x85,0x90,0xa2,0x77,0x15,0x10,0xed,0xbb,0xd5,0x90,0xfa,0x77,0x9b,0x21,0xed,0xef, -0xde,0xf8,0xb3,0xe8,0x7b,0x83,0xfe,0x77,0x87,0xde,0x7d,0x00,0x19,0x7b,0x77,0xe2, -0x0f,0xf2,0x14,0x32,0x07,0x59,0x84,0xbc,0x84,0x80,0x43,0xe0,0x90,0x1d,0x84,0x00, -0x71,0x85,0x78,0x42,0x7c,0x20,0x64,0x48,0xa0,0x95,0x50,0x48,0x24,0x24,0xee,0xb7, -0x48,0x3e,0x94,0x06,0xe1,0x1e,0x12,0x42,0x8a,0x0e,0x29,0x20,0xda,0x43,0xd5,0x90, -0xfa,0x43,0xcd,0x7f,0x16,0xed,0x56,0x6e,0x1c,0xea,0x3b,0x74,0xef,0xd0,0x03,0x8c, -0xb1,0x43,0x13,0x7f,0x07,0x26,0x0f,0x4d,0x1d,0x9a,0x3e,0x64,0x39,0x34,0x7f,0x68, -0xe1,0xd0,0xd2,0xa1,0xe5,0x43,0x2b,0x87,0x56,0x0f,0xe1,0xa8,0xb6,0x54,0x3c,0xd5, -0x81,0xea,0x44,0x75,0xa1,0xba,0x51,0x3d,0xa8,0x5e,0x54,0x22,0xd5,0x97,0x4a,0xa2, -0x52,0xa8,0x34,0x2a,0x9d,0x1a,0x42,0x0d,0xa3,0x46,0x50,0x19,0x54,0x16,0x35,0x9e, -0xca,0xa6,0x72,0xa8,0xa9,0xd4,0x74,0x6a,0x26,0x95,0x47,0x15,0x50,0x45,0x54,0x09, -0x55,0x4a,0x95,0x53,0x95,0x54,0x35,0x55,0x47,0x35,0x52,0x4d,0xd4,0x5a,0x6a,0x03, -0xb5,0x89,0xda,0x42,0x6d,0xa3,0x76,0x50,0xbb,0xa8,0xdd,0x54,0x33,0xb5,0x9f,0x3a, -0x48,0x1d,0xa2,0x0e,0x53,0x47,0xa8,0xa3,0xd4,0x31,0xea,0x38,0x75,0x92,0x3a,0x45, -0x9d,0xa6,0x5a,0xa8,0xf3,0xd4,0x05,0xea,0x12,0x75,0x99,0xba,0x42,0x5d,0xa5,0xe2, -0x68,0xb6,0x34,0x3c,0xcd,0x81,0xe6,0x44,0x73,0xa1,0xb9,0xd1,0x3c,0x68,0x5e,0x34, -0x22,0xcd,0x97,0x46,0xa2,0x51,0x68,0x34,0x1a,0x9d,0x16,0x42,0x0b,0xa3,0x45,0xd0, -0x18,0x34,0x16,0x2d,0xce,0x4a,0x3c,0x8d,0x4d,0xe3,0xd0,0x52,0x69,0xe9,0xb4,0x4c, -0x1a,0x8f,0x26,0xa0,0x89,0x68,0x12,0x9a,0x94,0x26,0xa7,0x29,0x69,0x6a,0x9a,0xf6, -0x9f,0x1c,0x1d,0xa4,0x96,0xd6,0x42,0xeb,0xa2,0xf5,0xd3,0x86,0x69,0x63,0xb4,0x29, -0xda,0x3c,0x6d,0x99,0x86,0x7b,0xcf,0xe1,0x3d,0xb7,0xf7,0x88,0xef,0x51,0xde,0x0b, -0x7b,0x2f,0xfe,0xbd,0xf4,0xf7,0x44,0xef,0x29,0xdf,0x33,0xbd,0xd7,0xf2,0x5e,0xf7, -0x7b,0x43,0xef,0x8d,0xbd,0x37,0xfd,0xde,0xd2,0x7b,0xb8,0xf7,0x9d,0xde,0xf7,0x7a, -0x3f,0xe4,0xfd,0xa4,0xf7,0xd9,0xef,0xa7,0xbf,0x2f,0x78,0x5f,0xfa,0xbe,0xfa,0x7d, -0xd3,0xfb,0x4d,0xef,0x77,0xbc,0x6f,0x7e,0x7f,0xe8,0xfd,0xd1,0xf7,0x27,0xdf,0xb7, -0xbc,0xbf,0xf4,0xfe,0xea,0xfb,0xf8,0x40,0x97,0x40,0xaf,0x40,0x52,0x20,0x3d,0x30, -0x22,0x30,0x3e,0x30,0x35,0x90,0x17,0x28,0x09,0x54,0x06,0x1a,0x03,0x1b,0x02,0xdb, -0x02,0xbb,0x03,0x07,0x03,0x47,0x02,0xc7,0x03,0xa7,0x03,0x17,0x02,0x57,0x02,0x6d, -0xe9,0x78,0xba,0x03,0xdd,0x89,0xee,0xfc,0x3b,0xb8,0xd0,0xbd,0xe8,0xbe,0x74,0x0a, -0x9d,0x4e,0x0f,0xa3,0x33,0xe8,0xf1,0x74,0x0e,0x3d,0x9d,0xce,0xa3,0x8b,0xe8,0x52, -0xba,0x92,0xae,0xa3,0x9b,0xe8,0x0d,0xf4,0x26,0x7a,0x0b,0xbd,0x8d,0xde,0x41,0xef, -0xa2,0x77,0xd3,0xcd,0xf4,0x7e,0xfa,0x20,0x7d,0x88,0x3e,0x4c,0x1f,0xa1,0x8f,0xd2, -0xc7,0xe8,0x93,0xf4,0x69,0xfa,0x3c,0x7d,0x89,0xbe,0x42,0xc7,0x05,0xe1,0x83,0x9c, -0x82,0xdc,0x82,0xbc,0x82,0x7c,0x83,0x28,0x41,0xf4,0xa0,0xb0,0x20,0x76,0x50,0x66, -0x10,0x3f,0x48,0x10,0x24,0x0a,0x92,0x04,0x49,0x83,0xe4,0x41,0xca,0x20,0x75,0x90, -0x2e,0xc8,0x18,0x64,0x0a,0xaa,0x0d,0x6a,0x08,0x6a,0x0a,0x6a,0x09,0x6a,0x0b,0xea, -0x08,0xea,0x0a,0xea,0x0e,0x32,0x07,0xf5,0x07,0x0d,0x06,0x0d,0x05,0x0d,0x07,0x8d, -0x04,0x8d,0x06,0x8d,0x05,0x8d,0x07,0x4d,0x06,0x4d,0x05,0x4d,0x07,0x59,0x82,0xe6, -0x83,0x16,0x82,0x96,0x82,0x96,0x83,0x56,0x82,0x56,0x83,0x70,0x87,0x6d,0x0f,0xe3, -0x0f,0x3b,0x1c,0x76,0x3a,0xec,0x72,0xd8,0xed,0xb0,0xc7,0x61,0xaf,0xc3,0xc4,0xc3, -0xbe,0x87,0x49,0x87,0x29,0x87,0xe9,0x87,0xc3,0x0e,0x33,0x0e,0xc7,0x1f,0xe6,0x1c, -0x4e,0x3f,0xcc,0x3b,0x2c,0x3a,0x2c,0x3d,0xac,0x3c,0xac,0x3b,0x6c,0x3a,0xdc,0x70, -0xb8,0xe5,0x70,0xc7,0xe1,0xee,0xc3,0xfd,0x87,0x87,0x0e,0x8f,0x1c,0x1e,0x3b,0x3c, -0x79,0x78,0xfa,0xf0,0xfc,0xe1,0xa5,0xc3,0xab,0x87,0xf1,0xc1,0x2e,0xc1,0x1e,0xc1, -0xbe,0xc1,0x94,0xe0,0x90,0xe0,0xb0,0xe0,0x88,0x60,0x46,0x30,0x2b,0x38,0x3e,0x98, -0x1d,0xcc,0x09,0x4e,0x0d,0x4e,0x0f,0xce,0x0c,0xe6,0x05,0x0b,0x82,0x45,0xc1,0x92, -0x60,0x69,0xb0,0x3c,0x58,0x19,0xac,0x0e,0xd6,0x05,0x1b,0x83,0x4d,0xc1,0xb5,0xc1, -0x0d,0xc1,0x4d,0xc1,0x2d,0xc1,0x6d,0xc1,0x1d,0xc1,0x5d,0xc1,0xdd,0xc1,0xe6,0xe0, -0xfe,0xe0,0xc1,0xe0,0xa1,0xe0,0xe1,0xe0,0x91,0xe0,0xd1,0xe0,0xb1,0xe0,0xf1,0xe0, -0xc9,0xe0,0xa9,0xe0,0xe9,0x60,0x4b,0xf0,0x7c,0xf0,0x42,0xf0,0x52,0xf0,0x72,0xf0, -0x4a,0x30,0x2e,0x04,0x17,0xe2,0x12,0x42,0x0c,0xa1,0x87,0x44,0x84,0x70,0x42,0x32, -0x43,0x44,0x21,0xba,0x90,0x86,0x90,0xb6,0x90,0xee,0x90,0xc1,0x90,0xd1,0x90,0xa9, -0x90,0x85,0x90,0xd5,0x10,0x87,0x0f,0x3c,0x3e,0x20,0x7d,0x10,0xf1,0x01,0xeb,0x83, -0xcc,0x0f,0xe4,0x1f,0x98,0x3e,0x68,0xf9,0xa0,0xff,0x83,0xb1,0x0f,0xa6,0x3f,0x58, -0xf8,0x60,0xe5,0x03,0xfc,0x87,0x6e,0x1f,0x92,0x3e,0x0c,0xfb,0x90,0xf5,0x21,0xe7, -0x43,0xde,0x87,0x92,0x0f,0x95,0x1f,0xea,0x3e,0x34,0x7d,0xd8,0xf4,0x61,0xc7,0x87, -0x43,0x1f,0x8e,0x7d,0x68,0xf9,0x70,0xf5,0x43,0x87,0x50,0xb7,0x50,0x62,0x68,0x48, -0x28,0x2b,0x34,0x33,0x54,0x14,0xaa,0x0e,0x35,0x85,0xb6,0x84,0x76,0x85,0x0e,0x86, -0x8e,0x85,0x4e,0x87,0x2e,0x87,0xda,0x86,0x39,0x84,0x79,0x85,0x91,0xc2,0xe8,0x61, -0x8c,0x30,0x76,0x58,0x7a,0x98,0x20,0x4c,0x19,0x66,0x0a,0x6b,0x08,0xeb,0x0e,0x1b, -0x0c,0x1b,0x0b,0x9b,0x0e,0x5b,0x0a,0x5b,0x0d,0xc3,0x1f,0x71,0x3b,0xe2,0x75,0x84, -0x72,0x24,0xe2,0x08,0xeb,0x48,0xe6,0x11,0xd1,0x11,0xe9,0x11,0xe5,0x11,0xdd,0x11, -0xd3,0x91,0x86,0x23,0x2d,0x47,0x3a,0x8e,0x74,0x1f,0xe9,0x3f,0x32,0x74,0x64,0xf4, -0xc8,0xe4,0x11,0xcb,0x91,0xa5,0x23,0xab,0x47,0xf0,0x47,0x5d,0x8e,0x7a,0x1d,0x25, -0x1d,0xa5,0x1f,0x8d,0x38,0x1a,0x7f,0x34,0xf5,0x28,0xef,0xa8,0xe4,0xa8,0xf2,0xa8, -0xee,0xa8,0xe9,0x68,0xd3,0xd1,0xb6,0xa3,0x5d,0x47,0xcd,0x47,0x87,0x8e,0x8e,0x1e, -0x1d,0x3f,0x3a,0x75,0xd4,0x72,0x74,0xe1,0xe8,0xf2,0x51,0xdb,0x70,0x87,0x70,0x97, -0x70,0x8f,0x70,0x62,0x38,0x29,0x9c,0x16,0x1e,0x12,0x1e,0x11,0x1e,0x1f,0x9e,0x1e, -0xce,0x0b,0x17,0x85,0x4b,0xc3,0x95,0xe1,0xba,0x70,0x53,0x78,0x43,0x78,0x5b,0x78, -0x77,0xf8,0x60,0xf8,0x48,0xf8,0x58,0xf8,0x64,0xf8,0x74,0xf8,0x7c,0xf8,0x52,0xf8, -0x4a,0x38,0x2e,0x02,0x1f,0xe1,0x14,0xe1,0x16,0x41,0x8c,0xa0,0x44,0xd0,0x23,0x22, -0x22,0xe2,0x23,0x52,0x23,0x32,0x23,0x44,0x11,0xf2,0x08,0x63,0x44,0x6d,0x44,0x4b, -0x44,0x57,0x44,0x7f,0xc4,0x70,0xc4,0x64,0xc4,0x52,0xc4,0x4a,0x04,0xee,0x18,0xfe, -0x98,0xd3,0x31,0xb7,0x63,0x5e,0xc7,0x7c,0x8f,0x51,0x8e,0xd1,0x8f,0x85,0x1d,0x63, -0x1c,0x8b,0x3f,0xc6,0x39,0x96,0x7e,0x8c,0x77,0x4c,0x74,0x4c,0x7a,0x4c,0x79,0xcc, -0x74,0xac,0xe1,0x58,0xcb,0xb1,0x8e,0x63,0xfd,0xc7,0x86,0x8f,0x8d,0x1e,0x1b,0x3f, -0x36,0x75,0xcc,0x72,0x6c,0xe1,0xd8,0xf2,0xb1,0xd5,0x63,0xb6,0xc7,0x1d,0x8e,0xbb, -0x1c,0xf7,0x3a,0xee,0x7b,0x9c,0x72,0x3c,0xe4,0x38,0xe3,0x78,0xfc,0xf1,0xf4,0xe3, -0x82,0xe3,0x92,0xe3,0xf2,0xe3,0xea,0xe3,0xc6,0xe3,0x0d,0xc7,0xdb,0x8e,0x77,0x1d, -0x37,0x1f,0x1f,0x3c,0x3e,0x7c,0x7c,0xf4,0xf8,0xf8,0xf1,0xa9,0xe3,0x96,0xe3,0x0b, -0xc7,0x57,0x8e,0xdb,0x46,0x3a,0x45,0x7a,0x44,0xfa,0x46,0xd2,0x22,0xc3,0x22,0x59, -0x91,0x9c,0xc8,0xcc,0x48,0x51,0xa4,0x3c,0x52,0x17,0x59,0x1b,0xd9,0x12,0xd9,0x15, -0xd9,0x1f,0x39,0x1c,0x39,0x16,0x39,0x15,0x39,0x1f,0xb9,0x1c,0x09,0x18,0xeb,0xfc, -0x65,0xe0,0x18,0xb6,0x0c,0xbb,0x75,0xfe,0x09,0xc0,0x33,0xec,0xff,0xed,0x71,0x60, -0x38,0x31,0x5c,0x18,0xae,0x56,0xdc,0x18,0x1e,0x0c,0xcf,0x7f,0x09,0xbc,0x18,0x44, -0x86,0x2f,0x83,0xc4,0x20,0xff,0x1f,0x50,0x18,0xd4,0x75,0xfe,0x2c,0x02,0x19,0xc1, -0x8c,0x50,0x46,0x38,0x23,0x92,0xc1,0x64,0xc4,0x31,0x92,0x18,0xc9,0x8c,0x14,0x46, -0x1a,0x23,0x83,0xc1,0x65,0xf0,0x19,0x42,0x86,0x98,0x51,0xc4,0x90,0x31,0x14,0x0c, -0x15,0x43,0xcb,0x30,0x30,0xaa,0x19,0x35,0x8c,0x7a,0x46,0x23,0xa3,0x99,0xd1,0xca, -0x68,0x67,0x74,0x32,0x6e,0x30,0x7a,0x19,0x7d,0x8c,0x01,0xc6,0x3d,0xc6,0x7d,0xc6, -0x03,0xc6,0x43,0xc6,0x23,0xc6,0x63,0xc6,0x04,0xe3,0x09,0xe3,0x29,0x63,0x86,0x31, -0xc7,0x78,0xce,0x58,0x64,0xbc,0x60,0xbc,0x64,0xbc,0x62,0x80,0x28,0x9b,0x28,0xbb, -0x28,0xfb,0x28,0x42,0x94,0x73,0x94,0x6b,0x94,0x7b,0x94,0x67,0x94,0x77,0x94,0x4f, -0x94,0x5f,0x14,0x39,0x8a,0x1a,0x15,0x18,0x15,0x1c,0x15,0x1a,0x15,0x1e,0x15,0x19, -0xc5,0x8c,0x8a,0x8b,0x4a,0x8a,0x4a,0x8e,0x4a,0x89,0x4a,0x8b,0xca,0x88,0xe2,0x46, -0xf1,0xa3,0x84,0x51,0xe2,0xa8,0xa2,0x28,0x59,0x94,0x22,0x4a,0x15,0xa5,0x8d,0x32, -0x44,0x55,0x47,0xd5,0x44,0xd5,0x47,0x35,0x46,0x35,0x47,0xb5,0x46,0xb5,0x47,0x75, -0x46,0xdd,0x88,0xea,0x8d,0xea,0x8b,0x1a,0x88,0xba,0x17,0x75,0x3f,0xea,0x41,0xd4, -0xc3,0xa8,0x47,0x51,0x8f,0xa3,0x26,0xa2,0x9e,0x44,0x3d,0x8d,0x9a,0x89,0x9a,0x8b, -0x7a,0x1e,0xb5,0x18,0xf5,0x22,0xea,0x65,0xd4,0xab,0x28,0x10,0x6d,0x13,0x6d,0x17, -0x6d,0x1f,0x4d,0x88,0x76,0x8e,0x76,0x8d,0x76,0x8f,0xf6,0x8c,0xf6,0x8e,0xf6,0x89, -0xf6,0x8b,0x26,0x47,0x53,0xa3,0x03,0xa3,0x83,0xa3,0x43,0xa3,0xc3,0xa3,0x23,0xa3, -0x99,0xd1,0x71,0xd1,0x49,0xd1,0xc9,0xd1,0x29,0xd1,0x69,0xd1,0x19,0xd1,0xdc,0x68, -0x7e,0xb4,0x30,0x5a,0x1c,0x5d,0x14,0x2d,0x8b,0x56,0x44,0xab,0xa2,0xb5,0xd1,0x86, -0xe8,0xea,0xe8,0x9a,0xe8,0xfa,0xe8,0xc6,0xe8,0xe6,0xe8,0xd6,0xe8,0xf6,0xe8,0xce, -0xe8,0x1b,0xd1,0xbd,0xd1,0x7d,0xd1,0x03,0xd1,0xf7,0xa2,0xef,0x47,0x3f,0x88,0x7e, -0x18,0xfd,0x28,0xfa,0x71,0xf4,0x44,0xf4,0x93,0xe8,0xa7,0xd1,0x33,0xd1,0x73,0xd1, -0xcf,0xa3,0x17,0xa3,0x5f,0x44,0xbf,0x8c,0x7e,0x15,0x0d,0x98,0x36,0x4c,0x3b,0xa6, -0x3d,0x93,0xc0,0x74,0x66,0xba,0x32,0xdd,0x99,0x9e,0x4c,0x6f,0xa6,0x0f,0xd3,0x8f, -0x49,0x66,0x52,0x99,0x81,0xcc,0x60,0x66,0x28,0x33,0x9c,0x19,0xc9,0x64,0x32,0xe3, -0x98,0x49,0xcc,0x64,0x66,0x0a,0x33,0x8d,0x99,0xc1,0xe4,0x32,0xf9,0x4c,0x21,0x53, -0xcc,0x2c,0x62,0xca,0x98,0x0a,0xa6,0x8a,0xa9,0x65,0x1a,0x98,0xd5,0xcc,0x1a,0x66, -0x3d,0xb3,0x91,0xd9,0xcc,0x6c,0x65,0xb6,0x33,0x3b,0x99,0x37,0x98,0xbd,0xcc,0x3e, -0xe6,0x00,0xf3,0x1e,0xf3,0x3e,0xf3,0x01,0xf3,0x21,0xf3,0x11,0xf3,0x31,0x73,0x82, -0xf9,0x84,0xf9,0x94,0x39,0xc3,0x9c,0x63,0x3e,0x67,0x2e,0x32,0x5f,0x30,0x5f,0x32, -0x5f,0x31,0x01,0xcb,0x86,0x65,0xc7,0xb2,0x67,0x11,0x58,0xce,0x2c,0x57,0x96,0x3b, -0xcb,0x93,0xe5,0xcd,0xf2,0x61,0xf9,0xb1,0xc8,0x2c,0xf8,0x85,0x8b,0x15,0xc8,0x0a, -0x66,0x85,0xb2,0xc2,0x59,0x91,0x2c,0x26,0x2b,0x8e,0x95,0xc4,0x4a,0x66,0xa5,0xb0, -0xd2,0x58,0x19,0x2c,0x2e,0x8b,0x6f,0x45,0x08,0x11,0x5b,0x29,0x62,0xc9,0x58,0x0a, -0x96,0x8a,0xa5,0x65,0x19,0x58,0xd5,0xac,0x1a,0x56,0x3d,0xab,0x11,0xd2,0x0c,0x69, -0xb5,0xd2,0xce,0xea,0xc4,0xb8,0xc1,0xea,0x65,0xf5,0xb1,0x06,0x58,0xf7,0x58,0xf7, -0x59,0x0f,0x58,0x0f,0x59,0x8f,0x58,0x8f,0x59,0x13,0xac,0x27,0xac,0xa7,0xac,0x19, -0xd6,0x1c,0xeb,0x39,0x6b,0x91,0xf5,0x82,0xf5,0x92,0xf5,0x8a,0x05,0x62,0x6c,0x62, -0xec,0x62,0xec,0x63,0x08,0x31,0xce,0x31,0xae,0x31,0xee,0x31,0x9e,0x31,0xde,0x31, -0x3e,0x31,0x7e,0x31,0xe4,0x18,0x6a,0x4c,0x60,0x4c,0x70,0x4c,0x68,0x4c,0x78,0x4c, -0x64,0x0c,0x33,0x26,0x2e,0x26,0x29,0x26,0x39,0x26,0x25,0x26,0x2d,0x26,0x23,0x86, -0x1b,0xc3,0x8f,0x11,0xc6,0x88,0x63,0x8a,0x62,0x64,0x31,0x8a,0x18,0x55,0x8c,0x36, -0xc6,0x10,0x53,0x1d,0x53,0x13,0x53,0x1f,0xd3,0x18,0xd3,0x1c,0xd3,0x1a,0xd3,0x1e, -0xd3,0x19,0x73,0x23,0xa6,0x37,0xa6,0x2f,0x66,0xc0,0xca,0xbd,0x98,0xfb,0x31,0x0f, -0x62,0x1e,0xc6,0x3c,0x8a,0x79,0x1c,0x33,0x11,0xf3,0x24,0xe6,0x69,0xcc,0x4c,0xcc, -0x5c,0xcc,0xf3,0x98,0xc5,0x98,0x17,0x31,0x2f,0x63,0x5e,0xc5,0x80,0x58,0x9b,0x58, -0xbb,0x58,0xfb,0x58,0x42,0xac,0x73,0xac,0x6b,0xac,0x7b,0xac,0x67,0xac,0x77,0xac, -0x4f,0xac,0x5f,0x2c,0x39,0x96,0x1a,0x1b,0x18,0x1b,0x1c,0x1b,0x1a,0x1b,0x1e,0x1b, -0x19,0xcb,0x8c,0x8d,0x8b,0x4d,0x8a,0x4d,0x8e,0x4d,0x89,0x4d,0x8b,0xcd,0x88,0xe5, -0xc6,0xf2,0x63,0x85,0xb1,0xe2,0xd8,0xa2,0x58,0x59,0xac,0x22,0x56,0x15,0xab,0x8d, -0x35,0xc4,0x56,0xc7,0xd6,0xc4,0xd6,0xc7,0x36,0xc6,0x36,0xc7,0xb6,0xc6,0xb6,0xc7, -0x76,0xc6,0xde,0x88,0xed,0x8d,0xed,0x8b,0x1d,0x88,0xbd,0x17,0x7b,0x3f,0xf6,0x41, -0xec,0xc3,0xd8,0x47,0xb1,0x8f,0x63,0x27,0x62,0x9f,0xc4,0x3e,0x8d,0x9d,0x89,0x9d, -0x8b,0x7d,0x1e,0xbb,0x18,0xfb,0x22,0xf6,0x65,0xec,0xab,0x58,0x10,0x67,0x13,0x67, -0x17,0x67,0x1f,0x47,0x88,0x73,0x8e,0x73,0x8d,0x73,0x8f,0xf3,0x8c,0xf3,0x8e,0xf3, -0x89,0xf3,0x8b,0x23,0xc7,0x51,0xe3,0x02,0xe3,0x82,0xe3,0x42,0xe3,0xc2,0xe3,0x22, -0xe3,0x98,0x71,0x71,0x71,0x49,0x71,0xc9,0x71,0x29,0x71,0x69,0x71,0x19,0xbf,0x22, -0x99,0x10,0x41,0x9c,0x24,0x4e,0x1e,0xa7,0x8b,0xab,0x8d,0x6b,0x8a,0x6b,0xfd,0x03, -0xb4,0xc5,0x75,0xc5,0x99,0xe3,0x06,0xe3,0x86,0xe3,0x1e,0xbe,0xc1,0x63,0xc8,0x54, -0xdc,0x74,0x9c,0x25,0x6e,0x3e,0x6e,0x21,0x6e,0x29,0x6e,0x39,0x6e,0x25,0x6e,0x35, -0x0e,0x17,0x6f,0x13,0x6f,0x1f,0xef,0x1c,0xef,0x19,0xef,0x17,0x4f,0x8d,0x0f,0x8e, -0x0f,0x8f,0x67,0xc6,0x27,0xc5,0xa7,0xc4,0x67,0xc4,0xf3,0xe3,0xc5,0x10,0x59,0xbc, -0x2a,0xde,0x10,0x5f,0x13,0xdf,0x08,0x69,0x85,0x74,0xc6,0xf7,0x42,0x06,0xe2,0xef, -0x43,0x1e,0xc6,0x3f,0x8e,0x7f,0x12,0x3f,0x13,0xff,0x3c,0xfe,0x45,0xfc,0xab,0x78, -0x9b,0x04,0x87,0x04,0x97,0x04,0xb7,0x04,0x8f,0x04,0xaf,0x04,0x62,0x82,0x6f,0x02, -0x29,0x81,0x92,0x40,0x4b,0xa0,0x27,0x84,0x24,0x84,0x25,0x44,0x24,0x30,0x12,0x58, -0x09,0xf1,0x09,0xec,0x04,0x4e,0x42,0x6a,0x42,0x7a,0x42,0x66,0x02,0x2f,0x41,0x90, -0x20,0x4a,0x90,0x24,0x48,0x13,0xe4,0x09,0xca,0x04,0x75,0x82,0x2e,0xc1,0x98,0x60, -0x4a,0xa8,0x4d,0x68,0x48,0x68,0x4a,0x68,0x49,0x68,0x4b,0xe8,0x48,0xe8,0x4a,0xe8, -0x4e,0x30,0x27,0xf4,0x27,0x0c,0x26,0x0c,0x25,0x0c,0x27,0x8c,0x24,0x8c,0x26,0x8c, -0x25,0x8c,0x27,0x4c,0x26,0x4c,0x25,0x4c,0x27,0x58,0x12,0xe6,0x13,0x16,0x12,0x96, -0x12,0x96,0x13,0x56,0x12,0x56,0x13,0x70,0x89,0xb6,0x89,0xf8,0x44,0x87,0x44,0xa7, -0x44,0x97,0x44,0xb7,0x44,0x8f,0x44,0xaf,0x44,0x62,0xa2,0x6f,0x22,0x29,0x91,0x92, -0x48,0x4b,0xa4,0x27,0x86,0x24,0x86,0x25,0x46,0x24,0x32,0x12,0x59,0x89,0xf1,0x89, -0xec,0x44,0x4e,0x62,0x6a,0x62,0x7a,0x62,0x66,0xa2,0x20,0x51,0x92,0x28,0x4d,0x94, -0x27,0x2a,0x13,0xd5,0x89,0xba,0x44,0x63,0xa2,0x29,0xb1,0x36,0xb1,0x21,0xb1,0x29, -0xb1,0x2d,0xb1,0xf3,0xaf,0xa6,0x2b,0xb1,0x3b,0xd1,0x9c,0xd8,0x9f,0x38,0x98,0x38, -0x94,0x38,0x9c,0x38,0x92,0x38,0x9a,0x38,0x96,0x38,0x9e,0x38,0x95,0x38,0x9d,0x68, -0x49,0x9c,0x4f,0x5c,0x48,0x5c,0x4a,0x5c,0x4e,0x5c,0x49,0x5c,0x4d,0xc4,0x25,0xd9, -0x26,0xe1,0x93,0x1c,0x92,0xdc,0x92,0x88,0x49,0x94,0xa4,0x90,0x24,0x46,0x12,0x3b, -0x29,0x3d,0x49,0x90,0x24,0x4d,0x52,0x27,0x99,0x92,0x9a,0x92,0x3a,0x92,0xcc,0x49, -0x43,0x49,0xa3,0x49,0x93,0x49,0x96,0xa4,0xf9,0xa4,0x85,0xa4,0xa5,0xa4,0x65,0x08, -0x8e,0xed,0xc0,0x76,0x63,0x13,0xd9,0x14,0x36,0x9d,0x1d,0xc6,0x66,0xb0,0xe3,0xd9, -0x1c,0x76,0x3a,0x9b,0xc7,0x16,0xb1,0xa5,0x6c,0x25,0x5b,0xc7,0x36,0xb1,0x1b,0xd8, -0x2d,0xec,0x0e,0x76,0x37,0xbb,0x9f,0x3d,0xc4,0x1e,0x61,0x8f,0xb1,0x27,0xd9,0xd3, -0xec,0x79,0xf6,0x12,0x7b,0x85,0x8d,0x3b,0x81,0x3f,0xe1,0x74,0xc2,0xed,0x84,0xd7, -0x09,0xdf,0x13,0x94,0x13,0xf4,0x13,0x61,0x27,0x18,0x27,0xe2,0x4f,0x70,0x4e,0xa4, -0x9f,0xe0,0x9d,0x10,0x9d,0x90,0x9e,0x50,0x9e,0xd0,0x9d,0x30,0x9d,0x68,0x38,0xd1, -0x72,0xa2,0xe3,0x44,0xf7,0x89,0xfe,0x13,0x43,0x27,0x46,0x4e,0x8c,0x9d,0x98,0x3c, -0x31,0x7d,0x62,0xfe,0xc4,0xd2,0x89,0x95,0x13,0xb8,0x93,0xf8,0x93,0x4e,0x27,0xdd, -0x4e,0x7a,0x9d,0xf4,0x3d,0x49,0x39,0x49,0x3f,0x19,0x76,0x92,0x71,0x32,0xfe,0x24, -0xe7,0x64,0xfa,0x49,0xde,0x49,0xd1,0x49,0xe9,0x49,0xe5,0x49,0xdd,0x49,0xd3,0xc9, -0x86,0x93,0x2d,0x27,0x3b,0x4e,0x76,0x9f,0xec,0x3f,0x39,0x74,0x72,0xe4,0xe4,0xd8, -0xc9,0xc9,0x93,0xd3,0x27,0xe7,0x4f,0x2e,0x9d,0x5c,0x39,0x69,0x9b,0xec,0x94,0xec, -0x91,0xec,0x9b,0x4c,0x4b,0x0e,0x4b,0x66,0x25,0x73,0x92,0x33,0x93,0x45,0xc9,0xf2, -0x64,0x5d,0xb2,0x29,0xb9,0x21,0xb9,0x25,0xb9,0x23,0xb9,0x3b,0xb9,0x3f,0x79,0x28, -0x79,0x24,0x79,0x2c,0x79,0x32,0x79,0x3a,0x79,0x3e,0x79,0x29,0x79,0x25,0x19,0xc7, -0xc1,0x73,0x9c,0x38,0x6e,0x1c,0x2f,0x8e,0x2f,0x87,0xc2,0xa1,0x73,0xc2,0x38,0x0c, -0x4e,0x3c,0x87,0xc3,0x49,0xe7,0xf0,0x38,0x22,0x8e,0x94,0xa3,0xe4,0xe8,0x38,0x26, -0x4e,0x03,0xa7,0x85,0xd3,0xc1,0xe9,0xe6,0xf4,0x73,0x86,0x38,0x23,0x9c,0x31,0xce, -0x24,0x67,0x9a,0x33,0xcf,0x59,0xe2,0xac,0x72,0xf0,0xa7,0x5c,0x4e,0x79,0x9d,0x22, -0x9d,0xa2,0x9d,0x0a,0x39,0x15,0x71,0x8a,0x75,0x8a,0x7d,0x2a,0xf5,0x54,0xe6,0x29, -0xc1,0x29,0xc9,0x29,0xf9,0x29,0xf5,0x29,0xe3,0xa9,0xda,0x53,0x4d,0xa7,0xda,0x4e, -0x75,0x9d,0x32,0x9f,0x1a,0x3c,0x35,0x7c,0x6a,0xf4,0xd4,0xf8,0xa9,0xa9,0x53,0x96, -0x53,0x0b,0xa7,0x96,0x4f,0xad,0x9e,0xb2,0x3d,0xed,0x70,0xda,0xe5,0xb4,0xc7,0x69, -0xe2,0x69,0xd2,0x69,0xda,0xe9,0x90,0xd3,0x11,0xa7,0x59,0xa7,0xd9,0xa7,0x53,0x4f, -0x67,0x9e,0x16,0x9c,0x96,0x9c,0x96,0x9f,0x56,0x9f,0x36,0x9e,0xae,0x3d,0xdd,0x74, -0xba,0xed,0x74,0xd7,0x69,0xf3,0xe9,0xc1,0xd3,0xc3,0xa7,0x47,0x4f,0x8f,0x9f,0x9e, -0x3a,0x6d,0x39,0xbd,0x70,0x7a,0xf9,0xf4,0xea,0x69,0xdb,0x14,0x87,0x14,0x97,0x14, -0x8f,0x14,0x62,0x0a,0x29,0x85,0x96,0x12,0x92,0x12,0x91,0x12,0x9f,0x92,0x9a,0x92, -0x99,0x22,0x48,0x91,0xa4,0xc8,0x53,0xd4,0x29,0xc6,0x94,0xda,0x94,0xa6,0x94,0xb6, -0x94,0xae,0x14,0x73,0xca,0x60,0xca,0x70,0xca,0x68,0xca,0x78,0xca,0x54,0x8a,0x25, -0x65,0x29,0x65,0x35,0x05,0x9f,0xea,0x94,0xea,0x96,0xea,0x95,0xea,0x9b,0x4a,0x49, -0xa5,0xa7,0x86,0xa5,0x32,0x52,0xe3,0x53,0x39,0xa9,0xe9,0x10,0x5e,0xaa,0x28,0x55, -0x9a,0xaa,0x4c,0xd5,0xa5,0x9a,0x52,0x1b,0x52,0x5b,0x52,0x3b,0x52,0xbb,0x53,0xfb, -0x53,0x87,0x52,0x47,0x52,0xc7,0x52,0x27,0x53,0xa7,0x53,0xe7,0x53,0x97,0x52,0x57, -0x52,0x71,0x67,0xf0,0x67,0x9c,0xce,0xb8,0x9d,0xf1,0x3a,0xe3,0x7b,0x86,0x72,0x86, -0x7e,0x26,0xec,0x0c,0xe3,0x4c,0xfc,0x19,0xce,0x99,0xf4,0x33,0xbc,0x33,0xa2,0x33, -0xd2,0x33,0xca,0x33,0xba,0x33,0xa6,0x33,0x0d,0x67,0x5a,0xce,0x74,0x9c,0xe9,0x3e, -0xd3,0x7f,0x66,0xe8,0xcc,0xc8,0x99,0xb1,0x33,0x93,0x67,0xa6,0xcf,0xcc,0x9f,0x59, -0x3a,0xb3,0x72,0x06,0x77,0x16,0x7f,0xd6,0xe9,0xac,0xdb,0x59,0xaf,0xb3,0xbe,0x67, -0x29,0x67,0xe9,0x67,0xc3,0xce,0x32,0xce,0xc6,0xfd,0x09,0xc4,0x9f,0x4d,0x3d,0xcb, -0x3b,0x2b,0x39,0xab,0x3c,0x6b,0x3c,0xdb,0x70,0xb6,0xed,0x6c,0xf7,0xd9,0xc1,0xb3, -0x23,0x67,0xc7,0xcf,0x4e,0x9f,0x5d,0x38,0xbb,0x72,0xd6,0x36,0xcd,0x29,0xcd,0x23, -0xcd,0x37,0x8d,0x96,0x16,0x96,0xc6,0x4a,0xe3,0xa4,0x65,0xa6,0x89,0xd2,0xe4,0x69, -0xba,0xb4,0xda,0xb4,0x96,0xb4,0xae,0xb4,0xfe,0xb4,0xe1,0xb4,0xb1,0xb4,0xa9,0xb4, -0xf9,0xb4,0xe5,0x34,0x5c,0xba,0x43,0xba,0x5b,0x3a,0x31,0x9d,0x92,0x1e,0x92,0xce, -0x48,0x67,0xa7,0xa7,0xa7,0x0b,0xd2,0xa5,0xe9,0xea,0x74,0x53,0x7a,0x53,0x7a,0x47, -0xba,0x39,0x7d,0x28,0x7d,0x34,0x7d,0x32,0xdd,0x92,0xbe,0x94,0xbe,0x9a,0x8e,0xff, -0xc8,0xe5,0x23,0xaf,0x8f,0x48,0x1f,0xd1,0x3f,0x8a,0xf8,0x28,0x0e,0x12,0xff,0x51, -0xea,0x47,0xbc,0x8f,0x24,0x1f,0x29,0x3f,0x32,0x7e,0xd4,0xf0,0x51,0xdb,0x47,0xdd, -0x1f,0x0d,0x7e,0x34,0xf2,0xd1,0xf8,0x47,0xd3,0x1f,0x2d,0x7c,0xb4,0xf2,0x91,0xed, -0xc7,0x4e,0x1f,0x7b,0x7c,0xec,0xfb,0x31,0xed,0xe3,0xb0,0x8f,0x59,0x1f,0x73,0x3e, -0xce,0xfc,0x58,0xf4,0xb1,0xfc,0x63,0xdd,0xc7,0xb5,0x1f,0xb7,0x7c,0xdc,0xf5,0x71, -0xff,0xc7,0xc3,0x1f,0x8f,0x7d,0x3c,0xf5,0xf1,0xfc,0xc7,0xcb,0x1f,0xe3,0x32,0x1c, -0x32,0xdc,0x32,0x88,0x19,0x94,0x8c,0x90,0x0c,0x46,0x06,0x3b,0x23,0x3d,0x43,0x90, -0x21,0xcd,0x50,0x67,0x98,0x32,0x9a,0x32,0x3a,0x32,0xcc,0x19,0x43,0x19,0xa3,0x19, -0x13,0xbf,0x32,0x93,0x19,0x96,0x8c,0xa5,0x0c,0x5c,0xa6,0x53,0xa6,0x57,0x26,0x25, -0x33,0x2c,0x33,0x3e,0x33,0x3d,0x53,0x90,0x69,0xce,0x1c,0xcf,0x9c,0xf9,0x13,0xb1, -0x64,0xce,0x67,0x2e,0x64,0x2e,0x65,0x2e,0x67,0xae,0x64,0xae,0x66,0xe2,0xb2,0x6c, -0xb3,0xf0,0x59,0xce,0x7f,0x06,0x2e,0x59,0x1e,0x59,0x5e,0x59,0xc4,0x2c,0xdf,0x2c, -0x52,0x16,0x25,0x8b,0x96,0x45,0xcf,0x0a,0xc9,0x0a,0xcb,0x8a,0xc8,0x62,0x64,0xb1, -0xb2,0xe2,0xb3,0xd8,0x59,0x9c,0xac,0xd4,0xac,0xf4,0xac,0xcc,0x2c,0x5e,0x16,0x1f, -0x22,0xc8,0x12,0x65,0x49,0xb2,0xe4,0x59,0xea,0x2c,0x63,0x56,0x6d,0x56,0x43,0x56, -0x53,0x56,0x4b,0x56,0x5b,0x56,0x47,0x56,0x67,0x56,0x57,0x56,0x77,0x96,0x39,0xab, -0x3f,0x6b,0x30,0x6b,0x28,0x6b,0x38,0x6b,0x24,0x6b,0x34,0x6b,0x2c,0x6b,0x3c,0x6b, -0x32,0x6b,0x2a,0x6b,0x3a,0xcb,0x92,0x35,0x9f,0xb5,0x90,0xb5,0x94,0xb5,0x9c,0xf5, -0x32,0x6b,0x25,0x6b,0x35,0x0b,0x77,0xce,0xf6,0x9c,0x1d,0x06,0xfe,0x9c,0xd3,0x39, -0xb7,0x73,0x9e,0xe7,0xbc,0xce,0xf9,0x9c,0xf3,0x3d,0x47,0x39,0x47,0x3f,0x17,0x76, -0x8e,0x71,0x2e,0xfe,0x1c,0xe7,0x5c,0xfa,0x39,0xde,0x39,0xd1,0x39,0xe9,0x39,0xf9, -0x39,0xf5,0x39,0xe3,0xb9,0xda,0x73,0x4d,0xe7,0xda,0xce,0x75,0x9d,0x33,0x9f,0x1b, -0x3c,0x37,0x7c,0x6e,0xf4,0xdc,0xf8,0xb9,0xa9,0x73,0xd3,0xe7,0x2c,0xe7,0xe6,0xcf, -0x2d,0x9c,0x5b,0x3a,0xb7,0x7c,0x6e,0xe5,0xdc,0xea,0x39,0x1c,0xd7,0x96,0x8b,0xe7, -0x3a,0x70,0x9d,0xb8,0x2e,0x5c,0x37,0xae,0x07,0xd7,0x8b,0x4b,0xe4,0xfa,0x72,0x49, -0x5c,0x0a,0x97,0xc6,0xa5,0x73,0x43,0xb8,0x61,0xdc,0x08,0x2e,0x83,0xcb,0xe2,0xc6, -0x73,0xd9,0x5c,0x0e,0x37,0x95,0x9b,0xce,0xcd,0xe4,0xf2,0xb8,0x02,0xae,0x88,0x2b, -0xe1,0x4a,0xb9,0x72,0xae,0x92,0xab,0xe6,0xea,0xb8,0x46,0xae,0x89,0x5b,0xcb,0x6d, -0xe0,0x36,0x71,0x5b,0xb8,0x6d,0xdc,0x0e,0x6e,0x17,0xb7,0x9b,0x6b,0xe6,0xf6,0x73, -0x07,0xb9,0x43,0xdc,0x61,0xee,0x08,0x77,0x94,0x3b,0xc6,0x1d,0xe7,0x4e,0x72,0xa7, -0xb8,0xd3,0x5c,0x0b,0x77,0x9e,0xbb,0xc0,0x5d,0xe2,0x2e,0x73,0x57,0xb8,0xab,0x5c, -0x1c,0xcf,0x96,0x87,0xe7,0x39,0xf0,0x9c,0x78,0x2e,0x3c,0x37,0x9e,0x07,0xcf,0x8b, -0x47,0xe4,0xf9,0xf2,0x48,0x3c,0x0a,0x8f,0xc6,0xa3,0xf3,0x42,0x78,0x61,0xbc,0x08, -0x1e,0x83,0xc7,0xe2,0xc5,0xf3,0xd8,0x3c,0x0e,0x2f,0x95,0x97,0xce,0xcb,0xe4,0xf1, -0x78,0x02,0x9e,0x88,0x27,0xe1,0x49,0x79,0x72,0x9e,0x8e,0x57,0xcb,0x6b,0xe1,0x75, -0xf1,0xfa,0x79,0xc3,0xbc,0x51,0xde,0xe3,0x5f,0x18,0xe7,0x4d,0xf2,0xa6,0x78,0xd3, -0x3c,0x0b,0x6f,0x9e,0xb7,0xc0,0x5b,0xe2,0x2d,0xf3,0x56,0x78,0xab,0x3c,0x5c,0xb6, -0x6d,0x36,0x3e,0xdb,0x21,0xdb,0x29,0xdb,0x25,0xdb,0x2d,0xdb,0x23,0xdb,0x2b,0x9b, -0x98,0xed,0x9b,0x4d,0xca,0xa6,0x64,0xd3,0xb2,0xe9,0xd9,0x21,0xd9,0x61,0xd9,0x11, -0xd9,0x8c,0x6c,0x56,0x76,0x7c,0x36,0x3b,0x9b,0x93,0x9d,0x9a,0x9d,0x9e,0x9d,0x99, -0xcd,0xcb,0x16,0x64,0x8b,0xb2,0x25,0xd9,0xd2,0x6c,0x79,0xb6,0x32,0x5b,0x9d,0xad, -0xcb,0x36,0x66,0x9b,0xb2,0x6b,0xb3,0x1b,0xb2,0x9b,0xb2,0x5b,0xb2,0xdb,0xb2,0x3b, -0xb2,0xbb,0xb2,0xbb,0xb3,0xcd,0xd9,0xfd,0xd9,0x83,0xd9,0x43,0xd9,0xc3,0xd9,0x23, -0xd9,0xa3,0xd9,0x63,0xd9,0xe3,0xd9,0x93,0xd9,0x53,0xd9,0xd3,0xd9,0x96,0xec,0xf9, -0xec,0x85,0xec,0xa5,0xec,0xe5,0xec,0x95,0xec,0xd5,0x6c,0x5c,0x8e,0x6d,0x0e,0x3e, -0xc7,0x21,0xc7,0x29,0xc7,0x25,0xc7,0x2d,0xc7,0x23,0xc7,0x2b,0x87,0x98,0xe3,0x9b, -0x43,0xca,0xa1,0xe4,0xd0,0x72,0xe8,0x39,0x21,0x39,0x61,0x39,0x11,0x39,0x8c,0x1c, -0x56,0x4e,0x7c,0x0e,0x3b,0x87,0x93,0x93,0x9a,0x93,0x9e,0x93,0x99,0xc3,0xcb,0x11, -0xe4,0x88,0x72,0x24,0x39,0xd2,0x1c,0x79,0x8e,0x32,0x47,0x9d,0xa3,0xcb,0x31,0xe6, -0x98,0x72,0x6a,0x73,0x1a,0x72,0x9a,0x72,0x5a,0x72,0xda,0x72,0x3a,0x72,0xba,0x72, -0xba,0x73,0xcc,0x39,0xfd,0x39,0x83,0x39,0x43,0x39,0xc3,0x39,0x23,0x39,0xa3,0x39, -0x63,0x39,0xe3,0x39,0x93,0x39,0x53,0x39,0xd3,0x39,0x96,0x9c,0xf9,0x9c,0x85,0x9c, -0xa5,0x9c,0xe5,0x9c,0x95,0x9c,0xd5,0x1c,0x1c,0xdf,0x96,0x8f,0xe7,0x3b,0xf0,0x9d, -0xf8,0x2e,0x7c,0x37,0xbe,0x07,0xdf,0x8b,0x4f,0xe4,0xfb,0xf2,0x49,0x7c,0x0a,0x9f, -0xc6,0xa7,0xf3,0x43,0xf8,0x61,0xfc,0x08,0x3e,0x03,0xbe,0x28,0xc7,0xf3,0xd9,0x7c, -0x0e,0x3f,0x95,0x9f,0xce,0xcf,0xe4,0xf3,0xf8,0x02,0xbe,0x88,0x2f,0xe1,0x4b,0xf9, -0x72,0xbe,0x92,0xaf,0xe6,0xeb,0xf8,0x46,0xbe,0x89,0x5f,0xcb,0x6f,0xe0,0x37,0xf1, -0x5b,0xf8,0x6d,0xfc,0x0e,0x7e,0x17,0xbf,0x9b,0x6f,0xe6,0xf7,0xf3,0x07,0xf9,0x43, -0xfc,0x61,0xfe,0x08,0xff,0xa1,0x95,0x51,0xfe,0x18,0x7f,0x9c,0x3f,0xc9,0x9f,0xe2, -0x4f,0xf3,0x67,0x20,0x16,0xfe,0x3c,0x7f,0x81,0xbf,0xc4,0x5f,0xe6,0xaf,0xf0,0x5f, -0x41,0x56,0xf9,0x38,0x81,0xad,0x00,0x2f,0x70,0x10,0x38,0x09,0x9c,0x21,0x2e,0x02, -0x37,0x81,0x87,0xc0,0xd3,0x8a,0x97,0x80,0x28,0xf0,0x15,0x90,0x04,0x34,0x01,0x5d, -0x10,0x22,0x08,0x15,0x84,0x09,0x22,0x04,0x0c,0x01,0x4b,0x10,0x2f,0x60,0x0b,0x38, -0x82,0x94,0x75,0xfe,0x04,0x52,0x05,0xe9,0x82,0x4c,0x01,0x4f,0x20,0x10,0x08,0x05, -0x22,0x81,0x44,0x20,0x15,0xc8,0x05,0x4a,0x81,0x5a,0xa0,0x13,0x18,0x05,0x26,0x41, -0xad,0xa0,0x41,0xd0,0x24,0x68,0x11,0xb4,0x09,0x3a,0x04,0x5d,0x82,0x6e,0x81,0x59, -0xd0,0x2f,0x18,0x14,0x0c,0x09,0x86,0x05,0x23,0x82,0x51,0xc1,0x98,0x60,0x5c,0x30, -0x29,0x98,0x12,0x4c,0x0b,0x2c,0x82,0x79,0xc1,0x82,0x60,0x49,0xb0,0x2c,0x58,0x11, -0xac,0x0a,0x70,0xe7,0x6d,0xcf,0xe3,0xcf,0x3b,0x9c,0x77,0x3a,0xef,0x72,0xde,0xf5, -0xbc,0xdb,0x79,0x8f,0xf3,0x5e,0xe7,0x89,0xe7,0x7d,0xcf,0x93,0xce,0x53,0xce,0xd3, -0xce,0xd3,0xcf,0x07,0xaf,0xf3,0x4f,0x4e,0x38,0x84,0xf9,0x3f,0x92,0xb4,0x8e,0x95, -0x94,0xf3,0x19,0xeb,0xac,0xf3,0x17,0xc1,0x3f,0x2f,0x5e,0x67,0x9d,0x7f,0x61,0x64, -0xe7,0x55,0x10,0xc3,0x3a,0xff,0xa6,0xd4,0x9c,0x6f,0xfc,0x37,0xa6,0x75,0x9d,0x75, -0x7e,0x35,0x3a,0xcf,0xf7,0x9e,0xbf,0x77,0xfe,0xe1,0xf9,0x89,0xf3,0x33,0xe7,0x17, -0xff,0xa9,0x78,0x79,0x1e,0xe4,0xda,0xe7,0xba,0xe6,0x7a,0xe7,0x92,0xd7,0x59,0xe7, -0xff,0x22,0x14,0x08,0x2d,0x97,0x9e,0x1b,0x92,0x1b,0x96,0x1b,0x91,0xcb,0xc8,0x65, -0xe5,0xc6,0xe7,0xb2,0x73,0x39,0xb9,0xa9,0xb9,0xe9,0xb9,0x99,0xb9,0xbc,0x5c,0x41, -0xae,0x28,0x57,0x92,0x2b,0xcd,0x95,0xe7,0x2a,0x73,0xd5,0xb9,0xba,0x5c,0x63,0xae, -0x29,0xb7,0x36,0xb7,0x21,0xb7,0x29,0xb7,0x25,0xb7,0x2d,0xb7,0x23,0xb7,0x2b,0xb7, -0x3b,0xd7,0x9c,0xdb,0x9f,0x3b,0x98,0x3b,0x94,0x3b,0x9c,0x3b,0x92,0x3b,0x9a,0x3b, -0x96,0x3b,0x9e,0x3b,0x99,0x3b,0x95,0x3b,0x9d,0x6b,0xc9,0x9d,0xcf,0x5d,0xc8,0x5d, -0xca,0x5d,0xce,0x5d,0xc9,0x5d,0xcd,0xc5,0x09,0x6d,0x85,0x78,0xa1,0x83,0xd0,0x49, -0xe8,0x22,0x74,0x13,0x7a,0x08,0xbd,0x84,0x44,0xa1,0xaf,0x90,0x24,0xa4,0x08,0x69, -0x42,0xba,0x30,0x44,0x18,0x26,0x8c,0x10,0x32,0x84,0x2c,0x61,0xbc,0x90,0x2d,0xe4, -0x08,0x53,0x85,0xe9,0xc2,0x4c,0x21,0x4f,0x28,0x10,0x8a,0x84,0x12,0xa1,0x54,0x28, -0x17,0x2a,0x85,0x2a,0xa1,0x5a,0xa8,0x13,0x1a,0x85,0x26,0x61,0xad,0xb0,0x41,0xd8, -0x24,0x6c,0x11,0xb6,0x09,0x3b,0x84,0x5d,0xc2,0x6e,0xa1,0x59,0xd8,0x2f,0x1c,0x14, -0x0e,0x09,0x87,0x85,0x23,0xc2,0x51,0xe1,0x98,0x70,0x5c,0x38,0x29,0x9c,0x12,0x4e, -0x0b,0x2d,0xc2,0x79,0xe1,0x82,0x70,0x49,0xb8,0x2c,0x5c,0x11,0xae,0x0a,0x71,0x22, -0x5b,0x11,0x5e,0xe4,0x20,0x72,0x12,0xb9,0x88,0xdc,0x44,0x1e,0x22,0x2f,0x11,0x51, -0xe4,0x2b,0x22,0x89,0x28,0x22,0x9a,0x88,0x2e,0x0a,0x11,0x85,0x89,0x22,0x44,0x0c, -0x11,0x4b,0x14,0x2f,0x62,0x8b,0x38,0xa2,0x54,0x51,0xba,0x28,0x53,0xc4,0x13,0x09, -0x44,0x22,0x91,0x44,0x24,0x15,0xc9,0x45,0x4a,0x91,0x5a,0xa4,0x13,0x19,0x45,0x26, -0x51,0xad,0xa8,0x41,0xd4,0x24,0x6a,0x16,0xb5,0x88,0xda,0x44,0xed,0x90,0x0e,0x51, -0x27,0xa4,0x4b,0xd4,0x2d,0xea,0x85,0x98,0x45,0xfd,0xa2,0x41,0xd1,0x90,0xe8,0xbe, -0x68,0x58,0x34,0x22,0x1a,0x15,0x8d,0x89,0xc6,0x45,0x93,0xa2,0x29,0xd1,0xb4,0xc8, -0x22,0x9a,0x17,0x2d,0x88,0x96,0x44,0x2f,0x44,0xcb,0xa2,0x97,0xa2,0x15,0xd1,0xaa, -0x08,0x97,0x67,0x9b,0x87,0xcf,0x73,0xc8,0x73,0xca,0x73,0xce,0x73,0xc9,0x73,0xcb, -0xf3,0xc8,0xf3,0xca,0x23,0xe6,0xf9,0xe6,0x91,0xf2,0x28,0x79,0xb4,0x3c,0x7a,0x5e, -0x48,0x5e,0x58,0x5e,0x44,0x1e,0x23,0x8f,0x95,0x17,0x9f,0xc7,0xce,0xe3,0xe4,0xa5, -0xe6,0xa5,0xe7,0x65,0xe6,0xf1,0xf2,0x04,0x79,0xa2,0x3c,0x49,0x9e,0x34,0x4f,0x9e, -0xa7,0xcc,0x53,0xe7,0xe9,0xf2,0x8c,0x79,0xa6,0xbc,0xda,0xbc,0x86,0xbc,0xa6,0xbc, -0x96,0xbc,0xb6,0xbc,0x8e,0xbc,0xae,0xbc,0xee,0x3c,0x73,0x5e,0x7f,0xde,0x60,0xde, -0x50,0xde,0x70,0xde,0x48,0xde,0x68,0xde,0x58,0xde,0x78,0xde,0x64,0xde,0x54,0xde, -0x74,0x9e,0x25,0x6f,0x3e,0x6f,0x21,0x6f,0x29,0x6f,0x39,0x6f,0x25,0x6f,0x35,0x0f, -0x97,0x8f,0xcb,0xb7,0xcd,0xc7,0xe7,0x3b,0xe4,0x3b,0xe5,0xbb,0xe4,0xbb,0xe6,0xbb, -0xe5,0x7b,0xe4,0x7b,0xe5,0x13,0xf3,0x7d,0x20,0xbe,0xf9,0xa4,0x7c,0x4a,0x3e,0x2d, -0x9f,0x9e,0x1f,0x92,0x1f,0x96,0x1f,0x91,0x1f,0x99,0xcf,0xc8,0x67,0xe5,0xc7,0xe7, -0xb3,0xf3,0x39,0xf9,0xa9,0xf9,0xe9,0xf9,0x19,0xf9,0x99,0xf9,0xbc,0x7c,0x41,0xbe, -0x28,0x5f,0x92,0x2f,0xcd,0x97,0xe7,0x2b,0xf3,0xd5,0xf9,0xba,0x7c,0x63,0xbe,0x29, -0xbf,0x36,0xbf,0x21,0xbf,0x29,0xbf,0x25,0xbf,0x2d,0xbf,0x23,0xbf,0x2b,0xbf,0x3b, -0xdf,0x9c,0xdf,0x9f,0x3f,0x98,0x3f,0x94,0x3f,0x9c,0x3f,0x92,0x3f,0x9a,0x3f,0x96, -0xff,0x38,0x7f,0x3c,0x7f,0x32,0x7f,0x2a,0x7f,0x3a,0x7f,0x26,0xdf,0x92,0x3f,0x9f, -0xbf,0x90,0xbf,0x94,0xbf,0x9c,0xff,0x32,0x7f,0x25,0xff,0x95,0x95,0xd5,0x7c,0x9c, -0xd8,0x56,0x8c,0x17,0x3b,0x88,0x9d,0xc4,0x2e,0x62,0x57,0xb1,0x9b,0xd8,0x43,0xec, -0x25,0x26,0x8a,0x7d,0xc5,0x24,0x31,0x45,0x4c,0x13,0xd3,0xc5,0x21,0xe2,0x30,0x71, -0x84,0x98,0x21,0x66,0x89,0xe3,0xc5,0x6c,0x31,0x47,0x9c,0x2a,0x4e,0x17,0x67,0x8a, -0x79,0x62,0x81,0x58,0x24,0x96,0x88,0xa5,0x62,0xb9,0x58,0x29,0x56,0x8b,0x75,0x62, -0xa3,0xd8,0x24,0xae,0x15,0x37,0x88,0x9b,0xc4,0x2d,0xe2,0x36,0x71,0x87,0xb8,0x4b, -0xdc,0x2d,0x36,0x8b,0xfb,0xc5,0x83,0xe2,0x21,0xf1,0xb0,0x78,0x44,0x3c,0x2a,0x1e, -0x13,0x8f,0x8b,0x27,0xc5,0x53,0xe2,0x69,0xb1,0x45,0x3c,0x2f,0x5e,0x10,0x2f,0x89, -0x97,0xc5,0x2b,0xe2,0x55,0x31,0x4e,0x62,0x2b,0xc1,0x4b,0x1c,0x24,0x4e,0x12,0x17, -0x89,0x9b,0xc4,0x43,0xe2,0x25,0x21,0x4a,0x7c,0x25,0x24,0x09,0x45,0x42,0x93,0xd0, -0x25,0x21,0x92,0x30,0x49,0x84,0x84,0x21,0x61,0x49,0xe2,0x25,0x6c,0x09,0x47,0x92, -0x2a,0x49,0x97,0x64,0x4a,0x78,0x12,0x81,0x44,0x24,0x91,0x48,0xa4,0x12,0xb9,0x44, -0x29,0x51,0x4b,0x74,0x12,0xa3,0xc4,0x24,0xa9,0x95,0x34,0x48,0x9a,0x24,0x2d,0x92, -0x36,0x49,0x87,0xa4,0x4b,0xd2,0x2d,0x31,0x4b,0xfa,0x25,0x83,0x92,0x21,0xc9,0xb0, -0x64,0x44,0x32,0x2a,0x19,0x93,0x8c,0x4b,0x26,0x25,0x53,0x92,0x69,0x89,0x45,0x32, -0x2f,0x59,0x90,0x2c,0x49,0x96,0x25,0x2b,0x92,0x55,0x09,0xae,0xc0,0xb6,0x00,0x5f, -0xe0,0x50,0xe0,0x54,0xe0,0x52,0xe0,0x56,0xe0,0x51,0xe0,0x55,0x40,0x2c,0xf0,0x2d, -0x20,0x15,0x50,0x0a,0x68,0x05,0xf4,0x82,0x90,0x82,0xb0,0x82,0x88,0x02,0x46,0x01, -0xab,0x20,0xbe,0x80,0x5d,0xc0,0x29,0x48,0x2d,0x48,0x2f,0xc8,0x2c,0xe0,0x15,0x08, -0x0a,0x44,0x05,0x92,0x02,0x69,0x81,0xbc,0x40,0x59,0xa0,0x2e,0xd0,0x15,0x18,0x0b, -0x4c,0x05,0xb5,0x05,0x0d,0x05,0x4d,0x05,0x2d,0x05,0x6d,0x05,0x1d,0x05,0x5d,0x05, -0xdd,0x05,0xe6,0x82,0xfe,0x82,0xc1,0x82,0xa1,0x82,0xe1,0x82,0x91,0x82,0xd1,0x82, -0x31,0xc8,0x78,0xc1,0x64,0xc1,0x54,0xc1,0x74,0x81,0xa5,0x60,0xbe,0x60,0xa1,0x60, -0xa9,0x60,0xb9,0x60,0xa5,0x60,0xb5,0x00,0x57,0x68,0x5b,0x88,0x2f,0x74,0x28,0x74, -0x2a,0x74,0x29,0x74,0x2b,0xf4,0x28,0xf4,0x2a,0x24,0x16,0xfa,0x16,0x92,0x0a,0x29, -0x85,0xb4,0x42,0x7a,0x61,0x48,0x61,0x58,0x61,0x44,0x21,0xa3,0x90,0x55,0x18,0x5f, -0xc8,0x2e,0xe4,0x14,0xa6,0x16,0xa6,0x17,0x66,0x16,0xf2,0x0a,0x05,0x85,0xa2,0x42, -0x49,0xa1,0xb4,0x50,0x5e,0xa8,0x2c,0x54,0x17,0xea,0x0a,0x8d,0x85,0xa6,0xc2,0xda, -0xc2,0x86,0xc2,0xa6,0xc2,0x96,0xc2,0xb6,0xc2,0x8e,0xc2,0xae,0xc2,0xee,0x42,0x73, -0x61,0x7f,0xe1,0x60,0xe1,0x50,0xe1,0x70,0xe1,0x48,0xe1,0x68,0xe1,0x58,0xe1,0x78, -0xe1,0x64,0xe1,0x54,0xe1,0x74,0xa1,0xa5,0x70,0xbe,0x70,0xa1,0x70,0xa9,0x70,0xb9, -0x70,0xa5,0x70,0xb5,0x10,0x57,0x64,0x5b,0x84,0x2f,0x72,0x28,0x72,0x2a,0x72,0x29, -0x72,0x2b,0xf2,0x28,0xf2,0x2a,0x22,0x16,0xf9,0x16,0x91,0x8a,0x28,0x45,0xb4,0x22, -0x7a,0x51,0x48,0x51,0x58,0x51,0x44,0x11,0xa3,0x88,0x55,0x14,0x5f,0xc4,0x2e,0xe2, -0x14,0xa5,0x16,0xa5,0x17,0x65,0x16,0xf1,0x8a,0x04,0x45,0xa2,0x22,0x49,0x91,0xb4, -0x48,0x5e,0xa4,0x2c,0x52,0x17,0xe9,0x8a,0x8c,0x45,0xa6,0xa2,0xda,0xa2,0x86,0xa2, -0xa6,0xa2,0x96,0xa2,0xb6,0xa2,0x8e,0xa2,0xae,0xa2,0xee,0x22,0x73,0x51,0x7f,0xd1, -0x60,0xd1,0x50,0xd1,0x70,0xd1,0x48,0xd1,0x68,0xd1,0x58,0xd1,0x78,0xd1,0x64,0xd1, -0x54,0xd1,0x74,0x91,0xa5,0x68,0xbe,0x68,0xa1,0x68,0xa9,0x68,0xb9,0x68,0xa5,0x68, -0xb5,0x08,0x27,0xb5,0x95,0xe2,0xa5,0x0e,0x52,0x27,0xa9,0x8b,0xd4,0x4d,0xea,0x21, -0xf5,0x92,0x12,0xa5,0xbe,0x52,0x92,0x94,0x22,0xa5,0x49,0xe9,0xd2,0x10,0x69,0x98, -0x34,0x42,0xca,0x90,0xb2,0xa4,0xf1,0x52,0xb6,0x94,0x23,0x4d,0x95,0xa6,0x4b,0x33, -0xa5,0x5c,0x08,0x4f,0x2a,0x90,0x8a,0xa4,0x12,0xa9,0x54,0x2a,0x97,0x2a,0xa5,0x6a, -0xa9,0x4e,0x6a,0x94,0x9a,0xa4,0xb5,0xd2,0x06,0x69,0x93,0xb4,0x45,0xda,0x26,0xed, -0x90,0x76,0x49,0xbb,0xa5,0x66,0x69,0xbf,0x74,0x50,0x3a,0x24,0x1d,0x96,0x8e,0x48, -0x47,0xa5,0x63,0xd2,0x71,0xe9,0xa4,0x74,0x4a,0x3a,0x2d,0xb5,0x48,0xe7,0xa5,0x0b, -0xd2,0x25,0xe9,0xb2,0x74,0x45,0xba,0x2a,0xc5,0x15,0xdb,0x16,0xe3,0x8b,0x1d,0x8a, -0x9d,0x8a,0x5d,0x8a,0xdd,0x8a,0x3d,0x8a,0xbd,0x8a,0x89,0xc5,0xbe,0xc5,0xa4,0x62, -0x4a,0x31,0xad,0x98,0x5e,0x1c,0x52,0x1c,0x56,0x1c,0x51,0xcc,0x28,0x66,0x15,0xc7, -0x17,0xb3,0x8b,0x39,0xc5,0xa9,0xc5,0xe9,0xc5,0x99,0xc5,0xbc,0x62,0x41,0xb1,0xa8, -0x58,0x52,0x2c,0x2d,0x96,0x17,0x2b,0x8b,0xd5,0xc5,0xba,0x62,0x63,0xb1,0xa9,0xb8, -0xb6,0xb8,0xa1,0xb8,0xa9,0xb8,0xa5,0xb8,0xad,0xb8,0xa3,0xb8,0xab,0xb8,0xbb,0xd8, -0x5c,0xdc,0x5f,0x3c,0x58,0x3c,0x54,0x3c,0x5c,0x3c,0x02,0x19,0x2d,0x1e,0x2b,0x1e, -0x2f,0x9e,0x2c,0x9e,0x2a,0x9e,0x2e,0xb6,0x14,0xcf,0x17,0x2f,0x14,0x2f,0x15,0x2f, -0x17,0xaf,0x14,0xaf,0x16,0xe3,0x4a,0x6c,0x4b,0xf0,0x25,0x0e,0x25,0x4e,0x25,0x2e, -0x25,0x6e,0x25,0x1e,0x25,0x5e,0x25,0xc4,0x12,0xdf,0x12,0x52,0x09,0xa5,0x84,0x56, -0x42,0x2f,0x09,0x29,0x09,0x2b,0x89,0x28,0x61,0x94,0xb0,0x4a,0xe2,0x4b,0xd8,0x25, -0x9c,0x92,0xd4,0x92,0xf4,0x92,0xcc,0x12,0x5e,0x89,0xa0,0x44,0x54,0x22,0x29,0x91, -0x96,0xc8,0x4b,0x94,0x25,0xea,0x12,0x5d,0x89,0xb1,0xc4,0x54,0x52,0x5b,0xd2,0x50, -0xd2,0x54,0xd2,0x52,0xd2,0x56,0xd2,0x51,0xd2,0x55,0xd2,0x5d,0x62,0x2e,0xe9,0x2f, -0x19,0x2c,0x19,0x2a,0x19,0x2e,0x19,0x29,0x19,0x2d,0x19,0x2b,0x19,0x2f,0x99,0x2c, -0x99,0x2a,0x99,0x2e,0xb1,0x94,0xcc,0x97,0x2c,0x94,0x2c,0x95,0x2c,0x97,0xac,0x94, -0xac,0x96,0xe0,0x64,0xb6,0x32,0xbc,0xcc,0x41,0xe6,0x24,0x73,0x91,0xb9,0xc9,0x3c, -0x64,0x5e,0x32,0xa2,0xcc,0x57,0x46,0x92,0x51,0x64,0x34,0x19,0x5d,0x16,0x22,0x0b, -0x93,0x45,0xc8,0x18,0x32,0x96,0x2c,0x5e,0xc6,0x96,0x71,0x64,0xa9,0xb2,0x74,0x59, -0xa6,0x8c,0x27,0x13,0xc8,0x44,0x32,0x89,0x4c,0x2a,0x93,0xcb,0x94,0x32,0xb5,0x4c, -0x27,0x33,0xca,0x4c,0xb2,0x5a,0x59,0x83,0xac,0x49,0xd6,0x22,0x6b,0x93,0x75,0xc8, -0xba,0x64,0xdd,0x32,0xb3,0xac,0x5f,0x36,0x28,0x1b,0x92,0x0d,0xcb,0x46,0x64,0xa3, -0xb2,0x31,0xd9,0xb8,0x6c,0x52,0x36,0x25,0x9b,0x96,0x59,0x64,0xf3,0xb2,0x05,0xd9, -0x92,0x6c,0x59,0xb6,0x22,0x5b,0x95,0xe1,0xe4,0xb6,0x72,0xbc,0xdc,0x41,0xee,0x24, -0x77,0x91,0xbb,0xc9,0x3d,0xe4,0x5e,0x72,0xa2,0xdc,0x57,0x4e,0x92,0x53,0xe4,0x34, -0x39,0x5d,0x1e,0x22,0x0f,0x93,0x47,0xc8,0x19,0x72,0x96,0x3c,0x5e,0xce,0x96,0x73, -0xe4,0xa9,0xf2,0x74,0x79,0xa6,0x9c,0x27,0x17,0xc8,0x45,0x72,0x89,0x5c,0x2a,0x97, -0xcb,0x95,0x72,0xb5,0x5c,0x27,0x37,0xca,0x4d,0xf2,0x5a,0x79,0x83,0xbc,0x49,0xde, -0x22,0x6f,0x93,0x77,0xc8,0xbb,0xe4,0xdd,0x72,0xb3,0xbc,0x5f,0x3e,0x28,0x1f,0x92, -0x0f,0xcb,0x47,0xe4,0xa3,0xf2,0x31,0xf9,0xb8,0x7c,0x52,0x3e,0x25,0x9f,0x96,0x5b, -0xe4,0xf3,0xf2,0x05,0xf9,0x92,0x7c,0x59,0xfe,0x12,0xb2,0x22,0x5f,0x95,0xe3,0x4a, -0x6d,0x4b,0xf1,0xa5,0x0e,0xa5,0x4e,0xa5,0x2e,0xa5,0x6e,0xa5,0x1e,0xa5,0x5e,0xa5, -0xc4,0x52,0xdf,0x52,0x52,0x29,0xa5,0x94,0x56,0x4a,0x2f,0x0d,0x29,0x0d,0x2b,0x8d, -0x28,0x65,0x94,0xb2,0x4a,0xe3,0x4b,0xd9,0xa5,0x9c,0xd2,0xd4,0xd2,0xf4,0xd2,0xcc, -0x52,0x5e,0xa9,0xa0,0x54,0x54,0x2a,0x29,0x95,0x96,0xca,0x4b,0x95,0xa5,0xea,0x52, -0x5d,0xa9,0xb1,0xd4,0x54,0x5a,0x5b,0xda,0x50,0xda,0x54,0xda,0x52,0xda,0x56,0xda, -0x51,0xda,0x55,0xda,0x5d,0x6a,0x2e,0xed,0x2f,0x1d,0x2c,0xbd,0xf7,0x37,0x67,0xa8, -0x74,0xb8,0x74,0xa4,0x74,0xb4,0x74,0xac,0x74,0xbc,0x74,0xb2,0x74,0xaa,0x74,0xba, -0xd4,0x52,0x3a,0x5f,0xba,0x50,0xba,0x54,0xba,0x5c,0xba,0x52,0xba,0x5a,0x8a,0x2b, -0xb3,0x2d,0xc3,0x97,0x39,0x94,0x39,0x95,0xb9,0x94,0xb9,0x95,0x79,0x94,0x79,0x95, -0x11,0xcb,0x7c,0xcb,0x48,0x65,0x94,0x32,0x5a,0x19,0xbd,0x2c,0xa4,0x2c,0xac,0x2c, -0xa2,0x8c,0x51,0xc6,0x2a,0x8b,0x2f,0x63,0x97,0x71,0xca,0x52,0xcb,0xd2,0xcb,0x32, -0xcb,0x78,0x65,0x82,0x32,0x51,0x99,0xa4,0x4c,0x5a,0x26,0x2f,0x53,0x96,0xa9,0xcb, -0x74,0x65,0xc6,0x32,0x53,0x59,0x6d,0x59,0x43,0x59,0x53,0x59,0x4b,0x59,0x5b,0x59, -0x47,0x59,0x57,0x59,0x77,0x99,0xb9,0xac,0x6f,0x9d,0x75,0xd6,0xf9,0x23,0xf4,0x43, -0x06,0xcb,0x86,0xca,0x86,0xcb,0x1e,0x94,0x8d,0x94,0x8d,0x96,0x8d,0x95,0x8d,0x97, -0x4d,0x96,0x4d,0x95,0x4d,0x97,0x59,0xca,0xe6,0xcb,0x16,0xca,0x96,0xca,0x96,0xcb, -0x56,0xca,0x56,0xcb,0x70,0x0a,0x5b,0x05,0x5e,0xe1,0xa0,0x70,0x52,0xb8,0x28,0xdc, -0x14,0x1e,0x0a,0x2f,0x05,0x51,0xe1,0xab,0x20,0x29,0x28,0x0a,0xaa,0x82,0xa6,0xa0, -0x2b,0x82,0x15,0x21,0x8a,0x50,0x48,0x98,0x22,0x5c,0x11,0xa1,0x60,0x28,0x58,0x8a, -0x78,0x05,0x5b,0xc1,0x51,0xa4,0x2a,0xd2,0x15,0x99,0x0a,0x9e,0x82,0xaf,0x10,0x28, -0x44,0x0a,0x89,0x42,0xaa,0x90,0x29,0xe4,0x0a,0x85,0x42,0xa9,0x50,0xbd,0x81,0x5a, -0xa1,0xc5,0xd0,0x29,0x0c,0x0a,0xa3,0xa2,0x5a,0x61,0x52,0xd4,0x28,0x6a,0x15,0x0d, -0x8a,0x26,0x45,0xb3,0xa2,0x45,0xd1,0xa6,0x68,0x57,0x74,0x28,0x3a,0x21,0x5d,0x8a, -0x1b,0x8a,0x6e,0x45,0xaf,0xc2,0xac,0xe8,0x53,0xf4,0x2b,0x06,0x14,0x83,0x8a,0x7b, -0x8a,0x21,0xc5,0xb0,0xe2,0x81,0x62,0x44,0xf1,0x10,0x32,0xaa,0x18,0x53,0x8c,0x2b, -0x26,0x15,0x4f,0x14,0x53,0x8a,0x69,0x85,0x45,0x31,0xaf,0x58,0x50,0x2c,0x29,0x96, -0x15,0x2f,0x15,0x2b,0x8a,0x55,0x05,0x4e,0x69,0xab,0xb4,0x53,0xe2,0x95,0x0e,0x4a, -0x27,0xa5,0x8b,0xd2,0x55,0xe9,0xa6,0x74,0x57,0x7a,0x28,0xbd,0x94,0x44,0xa5,0xaf, -0x92,0xa4,0xa4,0x28,0x69,0x4a,0xba,0x32,0x44,0x19,0xa6,0x0c,0x57,0x46,0x28,0x19, -0x4a,0x96,0x32,0x5e,0xc9,0x56,0x72,0x94,0xa9,0xca,0x74,0x65,0xa6,0x92,0xa7,0x14, -0x28,0x45,0x4a,0x89,0x52,0xaa,0x94,0x2b,0x95,0x4a,0xb5,0x52,0xfb,0x0b,0x3a,0xa5, -0x51,0x69,0x52,0xd6,0x28,0x6b,0x95,0x0d,0xca,0x26,0x65,0x8b,0xb2,0x4d,0xd9,0xae, -0xec,0x50,0x76,0x29,0xbb,0x95,0x66,0x65,0xbf,0x72,0x50,0x39,0xa4,0x1c,0x56,0x8e, -0x28,0x47,0x95,0x63,0xca,0x71,0xe5,0xa4,0x72,0x4a,0x39,0xad,0xb4,0x28,0xe7,0x95, -0xcf,0xd7,0x59,0xe7,0x1f,0x82,0x05,0xc8,0xb2,0x72,0x55,0x69,0x5b,0xee,0x50,0xee, -0x52,0xee,0x51,0x4e,0x2c,0x27,0x95,0xd3,0xca,0x43,0xca,0xc3,0x7f,0x21,0xa2,0x3c, -0xbe,0x3c,0xb5,0x9c,0x57,0x2e,0x29,0x57,0x96,0x1b,0xcb,0x1b,0xca,0xdb,0xca,0xbb, -0xcb,0x07,0xcb,0x47,0xca,0xc7,0xcb,0xa7,0xcb,0x17,0xca,0x57,0xca,0x6d,0x2b,0x9c, -0x2a,0x3c,0x2a,0x7c,0x2b,0x68,0x15,0x61,0x15,0xac,0x0a,0x4e,0x45,0x66,0x85,0xa8, -0x42,0x5e,0xa1,0xab,0x30,0x56,0x98,0x2a,0x1a,0x2a,0x9a,0x2b,0x5a,0x2a,0xda,0x2a, -0x3a,0x2a,0xba,0x2a,0xba,0x2b,0xcc,0x15,0xfd,0x15,0x83,0x15,0x43,0x15,0xc3,0x15, -0x23,0x15,0xa3,0x15,0x63,0x15,0xe3,0x15,0x93,0x15,0x53,0x15,0xd3,0x15,0x96,0x8a, -0xf9,0x8a,0x85,0x8a,0xa5,0x8a,0xe5,0x8a,0x95,0x8a,0xd5,0x0a,0x9c,0xca,0x56,0x85, -0x57,0x39,0xa9,0xdc,0x54,0x5e,0x2a,0x5f,0x15,0x4d,0x15,0xfc,0x17,0x10,0xa2,0x8a, -0x50,0xb1,0x54,0x49,0xbf,0x0a,0x6c,0x55,0xca,0xbf,0x34,0xa9,0x90,0x4c,0x95,0x40, -0x25,0xfc,0x83,0x88,0x54,0x12,0x95,0x54,0x25,0x57,0xa9,0x55,0x3a,0x95,0x51,0x65, -0x52,0xd5,0xaa,0x1a,0x54,0x4d,0xaa,0x16,0x55,0x9b,0xaa,0x43,0xd5,0xa5,0xea,0x56, -0x99,0x55,0xfd,0xaa,0x41,0xd5,0x90,0x6a,0x58,0x35,0xa2,0x1a,0x55,0x8d,0xa9,0xc6, -0x55,0x93,0xaa,0x29,0xd5,0xb4,0xca,0xa2,0x9a,0x57,0x2d,0xa8,0x96,0x54,0xcb,0xaa, -0x15,0xd5,0xaa,0x0a,0xa7,0xb6,0x55,0xe3,0xd5,0x0e,0x6a,0x27,0xb5,0x8b,0xda,0x4d, -0xed,0xa1,0xf6,0x52,0x7b,0x63,0x10,0xd5,0x14,0x75,0x88,0x9a,0xa1,0x66,0xab,0xd3, -0xd5,0x02,0xb5,0x54,0xad,0x56,0x57,0xff,0x16,0x26,0x75,0xad,0xba,0x7e,0x9d,0x75, -0xd6,0xf9,0x0b,0x69,0x50,0x37,0xa9,0x5b,0xd4,0x6d,0xea,0x0e,0x75,0x97,0xba,0x5b, -0x6d,0x56,0xf7,0xab,0x07,0xd5,0xf7,0x7e,0x87,0xfb,0xea,0x07,0xea,0x87,0xea,0x47, -0xea,0xc7,0xea,0x09,0xf5,0x13,0xf5,0x53,0xf5,0x8c,0x7a,0x4e,0xfd,0x5c,0xbd,0xa8, -0x7e,0xa1,0x7e,0xa9,0x7e,0xa5,0x06,0x1a,0x1b,0x8d,0x9d,0xc6,0x5e,0x43,0xd0,0x38, -0x6b,0x5c,0x35,0xee,0x1a,0x4f,0x8d,0xb7,0xc6,0x47,0xe3,0xa7,0x21,0x6b,0xa8,0x9a, -0x40,0x4d,0xb0,0x26,0x54,0x13,0xae,0x89,0xd4,0x30,0x35,0x71,0x9a,0x24,0x4d,0xb2, -0x26,0x45,0x93,0xa6,0xc9,0xd0,0x70,0x35,0x7c,0x8d,0x50,0x23,0xd6,0x14,0x69,0x64, -0x1a,0x85,0x46,0xa5,0xd1,0x6a,0x0c,0x9a,0x6a,0x4d,0x8d,0xa6,0x5e,0xd3,0xa8,0x69, -0xd6,0xb4,0x6a,0xda,0x35,0x9d,0x9a,0x1b,0x9a,0x5e,0x4d,0x9f,0x66,0x40,0x73,0x4f, -0x73,0x5f,0xf3,0x40,0xf3,0x50,0xf3,0x48,0xf3,0x58,0x33,0xa1,0x79,0xa2,0x79,0xaa, -0x99,0xd1,0xcc,0x69,0x9e,0x6b,0x16,0x35,0x2f,0x34,0x2f,0x35,0xaf,0x34,0xa0,0xd2, -0xa6,0xd2,0xae,0xd2,0xbe,0x92,0x50,0xe9,0x5c,0xe9,0x5a,0xe9,0x5e,0xe9,0x59,0xe9, -0x5d,0xe9,0x53,0xe9,0x57,0x49,0xae,0xa4,0x56,0x06,0x56,0x06,0x57,0x86,0x56,0x86, -0x57,0x46,0x56,0x32,0x2b,0xe3,0x2a,0x93,0x2a,0x93,0x2b,0x53,0x2a,0xd3,0x2a,0x33, -0x2a,0xb9,0x95,0xfc,0x4a,0x61,0xa5,0xb8,0xb2,0xa8,0x52,0x56,0xa9,0xa8,0x54,0x55, -0x6a,0x2b,0x0d,0x95,0xd5,0x95,0x35,0x95,0xf5,0x95,0x8d,0x95,0xcd,0x95,0xad,0x95, -0xed,0x95,0x9d,0x95,0x37,0x2a,0x7b,0x2b,0xfb,0x2a,0x07,0x2a,0xef,0x55,0xde,0xaf, -0x7c,0x50,0xf9,0xb0,0xf2,0x51,0xe5,0xe3,0xca,0x89,0xca,0x27,0x95,0x4f,0x2b,0x67, -0x2a,0xe7,0x2a,0x9f,0x57,0x2e,0x56,0xbe,0xa8,0x7c,0x59,0xf9,0xaa,0x12,0x68,0x6d, -0xb4,0x76,0x5a,0x7b,0x2d,0x41,0xeb,0xac,0x75,0xd5,0xba,0x6b,0x3d,0xb5,0xde,0x5a, -0x1f,0xad,0x9f,0x96,0xac,0xa5,0x6a,0x03,0xb5,0xc1,0xda,0x50,0x6d,0xb8,0x36,0x52, -0xcb,0xd4,0xc6,0x69,0x93,0xb4,0xc9,0xda,0x14,0x6d,0x9a,0x36,0x43,0xcb,0xd5,0xf2, -0xb5,0x42,0xad,0x58,0x5b,0xa4,0x95,0xc1,0xd7,0x5b,0x95,0x56,0xab,0x35,0x68,0xab, -0xb5,0x35,0xda,0x7a,0x6d,0xa3,0xb6,0x59,0xdb,0xaa,0x6d,0xd7,0x76,0x6a,0x6f,0x68, -0x7b,0xb5,0x7d,0xda,0x01,0xed,0x3d,0xed,0x7d,0xed,0x03,0xed,0x43,0xed,0x23,0xed, -0x63,0xed,0x84,0xf6,0x89,0xf6,0xa9,0x76,0x46,0x3b,0xa7,0x7d,0xae,0x5d,0xd4,0xbe, -0xd0,0xbe,0xd4,0xbe,0xd2,0x02,0x9d,0x8d,0xce,0x4e,0x67,0xaf,0x23,0xe8,0x9c,0x75, -0xae,0x3a,0x77,0x9d,0xa7,0xce,0x5b,0xe7,0xa3,0xf3,0xd3,0x91,0x75,0x54,0x5d,0xa0, -0x2e,0x58,0x17,0xaa,0x0b,0xd7,0x45,0xea,0x98,0xba,0x38,0x5d,0x92,0x2e,0x59,0x97, -0xa2,0x4b,0xd3,0x65,0xe8,0xb8,0x3a,0xbe,0x4e,0xa8,0x13,0xeb,0x8a,0x74,0x32,0x9d, -0x42,0xa7,0xd2,0x69,0x75,0x06,0x5d,0xb5,0xae,0x46,0x57,0xaf,0x6b,0xd4,0x35,0xeb, -0x5a,0x75,0xed,0xba,0x4e,0xdd,0x0d,0x5d,0xaf,0xae,0x4f,0x37,0xa0,0xbb,0x07,0xb9, -0xaf,0x7b,0xa0,0x7b,0xa8,0x7b,0xa4,0x7b,0xac,0x9b,0xd0,0x3d,0xd1,0x3d,0xd5,0xcd, -0xe8,0xe6,0x74,0xcf,0x75,0x8b,0xba,0x17,0xba,0x97,0xba,0x57,0x3a,0xa0,0xb7,0xd1, -0xdb,0xe9,0xed,0xf5,0x04,0xbd,0xb3,0xde,0x55,0xef,0xae,0xf7,0xd4,0x7b,0xeb,0x7d, -0xf4,0x7e,0x7a,0xb2,0x9e,0xaa,0x0f,0xd4,0x07,0xeb,0x43,0xf5,0xe1,0xfa,0x48,0x3d, -0x53,0x1f,0xa7,0x4f,0xd2,0x27,0xeb,0x53,0xf4,0x69,0xfa,0x0c,0x3d,0x57,0xcf,0xd7, -0x0b,0xf5,0x62,0x7d,0x91,0x5e,0xa6,0x57,0xe8,0x55,0x7a,0xad,0xde,0xa0,0xaf,0xd6, -0xd7,0xe8,0xeb,0xf5,0x8d,0xfa,0x66,0x7d,0xab,0xbe,0x5d,0xdf,0xa9,0xbf,0xa1,0xef, -0xd5,0xf7,0xe9,0x07,0xf4,0xf7,0xf4,0xf7,0xf5,0x0f,0xf4,0x0f,0xf5,0x8f,0xf4,0x8f, -0xf5,0x13,0xfa,0x27,0xfa,0xa7,0xfa,0x19,0xfd,0x9c,0xfe,0xb9,0x7e,0x51,0xff,0x42, -0xff,0x52,0xff,0x4a,0x0f,0xaa,0x6c,0xaa,0xec,0xaa,0xec,0xab,0x08,0x55,0xce,0x55, -0xae,0x55,0xee,0x55,0x9e,0x55,0xde,0x55,0x3e,0x55,0x7e,0x55,0xe4,0x2a,0x6a,0x55, -0x60,0x55,0x70,0x55,0x68,0x55,0x78,0x55,0x64,0x15,0xb3,0x2a,0xae,0x2a,0xa9,0x2a, -0xb9,0x2a,0xa5,0x2a,0xad,0x2a,0xa3,0x8a,0x5b,0xc5,0xaf,0x12,0x56,0x89,0xab,0x8a, -0xaa,0x64,0x55,0x8a,0x2a,0x55,0x95,0xb6,0xca,0x50,0x55,0x5d,0x55,0x53,0x55,0x5f, -0xd5,0x58,0xd5,0x5c,0xd5,0x5a,0xd5,0x5e,0xd5,0x59,0x75,0xa3,0xaa,0xb7,0xaa,0xaf, -0x6a,0xa0,0xea,0x5e,0xd5,0xfd,0xaa,0x07,0x55,0x0f,0xab,0x1e,0x55,0x3d,0xae,0x9a, -0xa8,0x7a,0x52,0xf5,0xb4,0x6a,0xa6,0x6a,0xae,0xea,0x79,0xd5,0x62,0xd5,0x8b,0xaa, -0x97,0x55,0xaf,0xaa,0x80,0xc1,0xc6,0x60,0x67,0xb0,0x37,0x10,0x0c,0xce,0x06,0x57, -0x83,0xbb,0xc1,0xd3,0xe0,0x6d,0xf0,0x31,0xf8,0x19,0xc8,0x06,0xaa,0x21,0xd0,0x10, -0x6c,0x08,0x35,0x84,0x1b,0x22,0x0d,0x4c,0x43,0x9c,0x21,0xc9,0x90,0x6c,0x48,0x31, -0xa4,0x19,0x32,0x0c,0x5c,0x03,0xdf,0x20,0x34,0x88,0x0d,0x45,0x06,0x99,0x41,0x61, -0x50,0x19,0xb4,0x06,0x83,0xa1,0xda,0x50,0x63,0xa8,0x37,0x34,0x1a,0x9a,0x0d,0xad, -0x86,0x76,0x43,0xa7,0xe1,0x86,0xa1,0xd7,0xd0,0x67,0x18,0x30,0xdc,0x33,0xdc,0x37, -0x3c,0x30,0x3c,0x34,0x3c,0x32,0x3c,0x36,0x4c,0x18,0x9e,0x18,0x9e,0x1a,0x66,0x0c, -0x73,0x86,0xe7,0x86,0x45,0xc3,0x0b,0xc3,0x4b,0xc3,0x2b,0x03,0x30,0xda,0x18,0xed, -0x8c,0xf6,0x46,0x82,0xd1,0xd9,0xe8,0x6a,0x74,0x37,0x7a,0x1a,0xbd,0x8d,0x3e,0x46, -0x3f,0x23,0xd9,0x48,0x35,0x06,0x1a,0x83,0x8d,0xa1,0xc6,0x70,0x63,0xa4,0x91,0x69, -0x8c,0x33,0x26,0x19,0x93,0x8d,0x29,0xc6,0x34,0x63,0x86,0x91,0x6b,0xe4,0x1b,0x85, -0x46,0xb1,0xb1,0xc8,0x28,0x33,0x2a,0x8c,0x2a,0xa3,0xd6,0x68,0x30,0x56,0x1b,0x6b, -0x8c,0xf5,0xc6,0x46,0x63,0xb3,0xb1,0xd5,0xd8,0x6e,0xec,0x34,0xde,0x30,0xf6,0x1a, -0xfb,0x8c,0x03,0xc6,0x7b,0x90,0xfb,0xc6,0x07,0xc6,0x87,0xc6,0x47,0xc6,0xc7,0xc6, -0x09,0xe3,0x13,0xe3,0x53,0xe3,0x8c,0x71,0xce,0xf8,0xdc,0xb8,0x68,0x7c,0x61,0x7c, -0x69,0x7c,0x65,0x04,0x17,0x6c,0x2e,0xd8,0x5d,0xb0,0xbf,0x40,0xb8,0xe0,0x7c,0xc1, -0xf5,0x82,0xfb,0x05,0xcf,0x0b,0xde,0x17,0x7c,0x2e,0xf8,0x5d,0x20,0x5f,0xa0,0x5e, -0x08,0x5c,0xe7,0x5f,0x80,0xb5,0xff,0xf7,0xac,0x27,0x96,0xec,0x36,0x02,0x90,0x8e, -0x1d,0xdb,0xc0,0xe3,0x77,0x61,0x7e,0x08,0x2b,0xe3,0x60,0x79,0x60,0xe3,0xda,0xf1, -0x01,0x98,0x53,0x60,0x9e,0x0b,0xd6,0xf2,0x70,0x58,0x49,0x7d,0xe3,0xf8,0xf5,0x79, -0xaf,0xeb,0xc3,0xd0,0x4d,0x36,0xae,0xe5,0x38,0x2c,0xdf,0x80,0xe5,0x1b,0xb1,0xdc, -0x0e,0xcb,0xb7,0xc0,0xfc,0x28,0x76,0x8f,0x08,0xec,0xbc,0x08,0xec,0xbc,0x08,0xec, -0xbc,0x08,0xac,0x3f,0x03,0x6b,0x67,0x60,0xed,0x0c,0xac,0x9d,0x81,0xb5,0xc7,0x60, -0xd7,0x8f,0xc5,0xfa,0xc5,0x62,0xfd,0x62,0xb1,0x7e,0xb1,0x6f,0xb4,0xa3,0xfe,0x6c, -0xac,0x1f,0x1b,0xeb,0xc7,0xc6,0xfa,0xb1,0xb1,0x76,0x0e,0x56,0x9f,0x8e,0xf5,0x4b, -0x7f,0xa3,0xbc,0x01,0xcb,0x37,0x62,0xf9,0x6b,0x5b,0xa2,0xf9,0x7c,0x8c,0xcd,0x27, -0x13,0x3b,0x2f,0x13,0x3b,0x2f,0x13,0x3b,0x2f,0x13,0xeb,0xcf,0xc3,0xda,0x79,0x58, -0x3b,0x0f,0x6b,0xe7,0x61,0xed,0xe7,0xb1,0xeb,0xe7,0x62,0xfd,0x72,0xb1,0x7e,0xb9, -0x58,0xbf,0xdc,0x37,0xda,0x51,0x7f,0x09,0xd6,0x4f,0x82,0xf5,0x93,0x60,0xfd,0x24, -0x58,0xbb,0x14,0xab,0x97,0xbe,0x61,0x7f,0x1b,0x6c,0xdc,0x36,0x58,0x79,0x13,0x56, -0xde,0x84,0x95,0x7d,0xb0,0xb2,0x0f,0xe6,0x27,0x1c,0x36,0x3f,0x1c,0x56,0xde,0x80, -0x95,0x37,0x60,0xe5,0xcd,0x58,0x79,0x33,0x56,0xb6,0xc7,0xca,0x28,0x0f,0xc7,0xf2, -0x0c,0x2c,0x8f,0xc0,0xee,0x9b,0x89,0xe5,0x11,0xd8,0x7d,0x33,0xb1,0x3c,0x02,0xbb, -0x4e,0x26,0x96,0x47,0x60,0xe3,0xc8,0xc4,0xf2,0x08,0xec,0x3a,0x99,0x58,0x7e,0x1c, -0x1b,0xc7,0x39,0x2c,0x3f,0x8e,0x5d,0xe7,0x1c,0x96,0x1f,0xc7,0xae,0x73,0x0e,0xcb, -0x8f,0x63,0x7e,0x3a,0x87,0xe5,0x91,0xd8,0x79,0xdc,0x37,0xe2,0x6a,0x23,0xe6,0x8f, -0x8d,0x58,0xd9,0x06,0x2b,0xdb,0x60,0xe5,0x4d,0x58,0x79,0x13,0x56,0xf6,0xc1,0xca, -0x3e,0x58,0x79,0x33,0x96,0x47,0x81,0xb5,0xfa,0x6c,0xec,0x18,0x5d,0x3f,0x1b,0xcb, -0xa3,0xb1,0xfb,0xe7,0x60,0x39,0x13,0xb3,0x2f,0x1f,0xcb,0x99,0x58,0x3d,0xff,0x8d, -0x76,0x7b,0xac,0x6c,0x8f,0x95,0x6f,0x83,0xb5,0x32,0xca,0x63,0xb0,0xf3,0xce,0x63, -0x79,0x0c,0x76,0xde,0x79,0x2c,0x8f,0xc1,0xce,0x3b,0x8f,0xe5,0x03,0x1b,0xd6,0x8e, -0x63,0xb1,0x79,0xe5,0x62,0x79,0x2c,0x36,0xaf,0x5c,0x2c,0x47,0xe5,0xad,0x58,0x19, -0xe5,0x09,0xd8,0xf5,0xf3,0xb0,0x3c,0x01,0xbb,0x7e,0x1e,0x96,0x27,0x60,0xd7,0xcf, -0xc3,0xf2,0x44,0xac,0x5f,0x3e,0x96,0x27,0x62,0xf3,0xcf,0xc7,0xf2,0x44,0xec,0xbc, -0x7c,0x2c,0x4f,0xc4,0xce,0xcb,0xc7,0xf2,0x24,0xac,0x5e,0x8c,0xe5,0x49,0x58,0xbd, -0x18,0xcb,0xd9,0x98,0x9f,0x24,0x58,0xce,0xc6,0xe6,0x21,0xc1,0x72,0x36,0x36,0x0f, -0x09,0x96,0xb3,0xb1,0xf5,0x2a,0xc1,0x72,0x36,0x36,0x2f,0x09,0x96,0xb3,0x31,0x3f, -0x4a,0xb0,0xfc,0x24,0x36,0xce,0x42,0x2c,0xe7,0x60,0xb9,0xf4,0x8d,0x32,0x5a,0x57, -0xa7,0xb0,0xf9,0x15,0x63,0xf9,0x29,0x2c,0x0e,0x8a,0xb1,0xfc,0x14,0x36,0xde,0xe2, -0x37,0xe6,0x87,0x6c,0xbb,0x1b,0xb3,0xed,0x6e,0xec,0xde,0xbb,0xb1,0x7b,0xef,0xc6, -0xd6,0xce,0xa9,0x37,0xd6,0x51,0xf1,0x1b,0x6b,0xa9,0xf8,0x8d,0x38,0x40,0xb1,0xc5, -0xc4,0xe2,0x8c,0x8f,0xe5,0x31,0x58,0x7d,0x0c,0x56,0x3e,0x8f,0xe5,0x61,0xd8,0x79, -0xe9,0x58,0xce,0xc0,0x72,0x1e,0x96,0xc7,0x62,0x79,0xee,0x1b,0xf6,0xb5,0xc7,0xc6, -0x64,0xff,0xc6,0x3e,0x69,0xf3,0xc6,0x1e,0x63,0xf3,0x46,0x3d,0xee,0x8d,0x7a,0xdc, -0x1b,0xf5,0xf6,0x6f,0xd4,0xbf,0x79,0x1d,0xf0,0x46,0x3d,0x78,0xe3,0x39,0x61,0xf3, -0xc6,0x1e,0xfb,0x7a,0x9f,0xda,0xfc,0x46,0xfd,0xeb,0xe3,0xff,0x85,0xf9,0x79,0x16, -0xcb,0x8f,0x63,0xe3,0x3c,0x87,0xe5,0xd1,0x58,0x9e,0xf3,0xc6,0xfc,0x7c,0xb0,0xf9, -0xf9,0xbc,0x51,0xb6,0x79,0xa3,0x0e,0x1d,0xdf,0xc6,0xad,0xf5,0xff,0x74,0xc3,0x5a, -0x9e,0xfd,0x86,0x1f,0x90,0x4f,0x5e,0xfb,0xe3,0xb5,0x2f,0x8e,0x63,0x7e,0x3f,0xf7, -0xc6,0xfa,0x03,0xd8,0x7a,0x03,0x6f,0x3c,0xf7,0x70,0x6f,0x3c,0x33,0x70,0xd8,0xf8, -0x71,0xd8,0xf8,0x51,0x3e,0x81,0xe5,0x2f,0xff,0x3f,0xf6,0xce,0x04,0x40,0xc7,0xe2, -0xf1,0xe3,0xcf,0xfb,0xee,0xbe,0xbb,0xd6,0x7d,0x76,0x29,0xd7,0x16,0xc2,0xae,0xbd, -0x59,0xe7,0x5a,0xd6,0x99,0x90,0x90,0x54,0xae,0x90,0x5c,0xeb,0x08,0x95,0xca,0x91, -0xd2,0x49,0x87,0x4a,0x27,0x9d,0xa4,0x72,0x25,0x54,0xce,0x0a,0x91,0x12,0x15,0x65, -0x8b,0x90,0x44,0x42,0xba,0x48,0xf5,0xff,0xcc,0x3e,0xdf,0x27,0xe3,0xf9,0xdb,0x1f, -0xaa,0x5f,0xbf,0x8e,0xf7,0x19,0x1f,0xdf,0x99,0x79,0xe6,0x99,0x67,0x66,0x9e,0x99, -0x79,0x9e,0xf7,0x99,0x79,0x66,0xad,0xfb,0x68,0x11,0x1d,0x53,0x44,0xee,0x62,0x72, -0x17,0x53,0x7f,0x58,0x44,0xfd,0x61,0x11,0xb9,0x8b,0xc9,0x5d,0x4c,0xd7,0xb7,0x88, -0xae,0x6f,0x11,0xb9,0x8b,0xc9,0x5d,0x4c,0xf9,0x2f,0xa2,0xbc,0x17,0x91,0xbb,0x98, -0xdc,0xc5,0xd4,0x9e,0x8b,0xa8,0x3d,0x17,0x91,0xbb,0x98,0xdc,0xc5,0x74,0x1d,0x8b, -0xe8,0x1a,0x16,0x91,0xbb,0x98,0xdc,0xc5,0xd4,0x9e,0x2b,0xaa,0xbe,0x57,0x54,0xfb, -0xad,0xa8,0xf6,0x5b,0x51,0xfd,0x6f,0x41,0xf5,0xbf,0x05,0xad,0xeb,0xdc,0xd5,0xea, -0xff,0xbd,0xfb,0x6a,0x25,0xeb,0x3e,0x1e,0x69,0xdd,0x03,0x23,0xad,0xfb,0x7c,0xa4, -0x75,0x8f,0xf4,0xfc,0xa3,0xe5,0x17,0x6d,0xb9,0x23,0x2d,0xbf,0x48,0xb5,0xe3,0x48, -0xb5,0xeb,0x48,0xa5,0xa7,0x67,0xd0,0xbd,0xee,0x26,0xaf,0x57,0x63,0xbf,0x16,0x46, -0x05,0xdd,0xbe,0xe0,0x6a,0x3d,0x33,0x45,0xe9,0x79,0x29,0x5a,0x9a,0x5f,0x5a,0x59, -0x1a,0x21,0x35,0x7d,0x4b,0xf7,0xa0,0xdb,0x3e,0x4d,0x59,0x0c,0x87,0x89,0x41,0xb7, -0x6e,0x98,0xeb,0x5c,0x22,0xe2,0x48,0x9b,0x59,0x10,0x74,0x8f,0xc9,0xc2,0x5e,0xdb, -0x7a,0x36,0x9b,0x2a,0xbd,0x4b,0xe1,0x4c,0xbf,0x3f,0x51,0xf6,0xfb,0xa5,0x93,0xa4, -0x8f,0x49,0x9f,0x92,0x4e,0xf3,0xe2,0xb6,0xce,0x33,0x49,0xf6,0xa7,0xa4,0xb3,0xe4, -0x3f,0xd7,0x8b,0xdf,0x3a,0xc6,0xe8,0x1b,0x76,0x1a,0x65,0xf7,0xfc,0x16,0x5b,0x61, -0x8c,0xbe,0x29,0x9d,0x0d,0xf3,0x75,0x8e,0x75,0xf2,0x5b,0xa7,0x63,0x96,0xc3,0x12, -0x78,0x19,0x96,0xc2,0x32,0x78,0x40,0xe7,0x7f,0x02,0x4a,0x45,0xba,0xe5,0x63,0xd4, -0x84,0x2f,0x11,0xe9,0x1e,0x1f,0x25,0xf7,0x19,0x72,0x9f,0xa6,0x70,0xb1,0x91,0xee, -0xf5,0x38,0x4d,0x5a,0x53,0x9a,0xaa,0xfd,0xa9,0x3a,0x2e,0x59,0xc7,0xb5,0x97,0xbb, -0x96,0xdc,0x35,0x15,0xae,0xa1,0x8e,0x1b,0x12,0xa9,0xba,0x2d,0x3d,0x45,0xfe,0x69, -0xd2,0xa2,0xd2,0x04,0xcb,0x9d,0x4f,0xee,0x7c,0x4a,0xb7,0x77,0x7e,0xa3,0x1b,0xe5, -0xff,0xa1,0xf4,0x14,0x69,0x9a,0xf4,0x54,0x69,0x0d,0xa9,0xc9,0x47,0xa4,0xd2,0x15, -0x29,0x77,0x3e,0xb9,0x8d,0x96,0x91,0xd6,0x93,0xee,0x94,0x7e,0x21,0x8d,0x93,0xb6, -0x94,0xc6,0x2a,0x9e,0x86,0xd2,0x58,0xf9,0x37,0xb4,0xf6,0x17,0x90,0xdb,0x68,0x25, -0xf9,0x37,0x91,0x56,0x95,0xb6,0x90,0xf6,0x08,0x39,0xce,0x68,0xa8,0x14,0x45,0x3b, -0x8f,0x72,0xf5,0x42,0x68,0x2a,0x35,0xee,0x76,0xd0,0xdc,0x72,0x0f,0xd1,0x7e,0xa3, -0x2b,0xa4,0xcd,0xa5,0xef,0x2b,0xdc,0x52,0xe9,0x3a,0x69,0xe5,0x18,0xc7,0xa9,0x03, -0x09,0xd2,0x64,0x69,0x29,0xe9,0x29,0xd2,0x53,0xa5,0x67,0x4a,0xcb,0x4b,0x2b,0x48, -0xab,0x4a,0xab,0x4b,0x57,0xc0,0x22,0xe9,0x06,0x98,0x02,0xaf,0xc2,0xe3,0xd2,0x19, -0xd2,0xa4,0xfc,0x84,0x87,0x9a,0xd2,0x53,0xa4,0xa7,0x4a,0xcf,0x94,0x56,0x95,0x36, -0x29,0x40,0xdd,0x2a,0xe0,0x6a,0x3d,0x69,0x07,0x28,0x0f,0x75,0xa0,0x82,0xf4,0x6e, -0xd8,0x00,0xcb,0x61,0x11,0xac,0x90,0x2e,0x97,0x7f,0xe3,0x82,0xc4,0x03,0x8b,0xe1, -0x7d,0x58,0x6e,0xe9,0x07,0xd2,0x65,0x96,0x9a,0x7d,0x8d,0x0b,0x71,0x4e,0x68,0x22, -0x35,0xee,0x0e,0xf0,0x21,0xac,0x92,0xbe,0x63,0xa9,0xe7,0xb7,0x19,0x5a,0x16,0x26, -0xaf,0xb0,0x06,0x66,0xc3,0x74,0x98,0x24,0x9d,0x02,0x05,0x8a,0x38,0x4e,0x26,0xcc, -0x83,0xf3,0xa4,0x6d,0xa4,0xed,0xa5,0x9d,0xa4,0x19,0x30,0x17,0x06,0xc2,0x20,0xe9, -0x10,0x98,0x0d,0x23,0xa5,0x03,0x65,0x9f,0x63,0xa9,0xe7,0xe7,0xe9,0xdd,0x8a,0xef, -0x61,0xe9,0x14,0xe9,0xd3,0xd2,0xe9,0xd2,0x09,0x3a,0xdf,0x39,0x45,0x1d,0x27,0x1e, -0x72,0x20,0x54,0x9a,0xb6,0x07,0xd1,0xd2,0x18,0x69,0x01,0x69,0x21,0x69,0x31,0x69, -0x2d,0x69,0x1d,0x69,0x3d,0x69,0x7d,0x69,0xa6,0xd4,0xdc,0xa3,0xcc,0x7d,0x3b,0x53, -0xcf,0x01,0xe6,0x1e,0x75,0x67,0xc0,0x7d,0x06,0x30,0xf7,0x33,0xef,0xd9,0xbf,0x85, -0x9e,0xcb,0x5a,0xea,0x39,0xcc,0xdc,0x7b,0x2a,0xd0,0xb7,0xb7,0x76,0xdc,0xfb,0xa8, -0xb9,0x17,0x9a,0xfb,0xa5,0x79,0xc6,0x34,0xf7,0xbb,0xd6,0xec,0x6b,0x03,0xc1,0xb3, -0x1c,0xa7,0x9b,0x9e,0x2d,0xcc,0x7d,0xaf,0x23,0x7e,0x9d,0xe0,0x92,0xa0,0xfb,0x7c, -0x61,0x9e,0x65,0xfa,0x99,0xf8,0x03,0xee,0x3d,0xec,0x42,0xfc,0x4f,0xe1,0x98,0x53, -0x21,0xdb,0x71,0xef,0xad,0xe6,0xfe,0x7b,0x16,0xee,0x01,0xec,0x1b,0x8a,0xfd,0x9c, -0xb3,0xdc,0xbe,0x78,0x0e,0xbc,0xa8,0xbe,0x77,0x85,0x9e,0x03,0x06,0x29,0xbc,0x09, -0xe7,0x85,0x59,0x6a,0x85,0xa9,0x4b,0x7b,0xbf,0x20,0xe8,0xfe,0xa6,0x6b,0x87,0xee, -0x73,0xdc,0xb4,0xf4,0x44,0x3b,0xa3,0x5d,0xa1,0x07,0x5c,0x01,0xbd,0xcd,0x3d,0xd3, -0xdc,0x2b,0x39,0xdf,0x23,0x68,0x3f,0x18,0x8b,0xfd,0x31,0x74,0x20,0x64,0xc3,0x20, -0x18,0x0c,0x43,0xe0,0x2a,0x18,0x0e,0xa3,0x61,0x0c,0x4c,0x27,0x4f,0xb7,0xa0,0xb7, -0xc2,0x99,0x1c,0x77,0x1b,0x7a,0x7b,0xd0,0x7d,0xc6,0x9a,0x80,0xde,0x15,0x74,0x9f, -0xc9,0xe6,0xeb,0x59,0xe1,0x1c,0x3d,0x2b,0x18,0xcd,0xd4,0x7d,0xb8,0x9b,0xd4,0xb8, -0x63,0xe5,0x8e,0x95,0x3b,0x51,0xee,0x44,0xeb,0x1d,0x44,0xc0,0xfa,0xfd,0x1e,0xd0, -0x33,0x5e,0xb4,0x9e,0xb3,0xa3,0xe5,0x8e,0x95,0x3b,0x56,0xee,0x44,0xb9,0x13,0xe5, -0xae,0x24,0x77,0x25,0xb9,0xe3,0xe4,0x8e,0xb3,0x7e,0xf3,0x3a,0xd6,0xef,0x5e,0xc7, -0xf2,0x0f,0x58,0xfe,0xde,0x3b,0x90,0x38,0xf9,0x79,0xc7,0x27,0xc8,0x9d,0x60,0x3d, -0x13,0x45,0x59,0xcf,0x45,0xc6,0xde,0x58,0xe9,0xed,0x69,0xfd,0xd6,0x8d,0xd4,0x33, -0x69,0xa4,0x9e,0xb5,0xa2,0xf5,0x6c,0x13,0x2d,0x77,0xac,0xdc,0xb1,0x72,0xe7,0x93, -0x3b,0x9f,0xdc,0x95,0xe4,0xf6,0x7e,0x2b,0xc7,0xcb,0x1d,0xaf,0x67,0xc9,0x04,0xd5, -0xa1,0x04,0xeb,0x9d,0x4c,0xc0,0x7a,0x9f,0x11,0xd0,0x33,0x78,0x40,0xcf,0xe0,0x9e, -0x3b,0x56,0xee,0x58,0xb9,0x13,0xe5,0x4e,0xd4,0x6f,0x9a,0x58,0xfd,0xd6,0x8d,0xb5, -0xdc,0x91,0x96,0x5f,0xa4,0xfc,0x13,0xe5,0xe7,0x1d,0x17,0x27,0xb7,0xd1,0x96,0x3a, -0x5f,0x3f,0x69,0x4b,0xe5,0xbb,0x9f,0xb4,0xa5,0xe2,0xea,0x27,0x3d,0x5f,0xfe,0xfd, -0xa5,0xe7,0xcb,0xbf,0xbf,0xb5,0x3f,0x51,0xee,0x44,0xb9,0xe3,0xe4,0x8e,0xb3,0x9e, -0x41,0x03,0xd6,0x33,0x68,0xc0,0xf2,0xcf,0x67,0xf9,0xe7,0x8b,0x38,0xf2,0xdb,0xdb, -0xb1,0x7e,0x7f,0x3b,0x96,0x7f,0xc0,0xf2,0x37,0xf6,0xd6,0xca,0x47,0xb6,0x73,0xc4, -0x1d,0x2d,0x77,0xb4,0x9e,0xcd,0xa3,0xf5,0x6c,0xee,0xb9,0x63,0xe5,0x8e,0xb5,0xdc, -0x91,0x96,0x5f,0xa4,0xfc,0x13,0xe5,0x97,0xa8,0x67,0xf6,0x68,0x3d,0xb3,0x47,0xcb, -0x1d,0x2b,0x77,0xac,0xf5,0x9b,0x3e,0xda,0xfa,0x5d,0x1f,0x6d,0xfd,0x76,0x8f,0xb6, -0x7e,0xbf,0xdb,0xc7,0x47,0x5b,0x71,0x44,0xeb,0xb7,0x40,0xb4,0x7e,0x0b,0x78,0xee, -0x58,0xb9,0x63,0xe5,0x4e,0x94,0x3b,0x51,0xee,0x38,0xb9,0xe3,0xf4,0x5b,0xe3,0x6c, -0xfd,0xd6,0x38,0x5b,0xee,0x04,0xb9,0x13,0xe4,0x8e,0x93,0x3b,0xce,0x7a,0x57,0x10, -0xb0,0xde,0x17,0x04,0xac,0x77,0x06,0xf9,0xac,0xf7,0x06,0xc6,0xde,0x5e,0x61,0x86, -0x4a,0xdb,0x2b,0x5d,0x43,0xa5,0x1d,0xf4,0xdb,0x6e,0x98,0xb4,0x83,0xca,0x62,0x98, -0xb4,0x83,0xda,0xc0,0x30,0x69,0x07,0xe5,0x73,0x98,0xb4,0x83,0xe2,0x19,0x26,0xbd, -0x48,0xfe,0xc3,0xa5,0x17,0xe9,0xb8,0xe1,0xd6,0xbb,0xc9,0x68,0xfd,0x46,0xf1,0xde, -0x29,0x04,0xf5,0x4e,0x21,0x28,0x77,0xac,0xdc,0xb1,0x72,0x27,0xca,0x9d,0xa8,0x76, -0xeb,0x95,0xa7,0x97,0xae,0xfc,0x8a,0x2f,0xbf,0xfa,0xd1,0x45,0xf4,0xad,0x37,0x04, -0xdc,0xf8,0x1b,0x28,0x9e,0xae,0x52,0xe3,0x8e,0x91,0x3b,0xc6,0x7a,0xc7,0x6b,0xbf, -0x1f,0xb5,0xdf,0xfd,0x3a,0x96,0xbf,0x63,0xf9,0xc7,0x58,0xfe,0x76,0x3c,0x11,0x96, -0x7f,0x84,0x75,0xfe,0xa0,0x95,0x86,0xa0,0xf5,0xce,0x32,0x60,0xbd,0xb7,0x0c,0x58, -0xfe,0x8e,0xe5,0xef,0x58,0xfe,0x31,0x96,0x7f,0x8c,0xe5,0x1f,0x61,0xf9,0xdb,0xe7, -0x8d,0xb2,0xce,0xeb,0xbd,0x9b,0x8c,0x55,0x9f,0x1b,0x2b,0x77,0x8c,0xdc,0x31,0x72, -0x47,0xc8,0x1d,0x61,0xbd,0xcb,0xb6,0xdf,0x03,0xdb,0xef,0xb8,0x1d,0xcb,0xdf,0xb1, -0xfc,0x63,0x2c,0xff,0x18,0xcb,0x3f,0xc2,0xf2,0x8f,0xb0,0xd2,0x13,0xb4,0xd2,0xe4, -0xbd,0xc3,0x8c,0x51,0x1f,0x1c,0x23,0x77,0xac,0xdc,0xb1,0xea,0x5f,0x62,0xd5,0xb7, -0x78,0xee,0x18,0xb9,0x63,0xac,0x77,0xe7,0xf6,0x7b,0x67,0xfb,0x9d,0xba,0x63,0xf9, -0x3b,0x96,0x7f,0x8c,0xe5,0x6f,0xc7,0x13,0x61,0xf9,0x47,0x58,0xe7,0x0f,0x5a,0x69, -0xf0,0xde,0xd5,0x97,0xb6,0xce,0x5b,0xda,0x3a,0x6f,0x69,0xeb,0xbc,0xa5,0xad,0xf3, -0x96,0xb6,0xce,0x5b,0xda,0x3a,0x6f,0x69,0xeb,0xbc,0xa5,0xad,0xf3,0x1a,0x7b,0xac, -0xe5,0x1f,0xab,0xf6,0x1f,0xab,0xb6,0xef,0xb9,0x63,0xe4,0x8e,0xb1,0xde,0xcb,0x05, -0xac,0x77,0x73,0x01,0xcb,0xdf,0xb1,0xfc,0x1d,0xcb,0x3f,0xc6,0xf2,0xb7,0xe3,0x89, -0xb0,0xfc,0x23,0x2c,0xff,0x58,0xcb,0x3f,0x56,0xed,0xdd,0x51,0xfb,0x74,0xe4,0x8e, -0x95,0xdb,0xdb,0x1f,0x23,0x77,0x8c,0xdc,0x11,0x72,0x47,0xe8,0xf7,0x7c,0x09,0x69, -0x49,0xcb,0xed,0x58,0x7e,0x8e,0xe5,0x1f,0xb0,0xfc,0x03,0x96,0x7f,0xa6,0xe5,0x9f, -0xa9,0xf7,0x0f,0x25,0xa4,0x25,0x2d,0xb7,0x63,0xf9,0x39,0x96,0x7f,0xc0,0xf2,0x0f, -0x58,0xfe,0x99,0x96,0x7f,0xa6,0x7e,0xf7,0x97,0x90,0x96,0xb4,0xdc,0x8e,0xe5,0xe7, -0x58,0xfe,0x01,0xcb,0xdf,0xd8,0x27,0xca,0x7f,0xa2,0xfc,0x26,0x5a,0xc7,0x4f,0xb4, -0x8e,0x9f,0x68,0x1d,0x3f,0xd1,0x3a,0x7e,0x9e,0xfc,0xe7,0xc9,0x6f,0x9e,0x75,0xfc, -0x3c,0xeb,0xf8,0x79,0xd6,0xf1,0xf3,0x8e,0x71,0x7c,0xa6,0xe5,0x9f,0xa9,0x77,0x33, -0x25,0xa4,0x25,0x2d,0xb7,0x63,0xf9,0x39,0x96,0x7f,0xc0,0xf2,0x0f,0x58,0xfe,0x99, -0x96,0x7f,0xa6,0xde,0xc1,0x94,0x90,0x96,0xb4,0xdc,0x8e,0xe5,0xe7,0x58,0xfe,0x01, -0xcb,0x3f,0x60,0xf9,0x67,0x5a,0xfe,0x99,0x7a,0x2f,0x54,0x42,0x5a,0xd2,0x72,0x3b, -0x96,0x9f,0x63,0xf9,0x07,0x2c,0xff,0x80,0xe5,0x9f,0x69,0xf9,0x67,0xea,0x1d,0x51, -0x09,0x69,0x49,0xcb,0xed,0x58,0x7e,0x8e,0xe5,0x1f,0xb0,0xfc,0xbd,0x77,0x5a,0x25, -0xa4,0x25,0x2d,0xb7,0x63,0xf9,0x39,0x96,0x7f,0xc0,0xf2,0xf7,0xde,0x4d,0x95,0x90, -0x96,0xb4,0xdc,0x8e,0xe5,0xe7,0x58,0xfe,0x01,0xcb,0xdf,0x3e,0x3e,0xd3,0xf2,0xcf, -0xd4,0xbb,0xad,0x92,0x96,0x3a,0x96,0x3d,0x60,0xd9,0x33,0xf5,0x5e,0xac,0x84,0xb4, -0xa4,0xe5,0x76,0x2c,0x3f,0xc7,0xf2,0x0f,0x58,0xfe,0x01,0xcb,0x3f,0xd3,0xf2,0xcf, -0xd4,0xfb,0xbd,0x12,0xd2,0x92,0x96,0xdb,0xb1,0xfc,0x1c,0xcb,0x3f,0x60,0xf9,0x07, -0x2c,0xff,0x4c,0xcb,0xdf,0x6b,0xf7,0x8e,0xef,0xdd,0xa0,0xe3,0x7b,0x47,0xe8,0xf8, -0xde,0x15,0x3a,0xd6,0x3b,0xc3,0xc5,0xd6,0x35,0xf5,0xca,0xd0,0xf1,0xbd,0x27,0x74, -0xac,0xf7,0x85,0x5e,0x9f,0x93,0x65,0xf5,0x39,0x59,0xbe,0xbe,0x2b,0xcb,0xd7,0x7f, -0x65,0xf9,0xfa,0xb0,0x2c,0x5f,0x3f,0x96,0xe5,0xeb,0xcb,0xb2,0x7c,0xfd,0x59,0x96, -0xd5,0x27,0x65,0x59,0x7d,0x52,0x96,0xaf,0x6f,0xcb,0xf2,0xf5,0x6f,0x59,0xbe,0x3e, -0x2e,0xcb,0xd7,0xcf,0x65,0xf9,0xfa,0xba,0x2c,0x5f,0x7f,0x97,0x65,0xf5,0x19,0x59, -0x56,0x9f,0x91,0xe5,0xeb,0x7b,0xb2,0x7c,0xfd,0x4f,0x96,0xaf,0x0f,0xca,0xf2,0xf5, -0x43,0x59,0xbe,0xbe,0x28,0xcb,0xd7,0x1f,0x65,0x59,0x7d,0x4a,0x96,0xd5,0xa7,0x64, -0xf9,0xfa,0xa6,0x2c,0x5f,0xff,0x94,0xe5,0xeb,0xa3,0xb2,0x7c,0xfd,0x54,0x96,0xaf, -0xaf,0xca,0xf2,0xf5,0x57,0x59,0x56,0xfd,0xcd,0xb2,0xea,0x6f,0x96,0xaf,0x1d,0x64, -0xf9,0xda,0x42,0x96,0xaf,0x3d,0x64,0xf9,0xda,0x44,0x96,0xaf,0x5d,0x64,0xf9,0xda, -0x46,0x96,0x55,0xbf,0xb3,0xac,0xfa,0x9d,0xe5,0x6b,0x27,0x59,0xbe,0xb6,0x92,0xe5, -0x6b,0x2f,0x59,0xbe,0x36,0x93,0xe5,0x6b,0x37,0x59,0xbe,0xb6,0xe3,0xd5,0xb3,0x28, -0x69,0xa4,0xd5,0x9e,0xbc,0x7d,0x59,0x56,0xdb,0xf2,0xec,0x99,0x96,0x7a,0x75,0x26, -0x4a,0x1a,0x29,0x75,0xac,0x71,0x80,0xbb,0x14,0xce,0x8c,0x13,0x78,0xf7,0x03,0xcf, -0x6e,0x34,0x53,0x63,0x07,0x99,0x56,0x7b,0xf5,0xea,0x44,0x96,0xd5,0x76,0x3d,0x7b, -0xa6,0xa5,0x59,0xba,0x47,0x7a,0xf7,0x4d,0xef,0x7e,0xe4,0x58,0x63,0x0e,0xf7,0x2b, -0xdc,0xe2,0xb2,0x6a,0xeb,0x65,0xd5,0xf6,0xcb,0x1e,0xb9,0xb7,0x44,0x49,0x23,0xad, -0xb1,0x03,0xc7,0x37,0x1e,0xb1,0xc0,0xba,0x17,0xe5,0xb3,0xee,0x1f,0x51,0xd2,0x48, -0xa9,0x63,0x8d,0x73,0xfc,0xac,0x73,0xfe,0x5c,0xf6,0x88,0xdb,0xeb,0x9f,0xa3,0xa4, -0x91,0xd6,0x38,0x85,0xe3,0x1b,0xc7,0x58,0xaa,0xeb,0xb7,0xd4,0xba,0x27,0x64,0x5a, -0x61,0xbc,0xfe,0x3d,0x4a,0x1a,0x29,0x75,0xac,0xb1,0x95,0x29,0x3a,0x76,0xaa,0x9e, -0xd3,0xbc,0x71,0x9a,0x2e,0xce,0x91,0xfe,0xcd,0xab,0x93,0x59,0x56,0x5f,0xe7,0xd9, -0x33,0x2d,0xcd,0xd2,0x3d,0xcb,0xb1,0xc6,0x70,0xa6,0x59,0x7d,0xb7,0xe7,0x36,0xe1, -0x5e,0xd4,0xd8,0x90,0x39,0x77,0x10,0x4b,0x44,0xb9,0x23,0xf3,0x7c,0xfe,0x13,0x45, -0x15,0x2e,0x99,0xe3,0xe2,0x9d,0x63,0x63,0xf6,0x27,0x95,0xfb,0xff,0xa4,0x1e,0x83, -0xf2,0x8e,0x8b,0x39,0x26,0x44,0x9c,0xf5,0x9d,0x23,0x78,0xfb,0xea,0x1f,0x23,0x3e, -0x13,0x3e,0x41,0x73,0x24,0xcc,0x1c,0xa2,0x54,0x48,0x83,0x1a,0x50,0x13,0xd2,0xa1, -0x2a,0x14,0xaf,0xe0,0x38,0x75,0xcd,0x98,0x1a,0x9c,0xab,0xb1,0xec,0x04,0xcd,0x45, -0xf2,0xe6,0x21,0x9d,0xcc,0xf1,0x5d,0xf5,0x5e,0x75,0x80,0xc6,0xe1,0xcc,0xfb,0xd5, -0x2b,0xf4,0x5e,0xb5,0xaf,0xde,0xad,0x9a,0x73,0x64,0x6b,0xac,0x6e,0x88,0xde,0xd7, -0x0e,0xd6,0xb1,0xd5,0x1d,0xf7,0x7d,0xa1,0x67,0x37,0xfe,0xe6,0x5d,0xe2,0x4c,0x69, -0x77,0xf9,0x0f,0xb0,0xec,0xe6,0xb9,0x7e,0x42,0xc0,0x0d,0x63,0xde,0xd3,0xf5,0xd2, -0xbb,0x62,0x8f,0xdc,0x77,0x6c,0x01,0xf7,0xb7,0x5a,0x33,0xbd,0x37,0xee,0xab,0xf7, -0xc6,0xe7,0x2b,0x2e,0xf3,0xbe,0xa7,0x8d,0xd2,0xe2,0xd1,0x56,0xef,0x97,0x2f,0xd4, -0x7b,0xe8,0xf3,0x64,0x6f,0xa9,0x71,0xea,0x69,0x7a,0x0f,0xd0,0xc2,0x39,0x32,0x06, -0x9d,0xa9,0x74,0xf6,0xd0,0x31,0x8d,0x15,0xde,0x9c,0x63,0x6d,0xc8,0x71,0xde,0x85, -0x75,0xb0,0x3e,0xe4,0x5e,0x9b,0xc6,0x3a,0xd6,0xbc,0x8f,0x58,0xa2,0xf7,0xc3,0xf7, -0xc0,0x64,0x28,0x56,0xc1,0x7d,0xdf,0xe9,0xbd,0xab,0xf6,0xe6,0xbb,0x78,0xf3,0xc4, -0x6a,0x58,0xf6,0x74,0xcb,0x9e,0x68,0x5d,0x43,0xe3,0x4e,0xd6,0xb5,0xf4,0xec,0x9e, -0x7f,0xaa,0xe5,0x9f,0x6a,0xcd,0x39,0x4b,0xd5,0x35,0xf7,0xec,0x5e,0xf8,0x34,0xd5, -0x03,0xcf,0xee,0xf9,0xd7,0xb4,0x8e,0xad,0x69,0x85,0xa9,0xa9,0xfa,0xe2,0xd9,0xbd, -0xf0,0xde,0x75,0x38,0x16,0xed,0x2d,0x9a,0x59,0xea,0xb7,0x7b,0x5c,0x64,0xd1,0xcc, -0x52,0xef,0x3a,0x37,0xd4,0x38,0x42,0x4b,0x95,0x5f,0x5e,0x0c,0xb5,0xe8,0x6d,0xa9, -0xdf,0xee,0x31,0xdc,0xa2,0xb7,0xa5,0xbd,0x55,0xb7,0xba,0xeb,0xba,0xf5,0xd3,0xb5, -0xf0,0xca,0x7e,0x02,0x0d,0xb6,0xa6,0x99,0xfb,0x20,0xbd,0x57,0xba,0x56,0xfa,0x9e, -0x74,0x9d,0x34,0xa2,0x82,0xab,0xf9,0xa4,0x05,0xa4,0xb1,0xd2,0x73,0xa4,0x55,0x2b, -0xfc,0x7f,0xe2,0x8f,0x41,0x1d,0x85,0x6f,0x28,0xcd,0x92,0x36,0x95,0x9a,0xb6,0x6c, -0xb4,0xab,0xdc,0x2d,0xa5,0x75,0xe4,0x5f,0x4f,0x7a,0xb9,0xfc,0x7b,0x48,0x07,0x49, -0x07,0x4b,0x87,0x4a,0x87,0x49,0xaf,0x91,0x5e,0x2b,0x1d,0x2d,0x1d,0x23,0xbd,0x49, -0x7a,0xb3,0xf4,0x71,0xe9,0x54,0xe9,0x34,0xe9,0x74,0xe9,0x08,0xe9,0x75,0xd2,0xbb, -0xa4,0x77,0x4b,0x67,0x4b,0xe7,0x48,0x5f,0x94,0xce,0xf5,0xca,0x93,0x8b,0x12,0x93, -0x70,0x62,0xfd,0x9c,0xdd,0x9e,0x12,0xad,0xbe,0x31,0xd1,0x39,0xd2,0x9e,0xbc,0xf9, -0x9b,0x5e,0x7b,0xf1,0xda,0x87,0xd7,0x46,0xbd,0xfa,0x9f,0xae,0x63,0x13,0xd4,0x67, -0x26,0xaa,0xdf,0xac,0x2c,0x7f,0xcf,0x9e,0x6c,0xd9,0x53,0x2c,0x7b,0xaa,0x65,0x4f, -0xb3,0xec,0x35,0x2c,0x7b,0x4d,0xcb,0x9e,0x6e,0xd9,0xbd,0x7c,0xd8,0xee,0x44,0x9f, -0x3b,0xc9,0xe7,0x4e,0xf6,0xb9,0x53,0x7c,0xee,0x54,0x9f,0x3b,0xcd,0xe7,0xae,0xe1, -0x73,0xd7,0xf4,0xb9,0xd3,0x7d,0xf9,0xf7,0xd2,0x97,0xa8,0x7b,0x65,0x92,0x34,0x59, -0x9a,0x22,0x4d,0x95,0xa6,0x49,0x6b,0x48,0x6b,0x4a,0xd3,0xa5,0x5e,0x9e,0xe3,0xad, -0xfc,0xc6,0x5b,0x79,0x8d,0xb7,0xf2,0x19,0x6f,0xe5,0x31,0xde,0xca,0x5f,0xbc,0x95, -0xb7,0x78,0x2b,0x5f,0xf1,0x56,0x9e,0xe2,0xad,0xfc,0xc4,0x5b,0x79,0x89,0x57,0xde, -0xba,0x5a,0xf9,0xec,0x66,0xd9,0xbb,0x5b,0xf6,0xcb,0x2d,0x7b,0x0f,0xcb,0xde,0xd3, -0xb2,0xf7,0xb2,0xec,0x57,0x58,0xf6,0xde,0x96,0xfd,0x4a,0xcb,0xde,0xc7,0xb2,0xf7, -0xb5,0xec,0xfd,0x2c,0x7b,0x7f,0xcb,0x3e,0xc0,0xb2,0x67,0x5b,0xf6,0x81,0x96,0x7d, -0x90,0x65,0x1f,0x6c,0xd9,0x87,0x58,0xf6,0xab,0x2c,0xfb,0x50,0xcb,0x3e,0xcc,0xb2, -0x0f,0xb7,0xec,0x57,0x5b,0xf6,0x6b,0x64,0x6f,0xe0,0x1c,0xb9,0x9f,0x36,0xb2,0xee, -0xa7,0x27,0x32,0x16,0x6c,0xdf,0xcf,0xdb,0x5a,0xe3,0xc1,0xed,0x35,0x26,0x6c,0xee, -0x13,0x1d,0x75,0x1f,0xef,0xaa,0x6b,0xd2,0xdd,0xba,0xd7,0xf6,0x54,0x59,0x5f,0x61, -0xdd,0x77,0xfd,0xcf,0x30,0x03,0x54,0x46,0x03,0x55,0x26,0x83,0xad,0xf1,0xe1,0xa1, -0xca,0xeb,0x70,0xe5,0xed,0x1a,0xd5,0x07,0x7f,0x1f,0x5d,0xcb,0x71,0xa9,0x9b,0x07, -0x1f,0x57,0x71,0xfb,0xab,0x2b,0x95,0xf6,0xae,0x71,0x8e,0xb3,0x86,0x84,0x3c,0xf6, -0x98,0x9b,0xd9,0xca,0x90,0x06,0xf5,0xa1,0x23,0x8c,0x85,0xdb,0x61,0x32,0xbc,0x6c, -0xfc,0x29,0x84,0x1e,0xd0,0x07,0x46,0xc3,0x7d,0x30,0x1d,0xb6,0xc0,0xb7,0x2a,0xa0, -0x87,0xe0,0x20,0x94,0xa2,0xa0,0xce,0x80,0x9a,0xd0,0x00,0x2e,0x81,0xde,0x30,0x1a, -0x5e,0x82,0x95,0xb0,0x0d,0x36,0x90,0x90,0xb2,0x14,0xe2,0x6e,0x0a,0x31,0x48,0x21, -0xe6,0x87,0x52,0x50,0x09,0x06,0x43,0xeb,0x4e,0x8e,0x33,0x12,0x7e,0x80,0x22,0x97, -0x38,0x4e,0x05,0xa8,0x09,0xfd,0x61,0x20,0x6c,0xba,0xd4,0x71,0x3e,0x83,0xfd,0xf0, -0x33,0x0c,0xba,0x8c,0xf2,0x81,0x1b,0xe0,0x1b,0xf8,0x19,0x0a,0x74,0xe6,0xb7,0x03, -0xb4,0x86,0xae,0x30,0x18,0x5e,0x83,0x7c,0x5c,0xa8,0x34,0x68,0x01,0xd5,0xb9,0x50, -0x29,0x70,0x33,0xdc,0x0f,0x4f,0xc2,0x02,0xd8,0x02,0x9f,0xc1,0x3e,0x2e,0x62,0x3e, -0x2e,0x62,0x65,0x28,0x47,0x99,0x75,0x83,0xab,0x61,0x0e,0xac,0x86,0xf7,0x60,0x13, -0x14,0xe1,0xa2,0x96,0x84,0x14,0xe8,0xc3,0x05,0xad,0xc2,0xc5,0x4c,0x83,0xda,0x50, -0x1f,0x9a,0x40,0x47,0xe8,0x04,0xcf,0xc1,0x8d,0x5c,0xe8,0x5b,0x20,0x87,0x8b,0xbd, -0x03,0x4e,0xe3,0x82,0x97,0x85,0xca,0x90,0x00,0xb7,0xc1,0xdd,0x30,0x94,0x4a,0x70, -0x1d,0xbc,0x00,0x8b,0xe1,0x2b,0xd8,0x44,0xa5,0xd8,0x0a,0x07,0xa0,0x16,0x15,0x63, -0x3e,0x2c,0x82,0x21,0x54,0x90,0xd5,0x70,0x10,0x06,0x8f,0xa0,0xec,0x20,0xed,0x06, -0xea,0x30,0xdc,0x0a,0x0b,0x21,0x30,0xd2,0x71,0x0a,0x42,0x71,0x48,0x86,0x1b,0xe0, -0x16,0xd8,0x36,0xca,0x71,0x76,0xc1,0x01,0x38,0x0c,0x05,0x47,0x3b,0x4e,0x69,0x28, -0x0b,0xfd,0x61,0x10,0x0c,0x87,0x96,0x37,0x91,0x3f,0xc8,0x18,0x47,0x7b,0x81,0xee, -0x70,0xfd,0x2d,0xa4,0x17,0xd6,0x81,0x73,0x2b,0xfd,0xda,0xed,0xb4,0x31,0x68,0x07, -0xc3,0xe1,0x11,0xb8,0xfc,0x0e,0xea,0x39,0xcc,0x81,0xe9,0x77,0x3a,0xce,0x2a,0x78, -0x68,0x3c,0xcf,0xdb,0x30,0x17,0xee,0x9a,0x40,0x5b,0xbc,0xcb,0x71,0x96,0xc3,0x5b, -0xf0,0x2e,0x0c,0x9b,0x48,0x1d,0x80,0x33,0xef,0xa3,0xee,0xc0,0x02,0xd8,0x09,0x6d, -0xee,0x77,0x9c,0xcb,0xa0,0x1b,0xf4,0x86,0xd5,0xb0,0x07,0x0e,0x40,0xe0,0x01,0xee, -0xf7,0xb0,0x09,0x36,0xc3,0x7d,0x93,0xf8,0x2d,0x0a,0xcf,0xc1,0xd4,0x07,0x1d,0x67, -0x23,0x6c,0x86,0x73,0x1e,0xe2,0xda,0x43,0x12,0xd4,0x81,0x8b,0xe1,0xb3,0x87,0x69, -0x77,0x8f,0x52,0x26,0xf0,0x14,0xbc,0x02,0xaf,0xc1,0x1a,0x78,0x17,0x0e,0xc2,0x4f, -0x50,0x98,0x76,0x53,0x02,0xca,0x41,0x6d,0x68,0x0e,0x17,0xc0,0x1d,0xf0,0x30,0x4c, -0x7e,0xcc,0xfd,0xed,0x54,0x3c,0xc1,0x6d,0x03,0x8d,0x20,0x0b,0x5a,0xe0,0x9e,0x04, -0x2d,0xa5,0xad,0xa4,0x6d,0xa4,0x6d,0xa5,0xed,0xa4,0x1d,0xa4,0x1d,0xa5,0x9d,0xa4, -0x97,0x4a,0x3b,0x4b,0xbb,0x4a,0x2f,0x97,0xf6,0x94,0x5e,0x21,0x1d,0x60,0xe9,0x83, -0x30,0x48,0xee,0x41,0x72,0x5f,0x25,0xf7,0x55,0x72,0x0f,0x97,0x7b,0xb8,0xdc,0xd7, -0xca,0x7d,0xad,0xdc,0x8d,0xe5,0x36,0x79,0xf4,0xd4,0xf8,0x3f,0x22,0xff,0x71,0x70, -0x2b,0x4c,0x97,0xfb,0x79,0xe9,0x0c,0xe9,0x2c,0xe9,0x1c,0xe9,0x5c,0xe9,0x3c,0xe9, -0x02,0xe9,0x2b,0xd2,0x85,0xd2,0xc5,0xd2,0xa5,0xd2,0xd7,0xa5,0xcb,0xa5,0x2b,0xa5, -0xef,0x58,0x6a,0xd2,0xb5,0x4e,0xee,0x75,0x72,0xbf,0x2f,0xf7,0xfb,0x72,0x6f,0x94, -0x7b,0xa3,0xdc,0x9b,0xe4,0xde,0x24,0xf7,0xd3,0x72,0xef,0x95,0xee,0x93,0xee,0x97, -0x7e,0x2d,0xfd,0xc9,0xca,0x97,0x49,0x8b,0x53,0x8c,0xfa,0x08,0xcf,0x42,0x10,0x9e, -0x83,0xe7,0x21,0x02,0x22,0x21,0x04,0x33,0x61,0x16,0xcc,0x86,0x39,0xf0,0x22,0xcc, -0x85,0x33,0x20,0x0a,0xa2,0x21,0x1f,0x94,0x87,0x18,0xc8,0x0f,0x05,0xa0,0x20,0x14, -0x82,0xc2,0x50,0x04,0x8a,0x42,0x31,0x28,0x0e,0x5d,0xa1,0x1b,0x74,0x87,0xcb,0xa1, -0x07,0xf4,0x84,0x5e,0x70,0x05,0xf4,0x86,0x2b,0xa1,0x0f,0xf4,0x85,0x7e,0xd0,0x1f, -0x06,0x40,0x36,0x0c,0x84,0x41,0x30,0x18,0x86,0xc0,0x55,0xd0,0x05,0x4a,0x42,0x29, -0x58,0x01,0x2b,0xe1,0x2d,0x78,0x1b,0xd6,0xc3,0x06,0xf8,0x10,0xce,0x84,0x8f,0x61, -0x33,0x9c,0x05,0x65,0xa0,0x1c,0x54,0x80,0x58,0xa8,0x04,0xe7,0x42,0x55,0xa8,0x06, -0x71,0x10,0x0f,0xd5,0x21,0x09,0xd2,0x20,0x03,0x9a,0xc0,0x79,0xb0,0x1f,0xbe,0x86, -0x0e,0x70,0x11,0x74,0x84,0x1b,0x61,0x2c,0x8c,0x83,0xbb,0xe0,0x6e,0xb8,0x17,0x1e, -0x85,0x29,0xc5,0xdc,0x7b,0x9a,0xb9,0x7f,0xc5,0xc0,0x26,0xee,0x33,0xf9,0xd1,0x38, -0x28,0x00,0x49,0x57,0xb9,0xf7,0xb8,0xd3,0x21,0x00,0xe7,0x72,0xaf,0x49,0xe8,0xe0, -0xde,0xe7,0xcc,0x73,0x83,0xb9,0x66,0xde,0x33,0x44,0xd0,0xb2,0x47,0x58,0xf6,0x90, -0x65,0x8f,0xb2,0xec,0xd1,0x96,0x3d,0xc6,0xb2,0x17,0xb0,0xec,0x05,0x2d,0x7b,0x61, -0xcb,0x5e,0xc4,0xb2,0x17,0xb5,0xec,0xc5,0x2c,0x7b,0x71,0xcb,0xee,0xe8,0x3a,0xdb, -0x69,0xed,0xea,0x4b,0x6f,0x57,0x5f,0x9a,0xbb,0xfa,0xd2,0xdd,0xd5,0x97,0xf6,0xae, -0xbe,0xf4,0x77,0xf5,0xe5,0xa1,0xab,0x2f,0x1f,0x5d,0x7d,0x79,0xe9,0xea,0xcb,0x4f, -0x57,0x5f,0x9e,0xba,0xfa,0xf2,0xd5,0xd5,0x97,0x37,0x7f,0xfc,0xfd,0x7d,0xe7,0xef, -0xad,0x7a,0x6f,0xea,0xf3,0xf4,0x63,0xec,0x2b,0xee,0x3b,0xc6,0xd4,0x03,0xcf,0x7e, -0xbb,0x65,0x8f,0xb1,0xec,0xa6,0x7e,0x78,0xf6,0x7b,0x2d,0xff,0x7e,0x6d,0xac,0xb2, -0xb4,0xfc,0xfb,0x58,0xfe,0x97,0x5a,0xfe,0xa6,0x9f,0xf7,0xec,0xe6,0x79,0xe1,0xd7, -0xf0,0xd9,0xd6,0x6f,0xb0,0xbe,0x47,0xec,0x95,0xad,0x30,0xe6,0x5e,0xe7,0xd9,0xcd, -0x33,0x91,0x67,0x37,0xcf,0x1f,0x9e,0xbd,0xca,0x15,0x56,0xfa,0xad,0x63,0xeb,0x5d, -0x7d,0xc4,0x5e,0xe8,0x42,0xeb,0x59,0x78,0xd0,0x11,0xfb,0x94,0xdb,0xad,0x34,0x5b, -0xe1,0x5f,0xbc,0xe0,0x88,0x7d,0x9b,0x95,0x97,0x11,0x56,0x3c,0x3d,0x3b,0x59,0x61, -0x86,0x1e,0xb1,0x07,0x5a,0x1d,0xb1,0xaf,0xb0,0xe2,0xbf,0xd0,0x2a,0x87,0x7e,0xd6, -0xb9,0x8a,0x59,0xe1,0xcd,0x73,0x86,0x67,0x3f,0x20,0x7b,0x2b,0x1e,0xac,0x47,0x5c, -0xe6,0x3e,0x87,0x8d,0xbf,0xd6,0x7d,0xf6,0xf6,0xde,0x99,0x25,0x59,0xbf,0xb5,0x92, -0xac,0xdf,0xda,0x49,0xfa,0x9d,0x95,0xe4,0x1c,0x79,0x0f,0x95,0x26,0xad,0x21,0xad, -0x29,0x4d,0xd7,0x31,0x09,0xd6,0xef,0xed,0x64,0x2b,0xae,0x64,0xeb,0xf7,0x7b,0xb2, -0xe2,0x73,0xd4,0x6f,0x47,0xa8,0xaf,0xf6,0xfa,0xe3,0x18,0xab,0x0f,0x3e,0x56,0xff, -0xeb,0xb5,0x4d,0xaf,0x4d,0x7a,0x6d,0xd1,0x6b,0x83,0x5e,0xdb,0xf3,0xda,0x9c,0xd7, -0xd6,0xbc,0x36,0xe6,0xb5,0x2d,0xaf,0x4d,0x79,0x6d,0xc9,0x6b,0x43,0x5e,0xdb,0x29, -0xee,0x0b,0x37,0x4f,0xe7,0xf6,0xda,0x49,0x7f,0xc5,0x39,0x44,0xda,0xff,0x18,0x7d, -0xa3,0xa9,0xf3,0xa6,0xae,0x9b,0x3a,0x6e,0xea,0xb6,0xa9,0xd3,0xa6,0x2e,0x9b,0x3a, -0x6c,0xea,0xae,0xa9,0xb3,0xa6,0xae,0x9a,0x3a,0x6a,0xea,0xa6,0xa9,0x93,0xa6,0x2e, -0x9a,0x3a,0x68,0xea,0x9e,0xa9,0x73,0xa6,0xae,0x99,0x3a,0x66,0xea,0x96,0xa9,0x53, -0x1b,0xd1,0x1a,0x57,0xb9,0xcf,0xf1,0xbd,0x79,0xae,0xab,0x42,0xbc,0xd9,0xc4,0xb9, -0x93,0xb8,0x42,0x0f,0xb8,0x75,0x61,0x12,0x7e,0xdd,0xfb,0x1c,0xdd,0x37,0xef,0xe0, -0x39,0xfe,0x00,0xe1,0x6a,0xc3,0xfd,0x9d,0xdc,0xba,0x67,0xea,0x9c,0xa9,0x6b,0xa6, -0x8e,0x99,0xba,0x75,0x66,0x47,0xf7,0xfa,0xa4,0xe9,0x3a,0xd5,0x90,0x7a,0xef,0x0f, -0xd3,0x75,0x0d,0x13,0xac,0xf7,0x29,0x29,0x56,0x5d,0xf1,0xae,0x71,0x8a,0xf5,0xae, -0x26,0x45,0xf1,0xa5,0x28,0xbe,0x14,0xc5,0x97,0xa2,0xf8,0x52,0xad,0x77,0x37,0xa6, -0x5c,0x92,0xa4,0xc9,0xd2,0x14,0x69,0xaa,0x34,0x4d,0x5a,0x43,0x5a,0x53,0x9a,0x2e, -0xf5,0xde,0x27,0x78,0xf6,0x44,0xcb,0xee,0xc5,0xdd,0x54,0xbf,0x1d,0x7b,0xe8,0x77, -0xa1,0x67,0x6f,0x6f,0xbd,0x43,0x36,0xbf,0x67,0x1f,0x27,0xa2,0x27,0xf5,0x8c,0x32, -0x15,0x9e,0xd5,0x73,0xd7,0xf3,0x7a,0xde,0x9a,0xa5,0xe7,0x91,0xb9,0x7a,0xbe,0x5a, -0xa0,0xe7,0xaa,0x85,0x7a,0x9e,0x5a,0xaa,0xe7,0xa8,0xe5,0x7a,0x66,0x59,0x05,0xab, -0xe1,0x2d,0x58,0x03,0x6f,0xeb,0x39,0x6a,0x9d,0x9e,0x97,0x36,0xea,0xb9,0xe8,0x13, -0xd8,0x0c,0x5b,0xe0,0x53,0xd8,0x0a,0xdb,0x61,0x07,0xec,0x84,0x2f,0x60,0x17,0xec, -0x86,0x2f,0x61,0x8f,0x9e,0x9f,0xf6,0xe9,0xb9,0xc9,0x3c,0x33,0x6d,0x37,0x75,0xf1, -0x42,0x37,0x0f,0xde,0xb3,0xda,0x61,0xa5,0xe3,0x71,0x1d,0x6b,0xce,0x39,0x45,0xee, -0x03,0xd6,0x33,0xda,0xe3,0xe2,0xb0,0xc2,0x3d,0xa9,0x74,0x1f,0xb0,0x9e,0x33,0x9f, -0x94,0x7b,0xa9,0xca,0x67,0x9a,0xdc,0x53,0x55,0x0e,0x33,0xac,0xf3,0x4d,0x92,0xff, -0x61,0x95,0xdf,0x61,0x95,0xe5,0x01,0x85,0x7d,0x56,0x7e,0x5b,0xb4,0xff,0x49,0xe5, -0x6f,0xba,0xf2,0xfa,0x9a,0xe2,0x99,0xae,0xbc,0xee,0xb2,0xe2,0x9a,0x24,0xbf,0x03, -0x96,0xfb,0x80,0xca,0xd0,0x7b,0x36,0xf6,0x3f,0x2b,0xaf,0xd6,0xf1,0xc6,0xfd,0x99, -0x15,0x9f,0xb7,0x7f,0xb7,0xf5,0x3c,0xec,0xf9,0xef,0xb1,0xd4,0x2b,0x83,0x2f,0x94, -0x66,0xcf,0xff,0x53,0x2b,0xcf,0xbb,0x2d,0xff,0xbd,0x56,0x1e,0xfc,0xc7,0xfa,0xdd, -0x2b,0xad,0x72,0xde,0x6d,0x3d,0xa7,0x3f,0x69,0x9d,0x7b,0x8f,0xce,0xb3,0x46,0x75, -0xf0,0xb0,0xca,0x71,0x8e,0x8e,0x59,0x25,0xfb,0x61,0xeb,0x39,0x7b,0xae,0xe2,0xf0, -0xe2,0x9d,0x6b,0x5d,0x3f,0xaf,0xec,0xe7,0xa9,0x2c,0xec,0xeb,0xfc,0x8a,0x15,0xce, -0xb3,0xaf,0xf4,0x95,0xcf,0x02,0xeb,0x77,0xc2,0x3c,0xeb,0x9a,0xef,0xb6,0xf2,0xb3, -0x4a,0xf5,0xfd,0x6d,0xab,0x2c,0xde,0x51,0x9a,0x5e,0xf7,0xd5,0x51,0xfb,0x3c,0xb6, -0xff,0xeb,0xd6,0xef,0x8f,0xc3,0xaa,0xfb,0xbb,0xad,0xdf,0x1e,0x8f,0x2b,0x2d,0x2b, -0x7d,0xfe,0x33,0x7c,0xee,0x39,0xd6,0xef,0x16,0xbb,0x1d,0xd8,0x75,0xcd,0xfb,0x0d, -0xf3,0x84,0x75,0x4d,0xbd,0xdf,0x36,0xaf,0x29,0x9f,0xcf,0x58,0xc7,0x7f,0x61,0xb5, -0xa1,0x19,0x2a,0x1f,0xaf,0xfd,0x78,0xed,0x6a,0xa1,0x65,0x5f,0xad,0x34,0x6c,0x54, -0x98,0xd7,0xad,0x7d,0x5e,0xbb,0xd8,0x68,0xe5,0x7d,0x9e,0xf5,0x3b,0xca,0xcb,0xff, -0x62,0xeb,0xfa,0x3e,0x69,0x95,0xd9,0x26,0x5f,0xf9,0x6f,0xd2,0xbe,0x4d,0x56,0xfc, -0x2b,0xad,0xdf,0x61,0x5e,0x3a,0x3d,0xbb,0xd7,0x7e,0x9e,0xb4,0xea,0x9b,0xe7,0xde, -0x2d,0xfb,0x6b,0xba,0x16,0x9f,0xc8,0x6f,0x86,0xec,0x07,0x94,0xd6,0xcf,0x65,0xdf, -0x6c,0xc5,0xe1,0xb9,0x77,0x59,0x6a,0x5f,0xcf,0xdd,0x6a,0x43,0x5e,0x7b,0xb5,0xed, -0x5e,0x3d,0xf2,0xb7,0xb1,0xed,0xbe,0x7e,0x66,0xbb,0x15,0xd7,0x0e,0xab,0x6f,0xdb, -0x65,0x5d,0xdb,0xdd,0x72,0x7f,0xe1,0xab,0x17,0xde,0x71,0x87,0xad,0x6b,0xed,0xf5, -0xb1,0x5b,0xa4,0x5e,0xd9,0xcd,0xb2,0xfa,0x1a,0xbb,0x7d,0x9b,0x7b,0xcf,0x82,0x6c, -0xf7,0x7e,0x63,0x34,0x49,0x9a,0x2c,0x4d,0x91,0xa6,0x4a,0xd3,0xa4,0x35,0xa4,0x35, -0xa5,0xe9,0x56,0x3c,0x76,0x9c,0x89,0x96,0x3d,0xc9,0xb2,0x27,0x5b,0xf6,0x14,0xcb, -0x9e,0x6a,0xd9,0xd3,0x2c,0x7b,0x0d,0xcb,0x5e,0xd3,0xb2,0xa7,0x5b,0xe9,0x4e,0xb0, -0xec,0x76,0x7e,0x92,0x2c,0x7b,0xb2,0x65,0xf7,0xce,0x7b,0x85,0xde,0xef,0x76,0xd5, -0xfb,0xda,0xae,0x7a,0x57,0xdc,0x4e,0xef,0x71,0xbb,0xea,0xbe,0x3b,0x40,0xf7,0xdc, -0x6c,0xdf,0x78,0x9c,0xa7,0x49,0x96,0x3d,0x59,0xef,0x93,0x4d,0x1c,0x83,0x79,0x96, -0x2d,0x4a,0x44,0x71,0x3d,0xdd,0x7b,0x9c,0x79,0xaf,0x69,0x9e,0x77,0x0a,0xe3,0x7e, -0xa5,0xaf,0xfb,0x0c,0x55,0xa4,0x33,0xbf,0xf3,0x5b,0xb9,0xcf,0x51,0xd9,0x3a,0x7f, -0x7f,0xe9,0xab,0x9a,0xe7,0xdc,0x4f,0xee,0x3e,0xd2,0x16,0x7a,0x9f,0xdd,0x52,0xda, -0x44,0xea,0x8d,0x77,0xf7,0x55,0x58,0xdb,0x9d,0xad,0x77,0xde,0xfd,0xa5,0xaf,0x46, -0x1c,0xd1,0x5e,0x3a,0x87,0xf7,0xdd,0x92,0x37,0xee,0x7d,0x8d,0xdc,0x9e,0xbd,0xa5, -0x65,0x6f,0x62,0xd9,0x2f,0xb4,0xec,0xaf,0x46,0x1c,0x79,0xb7,0xdd,0x57,0xe5,0xd2, -0xd7,0x7a,0xe7,0xdd,0xd3,0x7a,0xef,0xdd,0x4f,0xe1,0xfb,0x39,0x47,0xe8,0x2e,0xed, -0xe3,0x1c,0xed,0x9f,0x64,0xed,0x4b,0xb2,0xb4,0x8f,0xcf,0xcf,0xbb,0x06,0xdd,0x2d, -0xbb,0xa7,0x7d,0x7c,0x7e,0xa5,0x2a,0xb8,0xef,0xda,0x6d,0x7b,0x92,0x55,0x27,0xfa, -0x58,0xf6,0x96,0x96,0xbd,0x89,0x65,0x1f,0x64,0xd5,0x1f,0xdb,0xee,0xc5,0x77,0x2c, -0xbf,0x24,0x6b,0xde,0x42,0x7f,0xe9,0xab,0x11,0x47,0xd2,0x32,0x58,0xfb,0xdb,0x6b, -0x7f,0x7b,0xed,0x6f,0xaf,0xfd,0xed,0x95,0xb6,0xf6,0x4a,0x97,0x57,0x37,0x3b,0x28, -0x7c,0x07,0x85,0xef,0xa0,0xf0,0x1d,0x14,0xbe,0x83,0xc2,0x7b,0xee,0x69,0xfa,0xbe, -0x66,0x9a,0xe6,0xd0,0xc7,0x2b,0x7c,0xbc,0xea,0xd3,0x40,0x95,0x63,0x77,0xab,0xde, -0x37,0x54,0x3e,0xbc,0x7a,0xd2,0x50,0xed,0x23,0x5e,0xfb,0xbd,0xfa,0x78,0xb5,0xc6, -0x3c,0xba,0xaa,0x6e,0xb4,0xd6,0xf8,0x47,0x7f,0xd5,0x5f,0x8f,0x96,0x4a,0xcb,0x10, -0xe7,0xe8,0x7a,0xd3,0x5f,0x3a,0x40,0xe7,0xe9,0xab,0x31,0x90,0x7e,0x6a,0x9b,0xfd, -0xac,0x31,0xf2,0x7e,0x0a,0xd7,0x57,0xe7,0x69,0xaa,0xf2,0xb0,0xf3,0xd3,0x5a,0x78, -0xd7,0xd1,0x9b,0x2b,0x32,0x48,0xe3,0x3a,0x43,0x55,0x2e,0xdd,0x54,0x9e,0x26,0x8f, -0x5e,0xbb,0xf3,0xec,0x89,0xfa,0x3d,0x9e,0x24,0x4d,0x96,0xa6,0x48,0x53,0xa5,0x69, -0xd2,0x1a,0xd2,0x9a,0xd2,0x74,0xa9,0xd7,0x57,0x7a,0xf6,0x44,0xcb,0x9e,0x64,0xd9, -0x93,0x2d,0x7b,0x8a,0x65,0x4f,0xb5,0xec,0x69,0x96,0xbd,0x86,0x65,0xaf,0x69,0xd9, -0xd3,0xad,0x74,0x27,0x58,0x76,0x3b,0x3f,0x49,0x96,0x3d,0xd9,0xb2,0xa7,0x58,0xf6, -0x54,0xcb,0x9e,0x66,0xd9,0x6b,0x58,0xf6,0x9a,0x96,0x3d,0xdd,0x2a,0xa7,0x04,0xcb, -0xee,0x9d,0xb7,0x97,0xd5,0x3f,0x35,0x8f,0xe4,0x37,0x0d,0x0c,0x78,0xc6,0xad,0x53, -0x8d,0x35,0xee,0x56,0x31,0xc0,0xf5,0x81,0x4a,0xf8,0xd7,0x98,0x4e,0x5d,0x09,0x72, -0xed,0xd0,0x3b,0xd0,0xa6,0xfc,0x1e,0xfc,0xa6,0xa7,0x3b,0x8e,0xb0,0x12,0xfb,0xbb, -0x54,0x9a,0x24,0x7e,0x4f,0x7c,0xd6,0xd6,0x7d,0x07,0x6f,0x68,0xd3,0xd1,0xfd,0xdd, -0x7a,0x33,0x1d,0x72,0x53,0xec,0xdf,0x71,0xc2,0xde,0x5c,0xec,0xb1,0x37,0x38,0x4e, -0xfd,0x9b,0x1c,0xe7,0xe5,0x9b,0x1d,0xe7,0x87,0x71,0x8e,0x33,0x9e,0xdf,0xa8,0xc1, -0x2b,0x1d,0xa7,0x34,0x17,0xfa,0x43,0x2a,0xcf,0x27,0x54,0x8e,0xba,0x37,0x3a,0xce, -0x95,0x1c,0xbb,0x7f,0x92,0xe3,0x8c,0x26,0xde,0xab,0x88,0x37,0x92,0xca,0x5a,0x9a, -0x4a,0x13,0xc7,0xb1,0x65,0x1e,0xa5,0x2e,0xf1,0x7b,0x75,0x37,0x95,0x6f,0xcd,0x58, -0xea,0xff,0x2d,0x8e,0xf3,0x26,0x15,0x68,0xe3,0x28,0x7e,0x27,0x13,0xe7,0x2a,0xfa, -0xff,0x53,0xc9,0xe4,0x95,0xc4,0x79,0x98,0x63,0xde,0xe6,0x1c,0x37,0xd1,0xd7,0xcf, -0x23,0x63,0x9f,0x50,0x01,0x5f,0xa7,0xc1,0xac,0xe7,0x9c,0x45,0xd9,0xf7,0xf9,0x50, -0x77,0x5c,0x26,0x8a,0x78,0x2f,0x81,0xbd,0x77,0x90,0x97,0xfb,0x29,0x8f,0x87,0x1c, -0xe7,0xd0,0x23,0xdc,0x3f,0xa8,0xfc,0x37,0xd0,0xa8,0x26,0x5f,0xc7,0x39,0xc6,0x90, -0x8e,0x7b,0xdc,0x31,0x8a,0x0f,0x6e,0xe5,0x19,0xe5,0x22,0xdc,0xdc,0x47,0xba,0x8c, -0x70,0x9c,0xeb,0x89,0xa3,0x1b,0xf1,0xad,0x22,0xfc,0x32,0xca,0xe4,0xfb,0xfb,0x48, -0x0f,0xfb,0xbb,0x5d,0xe2,0x38,0x25,0x38,0xd7,0x47,0xa4,0xa5,0x08,0xe9,0xad,0x4e, -0x3c,0x35,0xae,0xa7,0x0d,0xb2,0x7f,0x1d,0x69,0xb9,0x8d,0xe3,0x72,0x48,0xd7,0x5b, -0x70,0x26,0x1d,0xf9,0x22,0xf6,0xef,0xe7,0x3c,0x57,0xb1,0x7f,0xe4,0x6d,0x3c,0xff, -0x74,0x73,0xcb,0xe7,0x67,0xce,0x97,0x4e,0x59,0x7c,0xce,0xef,0xf2,0xe2,0x5d,0x28, -0x57,0xca,0x29,0x9b,0xdf,0xf9,0xa7,0x52,0x36,0x3f,0x72,0xce,0xc5,0xe4,0x6f,0x1a, -0x69,0x29,0x44,0x98,0xb7,0xb8,0xb0,0xc3,0xb9,0xce,0x15,0x88,0xeb,0x35,0xf6,0x5f, -0x46,0x3a,0x02,0xc3,0xb8,0x3f,0x52,0xae,0xcf,0x12,0xcf,0xcb,0x7d,0xdc,0xb1,0x9f, -0x71,0x84,0xfb,0x99,0xf8,0x3f,0x1b,0x4d,0xfe,0xe8,0x68,0x7a,0x10,0xdf,0x0b,0x1c, -0xdf,0x9b,0xb4,0xbc,0x09,0xa3,0xe8,0x48,0x3e,0x27,0x6f,0x03,0xd8,0xbf,0x8e,0xe3, -0xde,0xe1,0x9a,0x7c,0x4b,0x9a,0x33,0x2f,0x74,0xdf,0x2f,0x7c,0x49,0x39,0xbf,0xc1, -0x79,0x7e,0x26,0x5f,0x55,0x28,0xa3,0xe7,0x27,0x52,0xe6,0x0f,0x3a,0xce,0xfd,0x94, -0xcf,0xdb,0x8f,0xba,0xe3,0x92,0xcb,0xa9,0x27,0xc3,0xcc,0xd8,0x1d,0xe7,0x1b,0x42, -0xf8,0x09,0x1a,0xac,0x7d,0x90,0x6b,0x10,0xcb,0x71,0xcd,0xe8,0xec,0x6e,0xa1,0x13, -0x5a,0xc5,0xf1,0xdf,0x90,0xde,0x01,0x94,0x47,0x45,0xc2,0x7e,0x45,0x5a,0x63,0xb9, -0x6e,0xcd,0x29,0xef,0x53,0x89,0xe7,0x09,0x58,0xc8,0x79,0x57,0x52,0x47,0x96,0x8d, -0x73,0xf3,0xf1,0x26,0xf1,0x7d,0x4b,0x9e,0xaf,0x25,0xed,0x2f,0x70,0x8e,0x7a,0xa4, -0xf5,0xaa,0xc1,0xee,0x6f,0xdb,0x83,0xed,0xdd,0xb2,0x7a,0x99,0x7a,0x72,0x26,0xe5, -0x35,0x1b,0xff,0xde,0x9c,0xe7,0x41,0xea,0x5f,0x63,0xce,0x91,0x72,0x37,0x75,0x92, -0x32,0x6e,0xca,0xb5,0x3e,0xed,0x01,0xae,0x03,0xe5,0xf7,0x82,0x79,0x87,0x42,0x1e, -0xe7,0xe3,0xff,0x29,0xc7,0xdc,0x44,0x3c,0x1f,0xd1,0x69,0x7d,0x45,0x3c,0xf5,0xb9, -0x8e,0x93,0x7a,0xb8,0xd7,0xe2,0x6d,0xd2,0x9c,0x49,0xbd,0x39,0x4c,0x1a,0x47,0x4c, -0x70,0xc7,0x9e,0xc6,0x91,0xcf,0x78,0x8e,0xbb,0x85,0x74,0x5e,0x4b,0xdd,0x3b,0x00, -0x0d,0xb8,0xe6,0x0f,0xd3,0x36,0x62,0x38,0x6f,0x47,0xca,0xb6,0x0f,0xd7,0xa9,0x28, -0x79,0xbc,0xec,0x01,0xf7,0xbd,0x4f,0x3c,0xe5,0x30,0x9c,0x63,0xaa,0x72,0x8e,0xd3, -0x49,0xe7,0x2e,0xc2,0x57,0x21,0xef,0xb7,0x91,0xa7,0x46,0x94,0xd3,0xa9,0x57,0xb8, -0xd7,0xf9,0x26,0xc2,0x9c,0x4b,0xbc,0x45,0xc8,0x7f,0x0f,0x53,0x9f,0x38,0xd7,0xf9, -0xc4,0x3f,0x95,0xfd,0x9f,0x71,0x0d,0xa3,0x88,0x7f,0x2b,0xf1,0x5f,0x4d,0xde,0xde, -0xa1,0x6c,0x3e,0x1d,0xe7,0x8e,0xe3,0x6d,0xe5,0xb8,0xfa,0x5c,0xff,0x97,0x49,0xc3, -0x59,0x1c,0xbb,0x96,0x74,0x3f,0x40,0xd8,0x43,0xb4,0x99,0x27,0xd8,0xd7,0xe1,0x61, -0xc7,0x79,0x8c,0xeb,0x74,0x3f,0x71,0xad,0xe6,0xdc,0x3b,0x47,0xb9,0x63,0x98,0xe5, -0xae,0x75,0x9c,0xbb,0x29,0xcb,0x25,0xd4,0xe7,0x49,0x94,0xf7,0x45,0xd4,0xc3,0x25, -0x66,0x9c,0x9a,0x7a,0x59,0x8b,0x74,0x44,0xc3,0xd3,0x94,0xfd,0x7a,0xd2,0xff,0x01, -0xe1,0xc6,0x52,0x3e,0x65,0x38,0xfe,0x45,0xd2,0x55,0x7b,0xbc,0x3b,0x36,0xd9,0xf2, -0x3e,0x77,0x5c,0x72,0x3d,0xe1,0x32,0xc8,0xeb,0x12,0xfa,0x81,0x8b,0xa9,0x87,0x43, -0x08,0xf3,0x09,0xee,0x2a,0xe4,0x6b,0x15,0x65,0x58,0x87,0x32,0xbf,0x0c,0x7a,0xc0, -0x78,0x68,0xcf,0xf5,0x58,0x34,0xc2,0x1d,0x2f,0x2d,0x4e,0x7b,0xfc,0x81,0xeb,0x5c, -0x93,0x32,0xfe,0x09,0xf6,0x52,0x6e,0x87,0xa1,0x32,0xfd,0xc2,0x8b,0xb4,0xcd,0x4f, -0xf0,0x9b,0xc7,0x79,0x5e,0xe0,0xda,0x7d,0x4e,0x19,0xb6,0x34,0xf5,0x96,0xb4,0x6d, -0x87,0x36,0xe4,0xfb,0x11,0xce,0x19,0x45,0x3d,0xb8,0x02,0x32,0x38,0xf7,0x54,0xb8, -0x5c,0xe3,0xd8,0xf7,0x72,0x7d,0xaf,0xa0,0x8c,0xef,0x84,0xaf,0xa1,0x15,0xd7,0x76, -0x2b,0xdc,0x45,0xfa,0xc6,0x52,0xae,0xc3,0xc8,0xcf,0x19,0x94,0x5b,0x05,0xea,0x68, -0x7f,0xca,0xad,0x2a,0x65,0x51,0x81,0xb2,0xbb,0x6b,0xb8,0xfb,0xcc,0xd8,0x0c,0x9a, -0x42,0x6b,0x93,0xe6,0xab,0xdd,0xf7,0x6f,0x77,0xc0,0x9d,0x90,0x41,0x19,0x8e,0x82, -0x25,0xd7,0xba,0x75,0x3a,0x86,0xf6,0xde,0x00,0x06,0x91,0xa7,0x10,0x75,0x6f,0x0f, -0xe5,0x7c,0xf5,0x68,0x97,0x0e,0xd4,0xa1,0xa2,0x94,0xd3,0x7d,0x10,0xa0,0x9c,0xd3, -0x61,0x3d,0xfd,0x47,0x3e,0xfa,0xa1,0x97,0xc6,0xbb,0x79,0xdf,0x46,0x1e,0x7f,0xa1, -0x5c,0x6a,0x93,0xf7,0xab,0x48,0xf7,0x57,0x99,0x41,0xe7,0x34,0x8e,0xad,0xc8,0x35, -0x99,0x4b,0x9e,0xaf,0x80,0x91,0x94,0x41,0x96,0x51,0x58,0x41,0xfe,0x0f,0x5d,0xe0, -0xe6,0xbf,0x1d,0x4c,0x82,0xad,0x2a,0xff,0x39,0xd0,0x88,0xb6,0x7b,0x21,0x74,0xbb, -0x98,0xb2,0xe4,0xda,0xad,0xe3,0x1a,0x7d,0x08,0xbd,0xa9,0x77,0xcf,0xc3,0x46,0xce, -0x71,0x3e,0x65,0x92,0x4f,0xe5,0xd3,0x45,0x65,0x94,0xc2,0xf5,0x7e,0x9d,0xb6,0x76, -0x26,0x6d,0xf7,0x02,0x68,0xdf,0xc3,0xbd,0x9e,0xa6,0xaf,0x2d,0x0d,0xed,0x7b,0xb9, -0xe3,0xf3,0xa6,0x7f,0x31,0x75,0x7f,0x13,0xe5,0xb7,0x5a,0x65,0x58,0x26,0xdb,0x2d, -0xc7,0x67,0xe8,0x87,0x52,0x29,0xcb,0x19,0x83,0xdc,0x3a,0x30,0x90,0x32,0x8d,0xa2, -0xee,0xd6,0x86,0xb3,0xa8,0x0f,0x65,0x87,0xba,0xf5,0x62,0x13,0x7c,0x03,0xcd,0x09, -0x9f,0x01,0x6f,0x51,0xee,0xb3,0x54,0xa6,0xd7,0x52,0x3f,0x3a,0x5d,0xe7,0x96,0x6d, -0x3d,0x95,0xe9,0x05,0xd4,0xcd,0xbd,0x70,0x35,0xf7,0x95,0x06,0x94,0xe5,0x4d,0x2a, -0xd3,0xc5,0xb7,0xba,0x75,0x68,0xf5,0xad,0x6e,0xf9,0x9a,0x7e,0x74,0xcf,0xad,0x6e, -0x39,0xdf,0x7a,0x9b,0x5b,0xce,0x35,0x29,0xe7,0x41,0x94,0xf3,0x24,0xda,0xcc,0x50, -0xfa,0x85,0x11,0xf7,0xb9,0x65,0x6e,0xea,0xe2,0xa6,0xfb,0xdd,0xb2,0x2f,0xf0,0x80, -0x5b,0xfe,0xc5,0x1f,0x72,0xef,0x6f,0xcd,0x2b,0x07,0x9d,0x46,0xf0,0x7e,0x72,0xd0, -0x79,0xa4,0x36,0x7d,0x48,0x06,0x71,0x42,0xb3,0x0b,0x82,0xce,0xda,0x4b,0x82,0xce, -0xfa,0xeb,0x83,0x4e,0x43,0xc2,0xdd,0xf9,0x98,0xfb,0xec,0xed,0xd1,0x5b,0xda,0xf7, -0x18,0x7e,0x9e,0xbf,0x37,0x0f,0xc5,0xd3,0x21,0x21,0xd2,0x15,0x72,0xb5,0x87,0xb4, -0x0f,0x5c,0x6f,0xf9,0xf7,0x83,0x0f,0xe1,0x45,0xf8,0x1a,0xe6,0xc1,0xd6,0x90,0x3b, -0x67,0xd5,0xcc,0x55,0x7d,0x0f,0x36,0x41,0x0e,0x7c,0x0c,0x3b,0x61,0x57,0xc8,0x9d, -0x03,0xfc,0x05,0xba,0x34,0xe4,0xea,0x32,0xe9,0xab,0x96,0xdf,0xab,0xf2,0x5f,0xab, -0x78,0x8d,0xce,0x97,0xbe,0xaa,0x39,0xb1,0xaf,0x6a,0x5e,0xec,0xab,0x3a,0xdf,0xab, -0x3a,0xa7,0xd1,0xf7,0xa5,0x1f,0x48,0x37,0x4a,0x3f,0x94,0x7e,0x24,0xdd,0x24,0xcd, -0x91,0x7e,0x22,0xdd,0x22,0xfd,0x54,0xba,0x4d,0xba,0x5d,0xba,0x43,0xfa,0xb9,0x74, -0xa7,0xd4,0x4b,0xfb,0x2e,0x2b,0x1d,0x0b,0x94,0xde,0xc5,0x3a,0xdf,0x62,0xc5,0xb3, -0x58,0xf9,0x31,0xe7,0x1e,0x18,0xe5,0x72,0xad,0x8f,0xeb,0x7d,0x8c,0xf4,0x71,0x8d, -0x8f,0x1b,0x7c,0x5c,0xed,0xe3,0x49,0x1f,0x4f,0xfb,0xb8,0xd1,0xc7,0x18,0x1f,0x37, -0xf9,0xb8,0xd9,0xc7,0x1d,0xe2,0x76,0x71,0xa7,0x18,0x27,0x1e,0x10,0x77,0x89,0x69, -0x3e,0x66,0xf8,0x98,0xe3,0x63,0x96,0x8f,0x97,0xc5,0x2b,0x3e,0xbc,0xb5,0x6b,0xec, -0x35,0x6c,0x6c,0x16,0xf9,0x58,0x67,0x61,0xaf,0x75,0xf3,0xbc,0x8f,0x15,0x62,0xb9, -0x58,0x29,0xbc,0xb5,0x73,0x56,0x8b,0x37,0xc4,0x9b,0x62,0xad,0x8f,0x66,0xc2,0x5e, -0x8b,0xe7,0x58,0xf6,0xf7,0xf3,0xb0,0x37,0xcd,0xc3,0xbe,0x22,0x0f,0xfb,0xf2,0x3c, -0xec,0x2b,0xf3,0xb0,0xaf,0x3d,0x01,0x7b,0xb3,0xff,0x60,0x7f,0xcb,0x87,0xb7,0xaf, -0x9a,0x65,0x8f,0xb3,0xec,0x59,0x79,0xc4,0x65,0xb4,0xb2,0x8e,0xab,0xac,0x63,0x8c, -0xc6,0x4b,0xb3,0xa4,0xcd,0xa4,0x26,0x7c,0x15,0x85,0xaf,0xa2,0xf0,0x55,0x14,0xbe, -0x8a,0xc2,0x57,0x51,0xf8,0x2a,0x0a,0x5f,0x55,0xe1,0xab,0x6a,0x7f,0x55,0xed,0xaf, -0xaa,0xfd,0xd5,0x14,0x4f,0x35,0xed,0x8f,0xb3,0xfc,0xb2,0x14,0x77,0x35,0x69,0x9c, -0xd4,0xf8,0x27,0xcb,0x3f,0x59,0xfe,0xc9,0xda,0x97,0xac,0xfd,0xa9,0xf2,0x4f,0x95, -0x3b,0x4d,0xe1,0xd3,0xe4,0x9f,0xa6,0xf0,0x69,0xda,0x5f,0x43,0xfe,0x35,0xe4,0xae, -0x29,0x4d,0xd7,0x71,0xe9,0x72,0xd7,0x92,0xbb,0x96,0xdc,0x0d,0xe4,0x6e,0xa0,0xe3, -0x1b,0x28,0xde,0x06,0xd6,0xfe,0x66,0x52,0x93,0xdf,0x4c,0x85,0xcb,0xd4,0xfe,0x4c, -0xed,0xcf,0xd4,0xfe,0x86,0xaa,0xa3,0x0d,0x15,0x6f,0x43,0x85,0x6f,0xa8,0x78,0x8d, -0x36,0x92,0x66,0x49,0x9b,0x49,0x9b,0x6b,0x5f,0x35,0x69,0x9c,0x34,0x5e,0x9a,0x25, -0x6d,0x26,0x6d,0x2e,0x3f,0xbb,0xec,0xb3,0xac,0x32,0xf6,0x68,0x66,0xd5,0xa1,0xc6, -0x0a,0xdf,0x58,0xe1,0x1b,0x2b,0x7c,0x63,0x85,0x69,0xac,0xf0,0x8d,0x15,0xbe,0x89, -0xc2,0x37,0xd1,0xfe,0x26,0xda,0xdf,0x44,0xfb,0x9b,0x5b,0xf5,0xd6,0xab,0xb3,0xf1, -0x56,0xda,0x9a,0x5b,0x75,0xd6,0x90,0x00,0xd9,0x90,0x28,0x6d,0x26,0x35,0xf3,0xa6, -0xce,0x43,0xdb,0xc8,0xde,0xd2,0xb2,0x9f,0x6f,0xd9,0x5b,0x59,0xf6,0xd6,0x96,0xbd, -0x8d,0xe2,0xf1,0xda,0x46,0xa2,0x65,0x4f,0xca,0xa3,0x2d,0x35,0x3e,0x4e,0xbb,0x4a, -0x94,0x26,0xf9,0xda,0x53,0xe3,0x3c,0xda,0x55,0xa2,0x34,0xc9,0xd7,0x9e,0x1a,0xe7, -0xd1,0xae,0x12,0xa5,0x49,0xbe,0xf6,0xd5,0xf8,0x18,0xed,0xec,0x58,0xf5,0x30,0xaf, -0x7a,0x77,0xbc,0xfa,0x95,0x57,0x3d,0xaa,0x64,0xd5,0x99,0xc6,0x4a,0x5f,0x63,0xa5, -0xcf,0xae,0x1f,0x8d,0x8f,0x51,0x4f,0x9a,0x59,0xe5,0xef,0x95,0x7d,0x92,0xaf,0x1e, -0x34,0x3e,0x46,0x7d,0x38,0x5e,0xdf,0x17,0x9f,0xc7,0xb5,0x6b,0x72,0x82,0x7d,0x5f, -0x93,0x13,0xec,0xf3,0x9a,0x58,0xd7,0xe0,0x64,0xfa,0xb4,0x93,0xed,0xcb,0xe2,0x7f, -0x43,0x9f,0xf6,0x47,0xf5,0x65,0xfe,0xbe,0xeb,0x44,0xfb,0xa8,0x13,0xe9,0x93,0x9a, -0x9c,0x40,0x5f,0x74,0x22,0x7d,0x4f,0x93,0x3c,0xfa,0x9c,0xec,0x13,0xec,0x6b,0x9a, -0x1c,0xa7,0xbe,0xf8,0xeb,0xc5,0xb1,0xae,0x7f,0x55,0xb9,0x93,0xad,0xeb,0x6b,0xdc, -0x29,0x72,0xa7,0xc8,0x7d,0xac,0x72,0xca,0x3a,0x46,0x7e,0xfc,0xe9,0xcb,0x88,0x3a, -0xd2,0xa7,0x19,0x7b,0x2b,0xcb,0xee,0xf5,0x69,0x35,0xd4,0x4e,0x6a,0xe8,0xb8,0x74, -0xb9,0xd3,0xe5,0xae,0x25,0x77,0x2d,0xb9,0x93,0xe5,0x4e,0x96,0x3b,0x45,0xee,0x14, -0xab,0xbc,0x9a,0x59,0xe5,0x56,0x4d,0xee,0x6a,0x56,0x39,0x36,0xb3,0xca,0x33,0x55, -0xee,0x54,0xb9,0xd3,0xe4,0x4e,0xb3,0xe2,0xaf,0x26,0x8d,0x93,0xc6,0xfb,0xca,0x28, -0x51,0xe9,0x49,0x54,0x3c,0x89,0x3a,0x3e,0xf1,0x5f,0x90,0xbf,0xe3,0x1d,0x6f,0xd7, -0xa9,0x26,0xd6,0x73,0x4b,0x5e,0x7d,0x49,0x5e,0xf1,0xf9,0x9f,0x77,0x4c,0x1f,0xde, -0xc2,0xd2,0x2a,0x56,0x9b,0xac,0x62,0xf5,0x65,0xc7,0xb2,0x67,0x59,0x7d,0x63,0x96, -0xd5,0x3e,0xaa,0x59,0xf6,0x38,0xcb,0x1e,0x7f,0x8c,0x3e,0xd2,0xb3,0xc7,0x59,0x75, -0x3e,0xce,0x7a,0x0e,0x49,0xb6,0xc2,0x26,0x5b,0xfd,0x6a,0xb2,0x75,0xcd,0x92,0xad, -0x78,0x8e,0x65,0xaf,0x66,0xd9,0xb3,0x7c,0xf6,0x54,0xeb,0xfc,0x7e,0x7b,0x96,0x75, -0xed,0xe2,0xf2,0xb0,0x57,0xb3,0xae,0x7f,0x96,0xef,0x9a,0xd9,0xf6,0x2c,0x9f,0x3d, -0xcd,0xaa,0x83,0x69,0x56,0x19,0xda,0xf6,0x1a,0x56,0x5e,0x8e,0x65,0xb7,0xc3,0x34, -0xb7,0xfa,0xfb,0x2c,0xab,0xcf,0xcf,0xcb,0xde,0xcc,0xba,0x0f,0x64,0x59,0xf6,0xe6, -0x96,0xbd,0x99,0x75,0x4f,0xc8,0xf2,0xd9,0x33,0xad,0xf4,0x64,0x5a,0xf1,0x34,0xb2, -0xca,0xa7,0x91,0xd5,0xbe,0x1a,0x59,0xf9,0xf5,0xee,0x0f,0xd5,0x8e,0x61,0x8f,0xb7, -0x8e,0x8d,0xf7,0xf5,0x93,0x71,0x3e,0xfb,0xb1,0xea,0x51,0x96,0x65,0x6f,0xee,0xbb, -0x3f,0xdb,0xf7,0x1b,0x7f,0x7d,0xb4,0xef,0x3b,0xde,0xbd,0xda,0xbe,0x47,0x35,0xf1, -0xdd,0x97,0xe2,0x7c,0xf6,0x66,0xd6,0xfd,0x2a,0x2b,0x0f,0x7b,0x33,0xab,0xaf,0x6f, -0x6e,0xd9,0x9b,0x59,0x69,0xcd,0xf2,0xd9,0x2b,0x5b,0x7d,0x50,0x15,0xab,0xbe,0x55, -0xb1,0xe2,0xac,0xe2,0x0b,0x13,0x6f,0xf9,0x67,0x59,0xfe,0x59,0x56,0x1f,0x97,0xe5, -0xfb,0x3d,0x66,0xfb,0x37,0xb3,0xfa,0x91,0x66,0x56,0xbb,0x68,0x6e,0xd5,0xff,0xe6, -0x56,0x1d,0xb6,0x7f,0x87,0xd8,0xcf,0x8c,0xcd,0x7d,0xf7,0x5e,0xfb,0x7e,0xdc,0xfc, -0x18,0x79,0x6d,0x6e,0xd5,0xa5,0xe6,0x56,0xd9,0x36,0xf7,0xd5,0x37,0xbb,0x8e,0xa5, -0x5b,0xe1,0x1b,0x1e,0xe3,0x77,0x8b,0xfd,0x5c,0x61,0xa7,0x33,0xcb,0x0a,0x9f,0xe5, -0xf3,0x6f,0xec,0x7b,0xa6,0x8b,0xb3,0xf2,0x51,0xcd,0x57,0xaf,0x9a,0x5b,0xcf,0x4b, -0xcd,0xad,0x67,0xcb,0xe6,0xbe,0xf8,0xed,0xb6,0x99,0xea,0xeb,0x8b,0xe2,0x7d,0x69, -0xf6,0xee,0x37,0x8d,0xf4,0xee,0x24,0xd3,0xb2,0x57,0x92,0xdd,0x7b,0x86,0xf2,0x9e, -0xe1,0xbd,0xdf,0x1f,0x76,0x3b,0xa8,0x6e,0xc5,0xe3,0x95,0x93,0x77,0x0f,0x6a,0x6a, -0xf9,0x37,0xb2,0x9e,0x35,0x9a,0x6a,0x7f,0x23,0x2b,0xad,0x8d,0xac,0x7a,0xe0,0xd9, -0x73,0xff,0x8e,0x8a,0x2f,0x2d,0xc6,0xcf,0x1f,0x9f,0xf1,0xf3,0xc7,0xe9,0xb5,0x75, -0xb3,0xcf,0xb3,0x57,0xb2,0xe2,0x49,0xd4,0x7b,0x0e,0xcf,0xaf,0x9a,0x99,0x33,0x9d, -0xe0,0x38,0xc1,0x04,0xf7,0x5b,0xbd,0xda,0xd6,0xba,0x0b,0xa7,0xe0,0x77,0x6a,0xc2, -0xb1,0xd7,0x79,0x28,0xc9,0x09,0x4a,0x40,0x67,0xc7,0xc5,0x5b,0x23,0xe1,0x5a,0xb8, -0xce,0xec,0xe7,0xb8,0x52,0x50,0x14,0x8a,0x41,0x7e,0x28,0x90,0x70,0xe4,0xdb,0xe4, -0x82,0x50,0x08,0x0a,0x43,0x11,0xf3,0x0d,0x91,0x99,0x03,0x6e,0xad,0x05,0x91,0x97, -0x7a,0xe7,0x33,0x78,0x69,0x8f,0x57,0xba,0x6b,0x59,0x6b,0x47,0x98,0xf4,0xe5,0x95, -0xa6,0x58,0x33,0x86,0x6b,0xe6,0xae,0x6b,0x9d,0x87,0x38,0xc7,0xfd,0x06,0xbc,0x9e, -0xbe,0x4b,0xbc,0xc4,0xac,0x0b,0x69,0xd6,0x86,0x85,0x0c,0xa5,0xa9,0x85,0x9e,0x09, -0x5b,0x58,0xbf,0x8f,0xbd,0xdf,0xc6,0xde,0xef,0x62,0xef,0x59,0xd2,0xfb,0x6d,0xec, -0x3d,0x4f,0x7a,0xbf,0x8f,0xbd,0x67,0x4a,0xef,0x37,0x72,0x86,0xf5,0x9b,0xf9,0x02, -0xb9,0x8d,0x96,0x8f,0x3a,0x7a,0x6d,0x6c,0x7b,0x8d,0x6c,0xff,0x5a,0xd9,0xfe,0x35, -0xb3,0xfd,0x6b,0x67,0xe7,0xa5,0x95,0x44,0x65,0x1f,0xe7,0x8a,0x2a,0x3e,0xaa,0xfa, -0xa8,0xe6,0x23,0xce,0x47,0xbc,0x8f,0xea,0x22,0x41,0x24,0x8a,0x24,0x91,0xec,0x23, -0xc5,0x47,0xaa,0x8f,0x34,0x1f,0x35,0x7c,0xd4,0xf4,0x91,0xee,0xa3,0x96,0x8f,0x06, -0x3e,0x32,0x7d,0x34,0xf4,0xd1,0xc8,0x47,0x96,0x8f,0xc6,0x3e,0x9a,0xf8,0x68,0x2a, -0x9a,0x1d,0xe3,0x37,0x78,0x73,0xab,0xdd,0xb6,0xcd,0xc3,0x7e,0x61,0x1e,0xf6,0x76, -0x79,0xd8,0x3d,0x35,0x6d,0xa3,0x82,0xe3,0xb6,0x01,0xaf,0x8e,0x9b,0xb6,0x50,0xc9, -0x6a,0xc3,0x5e,0xbb,0xa8,0xa6,0xb6,0x11,0xaf,0xb5,0x48,0x4e,0x74,0xed,0x14,0xaf, -0x1f,0xa9,0xa3,0xf6,0x54,0x4f,0xed,0x32,0xe3,0x4f,0xfc,0xee,0xb9,0x93,0xda,0xb1, -0xe9,0x53,0x2e,0x53,0x7f,0xd1,0xe5,0x4f,0xfc,0x1e,0xda,0xf4,0x39,0x23,0xd4,0xef, -0x5c,0x0f,0x63,0x29,0xd8,0x9b,0xce,0x75,0xfb,0x59,0xaf,0xef,0x33,0x7d,0xd7,0x8f, -0x9a,0x73,0x3e,0x45,0xf3,0x65,0x9f,0xd2,0xdc,0x58,0x33,0x27,0x7c,0x9b,0xe6,0x58, -0x7f,0xae,0x39,0x92,0x87,0x13,0xfe,0x7e,0xf3,0xea,0x0f,0x68,0xae,0xa7,0x99,0x23, -0xda,0xa5,0xd8,0x3f,0xeb,0xdb,0xc3,0xc7,0xc9,0xce,0x13,0xf0,0x9c,0xf5,0x77,0xd1, -0x9e,0x46,0x9f,0x32,0xf3,0xd7,0xf0,0x08,0x9e,0xe3,0xae,0x89,0x72,0x57,0x79,0x77, -0x4d,0x94,0x7b,0x60,0x32,0x7e,0xab,0x61,0x6d,0xd0,0x71,0xde,0x0d,0xba,0x7f,0xbf, -0x65,0x12,0xda,0x16,0x9e,0x30,0x6b,0xa3,0x4f,0xe7,0x78,0xf4,0x49,0x68,0x0f,0x1d, -0xcc,0xda,0xe5,0x67,0x51,0xb7,0xd1,0xcb,0x60,0x1a,0x5c,0x0e,0xdd,0xa0,0x0b,0x3c, -0x14,0x74,0xd7,0xff,0x79,0xd8,0xac,0xf1,0x0e,0x37,0xc2,0xb3,0x66,0x3d,0x74,0xf3, -0x37,0x43,0x20,0x72,0x73,0xc0,0xb9,0xf3,0x19,0xf2,0x82,0x3d,0x64,0xec,0x68,0x14, -0x6a,0xfe,0x4e,0xcc,0x50,0xf3,0x37,0x49,0x82,0x6e,0x9d,0xbe,0x06,0xcd,0x87,0xff, -0x75,0xe8,0xf5,0x30,0x12,0xa6,0xc2,0xd3,0x26,0x5e,0xd2,0xf4,0x0c,0x3a,0xce,0x84, -0xa5,0x53,0x18,0x8f,0x4e,0x81,0xc7,0xe1,0x01,0x58,0xc2,0xf9,0x97,0xc2,0x32,0xc8, -0x4f,0x1c,0x65,0x60,0x52,0xd1,0x80,0xf3,0x32,0x3c,0x24,0x7d,0x4a,0x9a,0x58,0x2c, -0xe0,0x54,0x82,0x24,0x69,0x93,0x12,0x01,0xa7,0x5e,0x09,0x57,0x3b,0xc0,0x82,0x92, -0x84,0x2b,0xe9,0xea,0x4c,0xe9,0x42,0x98,0x5f,0x2a,0xe0,0xcc,0x80,0x05,0xd2,0xd4, -0xd3,0x03,0x4e,0x02,0x74,0x78,0x37,0xe0,0xf4,0x80,0x8b,0x7c,0xda,0xdf,0xb2,0x0f, -0xb0,0xec,0xd9,0x96,0x7d,0xa0,0x65,0x1f,0x04,0x0b,0x64,0x7f,0x59,0xba,0xc0,0x8a, -0xeb,0x65,0xcb,0xbe,0xc0,0x8a,0xf7,0x65,0xcb,0xfe,0x4f,0x5b,0xd3,0xe1,0xaf,0x90, -0x9f,0x7f,0x52,0x5e,0xfe,0xe8,0x6b,0xe3,0xe5,0xa5,0x89,0x95,0x76,0x7f,0x9a,0x4f, -0x36,0xbd,0x3d,0x8f,0x93,0xce,0x7f,0x7b,0x99,0x67,0x1e,0x23,0x2f,0xc7,0xcb,0xc3, -0x7f,0x4a,0xff,0xff,0x3a,0xed,0xc7,0xba,0x06,0xad,0xfe,0x62,0x69,0x0e,0xf7,0xa7, -0xe1,0xfc,0x84,0xf3,0x13,0xce,0xcf,0x3f,0x2d,0x3f,0x89,0x3c,0x2f,0xd7,0x08,0xba, -0xeb,0xf0,0xde,0xad,0xb5,0x31,0xef,0xd5,0x7a,0xb9,0xf7,0x69,0x7d,0xdc,0x07,0xb4, -0x66,0xed,0x83,0xf0,0x10,0x3c,0x0c,0x8f,0xc0,0xa3,0x5a,0xe7,0x75,0xb2,0xd6,0x91, -0x7d,0x40,0x7f,0xfb,0xee,0x49,0xad,0x2f,0xfb,0x34,0x3c,0x63,0xd6,0x18,0xd4,0xba, -0xaf,0xd1,0x15,0xdc,0xb5,0x81,0xed,0xbf,0xe5,0x64,0xd6,0xe2,0x7e,0x49,0x6b,0xf6, -0xce,0xd7,0xfa,0xb9,0xe6,0x6f,0xea,0xbd,0xa2,0xbf,0xe7,0xbc,0x10,0x16,0x69,0x0d, -0xee,0x25,0xd6,0xdf,0xda,0x7b,0x0d,0x5e,0xd7,0x5a,0xb7,0xde,0xdf,0x7a,0x5a,0xa9, -0xb5,0x68,0x83,0x15,0xdc,0x78,0xe7,0x2b,0xae,0xe5,0x3a,0x6e,0x49,0x44,0x38,0x9f, -0xe1,0x7c,0x86,0xf3,0xf9,0x57,0xce,0x67,0x0e,0x7c,0x1c,0x71,0xe2,0xef,0xf9,0xfe, -0xf2,0xe1,0x22,0x09,0x07,0x49,0x91,0xee,0xdf,0xee,0x4c,0x89,0x74,0xff,0xa6,0xa6, -0xf9,0xbb,0x99,0xe6,0x6f,0x65,0x9a,0xbf,0x87,0x69,0xfe,0x86,0x67,0x6d,0xa8,0x13, -0xe9,0xfe,0x3d,0xcc,0xfa,0x90,0x01,0x0d,0x20,0x33,0xd2,0xfd,0x9b,0x96,0x8d,0x20, -0x0b,0x1a,0x47,0xba,0x7f,0xd3,0xb2,0x69,0xa4,0xfb,0xb7,0x2c,0xcd,0xdf,0xc7,0x3c, -0x1f,0x6e,0x79,0xda,0xfd,0xdb,0x9c,0xe6,0xef,0x82,0x5e,0x14,0xe9,0xfe,0x1d,0xcd, -0x19,0xf0,0x4e,0xe4,0xc9,0xa5,0xc1,0x3b,0x7f,0x83,0xff,0x70,0xde,0xe6,0x3a,0xf7, -0x5d,0x3a,0x5f,0x3b,0xe8,0x0c,0xd3,0xa1,0x0d,0xe9,0x98,0x15,0x79,0xe4,0xbd,0x7e, -0x35,0xbd,0x73,0x6f,0xaa,0x77,0xec,0x71,0xd6,0x1c,0x8f,0x86,0xbe,0x39,0x32,0xc9, -0x7a,0x2f,0xde,0x40,0xef,0xd7,0x33,0xad,0xb9,0x13,0xde,0xfb,0xff,0x78,0xbd,0xbb, -0x4f,0xd3,0x3b,0x75,0xf3,0xde,0xbc,0xbf,0xe6,0x35,0x4f,0x81,0x01,0xd6,0x79,0x9b, -0xf8,0xc6,0xea,0x8e,0x77,0x2e,0xff,0x79,0xd2,0xac,0x39,0x55,0xf6,0x38,0xa8,0x7d, -0xbc,0x7d,0xac,0x7d,0xcc,0xcb,0x79,0xa4,0xa5,0x86,0x6f,0xec,0xf0,0x64,0xd2,0x62, -0xe7,0x77,0x4a,0xd4,0xff,0x2f,0xe3,0x26,0x79,0x94,0xf3,0x1f,0x51,0xc6,0xc7,0xbb, -0x96,0x7f,0xc4,0x39,0xbc,0xf5,0x5c,0x13,0xf4,0xde,0x3f,0x51,0x9a,0x24,0x4d,0x96, -0xa6,0x48,0x53,0xa5,0x69,0xd2,0x1a,0xd2,0x9a,0xd2,0x74,0x69,0x65,0x3d,0xb7,0x79, -0xeb,0x2a,0x65,0x5a,0xf6,0x86,0x96,0xbd,0x91,0x65,0xcf,0xb2,0xec,0x8d,0x2d,0x7b, -0x13,0xcb,0xde,0xd4,0xb2,0x37,0xb3,0xec,0xcd,0x2d,0x7b,0x0b,0xcb,0x7e,0x9e,0x65, -0x6f,0x69,0xd9,0xcf,0xb7,0xec,0xad,0x2c,0x7b,0x6b,0xcb,0xde,0xc6,0xb2,0x5f,0x60, -0xd9,0xdb,0x5a,0xf6,0x0b,0x2d,0x7b,0x3b,0xcb,0xde,0xde,0xb2,0x77,0xb0,0xec,0x17, -0x59,0xf6,0x8e,0x96,0xfd,0x62,0xd9,0xcd,0x58,0xa5,0x89,0xdf,0x8c,0x57,0x36,0xd4, -0x79,0xbd,0xe7,0xde,0x0e,0x0a,0xf7,0x67,0x3d,0x0f,0x37,0xf5,0x7d,0xd7,0xdd,0x56, -0xe7,0x6b,0x2b,0xbc,0xef,0x98,0xbd,0x63,0x1b,0x2a,0xac,0xa7,0xde,0x1a,0xe5,0x17, -0xc8,0x6e,0xd2,0x64,0xd6,0x6c,0x6c,0xa1,0xb1,0x0a,0x6f,0xbc,0xc2,0xac,0x7b,0xda, -0xa1,0x93,0xe3,0xbc,0xd5,0xf6,0xc8,0x9a,0x28,0x66,0x4d,0xa8,0x33,0x48,0xc8,0xb6, -0x5b,0xdc,0x35,0xf1,0x9e,0xc4,0x5d,0x8e,0x87,0xf1,0xf2,0x03,0xdd,0x6f,0x0e,0x5b, -0x12,0xe9,0xed,0x9d,0x1d,0xe7,0x0e,0x32,0x33,0x13,0xf7,0x59,0xe6,0x1b,0xcc,0xeb, -0xdc,0x35,0x4b,0xa7,0xdd,0xee,0x38,0xfb,0xc8,0x48,0x3a,0x99,0x2b,0xc9,0xc3,0xf9, -0x44,0xe2,0x6f,0xd7,0xdd,0x2d,0x04,0xb3,0xce,0x54,0xf3,0x09,0xee,0xda,0x4e,0x66, -0x9d,0x27,0xb3,0xbe,0x53,0x74,0x77,0x77,0x2d,0xd0,0xb6,0x84,0x1b,0xc5,0x43,0xfa, -0x35,0x3c,0xa4,0xe7,0xe3,0xd8,0x91,0xfd,0xdd,0x75,0xa5,0x72,0xd7,0x56,0x22,0xde, -0x41,0x9c,0xe3,0x25,0x0a,0xab,0xe5,0x5d,0xee,0x75,0xaa,0xd6,0xcb,0xbd,0x4e,0xc6, -0x6e,0xe2,0xf5,0xec,0xb7,0x5b,0xf6,0x5b,0x3a,0x1d,0xb1,0x9b,0x75,0x1e,0x3c,0xbb, -0x39,0x97,0x67,0xdf,0x30,0xf4,0x88,0xfd,0xe3,0x0b,0x8e,0xd8,0x3b,0xf4,0x70,0xed, -0xf7,0x93,0xcf,0xbd,0x6d,0x4f,0xfc,0xfe,0x57,0x97,0xf3,0xd7,0x34,0xeb,0x66,0x41, -0x85,0x40,0xd0,0xe9,0xd2,0xca,0xfd,0x1e,0xf0,0x15,0x08,0x72,0xc1,0xae,0x81,0x49, -0xad,0xdd,0xef,0x03,0xdf,0x81,0x47,0x53,0x4c,0x5f,0x10,0xcc,0xfd,0x56,0xf0,0x42, -0xb8,0x1c,0x86,0x99,0x6f,0x6f,0x43,0x41,0x67,0x01,0xfb,0x7a,0xb5,0x71,0xcb,0xb9, -0x05,0xee,0xfb,0xd1,0x27,0xcd,0xb7,0xb9,0xc4,0xfd,0x5c,0x1b,0xf7,0x5b,0xbb,0xcd, -0x77,0x05,0x73,0xd7,0xdd,0x8d,0x20,0xed,0x9b,0x09,0x5f,0x1b,0x6d,0x7c,0x81,0x5b, -0x5e,0xc3,0x4c,0x7e,0x52,0xdd,0xef,0xef,0xbc,0xef,0x10,0xcd,0x77,0x78,0x21,0xf2, -0x13,0xd5,0xd6,0xfd,0x56,0xb7,0x59,0x5b,0xf7,0xdb,0xc4,0x8b,0x61,0x30,0x5c,0x07, -0x37,0x58,0x54,0xcb,0x1f,0x74,0xb2,0x29,0xbb,0x55,0xd8,0x37,0x43,0xf7,0x02,0x41, -0x67,0x37,0xba,0xdf,0xc4,0xc1,0x75,0x7a,0x14,0x6a,0x42,0x53,0xb8,0xc2,0xac,0xdf, -0x04,0xdf,0x41,0x51,0xae,0x55,0x5b,0xe8,0x0e,0x37,0x0a,0xf3,0xdd,0xdf,0x74,0x98, -0x03,0xcb,0xe0,0x94,0x0e,0xee,0xf7,0x90,0xa7,0xa2,0x6d,0xd0,0x21,0xed,0xdd,0x6f, -0x39,0xbf,0xa2,0xfe,0xbc,0x8d,0xdf,0x37,0x50,0x08,0xfb,0x6d,0x68,0x12,0x9a,0x08, -0xcf,0xc1,0xf6,0x92,0x41,0xe7,0x6b,0xf4,0x7b,0x88,0xea,0xe8,0xd6,0xd5,0x0a,0xe6, -0xfb,0x41,0x98,0x7a,0x4a,0xd0,0xd9,0x05,0x5f,0x62,0x2f,0x4d,0x43,0xaa,0x04,0x1b, -0xb1,0xf7,0x44,0xbf,0xe2,0x62,0x1d,0x86,0x7c,0xd4,0x8b,0x7a,0x62,0xe5,0xe9,0x41, -0xe7,0x35,0x74,0x63,0x27,0xf7,0xfb,0xdc,0x03,0x70,0x5a,0xe9,0xa0,0xf3,0x0b,0x1a, -0x75,0x09,0x79,0xe8,0xec,0xae,0x37,0x3c,0x8a,0x8b,0xdc,0x45,0xdf,0x6a,0x2e,0x81, -0x3b,0x60,0xfb,0x59,0x41,0xa7,0x21,0x75,0x79,0x07,0xda,0x1f,0xed,0x03,0x23,0xe0, -0x53,0xd8,0x0a,0xd5,0xa9,0x14,0x3f,0xa1,0x95,0x2f,0xa3,0x5e,0x98,0xef,0x19,0xa1, -0x1b,0x7e,0x63,0xca,0x07,0x9d,0x11,0xe8,0x4c,0xdc,0x73,0xe0,0xa5,0xcb,0xdc,0x6f, -0xc4,0xef,0x7e,0x22,0x98,0xbb,0x56,0x71,0x62,0x6c,0x30,0x97,0xc0,0x68,0xce,0xdd, -0xd9,0x65,0x05,0xe1,0xe7,0x27,0x05,0x9d,0x8f,0xba,0x06,0x9d,0x6e,0xb8,0xfb,0xc0, -0x36,0xfc,0x1e,0x44,0xd7,0xc0,0x06,0x38,0x08,0xa3,0xba,0x50,0x9f,0xa8,0x88,0x67, -0xa6,0xbb,0xdf,0x94,0xbe,0x57,0x31,0xe8,0xac,0x40,0x9b,0xf2,0x03,0xfb,0xbc,0xae, -0xee,0x77,0x94,0x46,0xaf,0xd1,0xb7,0x94,0xb3,0xe1,0x49,0x98,0x01,0x9f,0xe8,0xbb, -0x4a,0xf3,0x6d,0xbc,0x59,0xaf,0xa4,0x34,0x5c,0x0a,0xb3,0xe0,0x3d,0x68,0x4d,0x5b, -0x2d,0x58,0x35,0xe8,0xd4,0x45,0x0f,0xe3,0xbe,0x02,0x1d,0x03,0xdb,0x61,0x3f,0xfe, -0x15,0xf8,0xe1,0xfe,0x06,0xf6,0x69,0x10,0x5f,0x8b,0xfc,0xe2,0xbe,0x1e,0x1e,0x81, -0x61,0xd0,0xb7,0x96,0xfb,0x5d,0x6b,0xdf,0x1e,0x66,0x6e,0x4a,0xd0,0xd9,0x86,0xfe, -0x40,0xbf,0xd2,0x0c,0x4e,0xaf,0xed,0x7e,0xeb,0x9a,0x0f,0xdd,0x4e,0xb8,0xbb,0xa9, -0xd3,0x13,0xdb,0xb8,0x2f,0x00,0x1e,0xc6,0xff,0xf9,0x91,0x3c,0xef,0x35,0x3c,0xf2, -0x6d,0x67,0x79,0xb8,0x0c,0xda,0xc2,0x6b,0xc9,0x41,0xa7,0x19,0xc7,0x1d,0xc2,0x3e, -0x16,0x2e,0xb8,0xc2,0xfd,0x66,0xb6,0x5f,0x4a,0xd0,0xb9,0x13,0x2d,0x0b,0x25,0x7b, -0x3b,0xb9,0xdf,0x45,0x66,0xa2,0x4f,0xc0,0x2e,0x98,0x7a,0x25,0xf6,0xb4,0xa0,0xb3, -0x09,0x3d,0xad,0x0e,0x71,0xf6,0xe1,0xf7,0x41,0xcd,0xa0,0x73,0x21,0x7a,0x3e,0xee, -0x41,0x66,0x5d,0x6c,0x7d,0x3f,0xfa,0x0a,0xdc,0x51,0x2b,0xe8,0x14,0xe0,0x5a,0x1f, -0x42,0xcf,0xef,0xcb,0xef,0x81,0x3a,0x41,0x67,0x31,0xba,0x06,0x7a,0xc1,0x29,0xfd, -0xa8,0x53,0xfd,0xdc,0x6f,0x75,0xcd,0xf7,0xa6,0xbd,0x61,0x38,0x8c,0x85,0x32,0x75, -0x83,0x4e,0x0a,0x5a,0x9d,0x7e,0xad,0x3f,0x24,0xd7,0x75,0xbf,0x45,0x5d,0x01,0xef, -0xd6,0x0b,0x3a,0x07,0xd9,0xd7,0x9f,0xfe,0xf2,0xb2,0xfa,0xa4,0x19,0x96,0x63,0x4f, -0xcf,0x76,0xbf,0x53,0x2d,0x0d,0xf7,0x11,0xbe,0x39,0x7a,0x1d,0x0c,0x83,0xe7,0xe1, -0x1c,0xfa,0x84,0x2c,0xfa,0xe4,0xee,0x99,0x41,0xe7,0x61,0x74,0x7a,0xc3,0xa0,0x53, -0x79,0x90,0xfb,0x3d,0x6b,0x6b,0xc8,0xd7,0x38,0xe8,0x8c,0x44,0x27,0x1a,0xbf,0x26, -0x41,0xa7,0x64,0xd3,0xa0,0x73,0xcd,0x60,0xda,0x13,0x3c,0x57,0x8f,0xdf,0x44,0xe8, -0xfc,0x7a,0x2e,0x4d,0x86,0x38,0xce,0x25,0x43,0xdc,0xef,0x5f,0xc7,0x9a,0xef,0xdf, -0xa1,0x74,0x7d,0xc7,0x39,0x9b,0xbe,0x37,0xed,0xbc,0xa0,0x53,0xcf,0xac,0x41,0x8d, -0x9a,0x6f,0xfc,0x1f,0xa3,0xfe,0x16,0xa5,0xdf,0x9c,0xd2,0x2a,0xe8,0xcc,0x87,0x46, -0xad,0x83,0xce,0x61,0xc2,0xe6,0xcb,0x70,0xbf,0x91,0x3d,0x80,0xfb,0x6b,0x38,0xbd, -0x4d,0xd0,0x49,0x86,0x32,0xc3,0xb8,0x06,0xc2,0x7c,0x3f,0x6b,0xbe,0x4b,0xbd,0x0d, -0x6d,0x8c,0xde,0x97,0x61,0xbe,0x05,0xa7,0x3c,0x87,0xbb,0x6b,0x1b,0x98,0xef,0x6a, -0xb7,0xe1,0x57,0xb1,0x7d,0x30,0xf7,0x3b,0xe6,0x07,0xd1,0x37,0xc0,0x7c,0x8b,0xbd, -0x1b,0xaa,0x37,0x70,0xbf,0x67,0x6e,0x0e,0xad,0x60,0x44,0xc7,0xa0,0xf3,0xcc,0xc5, -0x2e,0x5f,0xe1,0x0e,0x72,0x73,0x9e,0xde,0x89,0xf2,0xbb,0x96,0x3e,0x0f,0x2a,0xe1, -0x1e,0x79,0x49,0xd0,0x59,0x37,0x82,0xdf,0x85,0xd8,0x77,0xa2,0xdb,0x34,0x49,0xe0, -0xa6,0xce,0x41,0xa7,0x3b,0x1a,0xa0,0x5e,0xad,0x40,0x83,0xd7,0x73,0x3f,0x87,0x14, -0xdc,0x95,0xbb,0x05,0x9d,0x26,0xd0,0x11,0xfb,0x87,0xe8,0x35,0x37,0x70,0x6d,0xbb, -0x07,0x9d,0x89,0xe8,0x21,0x7d,0xe3,0xfb,0xd1,0xe5,0x41,0x27,0xb6,0x07,0x7d,0x3c, -0xf6,0xa9,0x68,0x36,0xda,0x99,0xba,0xf8,0x3e,0xc7,0xcc,0xc6,0x1e,0x31,0xca,0x71, -0x0a,0x70,0xf3,0xad,0x87,0xce,0xa5,0xff,0x79,0xa6,0x57,0xd0,0x99,0x0b,0xf7,0x10, -0xe6,0xe1,0x64,0xb7,0x7d,0x47,0xc2,0xa3,0xe3,0x69,0xcf,0x84,0xbb,0x0b,0xfb,0x6d, -0xf0,0x08,0xcc,0xa1,0x1f,0x9c,0x65,0x14,0x16,0xc2,0x0e,0xa8,0xd3,0x27,0x98,0xbb, -0x36,0xc2,0x59,0x63,0xb8,0xe6,0xf0,0x3c,0xc4,0xc2,0x42,0xf8,0x7c,0x8c,0xfb,0xed, -0x76,0x5b,0x74,0x15,0xbc,0x05,0x39,0x90,0xd6,0x37,0xe8,0xf4,0xe9,0x47,0x9a,0xd0, -0xaa,0x3c,0xac,0xec,0x27,0xcc,0x01,0x38,0x65,0x2c,0xe1,0x06,0x07,0x9d,0xcb,0xd1, -0x6a,0x03,0x82,0xce,0xa5,0xec,0xeb,0x0a,0xb3,0xb0,0xaf,0xcb,0xe6,0x18,0xec,0xad, -0xb5,0x06,0x45,0x2f,0xe8,0x0d,0xd3,0x60,0x1c,0x14,0xbe,0x99,0xfe,0xed,0x26,0xf7, -0xdb,0xe6,0xca,0xd0,0x07,0x6e,0x82,0x0d,0x1c,0xf3,0x29,0x1a,0x18,0x47,0x5f,0x84, -0xbd,0x8b,0xd6,0x04,0xef,0x35,0x34,0xe8,0x6c,0x40,0x3f,0x81,0x54,0x1e,0x96,0x0e, -0xa1,0xaf,0x70,0xaf,0x7a,0x61,0x78,0xd0,0xe9,0x79,0x75,0xd0,0x59,0x84,0xdf,0x0a, -0x98,0xac,0x6f,0xa1,0xcd,0x77,0xd0,0x66,0xbd,0xf0,0xa9,0x23,0x82,0xce,0x74,0x74, -0x29,0x94,0xe6,0x19,0x61,0x18,0x54,0xbf,0x21,0xe8,0x44,0xe6,0x0b,0x3a,0xab,0xb1, -0xbf,0x0a,0xfb,0xe0,0x13,0xdc,0xef,0xdd,0xe9,0x7e,0x37,0xbd,0x6e,0x6c,0xd0,0xd9, -0x03,0xf7,0xf2,0x9c,0xb1,0x1f,0x8a,0xf1,0xbc,0x10,0x7f,0x73,0xd0,0x29,0x8d,0xd6, -0xbc,0x9b,0x34,0xc2,0x46,0xf3,0x4d,0x35,0x1c,0xbc,0x87,0xfb,0xe3,0xbd,0xa4,0xe7, -0xb6,0xa0,0x73,0xdb,0x44,0xda,0x09,0x0f,0x6f,0xf3,0x26,0x9a,0xf3,0x04,0x9d,0x1d, -0xd8,0x5f,0xbb,0x8f,0xeb,0x48,0xff,0x1d,0x7b,0x3f,0xf5,0x82,0xfb,0xec,0x19,0x77, -0xd3,0xcf,0xf3,0x20,0x35,0x14,0xb6,0xe0,0x97,0xff,0xde,0xa0,0x33,0x1b,0xfb,0x7d, -0xa8,0xf9,0x1e,0xdb,0x70,0x2e,0xbc,0x34,0x31,0xe8,0x6c,0x45,0x93,0x79,0x08,0x3c, -0x77,0x12,0xd7,0x1d,0x96,0xc1,0xcf,0xf0,0x36,0x7e,0x09,0x0f,0x05,0x73,0xbf,0xdb, -0xce,0x78,0x98,0xfb,0x03,0xbc,0xcd,0x83,0xe2,0x1e,0xe8,0xf5,0x08,0xf6,0xc9,0x41, -0xe7,0x07,0xec,0xa1,0x29,0x41,0xa7,0xf0,0xe3,0x41,0xe7,0x2e,0x30,0x6b,0x8f,0xb7, -0x6f,0xe9,0xae,0x39,0xfe,0x33,0x84,0x1e,0x73,0x9c,0x22,0x70,0x8a,0xd6,0x1c,0xcf, -0x9d,0x30,0x40,0xb1,0x07,0x23,0x22,0x43,0x51,0xd1,0xf9,0x62,0xf2,0x17,0x28,0x58, -0xa8,0x30,0x41,0x72,0x97,0xda,0x2d,0x5e,0xa2,0x64,0xa9,0x53,0xe8,0x37,0x9d,0x23, -0xdb,0x69,0xa7,0x73,0xcf,0x74,0xfe,0x17,0x5b,0x69,0xe7,0xcc,0xb3,0xca,0x94,0xfd, -0x83,0x23,0x75,0xff,0xaa,0x55,0x85,0xd8,0xb3,0x5d,0xe7,0x39,0x74,0x1e,0x95,0x2a, -0x9f,0x5b,0xa5,0x6a,0xb5,0xb8,0xf8,0xea,0x09,0x89,0x49,0xc9,0x4e,0x4a,0x6a,0xee, -0x63,0xda,0x1f,0xb4,0xd5,0xf0,0x1e,0xf5,0xfe,0xb0,0xad,0xd6,0xb1,0x3c,0x6b,0xd7, -0x39,0xca,0x59,0xb7,0x66,0x3d,0x77,0x3e,0x57,0x03,0x27,0xbc,0x85,0xb7,0xf0,0x16, -0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b, -0x78,0x0b,0x6f,0xff,0xd2,0x6d,0xc7,0xb1,0xb6,0x9d,0x39,0x6c,0x3b,0x37,0x9a,0xff, -0x73,0x56,0xad,0x3a,0xf2,0xbf,0xb6,0x80,0xd9,0x8c,0xc5,0x0b,0xbf,0x6f,0x87,0xeb, -0xc8,0xc9,0x71,0x72,0xff,0xc7,0x41,0x14,0x3b,0xbe,0xd8,0xb5,0xcb,0xfc,0x3b,0x2a, -0xea,0x70,0x89,0x1f,0xfb,0x12,0x84,0x8b,0x41,0x5b,0x6e,0xa5,0x32,0xff,0x7d,0xa2, -0xea,0xe5,0xd6,0xb9,0x5c,0xbf,0x4f,0xb6,0xef,0xc8,0x7d,0x47,0x59,0xc4,0xbc,0x9e, -0xcc,0x7d,0x3f,0x79,0xaa,0x79,0x29,0xb9,0x23,0xc7,0x29,0xfe,0x47,0xb7,0x87,0x32, -0x65,0xcb,0x9d,0xec,0xa1,0xa5,0xcd,0x3b,0xca,0x72,0xe5,0x2b,0x98,0x24,0xef,0x50, -0x2e,0x72,0xfc,0x81,0x62,0xff,0xcc,0x56,0xed,0x5a,0x72,0x72,0xd5,0x39,0x56,0x6a, -0x8e,0xb1,0x9d,0x7d,0x9c,0x98,0xdd,0x2b,0x61,0xae,0x88,0xf9,0x97,0x1b,0xbd,0x6b, -0x76,0xfc,0x4d,0xba,0xba,0x9c,0x23,0x09,0xcd,0xf9,0x4f,0x41,0x8f,0x74,0x8d,0xce, -0xaf,0xae,0x93,0xa9,0xc7,0x39,0x39,0xbf,0x2b,0xb1,0xea,0x5e,0x4f,0x32,0x7b,0x39, -0x76,0xb7,0xac,0xd4,0xeb,0x8a,0xb9,0x7b,0xa9,0xa4,0xaa,0x99,0x39,0xbf,0xbb,0xdf, -0x89,0xf6,0x7b,0xc4,0xa8,0x82,0xfc,0x49,0x17,0xf4,0x98,0xe7,0x3f,0xb9,0x52,0xfe, -0x1f,0x9f,0xdf,0x09,0x9f,0xff,0x8f,0xdc,0xfe,0x2a,0xf9,0xbf,0xb0,0xd3,0xbf,0xa1, -0xfc,0x63,0x62,0xfe,0x52,0xd7,0xff,0xcf,0x3d,0x79,0xaf,0x5e,0x47,0x9f,0xaf,0x0f, -0xdb,0x9f,0x79,0xfe,0xa1,0x43,0x8f,0x3e,0xff,0x35,0xd7,0x98,0x19,0x70,0x7f,0xe0, -0x63,0xd8,0x7f,0xba,0x7b,0xe5,0x60,0x36,0xfe,0xc6,0x88,0x47,0x8d,0x76,0x6e,0xcc, -0xb5,0x8c,0x66,0xe3,0x7f,0xee,0x5b,0x31,0xce,0xef,0xbd,0x65,0xe4,0xfc,0xd9,0x95, -0x2d,0xfa,0x18,0xb5,0xff,0x0f,0x28,0xf4,0x7f,0xde,0x2f,0x9b,0xbf,0x63,0xb2,0x8f, -0x77,0x69,0x63,0xfe,0xda,0xa9,0xff,0xa3,0x1e,0x6f,0xfe,0x5a,0xdb,0xf6,0xbf,0x58, -0x7a,0x3e,0xd9,0xf1,0x4f,0x6b,0xad,0x47,0xff,0xfc,0xf8,0x6f,0xde,0x95,0x8f,0xbc, -0x0c,0x3a,0xe9,0xd3,0x1c,0xfd,0x4a,0xc0,0xc9,0xc9,0xb1,0x7f,0x6d,0xff,0x49,0xdd, -0x4d,0xf4,0x6f,0xeb,0x0f,0x76,0xe4,0xfc,0xae,0x77,0x60,0xbf,0xe7,0x86,0x13,0xfd, -0x07,0xc5,0x93,0xf7,0xa3,0xe7,0x5f,0xe9,0x96,0x13,0xf0,0xaa,0x87,0xf9,0xdf,0x09, -0xb8,0x9b,0x75,0x7f,0xdd,0x91,0x1b,0xee,0x9f,0x72,0x8b,0xcd,0xf9,0xf5,0xbd,0xc6, -0x8e,0x5d,0x1f,0xe4,0xac,0xda,0x71,0x22,0xdb,0xce,0xed,0xdb,0x73,0x3e,0xda,0xf1, -0x45,0xce,0x3f,0xaf,0x0f,0xdb,0xb1,0x23,0x10,0x30,0x39,0x0c,0x18,0xf1,0x2e,0x36, -0xf6,0x9c,0x1d,0x7a,0x65,0xed,0xfc,0xab,0xb7,0xbf,0xda,0x13,0x59,0xcc,0x9f,0x90, -0xe1,0xff,0xb8,0x9d,0x78,0x4c,0x1f,0x6d,0xdf,0xf9,0xc9,0x96,0x2d,0x7f,0x5a,0xc9, -0xe4,0xcb,0xf7,0x8f,0xac,0x7f,0x47,0x5f,0x93,0xe3,0x5f,0xbd,0x3f,0xbe,0x3e,0xfc, -0xf6,0x6a,0xf8,0x57,0x7d,0xee,0x8f,0x39,0xa9,0xfa,0xff,0x3b,0x5e,0x09,0xe4,0xfc, -0x25,0x8a,0x29,0xfa,0xef,0xf3,0x5b,0xec,0xbf,0xd1,0x80,0x72,0x87,0x71,0x74,0x19, -0xcd,0xb8,0xc4,0x5f,0xb2,0xdb,0xfd,0xfb,0x35,0x94,0x63,0x6e,0x67,0x38,0xff,0xf6, -0x6d,0x87,0x3d,0x08,0x9b,0x13,0x1e,0xa7,0xfe,0x47,0x6d,0x39,0xe1,0x2c,0xfe,0x0f, -0x5b,0xd5,0x5f,0xb1,0xb0,0x4e,0x38,0x51,0x3b,0x02,0x39,0x7f,0x9f,0x1b,0xc9,0xef, -0xfc,0x99,0x1b,0x9e,0x9f,0xf3,0x17,0x69,0x34,0x7f,0x78,0x7d,0xcf,0xc9,0xf9,0xa3, -0x22,0x72,0x27,0xc2,0xfc,0x96,0x08,0x77,0xfc,0x03,0xde,0xc2,0xc4,0xfc,0xd6,0x90, -0xbf,0xbd,0xff,0x88,0x89,0xfe,0x83,0x2a,0xd5,0x49,0xd7,0xaa,0xdf,0xfb,0x02,0x35, -0xfa,0xbf,0x53,0xf2,0x7f,0xe2,0x2b,0xd9,0x98,0xe8,0xbf,0x5f,0x15,0x8d,0xfe,0xc3, -0x6f,0x55,0xd1,0x27,0x3e,0xff,0xe2,0xc8,0x4f,0xef,0x7f,0xde,0x64,0xcf,0x98,0xff, -0x50,0xf7,0x76,0x84,0x2b,0xe3,0x3f,0x3b,0xf3,0x31,0xff,0xa2,0x6c,0xc7,0x38,0xe1, -0x2d,0xdc,0xec,0xfe,0xff,0x93,0xc0,0x5f,0xba,0x20,0x62,0xfe,0x9c,0x38,0x63,0xfe, -0xa5,0xad,0x2d,0xdc,0x27,0xfc,0x77,0xa6,0xc2,0xc5,0xfc,0xcd,0xfa,0x80,0xf0,0xf6, -0x37,0xd9,0x7e,0x9d,0x0b,0xf2,0xdb,0x7f,0x2f,0x86,0x5f,0x07,0xfd,0x8d,0xb7,0xa8, -0xa8,0xbf,0x55,0x6d,0xfd,0x67,0x14,0xfa,0xc6,0x8d,0x6e,0xa3,0xdb,0xba,0xd1,0x6c, -0x9e,0xaf,0xf7,0x39,0xe9,0xaf,0x93,0xfa,0x8e,0xdf,0xf2,0xfe,0x8a,0x99,0xfb,0x7b, -0xf7,0x06,0xd6,0x27,0x6e,0xfe,0x69,0x02,0x47,0x76,0xfd,0x79,0x6f,0x2d,0xc2,0x1d, -0xeb,0x7f,0xb1,0x78,0xfe,0xed,0x37,0xae,0x9d,0x3b,0xff,0xf9,0xd3,0xff,0x7e,0xed, -0x53,0xff,0xf4,0x3e,0x24,0xfc,0x3e,0xe0,0xef,0xf9,0x40,0x9c,0xbb,0xfa,0x67,0x28, -0x14,0x1d,0xca,0x17,0x93,0x3f,0x14,0x2a,0x10,0xfa,0x75,0x2b,0x18,0x0a,0x15,0x2a, -0x1c,0x2a,0x52,0x34,0x64,0x6f,0xc5,0x42,0xff,0xec,0xad,0x78,0x89,0x50,0xc9,0x52, -0xa7,0x60,0x39,0x35,0x14,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7, -0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0x7f,0xc8,0x16, -0x70,0xfe,0x57,0x26,0xc2,0x09,0x39,0xd1,0xb9,0xa6,0x92,0x13,0xe7,0xd4,0x70,0x1a, -0x3a,0x3d,0x9c,0x5e,0xce,0x55,0xce,0x18,0x67,0x8a,0xf3,0x84,0xf3,0xbc,0xb3,0xc0, -0x59,0xec,0xbc,0xeb,0xec,0x77,0xbe,0xc5,0x84,0x02,0x25,0x02,0xe5,0x03,0x4d,0x02, -0x2d,0x02,0x1d,0x02,0x9d,0x02,0xfd,0x02,0x57,0x1f,0x65,0x26,0x05,0x1e,0x0b,0x4c, -0x0b,0xcc,0x0d,0x6c,0x08,0x7c,0x18,0xf8,0x3c,0xf0,0x7d,0xa0,0x44,0xf0,0xd4,0x60, -0xf9,0x60,0x5c,0x30,0x39,0x98,0x15,0xec,0x11,0xec,0x8d,0xb9,0x3a,0x78,0x73,0xf0, -0xfe,0xe0,0xc2,0xe0,0xd2,0xe0,0x3b,0xc1,0xf5,0xc1,0xcf,0x83,0x07,0xfe,0x8b,0xe6, -0xe0,0x6f,0x30,0x81,0x88,0x40,0x44,0x44,0x44,0x28,0x22,0x26,0xa2,0x40,0xae,0x29, -0xf1,0xab,0x29,0xf5,0xab,0x39,0x2b,0x22,0x36,0xe2,0x1c,0x4c,0x25,0x99,0xea,0x96, -0xa9,0x81,0x49,0x8f,0xa8,0x1d,0x51,0x3f,0xa2,0x41,0xae,0x69,0xf6,0xab,0x69,0xf1, -0xab,0x69,0x1b,0xd1,0x31,0xa2,0x13,0xe6,0x52,0x99,0x1e,0x47,0x99,0x7e,0x11,0x57, -0xfd,0x47,0x73,0x75,0xc4,0x75,0x7f,0xba,0x19,0x15,0x31,0x36,0x4f,0x73,0x73,0xc4, -0x2d,0xbf,0x9a,0xdb,0x22,0xee,0x38,0xca,0x8c,0x8f,0xb8,0x2b,0xe2,0x9e,0x88,0x89, -0x27,0x68,0xee,0xff,0xdd,0x66,0x4a,0xc4,0xf4,0xff,0x60,0xe6,0x46,0x2c,0x3e,0xca, -0x2c,0xfd,0x53,0xcc,0x6b,0x11,0x6f,0xfc,0x8f,0xcc,0x8a,0x88,0x37,0x23,0x56,0x47, -0xac,0xf9,0xd5,0xbc,0x13,0xf1,0xee,0x3f,0xc2,0xac,0x0f,0x9b,0x7f,0xb5,0xf9,0x54, -0xe6,0x0b,0xcc,0x01,0x4c,0x20,0xf2,0x88,0x89,0xc1,0x14,0x90,0x39,0x55,0xa6,0x7c, -0xae,0x89,0xc5,0x9c,0x93,0x6b,0x52,0x65,0xea,0x62,0x9a,0x61,0x3a,0x5a,0xa6,0x2b, -0xa6,0x87,0xcc,0x55,0x32,0xa3,0x22,0x6f,0x8e,0xbc,0x23,0xd7,0x8c,0x97,0xb9,0xe7, -0x4f,0x33,0x13,0x8f,0x61,0x26,0xe5,0x9a,0x87,0x30,0x53,0x22,0x9f,0x8a,0x7c,0x26, -0x72,0x06,0x66,0x96,0xcc,0x9c,0x5f,0xcd,0x2b,0x32,0x0b,0x65,0x16,0x63,0x96,0xe6, -0x9a,0x37,0x72,0xcd,0x0a,0xcc,0x9a,0xc8,0x77,0x23,0xd7,0x47,0x6e,0xc2,0x7c,0x2c, -0xb3,0xf9,0x57,0xf3,0xb9,0xcc,0x17,0x32,0xbb,0x31,0x7b,0xfe,0x9f,0xd9,0xfb,0x3b, -0xcc,0xfe,0xc8,0x03,0xff,0x08,0xf3,0x6d,0xe4,0xf7,0xff,0xd1,0x1c,0x8c,0xfc,0xf1, -0xa4,0x4c,0x78,0x28,0xf0,0xdf,0xbe,0xfd,0x18,0xf9,0xc7,0x9a,0x40,0xe8,0xf7,0x1a, -0x1e,0x89,0xff,0x65,0xbf,0xc7,0xa2,0x8f,0x6b,0x62,0x72,0x4d,0x81,0xbf,0x89,0x29, -0xe4,0x33,0x45,0x72,0x4d,0xb1,0xb0,0x39,0x21,0x53,0xea,0x5f,0x6f,0x4a,0xff,0x25, -0xcd,0x59,0x7f,0x92,0x29,0x1f,0x8a,0xfd,0x97,0x9b,0x73,0xfe,0x75,0xa6,0xd2,0x51, -0x26,0x4e,0xa6,0xfa,0xbf,0xd6,0x24,0x87,0x52,0xc3,0xe6,0xb8,0xa6,0x76,0xae,0xa9, -0xfb,0x17,0x34,0xf5,0xc3,0xe6,0x6f,0x6e,0x1a,0x60,0x1a,0x62,0xb2,0x30,0x4d,0x30, -0xcd,0x64,0x5a,0xfc,0xe1,0xa6,0x25,0xa6,0x15,0xa6,0x4d,0xa8,0x6d,0xae,0x69,0x17, -0x36,0xff,0x12,0xd3,0x21,0xd4,0xf1,0x0f,0x31,0x9d,0x42,0x97,0x1e,0x65,0x3a,0x87, -0xba,0xfe,0xcf,0x4c,0x8f,0x50,0xef,0x93,0x32,0x7d,0x42,0xfd,0x4e,0xc8,0x0c,0x08, -0x0d,0xfc,0x93,0xcc,0xd5,0xa1,0x51,0xa1,0x31,0xa1,0xb1,0xa1,0x9b,0x43,0xb7,0x84, -0x6e,0x0b,0xdd,0x11,0x9a,0x18,0x7a,0x24,0xf4,0x58,0x68,0x4a,0xe8,0x89,0xd0,0x53, -0xa1,0x67,0x42,0xd3,0x42,0xcf,0x87,0x66,0x1d,0x65,0xe6,0x86,0x16,0x1c,0x65,0x96, -0x86,0xde,0x0c,0xad,0x0e,0xad,0x09,0xbd,0x13,0x7a,0x37,0xb4,0x3e,0xf4,0x7e,0xe8, -0xe3,0xd0,0x67,0xa1,0xcf,0x43,0x5f,0x84,0x76,0x87,0xf6,0x84,0xf6,0x86,0xf6,0x87, -0xbe,0x0f,0xfd,0x74,0x94,0x89,0x88,0x8a,0x39,0xca,0x14,0x8a,0x2a,0x76,0x94,0x29, -0x15,0x75,0xfa,0x51,0xa6,0x6c,0xd4,0x39,0x3e,0x53,0xf5,0x28,0x93,0x1c,0x55,0x3b, -0xaa,0x6e,0x54,0xfd,0xa8,0x06,0x51,0x0d,0xa3,0xb2,0xa2,0x9a,0x44,0xb5,0x8a,0xea, -0x10,0xd5,0x31,0xaa,0x53,0xd4,0xa5,0x51,0x9d,0xa3,0xba,0x46,0x75,0x8f,0xea,0x21, -0xd3,0xcb,0x67,0x7a,0xff,0x0f,0x4c,0x9f,0xff,0x67,0x06,0x1e,0x65,0x06,0xff,0x97, -0xcd,0x55,0x3e,0x73,0x6d,0xd8,0x9c,0x80,0xb9,0x0e,0x73,0x03,0x66,0xd4,0xff,0xc8, -0x8c,0xc1,0x8c,0xc5,0xdc,0xfc,0x5f,0x36,0xb7,0xfc,0x6a,0x6e,0xcb,0x35,0x77,0x9c, -0xa4,0x19,0x8f,0xb9,0xeb,0xa4,0xcc,0x3d,0x47,0x99,0x89,0x98,0xfb,0x73,0xcd,0xa4, -0x5f,0xcd,0x43,0x27,0x68,0x1e,0xc9,0x35,0x8f,0x45,0x4d,0xc9,0xd3,0x3c,0x11,0xf5, -0x54,0xae,0x79,0x26,0x6a,0x5a,0xae,0x99,0x1e,0xf5,0x7c,0xd4,0x8c,0xa8,0x59,0xbf, -0x9a,0x39,0x51,0x73,0x73,0xcd,0xbc,0xa8,0x05,0xc7,0x30,0xaf,0x44,0x2d,0x3c,0x8e, -0x59,0x6c,0x99,0xa5,0x51,0xaf,0x61,0xde,0x38,0xca,0xac,0x88,0x7a,0x33,0x6a,0x75, -0xd4,0x9a,0xb0,0x39,0xae,0x79,0xe7,0x57,0xf3,0x2e,0x66,0x3d,0xe6,0x7d,0xcc,0x06, -0xcc,0x87,0x98,0x4d,0x98,0x8f,0x31,0x9b,0x31,0x9f,0x62,0xb6,0x61,0x3e,0xc3,0x7c, -0x9e,0x6b,0xbe,0xc0,0xec,0xc6,0xec,0x39,0xca,0xec,0xcf,0x35,0xdf,0xe6,0x9a,0x83, -0xb9,0xe6,0xa7,0x5c,0x13,0x88,0xfe,0xfd,0x26,0xe2,0xff,0x99,0x23,0x2f,0x72,0xcd, -0x16,0x83,0x29,0x80,0x29,0x84,0x29,0x82,0x29,0x86,0x29,0x81,0x29,0x85,0x39,0x15, -0x73,0x3a,0xa6,0x34,0xe6,0xac,0x5c,0x53,0x16,0x53,0x1e,0x13,0x7b,0x94,0xa9,0x94, -0x6b,0xaa,0xe6,0x9a,0xea,0xb9,0x26,0x39,0xd7,0xd4,0x38,0x41,0x93,0x1e,0x5d,0x3b, -0xba,0x6e,0x74,0xfd,0x63,0x9a,0x06,0x61,0xf3,0x1b,0x4d,0x43,0x4c,0xd6,0x31,0x4c, -0x93,0xb0,0xc9,0xc3,0x34,0x8b,0x6e,0x11,0x36,0x61,0x73,0x82,0xa6,0x55,0xd8,0x84, -0xcd,0x3f,0xde,0xb4,0x0b,0x9b,0x7f,0xb5,0xe9,0x10,0xdd,0xf1,0x5f,0x6b,0x3a,0x85, -0xcd,0x5f,0xd0,0x84,0x67,0x49,0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f, -0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc, -0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0, -0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2, -0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b, -0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d, -0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7, -0xf0,0x16,0xde,0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde, -0xc2,0x5b,0x78,0x0b,0x6f,0xe1,0x2d,0xbc,0x85,0xb7,0xf0,0x16,0xde,0xc2,0xdb,0xdf, -0x6f,0xab,0x19,0xe1,0x38,0xfd,0x2b,0xb8,0xda,0x45,0x3a,0x00,0x75,0xd0,0x25,0x48, -0x00,0x5d,0x8a,0x06,0xd1,0x65,0xc6,0x1b,0x7d,0x0d,0x8d,0x8c,0x30,0x3b,0x1d,0x27, -0x0a,0x0d,0xa2,0xd1,0x68,0xc5,0xa0,0xe3,0xe4,0x43,0x5f,0x67,0x57,0x0c,0xfa,0x78, -0x19,0xc7,0xc9,0x8f,0xbe,0x81,0xbb,0x20,0xba,0x86,0x70,0x45,0xcc,0x71,0x84,0x2b, -0x66,0x8e,0x43,0x63,0xd1,0xc9,0x84,0x3b,0xc7,0xf8,0xa3,0x95,0xd1,0x48,0xc5,0x17, -0x2c,0xe3,0xee,0x8f,0x44,0x13,0xd1,0xa8,0x32,0x6e,0x7a,0xa2,0x02,0x6e,0x7a,0xf2, -0x29,0x5c,0xfe,0x80,0x1b,0x7f,0x41,0xb4,0x12,0xba,0xc2,0x91,0x7f,0x19,0xd7,0xbf, -0x70,0xc0,0x8d,0xa7,0x60,0x19,0x77,0x7f,0x51,0x34,0x0e,0x2d,0xae,0x78,0x0b,0x97, -0x71,0xf3,0xbb,0x52,0xf9,0x7d,0x53,0xf9,0x5d,0xa5,0xfc,0xbe,0x5a,0xc6,0xcd,0x6f, -0x71,0xe5,0xb7,0xa4,0xce,0x7b,0x4a,0xc0,0xcd,0xef,0x6a,0xe5,0xf7,0x65,0x9d,0xef, -0x0c,0xe5,0x33,0x52,0xf9,0x8c,0x52,0x3e,0xe7,0xeb,0xfc,0x95,0x83,0x6e,0x3e,0x4f, -0x0b,0xb8,0xe9,0x38,0x0d,0xff,0x04,0x73,0x5c,0x19,0x37,0xde,0x32,0xca,0xe7,0x37, -0xca,0xe7,0x99,0x01,0xf7,0xfc,0xe5,0xca,0xb8,0xe7,0x2f,0xa3,0xf3,0x97,0x53,0xbe, -0x77,0x28,0xdf,0x15,0x14,0xfe,0x6c,0xed,0xaf,0x50,0xc6,0x4d,0x5f,0x45,0xa5,0xab, -0x8c,0xd2,0x71,0xb6,0x97,0x0e,0x34,0x1e,0xad,0xa2,0xfc,0xbf,0xa5,0xfc,0xaf,0x51, -0xfe,0xdf,0x56,0xfe,0x2b,0xeb,0xfc,0x55,0x94,0xff,0x6a,0x8a,0x3f,0x41,0xf9,0x7f, -0x47,0xf9,0x5f,0xa9,0xf3,0xbc,0xa3,0xfc,0xe7,0x53,0xfe,0xf3,0xeb,0xbc,0xab,0x74, -0x7d,0xe3,0x03,0x6e,0x7e,0xab,0x95,0x71,0xcf,0x93,0x12,0x70,0xcf,0x9b,0xa0,0xe3, -0x77,0xea,0x7a,0x25,0x29,0x9d,0x69,0x01,0xf7,0x3a,0xa5,0xa8,0x5c,0xd2,0x95,0xef, -0xba,0x0a,0x97,0xa6,0x70,0xb5,0x55,0x9e,0x75,0x74,0x5d,0x6b,0x29,0x7c,0x3d,0x95, -0x6b,0x86,0xea,0x53,0xa6,0xf2,0xfb,0x83,0xce,0xdb,0x30,0xe0,0xe6,0xf3,0x5d,0xd5, -0x9b,0x46,0x4a,0x47,0x13,0xc5,0xdf,0x58,0xf1,0x67,0x29,0xfe,0xe6,0x8a,0xbf,0xa9, -0xe2,0x59,0xa7,0x72,0x5b,0xaf,0x72,0x7b,0x4f,0xe5,0xf6,0xbe,0xda,0xc9,0x79,0x2a, -0xb7,0xf3,0x55,0x6e,0xf1,0x6a,0x27,0x1f,0xa8,0xdc,0xde,0x26,0x9e,0x02,0x68,0x6b, -0xe5,0xeb,0x5d,0x95,0x5f,0x41,0x95,0x5f,0x61,0xb4,0xb4,0x69,0x27,0x4a,0xcf,0x5b, -0x2a,0xc7,0x5d,0x4a,0xff,0x85,0xca,0x5f,0x7b,0xe5,0xf7,0x42,0x9d,0xe7,0x22,0xe5, -0xe3,0x22,0xc5,0x57,0x54,0xf1,0x15,0xd7,0xf5,0xb8,0x58,0xf9,0x6a,0xaf,0xf2,0xbd, -0x4c,0xc7,0x5f,0xac,0x7a,0x74,0x89,0xe2,0xe9,0xa2,0x78,0xba,0xe8,0xfc,0xdd,0x70, -0x57,0x34,0xf5,0x36,0xe8,0x1e,0x7f,0x99,0xc2,0x5d,0xa9,0x70,0x97,0x2b,0x5c,0x5f, -0x85,0x3b,0x43,0xe1,0xba,0xa9,0xfc,0xb2,0x55,0x7e,0xfd,0x55,0x7e,0x1f,0xaa,0xfc, -0x3e,0x52,0xf9,0x6d,0x52,0xf9,0x5d,0xa1,0x7a,0x77,0xa5,0xca,0xaf,0xaf,0xea,0x5b, -0x8e,0xca,0x6d,0x87,0xfa,0x97,0xfe,0x01,0xb7,0xfc,0xb2,0x55,0x7e,0xeb,0x95,0xdf, -0x92,0xca,0xef,0x29,0x2a,0xbf,0x19,0x4a,0xd7,0x76,0x8e,0x3b,0x1b,0x1d,0xa4,0x72, -0x1c,0xa4,0x74,0x0d,0x55,0x3b,0x1c,0x52,0xc6,0x3d,0xff,0x08,0xd5,0x97,0xeb,0x95, -0xce,0x91,0x2a,0x9f,0xd1,0xaa,0xb7,0x43,0x94,0xef,0x9b,0xd4,0xce,0x6e,0x54,0xf8, -0x71,0xba,0x1e,0xb7,0xca,0xff,0x76,0x1d,0xff,0xb5,0x8e,0xff,0x58,0xf9,0x1c,0xaa, -0x7a,0xf7,0x83,0xfa,0x97,0xa4,0xa0,0x7b,0xdc,0x9d,0x3a,0x6e,0x78,0xc0,0xcd,0xe7, -0x77,0x8a,0xf7,0x1b,0x1d,0x7f,0xb5,0xae,0xcf,0x04,0x9d,0xe7,0x5a,0xe5,0xfb,0x3a, -0xe5,0xef,0x6e,0x95,0xef,0xbd,0x3a,0xef,0x16,0x95,0xef,0xa7,0x3a,0xef,0x56,0x95, -0xef,0x36,0xd5,0xcf,0x80,0xca,0x37,0x42,0xf9,0xa9,0xa4,0xfa,0xb9,0x5d,0xe5,0xfc, -0x84,0xca,0xf9,0x33,0xf5,0xe3,0x6f,0xab,0x7c,0x03,0x2a,0xdf,0x08,0xd5,0xa7,0x29, -0xea,0xc7,0x03,0x2a,0xd7,0x90,0xe2,0x8b,0x50,0xfa,0x43,0x4a,0x57,0xb4,0xf2,0x11, -0xad,0x7c,0xc4,0x28,0x5c,0x01,0xe5,0xa3,0x90,0xfa,0xb3,0xcf,0xd5,0x1e,0x0b,0xa8, -0x5e,0x15,0x51,0xfe,0x0a,0xa9,0xde,0x16,0x53,0x3f,0x5e,0x42,0xf1,0x16,0x51,0x7e, -0x77,0x2a,0xbf,0x5f,0x28,0xbf,0xbb,0x94,0xdf,0x85,0x2a,0xe7,0x12,0xca,0x6f,0x29, -0x9d,0xf7,0x54,0xd5,0xab,0xdd,0xca,0xef,0x2b,0x3a,0x5f,0x69,0xe5,0x33,0xa4,0x7c, -0x46,0x2b,0x9f,0x0b,0x74,0xfe,0x73,0xd5,0x8f,0x9f,0xae,0xfa,0x73,0xba,0xea,0x4f, -0x69,0x5d,0x97,0xb2,0xca,0xe7,0xb7,0xca,0xe7,0x59,0xaa,0xcf,0xe5,0xd5,0x8f,0x97, -0xd5,0xf9,0xcb,0x2b,0xdf,0x9f,0x2b,0xdf,0xb1,0x0a,0x7f,0x8e,0xf6,0xc7,0xaa,0x3e, -0x54,0x52,0xba,0xca,0x2a,0x1d,0xe7,0x78,0xe9,0x50,0x3f,0x5e,0x55,0xe5,0x70,0x9f, -0xca,0xe1,0x4b,0x95,0xc3,0x1e,0x95,0xc3,0x57,0x2a,0x87,0x73,0x95,0x8e,0xaa,0x2a, -0x87,0x38,0xe5,0x7f,0xaf,0xf2,0xff,0xa6,0xce,0xb3,0x56,0xf9,0x8f,0x51,0xfe,0x0b, -0xe8,0xbc,0xab,0x75,0x7d,0xab,0xab,0x1f,0x8f,0x53,0x7b,0x48,0x55,0x3e,0xf6,0xa9, -0x5f,0x4a,0x54,0x3c,0x5f,0xe8,0xba,0x25,0x2b,0xbd,0x35,0xd4,0xdf,0xa4,0xaa,0x7c, -0x6a,0xe9,0xb8,0x7a,0x0a,0x57,0x43,0xe1,0xea,0xa8,0x5c,0xeb,0x2a,0x5f,0xb5,0x15, -0xbe,0xbe,0xca,0xb7,0x81,0xea,0x55,0x43,0xe5,0xf7,0xa0,0xce,0xdb,0x48,0xed,0x6a, -0xbf,0xea,0x4f,0x96,0xd2,0xd1,0x54,0xf1,0x37,0x51,0xfc,0x8d,0x15,0x7f,0x0b,0xc5, -0xdf,0xcc,0x6b,0xa7,0x2a,0xb7,0x03,0x2a,0xb7,0x6f,0x54,0x6e,0xdf,0xaa,0xbd,0xb4, -0x54,0xb9,0xb5,0xd2,0xf5,0xa9,0xae,0xf6,0xf2,0x9d,0xca,0xef,0x1d,0xf5,0xe7,0x6d, -0x94,0xaf,0x75,0x2a,0xc7,0x42,0x2a,0xc7,0x22,0xea,0x8f,0xa6,0x28,0x3d,0x6b,0x54, -0x9e,0xbb,0x95,0xfe,0x76,0xca,0x5f,0x07,0xe5,0xb7,0x9d,0xce,0xd3,0x51,0xf9,0xe8, -0xa8,0xf8,0x8a,0x29,0xbe,0x12,0xba,0x2e,0x9d,0x94,0xaf,0x0e,0x2a,0xdf,0xce,0x3a, -0xbe,0x93,0xea,0xd3,0xa5,0x8a,0xa7,0xab,0xe2,0xe9,0xaa,0xf3,0x77,0x57,0x3f,0x7d, -0xba,0xfa,0xe9,0xce,0x0a,0xd7,0x47,0xf5,0xee,0x7e,0x85,0xef,0xa1,0xf0,0xfd,0x14, -0xbe,0xb4,0xc2,0x77,0x57,0x39,0x0e,0x54,0x39,0x0e,0xf0,0xae,0x87,0xca,0xf1,0x90, -0xca,0xf1,0x47,0x95,0x63,0x6f,0xd5,0xbf,0x3e,0x2a,0xc7,0x7e,0xaa,0x7f,0x87,0x55, -0x7e,0x9f,0xab,0xbf,0x19,0xa0,0x7e,0x7d,0xa0,0xca,0xf1,0x3d,0xe5,0xbb,0x94,0xf2, -0x7d,0xaa,0xca,0x71,0xa6,0xd2,0xf5,0x99,0xfa,0xf5,0xc1,0x2a,0xcf,0xc1,0x4a,0xd7, -0x30,0xb5,0xcb,0xab,0xd4,0xaf,0x5f,0xa7,0x7a,0x73,0x83,0xd2,0x39,0x4a,0xe5,0x34, -0x46,0xf5,0xf8,0x2a,0xe5,0xff,0x66,0xe5,0x7f,0xac,0xd2,0xf3,0x80,0x8e,0xbb,0x45, -0xd7,0xe7,0x36,0xed,0xbf,0x43,0xf1,0x1c,0x50,0x3c,0x3f,0x29,0xbf,0xc3,0x54,0x0f, -0x0f,0xaa,0xdf,0x49,0x56,0xff,0x3e,0x5e,0xc7,0xfd,0xa2,0xfc,0x7e,0xaf,0xf8,0x27, -0x29,0xfe,0x6f,0x15,0xcf,0x35,0xba,0x6e,0x77,0xe9,0x7c,0x23,0x54,0x0e,0xd7,0x2b, -0xbf,0xf7,0xa8,0xbc,0x27,0xea,0xfc,0x7b,0xca,0xba,0xc7,0x8d,0x35,0xcf,0x38,0xe6, -0xb9,0xbd,0xac,0xeb,0xff,0xb4,0xe2,0x7b,0x52,0xf9,0x7f,0xb6,0x8c,0x7b,0xde,0xa9, -0x4a,0xd7,0x27,0xaa,0x77,0x87,0xa4,0x87,0x75,0x7d,0xb6,0xca,0x9d,0x4f,0xf1,0x2f, -0x51,0x3c,0x8b,0x14,0xcf,0xeb,0x8a,0x67,0x99,0xfc,0xe3,0xbd,0xe7,0x21,0xb9,0xd7, -0x2a,0xdc,0x07,0x0a,0xf7,0x9e,0xfc,0xcf,0xd3,0x79,0xab,0xa9,0xdd,0x9c,0x2f,0x77, -0x95,0xa0,0xbb,0xff,0xe7,0x80,0x1b,0xcf,0x26,0x9d,0x7f,0x83,0xd2,0xf3,0xbe,0xf2, -0xff,0xa1,0xf6,0x3f,0xa3,0xf8,0x9e,0xd2,0x79,0xa6,0xeb,0x3c,0xd3,0x14,0xdf,0x66, -0x1d,0xff,0xa3,0xf4,0x27,0xc5,0xb3,0x4d,0xee,0x18,0xa5,0x77,0xa9,0xe2,0x59,0xac, -0x78,0xde,0x50,0x3c,0xaf,0xc9,0xbf,0xba,0xc2,0xad,0x97,0xfb,0x5d,0x85,0xdb,0xa0, -0x70,0xef,0xcb,0xbf,0xa5,0xce,0x1b,0xa7,0x7c,0xb5,0x92,0xbb,0xaa,0xf2,0xf5,0x8b, -0xd2,0x9d,0xa3,0xf3,0x6f,0x54,0x7a,0x3e,0x50,0xbe,0x3e,0xd2,0xfe,0x99,0x8a,0xef, -0x05,0x9d,0xe7,0x45,0x9d,0x67,0xb6,0xd2,0x31,0x4b,0xfb,0x67,0x68,0xff,0x5c,0xed, -0x9f,0xa3,0xfd,0x25,0xb5,0xff,0x14,0xb9,0x4b,0xc9,0x7d,0xaa,0xdc,0xad,0xe5,0xbe, -0x40,0xee,0x36,0x72,0xb7,0x55,0x3d,0xbb,0x5c,0xda,0x43,0xda,0x53,0xda,0x4b,0xe1, -0x86,0x7b,0xcf,0x21,0xaa,0xc7,0xd7,0x48,0xaf,0x55,0xb8,0x87,0x14,0x6f,0x8e,0xc2, -0x7d,0xa4,0x74,0x6e,0x51,0x3a,0x3f,0x51,0x3d,0xdf,0xaa,0x70,0x1f,0x2b,0xdc,0x26, -0x85,0xfb,0x54,0xe1,0x36,0x2b,0xdc,0x36,0x85,0xdb,0xa5,0x70,0x3b,0x15,0xee,0x2b, -0x85,0xfb,0x52,0xe1,0xf6,0x29,0xdc,0x6e,0x85,0xfb,0x42,0xe1,0xf6,0x2a,0xdc,0x1e, -0x85,0xdb,0xaf,0xfe,0xec,0x2b,0x95,0xff,0x97,0xd2,0x3d,0xd2,0x2d,0xd2,0x4f,0xd5, -0x3f,0x9d,0xa9,0xfb,0xf5,0x59,0xba,0x9e,0x09,0x41,0x57,0x13,0x83,0x6e,0x3c,0x7b, -0x75,0xdd,0x5e,0x56,0xfb,0xbb,0x29,0xc2,0xdd,0xbf,0xa0,0xac,0x7b,0xdc,0x7c,0xb4, -0x84,0x69,0x47,0x68,0x49,0x53,0xef,0xd0,0x2c,0xf3,0xbb,0x52,0xed,0x73,0xa5,0x8e, -0x1b,0x17,0xe1,0x86,0x3b,0x4d,0xe1,0x4e,0xd7,0xfe,0x55,0xda,0x7f,0x8b,0xf6,0x57, -0xd6,0xfe,0x73,0x15,0xcf,0x5b,0x0a,0xf7,0x91,0xc2,0xdd,0xaa,0xf3,0x7f,0xa8,0xf3, -0x6f,0x2c,0xeb,0x5e,0x9f,0x67,0x75,0x7c,0x4d,0x1d,0x9f,0xae,0xe3,0x7e,0xd0,0x71, -0xb7,0x6b,0x7f,0x53,0xed,0x6f,0x26,0xfd,0x52,0xe1,0x76,0x29,0xdc,0x9d,0x8a,0xff, -0x0b,0xc5,0xbf,0x53,0xf1,0x4f,0x8f,0x70,0xc3,0x77,0x54,0xf8,0x43,0x0a,0x3f,0x5e, -0xf1,0x5e,0xa1,0xf8,0x7a,0x2b,0xdd,0x87,0xa5,0x2f,0x4a,0x5f,0xd7,0x71,0xd9,0x3a, -0xee,0x39,0x9d,0x67,0x96,0xce,0x33,0x53,0xe5,0xe8,0x28,0x9e,0x40,0x59,0xb7,0x9f, -0x7b,0x49,0xc7,0xcf,0xd1,0xf1,0x83,0x74,0xfc,0xf3,0x3a,0x6f,0x51,0x85,0x2f,0xa6, -0xfd,0x43,0xb4,0xff,0x05,0xed,0x2f,0xa7,0xfd,0xe5,0x15,0xdf,0x72,0xc5,0xf7,0x9a, -0xc2,0x0f,0x55,0xf8,0x19,0x4a,0xcf,0xbb,0x4a,0xcf,0x5a,0xe5,0x7b,0x95,0xe2,0x49, -0x50,0x3c,0x89,0x8a,0xe7,0x03,0x1d,0x3f,0x5c,0xc7,0xbf,0xa5,0x70,0x19,0x0a,0xd7, -0x40,0xf9,0xd9,0x2e,0xf7,0x67,0x0a,0x7f,0x8d,0xc2,0xaf,0xd1,0xf9,0x3e,0xd5,0xf9, -0xb6,0xe8,0x7c,0xab,0x15,0x4f,0x6b,0x1d,0xd7,0x46,0xe7,0xdb,0xa1,0xe3,0x47,0xe8, -0xf8,0xb7,0x15,0xae,0x8b,0xc2,0x75,0x55,0xb8,0xef,0x94,0xbf,0x03,0x0a,0xbf,0x4e, -0xe1,0x27,0xe8,0xbe,0xb1,0x41,0xfe,0x5b,0xe5,0x3f,0x53,0xfe,0x9f,0xeb,0xb8,0x6f, -0xe4,0xbf,0x3e,0xc2,0x4d,0xcf,0x7b,0xd2,0xe8,0x48,0x95,0x4b,0xa4,0xeb,0x5e,0x17, -0xe9,0x86,0x8b,0x88,0x74,0xe3,0x73,0xb4,0xff,0x03,0xed,0x0f,0xc8,0xbd,0x54,0xee, -0x1c,0xe9,0x27,0x0a,0x5f,0x28,0x52,0xf7,0x21,0x85,0x3b,0x5d,0xfb,0xb7,0x2b,0xde, -0x82,0x72,0xef,0x50,0xb8,0xaf,0x14,0xae,0xb0,0xfc,0xf7,0x45,0xba,0xcf,0x0f,0x5f, -0xcb,0xfd,0x8d,0xf4,0x07,0xe9,0x97,0x0a,0xff,0xae,0xdc,0xeb,0x15,0x6f,0x5b,0x9d, -0xbf,0xb5,0xf6,0x6f,0xd0,0xfe,0x36,0x72,0x2f,0x93,0xfb,0x63,0xe9,0x66,0x85,0xbf, -0x54,0xe9,0xd8,0xa6,0x70,0xe9,0xda,0xff,0x99,0xe2,0xbd,0x44,0xee,0xcf,0x15,0x6e, -0xaf,0xc2,0x5d,0x26,0xff,0xfd,0x4a,0xef,0x01,0xb9,0xbf,0x95,0x1e,0x94,0xee,0x91, -0x76,0x88,0x74,0x9f,0x83,0x86,0x4a,0x87,0xc9,0xff,0x23,0xe9,0x26,0xe9,0x2e,0xe9, -0x6e,0xb4,0x6d,0x94,0xe3,0x54,0x80,0x0b,0x21,0x16,0xda,0xc1,0x39,0x72,0x9f,0x2d, -0xad,0x28,0x5d,0x26,0x5d,0x2f,0x5d,0x02,0x75,0x62,0xe8,0x6f,0x62,0x5c,0x4d,0x94, -0xa6,0xc0,0x22,0x58,0x0d,0x1b,0xe0,0x2d,0xa8,0x57,0x80,0xe7,0x69,0x68,0x0f,0x4d, -0xa1,0x03,0x9c,0x07,0x1b,0xe0,0x5e,0x58,0x04,0xab,0xe4,0x7e,0x4b,0xee,0xd5,0x26, -0x7c,0x41,0xc2,0xc3,0xfb,0xb0,0x04,0x96,0xc1,0x2a,0xb9,0x57,0xc0,0x07,0xb0,0x52, -0xee,0xd5,0x50,0xaf,0x90,0xe3,0x34,0x87,0x0e,0x70,0x5e,0x21,0xd7,0xdd,0x02,0x56, -0xc1,0x47,0xf0,0x0e,0xe4,0xc0,0x66,0xf8,0x44,0xfe,0x1f,0x43,0x7c,0x51,0xf2,0x09, -0xa9,0xa5,0x29,0xfb,0xd2,0xae,0xe6,0x93,0xe6,0x97,0x16,0x94,0x16,0x96,0x16,0x97, -0xd6,0x96,0xd6,0x95,0x66,0x48,0x1b,0x48,0x1b,0x96,0x76,0xaf,0x6b,0x4d,0xdd,0x27, -0xd2,0xa5,0x97,0x48,0x2f,0xd5,0xfd,0xf1,0x0a,0x69,0x6f,0x3d,0x6f,0x3e,0xa7,0xfb, -0xcb,0x4b,0x72,0x3f,0x2f,0xf7,0x3c,0xb9,0x97,0x4b,0x57,0x48,0x37,0x4a,0x3f,0xd4, -0xfd,0x2e,0xa8,0xf6,0x18,0xa9,0xf6,0x1d,0xa5,0x76,0x3a,0x52,0xed,0x38,0x42,0xfb, -0x43,0xda,0x1f,0xad,0xfd,0xa3,0xa4,0xa3,0xa5,0x63,0xa4,0x37,0x4a,0xc7,0x4a,0x6f, -0x92,0xde,0xac,0xf8,0xf2,0x2b,0xbe,0x82,0x8a,0xaf,0xb0,0xf6,0x8f,0xd3,0xfe,0x02, -0xda,0x5f,0x48,0xfb,0x8b,0x68,0xff,0x2d,0xd2,0x5b,0xa5,0xb7,0x49,0x6f,0x97,0xde, -0x21,0xbd,0x53,0x3a,0x5e,0xf1,0x15,0x57,0x7c,0x25,0xe5,0x2e,0x21,0x77,0x29,0xb9, -0xcf,0x90,0xfb,0x4c,0xb9,0x4b,0xcb,0x7d,0x96,0xdc,0x15,0xe4,0x3e,0x5b,0xe9,0xa9, -0xa8,0xf8,0x27,0x68,0x7f,0xac,0xf6,0x9f,0xa3,0xfd,0x95,0xb4,0xff,0x2e,0xe9,0xdd, -0xd2,0x7b,0xa4,0xf7,0x4a,0x27,0x4a,0xef,0x93,0xde,0xaf,0xf8,0xaa,0x28,0xbe,0x6a, -0x8a,0x2f,0x5e,0xfb,0x1f,0xd0,0xfe,0xaa,0xda,0x1f,0xa7,0xfd,0xd5,0xb5,0x7f,0x92, -0xf4,0x41,0xe9,0x43,0xd2,0x87,0xa5,0x8f,0x48,0x1f,0x95,0x3e,0xa6,0xf8,0x92,0x14, -0x5f,0x8a,0xe2,0x4b,0x93,0x7f,0xb2,0xfc,0x53,0xe5,0x5f,0x43,0xfe,0xb5,0xe4,0x5f, -0x47,0xfe,0xf5,0xe4,0x5f,0x5b,0xfe,0x75,0xe5,0x5f,0x5f,0xfe,0x99,0xf2,0x6f,0x24, -0x77,0x43,0xb9,0xb3,0xe4,0x6e,0x2e,0xf7,0x79,0x72,0xb7,0x90,0xbb,0xa5,0xdc,0x17, -0xc8,0x7d,0xa1,0xe2,0x6d,0x2f,0xff,0xb6,0xf2,0x6f,0x27,0xff,0x0e,0xf2,0xef,0x24, -0xff,0x4b,0xe5,0xdf,0x59,0xfe,0xdd,0xe4,0x7f,0xb9,0xfc,0x7b,0xaa,0x1c,0x26,0x6b, -0x7f,0x77,0xed,0xef,0xa1,0xfd,0xbd,0xb4,0x7f,0x8a,0xf4,0x71,0xe9,0x13,0xd2,0x27, -0xa5,0x4f,0x49,0x9f,0x96,0x3e,0xa3,0xf8,0xae,0x54,0x7c,0x7d,0x15,0x5f,0x7f,0xed, -0x9f,0xaa,0xfd,0x7d,0xb4,0xbf,0x9f,0xf6,0x0f,0xd0,0xfe,0x69,0xd2,0x67,0xa5,0xd3, -0xa5,0xcf,0x49,0x9f,0x97,0xbe,0x20,0x9d,0x21,0x9d,0x2d,0x5d,0x26,0xfd,0x5a,0x3a, -0x4f,0xe7,0x5b,0xe3,0xdd,0xd7,0x75,0xbe,0x77,0xb4,0x7f,0x85,0xf4,0x7b,0x85,0xfb, -0x58,0xe1,0x3e,0x51,0xb8,0xcd,0x65,0xdd,0x71,0x9d,0x07,0xcb,0xbb,0xfa,0x90,0xf4, -0x05,0xe9,0x1a,0xe9,0x3b,0xd2,0xb7,0xa5,0x91,0x1a,0x0f,0x8a,0x91,0x16,0x94,0x9e, -0x2d,0xad,0x28,0x6d,0x20,0x6d,0x24,0x6d,0x22,0x6d,0x26,0xed,0x27,0xed,0x26,0xcd, -0x96,0x0e,0x94,0x0e,0x91,0x5e,0x25,0x1d,0x2e,0xbd,0x5a,0x3a,0x52,0x3a,0x4a,0xba, -0x45,0xfa,0xa9,0xf4,0x46,0xe9,0x58,0xe9,0x38,0xe9,0x2d,0xd2,0xad,0xd2,0x6d,0xd2, -0xe7,0xa4,0xcf,0x4b,0x5f,0x90,0xce,0x90,0xee,0x92,0xee,0x96,0x7e,0x29,0xdd,0x83, -0x4e,0x4a,0xa0,0xfd,0x27,0xb8,0x7a,0x9e,0xf4,0x7c,0x69,0x6b,0xe9,0x05,0xd2,0x0b, -0xa5,0xed,0xa5,0x17,0x49,0x2f,0x96,0x5e,0x22,0xbd,0x4c,0xda,0x45,0xda,0x4d,0xda, -0x43,0xda,0x4b,0xda,0x5b,0x9a,0x0d,0x0f,0xc2,0x40,0xb9,0x07,0xcb,0x3d,0x44,0xee, -0xa1,0x72,0x0f,0x93,0xfb,0x6a,0xb9,0xaf,0x91,0x7b,0x84,0xdc,0xd7,0xc9,0xfd,0xa8, -0xf4,0x1b,0xe9,0x73,0xd2,0x17,0xa4,0x33,0xa5,0xb3,0xa5,0x2f,0x4a,0x5f,0x92,0xce, -0x97,0xbe,0x2c,0x7d,0x55,0xba,0x48,0xba,0x44,0xba,0x4c,0xfa,0x86,0x74,0x85,0xf4, -0x4d,0xe9,0x5a,0xa5,0xeb,0x5d,0xb9,0xd7,0xcb,0xfd,0x9e,0xdc,0x1f,0xc8,0xbd,0x41, -0xee,0x0f,0xe5,0xfe,0x48,0xee,0x1c,0xb9,0x3f,0x96,0xfb,0x7b,0xe9,0x0f,0xd2,0x83, -0xd2,0x43,0xd2,0x9f,0x4d,0x9a,0x8b,0x06,0x9c,0x07,0xc1,0xe8,0xc3,0xd2,0xe9,0x50, -0xa9,0x58,0xc0,0x89,0x2f,0xe6,0x6a,0x75,0xa8,0x57,0x22,0xe0,0xb4,0x80,0x0e,0x70, -0x1e,0xcc,0x2c,0x19,0x70,0x5e,0x85,0x97,0xe1,0x15,0x58,0x08,0x8b,0x60,0x46,0x29, -0xfc,0x4a,0xb9,0xfa,0x0a,0x24,0x9c,0x1e,0x70,0x6a,0x02,0xa7,0x72,0xd2,0xa1,0x01, -0x5c,0x0c,0x9d,0x45,0x57,0xb8,0x06,0x9e,0x15,0x73,0xc5,0x3c,0xf1,0xb2,0x30,0x63, -0xb1,0x66,0xbc,0x68,0xa3,0xe3,0xbe,0x67,0xfc,0xc1,0xf8,0xf3,0xbb,0xf3,0x15,0xf1, -0x2a,0x2c,0x86,0x25,0xf0,0x1a,0xbc,0x0e,0xf7,0xf0,0xfb,0xf4,0x5e,0x98,0x08,0xf7, -0xc1,0x0c,0x98,0x09,0x4b,0x61,0x39,0xbc,0x0b,0x5b,0x60,0x3b,0x7c,0x29,0xbe,0x12, -0xa6,0x1f,0x19,0x60,0xda,0xaa,0x79,0x8f,0x66,0xda,0xa8,0x18,0x6a,0x9e,0x37,0xcd, -0x6f,0x14,0x71,0xad,0x79,0x9f,0x66,0xde,0xa5,0x89,0x9b,0xc4,0xcd,0x62,0x9c,0x7e, -0x8f,0xde,0x2e,0xcc,0x6f,0xc7,0x29,0xa6,0x0f,0x36,0xcf,0xb7,0xa6,0xcf,0x32,0xed, -0x9a,0xe7,0xd3,0x31,0x70,0x33,0xdc,0x0a,0xd5,0x43,0x3c,0x63,0x42,0x7b,0xe8,0x28, -0xba,0xc0,0x38,0xb8,0x0b,0x16,0xc2,0x62,0xb1,0x14,0x96,0xc1,0xeb,0xf0,0x06,0xac, -0x10,0x6b,0x61,0x17,0xec,0x85,0xaf,0xa1,0x28,0xcf,0xb0,0x67,0x40,0x39,0xa8,0x0f, -0x19,0xa2,0x01,0x34,0x87,0x16,0xd0,0x19,0xba,0x40,0x6f,0xe8,0x0f,0x03,0x20,0x5b, -0x0c,0xd4,0xf3,0xf0,0xfb,0xe2,0x03,0xc8,0x81,0xcd,0xb0,0x1d,0x3e,0x83,0x1d,0xf0, -0x39,0xec,0x84,0x5d,0xb0,0x07,0xbe,0x82,0xbd,0xb0,0x0f,0x0e,0xc2,0x21,0x38,0x0c, -0xbf,0x88,0xa2,0xd1,0x2e,0xc5,0x44,0x71,0xa8,0x0e,0x09,0xd0,0x1c,0x5a,0xc2,0x53, -0xf0,0x34,0xcc,0x84,0x59,0x62,0x09,0xbc,0x09,0xab,0x60,0x17,0xec,0x86,0x03,0xf0, -0x0d,0x7c,0x0b,0x87,0xc4,0x4f,0xc2,0xc9,0xc7,0xf3,0x12,0x9c,0x02,0xa7,0xc3,0x19, -0xa2,0x34,0xc4,0xc2,0xd9,0xe2,0x1c,0xa8,0x04,0x95,0xc5,0xb9,0x10,0x07,0x19,0x70, -0x11,0x74,0x84,0x4e,0xd0,0x05,0xae,0x84,0x6c,0xb8,0x19,0x6e,0x81,0xf1,0x70,0x3f, -0x3c,0x06,0x93,0x61,0x25,0xbc,0x29,0x56,0xc1,0xa7,0xb0,0x0d,0x82,0xfc,0x4e,0x88, -0x10,0x91,0x90,0x0e,0xb5,0x44,0x6d,0x51,0x47,0xd4,0x15,0xf5,0x20,0x03,0x1a,0x40, -0x53,0x68,0x06,0xe7,0x41,0x4b,0x71,0x3e,0xb4,0x82,0xd6,0xa2,0x0d,0x74,0x80,0x8b, -0xa0,0x2b,0x74,0x83,0xee,0xd0,0x13,0x06,0xc0,0x40,0x31,0x08,0x46,0xc2,0x28,0x31, -0x1a,0xc6,0xc0,0x58,0xb8,0x1d,0xc6,0xc3,0x04,0xb8,0x07,0xa6,0xc2,0xb3,0x30,0x13, -0x66,0x8b,0x97,0x60,0x01,0xbc,0x2a,0x16,0x0a,0xf3,0xbb,0x68,0x09,0x2c,0x85,0xd7, -0x61,0x05,0xac,0xd4,0x6f,0x25,0xf3,0x3b,0x69,0x8d,0x78,0x5b,0x6c,0x10,0x39,0xf0, -0x31,0x6c,0x86,0x4f,0x61,0x2b,0x6c,0x83,0x1d,0xb0,0x17,0xf6,0xc1,0x7e,0x38,0x2c, -0x7e,0x16,0x81,0xfc,0x94,0x2b,0x44,0x88,0x10,0xe4,0x87,0x22,0x50,0x14,0x4a,0x40, -0x65,0xa8,0x02,0x09,0x90,0x04,0xc9,0x90,0x0a,0x69,0x50,0x13,0xd2,0xa1,0x8e,0xa8, -0x07,0x19,0xd0,0x00,0x32,0xa1,0x09,0x34,0x85,0x16,0xd0,0x12,0xda,0x88,0x8e,0x70, -0x09,0x5c,0x26,0x7a,0xc2,0x00,0xc8,0x86,0x81,0x30,0x08,0x86,0xc0,0x55,0x62,0x14, -0x8c,0x86,0x31,0x62,0x2c,0xdc,0x01,0xe3,0xe1,0x2e,0xb8,0x07,0xa6,0xc2,0xb3,0x30, -0x13,0x66,0xc3,0x1c,0x98,0x0b,0x0b,0xe0,0x55,0xb1,0x50,0x2c,0x82,0x25,0xb0,0x14, -0xde,0x80,0x15,0xb0,0x12,0xde,0x14,0xab,0xe1,0x2d,0x58,0x23,0xd6,0x8a,0x2d,0xf0, -0x29,0x6c,0x85,0x6d,0xb0,0x03,0xf6,0xc2,0x41,0x71,0x08,0x7e,0x81,0x40,0x01,0x97, -0x20,0x44,0x40,0x08,0x0a,0x42,0x11,0x28,0x0a,0x25,0xa0,0x32,0x54,0x81,0x04,0x48, -0x82,0x64,0x48,0x85,0x74,0xa8,0x23,0xea,0x8a,0x7a,0xa2,0xbe,0xc8,0x10,0x0d,0xa0, -0x11,0x34,0xd1,0xef,0xe6,0x16,0xfa,0xdd,0xdc,0x52,0xb4,0xd3,0x6f,0xea,0x0e,0xe2, -0x12,0xb8,0x14,0x3a,0x43,0x57,0xe8,0x06,0xdd,0xa1,0x27,0x0c,0x80,0x81,0x62,0xb4, -0x18,0x23,0xc6,0xc2,0xad,0x70,0x27,0x4c,0x80,0xbb,0x61,0x22,0x4c,0x82,0x07,0xe1, -0x61,0xf1,0x28,0x3c,0x06,0x4f,0xc0,0x93,0x30,0x15,0x9e,0x85,0x17,0x60,0x81,0x7e, -0xb7,0x2f,0x86,0x25,0x62,0x29,0x2c,0x83,0xe5,0xb0,0x52,0xbf,0xf1,0xcd,0xef,0xfb, -0x35,0x62,0xad,0xd8,0x20,0x76,0xc0,0xde,0x02,0x66,0x40,0xd9,0x25,0x00,0x11,0x10, -0x29,0x42,0x50,0x10,0x0a,0x43,0x51,0x28,0x0e,0x95,0xa1,0x0a,0xa4,0x43,0x1d,0x51, -0x57,0xd4,0x83,0x0c,0x68,0x00,0x8d,0xa0,0xb1,0xde,0x27,0x34,0x87,0x96,0xd0,0xae, -0xa0,0xfb,0x8e,0xe1,0x22,0xb8,0x18,0x2e,0x81,0x4b,0xa1,0x0b,0x74,0x85,0x6e,0xd0, -0x1d,0x7a,0xc2,0x00,0x18,0x29,0x46,0x89,0xd1,0x30,0x06,0xc6,0xc2,0xed,0x70,0x27, -0x4c,0x80,0xbb,0x61,0x2a,0x3c,0x0b,0x73,0x60,0x2e,0x2c,0x80,0x57,0xc5,0x42,0xb1, -0x48,0x2c,0x16,0xe6,0x1d,0xc7,0xeb,0xb0,0x5c,0xac,0xd0,0xfb,0x8d,0x55,0x7a,0xbf, -0xf1,0x16,0xac,0xd1,0xfb,0x0e,0xf3,0xee,0x23,0x07,0x3e,0x81,0x2d,0xf0,0x29,0x6c, -0x85,0x6d,0xb0,0x03,0xf6,0xc2,0x7e,0xf8,0x1a,0x0e,0x08,0xa7,0x10,0x65,0x0a,0x41, -0x88,0x80,0x48,0x28,0x08,0x85,0xa1,0x28,0x14,0x87,0x5a,0x50,0x1b,0xea,0x40,0x5d, -0x61,0xde,0xa3,0x64,0x40,0x03,0x68,0x04,0x8d,0xa1,0xa9,0xde,0xb5,0x98,0xf7,0x2c, -0x2d,0xc5,0xf9,0xe2,0x42,0x68,0xaf,0xf7,0x30,0x86,0xce,0xd0,0x15,0xba,0x41,0x77, -0xe8,0x09,0x03,0xe0,0x1a,0xb8,0x01,0x46,0x89,0xd1,0x30,0x06,0xc6,0xc2,0x7d,0xf0, -0x20,0xcc,0x82,0x39,0xf0,0x0a,0x2c,0x14,0x4b,0x60,0xb9,0xde,0xdf,0xac,0xd2,0x7b, -0x9d,0x77,0x61,0x1d,0xbc,0x07,0x1f,0x88,0x8d,0x7a,0xd7,0xb3,0x03,0xf6,0xc2,0xd7, -0x70,0xc0,0x94,0x41,0x61,0xda,0x25,0x24,0x8a,0x24,0x48,0x86,0x14,0xa8,0x05,0x19, -0x90,0x05,0x8d,0x45,0x13,0x38,0x1f,0x5a,0x43,0x47,0x18,0x05,0xa3,0xe1,0x46,0x71, -0x13,0xdc,0x0a,0xb7,0xc3,0x13,0xf0,0x94,0x78,0x06,0x66,0xc2,0x2c,0x31,0x1b,0xe6, -0xc0,0x8b,0xf0,0x2a,0x2c,0x14,0x4b,0xe0,0x75,0x58,0x2e,0x56,0xc2,0xdb,0xb0,0x16, -0x3e,0x84,0x1c,0xd8,0x0c,0x4e,0x11,0x97,0xd3,0xe0,0x74,0x28,0x07,0xe7,0x42,0xaa, -0xa8,0x21,0xd2,0x45,0x3d,0xa8,0x0f,0x19,0xd0,0x04,0x9a,0x41,0x5f,0x18,0x08,0xd7, -0xc3,0x0d,0x62,0x24,0xdc,0x08,0x37,0xc1,0xcd,0x30,0x0e,0x6e,0x87,0x3b,0xe0,0x7e, -0x98,0x04,0xaf,0xc2,0x72,0xe1,0x14,0xa5,0xcd,0x41,0x55,0xa8,0x06,0x71,0x90,0x00, -0x89,0x22,0x09,0x6a,0x40,0x4d,0x91,0x0e,0xb5,0xa0,0x36,0xd4,0x81,0xba,0x50,0x0f, -0xea,0x8b,0x0c,0x68,0x06,0xad,0xa1,0x1d,0xb4,0x87,0x0e,0x70,0x11,0x74,0x84,0x8b, -0xe1,0x52,0xb8,0x0c,0xba,0x40,0x57,0xd1,0x0d,0x2e,0x87,0x1e,0xd0,0x13,0x7a,0x41, -0x3f,0xe8,0x0f,0xd9,0x30,0x10,0x86,0xc0,0x55,0x30,0x0a,0x46,0x8b,0x31,0x70,0x23, -0x8c,0x85,0x9b,0xe0,0x66,0xb8,0x1d,0xee,0x10,0x77,0x8a,0xf1,0x62,0x02,0x4c,0x82, -0x07,0xe1,0x61,0x78,0x44,0x4c,0x86,0x37,0x60,0x85,0x58,0x23,0xd6,0xc2,0x21,0x38, -0x2c,0x7e,0x82,0x5f,0xc0,0x29,0x46,0xbb,0x29,0x4e,0xbb,0x81,0x96,0xd0,0x1a,0xda, -0xc3,0x45,0xe2,0x62,0xb8,0x14,0xba,0xc0,0x38,0xb8,0x15,0xee,0x80,0x09,0x30,0x13, -0x66,0xc3,0x5c,0x98,0x0f,0x8b,0x60,0x89,0x58,0x06,0x6f,0xc0,0x4a,0xf8,0x00,0x36, -0x42,0xd1,0x12,0xb4,0x67,0x28,0x05,0xa7,0xc1,0xc5,0x70,0x29,0x74,0x86,0xde,0x30, -0x10,0x46,0xc2,0x78,0x98,0x0c,0xdf,0xc2,0x0f,0xf0,0x13,0x04,0x4a,0x52,0x4f,0x4e, -0xa1,0x8d,0xc2,0x0d,0x30,0x0a,0x1e,0x84,0xc9,0xb0,0x0b,0xbe,0x82,0x7d,0xb0,0x1f, -0x7e,0x00,0xe7,0x54,0xb2,0x06,0xc5,0xa1,0x24,0x94,0x12,0x65,0x21,0x11,0x92,0x20, -0x19,0x52,0x44,0x06,0xb4,0x81,0x0b,0xa0,0x2d,0x74,0x81,0xbe,0xd0,0x1f,0xb2,0x61, -0x10,0x0c,0x86,0x91,0x30,0x07,0x5e,0x84,0xb9,0xf0,0x92,0x98,0x07,0x0b,0x61,0x11, -0xbc,0x01,0xcb,0xc5,0x0a,0x58,0x09,0x6f,0xc2,0x7a,0xd8,0x20,0x72,0xc4,0xc7,0x62, -0x0b,0x7c,0x01,0x05,0x4e,0xa3,0x4b,0x84,0x22,0xa2,0x28,0x9c,0x0e,0xe5,0x20,0x13, -0x1a,0x8a,0x46,0x30,0x1c,0x46,0xc2,0x8d,0x30,0x16,0x6e,0x82,0x9b,0x61,0x2a,0x4c, -0x13,0xcf,0x8a,0x99,0xf0,0x2d,0x38,0xa7,0x3b,0x4e,0x19,0x28,0x07,0x15,0x20,0x16, -0x2a,0x42,0x25,0xa8,0x0c,0xe7,0x42,0x55,0x48,0x80,0x44,0x48,0x12,0xc9,0x50,0x13, -0xd2,0xa1,0x36,0x34,0x86,0x56,0xd0,0x1a,0xfa,0x41,0x36,0x0c,0x81,0x91,0x30,0x1d, -0x66,0xc2,0x9b,0xb0,0x16,0x3e,0x84,0x8f,0x84,0x73,0x06,0xcf,0xf6,0x70,0x2a,0x9c, -0x06,0xa7,0xc3,0x19,0x50,0x5a,0x94,0x83,0x0b,0xa1,0x9d,0x68,0x2f,0x3a,0x88,0x8b, -0xe0,0x32,0xe8,0x22,0xba,0x8a,0x6e,0xa2,0x3b,0x5c,0x0e,0x3d,0xa0,0x2f,0xf4,0x83, -0x41,0x30,0x18,0x46,0xc0,0x0d,0x62,0x24,0xdc,0x02,0x13,0x60,0x12,0x3c,0x23,0x66, -0xc2,0x42,0x58,0x0c,0x1f,0xc3,0x16,0xd8,0x0d,0x4e,0x69,0xee,0x4f,0xe6,0xbd,0xb9, -0x08,0x41,0x32,0xa4,0x88,0x54,0x91,0x06,0xb5,0xf4,0x0e,0xde,0x50,0x47,0xd4,0xd5, -0xfb,0xf7,0x4c,0x61,0xde,0xc1,0x37,0x82,0x2c,0x38,0x0f,0x5a,0x43,0x47,0xe8,0x03, -0x83,0x61,0x24,0x8c,0x82,0xd1,0x62,0x0c,0x4c,0x86,0x29,0xe2,0x71,0x78,0x0a,0x9e, -0x86,0x67,0x60,0x2a,0x4c,0x83,0x67,0xc5,0x74,0x78,0x1e,0x5e,0x80,0x19,0x30,0x13, -0x16,0xc0,0xcb,0xf0,0x19,0xec,0x10,0x9f,0x8b,0x9d,0xf0,0x05,0xec,0x82,0x2f,0x61, -0x8f,0xf8,0x4a,0xec,0x85,0xfd,0xf0,0x35,0x1c,0x00,0xe7,0x4c,0xea,0x0e,0x9c,0x0d, -0x55,0xa1,0x1a,0x24,0x43,0x0a,0xa4,0x42,0x1a,0xd4,0x80,0x0c,0x68,0x06,0x2d,0xa1, -0x15,0xb4,0x86,0x8e,0x70,0x31,0x0c,0x83,0xe1,0x70,0x1d,0x8c,0x84,0x5b,0x61,0x02, -0xbc,0x0c,0x0b,0x61,0x31,0xac,0x85,0x75,0xf0,0x1e,0x6c,0x81,0x4f,0xc5,0x56,0xd8, -0x09,0x5f,0xc0,0x97,0xb0,0x47,0x7c,0x05,0x07,0xe0,0x1b,0xf1,0x2d,0x7c,0x07,0xdf, -0x8b,0x1f,0xe0,0x20,0x1c,0x12,0xce,0x59,0xa4,0x1f,0xaa,0xc1,0x95,0xd0,0x07,0x86, -0xc1,0x70,0x71,0x35,0x3c,0x08,0x0f,0xc1,0x62,0x58,0x02,0xbf,0x9c,0xe5,0xce,0x01, -0x37,0xef,0xf5,0xcd,0x18,0xb8,0x79,0x7f,0x6f,0xc6,0x66,0xcd,0x7b,0x66,0x33,0x26, -0x6d,0xde,0x27,0x9b,0x31,0x4f,0xf3,0x9e,0xb8,0xa3,0xe8,0x24,0x2e,0x15,0xe6,0x5d, -0xf1,0x75,0x65,0xdd,0xb1,0x0f,0x33,0xae,0x6c,0xc6,0x86,0xcd,0x38,0xfb,0x22,0x61, -0xde,0xad,0x9a,0x71,0x66,0x33,0xc6,0x6b,0xc6,0xcd,0xcd,0x18,0xee,0xfa,0xb2,0xee, -0x58,0xed,0xa6,0xb2,0xee,0x18,0xab,0x19,0xef,0x36,0xef,0x5e,0xcd,0x38,0xa7,0x19, -0x2b,0x35,0xe3,0xd4,0x05,0xcb,0xd1,0x7f,0x40,0x7d,0xc8,0x80,0x0b,0xc5,0x40,0x71, -0x83,0x98,0x00,0x0f,0xc3,0x5a,0xc8,0x81,0x4f,0xc5,0x67,0xb0,0x0f,0x82,0xe5,0x5d, -0xa2,0x45,0x7e,0x28,0x01,0xa5,0xc4,0x69,0xe2,0x74,0x38,0x0b,0xce,0x16,0x15,0x45, -0x65,0x51,0x05,0xe2,0x20,0x5e,0x54,0x87,0x14,0x48,0x35,0xef,0x6e,0x21,0x5d,0xd4, -0x81,0xfa,0x90,0x05,0xcd,0xe0,0x7c,0xd1,0x05,0x46,0xc3,0x18,0xb8,0x11,0xc6,0xc2, -0x38,0x70,0xaa,0x39,0xce,0xb5,0x30,0x02,0xae,0x83,0xeb,0x61,0x3b,0xec,0x86,0xaf, -0x60,0x2f,0xec,0x87,0xaf,0xe1,0x00,0x38,0x71,0x8e,0x73,0x0e,0x54,0x12,0x71,0x22, -0x01,0x7a,0xc1,0x00,0x71,0x83,0x18,0x09,0xf7,0xc1,0x64,0x78,0x1a,0xa6,0xc2,0x0b, -0x30,0x13,0x5e,0x82,0xf9,0xb0,0x08,0x96,0xc0,0x72,0x58,0x09,0x6f,0xc3,0x5a,0xf8, -0x00,0x36,0xc2,0x27,0xb0,0x05,0x7e,0x81,0x50,0x82,0x4b,0x94,0x88,0x16,0xe5,0xe1, -0x5c,0xa8,0x02,0x71,0x10,0x0f,0xd5,0x21,0x11,0x52,0xa1,0x26,0xd4,0x82,0xda,0xa2, -0x8e,0x68,0x00,0xf7,0xe9,0xfd,0xa0,0x79,0x97,0xf8,0x10,0x3c,0x0c,0x8f,0xe8,0x3d, -0xe9,0x63,0x62,0x8a,0xde,0x23,0xfe,0x28,0x0e,0xeb,0x7d,0xe2,0x2f,0x22,0x94,0xc8, -0xf9,0x20,0x11,0xee,0x84,0xc9,0xb0,0x18,0xf6,0xc1,0x2f,0xe0,0xa4,0xe0,0x6e,0x89, -0x9e,0xcf,0x7d,0x74,0x32,0xd7,0x5e,0x9c,0x02,0xb7,0x3f,0x49,0x7e,0xe1,0x7b,0xf8, -0x01,0x7e,0x02,0xe7,0x29,0xee,0x61,0x4f,0x53,0x0f,0x45,0x51,0x28,0x0b,0xe5,0xe0, -0x5c,0xa8,0x02,0x55,0x21,0x03,0xfa,0x41,0x7f,0x31,0x40,0x0c,0x81,0xeb,0xe0,0x06, -0x31,0x12,0x1e,0x82,0x87,0xe1,0x11,0x78,0x14,0x1e,0x83,0xc9,0xf0,0x19,0xec,0x80, -0xbd,0xb0,0x0f,0xf6,0xc3,0xa9,0xcf,0x70,0x3e,0xa8,0x00,0x03,0x20,0x5b,0x0c,0x84, -0x9b,0x61,0x9c,0xb8,0x0d,0xee,0x84,0xf1,0x62,0x02,0xe4,0xc0,0x7e,0xf8,0x06,0xbe, -0x85,0xef,0xe0,0x7b,0xf1,0x03,0x1c,0x84,0x43,0xe2,0x47,0x08,0x4c,0xa5,0x8d,0x88, -0x08,0x08,0x41,0x94,0x88,0x86,0xfc,0x50,0x40,0x14,0x84,0x0a,0x10,0x0b,0x67,0xc3, -0x39,0x50,0x11,0x2a,0x89,0x6a,0x22,0x03,0x06,0xc3,0x48,0x18,0x05,0xa3,0x61,0x0e, -0xbc,0x08,0xaf,0xc1,0xeb,0xf0,0x06,0xac,0x85,0x0f,0x61,0x0b,0xec,0x87,0xaf,0xe1, -0x7b,0xf8,0x51,0xfc,0x04,0x3f,0xc3,0x2f,0xc2,0x99,0xe6,0x38,0x31,0x90,0x1f,0xce, -0x81,0x8a,0x10,0x07,0x09,0xd0,0x18,0x9a,0x40,0x1b,0xb8,0x00,0xda,0x42,0x17,0x18, -0x01,0x23,0x61,0x34,0x8c,0x11,0x37,0xc2,0x6c,0x98,0x23,0x5e,0x84,0xb9,0xf0,0x12, -0x2c,0x80,0x97,0xe1,0x15,0x78,0x15,0x16,0xc2,0x22,0x58,0x02,0xef,0x88,0xb5,0xf0, -0x21,0x6c,0x81,0xed,0xf0,0x99,0xd8,0x21,0x3e,0x87,0xbd,0xb0,0x0f,0x0e,0xc2,0x21, -0xf8,0x79,0x9a,0xfb,0xd2,0xb9,0x32,0x9c,0x0b,0xf1,0x50,0x1d,0x12,0x20,0x11,0x92, -0x20,0x19,0x52,0x20,0x15,0xd2,0x20,0x03,0x32,0xa1,0xa1,0x68,0x04,0x2d,0xe0,0x3c, -0xd1,0x52,0xb4,0x86,0x8e,0xd0,0x05,0x06,0x40,0xb6,0x18,0x08,0x43,0xe1,0x1a,0x71, -0xad,0x18,0x21,0xae,0x13,0xd7,0xc3,0x0c,0x98,0x29,0x66,0x89,0xd9,0xf0,0x22,0xcc, -0x85,0x97,0x60,0x1e,0xcc,0x87,0x05,0xb0,0x10,0x16,0xc1,0x62,0x58,0x22,0x96,0x8a, -0x65,0x62,0x13,0xe4,0xc0,0xc7,0x62,0x0b,0xec,0x82,0xdd,0xe2,0x4b,0xd8,0x03,0x5f, -0xc1,0x5e,0xf8,0x5a,0x1c,0x80,0x6f,0xe0,0x5b,0xf1,0x9d,0x08,0x4c,0xa7,0x5e,0x42, -0x0c,0x14,0x86,0x62,0x70,0x0a,0x94,0x83,0x8a,0x50,0x19,0xe2,0x21,0x01,0x2e,0x86, -0x4b,0xa0,0x33,0x74,0x81,0x2b,0xa0,0xb7,0xc8,0x86,0xc5,0xb0,0x04,0xb6,0xc2,0x36, -0xd8,0x0e,0x9f,0x89,0x1d,0xf0,0x39,0xec,0x14,0x5f,0xc0,0x2e,0xf8,0x52,0xec,0x11, -0xfb,0xe0,0x20,0x38,0xcf,0xf1,0xfb,0x74,0x03,0x65,0x07,0xcb,0x61,0x35,0xfc,0x08, -0x66,0x52,0x6e,0xbf,0x43,0x9c,0x0f,0x3e,0x34,0x13,0x73,0x7f,0x24,0xfd,0x50,0x02, -0x4e,0x85,0xb3,0x44,0x19,0x51,0x16,0x2a,0x43,0x15,0x48,0x83,0x9a,0x50,0x07,0xea, -0x89,0x0c,0x68,0x00,0x0d,0xa1,0x11,0x34,0x86,0x59,0xb0,0x1e,0xea,0xfe,0x44,0x3d, -0x80,0xf1,0x70,0x37,0xac,0x80,0x7d,0xf0,0xa3,0x99,0x20,0xfb,0x33,0xcf,0xe1,0x50, -0x0e,0xaa,0x43,0x32,0xa4,0x40,0x4b,0x68,0x05,0xd9,0x30,0x04,0x86,0xc2,0x61,0x28, -0xfa,0x0b,0xf7,0x44,0x28,0x0f,0xb5,0xa0,0xbe,0x68,0x00,0x17,0x43,0x0f,0xd1,0x13, -0x06,0x40,0xb6,0x18,0x08,0x8f,0xc0,0xa3,0xf0,0x18,0x4c,0x86,0x45,0xb0,0x0c,0x56, -0xc0,0x2a,0x78,0x07,0xd6,0xc1,0x06,0xf8,0x08,0x72,0xcc,0xc4,0x5c,0x27,0xe0,0x14, -0x80,0x42,0x50,0x11,0x2a,0x43,0x2d,0xa8,0x03,0x75,0xa1,0x3e,0xb4,0x84,0xd6,0x70, -0x29,0x8c,0x84,0x43,0x90,0x11,0x08,0x38,0x43,0xe0,0x27,0x31,0x32,0x18,0x70,0x1e, -0x86,0xc9,0xb0,0x16,0xb6,0x08,0xf3,0xb1,0x45,0x59,0x88,0x83,0x0c,0x68,0x20,0x32, -0xa1,0x19,0x34,0x17,0xad,0xe1,0x2a,0x18,0x0a,0xd7,0xc0,0x48,0x78,0x04,0x26,0xc3, -0x6b,0xb0,0x12,0xde,0x81,0x77,0xe1,0x7d,0xf3,0x01,0x47,0x64,0xc0,0x69,0x05,0xad, -0xe1,0x11,0x98,0x0c,0xd3,0x60,0x26,0xac,0x87,0x8d,0xf0,0xa3,0xf9,0xc0,0x2e,0x14, -0x70,0x2a,0x41,0x02,0x74,0x87,0x6c,0xb8,0x06,0x46,0xc0,0xad,0x70,0x3b,0xdc,0x0d, -0xf7,0xc2,0x44,0xb8,0x1f,0xa6,0xc0,0x13,0x30,0x0b,0xe6,0xc0,0x02,0x78,0x05,0x5e, -0x85,0x25,0x70,0xc0,0x7c,0xf0,0x11,0x15,0x70,0xd2,0xa2,0xc9,0x13,0xb4,0x83,0x2e, -0xd0,0x0b,0x46,0xc2,0x58,0xb8,0x19,0x66,0xc2,0x6c,0x78,0xd9,0x7c,0x00,0x92,0x2f, -0xe0,0x84,0x20,0x9f,0xc8,0x0f,0xa9,0x50,0x03,0x6a,0x42,0x1d,0x51,0x1f,0xda,0x41, -0x17,0x18,0x0a,0x23,0xe1,0x51,0xd8,0x02,0x5f,0xc3,0x37,0xf0,0xad,0xf9,0x20,0x30, -0x26,0xe0,0x94,0x82,0x72,0x90,0x0e,0x19,0xd0,0x11,0x46,0xc2,0x3c,0x58,0x04,0x8b, -0xcd,0x07,0x27,0xf9,0x5d,0x02,0x10,0x01,0x21,0x88,0x82,0x82,0x50,0x04,0x8a,0x42, -0x09,0x28,0x05,0xa7,0xc2,0xe9,0x90,0x0a,0x35,0xa1,0x16,0xd4,0x17,0x5d,0x60,0x04, -0x8c,0x84,0x87,0x61,0x09,0xac,0x80,0x37,0x61,0x3b,0x7c,0x06,0x3b,0xcc,0xb9,0x0a, -0x70,0x3c,0x64,0x40,0x3b,0xe8,0x02,0x83,0x60,0x24,0xdc,0x95,0xfb,0xe1,0x4b,0xc0, -0x69,0x0a,0x23,0x61,0x36,0x2c,0x81,0xaf,0xcd,0x07,0x8d,0x85,0x02,0x4e,0x2c,0x9c, -0x0d,0x95,0x20,0x01,0xd2,0x21,0x03,0x9a,0x41,0x73,0x68,0x09,0xe7,0x8b,0x56,0xa2, -0x35,0xf4,0x80,0xde,0xd0,0x0f,0x06,0x88,0x6c,0x18,0x0b,0x23,0x0b,0x53,0x2f,0x60, -0x3a,0x3c,0x07,0x33,0x61,0x16,0x2c,0x83,0xd7,0xe1,0x0d,0xb1,0x1c,0x56,0xc0,0x21, -0xf8,0xc5,0x7c,0x48,0x59,0x24,0xe0,0x9c,0x09,0x95,0x44,0x02,0x64,0x41,0x63,0x68, -0x0d,0xd9,0x30,0x0a,0x46,0xc3,0x58,0x98,0x09,0xaf,0xc3,0x16,0xf8,0xce,0x7c,0xc0, -0x53,0xd4,0x25,0x20,0x82,0x22,0x02,0x6a,0x40,0x4d,0x68,0x0c,0x3d,0x61,0x00,0x64, -0x8b,0x81,0x30,0x08,0x06,0xc3,0x10,0xb8,0x4a,0xdc,0x00,0xa3,0x60,0xb4,0x18,0x03, -0x33,0x60,0x26,0xcc,0x86,0x39,0xf0,0x12,0xcc,0x83,0xf9,0xb0,0x40,0x63,0xbc,0xcb, -0xc4,0x5a,0xd8,0x09,0xfb,0xe0,0xa0,0x49,0x5b,0x31,0xd2,0x03,0x11,0x50,0x51,0xe3, -0xbf,0x55,0xa1,0x9a,0x88,0x83,0x14,0x48,0x83,0xfa,0xd0,0x48,0x64,0x41,0x63,0x68, -0x22,0x5a,0xc3,0x20,0x18,0x2c,0x86,0x8a,0x91,0x30,0x0a,0x46,0x8b,0x31,0x30,0x1b, -0xe6,0xc0,0x5c,0x78,0x09,0x16,0xc1,0x62,0x58,0x02,0x4b,0xe1,0x75,0x78,0x13,0xde, -0x82,0xb7,0xc5,0x3b,0x62,0x2d,0x7c,0x08,0x1f,0x89,0x1c,0x61,0x3e,0x56,0x2d,0x06, -0x25,0xa0,0x2a,0x54,0x83,0x78,0xa8,0x0e,0x89,0x90,0x04,0xc9,0x90,0x22,0x52,0x45, -0x1a,0xd4,0x80,0x7a,0xa2,0x3e,0x64,0x40,0x03,0x31,0x12,0x6e,0x82,0x71,0xe2,0x56, -0xb8,0x03,0xc6,0xc3,0x23,0xf0,0x18,0x4c,0x85,0x99,0xf0,0x09,0x6c,0x16,0x5b,0x60, -0x2b,0x6c,0x83,0x5d,0xb0,0x0f,0x0e,0x9a,0x0f,0x6a,0x4b,0x50,0x0f,0x20,0x08,0x11, -0x10,0x82,0x82,0x50,0x04,0x8a,0x42,0x09,0xa8,0x0c,0x55,0x20,0x01,0x92,0x20,0x19, -0x52,0x21,0x1d,0x6a,0x43,0x1d,0xa8,0x2b,0xcc,0x38,0x7d,0x7d,0xc8,0x10,0x0d,0xa0, -0x11,0x34,0x81,0xa6,0x1a,0xc3,0x6f,0x09,0xad,0x45,0x07,0x71,0x29,0x74,0x85,0x6e, -0xd0,0x1d,0x7a,0x42,0x5f,0xc8,0x86,0x21,0x30,0x12,0x6e,0x81,0xdb,0xc4,0x9d,0x62, -0x02,0xcc,0x85,0x79,0x62,0x3e,0xbc,0x0c,0xaf,0xc0,0x12,0x58,0x26,0xde,0x10,0x2b, -0x60,0x15,0xbc,0x05,0x6b,0xe0,0x6d,0xf1,0x8e,0x58,0x2b,0xde,0x15,0xeb,0xc4,0x7a, -0xf1,0x29,0x6c,0x35,0x1f,0xb0,0x95,0xe4,0xba,0x41,0x2a,0xd4,0x80,0x9a,0x50,0x1f, -0x32,0xa0,0x01,0x64,0x42,0x23,0xc8,0x12,0x8d,0x45,0x13,0x68,0x0e,0xad,0xa1,0x23, -0x5c,0x26,0x3a,0x43,0x57,0x18,0x69,0xe6,0x30,0x94,0x74,0xe7,0x37,0xcc,0x86,0x39, -0x30,0x1f,0x16,0x88,0x97,0xad,0x39,0x0f,0x66,0xbe,0xc3,0x62,0x58,0x02,0x4b,0xc5, -0x32,0x78,0x0d,0x5e,0x87,0x37,0x60,0x85,0x58,0x0b,0x1f,0x9a,0xf8,0x4b,0x05,0x9c, -0x17,0x34,0x3f,0x62,0x16,0xcc,0x86,0xb9,0x30,0x5f,0xf3,0x25,0x5e,0x85,0x85,0xb0, -0x48,0x2c,0x86,0x25,0xb0,0x11,0x36,0x41,0x0e,0x7c,0x6c,0x3e,0xdc,0x3b,0x85,0xba, -0x0c,0x09,0x90,0x04,0xc9,0x50,0x0b,0x6a,0x43,0x1d,0xa8,0x2b,0xea,0x89,0xfa,0x90, -0x01,0x8d,0x44,0x6b,0xe8,0x08,0x23,0xe1,0x59,0x98,0x2e,0x9e,0x13,0xcf,0x8b,0x17, -0x60,0x06,0xcc,0x84,0xb9,0xf0,0x92,0x98,0x27,0xe6,0x8b,0x25,0xf0,0x26,0xac,0x85, -0x6d,0xe6,0xc3,0xf0,0x53,0x03,0xce,0x19,0x70,0x96,0x28,0x23,0xca,0x8a,0x72,0x50, -0x1e,0x2a,0xc0,0x39,0x50,0x51,0x54,0x82,0xaa,0x90,0x00,0xe9,0x90,0x01,0x8d,0xcd, -0x07,0x8a,0xa7,0xe1,0x0f,0xd5,0x20,0x1e,0xaa,0x43,0x0d,0xa8,0x29,0xd2,0xa1,0x16, -0x4c,0x86,0xcd,0xb0,0x05,0xbe,0x80,0x5f,0x20,0xea,0xf4,0x80,0x13,0x23,0x0a,0x42, -0x09,0x28,0x05,0xa7,0xc0,0x69,0x50,0xfd,0x74,0x77,0x9e,0x4a,0x2a,0xd4,0xd0,0x7c, -0x95,0xda,0x50,0x07,0xea,0x8a,0x7a,0xa2,0xbe,0xc8,0x10,0x0d,0x44,0xa6,0x68,0x28, -0x5a,0x43,0x47,0x98,0x0c,0xcf,0xc0,0xb3,0xb0,0x16,0xde,0x85,0xf5,0xf0,0x1e,0x6c, -0x80,0x8f,0x60,0x13,0xe4,0xc0,0x66,0xd8,0x22,0x3e,0x15,0xdb,0xc4,0x76,0x91,0xfb, -0x71,0x3d,0x04,0x20,0x3f,0x14,0x80,0x24,0x48,0x86,0x9a,0x90,0x2e,0x6a,0x89,0xda, -0x50,0x0f,0x9a,0x88,0xd6,0xa2,0x0d,0xb4,0x87,0x0e,0x70,0x11,0x74,0x84,0x4e,0x70, -0x09,0xdc,0x02,0xb7,0xc2,0x7d,0x70,0xbf,0x78,0x00,0x26,0xc1,0x23,0x62,0x26,0xfc, -0x00,0x5d,0x4a,0xbb,0x74,0x15,0xdd,0xe0,0x72,0xe8,0x21,0x7a,0x8a,0x5e,0x62,0x09, -0x6c,0x81,0x7d,0x70,0xd0,0x7c,0x60,0x7a,0x26,0xcf,0x3d,0x90,0x1f,0xe2,0xa1,0xba, -0x48,0x80,0x34,0xa8,0x09,0x75,0xa1,0x9e,0xa8,0x2f,0x32,0x44,0x6b,0xe8,0x08,0x83, -0x60,0x3c,0xdc,0x0d,0xcf,0xc0,0x34,0xf1,0x2c,0xcc,0x84,0x59,0x62,0x36,0xcc,0x81, -0x17,0xc5,0x5c,0x78,0xc9,0x2c,0x30,0x70,0x16,0xf5,0x04,0xf2,0x41,0x0c,0x14,0x80, -0x04,0x48,0x84,0x34,0xa8,0x25,0xea,0x40,0x5d,0xa8,0x0f,0x59,0xd0,0x58,0x34,0x11, -0xad,0xa1,0x23,0x74,0x81,0x1e,0xd0,0x0b,0xae,0x80,0x2b,0xe1,0x16,0xb8,0x15,0xee, -0x84,0x09,0x70,0x17,0xdc,0x03,0xf7,0xc2,0x44,0x71,0x9f,0xb8,0x5f,0x3c,0x20,0x26, -0xc3,0x34,0x98,0x09,0x1b,0xe1,0x43,0xf1,0x11,0x6c,0x82,0x2d,0xf0,0x85,0xd1,0x32, -0x3c,0x37,0xc1,0x01,0xf8,0x06,0xbe,0x85,0xef,0xcc,0x82,0x09,0x65,0xa9,0x33,0x10, -0x14,0x11,0x22,0x12,0x8a,0x42,0x71,0x48,0x86,0x14,0x48,0x85,0x34,0xa8,0x05,0xf5, -0xa0,0x3e,0x64,0x88,0x06,0x22,0x53,0xb4,0x86,0x8e,0x70,0xb1,0x98,0x29,0xcc,0xe2, -0x0c,0x93,0xcc,0x87,0xbc,0x67,0x07,0x9c,0xfe,0x30,0x12,0x1a,0x9e,0x43,0xbe,0xab, -0x73,0xed,0x73,0x3f,0x9c,0xe5,0x3a,0xa7,0x10,0xa7,0x68,0x00,0x8d,0xa1,0x09,0xb4, -0x83,0x2e,0x70,0xc8,0x2c,0x4c,0xd0,0x08,0x7f,0xf3,0xa1,0x6a,0x57,0xfa,0x11,0x28, -0x03,0xe7,0x42,0x15,0xa8,0x06,0x71,0x50,0x1d,0x12,0x20,0xdd,0x7c,0xd0,0x79,0x05, -0x75,0xe6,0x4a,0xe2,0x84,0xcb,0xa0,0x0b,0xf4,0x86,0x6c,0x58,0x04,0x4b,0xe0,0x4d, -0x58,0x0b,0x7b,0x60,0x1f,0x7c,0x63,0x3e,0xb0,0xef,0x43,0x3c,0x90,0x00,0x69,0x90, -0x01,0x0d,0xa1,0x35,0x74,0x84,0xee,0x30,0x0c,0xae,0x83,0xf1,0x66,0x7f,0x3f,0xf2, -0x0f,0x0d,0xe1,0x4a,0xe8,0x03,0x7d,0x21,0x1b,0xae,0x86,0x8c,0xfe,0x3c,0x9b,0xc1, -0x64,0x98,0x0f,0xaf,0xc0,0x7a,0xf3,0xa1,0xfe,0x00,0xee,0x3f,0xd0,0x4a,0xb4,0x16, -0x6d,0xe0,0x66,0x18,0x0f,0x77,0xc3,0x3d,0xf0,0x18,0x6c,0x81,0x4f,0x61,0x9b,0xd8, -0x2e,0xf6,0xc1,0x7e,0xf8,0x1a,0x0e,0xc0,0x37,0xf0,0x9d,0xf9,0x60,0x34,0x9b,0xdf, -0x41,0xb7,0xd3,0xef,0x41,0x99,0x3b,0x28,0x77,0xf8,0x1a,0xf6,0xcd,0x20,0x1c,0x7c, -0x0b,0x3f,0xc2,0x4f,0xf0,0xb3,0x59,0x10,0x60,0x26,0x7d,0xf0,0x2c,0xfa,0x10,0xd1, -0x1a,0x2e,0x80,0x76,0xe2,0x72,0xe8,0x05,0xd9,0xf0,0xe3,0x6c,0x77,0xa2,0xdd,0x95, -0x90,0x0d,0x23,0x60,0x24,0x8c,0x83,0x09,0x30,0x09,0x1e,0x81,0x47,0x61,0xdf,0x5b, -0xb4,0x6f,0x30,0x8b,0x61,0xc4,0x41,0x02,0x34,0x86,0x1e,0xef,0xd2,0x1f,0x40,0x2f, -0xe8,0x0d,0xfd,0x60,0x10,0x5c,0x0b,0xa3,0x61,0x2c,0xdc,0x06,0xcf,0xc2,0xf3,0x90, -0xb9,0x8e,0xfb,0x95,0xf9,0x80,0xf8,0xbd,0x80,0x73,0x21,0xb4,0x87,0x87,0xe1,0x51, -0x78,0x0c,0x1e,0x17,0x4f,0xc1,0xd3,0x30,0x0d,0x9e,0x83,0x17,0x60,0x01,0xbc,0x22, -0x16,0xc2,0x6b,0xf0,0x06,0x84,0xde,0x0f,0x38,0xd1,0x90,0x1f,0x0a,0x41,0x49,0x38, -0x05,0xce,0x84,0x32,0x90,0x0e,0xb5,0xa1,0x1e,0x64,0x40,0x23,0x68,0x2c,0x9a,0x43, -0x6b,0xb8,0x00,0x9e,0xfa,0x80,0x67,0x3d,0x58,0x02,0xcb,0xe0,0x23,0xc8,0x81,0x43, -0x70,0x18,0x4a,0x6e,0x20,0x5e,0x48,0x81,0x34,0x38,0x1f,0x5a,0x43,0x7f,0xc8,0x86, -0x71,0x70,0x2b,0x4c,0x85,0x67,0x61,0x19,0xbc,0x0e,0xab,0xe1,0x6d,0xf8,0xc5,0x7c, -0xf8,0xf9,0x11,0xc7,0x42,0x6d,0xe8,0x0b,0x57,0x89,0x1b,0xc5,0x43,0xf0,0x18,0x4c, -0x81,0x19,0xe6,0x03,0xca,0xcd,0xf4,0x5f,0x90,0x5f,0x14,0x80,0x32,0x70,0x0e,0x54, -0x31,0x1f,0x84,0x6e,0xa1,0x9f,0x83,0x7c,0x70,0x1a,0x94,0x86,0xf2,0x10,0x0b,0x67, -0x43,0x45,0xa8,0x02,0x09,0xd0,0x0f,0xc6,0x0b,0xf3,0x31,0x60,0x35,0x48,0x80,0x34, -0xa8,0x01,0x75,0x21,0x03,0x9a,0xc1,0xf9,0x62,0xc2,0x56,0xae,0x1b,0xbc,0x20,0x96, -0xc0,0x6e,0xf8,0x12,0xf6,0xc2,0x3e,0x38,0x08,0x6b,0xb7,0xf3,0x1c,0x0c,0xbb,0xc5, -0x97,0xb0,0x17,0xf6,0xc1,0x41,0x58,0xfb,0x19,0xed,0x13,0xbe,0x82,0xbd,0xb0,0x4f, -0xec,0x87,0x43,0xb0,0x64,0x07,0xcf,0xd7,0xb0,0x05,0xb6,0xc2,0x36,0xb1,0x1d,0x3e, -0x83,0x1d,0xe2,0x73,0xd8,0x03,0x5f,0xc1,0x5e,0xd8,0x07,0xdf,0xc0,0xb7,0xe2,0x67, -0xf1,0x8b,0xd8,0xf2,0x39,0xc7,0xc1,0x4e,0xd8,0x0d,0x7b,0xe0,0x2b,0xd8,0x07,0x3f, -0x9b,0x05,0x0a,0x76,0x72,0x8d,0x60,0x2d,0x7c,0x60,0x16,0x6a,0xf9,0x82,0x3e,0x00, -0x1a,0x41,0x73,0x68,0x21,0x5a,0x43,0x47,0xf3,0xe1,0xff,0x57,0xf4,0xb3,0x10,0x82, -0xb2,0x50,0x1e,0x2a,0xc0,0xd9,0xa2,0x92,0x38,0x17,0x92,0x20,0x05,0x6a,0x40,0xba, -0xa8,0x2d,0x32,0x45,0x13,0xd1,0x4c,0xb4,0x10,0x2d,0xa1,0x15,0xb4,0x81,0x0b,0xe0, -0x42,0xd1,0x41,0x74,0x14,0x9d,0xc4,0xa5,0xa2,0xb3,0xe8,0x0a,0xdd,0xe0,0x72,0xd1, -0x0b,0xae,0x84,0xbe,0x30,0x08,0x86,0xc0,0x30,0xb8,0x1a,0x46,0xc0,0xf5,0x62,0x24, -0xdc,0x02,0xb7,0xc1,0x43,0x30,0x05,0x9e,0x80,0xa7,0x60,0x1a,0x4c,0x87,0x57,0x60, -0xdf,0x8f,0x5c,0x57,0xf3,0x21,0xb2,0x13,0x74,0x36,0x3f,0x1d,0x74,0x9c,0x67,0x82, -0xce,0x59,0xf3,0x83,0x4e,0x39,0x78,0xfe,0xed,0xa0,0x33,0x13,0xb6,0xec,0x0e,0x3a, -0xfb,0xe0,0x52,0x33,0x01,0xf7,0x07,0xf6,0x1f,0x72,0x27,0xe2,0x36,0x2f,0x11,0xc1, -0x6f,0x95,0x08,0xe7,0xea,0x94,0x88,0xdc,0x09,0x2d,0x7b,0xc1,0x9b,0x47,0x9c,0xd7, -0xfc,0xe1,0xff,0xd5,0xbc,0xe1,0xdf,0x3a,0x5f,0xf8,0x44,0xe7,0x09,0x1f,0x6f,0x7e, -0xb0,0x7f,0xde,0x6f,0x5e,0xf3,0x7d,0xbd,0xf9,0xbd,0xfe,0x79,0xbd,0xde,0x3c,0x5e, -0x6f,0xde,0x6e,0x5e,0xf3,0x75,0xbd,0x79,0xba,0xde,0xfc,0x5c,0x6f,0x5e,0xae,0x37, -0x1f,0xd7,0x3f,0x0f,0xd7,0x9b,0x7f,0xeb,0xcd,0xbb,0xf5,0xe6,0xdb,0x7a,0xf3,0x6c, -0xbd,0xf9,0xb5,0x79,0xcd,0xab,0xf5,0xcf,0xa7,0xf5,0xe6,0xcd,0x7a,0xf3,0x63,0xbd, -0x79,0xaf,0xde,0x7c,0x57,0xff,0xfc,0xd6,0x93,0x9d,0xcf,0xea,0xcd,0x63,0xf5,0xe6, -0xa7,0xfa,0xe7,0xa5,0xfa,0xe7,0xa1,0xfe,0xd6,0xf9,0xa6,0xfe,0xf9,0xa3,0xde,0x7c, -0xd1,0x93,0x9d,0x17,0xea,0xcd,0x07,0xf5,0xcf,0xef,0xf4,0xe6,0x73,0x9e,0xec,0xbc, -0x4d,0x6f,0xbe,0xa6,0x7f,0x9e,0xa5,0x37,0xaf,0xf2,0x8f,0x9e,0x4f,0xe9,0xcd,0x8f, -0x3c,0xde,0xbc,0x47,0x6f,0xbe,0x63,0x5e,0xf3,0x18,0xbd,0x79,0x8b,0x27,0x3a,0x4f, -0xd1,0x9b,0x9f,0xe8,0x9f,0x5f,0xe8,0xcd,0x27,0xcc,0x6b,0xde,0xa0,0x37,0x5f,0xd0, -0x3f,0x0f,0xd0,0x9b,0xff,0xe7,0xcd,0xf7,0x3b,0xd1,0xf9,0x7d,0xde,0x3c,0x3d,0x6f, -0x7e,0x9e,0x7f,0x5e,0xde,0xc9,0xce,0xc3,0xf3,0xe6,0xdf,0xe5,0x35,0xef,0xce,0x3f, -0xcf,0xce,0x3f,0x6f,0xce,0x9b,0x17,0xe7,0xcd,0x7f,0xf3,0xe6,0xaf,0x79,0xf3,0xd6, -0xbc,0x79,0x6a,0xde,0xfc,0x34,0x6f,0x5e,0x9a,0x37,0x1f,0xcd,0x9b,0x87,0xe6,0xcd, -0x2f,0xfb,0xbb,0xcd,0x1f,0xfb,0xa3,0xe7,0x8b,0x79,0xf3,0xc3,0xbc,0xf9,0x60,0xfe, -0x79,0x60,0xde,0xfc,0x2f,0xff,0x3c,0xae,0x93,0x9d,0x9f,0x95,0xd7,0xbc,0xac,0xe3, -0xcd,0xa7,0xf2,0xe6,0x4f,0x79,0xf3,0xa4,0xbc,0x79,0x4b,0xde,0x7c,0x24,0x6f,0x3e, -0x91,0x37,0x5f,0xc8,0x9b,0xff,0xe3,0xcd,0xfb,0xf1,0xe6,0xed,0x78,0xf3,0x71,0x4e, -0x74,0x1e,0x8e,0x37,0xcf,0xc6,0x9b,0x5f,0xe3,0xcd,0xab,0xf9,0xad,0xf3,0x68,0xfe, -0xaa,0xf3,0x67,0xf2,0x9a,0x27,0xf3,0x77,0x9f,0x0f,0x73,0xb2,0xf3,0x60,0xfe,0xa8, -0xf9,0x2f,0xc7,0x9b,0xf7,0x72,0xa2,0xf3,0x5c,0x8e,0x37,0xbf,0xe5,0x7f,0x35,0xaf, -0x25,0xaf,0xf9,0x2c,0x79,0xcd,0x5f,0xf1,0xcf,0x5b,0xf9,0xb3,0xe7,0xab,0x78,0xf3, -0x54,0xbc,0xf9,0x29,0xde,0xbc,0x14,0x6f,0xde,0x89,0x37,0xdf,0x24,0xaf,0xf9,0x24, -0xde,0xfc,0x11,0x6f,0xde,0x88,0x37,0x4f,0xc4,0x9b,0x17,0xe2,0xcd,0xf3,0xf0,0xe6, -0x77,0xf8,0xe7,0x75,0xf8,0xe7,0x73,0x78,0xf3,0x34,0xbc,0xf9,0x19,0xc7,0x9b,0x87, -0xe1,0xcd,0xb7,0xf0,0xe6,0x59,0x78,0xf3,0x2b,0xbc,0x79,0x15,0xde,0x7c,0x8a,0xe3, -0xcd,0xa3,0xf0,0xcf,0x97,0xf8,0x6f,0xcd,0x8f,0xf8,0xbd,0xf3,0x1b,0xfe,0x5b,0xf3, -0x1a,0xfc,0xf3,0x16,0xbc,0xf9,0x0a,0xde,0x3c,0x85,0xbf,0xca,0xfc,0x04,0xff,0xbc, -0x84,0x93,0x9d,0x8f,0x70,0xb2,0xf3,0x10,0xc2,0xf3,0x0f,0x8e,0x3d,0xff,0x20,0xaf, -0x79,0x06,0xc7,0x9b,0x57,0xf0,0x7b,0xe7,0x13,0x1c,0x6f,0xde,0x40,0x5e,0xf3,0x05, -0x8e,0x37,0x4f,0x20,0xaf,0xf9,0x01,0xde,0xbc,0x00,0xff,0x7c,0x00,0x6f,0xdc,0xdf, -0x1b,0xdf,0xf7,0xc6,0xf5,0xbd,0x71,0x7c,0x6f,0x7c,0xde,0x1b,0x8f,0xf7,0xc6,0xdb, -0xfd,0xe3,0xec,0xde,0xf8,0xba,0x37,0x9e,0xee,0x8d,0x9b,0x1f,0x6f,0x5c,0xdc,0x1b, -0xdf,0x3e,0xd9,0x71,0xed,0x93,0x1d,0xa7,0xf6,0xc6,0xa7,0xbd,0x71,0x67,0x6f,0xbc, -0xf9,0x44,0xc7,0x95,0xbd,0xf1,0x60,0x6f,0x1c,0xd8,0x1b,0xff,0xf5,0xc6,0x73,0xfd, -0xe3,0xb7,0xfe,0xf1,0x57,0x6f,0xdc,0xd5,0x1b,0x47,0xf5,0xc6,0x4f,0xbd,0xf1,0x50, -0x6f,0x1c,0xd4,0x1b,0xcf,0xf4,0xc6,0x2f,0xfd,0xe3,0x8f,0xde,0xf8,0xe2,0x89,0x8e, -0x2b,0x7a,0xe3,0x85,0xde,0x38,0xa1,0x7f,0x3c,0xd0,0x3f,0xce,0xe7,0x8d,0xef,0x79, -0xe3,0x7a,0xde,0x38,0x9e,0x37,0x6e,0xe7,0x8d,0xcf,0xf9,0xc7,0xe1,0xbc,0x71,0x35, -0xff,0x78,0x9a,0x37,0x4e,0xe6,0x8d,0x8f,0xe5,0x35,0xce,0xe5,0x8d,0x63,0xe5,0x35, -0x6e,0xe5,0x8d,0x43,0xe5,0x39,0xfe,0xa4,0x71,0x27,0x6f,0x7c,0xc9,0x3f,0xae,0x74, -0xb2,0xe3,0x42,0xde,0x78,0x50,0x5e,0xe3,0x40,0xfe,0x71,0x1e,0x6f,0x7c,0xc7,0x1b, -0xd7,0xf1,0xc6,0x73,0xbc,0x71,0x9c,0x13,0x1d,0xbf,0x39,0xde,0xb8,0x8d,0x37,0x5e, -0x93,0xd7,0xf8,0xcc,0x5f,0x6d,0x3c,0xe6,0xdf,0x36,0x6e,0x72,0xbc,0xf1,0x0f,0x6f, -0x5c,0xc3,0x1b,0xcf,0xf0,0xc6,0x31,0xfc,0xe3,0x17,0xde,0xb8,0x85,0x7f,0x9c,0xc2, -0x1b,0x97,0xf0,0xc6,0x23,0xfc,0xe3,0x10,0xde,0xf8,0x83,0x37,0xee,0xe0,0x8d,0x37, -0xfc,0xd6,0x71,0x06,0x6f,0x7c,0xc1,0x1b,0x57,0x08,0x8f,0x27,0xb8,0xe3,0x09,0xbf, -0x7b,0x1c,0xc1,0xac,0x3d,0x0b,0xf9,0xc1,0xfb,0x0c,0xbb,0x10,0x14,0x76,0x5f,0x65, -0x98,0x25,0x16,0x1d,0x7e,0x9e,0x3b,0xe6,0x27,0x70,0x2c,0x54,0x84,0xaa,0xee,0xcf, -0x61,0xf3,0x53,0xd7,0x89,0x07,0xb3,0xa6,0x49,0x2d,0xa8,0xad,0x75,0x4d,0x3a,0x69, -0x3c,0xe2,0x5a,0xb8,0x01,0xc6,0xc2,0x4d,0xc0,0x4f,0x3f,0x67,0x0a,0x3c,0x0e,0x4f, -0x6b,0x9c,0xc2,0x3c,0xc2,0x3f,0x0f,0x2f,0xc0,0x4c,0x98,0x0d,0x2f,0x6a,0xec,0xe2, -0x25,0x58,0xa0,0xf1,0x8b,0x57,0x34,0x86,0xb1,0x41,0x63,0x18,0xdf,0x6b,0x0c,0x63, -0x01,0x59,0x7a,0x05,0x96,0xc1,0x5a,0x58,0xa7,0x31,0x89,0xcf,0x34,0x0e,0xb1,0x57, -0x6b,0x98,0x64,0x5b,0xe3,0x10,0x66,0xfc,0xe1,0x7a,0x8d,0x3b,0xdc,0x68,0xad,0x53, -0x32,0xce,0x1a,0x73,0x30,0xe3,0x0d,0xdf,0x69,0xbc,0x61,0x8c,0xc6,0x1b,0x12,0x35, -0xc6,0x70,0x2b,0xdc,0x01,0xe3,0xb5,0x0e,0xc9,0x22,0xad,0x41,0xb2,0x44,0xeb,0x90, -0xbc,0xa6,0x75,0x48,0x96,0x5b,0x6b,0x90,0x98,0x71,0x08,0x27,0x8a,0x7f,0x90,0x0f, -0x62,0xa0,0x00,0x14,0x84,0x42,0x50,0x38,0xca,0x5d,0x9b,0xa4,0x34,0x94,0xd1,0x3a, -0x24,0x66,0x0d,0x92,0x2b,0xa1,0x0f,0xf4,0xb3,0xd6,0x1f,0x31,0x6b,0x8e,0x7c,0x0c, -0x9f,0x68,0xdd,0x91,0xcf,0xb4,0xde,0xc8,0x17,0x5a,0x6f,0xe4,0x2b,0xad,0x33,0x62, -0xc6,0x2c,0x8a,0x58,0xeb,0x89,0x24,0x68,0x9c,0xe2,0x69,0x6b,0xed,0x90,0xdd,0x1a, -0xa3,0xf8,0xce,0x5a,0x27,0xe4,0xe7,0x68,0x77,0x7d,0x10,0x6f,0x5d,0x10,0x6f,0x3d, -0x10,0x6f,0x1d,0x90,0x04,0x8d,0x53,0x98,0x35,0x40,0x2e,0xd3,0x58,0x85,0x19,0x97, -0x78,0x09,0xd6,0xc3,0x56,0xad,0xef,0x11,0x61,0xad,0xe5,0xe1,0xad,0xe1,0xd1,0x40, -0x6b,0x76,0x78,0x6b,0x75,0xb4,0xd1,0x58,0x85,0x59,0x97,0xe3,0x72,0x6b,0xed,0x8d, -0xb1,0x1a,0xa3,0xb8,0x47,0x63,0x13,0xde,0x98,0x84,0xb7,0xb6,0xc6,0x52,0xad,0xa5, -0xb1,0xda,0x5a,0x3f,0xc3,0x5b,0x37,0x63,0xb3,0xd6,0xcb,0x30,0x6b,0x65,0x7c,0x0d, -0xdf,0xc0,0x8f,0xd6,0x3a,0x19,0x01,0x6b,0x6d,0x8c,0x22,0x1a,0xa3,0xa8,0xa2,0xb1, -0x89,0x54,0x8d,0x49,0x78,0x6b,0x5f,0x34,0xd0,0x9a,0x17,0x2d,0xac,0x75,0x2e,0xbc, -0xf5,0x2d,0xb2,0x35,0x4e,0x61,0xd6,0xb3,0x18,0xaa,0x35,0x2d,0xbc,0xb5,0x2c,0xc6, -0x6b,0xac,0xe2,0x59,0x8d,0x51,0xcc,0xb5,0xd6,0xab,0x58,0xaa,0xf5,0x29,0xbc,0x75, -0x29,0xd6,0x58,0x63,0x15,0x5b,0xb5,0x06,0xc5,0x7e,0x6b,0xfd,0x09,0x6f,0xdd,0x89, -0x90,0xc6,0x2d,0x4a,0x68,0xbc,0x22,0x49,0xe3,0x14,0xde,0xba,0x12,0xf5,0xad,0x35, -0x24,0x9a,0x68,0xed,0x08,0x6f,0xcd,0x08,0x6f,0xad,0x88,0xce,0x5a,0x23,0xa2,0xa7, -0xb5,0x1e,0xc4,0x58,0x8d,0x5b,0xdc,0xad,0xf1,0x0a,0x6f,0x9c,0xe2,0x09,0x8d,0x4f, -0xbc,0xa0,0x75,0x1e,0xbc,0xf5,0x1d,0x96,0x6b,0x5d,0x87,0x35,0xd6,0x5a,0x0e,0x66, -0x1d,0x87,0x03,0x70,0x10,0x0e,0x15,0x38,0xb2,0x96,0x83,0xb7,0x86,0x43,0x61,0x8d, -0x61,0x54,0xb1,0xd6,0x69,0x68,0xa0,0xf5,0x19,0x9a,0x6b,0x5d,0x86,0x8b,0x34,0x7e, -0xd1,0x4d,0xeb,0x2f,0x0c,0x83,0xe1,0x70,0x83,0xb5,0xf6,0xc2,0x9d,0x1a,0xc3,0x78, -0x56,0x63,0x17,0xde,0xda,0x0a,0xcb,0xb5,0x66,0xc2,0x5b,0x5a,0x2b,0xc1,0x1b,0xc3, -0xd8,0xaa,0xb5,0x11,0xf6,0xab,0x63,0x0b,0x6a,0x0c,0xa3,0xb8,0xd6,0x3c,0xa8,0xab, -0x35,0x0e,0x1a,0x6b,0x6d,0x83,0x96,0xd6,0x38,0x46,0x37,0xad,0x5b,0xe0,0xad,0x53, -0x30,0x56,0xe3,0x17,0x73,0xac,0x31,0x0b,0x6f,0x2d,0x82,0x75,0xd6,0xfa,0x03,0x3b, -0xb4,0xee,0x40,0xc0,0x5a,0x6b,0xc0,0xac,0x33,0x50,0x5f,0xe3,0x19,0x66,0x6d,0x81, -0x56,0x1a,0xcb,0xf0,0xc6,0x30,0x6e,0xb7,0xc6,0x2d,0xbc,0x75,0x03,0x5e,0xb4,0xc6, -0x2c,0xbc,0x35,0x02,0xd6,0x6a,0xcc,0xc2,0x5b,0x13,0xe0,0x0c,0xad,0x03,0x90,0xa6, -0x75,0x00,0x6a,0x6a,0x1d,0x80,0x5a,0x5a,0x0b,0xa0,0x99,0xbe,0xfd,0xf7,0xbe,0xf9, -0x1f,0xab,0x6f,0xfe,0xc7,0xe9,0x5b,0x7f,0xf3,0x9d,0xff,0x22,0x7d,0xe3,0xbf,0x02, -0xde,0xd6,0x58,0x47,0x9c,0xf5,0x5d,0xbf,0xf7,0x3d,0x7f,0x6d,0x7d,0xc7,0x5f,0x5f, -0xdf,0xe9,0x5f,0xac,0xef,0xf3,0xbb,0xea,0xbb,0xfb,0xab,0xac,0x6f,0xed,0xc7,0xea, -0x1b,0x7b,0xef,0xdb,0x7a,0xf3,0xed,0xfc,0xa3,0xd6,0x98,0x87,0x19,0xef,0x68,0xae, -0xf1,0x0c,0x6f,0x1c,0xa3,0x8b,0xc6,0x2f,0x26,0x68,0xdc,0x62,0xbe,0x35,0x56,0xb1, -0x52,0x63,0x14,0xc5,0x35,0x36,0x61,0xbe,0x6b,0xef,0xa2,0xf1,0x89,0x09,0x1a,0x9f, -0x30,0x63,0x13,0x4e,0x49,0x77,0x6c,0x62,0xa4,0xc6,0x24,0x1e,0xd2,0x98,0x84,0x19, -0x7f,0x28,0xac,0xef,0xd5,0xcb,0xe9,0xfb,0xf4,0x54,0x8d,0x43,0x5c,0xa0,0x71,0x88, -0xfe,0xff,0x57,0xd9,0xb9,0x40,0x47,0x59,0x98,0x69,0x78,0x26,0x4c,0x92,0x49,0xc2, -0x25,0x56,0x11,0xaf,0x88,0x82,0x02,0xa2,0x24,0x87,0x84,0x8b,0x5c,0xe3,0x0a,0xca, -0xd9,0x2e,0x27,0x41,0x2b,0x95,0x65,0x95,0xb8,0x8a,0x56,0x6a,0x0b,0xd5,0x54,0xad, -0x5a,0x8c,0xa0,0x45,0x50,0x2c,0xa7,0xab,0xed,0xd1,0xe2,0x82,0x6b,0xbd,0x50,0x45, -0xc2,0xa2,0xd6,0xae,0x0a,0x51,0xcb,0x6a,0xab,0x14,0x14,0xad,0xbb,0x5a,0x05,0xb4, -0xed,0x52,0x95,0xca,0x4d,0x91,0x9b,0xd9,0xf7,0x9b,0xff,0xf9,0x92,0x2f,0x63,0x50, -0x3b,0x39,0x6f,0x12,0x26,0x21,0x33,0xf9,0x33,0x13,0x7e,0xde,0xef,0x7d,0x9f,0x8f, -0x1e,0x7a,0x23,0xfd,0x73,0xef,0x9d,0xaf,0x0a,0x5d,0x73,0xeb,0x99,0xbf,0x26,0xbd, -0x15,0xfa,0xe5,0xd6,0x2d,0xdf,0x26,0xa5,0x8e,0x48,0xfa,0xe5,0x5d,0xe9,0x95,0xf7, -0x62,0x3e,0x71,0x33,0x73,0x89,0xa5,0x61,0x26,0x91,0xa2,0x23,0xde,0x9b,0x6e,0x78, -0x7f,0x3a,0xe1,0xde,0x05,0xb7,0x1e,0x78,0x8d,0x34,0x96,0x2e,0xf8,0x4c,0x66,0x15, -0x4d,0x74,0xbe,0xdf,0x61,0x56,0xd1,0x83,0x8e,0xb7,0x75,0xbb,0x7b,0x86,0x2e,0xf7, -0x79,0xa1,0xbf,0xed,0xbd,0xed,0x69,0xf4,0xb5,0xaf,0x0c,0x1d,0x6d,0xeb,0x67,0x2f, -0xa1,0x97,0x9d,0xa2,0x7b,0x5d,0x1d,0xba,0xd6,0x23,0x42,0xbf,0xda,0x7b,0xd5,0x75, -0xf4,0xa8,0x1b,0xe8,0x51,0xcf,0xa6,0x2f,0xfd,0x00,0x3d,0x69,0xef,0x47,0x3f,0x1a, -0x3a,0xd0,0x5b,0xe8,0x3e,0x6f,0x0d,0x7d,0x67,0xeb,0x3a,0xef,0x3f,0x3a,0xe9,0x36, -0x57,0xd3,0x69,0x1e,0xc1,0xec,0x64,0x21,0xb3,0x11,0xeb,0x27,0x6f,0xa0,0x9f,0xec, -0xbd,0xe4,0xbf,0x86,0x2e,0xb2,0x77,0x90,0x3f,0x0d,0x73,0x12,0xeb,0x10,0xef,0x63, -0x06,0x72,0x04,0xb3,0x8f,0xf1,0xcc,0x3c,0x26,0x87,0x39,0xc7,0x54,0xe6,0x1b,0x36, -0xdb,0x78,0x86,0xb9,0xc6,0x6a,0x66,0x1b,0x36,0xd7,0x58,0xcb,0x5c,0xc3,0x66,0x1a, -0x6f,0x33,0xd3,0xd8,0xca,0x4c,0xc3,0xe6,0x19,0x07,0x38,0x39,0x2a,0x93,0xba,0x4a, -0xdd,0xa4,0x72,0xa9,0x9f,0xd4,0x5f,0x3a,0x59,0x1a,0x20,0x9d,0x22,0x9d,0x2a,0x0d, -0x94,0x2a,0xa4,0x4a,0x69,0xb0,0x34,0x56,0x1a,0x27,0x4d,0x95,0xea,0xa5,0x4b,0xa4, -0x4b,0xa5,0x6f,0x49,0x97,0x49,0xd3,0xa5,0x99,0xcc,0x4b,0x1a,0xa4,0x6b,0xa5,0xeb, -0x99,0x9b,0x34,0x4a,0xf3,0xa5,0xdb,0x98,0xa1,0x2c,0xa1,0x6b,0x9c,0x62,0x8e,0xd2, -0x89,0x39,0x4a,0x96,0x59,0xca,0x61,0xcc,0x51,0x0e,0x67,0x86,0xd2,0x93,0xf9,0xc9, -0x89,0xcc,0x4f,0xfa,0x32,0x3f,0xe9,0xcf,0x0c,0xc5,0x67,0x27,0xc3,0x99,0x95,0xd4, -0x30,0x2b,0xf9,0x47,0xe6,0x24,0x75,0xcc,0x4a,0xe6,0x49,0x0b,0xa5,0xaf,0x9d,0xa0, -0x7f,0x97,0xa4,0xc3,0xa4,0x21,0x3a,0x51,0xbc,0x4e,0xba,0x53,0xfa,0xa9,0x54,0xd3, -0x47,0x9f,0x2b,0xdd,0x22,0x2d,0x92,0xde,0x97,0x1e,0xd1,0x89,0xe4,0x32,0x3b,0x99, -0xec,0x27,0xf5,0xd7,0xbf,0x9f,0x3a,0xa9,0xfc,0x19,0x27,0x96,0x95,0x52,0xbd,0xf4, -0x67,0xe6,0x2b,0x1f,0x31,0x5f,0xd9,0xc3,0x49,0x67,0xdf,0x30,0x53,0x99,0x11,0xfa, -0xc4,0x4b,0x98,0xa3,0x34,0x31,0x3f,0x69,0x66,0x6e,0xb2,0x9e,0x79,0xc9,0x26,0x4e, -0x58,0x1b,0xa5,0x9f,0xdb,0x89,0x6b,0x85,0x9e,0xb7,0x15,0xc9,0x09,0x6c,0x9a,0x39, -0x4a,0x96,0xd9,0xc9,0xc9,0x74,0x85,0x2b,0x99,0xa1,0x0c,0x61,0x86,0x32,0x8a,0x99, -0xc9,0x5d,0xcc,0x4c,0x6c,0x5e,0xb2,0x84,0x39,0x89,0xf7,0x7f,0x0b,0x99,0x8b,0x2c, -0x94,0x9a,0x99,0x89,0x1c,0x3b,0x48,0x0f,0x15,0xa9,0x4e,0xaa,0x97,0xae,0x97,0x6e, -0x90,0x56,0x48,0xcd,0xd2,0xcb,0xd2,0x7a,0xe9,0xea,0x2a,0x1d,0x3b,0xe9,0x1d,0x69, -0x93,0xd4,0x52,0x95,0xcc,0x52,0x9a,0x99,0xa5,0xd8,0x49,0xf4,0x42,0xe6,0x27,0x5d, -0x98,0x93,0xd4,0xd0,0xed,0xbd,0x92,0x7e,0xef,0x2c,0xe6,0x22,0xff,0xce,0x3c,0xc4, -0xba,0xbb,0x3b,0xec,0x84,0x9b,0x39,0x88,0xcd,0x3b,0xe6,0x49,0xcf,0x31,0xd7,0xf0, -0x7e,0xad,0xf7,0x6a,0xbd,0x4f,0x7b,0x22,0xdd,0xd9,0x7e,0x74,0x67,0x2b,0xa5,0x61, -0xcc,0x32,0x1a,0xe8,0xd0,0x5a,0x5f,0xf6,0xf7,0xf4,0x64,0x77,0x84,0x2e,0xac,0xf5, -0x5f,0x07,0xd2,0x7b,0xb5,0xce,0xeb,0x54,0xba,0xae,0x73,0x42,0xaf,0xf5,0x09,0xfa, -0xac,0x4f,0xd3,0x63,0xb5,0xb9,0xc6,0x3b,0xa1,0xaf,0x9a,0xa2,0x8f,0x5a,0x41,0x0f, -0xb5,0x8a,0xfe,0x69,0x4d,0xe8,0x9c,0xfe,0x53,0xe8,0x99,0xfe,0x4b,0xe8,0x8e,0x36, -0x85,0x9e,0xe8,0xe3,0xf4,0x43,0x7f,0x4d,0x2f,0xb4,0x39,0x74,0x41,0xdf,0xa2,0xeb, -0xf9,0xb7,0xd0,0xe3,0x2c,0x61,0x3e,0xd1,0x8b,0xb9,0x84,0xcd,0x24,0xa6,0x33,0x7b, -0xf0,0x0e,0xa6,0x77,0x2f,0xbd,0x6b,0x69,0x73,0x88,0x26,0xe6,0x0f,0xf6,0x1f,0x94, -0x99,0xcc,0x1c,0x0e,0x0d,0x3d,0x4a,0x9b,0x35,0xf4,0x67,0xd6,0x30,0x2c,0xcc,0x17, -0xce,0x60,0xae,0x50,0xc7,0x5c,0x61,0x34,0x73,0x85,0x9f,0x30,0x4f,0x38,0x40,0x4f, -0xb2,0x9c,0x9e,0x64,0xa5,0x54,0x27,0x4d,0x94,0xce,0x96,0xbe,0x21,0x9d,0x2b,0x4d, -0x92,0xa6,0x4a,0xf5,0xd2,0xbf,0x4a,0x17,0x4b,0xdf,0x92,0x2e,0x93,0xbe,0x4d,0x97, -0xd2,0xe6,0x11,0x2d,0x52,0xba,0x45,0x3f,0x73,0xa9,0x48,0x2a,0x93,0x3a,0x4b,0x5d, -0xa4,0xae,0x2d,0x49,0xc7,0xf2,0x28,0xe9,0x68,0x7a,0x96,0x23,0x98,0x5b,0x4c,0x61, -0x6e,0xf1,0x1c,0xf3,0x88,0x57,0x99,0x43,0x6c,0x92,0xde,0x95,0xfe,0x2c,0x6d,0x91, -0xf6,0x30,0x97,0xe8,0xc2,0x3c,0x62,0x24,0x73,0x88,0x3a,0xe6,0x0f,0xb6,0x68,0x2a, -0x2d,0x15,0x48,0xc5,0xd2,0xd0,0x74,0x32,0x8f,0x58,0x20,0x2d,0x94,0x96,0x48,0xeb, -0x43,0x6f,0x72,0x09,0x5d,0xc9,0xcd,0xcc,0x27,0x4e,0x65,0xfe,0x70,0x15,0xf3,0x87, -0xc5,0xcc,0x1d,0x52,0xf4,0x1c,0x9b,0x98,0x2f,0xa4,0x98,0x2b,0xcc,0x60,0x1e,0x50, -0xc3,0x1c,0x20,0x15,0x3c,0xfe,0xa1,0xc1,0xd7,0xff,0xa6,0xf4,0x20,0x5e,0xbe,0xf9, -0xf8,0xfb,0xa4,0xe3,0xf0,0xf0,0xc7,0xe0,0xdd,0x3f,0x2d,0xbd,0x5a,0x92,0xf4,0x05, -0x0b,0xe9,0x09,0x96,0xe3,0xdb,0x1f,0x49,0x2f,0xd0,0xfa,0x80,0x35,0x52,0x1d,0xfe, -0x7d,0x33,0xfd,0xbf,0x0f,0xf0,0xeb,0x4f,0xc3,0xaf,0x3f,0x4f,0xba,0x46,0xba,0x4b, -0x5a,0x8a,0x57,0xdf,0x88,0x47,0xbf,0x17,0x8f,0xbe,0x0f,0x5d,0xbf,0xfa,0xae,0x89, -0xf7,0x6e,0x3d,0xbd,0x65,0xf8,0xef,0x29,0x7c,0x75,0xeb,0xdc,0x4d,0xc4,0x53,0xdf, -0xd4,0xad,0xad,0x57,0x57,0x40,0x8f,0xee,0x2c,0xe9,0x6c,0xba,0x74,0x37,0xd0,0x8f, -0x5b,0x49,0x17,0xce,0x7a,0x70,0x4f,0x49,0x6b,0xf1,0xd8,0xb7,0xd1,0x7d,0xeb,0x44, -0xe7,0xcd,0xbb,0x6e,0x43,0xf0,0xd8,0xad,0xc3,0xd6,0x40,0x7f,0x6d,0x36,0x3d,0xb5, -0xd5,0xf4,0xd2,0xd6,0x86,0x2e,0xda,0x66,0x3c,0xf6,0x43,0xe9,0x9a,0x0d,0x0a,0xfd, -0x32,0xeb,0x96,0x0d,0xa3,0x57,0xd6,0x18,0x7c,0xf6,0x1f,0xe3,0xaf,0x37,0x85,0xae, -0xd8,0x7b,0x74,0xc4,0x52,0x74,0xc3,0x0a,0xf1,0xda,0x0f,0xc5,0x63,0x1f,0x84,0xb7, -0x3e,0x02,0x5f,0xdd,0xbb,0x5e,0x67,0xd1,0xf1,0xaa,0x0b,0xbd,0xae,0x4b,0xe8,0x71, -0xa5,0xe8,0x49,0xd5,0xd0,0x8f,0x1a,0x17,0x3a,0x51,0xe7,0x87,0x1e,0x54,0x23,0xbd, -0xa7,0x5f,0x87,0xae,0xd3,0xea,0xd0,0x6f,0xfa,0x0d,0x7d,0xa6,0x46,0xfa,0x4b,0x4f, -0xd2,0x5b,0xf2,0xbe,0xd2,0xb3,0xf4,0x94,0x52,0xf4,0x92,0x46,0x84,0x2e,0x92,0xf5, -0x90,0x4e,0xa7,0x7f,0x54,0x8f,0xef,0xfe,0x70,0xe8,0x1c,0x3d,0x4a,0xd7,0xe8,0x89, -0xd0,0x2f,0x6a,0xc6,0x8f,0x3f,0x96,0xde,0xd0,0x09,0xa1,0x2b,0x54,0x89,0x37,0x5f, -0x11,0x7a,0x40,0x23,0xf0,0xe9,0xcd,0xa3,0x77,0x6f,0xbe,0x3b,0x9e,0xfc,0x50,0xba, -0x3d,0xa3,0x42,0x9f,0xc7,0xfa,0x3a,0x63,0xe9,0xec,0x2c,0xc1,0x9b,0x7f,0x8d,0x6e, -0xce,0x1f,0x43,0x1f,0xc7,0x7b,0x37,0xc5,0x52,0x09,0x1e,0x7d,0x15,0x7d,0x1b,0xeb, -0xd9,0x8c,0x09,0x1d,0x9b,0x89,0x74,0x6b,0x26,0xe3,0xd9,0xcf,0x0f,0x3d,0x9a,0xbb, -0xcd,0xaf,0x3f,0x2a,0xf1,0xea,0x4b,0xe9,0xba,0x0c,0xa3,0xdf,0x62,0x7d,0x96,0x99, -0xf4,0x58,0xbc,0xbf,0xe2,0xbd,0x15,0xef,0xab,0xa4,0xf0,0xef,0xcb,0xe8,0xa7,0x78, -0x2f,0x65,0x4c,0xe8,0xa2,0xd4,0xe1,0xe5,0x5f,0x8a,0x87,0xbf,0x90,0xae,0xc9,0x9d, -0xa1,0x5f,0xe2,0xbd,0x92,0x4d,0xf4,0x45,0xac,0x2b,0x62,0x1e,0x7d,0xb3,0xf4,0xba, -0xf4,0xb6,0xb4,0x59,0x6a,0x39,0x2e,0xf1,0xeb,0x67,0xe2,0xd7,0x9b,0x47,0x5f,0x59, -0x9d,0x78,0xf2,0xe6,0xc3,0xd7,0xd0,0xb3,0xf8,0x2e,0xfe,0xbb,0x75,0x2a,0x3e,0xc6, -0x83,0xb7,0x3e,0xc5,0x50,0x7a,0x14,0x53,0xf0,0xe1,0xcd,0x83,0xaf,0xc1,0x53,0xf7, -0x0e,0xc4,0x8f,0xf1,0xd4,0xcd,0x4f,0x7f,0x37,0x74,0x1d,0xb6,0xe1,0xa1,0xa7,0x6e, -0x91,0x16,0x24,0xfe,0x78,0x1d,0x3e,0xb8,0x79,0xe0,0x29,0xbc,0xef,0x46,0x3c,0xef, -0x45,0x74,0x10,0x16,0x4b,0x4b,0xcc,0xff,0xb6,0x25,0x6e,0xaf,0xa4,0x53,0xfd,0xe9, -0x1c,0x4c,0x97,0xae,0xa4,0x6f,0x30,0x87,0xbe,0xc1,0x6d,0xf4,0x0d,0x1e,0xb5,0xc5, -0x93,0xaf,0x26,0x9d,0x83,0x71,0xd2,0x26,0xeb,0x1d,0x6c,0xd0,0xf7,0xb6,0x21,0xf1, -0xd1,0x27,0xe1,0x9f,0xbb,0x6f,0xbe,0x14,0xbf,0xdc,0x7d,0x72,0xf3,0xc8,0x8b,0xf1, -0xc6,0x0f,0xc7,0x13,0x1f,0x81,0x17,0xee,0x1e,0xb8,0xf9,0xdf,0xe6,0x7d,0xbf,0x85, -0xe7,0xdd,0x1d,0xaf,0xbb,0x16,0x8f,0x7b,0x1e,0xde,0xf6,0xf3,0x78,0xda,0xd6,0x03, -0xc8,0x2d,0x4a,0x7a,0x53,0xc7,0x91,0x1e,0xc0,0x77,0xe8,0x00,0x5c,0x45,0x07,0xe0, -0x66,0x7a,0x00,0xd6,0x01,0x48,0x91,0xed,0x3f,0x9a,0x4c,0xff,0x49,0x78,0xdd,0x95, -0x78,0xdd,0x35,0xf8,0xdc,0xcd,0x64,0xf2,0x2d,0x8f,0xdf,0xf2,0x6e,0xe2,0x37,0xbf, -0x40,0xae,0x3d,0x45,0x9e,0xdd,0x73,0xec,0x17,0x48,0xdf,0xfb,0x50,0x8f,0xfd,0xad, -0x89,0xff,0x5c,0x88,0xef,0xdc,0x27,0x78,0xcd,0xd5,0xc1,0x5f,0xfe,0x87,0xe0,0x29, -0xbb,0x97,0x3c,0x31,0xf8,0xc7,0x93,0x83,0x67,0xec,0x5e,0xb1,0x7b,0xc4,0x97,0xe3, -0x0d,0xff,0x20,0xf8,0xc1,0xb7,0xe2,0x03,0xdf,0x8f,0xff,0xbb,0xcd,0xfc,0xdf,0x6d, -0xfa,0x9e,0xa4,0x25,0xd2,0x0a,0xe9,0x59,0xe9,0x15,0x5b,0xbc,0xb7,0x5d,0xcf,0x0b, -0xa9,0x5c,0xaa,0x90,0x2a,0xa5,0xe9,0xd2,0x4c,0x69,0x99,0xf4,0x17,0xfb,0xd8,0x0e, -0x1d,0x07,0xa9,0x4e,0xaa,0x97,0x52,0x3b,0xf5,0xb3,0xfe,0x44,0x5f,0x57,0x4a,0xed, -0xd6,0x6d,0x4a,0x9b,0x24,0x5b,0x90,0x5a,0x2e,0xd5,0x49,0xf5,0xd2,0x42,0xa9,0xc9, -0x96,0xa6,0xee,0x49,0xa7,0xae,0x95,0xd6,0x4a,0xf5,0x7b,0xf5,0xb5,0xa5,0x6b,0xa4, -0x46,0x69,0xa1,0xd4,0x24,0x35,0x4b,0xeb,0x6d,0xa1,0xd8,0xbe,0x74,0xea,0x8e,0x7d, -0x49,0xfe,0x3d,0xb7,0xf8,0xf7,0xc1,0x82,0x54,0xcd,0xaf,0x12,0xbf,0xda,0xbc,0x6a, -0xf3,0xa7,0xcd,0xa8,0x4d,0xa7,0xba,0xea,0xbf,0x54,0x5d,0x13,0xf3,0x24,0x95,0x98, -0x11,0xd9,0x83,0x78,0xd4,0x47,0x27,0xff,0xc5,0x6b,0xf5,0xa8,0x6d,0x5d,0xf1,0x89, -0xd2,0xc9,0x79,0x1e,0x75,0x05,0xcc,0x6d,0xf3,0xa8,0x6b,0xc8,0xcb,0xd7,0x93,0x97, -0x9f,0x25,0xdd,0x84,0x47,0xbd,0x38,0x78,0xd4,0xf7,0x27,0xa7,0xb1,0x39,0x8f,0xfa, -0x11,0x3c,0xea,0xe5,0xd2,0x0a,0x69,0x65,0xf0,0xa8,0x9f,0x0c,0x1e,0xf5,0x6a,0x32, -0xf6,0x6f,0x90,0xb1,0x37,0x8f,0x5a,0xdf,0x5e,0xea,0xbf,0xc8,0xcc,0xaf,0x23,0x33, -0xbf,0x91,0xcc,0xfc,0x56,0x3c,0xea,0x96,0x82,0x84,0xb1,0x6d,0x79,0xf9,0xef,0x93, -0x93,0xff,0x61,0xf0,0xa8,0x6f,0x0e,0x1e,0xb5,0x67,0xe3,0xef,0x25,0x0f,0x6f,0x1e, -0xf5,0xec,0x8c,0xce,0xe7,0xc9,0xc3,0x5b,0x16,0x7e,0x1e,0x1e,0xf5,0xed,0x78,0xd4, -0xcf,0xe4,0x79,0xd4,0xcf,0xe1,0x51,0xaf,0x09,0x1e,0xb5,0x65,0xe5,0x77,0x49,0x85, -0x45,0xfa,0x3f,0x00,0x1e,0x75,0x69,0x9e,0x47,0xdd,0x0d,0x76,0xf6,0x31,0x64,0xe7, -0xa7,0xc2,0xc8,0x36,0x8f,0xfa,0xf2,0xc0,0xc9,0x7e,0x1d,0x26,0xb6,0x7b,0xd4,0x7f, -0x22,0x4b,0xbf,0x05,0x8f,0x7a,0x2b,0x99,0x7a,0xe3,0x60,0x77,0x09,0xdc,0xeb,0x0a, -0x58,0xd7,0xf7,0x07,0xc6,0xf5,0xfb,0xf0,0xac,0x2d,0x43,0xbf,0x27,0x78,0xd4,0xdd, -0x03,0xbf,0xda,0xb9,0xd5,0xce,0xab,0x36,0x4e,0xf5,0x68,0x72,0xf4,0x53,0xf0,0xa8, -0x2d,0x4b,0xff,0x98,0xf4,0x02,0xfc,0xe9,0x77,0xe1,0x4f,0x9f,0x96,0xe7,0x51,0xd7, -0xc0,0x95,0x76,0xa6,0x74,0x1d,0xfc,0xe8,0x0b,0xe1,0x46,0x3b,0x23,0x7a,0x0e,0x39, -0xfa,0x85,0xe4,0xe7,0x3d,0x3b,0xef,0x0c,0xe8,0x66,0x78,0xcf,0x2f,0x06,0xce,0xb3, -0x7b,0xd4,0x6f,0x93,0x9d,0x7f,0x8f,0xec,0xfc,0x4e,0x69,0x2f,0x1e,0xf5,0x01,0x3c, -0x6a,0x67,0x38,0x97,0x92,0xa3,0xef,0x47,0x7e,0xbe,0x8a,0xdc,0xbc,0x33,0x9a,0x6b, -0xe0,0x32,0x8f,0x0f,0x3c,0x66,0xcf,0xd1,0xcf,0x80,0xbd,0xdc,0x10,0x3c,0x6a,0x67, -0x2e,0x2f,0x20,0x4f,0xff,0x10,0x39,0xfa,0x95,0x81,0xab,0xdc,0x0c,0x43,0xd9,0xf9, -0xc9,0x2f,0x07,0x8f,0x7a,0x33,0x9c,0xe4,0x6d,0xc1,0xa3,0x76,0x3e,0x72,0x27,0xb2, -0xf5,0xe5,0x64,0xea,0x2b,0xc9,0xd2,0x3b,0xff,0x78,0x74,0xf0,0xa8,0xc7,0xc2,0x37, -0x76,0xb6,0xb1,0x33,0x8d,0xcf,0x27,0x5f,0x6f,0x0c,0xe3,0xab,0x83,0x47,0x3d,0x9f, -0x5c,0xfd,0x9d,0x21,0x4f,0xbf,0x98,0x0c,0xfd,0x2f,0xc9,0xce,0x3b,0x87,0xf8,0x39, -0xd8,0xc3,0x2f,0xe7,0x79,0xd4,0x3b,0xa4,0x4f,0xf3,0x3c,0x6a,0x67,0x0d,0x77,0x26, -0x67,0xdf,0x2f,0xe4,0xeb,0x6b,0x60,0x08,0x8f,0x87,0x1d,0x3c,0x89,0xac,0xfd,0x85, -0x30,0x82,0x67,0xe0,0x51,0xcf,0x0a,0x8c,0xe0,0xdb,0xc8,0xd9,0x3f,0x44,0xbe,0xde, -0x19,0xc0,0xbf,0x81,0xeb,0xfb,0x12,0x3c,0xdf,0x3f,0xe0,0x51,0x6f,0x86,0xdf,0xfb, -0x11,0x39,0xfb,0x34,0x39,0xfb,0x72,0xf2,0xf5,0x23,0xe1,0xf0,0x8e,0x85,0xbf,0xeb, -0xec,0xdd,0x5a,0xf2,0xf5,0x17,0x05,0x9e,0xee,0x1c,0x32,0xf6,0x2b,0x42,0xb6,0xde, -0x99,0xb9,0xaf,0x04,0x4e,0xee,0x46,0xd8,0xb8,0xbb,0xba,0xb4,0x31,0x71,0xab,0xe0, -0xe0,0x8e,0x21,0x67,0x6f,0xec,0xdb,0x29,0x21,0x6b,0x3f,0x3f,0xe4,0xeb,0x9d,0x6f, -0xbb,0x32,0x30,0x6d,0x3d,0x53,0xbf,0x16,0x7e,0xad,0x65,0xea,0x7b,0xc0,0xac,0xad, -0x3e,0x88,0x47,0x3d,0x8a,0xac,0xfd,0xe5,0x81,0x4d,0x7b,0x13,0x1e,0xf5,0x5c,0x72, -0xf7,0x3f,0x83,0x43,0xbb,0x06,0x8f,0xfa,0x65,0xe9,0xcd,0x6e,0x09,0x83,0xd6,0xf9, -0xb3,0xce,0x9d,0x1d,0x0e,0x6b,0x76,0x34,0x2c,0xd9,0xc9,0x64,0xf3,0xeb,0xc9,0xe2, -0x37,0x04,0x26,0xec,0x4d,0x70,0x60,0x9d,0x01,0xeb,0x8c,0xd7,0x35,0xc1,0xa3,0x1e, -0x4f,0xe6,0xde,0xf3,0xf6,0xe7,0x93,0xb1,0x5f,0x40,0xb6,0xfe,0xf1,0x90,0xa9,0x5f, -0x43,0x8e,0xbe,0x9c,0xfc,0xfc,0x3f,0xc3,0x5d,0xbd,0x9e,0xfc,0xfc,0x5d,0xe4,0xe7, -0x0f,0xe0,0x51,0x5b,0x66,0xbe,0x91,0xcc,0xfc,0x22,0x32,0xf2,0x9d,0xc9,0xc8,0x1f, -0x46,0x46,0xde,0xb8,0xa9,0x43,0xc8,0xc9,0x9f,0x43,0x4e,0x7e,0x26,0x9c,0xd4,0x95, -0x81,0x8f,0xfa,0x4c,0x60,0xa2,0xbe,0x08,0x07,0xf5,0xcd,0x3c,0x8f,0xda,0xd8,0xa7, -0x7b,0xa4,0x52,0xf8,0xa7,0x5d,0xe1,0x9e,0x5e,0x43,0x7e,0xfe,0x47,0x81,0x6b,0xfa, -0x4b,0x32,0xf3,0x3d,0x61,0x98,0x9e,0x04,0xbb,0x74,0x40,0x60,0x96,0x0e,0x83,0x53, -0x6a,0x1e,0xf5,0x38,0x32,0xf5,0x0d,0x64,0xe9,0x7f,0x0b,0x8b,0xb4,0xe5,0xc8,0x24, -0x4b,0x7f,0x44,0x60,0x90,0x9e,0x1b,0x3c,0xea,0x0b,0xf2,0x3c,0xea,0x8b,0x61,0x8a, -0x5e,0x11,0x58,0xa2,0xf3,0xe0,0x87,0x2e,0x93,0x9a,0x8f,0x4a,0x18,0xa1,0x55,0xc1, -0xa3,0x1e,0x1e,0x3c,0x6a,0xe7,0x7f,0x7e,0x5d,0x9a,0x0e,0xe7,0xf3,0x7a,0x38,0x9f, -0xf7,0xc2,0xf3,0x7c,0x30,0x70,0x3c,0x97,0x05,0x56,0xe7,0xff,0xc1,0xe7,0xfc,0x30, -0x78,0xd4,0xdb,0x61,0x71,0x0e,0x80,0xbd,0x39,0x18,0xe6,0xa6,0xf1,0x36,0x6f,0x21, -0xbf,0xff,0x02,0xfc,0xcc,0x0d,0x81,0x9f,0xb9,0x25,0x30,0x33,0x9d,0x95,0xb9,0x3b, -0x70,0x31,0x2d,0x9f,0xbf,0x07,0xce,0x65,0x77,0xf2,0xf9,0xe3,0xc8,0xe5,0x7f,0x33, -0xcf,0xa3,0xfe,0x21,0xf9,0xfb,0xa7,0x83,0x47,0xfd,0x2c,0xd9,0x7b,0xcb,0xdd,0xaf, -0x23,0x77,0x6f,0x99,0xfb,0x8d,0x64,0xee,0x3f,0x22,0x73,0x6f,0x79,0xfb,0xcf,0xa4, -0x52,0x98,0x95,0xee,0x51,0xf7,0xfd,0x0a,0x1e,0x75,0xb5,0x74,0x06,0x1e,0xf5,0x05, -0x78,0xd4,0x17,0x77,0xe0,0x51,0xcf,0x08,0x1e,0xf5,0x0f,0xa4,0xeb,0xa4,0x59,0x78, -0xd4,0xf3,0xa4,0x5b,0xa5,0xdb,0xc9,0xf8,0xaf,0x86,0x7d,0x99,0xc6,0xa3,0x2e,0xc2, -0xa3,0x2e,0x21,0xeb,0x7f,0x58,0xc8,0xfa,0x5b,0xc6,0xbf,0xf7,0x17,0x78,0xd4,0x9e, -0xf1,0xb7,0x2c,0xff,0x08,0xb2,0xfc,0x63,0xc9,0xf2,0x4f,0x90,0x6a,0xa5,0xa9,0x64, -0xf7,0x6f,0x95,0x0e,0x39,0xa1,0xcd,0xa3,0x1e,0xdc,0x5b,0xe7,0x7e,0xd2,0x1d,0x78, -0xd4,0x27,0xf5,0xd1,0x79,0x87,0x34,0x57,0xfa,0xb9,0xf4,0x57,0xe9,0xe1,0x93,0x12, -0x8f,0xba,0xa5,0xaf,0xd4,0x4f,0x8f,0x25,0x9d,0x50,0xde,0x29,0xb5,0x48,0x03,0x75, -0x62,0x79,0x01,0xf9,0xff,0xf7,0xc9,0xff,0x6f,0x27,0xff,0xdf,0x72,0x4a,0x5b,0xfe, -0xff,0x54,0x32,0xff,0x33,0xf1,0xa8,0x7f,0x4a,0xd6,0xff,0x51,0x32,0xfe,0xab,0xc8, -0xf6,0xff,0x9e,0x4c,0xff,0x3b,0xb0,0x2c,0xcf,0x1e,0xa8,0xc7,0xbc,0xb4,0x53,0x7a, -0x5d,0x27,0xaf,0xfb,0xf0,0xa8,0x33,0x64,0xfb,0x7b,0x91,0xed,0x3f,0x15,0x96,0x65, -0x25,0x19,0xff,0xa1,0x64,0xfa,0xc7,0x90,0xe9,0xbf,0x9b,0x4c,0xff,0x62,0x3c,0x6a, -0xe7,0x54,0x5a,0x7e,0xbf,0x82,0xdc,0xbe,0x65,0xf6,0xdf,0x93,0x8e,0x19,0xa4,0xe7, -0xbb,0x54,0x2b,0x4d,0x95,0xae,0x93,0x66,0x49,0x4d,0xd2,0x6a,0xe9,0x25,0x69,0x9d, -0x74,0x55,0x95,0x8e,0x9d,0xf4,0xb6,0xb4,0x51,0xfa,0x0c,0x8f,0xda,0xb2,0xfe,0x2d, -0xd2,0xfe,0xc5,0x49,0xbe,0xff,0xbf,0x7f,0x91,0xe4,0xf8,0xbb,0x91,0xdf,0xb7,0xcc, -0xfe,0x15,0x78,0xd4,0xce,0x9f,0xbc,0x07,0xd6,0xe4,0x47,0xb0,0x25,0x77,0x4b,0xc7, -0x87,0x5c,0xfe,0x6a,0xe9,0x77,0x81,0x03,0xe9,0xfc,0x47,0xe7,0x3e,0xf6,0x09,0x8c, -0xc7,0x01,0x78,0xd4,0x43,0xa5,0xd3,0xc8,0xda,0x5f,0x0d,0xd3,0x71,0x0d,0x2c,0xc7, -0xed,0x81,0xd9,0x78,0x22,0x7c,0xc6,0x33,0xe1,0x32,0x9e,0x43,0xce,0x7e,0x76,0xe0, -0x2f,0x3e,0x0e,0x73,0xf1,0x29,0x58,0x8b,0x6b,0x61,0x2b,0x3a,0x57,0xd1,0x72,0xf6, -0xfd,0xe0,0x25,0x56,0xc2,0x49,0xac,0x86,0x8f,0xe8,0x6c,0xc4,0xaf,0x07,0x8f,0x7a, -0x72,0x60,0x1c,0x2e,0x0f,0x1e,0xf5,0x63,0x64,0xec,0x9f,0x24,0x63,0xbf,0x3a,0xcf, -0xa3,0xfe,0x00,0x16,0xa1,0xf3,0x06,0x8b,0xc8,0xd0,0x1f,0x4e,0x76,0x7e,0x20,0xd9, -0xf8,0x6f,0x07,0x56,0xa0,0x33,0x02,0x9d,0x09,0x68,0x2c,0xc0,0xfb,0xc8,0xc8,0x5b, -0x3e,0xfe,0x3b,0xe4,0xe2,0x8b,0x42,0x1e,0xbe,0x27,0x59,0xf8,0xfe,0x64,0xe1,0x3d, -0x07,0x7f,0x3a,0xd9,0xf7,0x5a,0xe9,0x59,0x72,0xef,0x63,0xc8,0xbd,0x5b,0xe6,0x7d, -0x3f,0x1e,0xb5,0x71,0xfc,0x8e,0x84,0xe3,0x57,0x7b,0x10,0x8f,0xfa,0x02,0x3c,0xea, -0x0b,0xa5,0x8b,0xa4,0x4b,0xf0,0xa8,0xa7,0xe3,0x51,0x37,0x90,0x97,0x37,0x8f,0xba, -0xa0,0x45,0x3f,0x73,0xa9,0x34,0xcf,0xa3,0xee,0x06,0x03,0xd0,0x3c,0xea,0x5e,0xe4, -0xea,0x6b,0x02,0xff,0x6f,0x15,0x99,0xf9,0x75,0x64,0xe5,0x2d,0x27,0xbf,0x59,0xfa, -0x93,0xf4,0x17,0xe9,0x6f,0xd2,0x01,0xfb,0x9a,0x64,0xe6,0x87,0x93,0x95,0x9f,0x40, -0x46,0x7e,0x6f,0x9e,0x47,0x5d,0x25,0x8d,0x91,0x6e,0x93,0x6e,0x97,0x16,0xe1,0x51, -0xef,0xc7,0xa3,0x5e,0x14,0x98,0x7e,0xfb,0xa4,0xde,0x64,0xe4,0xbf,0x0f,0xab,0xef, -0x1e,0xb2,0xf1,0x96,0x87,0xbf,0x07,0x0e,0xdf,0x06,0xf2,0xef,0x7d,0xc9,0xbd,0x9b, -0x47,0x3d,0x84,0xac,0xba,0xe5,0xd4,0x3d,0x8b,0x3e,0x38,0xe4,0xcf,0xcf,0x25,0x6b, -0xbe,0x9c,0xac,0xb9,0xe5,0xcc,0x8f,0x2e,0x49,0x3c,0xea,0xd3,0xf0,0xa8,0x2d,0x5b, -0xbe,0x8e,0x5c,0x79,0x27,0x58,0x76,0xdd,0xc8,0x96,0xf7,0x20,0x53,0xee,0xdc,0xba, -0xf1,0xd2,0x79,0xd2,0x62,0xb2,0xe4,0xc6,0xa7,0xfb,0xa4,0x34,0xc9,0x93,0x8f,0x21, -0x4f,0x7e,0x05,0x39,0xf2,0x45,0xd2,0xf2,0xb2,0x24,0x4b,0xfe,0x9f,0x64,0xc8,0x5b, -0x3a,0x27,0x19,0xf2,0xbe,0xb0,0xe8,0x66,0x91,0x0d,0x7f,0x04,0x8f,0xda,0xf2,0xe1, -0x7d,0xc9,0x7d,0x1b,0x13,0x6e,0xb2,0xf4,0x52,0xe0,0xbf,0xa5,0xc9,0x7c,0x1b,0xe7, -0x6d,0x82,0x34,0x0d,0xd6,0xdb,0x8d,0x30,0xdb,0x9e,0x80,0xd5,0x66,0x9c,0xb6,0x67, -0xf1,0xa8,0xb7,0xc0,0x67,0x2b,0x20,0x07,0xee,0x4c,0xb6,0x6a,0x72,0xe0,0x57,0x04, -0xce,0xda,0x8d,0xb0,0xd4,0x8c,0xa3,0xf6,0x62,0xe0,0xa6,0x99,0x47,0xbd,0x51,0xda, -0x75,0x48,0x92,0x01,0x1f,0x08,0x0b,0xad,0x2a,0x78,0xd4,0xc6,0x3e,0x1b,0x85,0x47, -0xed,0x79,0xf0,0x05,0x64,0xc0,0x97,0x06,0xa6,0xd9,0xbb,0x70,0xcc,0x8c,0x61,0x96, -0x86,0x5d,0xd6,0x99,0x2c,0x78,0x3f,0x32,0xe0,0x55,0x64,0xbf,0x47,0x06,0x26,0xd9, -0x58,0x38,0x64,0x13,0x82,0x47,0x7d,0x11,0xac,0x31,0xe3,0x8c,0x0d,0x85,0xe3,0x75, -0x7a,0xe0,0x77,0x99,0x47,0x3d,0x25,0x78,0xd4,0x17,0xc2,0xe6,0x7a,0x32,0x78,0xd4, -0xab,0x02,0x87,0xeb,0x79,0x32,0xdf,0xc6,0xdb,0x5a,0x01,0x5f,0xeb,0xa9,0xc0,0xd5, -0x6a,0x26,0x03,0x6e,0x1c,0xad,0x41,0x70,0xb3,0x46,0x06,0x8f,0xda,0x39,0x59,0xc6, -0xc7,0xba,0x3c,0xf0,0xb1,0xdc,0xa3,0x5e,0x1e,0x58,0x58,0xee,0x51,0x1b,0xfb,0xea, -0x28,0xd8,0x56,0xc7,0x07,0xa6,0x95,0xb1,0xac,0xc6,0xf4,0x48,0x98,0x55,0xce,0xab, -0x1a,0x8e,0x47,0xbd,0x23,0x64,0xc8,0x0f,0x25,0x37,0x3e,0x18,0xfe,0xd4,0xc8,0xe0, -0x51,0x3b,0x57,0xea,0x4c,0x98,0x52,0x0f,0xc2,0x90,0x7a,0x03,0x76,0x94,0x73,0xa3, -0x9c,0x0f,0x55,0x24,0x65,0xe1,0x43,0x0d,0x82,0x0b,0x35,0x1c,0x0e,0xd4,0x99,0xc1, -0xa3,0x9e,0x04,0xfb,0x69,0x0a,0x99,0x72,0xe7,0x3d,0x19,0xe7,0xe9,0x3f,0xc8,0x95, -0x67,0xe1,0x31,0x0d,0x81,0xc3,0x34,0x4e,0xba,0x9c,0x2c,0xb9,0x73,0x96,0x9c,0xaf, -0xe4,0x5c,0x25,0xe3,0x29,0x15,0x91,0x2f,0xaf,0x0c,0xfc,0xa4,0x51,0x81,0x99,0x74, -0x16,0x9c,0xa4,0x69,0xe4,0xcc,0x6f,0x87,0x87,0x74,0x47,0x07,0x1e,0xb5,0x71,0x8f, -0x76,0xc0,0x33,0xfa,0x14,0x8f,0xfa,0x35,0xe9,0x8f,0xd2,0x26,0x69,0xfb,0x71,0x49, -0xa6,0xdc,0xf2,0xe4,0x0d,0xe4,0xc9,0x07,0x56,0xeb,0xfb,0xae,0x4e,0x32,0xe3,0xc3, -0xc8,0x88,0x1b,0x07,0x68,0x06,0xf9,0xf0,0x5d,0x78,0xd4,0x15,0xf0,0x7e,0xc6,0xc1, -0xf9,0xb9,0x90,0x9c,0xb8,0x65,0xc4,0xef,0xfe,0x6e,0x1b,0xab,0x67,0x2e,0x5c,0x9e, -0xc5,0xe4,0xbd,0xa3,0x47,0x6d,0x1c,0x9e,0xdd,0x73,0x93,0x9c,0x77,0x76,0x41,0x3a, -0xd5,0x93,0xcc,0xf6,0xa5,0x64,0xb4,0xa7,0x93,0xcd,0xbe,0x85,0x4c,0xf6,0x22,0x18, -0x39,0xe6,0x51,0xdf,0x27,0x7d,0xbc,0x5e,0x8f,0x15,0xb8,0x38,0x97,0xc1,0xc3,0xb9, -0x16,0x1e,0xce,0x4d,0xf0,0x70,0x96,0xc2,0xc3,0xd9,0x22,0x9d,0x0e,0x13,0xc7,0x3c, -0xea,0x9d,0xd2,0xa4,0x0d,0xe9,0xd4,0x35,0x1b,0x92,0x9c,0xf7,0xa2,0x90,0xef,0x7e, -0x80,0x4c,0xb7,0xe7,0xb9,0x9f,0x27,0xc3,0x5d,0x4a,0x76,0xfb,0x18,0x32,0xdb,0xa3, -0x43,0x56,0xbb,0x8e,0x7c,0xf6,0x9b,0x78,0xd4,0x96,0xc5,0xee,0x4e,0x06,0xbb,0x96, -0xec,0xf5,0x3c,0x32,0xd7,0xcf,0x93,0xb9,0x36,0x4e,0x4d,0xcb,0xff,0x26,0x9c,0x9a, -0xe1,0x70,0x6a,0x1a,0xf0,0xa8,0xe7,0xe0,0x51,0xdf,0x0a,0xa7,0xc6,0x18,0x35,0x45, -0xb0,0x67,0x8e,0x87,0x39,0x63,0xbc,0x99,0x53,0xe0,0xca,0x8c,0x82,0x27,0x53,0xbb, -0x39,0xc9,0x5f,0x7f,0x04,0x2f,0xc6,0x3c,0x6a,0xcb,0x43,0xaf,0x83,0xbb,0x72,0x46, -0xe0,0xad,0x18,0x67,0x65,0xaa,0xf4,0xd8,0x87,0xfa,0xfb,0x5b,0x93,0x7c,0xf4,0x71, -0x21,0x17,0xdd,0x97,0x2c,0xf4,0xd0,0x2f,0xf0,0xa8,0x6b,0x43,0xce,0xb9,0x23,0x8f, -0xda,0xb3,0xcc,0xd3,0xc9,0x2f,0x5f,0x1d,0x72,0xcb,0xf3,0xc8,0x2a,0xdf,0x47,0x46, -0xd9,0xf2,0xc9,0xdb,0xa5,0x01,0xdb,0xd2,0xa9,0x7f,0x93,0x1e,0x95,0x56,0x4b,0xeb, -0xa4,0x8f,0xa5,0xd2,0xed,0xfa,0xb7,0x49,0x1a,0x88,0x47,0x7d,0x99,0x34,0x43,0x7a, -0x04,0x8f,0xba,0x60,0x87,0xee,0xa3,0x34,0x5e,0x9a,0x28,0x4d,0x93,0xde,0xf8,0x24, -0x9d,0xfa,0x50,0xda,0x2f,0x5d,0xb9,0x3b,0x9d,0xfa,0x1f,0xe9,0x03,0xa9,0xec,0x53, -0x7d,0x1f,0xd2,0x64,0x69,0xae,0xb4,0x4c,0x5a,0x21,0x5d,0xb3,0x47,0x3f,0x1b,0xe9, -0x9c,0xbd,0x69,0x9d,0xf3,0xe8,0xe7,0x21,0x5d,0x2b,0xfd,0x48,0x7a,0x48,0x7a,0x42, -0x7a,0x4e,0xfa,0x83,0xf4,0x93,0x7d,0xe9,0xd4,0xef,0xe0,0xb3,0xbc,0xfd,0x40,0x41, -0xaa,0xfa,0x57,0x49,0xa6,0xfa,0x5e,0xb2,0xd4,0x96,0x9f,0xb6,0xec,0xb4,0x79,0xd4, -0x37,0xa4,0x12,0xfe,0xca,0x81,0x96,0x6e,0x52,0x79,0x2a,0x7d,0x78,0xf7,0xc3,0x3b, -0x77,0x4f,0xeb,0x55,0xa6,0x2c,0xd3,0xa9,0xa0,0x53,0x41,0x61,0x41,0xa6,0x48,0x2f, -0xe9,0xee,0xe9,0x02,0x5d,0xa3,0x77,0x32,0x65,0x85,0x7a,0x53,0x58,0x94,0x69,0xff, -0x92,0xd5,0x2b,0xde,0x2f,0xb2,0x77,0xb2,0xf6,0x3a,0x53,0x96,0x2d,0xf6,0x97,0xe2, -0xd2,0x4c,0x49,0x59,0x49,0x41,0x49,0x26,0x5b,0x52,0x92,0x2d,0x2d,0x2b,0x2d,0xc9, -0xea,0x8d,0xfe,0x90,0x95,0x0a,0x4b,0xec,0x4f,0x7a,0xd1,0xe7,0x65,0x8a,0xc3,0xdf, -0xc9,0x16,0x97,0xd8,0x67,0x67,0x8b,0xda,0xbf,0x24,0x97,0xdc,0x7b,0xd9,0xe4,0xbd, -0x32,0xbd,0x64,0xfd,0x03,0xf6,0x91,0x6c,0xee,0x4f,0x79,0x9f,0x9e,0x7c,0x7e,0x36, -0x7e,0x2e,0x9f,0xd1,0xfa,0xd9,0x6d,0x97,0x2c,0xd2,0xb7,0xed,0x1f,0xc8,0x7d,0xdd, -0xdc,0xb5,0x99,0xd6,0x6b,0x5a,0x95,0x0d,0x77,0xa9,0xf5,0x2b,0x65,0xb9,0x25,0xbd, -0x2d,0x6b,0x7f,0xc7,0x8b,0xda,0xee,0x5f,0x36,0xd3,0xfa,0x5e,0x36,0x5e,0xdd,0xe1, -0x77,0x5d,0xd4,0xfe,0x2e,0xe6,0x8e,0x7a,0xe7,0xdc,0x51,0x8f,0x37,0x9e,0xbc,0xd8, -0x4d,0x66,0x32,0xd9,0x74,0xb8,0xcd,0xe4,0xe3,0x99,0xdc,0x4f,0x29,0xf7,0x5d,0xb4, -0xde,0x2c,0x77,0x35,0x1b,0x6e,0xb0,0x83,0xfb,0x90,0xf5,0x23,0x1e,0xaf,0x8b,0xf7, -0x2d,0x93,0xdc,0x25,0xde,0x76,0x4e,0x17,0x15,0x67,0x3a,0x77,0xef,0x51,0xde,0xad, -0x6b,0x97,0x82,0xb2,0x4c,0x81,0xae,0x38,0xec,0x90,0xaf,0x1d,0x9a,0x2e,0x2c,0x2a, -0xec,0x94,0xc9,0xa9,0x2c,0x9b,0xc9,0x7f,0x2c,0xe9,0x7e,0xb7,0xbe,0x9f,0xe9,0x54, -0x96,0xbc,0xf5,0x87,0x5c,0xee,0xae,0xdb,0x1d,0xcf,0xb4,0xfe,0x00,0x38,0x18,0x19, -0xbb,0x74,0xce,0xf0,0xc1,0xdc,0xdb,0xf0,0x80,0xfc,0xfc,0x4b,0xf2,0x4a,0x8f,0xbf, -0xe4,0x30,0x64,0x5a,0x0f,0x62,0xee,0x4f,0xd9,0xdc,0xbd,0xe8,0xe0,0x60,0xe4,0x1d, -0xe3,0xa2,0x0e,0x8f,0x4f,0xdb,0xb1,0xe5,0xa2,0x87,0x72,0xa7,0xe2,0xdc,0xa5,0xa4, -0x24,0xa3,0x07,0x75,0xc6,0x6e,0xb7,0x20,0xf7,0xa2,0x27,0x9a,0x9e,0x29,0xba,0x32, -0xdd,0xfe,0x39,0x97,0xfb,0x7b,0x65,0xba,0x2e,0xd3,0x76,0x6c,0x73,0x77,0x3a,0xf7, -0xe0,0xcb,0x16,0xb6,0xfb,0xee,0x73,0xb7,0xd1,0x76,0xc9,0xe4,0x5e,0xeb,0xd1,0x9a, -0x7b,0x9d,0x7b,0xdf,0xaf,0xcc,0xdd,0x87,0x6c,0x69,0xa9,0x5d,0x53,0x6c,0xcf,0xb9, -0x62,0xbe,0xfd,0x6c,0xfb,0x1f,0x6e,0xfb,0x47,0x5e,0xbb,0x07,0xe1,0xe7,0x9e,0x85, -0x45,0xf1,0x81,0x93,0x7f,0xb0,0xda,0x1d,0x9f,0xcc,0xe7,0x3e,0x14,0x8f,0x52,0xdb, -0xcd,0x1d,0xec,0xf1,0x17,0x9e,0xaa,0x7c,0x91,0x6c,0xb6,0xfd,0xdd,0xf6,0x27,0x6d, -0xde,0x13,0xa5,0xdd,0xfd,0xcd,0xe4,0x1d,0xb9,0x6c,0x51,0xf2,0x1c,0x49,0xfb,0x0f, -0xdf,0x0f,0x7f,0xfe,0xa5,0xed,0xd1,0x53,0xd8,0x76,0xaf,0x92,0x4b,0xeb,0xaf,0xa2, -0xe2,0xe4,0x77,0x97,0xfd,0xea,0xfa,0xb2,0x4b,0x26,0xb9,0x14,0x66,0xc2,0xaf,0xce, -0x83,0x5e,0x0a,0xb9,0x0f,0x69,0xdd,0xcb,0xa2,0x54,0xdb,0x4e,0xdb,0x39,0xcc,0xcd, -0xbe,0xea,0x2e,0x59,0xdf,0x1d,0xeb,0x3b,0x62,0x7d,0x27,0x6c,0xfe,0x0e,0xd8,0xfc, -0xdd,0xaf,0xbe,0xd3,0xd5,0x77,0xb9,0xfa,0x0e,0x57,0xdf,0xd5,0xea,0xbb,0x59,0x7d, -0x27,0xab,0xef,0x62,0xf5,0x1d,0xac,0xbe,0x7b,0xd5,0x77,0xae,0x6e,0x08,0x3b,0x54, -0xbd,0x63,0x31,0x92,0xdd,0xa8,0xb5,0x61,0xe7,0xa9,0xef,0x3a,0xf5,0x79,0x95,0xef, -0x26,0x5d,0xd5,0xc1,0x2e,0xd2,0xb5,0x61,0xf7,0xa8,0xef,0x1a,0xfd,0x2c,0xaf,0x2f, -0x11,0x77,0x82,0x7e,0xd1,0x2e,0x50,0xdf,0xf9,0x19,0x77,0x7d,0xce,0x09,0x3b,0x3b, -0x57,0x85,0x1d,0x9d,0xb1,0x03,0xe1,0x3b,0x38,0xf7,0xe6,0xcd,0x94,0x46,0x86,0xf9, -0x51,0xfe,0x6e,0xcc,0xd8,0x6f,0xf0,0xdd,0x97,0xbe,0xeb,0x72,0x55,0x07,0xbb,0x28, -0xd7,0x86,0xdd,0x93,0x29,0x66,0x3f,0xa3,0xbf,0x64,0x57,0xa4,0xef,0x84,0xbc,0x91, -0xdd,0x8f,0xbe,0xd3,0x71,0x55,0xd8,0xdd,0xe8,0x3b,0x1b,0xe3,0xae,0x46,0xdf,0xcd, -0x98,0x62,0xf7,0xa2,0xef,0x58,0x1c,0xdd,0xc1,0x4e,0xc5,0x09,0x61,0x77,0xa2,0xef, -0x4c,0xf4,0x99,0x4e,0xdc,0x79,0xd8,0xd1,0xae,0x43,0xdf,0x71,0xe8,0xbb,0x0d,0x7d, -0xa7,0xa1,0xef,0x30,0xf4,0x5d,0x84,0xbe,0x83,0xf0,0x45,0xe6,0x34,0xbe,0x53,0xf0, -0xcb,0x76,0x09,0x7e,0x2f,0x6f,0x57,0xe0,0xc1,0x76,0x04,0x0e,0x60,0xf6,0x32,0x89, -0xd9,0x8b,0xef,0xee,0xf3,0x9d,0x7d,0xbe,0xab,0xcf,0x77,0xf4,0xcd,0x66,0xf6,0xe2, -0x3b,0xf7,0xee,0x66,0x06,0xe3,0x3b,0xeb,0x7c,0xb7,0xdc,0x20,0x66,0x21,0xbe,0x3b, -0xce,0x77,0xc5,0x3d,0xc6,0xac,0xc3,0x77,0xbc,0xf9,0x6e,0x37,0x67,0x01,0xf9,0x8e, -0xb6,0x5e,0x61,0xe7,0x9a,0xcd,0x2c,0x7a,0x84,0x59,0x84,0xcf,0x20,0xe2,0xee,0xb2, -0x26,0x66,0x0d,0x31,0x0f,0x3f,0x36,0x6f,0x77,0xd8,0x6c,0x66,0x0a,0xcb,0x98,0x1f, -0xd8,0x9c,0xa0,0x0f,0xf3,0x81,0xb8,0x53,0x6b,0x4b,0xd8,0x9d,0xb5,0x2b,0x6f,0x16, -0xd0,0xcc,0x1c,0x60,0x1f,0xb3,0x80,0xf5,0xf8,0xe3,0xbe,0x5b,0xc9,0x77,0x25,0xf9, -0x8e,0xa3,0x93,0xf1,0x7b,0x7d,0x27,0xd1,0x0c,0x3c,0x55,0xdf,0xe9,0xe3,0xbb,0x7b, -0x7c,0x57,0x8f,0xef,0xce,0xf1,0x9d,0x39,0xbe,0x2b,0xa7,0x77,0xde,0x4e,0x1c,0xdf, -0x85,0xf3,0x18,0x5e,0xa9,0xef,0xbc,0xf1,0xdd,0x36,0xbe,0xcb,0xe6,0x2c,0x7c,0xd2, -0x98,0xe3,0x6d,0x0e,0x3b,0x66,0xfa,0xe3,0x7d,0xfa,0x4e,0x18,0xf7,0x3d,0xaf,0x0b, -0x99,0xdc,0xa6,0xb0,0xbb,0xc5,0x77,0xb6,0xf8,0xae,0x16,0xdf,0xd1,0xf2,0x01,0x3b, -0x57,0xdc,0xef,0x7c,0x2f,0xec,0x38,0x31,0x2f,0xd3,0x77,0x92,0xe4,0xef,0x0e,0xf1, -0x5d,0x1b,0xbe,0x5b,0xc3,0x77,0x65,0x1c,0x6c,0xb7,0x43,0xfe,0x0e,0x07,0xdf,0xd1, -0xe0,0x3b,0x16,0x7c,0x27,0x82,0xef,0x34,0x48,0x85,0x4c,0xe5,0x99,0x21,0x4b,0xd9, -0x84,0x47,0xe5,0x3b,0x03,0xfa,0xe2,0x47,0xf9,0x2e,0x00,0x67,0xff,0x7b,0x66,0x72, -0x25,0x4c,0xff,0xdf,0xe6,0x79,0x52,0xa7,0xe4,0x31,0xf7,0x37,0xe2,0x2d,0xa5,0xf0, -0x95,0x9c,0x71,0x3f,0xfa,0x20,0x2c,0x7b,0x67,0xd8,0x1f,0x8c,0x5d,0x3f,0x18,0x0f, -0xc9,0x59,0xef,0x4d,0x78,0x44,0xcb,0x03,0x7b,0xbd,0x39,0xb0,0xd5,0x2b,0xf1,0x80, -0x1e,0xc6,0xdf,0x39,0x16,0x1f,0xe7,0x14,0xbc,0x9b,0x8e,0x58,0xe1,0xa3,0x03,0x13, -0xdc,0xfd,0x9a,0x57,0x02,0xe3,0x7b,0x53,0x60,0x78,0x3b,0xbb,0x3b,0x66,0x07,0x23, -0xa3,0x7b,0x22,0x9e,0xcc,0x7c,0xbc,0x98,0x8a,0xc0,0xc2,0x1e,0x93,0xc7,0xb8,0x36, -0xaf,0xe5,0xcb,0x18,0xd5,0xce,0xa6,0xee,0x88,0x3d,0x6d,0x1e,0xcb,0x4e,0x18,0xd1, -0xce,0x42,0x76,0x06,0xb2,0x33,0x8a,0xf3,0xd9,0xc4,0xf9,0x0c,0x62,0x67,0xfe,0x4e, -0xfb,0x7b,0x99,0xbe,0x7f,0x2f,0xdb,0xf6,0xab,0xb2,0x6b,0xf1,0x12,0x9c,0x39,0xeb, -0xac,0x56,0x67,0xb4,0x3a,0x43,0xf4,0xff,0x01, +0xec,0x9c,0x09,0x40,0x54,0x55,0xfb,0xff,0x1f,0x18,0x59,0x94,0x65,0x9c,0x19,0xb6, +0x51,0x61,0x10,0x18,0x98,0x61,0x9f,0x19,0x18,0x76,0x66,0x58,0xda,0xcb,0xb6,0xb7, +0x3d,0x2b,0xf7,0xdc,0xb7,0xb4,0xb4,0xd2,0xcb,0x2e,0x28,0xe0,0x86,0x0a,0xb2,0x08, +0x8a,0x1b,0xa2,0x02,0xa2,0xec,0x60,0x88,0x8a,0xa5,0x88,0x88,0x65,0x6f,0x96,0x9a, +0x20,0x58,0x5a,0x56,0xb6,0x58,0x32,0xff,0xef,0xbd,0x33,0xa0,0x99,0xbd,0xf5,0x96, +0xbd,0xbf,0xdf,0xfb,0xfb,0x37,0x0f,0x9f,0x73,0xce,0x3d,0xf7,0x9c,0xf3,0x3c,0xe7, +0xb9,0xe7,0x9e,0x7b,0xce,0x1d,0x80,0x18,0x22,0x2d,0x31,0xd4,0x44,0x64,0xa4,0x35, +0x62,0x8c,0x9a,0x8c,0xc8,0x58,0x6b,0xcc,0x18,0x13,0xd3,0x64,0x4c,0x3c,0x2d,0x8f, +0xe1,0x35,0xf1,0x68,0x90,0x76,0x10,0x33,0xa8,0x69,0x10,0x99,0x18,0x31,0xc6,0x8c, +0xd6,0x84,0x18,0x1e,0x33,0x88,0x31,0x61,0x4c,0x19,0x33,0xc6,0x9c,0x19,0xcc,0x0c, +0x61,0x2c,0x18,0x62,0x18,0x13,0x4b,0xa6,0xc9,0x84,0x4c,0xb5,0xa6,0x56,0x8c,0x35, +0xc3,0x67,0x18,0xd3,0xa1,0x8c,0x80,0x11,0x32,0x22,0xc6,0x86,0xb1,0x65,0xec,0x18, +0x7b,0xc6,0x81,0x11,0x33,0x4d,0xa6,0xc3,0x18,0x32,0xd3,0x9a,0x31,0x66,0x4d,0x66, +0x64,0x3e,0x1c,0xf5,0x88,0xd1,0x9a,0x33,0xe6,0xd0,0x67,0x4e,0xdc,0xd1,0x08,0xc6, +0x91,0x71,0x62,0x24,0x8c,0x33,0x33,0x92,0xa1,0xc1,0xfa,0xbc,0x9f,0x8b,0x0b,0xe3, +0xca,0xb8,0x31,0x52,0x46,0x3b,0xd8,0x9d,0x61,0x06,0xbb,0x32,0x1e,0x8c,0x8c,0x91, +0x33,0x9e,0x8c,0x17,0xe3,0xcd,0xf8,0x30,0xbe,0x8c,0x1f,0xe3,0x8f,0x52,0x0a,0xa0, +0x64,0x54,0x4c,0x00,0xd3,0x34,0x38,0x90,0xa1,0x21,0xda,0x21,0xcc,0x10,0x68,0x19, +0x42,0x16,0x5a,0x0b,0xc6,0xa2,0xc9,0x82,0x2c,0xb5,0x96,0x8c,0x65,0x93,0x25,0x59, +0x69,0xad,0xd4,0x0c,0x63,0xd5,0x64,0x45,0xd6,0xb0,0xc5,0x5a,0xaf,0x83,0x31,0xc4, +0x41,0x4c,0x93,0x35,0xf1,0xb5,0xfc,0x3b,0xd9,0x71,0x27,0x61,0xf8,0x4d,0x6c,0xd9, +0xa1,0xc4,0x04,0xeb,0xfb,0x36,0x94,0x19,0xda,0x34,0x94,0x04,0x21,0x8c,0x56,0x10, +0xca,0x84,0x21,0x27,0x9c,0x61,0x04,0x4d,0x02,0x12,0x6a,0x85,0x8c,0xb0,0x49,0x48, +0xa2,0x08,0x46,0x2b,0x62,0x44,0x4d,0x22,0xb2,0xd1,0xda,0x44,0x32,0x8c,0x4d,0x93, +0x0d,0xd9,0x6a,0x6d,0x19,0xdb,0x26,0x5b,0xb2,0xd3,0xda,0xfd,0x5e,0xbd,0x7f,0xcb, +0xdf,0xf2,0xb7,0xfc,0x35,0xa2,0x61,0xb4,0x03,0xe9,0x28,0x86,0xb1,0x6b,0xb2,0x8b, +0x66,0xc8,0x5e,0x6b,0xcf,0xd8,0x37,0xd9,0xc7,0x30,0x48,0x33,0xb1,0xe0,0x1e,0x70, +0x2f,0x73,0x1f,0x73,0x3f,0xe2,0x07,0x98,0x07,0x19,0x72,0xd0,0x3a,0x3c,0xf4,0xb7, +0xf7,0xfe,0x42,0x79,0x98,0x79,0x84,0x19,0xf5,0xb7,0x70,0xc2,0x38,0x34,0x39,0x90, +0x58,0x2b,0x66,0xc4,0x4d,0x62,0x1a,0xa6,0x1d,0xc6,0x0c,0x6b,0x1a,0x46,0xc3,0xb5, +0xc3,0x99,0xe1,0x4d,0xc3,0x69,0x84,0x76,0x04,0x33,0xa2,0x69,0x04,0x39,0x6a,0x1d, +0x19,0xc7,0x26,0x47,0x72,0xd2,0x3a,0x31,0x4e,0x4d,0x4e,0x24,0xd1,0x4a,0x1e,0x65, +0x1e,0x83,0x27,0x1f,0x67,0x9e,0x40,0xf8,0x24,0xf3,0x0f,0xae,0xad,0xa7,0x98,0xa7, +0x99,0x67,0x98,0x67,0x99,0xe7,0x98,0xe7,0x19,0x46,0x82,0x67,0xa6,0x84,0x9c,0x5f, +0x60,0xb4,0xce,0x8c,0xf3,0x8b,0x03,0xbe,0xbf,0x8f,0x19,0xcd,0x34,0x39,0x8f,0x62, +0x5e,0x62,0x5e,0x66,0x5e,0x61,0xc6,0x30,0x63,0x99,0x71,0xcc,0x78,0x66,0x02,0x33, +0x91,0x99,0xc4,0xbc,0xca,0x4c,0x66,0xa6,0x30,0x53,0x99,0x69,0x68,0x8b,0x98,0xe9, +0x0c,0x8d,0x9c,0xc1,0xcc,0x64,0xb4,0x23,0x67,0x71,0xad,0xcf,0x66,0xe6,0x30,0x73, +0x99,0x17,0x98,0xd7,0x98,0x79,0xcc,0x7c,0x9c,0x7f,0x9d,0x79,0x83,0x59,0xc0,0x2c, +0x64,0xde,0x44,0xfa,0x2d,0xe6,0x6d,0x66,0x11,0xb3,0x98,0x61,0x98,0x38,0x26,0x9e, +0x49,0x60,0x12,0x91,0x97,0x04,0x92,0xb9,0x9a,0x29,0xcc,0x12,0xa4,0x53,0x99,0x34, +0x66,0x29,0xb3,0x8c,0x49,0xe7,0xf2,0x32,0xd8,0xbe,0x8f,0xcc,0x64,0x96,0x33,0x2b, +0x98,0x95,0xcc,0x2a,0x9c,0x5f,0xcd,0x64,0x61,0x7d,0xb0,0x86,0x59,0x8b,0x33,0xeb, +0x98,0x6c,0x26,0x87,0x59,0x8f,0x54,0x2e,0x93,0xc7,0xe4,0x33,0x05,0x06,0x6f,0x6d, +0x60,0x0a,0x99,0x22,0x66,0x23,0xb3,0xe9,0x5f,0x8e,0xaf,0x71,0x9c,0xfd,0xfd,0x52, +0x3c,0x90,0x4a,0xbf,0x4b,0xd7,0x6c,0x33,0xb3,0xe5,0x37,0xc7,0xf8,0x56,0x66,0xdb, +0xff,0xe0,0x1d,0xf6,0xf8,0x1d,0xf2,0xd2,0xff,0x4f,0xde,0x3f,0x69,0x7f,0xb0,0xde, +0xed,0xde,0x71,0x65,0xb6,0x33,0x25,0xcc,0x0e,0xa4,0x4a,0x99,0x9d,0x77,0xd4,0xd0, +0x34,0x92,0x5c,0x76,0xe1,0xfc,0x6e,0xa6,0x8c,0x29,0xff,0xff,0x64,0xa6,0xae,0x60, +0xf6,0x70,0xbe,0xfa,0xd7,0xe3,0xbd,0x92,0xd9,0xfb,0xff,0xd9,0xac,0xbd,0x6f,0xa0, +0xef,0x5a,0x97,0xaa,0x5b,0x3c,0x91,0x71,0xd7,0x34,0x10,0x53,0xcd,0x30,0x2e,0xff, +0x73,0x3d,0xd4,0xf7,0xa7,0xc9,0xe5,0xd6,0xeb,0x5c,0xc3,0xd4,0x32,0x75,0xdc,0x9a, +0xaa,0xde,0x90,0x23,0x63,0x43,0x57,0xad,0x2b,0xe3,0x4a,0x4c,0x03,0x9e,0x00,0x8d, +0x6c,0x1d,0xfd,0xdd,0xe2,0x4a,0x6e,0x5a,0x37,0xc6,0xad,0xc9,0x8d,0xa4,0x5a,0x29, +0x23,0x6d,0x92,0x92,0xbb,0xd6,0x9d,0x71,0x6f,0x72,0x27,0x0f,0xad,0x07,0xe3,0x71, +0xa7,0x71,0xb4,0x1f,0xf5,0xde,0xf9,0x4d,0xbb,0x9a,0x3c,0x48,0xa6,0x95,0x31,0xb2, +0x26,0x59,0x33,0x8e,0x0f,0x30,0x2d,0x03,0xe7,0x0e,0x32,0x87,0x6e,0x2b,0x7d,0xd8, +0x10,0xb7,0x1a,0xe2,0x23,0x86,0xf8,0x5d,0x83,0xc6,0xf7,0x18,0x92,0x1f,0xfd,0x15, +0x4d,0xc7,0x98,0x36,0x84,0xc7,0x0d,0x47,0x5a,0x39,0x23,0x6f,0x92,0xb7,0x0f,0x9c, +0xf5,0x42,0xed,0x13,0x4c,0x07,0x43,0x9e,0x5a,0x4f,0xc6,0xf3,0x24,0xd3,0xe4,0x49, +0x5e,0x77,0x9a,0x57,0x7e,0x2e,0x9d,0x86,0xf8,0x14,0xf3,0x3e,0xf3,0x01,0x73,0x9a, +0xf9,0xf0,0x96,0x73,0xff,0x04,0x1f,0x71,0xa9,0x33,0x8c,0xd6,0xeb,0xdf,0x9d,0xbf, +0xfe,0x96,0xbf,0xe5,0x6f,0xf9,0x5b,0xfe,0x96,0x7f,0x25,0xaf,0xfe,0xaf,0xb1,0xe4, +0xe3,0xff,0x42,0xef,0xd5,0xfd,0x7f,0x33,0x4e,0x3e,0xb9,0x43,0xde,0x92,0xbb,0xbb, +0xef,0xf7,0x6a,0xf2,0x22,0x6f,0xad,0x37,0xe3,0xdd,0xe4,0x4d,0x3e,0x5a,0x1f,0xc6, +0xe7,0xcf,0xed,0x5f,0xfe,0xf7,0xc8,0xd9,0xbf,0xe7,0x19,0x4e,0xd2,0xfe,0x7e,0xbb, +0xf5,0xb7,0xfc,0x2d,0x7f,0xcb,0xff,0x49,0xf9,0x7b,0x7e,0xff,0xab,0x45,0xa7,0x33, +0x22,0x1e,0x99,0x90,0x19,0x0d,0x26,0x0b,0xb2,0x22,0x3e,0x09,0x48,0x44,0xb6,0x64, +0x4f,0x62,0x1a,0x4e,0x8e,0x24,0xa1,0x91,0xe4,0x4a,0x52,0xf2,0x20,0x39,0x79,0x91, +0x0f,0xf9,0x91,0x82,0x54,0xa4,0xbb,0x6b,0x9f,0xbe,0x3f,0x29,0x81,0xb7,0xd9,0x12, +0x44,0x6c,0x8f,0xd8,0x14,0x21,0x0c,0xe3,0x52,0x1a,0x8a,0xa2,0x18,0xba,0x8f,0x4b, +0x3f,0x48,0xa3,0xd0,0x2b,0x9d,0xee,0x31,0x7a,0x9a,0x5e,0x44,0x3c,0x96,0x26,0xd0, +0xab,0x34,0x95,0x66,0xd0,0x6c,0x7a,0x8d,0x5e,0xa7,0x85,0xf4,0x36,0xdc,0x92,0x40, +0xc9,0x94,0x4a,0xcb,0x28,0x93,0x56,0x52,0x16,0xad,0xa3,0xf5,0x94,0x4f,0x85,0xb4, +0x09,0xe5,0xb7,0xd0,0x76,0x2a,0xa5,0xdd,0x54,0x41,0x7b,0xa9,0xfa,0x2e,0xf8,0xa1, +0x0e,0x6d,0x34,0x82,0x77,0x40,0x0b,0x38,0x0c,0xde,0x05,0xc7,0x40,0x3b,0x38,0x09, +0xde,0x07,0x1f,0x82,0x33,0xe0,0x2c,0xf8,0x14,0x74,0x83,0x5e,0xf0,0x39,0xf8,0x02, +0x7c,0x05,0xae,0x81,0xef,0xc1,0x8f,0xa0,0x8f,0xf5,0x83,0x91,0x4e,0x37,0x08,0x98, +0x1b,0x99,0x1b,0x59,0x20,0xb6,0x36,0x62,0x35,0x0a,0x10,0xda,0x00,0x7b,0x30,0xcc, +0x68,0x98,0x91,0x13,0xe2,0x91,0xc0,0x0d,0x78,0x00,0x4f,0x23,0x5f,0x84,0x0a,0x10, +0x00,0x82,0x40,0x28,0x88,0x00,0x5a,0x10,0x03,0xee,0x05,0x0f,0x80,0x87,0xc1,0xa3, +0xe0,0x09,0xf0,0x14,0x78,0x16,0xbc,0x00,0x5e,0x02,0x63,0xc0,0x78,0x30,0x09,0x4c, +0x01,0xd3,0xc1,0x2c,0x30,0xd7,0x68,0x3e,0xc2,0x05,0xe0,0x2d,0x20,0x85,0x95,0x8b, +0x8d,0xe2,0x91,0x4a,0x02,0x4b,0x8c,0x96,0x22,0xcc,0x30,0x5a,0x61,0xb4,0x9a,0xb3, +0x74,0xad,0x51,0x8e,0x51,0x9e,0xd1,0x06,0xa4,0x37,0x1a,0x6d,0x46,0xb8,0xcd,0x68, +0x87,0xd1,0x2e,0x23,0xbd,0xdf,0xca,0x8d,0x2a,0x91,0xaa,0x32,0xaa,0x45,0xd8,0x00, +0xf6,0x83,0x03,0x46,0x87,0x10,0x1e,0xe1,0x4a,0x1c,0x45,0x78,0xdc,0xa8,0x03,0xe1, +0x29,0xa3,0xd3,0x46,0x1f,0x21,0xfe,0x04,0x9c,0x37,0xea,0x32,0xd4,0xef,0x31,0xfa, +0xf9,0x75,0xf8,0xcc,0x88,0x95,0x2f,0x38,0xf9,0x8a,0x93,0x6b,0x28,0xf1,0x3d,0xf8, +0x11,0xf4,0x01,0x23,0x63,0x78,0x13,0x98,0x81,0x21,0xc6,0x6c,0x1d,0x2b,0x84,0x43, +0x81,0x08,0xd8,0x01,0x31,0x18,0x01,0x24,0xc0,0x05,0x48,0xb9,0x52,0x32,0x63,0x56, +0xbc,0x90,0xf6,0x35,0x56,0x18,0x07,0x20,0x0e,0x02,0xa1,0x20,0x02,0x68,0x41,0x0c, +0xb8,0x17,0x3c,0x00,0x1e,0x06,0x8f,0x82,0x27,0xc0,0x53,0xe0,0x59,0xf0,0x02,0x78, +0x09,0x8c,0x01,0xe3,0xc1,0x24,0x30,0x05,0x4c,0x07,0xb3,0xc0,0x5c,0x30,0x1f,0x2c, +0x00,0x6f,0x81,0xc5,0x20,0x1e,0x24,0x81,0x25,0x60,0xa9,0xf1,0xcf,0xfb,0x9a,0x61, +0xbc,0x12,0x39,0x59,0xc6,0xeb,0xb8,0xfc,0x5c,0x84,0x05,0xc6,0x45,0xc6,0xc5,0xc6, +0x5b,0x91,0x2a,0x01,0x3b,0x41,0x19,0xd8,0x63,0xac,0xfb,0xaf,0xff,0xf0,0x69,0x9f, +0xb1,0x08,0x33,0x58,0x8d,0x71,0xbd,0x71,0x93,0xb1,0x0f,0x66,0xaf,0x3f,0xd7,0x5e, +0xb3,0xf1,0x21,0xe3,0x77,0x8d,0xdb,0x8c,0x3b,0x8c,0xdf,0xe7,0xbc,0xb3,0xd9,0xc8, +0x1e,0xb3,0xa3,0x1f,0xfd,0xf3,0x0f,0xfa,0xea,0x63,0xe3,0x73,0xa8,0x79,0xc1,0xf8, +0xa2,0xf1,0xe7,0x77,0x68,0x81,0xfe,0xf4,0x0c,0xf3,0x05,0x5a,0xfd,0x0a,0x5c,0x03, +0xdf,0x1b,0xeb,0xe7,0xdb,0x1f,0xfb,0x35,0x19,0x1b,0xf1,0xfa,0xe7,0xd1,0x18,0x1a, +0xc4,0x1b,0xc2,0xb3,0xe2,0x0d,0xe5,0x89,0x78,0x76,0xc8,0x15,0x83,0x11,0x3c,0x09, +0x0f,0x23,0x99,0x27,0xe5,0xc9,0x78,0x5e,0x3c,0x5f,0x9e,0x82,0x17,0xc0,0x0b,0xe2, +0x7d,0x6e,0x1c,0xca,0x8b,0xe0,0xdd,0x47,0x5a,0x5e,0x0c,0xef,0x5e,0xde,0x03,0xbc, +0x87,0x51,0xf2,0x51,0xde,0x13,0xbc,0xa7,0x78,0xcf,0xf2,0x5e,0xe0,0xbd,0xc4,0x1b, +0xc3,0x1b,0xcf,0x9b,0xc4,0xbb,0x3b,0x57,0x6f,0x0a,0x74,0x07,0xa1,0xe5,0x11,0x68, +0xf1,0x59,0xe8,0xc2,0x98,0x07,0xb3,0xc0,0x5c,0x30,0x1f,0x2c,0x00,0x6f,0x81,0xc5, +0x20,0x1e,0x24,0x81,0x25,0x60,0x29,0xc8,0x00,0xa1,0xb0,0xef,0x51,0xc4,0x41,0xb0, +0x5f,0xa7,0x5b,0x01,0x1e,0xe5,0xad,0xe6,0xac,0x5b,0xcb,0xcb,0xe1,0xe5,0xf1,0x36, +0xf0,0x36,0xf2,0x36,0xf3,0xb6,0xf1,0x76,0xf0,0x76,0xf1,0xca,0x79,0x95,0xbc,0x2a, +0x5e,0x2d,0xaf,0x81,0xb7,0x9f,0x77,0x80,0x77,0x88,0x77,0x84,0x77,0x94,0x77,0x9c, +0xd7,0xc1,0x3b,0xc5,0x3b,0xcd,0xfb,0x88,0xf7,0x09,0xef,0x3c,0xaf,0x8b,0xd7,0xc3, +0xfb,0x8c,0x77,0x85,0x77,0x95,0xf7,0x0d,0xef,0x3b,0xde,0x75,0xde,0x0d,0x1e,0xdc, +0x36,0xc8,0x74,0xd0,0xe0,0x41,0x96,0x83,0xf8,0x83,0x84,0x83,0x6c,0x07,0x39,0x0c, +0x1a,0x3e,0xc8,0x69,0xd0,0xc8,0x41,0x6e,0x83,0x3c,0x06,0x79,0x0e,0xf2,0x19,0xf4, +0x57,0x8f,0x6f,0x7f,0x68,0x50,0x01,0x35,0x08,0x01,0xe1,0x40,0x03,0xa2,0xc1,0x3d, +0xe0,0x7e,0xf0,0x10,0x18,0x05,0x1e,0x07,0xff,0x00,0xcf,0x80,0xe7,0xc1,0x68,0xf0, +0xca,0x1d,0x2c,0x1c,0x87,0xbc,0x89,0x60,0x32,0x98,0x06,0x66,0x82,0x39,0x60,0x1e, +0x78,0x03,0xbc,0x09,0x16,0x81,0x38,0x90,0x08,0x52,0x40,0x1a,0x48,0x07,0xcb,0xc1, +0x2a,0xb0,0x06,0x64,0x83,0x5c,0x50,0x00,0x8a,0x40,0x31,0xd8,0x0a,0x4a,0xc0,0x4e, +0x50,0x06,0xf6,0x0c,0xda,0x87,0xb0,0x06,0xd4,0x83,0x26,0xd0,0x0c,0x0e,0x82,0x56, +0xce,0xb2,0xf7,0x10,0xb6,0x81,0x13,0xa0,0x13,0x7c,0x00,0xfe,0x09,0x3e,0x06,0xe7, +0xc0,0x05,0x70,0x11,0x5c,0x02,0x97,0xc1,0x97,0xe0,0x6b,0xf0,0x2d,0xf8,0x01,0xfc, +0xc4,0xb6,0x02,0x8c,0x4d,0x74,0x3a,0x13,0x60,0x0e,0x2c,0x80,0x35,0x10,0x00,0x1b, +0x60,0x0f,0x86,0x01,0x47,0xe0,0x0c,0x5c,0x81,0x3b,0x90,0x03,0x6f,0xe0,0x07,0x94, +0x20,0x10,0x04,0x83,0x30,0x10,0x09,0xa2,0x40,0x2c,0xb8,0x0f,0x3c,0x08,0x1e,0x01, +0x8f,0x81,0x27,0xc1,0xd3,0xe0,0x39,0x13,0xf6,0x7e,0x7b,0xd1,0xe4,0x65,0x93,0xb1, +0x26,0x13,0x4c,0x5e,0x35,0x99,0x6a,0x32,0xc3,0x64,0xb6,0xc9,0x6b,0x26,0xaf,0x9b, +0x2c,0x34,0x79,0xdb,0x84,0x31,0x49,0x30,0x49,0x36,0x49,0x35,0x59,0x66,0x92,0x69, +0xb2,0xd2,0x24,0xcb,0x64,0x9d,0xc9,0x7a,0x93,0x7c,0x93,0x42,0x93,0x4d,0x26,0x5b, +0x4c,0xb6,0x9b,0x94,0x9a,0xec,0x36,0xa9,0x30,0xd9,0x6b,0x52,0x6d,0x52,0x67,0xd2, +0x68,0xf2,0x8e,0x49,0x8b,0xc9,0x61,0x93,0x77,0x4d,0xfa,0x74,0x33,0x4c,0xfe,0xca, +0xd1,0x74,0xcc,0xd0,0xfa,0x42,0x58,0xd3,0xbf,0x3e,0xfb,0xbf,0xf2,0xe9,0x30,0xf9, +0xc0,0xe4,0x8c,0xc9,0xf9,0x3f,0xe9,0xbf,0x8b,0x26,0x57,0x4c,0xae,0x99,0xfc,0x64, +0xc2,0x33,0x1d,0x62,0x2a,0x30,0x75,0x30,0xbd,0xbb,0x2b,0xe1,0x5b,0xe3,0x3b,0xad, +0x8e,0x6f,0xe6,0x48,0x4c,0xdd,0x4d,0xfb,0x74,0x3e,0xa6,0xb7,0xd7,0xfe,0x63,0x3a, +0x6f,0xbf,0xce,0x37,0xf5,0xfd,0xfb,0x2d,0xf7,0xdd,0xe1,0x38,0xc0,0x94,0x0d,0xc3, +0x4c,0x6f,0x6d,0xb1,0xef,0x37,0xf5,0xdd,0xde,0x67,0xbd,0x44,0x9b,0x3e,0x60,0xfa, +0x98,0x29,0x9b,0xfb,0x8c,0xe9,0xed,0xde,0xf9,0xf7,0x77,0x1b,0xff,0xca,0xff,0xbf, +0x56,0x8a,0x95,0x97,0x4c,0x27,0x98,0xf6,0xdd,0xd1,0x93,0x7f,0xdc,0x82,0xbf,0xee, +0x33,0xcd,0x54,0xf7,0x2b,0xd7,0xb7,0x6f,0xe0,0x1a,0xf5,0xfd,0x8b,0x6b,0xf8,0xfb, +0xae,0xfa,0xaf,0xd7,0x9a,0x6b,0xfa,0xaf,0x47,0xdf,0xaf,0xb5,0xd0,0xf7,0xab,0x3e, +0x5c,0x68,0x1a,0x67,0x7a,0x37,0xf6,0x8f,0xbf,0xf6,0x59,0x62,0xfa,0x9f,0x9c,0x9b, +0x96,0x99,0xfe,0xb2,0xc7,0xab,0x06,0xf2,0x72,0x06,0x52,0x85,0x03,0xa9,0xad,0xbf, +0x6a,0xdf,0x2e,0xd3,0x5f,0xde,0x53,0x7b,0x91,0x57,0x6f,0x7a,0xc0,0xf4,0x5d,0xd3, +0x4e,0xd3,0x8f,0x6e,0xab,0xd9,0xfd,0x3b,0x7a,0x7a,0xf9,0x0e,0xf6,0x7d,0x33,0x90, +0xf7,0xe3,0x40,0xca,0xd8,0xac,0x3f,0x35,0xd8,0xec,0xd7,0xda,0x1a,0x6a,0x76,0x37, +0x9f,0x2c,0xf6,0x66,0xc3,0xcd,0x24,0x66,0xae,0x66,0x1e,0x66,0x5e,0x66,0x7e,0x66, +0x2a,0xb3,0x20,0xb3,0x30,0x33,0x8d,0x59,0x8c,0xd9,0x7d,0x66,0x0f,0x99,0x3d,0x6a, +0xf6,0xa4,0xd9,0x33,0x66,0x2f,0x98,0xbd,0x6c,0x36,0xce,0x6c,0x92,0xd9,0x54,0xb3, +0x99,0x66,0x73,0xcd,0x5e,0x37,0x7b,0xd3,0x6c,0xb1,0x59,0x82,0x59,0x8a,0xd9,0x52, +0xb3,0x4c,0xb3,0x55,0x66,0x6b,0xcd,0xd6,0x9b,0x15,0x98,0x6d,0x34,0xdb,0x62,0x56, +0x62,0xd6,0xa7,0xdb,0x65,0x76,0x73,0x64,0x54,0x98,0xfd,0x95,0x77,0xe7,0x3e,0xb3, +0xbb,0xd1,0x0a,0x11,0x91,0xee,0xbf,0xe6,0xc3,0xfa,0xb3,0xd6,0xac,0xd1,0xac,0xd9, +0xec,0x90,0xd9,0xbb,0x66,0x6d,0x66,0x7d,0xff,0xc1,0xd5,0xc5,0xbf,0xe7,0x29,0x1a, +0xf8,0xfc,0xd6,0x1c,0xfe,0x67,0x3f,0xa7,0xb0,0xb3,0xb8,0xce,0x63,0xf7,0x10,0xa6, +0xd8,0x37,0xa8,0x06,0x75,0x98,0xbd,0x6f,0x76,0xab,0x86,0x7f,0x9a,0x7d,0x62,0xf6, +0xa9,0xd9,0x45,0xb3,0xcf,0xcc,0xbe,0x30,0xfb,0xda,0xec,0x3b,0xb3,0x1f,0xcd,0x74, +0x66,0x3c,0x73,0x33,0xf3,0x7d,0x66,0x16,0xe6,0x7c,0x73,0x91,0xb9,0xbd,0xf9,0x70, +0x73,0x89,0xb9,0xab,0xb9,0x87,0xb9,0x97,0xb9,0x9f,0xb9,0xca,0x3c,0xc8,0x3c,0xcc, +0x5c,0x63,0x1e,0x63,0x7e,0x9f,0xf9,0x43,0xe6,0x8f,0x9a,0x3f,0x69,0xfe,0x8c,0xf9, +0x0b,0xe6,0x2f,0x9b,0x8f,0x33,0x9f,0x64,0x3e,0xd5,0x7c,0xa6,0xf9,0x5c,0xf3,0xd7, +0xcd,0xdf,0x34,0x5f,0x6c,0xce,0xb6,0x9c,0x60,0x9e,0x62,0xbe,0xd4,0xfc,0xaf,0xf2, +0xb7,0x11,0xbd,0x46,0x3c,0x78,0x8f,0x7d,0xaf,0xb8,0xd6,0xe8,0xf6,0xf7,0x8a,0x58, +0x6b,0xd3,0x5c,0x63,0x09,0xf6,0xe5,0xec,0x7b,0x45,0x1f,0x32,0xa2,0x4c,0xf3,0x95, +0xe6,0x59,0xe6,0x3c,0xee,0x3d,0x24,0xfb,0xd6,0x27,0xdb,0xdc,0x0a,0xa5,0x6c,0x51, +0xda,0xd7,0xc8,0x91,0x96,0x18,0xe5,0x9a,0x6f,0x30,0x97,0x70,0xa5,0x37,0x99,0x97, +0x1b,0x79,0xd1,0x56,0x73,0xfd,0xae,0x94,0xdd,0x73,0x0a,0xd0,0x0e,0xfb,0x76,0x92, +0xcd,0x79,0x98,0xcb,0xf9,0x75,0xbb,0xbe,0xbb,0x2b,0x3b,0xd3,0x1d,0xe6,0x26,0xb4, +0xcb,0x7c,0x25,0x65,0x9b,0x5b,0x50,0xb9,0x79,0xa5,0x79,0x95,0xf9,0x0e,0xa3,0x6d, +0x46,0xb5,0xe6,0x0d,0xe6,0xef,0x98,0xb7,0x98,0x1f,0x36,0x7f,0xcf,0xbc,0xcd,0xfc, +0x84,0x79,0xa5,0x51,0xa7,0xf9,0x07,0xe6,0x55,0x46,0xff,0x34,0xff,0xd8,0xfc,0x88, +0xd1,0x39,0xf3,0x22,0xe3,0x53,0x46,0x17,0xcc,0x4f,0x1b,0x15,0x1b,0xab,0xa8,0xc7, +0xfc,0x33,0xf3,0xf3,0x46,0x41,0xbc,0x2b,0xb8,0x02,0x5f,0x81,0x6f,0xc1,0x75,0xd0, +0x07,0x8c,0x07,0xeb,0x74,0xa6,0x60,0x08,0xb0,0x06,0x42,0x60,0x07,0x86,0x01,0x27, +0xe0,0x02,0xdc,0x81,0x27,0xf0,0x05,0x4a,0xa0,0x06,0xa1,0x20,0x12,0x44,0x83,0x7b, +0xc1,0x83,0x60,0x14,0x78,0x02,0x3c,0x0d,0x9e,0x07,0x2f,0x81,0xb1,0x60,0x22,0x98, +0x02,0x66,0x80,0x39,0x60,0x3e,0x58,0x08,0x16,0x81,0x78,0x90,0x0c,0xd2,0x40,0x06, +0x58,0x09,0xd6,0x80,0x1c,0x90,0x0f,0x8a,0xc0,0x66,0xb0,0x1d,0xec,0x04,0xe5,0x60, +0x2f,0xa8,0x01,0x0d,0xe0,0x1d,0x70,0x10,0x1c,0x01,0xc7,0xc0,0x09,0x70,0x0a,0x7c, +0x08,0x3e,0x06,0xe7,0x41,0x37,0xb8,0x04,0xae,0x80,0xaf,0xc0,0xb7,0xe0,0x3a,0xe8, +0x03,0xc6,0x43,0xd0,0x7f,0x30,0x04,0x58,0x03,0x21,0xb0,0x1b,0x72,0xd3,0xfb,0xc3, +0x86,0xb0,0x5a,0xe1,0x0b,0xe4,0x8d,0x04,0x52,0x20,0x07,0x3e,0x40,0x01,0x02,0x41, +0x08,0x88,0x00,0x51,0xe0,0x1e,0xf0,0x00,0x78,0x04,0x3c,0x0e,0x9e,0x02,0xcf,0x81, +0xd1,0x60,0x0c,0x98,0x00,0x26,0x83,0xe9,0x60,0x36,0x98,0x07,0x16,0x80,0xb7,0x41, +0x1c,0x48,0x02,0xa9,0x20,0x1d,0xac,0x00,0x59,0x20,0x1b,0xe4,0x81,0x42,0x50,0x0c, +0xb6,0x81,0x52,0x50,0x06,0x2a,0x41,0x35,0xa8,0x07,0xfb,0x41,0x0b,0x68,0x05,0x47, +0x41,0x3b,0xe8,0x04,0xa7,0xc1,0x99,0x21,0xbf,0x1c,0x59,0xe7,0x86,0x74,0x0d,0xe9, +0x1d,0x72,0x79,0xc8,0xd5,0x21,0xd7,0x86,0xfc,0x30,0xe4,0xc6,0x90,0xdb,0xe7,0x1d, +0x23,0x0b,0x13,0x8b,0xc1,0x16,0x56,0x16,0x02,0x0b,0x5b,0x8b,0x3b,0xcd,0x3f,0x62, +0x0b,0x47,0x8b,0x91,0x16,0x52,0x0b,0xb9,0x85,0x8f,0x85,0xc2,0x22,0xd0,0xe2,0xf6, +0xf3,0x21,0x16,0x11,0x16,0x51,0x16,0xf7,0x58,0x3c,0x60,0xf1,0x88,0xc5,0xe3,0x16, +0x4f,0x59,0xdc,0xde,0xfe,0x73,0x16,0xa3,0x2d,0xc6,0x58,0x4c,0xb0,0x98,0x6c,0x31, +0xfd,0x8e,0xed,0xf7,0xe9,0x66,0x23,0x7f,0x1e,0x58,0x00,0xde,0xfe,0x45,0xfb,0x71, +0x16,0x49,0x16,0xa9,0x16,0xe9,0x16,0x2b,0x2c,0xb2,0x2c,0xb2,0x2d,0xf2,0x70,0x7e, +0x08,0xee,0xb8,0xa1,0x40,0x04,0xec,0x80,0x18,0x8c,0x00,0x12,0xee,0xdd,0x53,0xa1, +0xc5,0x16,0x8b,0x52,0x8b,0x0a,0x8b,0x6a,0x8b,0x46,0x8b,0x16,0x8b,0x77,0x2d,0x6e, +0x3f,0x6e,0xb7,0x78,0xdf,0xe2,0x8c,0xc5,0xa7,0x16,0xbd,0x16,0x5f,0x58,0x5c,0xb3, +0xf8,0xf1,0x17,0xc7,0x46,0x96,0x66,0x96,0x56,0x96,0x22,0x4b,0xb1,0xa5,0xc4,0x52, +0x6a,0xe9,0x65,0x79,0xfb,0x31,0x6b,0x93,0xc2,0x32,0xc8,0x32,0xdc,0x92,0xed,0x4b, +0x94,0xe5,0x7d,0x96,0x0f,0x59,0x3e,0x6a,0x39,0x84,0x17,0x64,0xf9,0xa4,0xe5,0xe7, +0xc6,0x4f,0x5a,0x3e,0x63,0xf9,0x82,0xe5,0x18,0xcb,0x49,0x96,0xd3,0xb8,0xf3,0xb3, +0x2d,0x5f,0xb7,0x1c,0xca,0x7b,0xd3,0x52,0xc4,0x9b,0x64,0xb9,0xd8,0x32,0xc9,0x72, +0xa9,0xa5,0xbe,0x57,0x2b,0x2c,0xfb,0x7d,0xb1,0xda,0x72,0x9d,0x65,0xae,0x25,0xfb, +0x86,0x6c,0x83,0xe5,0x66,0xcb,0x1d,0x86,0xf3,0xe5,0x96,0xfd,0xfd,0xaf,0xb4,0xac, +0xb6,0xac,0xb7,0x1c,0xc1,0xdb,0x6f,0xd9,0x62,0x39,0x88,0xf7,0x2e,0x57,0xef,0xa8, +0x65,0x87,0xe5,0x07,0x5c,0xfb,0x67,0x2c,0x3f,0xb5,0x14,0xf3,0x2e,0x5a,0x4a,0x78, +0x1d,0x96,0x31,0xf4,0x99,0x25,0xfb,0xfd,0xc5,0x9d,0x44,0xff,0xdc,0xd1,0xeb,0xfc, +0xc2,0xf2,0xa6,0x77,0xbf,0xb6,0xfc,0xd7,0xfb,0x0a,0xdd,0xaf,0x7c,0x3b,0xf2,0x9d, +0x65,0x1f,0x6a,0x9a,0x5b,0xf1,0xad,0x06,0xc6,0x09,0x52,0x23,0xac,0x6e,0x6f,0xc5, +0xd9,0xca,0xd5,0xca,0xdd,0xea,0xd7,0xe7,0x3d,0xf9,0x6d,0xe7,0x02,0x6f,0x3e,0x28, +0xe9,0xa6,0xd6,0x5b,0x32,0x49,0x6d,0x25,0xe0,0xce,0x04,0x5b,0x85,0x5a,0x85,0x5b, +0x45,0x5a,0x69,0xad,0xa2,0xad,0x62,0xad,0xee,0xb5,0x7a,0xd0,0xea,0x61,0xab,0x51, +0x56,0xc3,0x71,0x7e,0x14,0xb1,0xdf,0xcf,0xdc,0xf9,0x3c,0xfb,0x1c,0x19,0x4c,0x8e, +0xe4,0x87,0x67,0x02,0x7f,0xe0,0xe9,0x21,0xe1,0xbe,0x8f,0xf2,0xb9,0xe3,0x37,0x51, +0x8f,0x59,0xfd,0x7b,0x33,0xf9,0x93,0x56,0xcf,0x58,0x99,0xd0,0x0b,0xa8,0xf5,0xb2, +0xd5,0x38,0xab,0x3c,0xf6,0x1b,0x0b,0x2b,0xf6,0x69,0xa5,0x97,0x6b,0x78,0x6a,0x09, +0xa0,0xd5,0x1e,0x7a,0x86,0xd3,0x54,0xae,0x6d,0xfd,0x37,0x62,0xac,0xb0,0x47,0x33, +0xac,0x66,0x5b,0xcd,0x43,0x3e,0x6b,0xc9,0x18,0x9e,0x3e,0xb6,0xa5,0xd9,0xdc,0x77, +0x6a,0x58,0x05,0x73,0xdf,0xaa,0xbd,0x61,0x25,0x46,0x1f,0xde,0xb2,0x5a,0x6c,0x15, +0x6f,0x95,0x04,0x7f,0x60,0x77,0x61,0xf5,0x00,0x9e,0x55,0x32,0xde,0x03,0xbc,0x65, +0x03,0xf6,0x9a,0x71,0xcf,0x3e,0xf6,0x29,0x79,0xab,0x7d,0xcb,0xad,0xd6,0x58,0xe5, +0x5a,0x6d,0xb4,0xda,0x66,0xb5,0xcb,0xaa,0xd2,0xaa,0xd6,0x6a,0xbf,0xd5,0x21,0xab, +0xa3,0x56,0x1d,0x56,0xa7,0xad,0x3e,0xb1,0xea,0xb2,0xfa,0x0c,0xad,0x7d,0x69,0xf5, +0xb5,0xd5,0x77,0x56,0x5e,0x74,0xdd,0xea,0x86,0x95,0x91,0xb5,0xa9,0xb5,0x1f,0x0d, +0xb6,0xb6,0xb4,0xb6,0xe7,0xbe,0xd3,0x13,0xd3,0x6f,0x9d,0x37,0xac,0xc9,0xad,0x6f, +0x6a,0xb4,0xb1,0xbe,0x7d,0xf7,0xf0,0xdf,0xf8,0x19,0x66,0x3d,0x12,0xfd,0xf0,0xb2, +0x56,0x5a,0xff,0xa7,0x35,0x87,0x5b,0x6b,0xff,0xb4,0xce,0xdf,0xbf,0x7f,0xbd,0xc3, +0xdd,0x63,0x7d,0x9f,0xf5,0x83,0xd6,0x8f,0x58,0x3f,0x66,0xfd,0xa4,0xf5,0xd3,0xd6, +0xcf,0x59,0xbf,0x68,0xfd,0xb2,0xf5,0x58,0xeb,0x09,0xd6,0x93,0xad,0xa7,0x5b,0xcf, +0xb6,0x9e,0x67,0xbd,0xc0,0xfa,0x6d,0xeb,0x38,0xeb,0x24,0xeb,0x54,0xeb,0x0c,0xeb, +0x55,0xd6,0xeb,0xac,0xf3,0xac,0x8b,0xac,0xb7,0x58,0xef,0xb0,0x2e,0xb3,0xde,0x6b, +0x5d,0x6b,0xfd,0x7b,0xf5,0x36,0x59,0x1f,0xb0,0x3e,0x6c,0xfd,0x9e,0xf5,0x71,0xeb, +0x93,0xd6,0x1f,0x58,0x7f,0x64,0x7d,0xd6,0xfa,0x82,0x75,0x8f,0xf5,0xe7,0xd6,0x5f, +0x5a,0x7f,0x63,0xfd,0xbd,0xf5,0x4f,0xd6,0xc4,0x1f,0xc4,0x37,0xe7,0x5b,0xf2,0x87, +0xf2,0x6d,0xf8,0x0e,0xfc,0x11,0x7c,0x67,0xbe,0x1b,0xff,0x8f,0x7c,0xd3,0xfc,0x47, +0xea,0xa8,0xad,0xfe,0xfc,0x55,0x94,0xf1,0x75,0xff,0xa7,0x3e,0x81,0xfc,0x10,0x7e, +0xf8,0x5d,0xec,0x93,0xf6,0x2e,0xb5,0x75,0x2f,0xff,0x41,0xfe,0x28,0xfe,0x13,0xfc, +0xa7,0xf9,0xcf,0xf3,0x5f,0xe2,0x8f,0xe5,0x4f,0xe4,0x4f,0xe1,0xcf,0xe0,0xcf,0xe1, +0xcf,0xe7,0x2f,0xe4,0x2f,0xe2,0xc7,0xf3,0x93,0xf9,0x69,0xfc,0x0c,0xfe,0x4a,0xfe, +0x1a,0x7e,0x0e,0x3f,0x9f,0x5f,0xc4,0xdf,0xcc,0xdf,0xce,0xdf,0xc9,0x2f,0xe7,0xef, +0xe5,0xd7,0xf0,0x1b,0xf8,0xef,0xf0,0x0f,0xf2,0x8f,0xf0,0x8f,0xf1,0x4f,0xf0,0x4f, +0xf1,0x3f,0xe4,0x7f,0xcc,0x3f,0xcf,0xef,0xe6,0x5f,0xe2,0x5f,0xe1,0x7f,0xc5,0xff, +0x96,0x7f,0x9d,0xdf,0xc7,0x37,0x1e,0xfa,0x57,0xfb,0xd5,0x14,0x1a,0x86,0x0c,0xb5, +0x1a,0x2a,0xe0,0x34,0xd9,0x20,0x74,0x00,0x23,0xc0,0x4a,0xec,0x01,0x32,0xcd,0x77, +0x60,0x3d,0xef,0xcc,0x9d,0x73,0xfb,0x99,0x2d,0x22,0x8c,0x57,0xd9,0x50,0xaf,0xa1, +0xbe,0xc8,0x55,0x02,0x35,0x08,0x05,0x91,0x20,0x1a,0xdc,0x0b,0x1e,0x04,0xa3,0xc0, +0x13,0xe0,0x69,0xf0,0x3c,0x78,0x09,0x8c,0x05,0x13,0xc1,0x14,0x30,0x03,0xcc,0x01, +0xf3,0xc1,0x42,0xb0,0x08,0xc4,0x83,0x64,0x90,0x06,0x32,0x58,0x4b,0xc0,0x1a,0x90, +0x03,0xf2,0x41,0x11,0xd8,0x0c,0xb6,0x83,0x9d,0xa0,0x1c,0xec,0x05,0x35,0xa0,0x01, +0xbc,0x03,0x0e,0x82,0x23,0xe0,0x18,0x38,0x01,0x4e,0x81,0x0f,0xc1,0xc7,0xe0,0x3c, +0xe8,0x06,0x97,0xc0,0x15,0xf0,0xd5,0x2f,0xbc,0xfc,0x2d,0x72,0xae,0x0f,0xe4,0xf6, +0x0d,0xd5,0xfd,0xc7,0xde,0x77,0xfe,0x7c,0x96,0x32,0x16,0xe8,0xfe,0xd0,0xdb,0xbf, +0xdf,0xfb,0x86,0xdb,0x54,0xf0,0xdf,0x71,0xf7,0x0f,0x11,0xfc,0x9a,0x07,0xac,0x05, +0x42,0x81,0x9d,0x60,0x98,0xc0,0x49,0xe0,0x22,0x70,0x17,0x78,0x0a,0x7c,0x05,0x4a, +0x81,0x5a,0x10,0x2a,0x88,0x14,0x44,0x0b,0xee,0x15,0x3c,0x28,0x18,0x25,0x78,0x42, +0xf0,0xb4,0xe0,0x79,0xc1,0x4b,0x82,0xb1,0x82,0x89,0x82,0x29,0x82,0x19,0x82,0x39, +0x82,0xf9,0x82,0x85,0x82,0x45,0x82,0x78,0x41,0xb2,0x20,0x4d,0x90,0x21,0x58,0x29, +0x58,0x23,0xc8,0x11,0xe4,0x0b,0x8a,0x04,0x9b,0x05,0xdb,0x05,0x3b,0x05,0xe5,0x82, +0xbd,0x82,0x1a,0x41,0x83,0xe0,0x1d,0xc1,0x41,0xc1,0x11,0xc1,0x31,0xc1,0x09,0xc1, +0x29,0xc1,0x87,0x82,0x8f,0x05,0xe7,0x05,0xdd,0x82,0x4b,0x82,0x2b,0x82,0xaf,0x04, +0xdf,0x0a,0xae,0x0b,0xfa,0x04,0xc6,0x42,0x53,0xe1,0x10,0xa1,0xb5,0x50,0x28,0xb4, +0x13,0x0e,0x13,0x3a,0x09,0x5d,0x84,0xee,0x42,0x4f,0xa1,0xaf,0x50,0x29,0x54,0x0b, +0x43,0x85,0x91,0xc2,0x68,0xe1,0xbd,0xc2,0x07,0x85,0xa3,0x84,0x4f,0x08,0x9f,0x16, +0x3e,0x2f,0x7c,0x49,0x38,0x56,0x38,0x51,0x38,0x45,0x38,0x43,0x38,0x47,0x38,0x5f, +0xb8,0x50,0xb8,0x48,0x18,0x2f,0x4c,0x16,0xa6,0x09,0x33,0x84,0x2b,0x85,0x6b,0x84, +0x39,0xc2,0x7c,0x61,0x91,0x70,0xb3,0x70,0xbb,0x70,0xa7,0xb0,0x5c,0xb8,0x57,0x58, +0x23,0x6c,0x10,0xbe,0x23,0x3c,0x28,0x3c,0x22,0x3c,0x26,0x3c,0x21,0x3c,0x25,0xfc, +0x50,0xf8,0xb1,0xf0,0xbc,0xb0,0x5b,0x78,0x49,0x78,0x45,0xf8,0x95,0xf0,0x5b,0xe1, +0x75,0x61,0x9f,0xd0,0x58,0x64,0x2a,0x1a,0x22,0xb2,0x16,0x09,0x45,0x76,0xa2,0x61, +0x22,0x27,0x91,0x8b,0xc8,0x5d,0xe4,0x29,0xf2,0x15,0x29,0x45,0x6a,0x51,0xa8,0x28, +0x52,0x14,0x2d,0xba,0x57,0xf4,0xa0,0x68,0x94,0xe8,0x09,0xd1,0xd3,0xa2,0xe7,0x45, +0x2f,0x89,0xc6,0x8a,0x26,0x8a,0xa6,0x88,0x66,0x88,0xe6,0x88,0xe6,0x8b,0x16,0x8a, +0x16,0x89,0xe2,0x45,0xc9,0xa2,0x34,0x51,0x86,0x68,0xa5,0x68,0x8d,0x28,0x47,0x94, +0x2f,0x2a,0x12,0x6d,0x16,0x6d,0x17,0xed,0x14,0x95,0x8b,0xf6,0x8a,0x6a,0x44,0x0d, +0xa2,0x77,0x44,0x07,0x45,0x47,0x44,0xc7,0x44,0x27,0x44,0xa7,0x44,0x1f,0x8a,0x3e, +0x16,0x9d,0x17,0x75,0x8b,0x2e,0x89,0xae,0x88,0xbe,0x12,0x7d,0x2b,0xba,0x2e,0xea, +0x13,0x19,0xdb,0x98,0xda,0x0c,0xb1,0xb1,0xb6,0x11,0xda,0xd8,0xd9,0x0c,0xb3,0x71, +0xb2,0x71,0xb1,0x71,0xb7,0xf1,0xb4,0xf1,0xb5,0x51,0xda,0xa8,0x6d,0x42,0x6d,0x22, +0x6d,0xa2,0x6d,0xee,0xb5,0x79,0xd0,0x66,0x94,0xcd,0x13,0x36,0x4f,0xdb,0x3c,0x6f, +0xf3,0x92,0xcd,0x58,0x9b,0x3e,0xdd,0xdd,0x17,0x76,0x87,0x30,0xd1,0xe6,0x3f,0x33, +0x0a,0x5f,0x85,0x9e,0x29,0x82,0x69,0x36,0xb3,0x6c,0xfe,0xcc,0xdd,0xcd,0x7e,0x5e, +0xb3,0x59,0xc0,0xb5,0xb1,0xc8,0xe6,0xbf,0xfb,0xa9,0x9c,0x64,0xf3,0x57,0xcf,0x8b, +0x7d,0xba,0x65,0x36,0xcb,0x6d,0x56,0xdb,0xac,0xb3,0xc9,0xb5,0xd9,0x60,0xb3,0xc9, +0x66,0xab,0xcd,0x0e,0x9b,0xdd,0x36,0x7b,0x6c,0xaa,0x6c,0xea,0x6c,0x9a,0x6c,0x0e, +0xd8,0x1c,0xb6,0x79,0xcf,0xe6,0xb8,0xcd,0x49,0x9b,0x0f,0x6c,0x3e,0xb2,0x39,0x6b, +0x73,0xc1,0xa6,0xc7,0xe6,0x73,0x9b,0x2f,0x6d,0xbe,0xb1,0xf9,0xde,0xe6,0x27,0x1b, +0xb2,0x1d,0x64,0x6b,0x6e,0x6b,0x69,0x3b,0xd4,0xd6,0xc6,0xd6,0xc1,0x76,0x84,0xad, +0xb3,0xad,0x9b,0xad,0xcc,0xd6,0xdb,0xd6,0xdf,0x36,0xc0,0x36,0xd8,0x36,0xdc,0x56, +0x6b,0x1b,0x6b,0x7b,0xbf,0xed,0xc3,0xb6,0x8f,0xd9,0xfe,0xc3,0x96,0xe8,0x59,0xdb, +0x17,0x6d,0x5f,0xb1,0x1d,0x6f,0xfb,0xaa,0xed,0x34,0xdb,0x59,0xb6,0xaf,0xd9,0xbe, +0x61,0xfb,0x96,0x2d,0x63,0x9b,0x68,0xbb,0xc4,0x76,0x99,0xed,0x72,0xdb,0xd5,0xb6, +0xeb,0x6c,0x73,0x6d,0x37,0xd8,0x6e,0xb2,0xdd,0x6a,0xbb,0xc3,0x76,0xb7,0xed,0x1e, +0xdb,0x2a,0xdb,0x3a,0xdb,0x26,0xdb,0x03,0xb6,0x87,0x6d,0xdf,0xb3,0x3d,0x6e,0x7b, +0xd2,0xf6,0x03,0xdb,0x8f,0x6c,0xcf,0xda,0x5e,0xb0,0xed,0xb1,0xfd,0xdc,0xf6,0x4b, +0xdb,0x6f,0x6c,0xbf,0xb7,0xfd,0xc9,0x56,0xef,0x15,0x6b,0xcc,0x4c,0x64,0x37,0xc8, +0xce,0xdc,0xce,0xd2,0x6e,0xa8,0x9d,0x8d,0x9d,0x93,0xc0,0xc1,0x6e,0x84,0x9d,0xb3, +0x9d,0x9b,0x9d,0xef,0x9f,0x9e,0x7f,0x65,0x76,0xbe,0x76,0x01,0x76,0xa1,0x76,0x5a, +0xbb,0x7b,0xed,0x1e,0xb6,0x7b,0xc2,0xee,0x59,0xbb,0x97,0xec,0xc6,0xdb,0x4d,0xb1, +0x9b,0x65,0x37,0xdf,0xee,0x2d,0xbb,0x78,0xbb,0x25,0x76,0x19,0x76,0xab,0xed,0x72, +0xec,0x36,0xd8,0x6d,0xb6,0xdb,0x61,0x57,0x6e,0x57,0x65,0xd7,0x60,0x77,0xc0,0xee, +0x88,0xdd,0x71,0xbb,0x53,0x76,0x9f,0xd8,0xf5,0xe9,0x7a,0xec,0xae,0xd8,0x7d,0x63, +0x77,0xdd,0x8e,0xec,0x4d,0xed,0x2d,0xed,0x85,0xf6,0x0e,0xf6,0x4e,0xf6,0x6e,0xf6, +0x9e,0xf6,0xfe,0xf6,0x6a,0xfb,0x70,0xfb,0x68,0xfb,0xfb,0xed,0x47,0xd9,0xff,0xc3, +0xfe,0x79,0xfb,0x57,0xec,0x27,0xda,0x4f,0xb3,0x9f,0x63,0xff,0x86,0xfd,0x22,0xfb, +0x44,0xfb,0x34,0xfb,0xe5,0xf6,0x6b,0xec,0x73,0xed,0x8b,0xec,0xb7,0xda,0xef,0xb4, +0xdf,0x63,0x5f,0x63,0xdf,0x64,0x7f,0xc0,0xde,0x4e,0x78,0xd8,0xfe,0x76,0xfb,0xde, +0xb3,0x3f,0x6e,0xdf,0x61,0x7f,0xca,0xfe,0xb4,0xfd,0x47,0xf6,0x9f,0xd8,0x9f,0xb7, +0xef,0xb2,0xef,0xb1,0xff,0xcc,0xfe,0x8a,0xfd,0x55,0xfb,0x6f,0xec,0xbf,0xb3,0xbf, +0x6e,0xbf,0x0c,0x57,0x76,0x13,0xae,0x29,0x7b,0x15,0x3f,0xe2,0xae,0xdf,0xcd,0xab, +0x77,0xc3,0xde,0xc8,0xc1,0xc4,0x61,0xb0,0x83,0x95,0x83,0xc0,0xc1,0xd6,0x41,0xec, +0xe0,0xe8,0x30,0xd2,0x41,0xea,0x20,0x77,0xf0,0x71,0x50,0x38,0x04,0x3a,0x84,0x3b, +0xc4,0x38,0xdc,0xf4,0xed,0x7d,0x0e,0x0f,0x39,0x3c,0xea,0x10,0x2a,0x78,0xd2,0x61, +0x8a,0x40,0x89,0xb9,0xf6,0x25,0xcc,0xc2,0x9b,0x45,0x69,0x02,0x4f,0xe1,0x33,0x0e, +0x2f,0x38,0xbc,0xec,0x30,0xce,0x61,0x92,0xc3,0x54,0x87,0x99,0x0e,0x73,0x1d,0x5e, +0x77,0x78,0xd3,0xa1,0x48,0xb0,0xd8,0x21,0xc1,0x21,0xc5,0x61,0xa9,0x43,0xa6,0xc3, +0x2a,0x87,0xb5,0x0e,0xeb,0x1d,0xf4,0xd7,0xa6,0xc0,0x61,0xa3,0xc3,0x16,0x87,0x12, +0x87,0x5d,0x0e,0x15,0x0e,0xfb,0x1c,0x6a,0x1d,0x1a,0x1d,0x9a,0x1d,0x0e,0x39,0x1c, +0x71,0x38,0xea,0x70,0xdc,0xa1,0xc3,0xe1,0x94,0xc3,0x69,0x87,0x8f,0x1c,0x3e,0x71, +0x38,0xef,0xd0,0xe5,0xd0,0xe3,0xf0,0x99,0xc3,0x15,0x87,0xab,0x0e,0xdf,0x38,0xfc, +0xe0,0xd0,0xe7,0xc0,0x13,0x9b,0x8b,0xad,0xc4,0x42,0xb1,0xbd,0x78,0x84,0x78,0xa4, +0xd8,0x43,0xec,0x23,0x56,0x89,0xd5,0xe2,0x50,0x71,0x84,0x38,0x4a,0x7c,0x8f,0xf8, +0x01,0xf1,0x23,0xe2,0xc7,0xc5,0x4f,0x89,0x9f,0x13,0x8f,0x16,0x8f,0x11,0x4f,0x10, +0x4f,0x16,0x4f,0x17,0xcf,0x16,0xcf,0x13,0x2f,0x10,0xbf,0x2d,0x8e,0x13,0x27,0x89, +0x53,0xc5,0xe9,0xe2,0x15,0xe2,0x2c,0x71,0xb6,0x38,0x4f,0x5c,0x28,0x2e,0x16,0x6f, +0x13,0x97,0x8a,0xcb,0xc4,0x95,0xe2,0x6a,0x71,0xbd,0x78,0xbf,0xb8,0x45,0xdc,0x2a, +0x3e,0x2a,0x6e,0x17,0x77,0x8a,0x4f,0x8b,0xcf,0x88,0xcf,0x89,0xbb,0xc4,0xbd,0xe2, +0xcb,0xe2,0xab,0xe2,0x6b,0xe2,0x1f,0xc4,0x37,0xc4,0x83,0x86,0x09,0x86,0x39,0x0d, +0xf3,0x1a,0x16,0x38,0x2c,0x7a,0xd8,0xc3,0xc3,0x9e,0x1e,0x36,0x71,0xd8,0xdc,0x61, +0x6f,0x0f,0x4b,0x19,0xb6,0x62,0x58,0xfe,0xb0,0x92,0x61,0x95,0xc3,0x1a,0x87,0x1d, +0x1c,0x76,0x7c,0xd8,0x99,0x61,0x97,0x86,0x5d,0x1d,0x66,0x34,0xdc,0x66,0xb8,0xdb, +0x70,0xdf,0xe1,0x91,0xc3,0x47,0x0d,0x7f,0x61,0xf8,0x84,0xe1,0x33,0x87,0x2f,0x18, +0x9e,0x3c,0x7c,0xcd,0xf0,0x8d,0xc3,0x4b,0x87,0xef,0x1b,0xbe,0x7f,0xf8,0xe1,0xe1, +0x6d,0xc3,0x4f,0x0d,0x3f,0x33,0xfc,0xe2,0xf0,0xab,0xc3,0x8d,0x46,0x58,0x8c,0x70, +0x18,0x21,0x1b,0xa1,0x1c,0x11,0x32,0x42,0x3b,0xe2,0xb1,0x11,0xa3,0x47,0x4c,0x1f, +0xf1,0xfa,0x88,0x94,0x11,0x19,0x23,0xd6,0x8d,0x28,0x1a,0xb1,0x63,0xc4,0xde,0x11, +0x4d,0x23,0x8e,0x8e,0x78,0x7f,0xc4,0xc7,0x23,0x7a,0x46,0x7c,0x35,0xe2,0xa7,0x11, +0x83,0x1d,0x45,0x8e,0x8e,0x8e,0x1e,0x8e,0x41,0x8e,0xb1,0x8e,0x0f,0x39,0xbe,0xe0, +0x38,0xd6,0x71,0xa6,0xe3,0x5b,0x8e,0xc9,0x8e,0xcb,0x1d,0x73,0x1c,0xb7,0x38,0xee, +0x74,0xac,0x72,0x6c,0x71,0x7c,0xcf,0xf1,0x23,0xc7,0x6e,0xc7,0xcf,0x1c,0xbf,0x74, +0xbc,0xe6,0x78,0xdd,0x51,0xe7,0x38,0xc8,0x69,0xb0,0x93,0xb5,0x93,0xc8,0xc9,0xc1, +0xc9,0xc9,0xc9,0xcd,0xc9,0xd3,0xc9,0xdf,0x49,0xed,0x14,0xee,0x14,0xed,0x74,0xbf, +0xd3,0x28,0xa7,0x7f,0x38,0x3d,0xef,0xf4,0x8a,0xd3,0x44,0xa7,0x69,0x4e,0x73,0x9c, +0xe6,0x3b,0x2d,0x70,0x7a,0xcb,0x89,0x71,0x4a,0x70,0x4a,0x76,0x4a,0x75,0x4a,0x77, +0x5a,0xe1,0xb4,0xda,0x69,0xbd,0x53,0x91,0xd3,0x36,0xa7,0xdd,0x4e,0xf5,0x4e,0x4d, +0x4e,0xcd,0x4e,0x87,0x9c,0x8e,0x38,0x1d,0x75,0x3a,0xee,0xd4,0xe1,0x74,0xca,0xe9, +0x43,0xa7,0x4f,0x9c,0xce,0x3b,0x75,0x39,0xf5,0x3a,0x5d,0x76,0xfa,0xd2,0xe9,0x6b, +0xa7,0x6f,0x9d,0xae,0x3b,0xf5,0x39,0x19,0x4b,0x4c,0x25,0x43,0x24,0x56,0x92,0xa1, +0x12,0x91,0xc4,0x4e,0x22,0x96,0x38,0x4a,0x9c,0x25,0xae,0x12,0x77,0x89,0xa7,0xc4, +0x57,0xa2,0x90,0x04,0x4a,0x42,0x24,0x11,0x12,0xad,0x24,0x56,0xf2,0xa0,0xa4,0xde, +0xe9,0x71,0xc9,0x53,0x92,0xe7,0x24,0xa3,0x25,0x63,0x24,0x93,0x25,0x73,0x24,0xf3, +0x24,0x6f,0x48,0xde,0x92,0x2c,0x96,0xc4,0x4b,0x92,0x24,0xa9,0x92,0x65,0x20,0x53, +0xb2,0x52,0x92,0x25,0xc9,0x96,0xe4,0x82,0x02,0xc9,0x46,0x49,0x9f,0x6e,0x8b,0x64, +0xbb,0xa4,0x54,0xb2,0x1b,0xa9,0x7d,0x92,0x1a,0x49,0xbd,0xa4,0x49,0xd2,0x2c,0x39, +0x88,0xf6,0x5b,0x25,0xef,0x49,0xda,0x24,0x27,0x24,0xa7,0x24,0xc7,0x9d,0x4e,0x4b, +0xce,0x48,0xce,0xa1,0xc4,0x05,0x49,0x8f,0xe4,0x33,0xc9,0x15,0xc9,0x55,0xc9,0x37, +0x92,0xeb,0x12,0x72,0x36,0x71,0x1e,0xe2,0xcc,0x77,0xb6,0x71,0x16,0x3b,0x3b,0x39, +0xbb,0x3a,0xcb,0x9c,0x7d,0x9c,0x55,0xce,0x21,0xce,0x1a,0xe7,0x7b,0x9c,0x1f,0x72, +0x7e,0xdc,0xf9,0x19,0xe7,0xd1,0xce,0xe3,0x9c,0x27,0x3b,0xcf,0x74,0x9e,0xe7,0xfc, +0xa6,0x73,0x9c,0x73,0x8a,0x73,0xba,0xf3,0x2a,0xe7,0x6c,0xe7,0x02,0xe7,0x62,0xe7, +0x12,0xe7,0x32,0xe7,0x4a,0x67,0x9d,0xae,0x1a,0xd4,0x83,0xfd,0xa0,0x05,0x74,0x98, +0xe9,0x74,0xad,0x88,0x8f,0x82,0x76,0xd0,0x09,0x4e,0x83,0x33,0xe0,0x1c,0xe8,0x02, +0xbd,0xe0,0x32,0xb8,0x0a,0xae,0x81,0x1f,0xc0,0x0d,0x60,0x34,0x52,0xa7,0x33,0x01, +0x83,0x47,0xfe,0xbe,0xf9,0xc7,0x0a,0xe5,0x04,0xc0,0x16,0x88,0x81,0x23,0x18,0x09, +0xa4,0x40,0x0e,0x7c,0x80,0x02,0x04,0x82,0x10,0x10,0x01,0xa2,0x80,0xd3,0x20,0xb7, +0x41,0xff,0x5b,0x9e,0x62,0xf7,0xc0,0x9e,0x07,0xc0,0x23,0xe0,0x71,0xf0,0x14,0x78, +0x0e,0x8c,0x36,0xf8,0x60,0x0c,0xe2,0x09,0x60,0x32,0x98,0x0e,0x66,0x83,0x79,0x60, +0x01,0x78,0x1b,0xc4,0x81,0x24,0x90,0x0a,0xd2,0xc1,0x0a,0x90,0x05,0xb2,0x41,0x1e, +0x28,0x04,0xc5,0x60,0x1b,0x28,0x05,0x65,0xa0,0x12,0x54,0x83,0x7a,0xb0,0x1f,0xb4, +0x80,0x56,0x70,0x14,0xb4,0x83,0x4e,0x70,0xda,0xc0,0xcf,0x3f,0x67,0x90,0x73,0x0e, +0x74,0x8d,0xec,0x45,0x78,0x19,0x5c,0x05,0xd7,0xc0,0x0f,0x03,0x65,0x6f,0x20,0x55, +0xc5,0x7d,0x37,0x66,0xe4,0x82,0xeb,0xe9,0x62,0xf8,0x4e,0x1b,0xb1,0x15,0x10,0x00, +0x5b,0x20,0x06,0x8e,0x60,0x24,0x90,0x02,0x39,0xf0,0x01,0xfb,0x8c,0xb3,0xcd,0x2b, +0xcd,0x15,0x2e,0xb5,0x68,0x21,0xc0,0x25,0xc8,0xe5,0x1d,0xf3,0x50,0x97,0x48,0xe4, +0x47,0x83,0x7b,0xc1,0x83,0x60,0x14,0x78,0x02,0x3c,0x0d,0x9e,0x07,0x2f,0xb9,0x7c, +0x6c,0x3e,0xd6,0x65,0x22,0x52,0x53,0xc0,0x0c,0x97,0xd9,0x08,0xe7,0x81,0x05,0xe0, +0x6d,0x10,0x07,0x92,0x40,0x2a,0x48,0x07,0x2b,0x5c,0x56,0xbb,0xf4,0xaf,0x1c,0xd6, +0xba,0xfc,0xab,0x15,0x9e,0x94,0x4c,0xc8,0x82,0x46,0x52,0x0e,0xd7,0x8b,0x6b,0x14, +0x6a,0x74,0x37,0xae,0xf9,0x23,0x23,0xf3,0x5d,0x86,0x0c,0x2d,0x72,0xf9,0xe5,0x99, +0xcd,0x5c,0xde,0x36,0x97,0x52,0xce,0xaa,0x32,0x97,0x4a,0x97,0x6a,0x97,0x7a,0x97, +0xfd,0x2e,0x2d,0x2e,0xad,0x2e,0x47,0x5d,0xda,0x5d,0x3a,0x5d,0x4e,0xbb,0x9c,0x71, +0x39,0xe7,0xd2,0xe5,0xd2,0xeb,0x72,0xd9,0xe5,0xaa,0xcb,0x35,0x97,0x1f,0x5c,0x6e, +0xb8,0x18,0xb9,0x9a,0xb8,0x0e,0x76,0xb5,0x72,0x15,0xb8,0xda,0xba,0x8a,0x5d,0x1d, +0x5d,0x47,0xba,0x4a,0x5d,0xe5,0xae,0x3e,0xae,0x0a,0xd7,0x40,0xd7,0x10,0xd7,0x08, +0xd7,0x28,0xd7,0x7b,0x5c,0x1f,0x70,0x7d,0xc4,0xf5,0x71,0xd7,0xa7,0x5c,0x9f,0x73, +0x1d,0xed,0x3a,0xc6,0x75,0x82,0xeb,0x64,0xd7,0xe9,0xae,0xb3,0x5d,0xe7,0xb9,0x2e, +0x70,0x7d,0xdb,0x35,0xce,0x35,0xc9,0x35,0xd5,0x35,0xdd,0x75,0x85,0x6b,0x96,0x6b, +0xb6,0x6b,0x9e,0x6b,0xa1,0x6b,0xb1,0xeb,0x36,0xd7,0x52,0xd7,0x32,0xd7,0x4a,0xd7, +0x6a,0xd7,0x7a,0xd7,0xfd,0xae,0x2d,0xae,0xad,0xae,0x47,0x5d,0xdb,0x5d,0x3b,0x5d, +0x4f,0xbb,0x9e,0x71,0x3d,0xe7,0xda,0xe5,0xda,0xeb,0x7a,0xd9,0xf5,0xaa,0xeb,0x35, +0xd7,0x64,0xd1,0x0f,0xae,0x37,0x5c,0x8d,0xdc,0x4c,0xdc,0x5e,0xc2,0x3a,0x7b,0xb0, +0xdb,0x66,0x91,0x95,0x9b,0xc0,0xcd,0xd6,0x4d,0xec,0xe6,0xe8,0x36,0xd2,0x4d,0xea, +0x26,0x77,0xf3,0x71,0x53,0xb8,0x05,0xba,0x85,0xb8,0x45,0xb8,0x45,0xb9,0xdd,0xe3, +0xf6,0x80,0xdb,0x23,0x6e,0x8f,0xbb,0x3d,0xe5,0xf6,0x9c,0xdb,0x68,0xb7,0x31,0x6e, +0x13,0xdc,0x26,0xbb,0x4d,0x77,0x9b,0xed,0x36,0xcf,0x6d,0x81,0xdb,0xdb,0x6e,0x71, +0x6e,0x49,0x6e,0xa9,0x6e,0xe9,0x6e,0x2b,0xdc,0xb2,0xdc,0xb2,0xdd,0xf2,0xdc,0x0a, +0xdd,0x8a,0xdd,0xb6,0xb9,0x95,0xba,0xf5,0x09,0xcb,0xdc,0x2a,0xdd,0xaa,0xdd,0xea, +0xdd,0xf6,0xbb,0xb5,0xb8,0xb5,0xba,0x1d,0x75,0x6b,0x77,0xeb,0x74,0x3b,0xed,0xe6, +0x62,0x73,0xc6,0xed,0x9c,0x5b,0x97,0x5b,0xaf,0xdb,0x65,0xb7,0xab,0x6e,0xd7,0xdc, +0x7e,0x70,0xbb,0xe1,0x66,0x24,0x35,0x91,0x0e,0x96,0x5a,0x49,0x05,0x52,0x5b,0xa9, +0x58,0xea,0x28,0x1d,0x29,0x95,0x4a,0xe5,0x52,0x1f,0xa9,0x42,0x1a,0x28,0x0d,0x91, +0x46,0x48,0xa3,0xa4,0xf7,0x48,0x15,0x6e,0x0f,0x48,0x1f,0x91,0x3e,0x2e,0x7d,0x4a, +0xfa,0x9c,0x74,0xb4,0x74,0x8c,0x74,0x82,0x74,0xb2,0x74,0xba,0x74,0xb6,0x74,0x9e, +0x74,0x81,0xf4,0x6d,0x69,0x9c,0x34,0x49,0x9a,0x2a,0x4d,0x97,0xae,0x90,0x66,0x49, +0x33,0x44,0xd9,0xd2,0x3c,0x69,0xa1,0xb4,0x58,0xba,0x4d,0x5a,0x2a,0x2d,0x93,0x56, +0x4a,0xab,0xa5,0xf5,0xd2,0xfd,0xd2,0x16,0x69,0xab,0xf4,0xa8,0xb4,0x5d,0x5a,0x24, +0xe8,0x94,0x9e,0x96,0x9e,0x91,0x9e,0x93,0x76,0x49,0x7b,0xa5,0x97,0xa5,0x57,0xa5, +0x4f,0x0b,0xae,0x49,0x7f,0x90,0xde,0x90,0x1a,0xb9,0x9b,0xb8,0x0f,0x76,0xb7,0x72, +0x17,0xb8,0xdb,0xba,0x8b,0xdd,0x1d,0xdd,0x47,0xba,0x4b,0xdd,0xe5,0xee,0x3e,0xee, +0x0a,0xf7,0x40,0xf7,0x10,0xf7,0x08,0xf7,0x28,0xf7,0x7b,0xdc,0x1f,0x70,0x5f,0x21, +0x7d,0xc4,0xfd,0x71,0xf7,0xa7,0xdc,0x9f,0x73,0x1f,0xed,0x3e,0xc6,0x7d,0x82,0xfb, +0x64,0xf7,0xc7,0xa5,0xd3,0xdd,0x67,0xbb,0xcf,0x73,0x5f,0xe0,0xfe,0xb6,0x7b,0x9c, +0x7b,0x92,0x7b,0xaa,0x7b,0xba,0xfb,0x0a,0xf7,0x2c,0xf7,0x6c,0xf7,0x3c,0xf7,0x42, +0xf7,0x62,0xf7,0x6d,0xee,0xa5,0xee,0x65,0xee,0x95,0xee,0xd5,0xee,0x0a,0xb7,0x7a, +0xf7,0xfd,0xee,0x2d,0xee,0xad,0xee,0xcf,0xdb,0x1c,0x75,0x6f,0x77,0xef,0x74,0x3f, +0xed,0x7e,0xc6,0xfd,0x9c,0x7b,0x97,0x7b,0xaf,0xfb,0x65,0xf7,0xab,0xee,0xd7,0xdc, +0x7f,0x70,0x7f,0xc8,0xe1,0x86,0xbb,0x91,0x87,0x89,0xc7,0x60,0x0f,0x2b,0x0f,0x81, +0x87,0xad,0x87,0xd8,0xc3,0xd1,0xe3,0x39,0xe9,0x48,0x0f,0xa9,0x87,0xdc,0xc3,0xc7, +0x43,0xe1,0x11,0xe8,0x11,0xe2,0x11,0xe1,0x11,0xe5,0x71,0x8f,0xc7,0x03,0x1e,0x8f, +0x78,0x3c,0xee,0x51,0x24,0x7a,0xca,0xe3,0x39,0x8f,0xd1,0x1e,0x63,0x3c,0x26,0x78, +0x4c,0xf6,0x98,0xee,0x31,0xdb,0x63,0x9e,0xc7,0x02,0x8f,0xb7,0x3d,0xe2,0x3c,0x92, +0x3c,0x3e,0x16,0xa6,0x7a,0xa4,0x7b,0xac,0xf0,0xc8,0xf2,0xc8,0xf6,0xc8,0xf3,0x28, +0xf4,0x28,0xf6,0xd8,0xe6,0x51,0xea,0x51,0xe6,0x51,0xe9,0x51,0xed,0x51,0xef,0xb1, +0xdf,0xa3,0xc5,0xe3,0x41,0x51,0xab,0xc7,0xd3,0xa2,0xa3,0x1e,0xed,0x1e,0x9d,0x1e, +0xec,0x38,0x3e,0x8d,0xf0,0x0c,0x97,0x3a,0xe7,0xd1,0xe5,0xd1,0xeb,0x71,0xd9,0xe3, +0xaa,0xc7,0x35,0x8f,0x1f,0x3c,0x6e,0x78,0x18,0xc9,0xae,0x0b,0x31,0x37,0xc8,0x30, +0x2f,0xc8,0xb8,0x99,0x5c,0x26,0x90,0xe9,0xef,0x00,0x5b,0x99,0x58,0xe6,0x28,0x1b, +0x29,0x93,0xca,0xe4,0x32,0x1f,0x99,0x42,0x16,0x28,0x0b,0x91,0x45,0xc8,0xa2,0x64, +0xf7,0xc8,0x1e,0x90,0x3d,0x22,0x7b,0x5c,0xf6,0x94,0xec,0x39,0x59,0x83,0x60,0xb4, +0x6c,0x8c,0x6c,0x82,0x6c,0xb2,0x6c,0xba,0x6c,0xb6,0x6c,0x9e,0x6c,0x81,0xec,0x6d, +0x59,0x9c,0x2c,0x49,0x96,0x2a,0x4b,0x97,0xad,0x90,0x65,0xc9,0x5e,0x76,0xc8,0x96, +0xe5,0xc9,0x0a,0x65,0xc5,0xb2,0x99,0x0e,0xdb,0x64,0xa5,0xb2,0x32,0x59,0xa5,0xac, +0x5a,0x36,0xd2,0xbd,0x5e,0xb6,0x5f,0xd6,0x22,0x6b,0x95,0x1d,0x95,0xb5,0x43,0x3a, +0x65,0xa7,0x65,0x67,0x64,0xe7,0x64,0x5d,0xb2,0x5e,0xd9,0x65,0xd9,0x55,0x99,0x95, +0xec,0x9a,0xec,0x07,0xd9,0x0d,0x99,0x91,0xdc,0x44,0x3e,0x44,0xce,0xed,0xef,0xe5, +0x42,0xb9,0x9d,0x7c,0x98,0xdc,0x49,0xee,0x22,0x77,0x97,0x7b,0xca,0xef,0x91,0xf9, +0xca,0x95,0x72,0xb5,0xfc,0xb4,0x47,0xa8,0x3c,0x52,0x1e,0x2d,0xbf,0x57,0xfe,0xa0, +0x7c,0x94,0xfc,0x09,0xf9,0xd3,0xf2,0xe7,0xe5,0x2f,0xc9,0xc7,0xca,0x27,0xca,0x27, +0xc8,0xa6,0xc8,0x27,0xcb,0x66,0xc8,0xe7,0xc8,0xe7,0xcb,0x17,0xca,0x17,0xc9,0xcf, +0x78,0x24,0xb9,0xc5,0xcb,0x93,0xe5,0xd1,0xc2,0x2c,0xe9,0x39,0xf7,0x34,0x79,0x86, +0x3c,0x49,0xb6,0x52,0x9e,0x2a,0x5b,0x23,0xcf,0x91,0xe7,0xcb,0xbb,0x3c,0x8a,0xe4, +0x9b,0xe5,0xdb,0xe5,0x3b,0xe5,0xe5,0xf2,0x5e,0x8f,0xbd,0xf2,0x1a,0x79,0x83,0xfc, +0x1d,0xf9,0x41,0xf9,0x11,0x79,0xb5,0xec,0x98,0xfc,0x84,0x7c,0xa4,0xfb,0x29,0x79, +0xab,0xec,0x43,0xf9,0xc7,0xf2,0xf3,0xf2,0x6e,0xf9,0x25,0xf9,0x19,0xd9,0x15,0xf9, +0x60,0xd9,0x57,0xf2,0x73,0xb2,0x07,0xa4,0xdf,0xca,0xbb,0x64,0xd7,0xe5,0x97,0x65, +0x7d,0x72,0x63,0x4f,0x53,0xcf,0x21,0x9e,0xd6,0x9e,0xd7,0x64,0x37,0x3c,0x84,0x9e, +0x3f,0xc8,0xec,0x3c,0x6f,0xc8,0x86,0x79,0xbe,0x64,0xe3,0xe4,0xe9,0xea,0x29,0xf3, +0xf4,0xf1,0x54,0x78,0x06,0x7a,0x86,0x78,0x46,0x7a,0xc6,0x78,0xde,0xef,0xf9,0xb0, +0xe7,0xdd,0xdc,0xff,0x3e,0xe6,0xf9,0xa4,0xe7,0xd3,0x9e,0xcf,0x79,0x8e,0xf6,0x1c, +0x03,0xf9,0xb5,0x52,0xe3,0x3d,0x27,0x7b,0xce,0xf0,0x9c,0xeb,0xf9,0xc6,0x2d,0x25, +0xde,0xf6,0xd4,0xe9,0xe2,0x3d,0x53,0x3c,0xdf,0xb2,0x4a,0xb2,0x4a,0xf3,0x4c,0xf7, +0x5c,0xee,0xb9,0xca,0x73,0x8d,0x67,0xb6,0x67,0xac,0x55,0xae,0x67,0xa1,0xe7,0x66, +0xcf,0x52,0xcf,0x3d,0x9e,0xd5,0x9e,0x0d,0x9e,0xcd,0x9e,0x87,0x3d,0x8f,0x7a,0x9e, +0xf0,0x7c,0xdf,0xf3,0x23,0xd4,0x3e,0xe7,0xd9,0xed,0xf9,0x99,0xe7,0x97,0x9e,0xd7, +0x90,0xbe,0x0e,0x74,0x9e,0x83,0xbc,0xfa,0x74,0x83,0xbd,0xac,0x11,0x8a,0xbc,0x1c, +0xbc,0x1c,0xbd,0x5c,0xbc,0x3c,0xbc,0xbc,0xbd,0x14,0x5e,0x6a,0xaf,0x30,0x2f,0xad, +0xd7,0x3d,0x90,0xfb,0x0d,0xf2,0x90,0x41,0x46,0x19,0xe4,0x71,0x83,0xfc,0xc3,0x20, +0xcf,0x18,0xe4,0x79,0x83,0x8c,0x36,0xc8,0x2b,0x06,0x19,0x67,0x90,0x89,0x06,0x99, +0x6c,0x90,0x69,0x90,0x99,0x90,0x39,0x90,0x79,0x90,0x37,0x20,0x6f,0x42,0x16,0x19, +0x24,0xce,0x20,0x89,0x06,0x49,0x31,0x48,0x1a,0x24,0xdd,0x20,0xcb,0x21,0xab,0x0c, +0xb2,0xc6,0x20,0xd9,0x90,0x5c,0xc8,0x9f,0x7f,0xda,0x14,0x78,0xe9,0xa5,0x08,0x52, +0x0c,0xd9,0x0a,0x39,0x63,0x52,0xe2,0x55,0xe2,0xb5,0x13,0x52,0x06,0xd9,0x63,0x90, +0x7d,0x90,0x1a,0x48,0x23,0xe4,0x00,0xa4,0x15,0x72,0x0c,0xd2,0x01,0xf9,0x80,0x93, +0x33,0x9c,0x9c,0x37,0x48,0x97,0xd7,0x25,0xaf,0x2f,0x70,0xfc,0x8d,0xd7,0x0f,0x5e, +0x7d,0x5e,0x3c,0x6f,0x73,0x6f,0x2b,0x6f,0xa1,0xb7,0xbd,0xf7,0x08,0xef,0x91,0xde, +0xee,0xde,0x5e,0xde,0xfe,0xde,0x81,0xde,0xa1,0xde,0x1a,0xef,0x58,0xef,0x07,0xbc, +0x47,0x79,0x3f,0xe9,0xfd,0xac,0xf7,0x68,0xef,0xb1,0xde,0x93,0xbc,0xa7,0x79,0xcf, +0xf6,0x9e,0xef,0xfd,0xa6,0x37,0xe3,0x9d,0xe4,0x9d,0xe6,0x9d,0xe9,0xbd,0xda,0x3b, +0xdb,0x3b,0xdf,0x7b,0xa3,0xf7,0x56,0xef,0x52,0xef,0x72,0xef,0x7d,0xde,0x75,0xde, +0xfb,0xbd,0x0f,0x7a,0xbf,0xeb,0x7d,0xdc,0xbb,0xd3,0xfb,0x43,0xef,0x4f,0xbc,0x2f, +0x78,0xf7,0x7a,0x5f,0xf1,0xfe,0xda,0xfb,0x7b,0xef,0x1b,0xde,0xc6,0x3e,0x66,0x3e, +0x96,0x3e,0x02,0x1f,0x3b,0x9f,0xe1,0x3e,0xce,0x3e,0x52,0x1f,0x4f,0x1f,0x3f,0x9f, +0x00,0x9f,0x10,0x9f,0x48,0x9f,0x18,0x9f,0xfb,0x7d,0x1e,0xf1,0x79,0xc2,0xe7,0x19, +0x9f,0x17,0x7d,0xc6,0xf8,0x4c,0xf4,0x99,0xea,0x33,0xcb,0x67,0x9e,0xcf,0x42,0x9f, +0xc5,0x3e,0x89,0x3e,0xa9,0x3e,0x19,0x3e,0xab,0x7c,0xd6,0xf9,0xe4,0xf9,0x14,0xf9, +0x6c,0xf1,0xd9,0xe1,0x53,0xe6,0xb3,0xd7,0xa7,0xce,0xe7,0x1d,0x9f,0xc3,0x3e,0xc7, +0x7c,0x4e,0xfa,0x7c,0xe8,0xf3,0x89,0xcf,0x17,0x5e,0x17,0x7c,0xd8,0x9e,0xf4,0xfa, +0x5c,0xf1,0x31,0xf7,0xfe,0xda,0x87,0xed,0xc9,0xf7,0x3e,0x37,0x7c,0xdc,0xbd,0x8d, +0x7d,0xd9,0x9e,0x98,0xf9,0x5a,0xfa,0x86,0x7a,0x0b,0x7c,0xd9,0xde,0xb0,0x56,0xe9, +0x2d,0xea,0xb7,0x45,0x6f,0x85,0x9d,0xef,0xfd,0x3e,0xc3,0x7d,0x9d,0x7d,0x27,0xfa, +0x48,0x7d,0x59,0xed,0x65,0x3e,0x9e,0xbe,0x7e,0xbe,0xeb,0x7c,0x02,0x7c,0x59,0xbd, +0xac,0xb7,0x42,0x7c,0xbf,0xf0,0x8a,0xf4,0xed,0xf7,0x56,0x8c,0x6f,0xbf,0xaf,0xee, +0x47,0xdb,0x37,0x7d,0x74,0xab,0x87,0x1e,0xf1,0xbd,0xd5,0x47,0xbf,0xf4,0x10,0xeb, +0x9d,0x9b,0x7e,0xe9,0xf7,0xc9,0x13,0xbe,0xfd,0x1e,0xe9,0xf7,0xc6,0x33,0xbe,0xac, +0x2f,0x5e,0xf4,0xed,0xf7,0xc4,0x18,0xce,0x12,0xd6,0x06,0xbd,0xf6,0x89,0xbe,0x6f, +0x7a,0x4f,0xf5,0x9d,0xe5,0x3b,0xcf,0x97,0x6d,0xc7,0x93,0xab,0xc1,0x96,0x5a,0xe8, +0x1b,0xe7,0xbb,0xc4,0x37,0xd3,0x77,0xb5,0x6f,0xb6,0x6f,0xbe,0xef,0x46,0xdf,0xad, +0xbe,0xa5,0xbe,0xe5,0xbe,0xfb,0x7c,0xeb,0x7c,0xf7,0xfb,0x1e,0xf4,0x7d,0xd7,0xf7, +0xb8,0x6f,0xa7,0xef,0x87,0xbe,0x9f,0xf8,0x5e,0xf0,0xed,0xf5,0xbd,0xe2,0xfb,0xb5, +0xef,0xf7,0xbe,0x37,0xd0,0x8a,0xb1,0x9f,0x99,0x9f,0xa5,0x9f,0xc0,0xef,0x8f,0xd6, +0xeb,0x3f,0x9e,0x0a,0x7b,0x36,0x1a,0xbc,0xa1,0xcf,0x63,0x47,0x89,0x9d,0x9f,0x9d, +0xdf,0xef,0x19,0xf9,0xc3,0xfd,0x5c,0x20,0x72,0x3f,0x7f,0xbf,0x20,0xbf,0x48,0xbf, +0x7b,0xfc,0x1e,0x86,0x3c,0xe9,0xf7,0xbc,0xdf,0x18,0xbf,0x57,0xfd,0x66,0xfa,0xcd, +0x87,0xbc,0xed,0x97,0x08,0x59,0x0a,0x59,0xe9,0x97,0x0d,0xd9,0xe0,0xb7,0x05,0xb2, +0x13,0x52,0xe9,0x57,0x07,0x69,0x86,0x1c,0xf1,0x6b,0xf7,0xfb,0xc0,0xef,0x13,0x48, +0xb7,0xdf,0x65,0xbf,0x6f,0xfc,0x7e,0xf4,0x33,0xf6,0x37,0xf6,0x1f,0xec,0x3f,0xd4, +0xdf,0xde,0xdf,0xc9,0x5f,0xea,0x8f,0xc1,0xe1,0xaf,0x82,0x84,0x42,0xa2,0xfc,0xef, +0xf7,0x7f,0xd4,0xff,0x69,0xff,0xd1,0xfe,0xe3,0xfd,0xa7,0xfa,0xb3,0x36,0xcc,0xf1, +0x5f,0xe0,0xcf,0xf8,0xa7,0xf8,0x67,0xf8,0x67,0x41,0x72,0xfd,0x37,0xfa,0x6f,0xf7, +0x2f,0x83,0x54,0xf9,0x37,0xfa,0x1f,0xf4,0x3f,0xea,0x7f,0xd2,0xff,0x9f,0xfe,0xe7, +0xfd,0x7b,0xfd,0xbf,0xf4,0xff,0xce,0xbf,0xcf,0xdf,0x44,0x61,0xa9,0x10,0x29,0x86, +0x29,0x46,0x2a,0x64,0x0a,0x3f,0x85,0x5a,0x11,0xa1,0x88,0x55,0x3c,0xa4,0x18,0x0c, +0x4d,0x4f,0x28,0x9e,0x53,0xbc,0xa2,0x98,0xa4,0x98,0xa1,0x98,0x07,0x5e,0x51,0xbc, +0xa5,0x48,0x50,0xa4,0x29,0x56,0x28,0xd6,0xe1,0xf8,0x03,0x58,0x5f,0xa0,0xd8,0xac, +0xf8,0xe3,0xdf,0x84,0xde,0x59,0x4a,0x15,0x7b,0x14,0xb5,0x8a,0x03,0x8a,0xa3,0x8a, +0x53,0x8a,0x4f,0x14,0x3d,0x8a,0xab,0x8a,0xeb,0x0a,0x23,0xa5,0xab,0x52,0xa5,0xbc, +0xfd,0x37,0xfd,0xee,0xfc,0x09,0x57,0x46,0x2a,0xfb,0x74,0xd1,0x4a,0x9d,0x71,0xac, +0xf2,0x5e,0xe5,0xfd,0xca,0x87,0x95,0xff,0xde,0x37,0x08,0x78,0xc2,0x28,0xff,0xa1, +0x7c,0x16,0xc2,0xfe,0x3e,0xc3,0xf3,0xca,0x17,0x95,0x2f,0x29,0xc7,0x2a,0x27,0x2a, +0xa7,0x28,0x67,0x28,0xe7,0x28,0xd9,0xef,0x8a,0xe7,0x2b,0x17,0x2a,0x17,0x29,0xe3, +0x39,0x7b,0x92,0x95,0x4b,0x94,0x23,0xac,0xf4,0xf2,0x2c,0x57,0x4b,0xaf,0x1f,0x7a, +0x8c,0xa3,0xa1,0x3f,0x56,0xf9,0xd8,0xcf,0xda,0x49,0x53,0x2e,0x53,0x66,0x28,0x63, +0xad,0x96,0x2b,0x57,0x2a,0x57,0x2b,0x1f,0xb4,0xea,0xd3,0xad,0x51,0xae,0x53,0xe6, +0x28,0x73,0x07,0xac,0xcc,0x57,0x16,0x29,0xb7,0xa0,0xed,0x12,0xe4,0xec,0x52,0x56, +0x28,0xab,0x94,0x75,0xca,0xfd,0xca,0x16,0xe5,0x11,0xe5,0x31,0x65,0x87,0xf2,0x7d, +0xe5,0x47,0xca,0x4f,0x20,0xe7,0x21,0x5d,0x90,0x1e,0xc8,0x67,0x06,0xb9,0x02,0xb9, +0x6a,0x90,0x6f,0x20,0xdf,0x19,0xe4,0xba,0x41,0x6e,0x18,0x84,0x54,0x7a,0xe1,0x19, +0xc4,0x14,0x32,0x18,0x62,0x09,0xe1,0x43,0x84,0x06,0xb1,0x35,0x88,0x83,0x41,0x86, +0x1b,0xc4,0xc9,0x20,0x23,0x0d,0xe2,0x66,0x10,0x0f,0x83,0x78,0x1a,0xc4,0xc7,0x20, +0xfe,0x06,0xe9,0xff,0xa8,0x0d,0x12,0x62,0x90,0x70,0x83,0x68,0x20,0xec,0xd3,0x20, +0x5a,0xa5,0x97,0x7b,0x20,0x0f,0x42,0x1e,0x85,0xfc,0x03,0xa2,0xff,0x4d,0x95,0x3e, +0x5d,0xac,0xf2,0x39,0x55,0x1a,0xe7,0xb5,0x65,0xca,0x17,0x54,0xac,0x77,0x59,0x8f, +0x86,0x2b,0x97,0x2b,0x27,0xda,0x8c,0x56,0xdd,0xe9,0xf7,0x53,0xd8,0xd1,0xb0,0x12, +0xde,0x5e,0x8d,0x2b,0x92,0xab,0xfc,0x23,0xdf,0x50,0x27,0x2b,0xd7,0xe0,0x4a,0xbf, +0xac,0x7a,0x56,0xf9,0xae,0xe5,0x1f,0xa9,0xff,0xbc,0x72,0x8c,0xea,0x45,0xe5,0x38, +0xd5,0x04,0xd5,0x64,0xd5,0x44,0x1b,0x76,0x04,0x45,0x2a,0xa7,0xab,0x7e,0x10,0xcf, +0x56,0xcd,0x53,0x2d,0x50,0xbd,0xad,0x8a,0x53,0x25,0xa9,0x52,0x55,0xe9,0xaa,0x15, +0xaa,0x2c,0xd5,0x5f,0xf5,0x06,0x2d,0x5b,0x95,0xa7,0x2a,0x54,0x11,0xfd,0x99,0xf7, +0xcb,0xfa,0x31,0x7a,0xeb,0x5b,0x66,0xf6,0xf8,0xd6,0x37,0xcd,0xec,0xf1,0xad,0x6f, +0x9b,0xd9,0x63,0xfd,0x1b,0x67,0x7d,0xdd,0x62,0xd5,0x56,0x55,0x89,0x2a,0x8c,0x76, +0xaa,0xca,0x54,0x7b,0x70,0x4d,0xab,0x54,0x75,0xaa,0x26,0xd5,0x01,0xd5,0x61,0xd5, +0x7b,0xaa,0xe3,0xaa,0xdf,0x9e,0x1f,0x4e,0xaa,0x4e,0xab,0x3e,0x56,0x7d,0xaa,0xea, +0x51,0x5d,0x56,0x7d,0xa5,0xfa,0x4e,0xf5,0x93,0xca,0x28,0xc0,0x34,0xc0,0x22,0x60, +0x68,0x80,0x6d,0xc0,0xb0,0x00,0x49,0x80,0x5b,0x80,0x3c,0xc0,0x37,0x40,0x15,0x10, +0x1c,0x10,0x11,0x10,0x1d,0x70,0x5f,0xc0,0xc3,0x01,0x8f,0x07,0x3c,0x1d,0xf0,0x42, +0xc0,0x2b,0x01,0x13,0x02,0xa6,0x04,0xcc,0x0c,0x78,0x2d,0x60,0x41,0xc0,0xa2,0x80, +0x84,0x80,0x25,0x01,0xe9,0x01,0x2b,0x03,0xd6,0x06,0xfc,0xa7,0x7f,0x9f,0xfa,0xb7, +0xbe,0x03,0xcd,0x0d,0x28,0x0c,0xd8,0x1c,0x50,0x12,0xb0,0x3b,0xa0,0x32,0xa0,0x26, +0xa0,0x31,0xe0,0x40,0x40,0x6b,0xc0,0xb1,0x80,0x8e,0x80,0x0f,0x02,0xce,0x04,0x9c, +0x0f,0xb8,0x18,0xf0,0x79,0xc0,0xd5,0x80,0x6f,0x03,0x7e,0x0c,0xa0,0x40,0x93,0xc0, +0x21,0x81,0xfc,0x40,0x9b,0x40,0x71,0xa0,0x53,0xa0,0x6b,0xa0,0x2c,0xd0,0x27,0x50, +0x19,0x18,0x14,0x18,0x1e,0x18,0x15,0x78,0x6f,0xe0,0x43,0x81,0x77,0xfb,0x5b,0x8a, +0xbf,0xaa,0xbd,0xdb,0x67,0xe7,0xc7,0x02,0x9f,0x0a,0x7c,0x3e,0xf0,0xe5,0xc0,0xf1, +0x81,0x93,0x03,0x67,0x04,0xce,0x0d,0x7c,0x23,0xf0,0xed,0xc0,0x78,0xf4,0x26,0x25, +0x70,0x59,0xe0,0x8a,0xc0,0x35,0x81,0xeb,0x03,0x37,0x04,0x16,0x07,0x6e,0x0f,0xdc, +0x15,0xb8,0x27,0xb0,0x3a,0xb0,0x21,0xb0,0x39,0xf0,0x70,0xe0,0x51,0x9c,0x3f,0x11, +0xf8,0x7e,0xe0,0x47,0x81,0xe7,0x02,0xbb,0x03,0x3f,0x0b,0xfc,0x12,0xc7,0xd7,0x02, +0xaf,0x07,0xf6,0xfd,0xe6,0xf7,0xc1,0xbf,0xef,0x7c,0xdf,0xcf,0x7e,0x63,0x4f,0x17, +0x68,0xac,0x7e,0x8d,0x4c,0xd4,0x8b,0x8d,0xfa,0x74,0xe6,0x6a,0x0b,0x35,0x5f,0x2d, +0x54,0xb3,0x7f,0x03,0x6f,0xab,0x16,0xab,0x47,0xa8,0x25,0xea,0x19,0x2e,0x2e,0xea, +0x8d,0x46,0x52,0xf5,0x35,0x92,0xa9,0xbd,0xd4,0xbe,0x6a,0x85,0x3a,0x40,0xad,0x70, +0x09,0x52,0x87,0xab,0xb5,0xea,0x18,0xf5,0xfd,0xea,0x87,0xd4,0x5b,0xe8,0x31,0xf5, +0x6a,0x97,0x91,0xf4,0xa4,0xfa,0x69,0xb5,0x60,0xe8,0x0b,0xea,0x03,0x46,0x2f,0xa9, +0xc7,0xa8,0xc7,0xab,0x5f,0x55,0x1f,0x37,0x9a,0xaa,0xee,0xd3,0xcd,0x54,0xcf,0x51, +0xcf,0x53,0xbf,0xa1,0x7e,0x53,0xbd,0x48,0x1d,0xa7,0x4e,0x54,0xa7,0xaa,0x83,0x5c, +0x32,0xd4,0x2b,0xd4,0x01,0x2e,0xab,0xd5,0xd9,0xea,0x7c,0xf5,0x46,0xf5,0x56,0x75, +0xa9,0xba,0x5c,0xbd,0x4f,0x5d,0xa7,0xde,0xaf,0x3e,0xa8,0x7e,0x57,0x7d,0x5c,0xdd, +0xa9,0xfe,0x50,0xfd,0x89,0xfa,0x82,0xba,0x57,0x7d,0x45,0xfd,0xb5,0xfa,0x7b,0xf5, +0x0d,0xb5,0x71,0x90,0x59,0x90,0x65,0x90,0x20,0xc8,0x2e,0x68,0x78,0x90,0x73,0x90, +0x34,0xc8,0x33,0xc8,0x2f,0x28,0x20,0x28,0x24,0x28,0x32,0x28,0x26,0xe8,0xfe,0xa0, +0x47,0x82,0x9e,0x08,0x7a,0x26,0xe8,0xc5,0xa0,0x31,0x41,0x13,0x83,0xa6,0x06,0xcd, +0x0a,0x9a,0x17,0xb4,0x30,0x68,0x71,0x50,0x62,0x50,0x6a,0x50,0x46,0xd0,0xaa,0xa0, +0x3f,0xfe,0x0d,0xfc,0xba,0xa0,0xbc,0xa0,0xa2,0xa0,0x2d,0x41,0x3b,0x82,0xca,0x82, +0xf6,0x06,0xd5,0x06,0x35,0x05,0xb5,0x04,0x1d,0x09,0x6a,0x0b,0x3a,0x19,0x74,0x3a, +0xe8,0xe3,0xa0,0x4f,0x83,0x7a,0x82,0x2e,0x07,0x7d,0x15,0xf4,0x5d,0xd0,0x4f,0x41, +0x46,0xc1,0x7f,0x64,0x44,0xfd,0xd9,0xf5,0x85,0x69,0xb0,0x45,0xf0,0xd0,0x60,0xdb, +0xe0,0x61,0xc1,0x92,0x60,0xb7,0x60,0x79,0xb0,0x6f,0xb0,0x2a,0x38,0x38,0x38,0x22, +0x38,0x3a,0xf8,0xbe,0xe0,0x87,0x83,0x1f,0x0f,0x7e,0x3a,0xf8,0x85,0xe0,0x57,0x82, +0x27,0x04,0x4f,0x09,0x9e,0x19,0xfc,0x5a,0xf0,0x82,0xe0,0x45,0xc1,0x09,0xc1,0x4b, +0x82,0xd3,0x83,0x57,0x06,0xaf,0x0d,0xce,0x0d,0x2e,0x0c,0xde,0x1c,0x5c,0x12,0xbc, +0x3b,0xb8,0x32,0xb8,0x26,0xb8,0x31,0xf8,0x40,0x70,0x6b,0xf0,0xb1,0xe0,0x8e,0xe0, +0x0f,0x82,0xcf,0x04,0x9f,0x0f,0xbe,0x18,0xfc,0x79,0xf0,0xd5,0xe0,0x6f,0x83,0x7f, +0x0c,0xa6,0x10,0x93,0x90,0x21,0x21,0xfc,0x10,0x9b,0x10,0x71,0x88,0x53,0x88,0x6b, +0x88,0x2c,0xc4,0x27,0x44,0x19,0x12,0x14,0x12,0x1e,0x12,0x15,0xf2,0x3f,0xf7,0x97, +0x1c,0x7a,0xb9,0x37,0xe4,0xa1,0x90,0xc7,0x42,0x9e,0x0a,0x79,0x3e,0xe4,0xe5,0x90, +0xf1,0x21,0x93,0x43,0x66,0x84,0xcc,0x0d,0x79,0x23,0xe4,0xed,0x90,0xf8,0x90,0x94, +0x90,0x65,0x21,0x2b,0x42,0xd6,0x84,0xac,0x0f,0xd9,0x10,0x52,0x1c,0xb2,0x3d,0x64, +0x57,0xc8,0x9e,0x90,0xea,0x90,0x86,0x90,0xbf,0xe2,0xbb,0xce,0xe6,0x90,0x23,0x21, +0xed,0x21,0x1f,0x84,0xdc,0xf9,0x8a,0xea,0xfe,0xad,0xdf,0x00,0xf9,0xed,0xf1,0x79, +0x6b,0xfe,0x2f,0x7f,0xfb,0xf5,0xee,0xfc,0xfd,0xd9,0x9d,0xff,0xa6,0xe2,0x8f,0xfc, +0x2e,0xdc,0x2f,0xd7,0x2f,0x3f,0xff,0x8d,0xe1,0x3f,0xfe,0xf9,0x24,0xa4,0x27,0xe4, +0x6a,0x48,0x5f,0x88,0x45,0xa8,0x43,0xa8,0x34,0xf4,0xf7,0xfd,0x3d,0xcd,0xaf,0xff, +0x55,0xcd,0x7f,0xf2,0xa3,0x0c,0x0d,0x0b,0x8d,0x0d,0x7d,0x3c,0xf4,0xa5,0xd0,0xa9, +0xa1,0xff,0xb3,0x96,0xfc,0xa7,0x7e,0x27,0xf2,0xcf,0xd7,0xe9,0xd3,0xfd,0xef,0xb2, +0xad,0x4f,0xc7,0xd6,0x61,0xc7,0xb0,0x15,0x17,0xb2,0x75,0xd8,0xb8,0xbf,0x0e,0xfb, +0xcd,0xc7,0x9d,0xf5,0xf4,0xe9,0x2c,0xc0,0xcf,0xf5,0xf4,0xe9,0xfe,0xe7,0x7d,0xdd, +0xa7,0xbb,0xe9,0x6b,0x7d,0x7f,0x6e,0xad,0x73,0x7b,0x7f,0xfa,0x74,0x77,0x43,0xcf, +0xcd,0x3a,0x7d,0x3a,0x47,0xea,0xff,0xc6,0xe8,0xee,0xe8,0xf9,0xbb,0xce,0xdf,0x75, +0xfe,0x53,0x75,0xde,0x08,0x7d,0x33,0x74,0x51,0x68,0xdf,0xef,0xf8,0x6f,0x35,0x41, +0xbc,0x9f,0xff,0xb7,0x9a,0xb8,0xd0,0xdf,0xae,0xf3,0xe8,0x6d,0x75,0x92,0x42,0x7d, +0x51,0x2e,0x14,0xc7,0x0f,0xe3,0xfc,0xdf,0x3a,0xff,0x6f,0xe9,0x9c,0x0b,0x61,0xe7, +0xc1,0x3b,0xad,0x9d,0xee,0x76,0x5e,0xea,0x6d,0xeb,0x8f,0x0c,0x1c,0xaf,0xe2,0xf2, +0xd6,0x19,0xce,0xe4,0xfd,0x5b,0x2b,0x94,0x22,0x94,0xde,0x02,0x76,0x80,0x32,0x43, +0xcd,0xbd,0x88,0x6b,0x41,0x13,0x68,0x01,0x47,0x40,0x1b,0x38,0x19,0xfa,0xdb,0x7b, +0xa0,0x9b,0x9f,0x45,0xa1,0x3a,0x5d,0xdf,0x7f,0x50,0x4e,0x87,0x7e,0x1c,0xfa,0x69, +0xe8,0x66,0xa3,0x9e,0xd0,0x02,0xe3,0x93,0x64,0x67,0xec,0x64,0x94,0x65,0xfc,0x79, +0xe8,0xd5,0xd0,0x12,0xe3,0x6f,0x43,0xaf,0x87,0xce,0x32,0x5e,0xeb,0xa2,0x0b,0x35, +0x0e,0x33,0x09,0x1b,0x12,0xc6,0x0f,0x13,0x86,0xd9,0x85,0x0d,0x0f,0x73,0x0e,0x73, +0x0d,0xf3,0x08,0xf3,0x0a,0xf3,0x0b,0x53,0x85,0xa9,0xc3,0x42,0xc2,0xc2,0xc3,0x34, +0x61,0xd1,0x61,0xf7,0x84,0xdd,0x1f,0xc6,0x5e,0xe3,0x87,0xc2,0x1e,0x0d,0x7b,0x32, +0xec,0x99,0xb0,0xb1,0x2e,0x4b,0x8d,0x76,0x19,0xed,0x37,0x7a,0x21,0xec,0xa8,0xd1, +0x4b,0x61,0xff,0xde,0x4e,0xfe,0xce,0x6f,0x5d,0xfa,0x7e,0x51,0xf7,0x66,0x2f,0x7e, +0xf9,0xff,0xa3,0xf4,0xff,0x3d,0xea,0xce,0xff,0x3b,0x6a,0x24,0xf7,0x5f,0xa3,0x1c, +0x47,0x7e,0x30,0xa8,0x9c,0x57,0xc5,0xfb,0x72,0x50,0xf6,0xa0,0x3d,0x83,0xee,0xdc, +0x02,0x5b,0x9f,0xf7,0xb3,0xba,0xec,0x7f,0x9d,0x9a,0x86,0x7a,0xbb,0x78,0x47,0x79, +0xab,0x06,0xb5,0x3b,0xe7,0x0e,0xfa,0x3d,0x5e,0x1e,0x17,0xf6,0x6a,0xd8,0xf4,0xb0, +0x39,0x61,0xaf,0x87,0xbd,0x15,0x16,0x17,0x96,0x1c,0xb6,0x34,0x6c,0x79,0x58,0x56, +0x58,0x4e,0x58,0x41,0xd8,0xa6,0xb0,0x6d,0x61,0x3b,0xc3,0x2a,0xc2,0xaa,0xc2,0xea, +0xc3,0xde,0x09,0x3b,0x14,0xf6,0x5e,0x58,0x7b,0xd8,0xa9,0xb0,0x7f,0x86,0x9d,0x0d, +0xeb,0x0a,0xbb,0x14,0xf6,0x45,0xd8,0x37,0x61,0x3f,0x84,0xf5,0x85,0xf1,0xc2,0xcd, +0xc3,0xff,0xcc,0xfa,0x97,0x7d,0xc7,0x7c,0x43,0x69,0xaa,0xea,0xd3,0x69,0x54,0x7c, +0x15,0xa9,0x9c,0x54,0xd1,0xdc,0xbb,0x5d,0xf6,0x7d,0xae,0x50,0xe5,0xa6,0xf2,0x54, +0x39,0xa8,0x7c,0x54,0x96,0x2a,0x5b,0x15,0xfb,0xe6,0x99,0xa7,0x1a,0xac,0x1a,0xae, +0x1a,0xa9,0xf2,0x50,0x59,0x85,0xa7,0x79,0x0d,0x0d,0x17,0x85,0xf7,0xe9,0xd8,0xfa, +0x7d,0xba,0x70,0xfd,0xfb,0x5c,0x84,0x77,0xaa,0xdf,0xa7,0xeb,0xaf,0x8f,0xf5,0x21, +0xf0,0xf8,0xd9,0x9b,0xc1,0x1b,0x03,0x6f,0xcb,0xf5,0xf5,0xfb,0x74,0x2a,0xa0,0xaf, +0xdf,0xa7,0xeb,0xaf,0xcf,0x9e,0xbf,0xb5,0x7e,0x1a,0xfb,0x8d,0xed,0x2f,0xf4,0xeb, +0xed,0xc7,0xdc,0xf1,0x2f,0xf4,0xeb,0xed,0xef,0xd3,0x0d,0x05,0xfd,0xfd,0x67,0xdf, +0x57,0xf7,0xf7,0x9f,0xd5,0xff,0x5b,0xfd,0xbf,0x69,0xfd,0x2f,0xfd,0xf7,0xef,0xd5, +0xb7,0x0b,0x17,0x87,0x8f,0x08,0x97,0x84,0xbb,0x84,0x4b,0xc3,0x65,0xe1,0x5e,0xe1, +0xbe,0xe1,0x8a,0x5b,0xae,0xe8,0x1f,0xf9,0x3b,0xaf,0x80,0x70,0x13,0x3c,0xa1,0x4b, +0x25,0xe1,0xe1,0x7f,0x6c,0x7f,0xa3,0x09,0x4f,0x95,0x44,0x87,0x2f,0x0a,0xbd,0x27, +0xfc,0x81,0x3f,0x34,0xb6,0x1e,0x0e,0x7f,0x34,0xfc,0x89,0xf0,0xbb,0xb3,0x3f,0x7b, +0x2a,0xfc,0xee,0xbc,0x27,0xf9,0x35,0x79,0x36,0xfc,0xe5,0xf0,0xc9,0xe2,0x5f,0x3f, +0x3f,0x44,0x38,0x31,0x7c,0x4a,0xf8,0x8c,0x70,0x77,0xc1,0x9c,0xf0,0xf9,0xe1,0xce, +0x76,0x0b,0xc3,0x17,0x85,0xc7,0x87,0x57,0xbb,0x27,0x87,0xa7,0x85,0x67,0x84,0xaf, +0x0c,0x5f,0x13,0x9e,0x13,0x9e,0x23,0xcc,0x0f,0x2f,0x0a,0xdf,0x1c,0xbe,0x3d,0x7c, +0x67,0x78,0x79,0xb8,0xb5,0x80,0xec,0xf6,0x86,0x17,0x38,0x58,0xda,0x6d,0x74,0xa8, +0x09,0x5f,0x28,0x6a,0x08,0x7f,0x27,0xfc,0x60,0xf8,0x91,0xf0,0x63,0xe1,0x2f,0x38, +0x28,0x85,0x27,0xc2,0x4f,0x85,0x7f,0x18,0xfe,0x71,0x78,0x7f,0xfb,0xe7,0xc3,0x3f, +0x0f,0xff,0x36,0x9c,0x22,0x86,0x44,0xd8,0x44,0x38,0x45,0xc8,0x22,0x94,0x11,0x3f, +0xd7,0x1f,0x1e,0xa1,0x8d,0xf8,0xbd,0xef,0x2f,0xfe,0xea,0xf7,0x1f,0x7f,0xe4,0x73, +0xe7,0xf7,0x1f,0x37,0xf5,0xc7,0x46,0xdc,0x1f,0xf1,0x70,0xc4,0x63,0x11,0x4f,0x45, +0xf8,0xc8,0x9e,0x8b,0x18,0x1d,0x31,0x26,0x62,0x42,0x84,0x42,0x36,0x39,0x62,0x7a, +0xc4,0xec,0x88,0x40,0xd9,0xfc,0x88,0x85,0x11,0x8b,0x22,0xe2,0x23,0x52,0x22,0x96, +0x46,0x64,0x84,0x67,0x46,0xac,0x8e,0x58,0x17,0x91,0x1b,0xb1,0x21,0x42,0x28,0xdf, +0x14,0x31,0x4a,0xb0,0x2d,0xa2,0x34,0xa2,0x2c,0xa2,0x32,0xe2,0x54,0x78,0x75,0x44, +0x7d,0x84,0xbb,0x9c,0xfd,0x2d,0x1f,0x4f,0xf9,0xfe,0x88,0x96,0x88,0x31,0xd2,0xd6, +0x88,0x28,0xd9,0xd1,0x88,0xf6,0x88,0xce,0x88,0xd3,0x9c,0x9c,0x89,0x38,0x1f,0xd1, +0x1d,0x71,0x29,0xe2,0x4a,0xc4,0xd7,0x11,0xdf,0x45,0xfc,0x18,0xa1,0x8b,0xe0,0x45, +0x9a,0x45,0x5a,0x44,0xf2,0x23,0x45,0x91,0xf6,0x91,0xc3,0x23,0x25,0x91,0xae,0x10, +0xa5,0xdc,0x23,0xd2,0x2b,0xd2,0x2f,0x52,0x15,0xf9,0x80,0x2c,0x28,0x32,0x2c,0x52, +0x13,0xb9,0xcd,0x23,0x26,0xf2,0xbe,0xc8,0x87,0x22,0x1f,0x8d,0x7c,0x32,0xf2,0x99, +0xc8,0x17,0x22,0x5f,0x8e,0x1c,0x17,0xf9,0x6a,0xe4,0xb4,0xc8,0x59,0x91,0x73,0xc2, +0x5f,0x8b,0x7c,0x23,0xf2,0xad,0xc8,0xb8,0xc8,0xe4,0xc8,0xb4,0xc8,0x8c,0xc8,0x95, +0x91,0x6b,0x22,0x73,0x22,0xf3,0x23,0x8b,0x22,0x37,0x43,0xb6,0x47,0xee,0x8a,0xac, +0x88,0x7c,0x5c,0xba,0x2f,0xb2,0x36,0xb2,0x29,0xf2,0x40,0xe4,0xe1,0xc8,0xbd,0x82, +0xf7,0x22,0x8f,0x47,0x36,0x08,0x4e,0x46,0x7e,0x10,0xf9,0x51,0xe4,0xb9,0xc8,0xae, +0xc8,0x4b,0x91,0x57,0x22,0xbf,0x8a,0xfc,0x36,0xf2,0x7a,0x64,0x5f,0xa4,0xb1,0xc6, +0x54,0x33,0x44,0x63,0xad,0x11,0x6a,0xec,0x34,0xc3,0x35,0x12,0x8d,0xab,0xc6,0x43, +0x13,0xe7,0xe6,0xa5,0xe9,0x16,0xf8,0x6b,0xfc,0x35,0x81,0x9a,0x10,0x48,0x84,0x26, +0x4a,0x73,0xaf,0xe6,0x21,0xcd,0xa3,0x9a,0x27,0x35,0xcf,0x68,0x5e,0xd0,0xbc,0xac, +0x19,0xa7,0x99,0xa4,0x99,0xaa,0x99,0xa9,0x19,0x2d,0x9b,0xab,0x79,0x43,0xf3,0x96, +0x86,0xd1,0x8c,0x95,0x33,0x9a,0x44,0xcd,0x04,0xd9,0x12,0xcd,0x32,0xcd,0x72,0xcd, +0x6a,0xcd,0x64,0x99,0xad,0xdb,0x3a,0x4d,0xae,0x66,0x83,0x66,0x93,0x66,0xab,0x66, +0x87,0x66,0xb7,0xa6,0x52,0x53,0xad,0xa9,0xd7,0xec,0xd7,0xb4,0x68,0x5a,0x35,0xc7, +0x34,0x27,0x34,0xa7,0x34,0x1f,0x6a,0x3e,0xd6,0x9c,0xd7,0x74,0x6b,0x2e,0x69,0xae, +0x68,0xa6,0xcb,0xbe,0xd2,0x7c,0xab,0xf9,0x51,0xa3,0xd3,0xf0,0xb4,0x66,0xda,0x79, +0x32,0x0b,0x2d,0x5f,0x2b,0xd2,0xda,0x6b,0x87,0x6b,0x25,0x5a,0x57,0xad,0x87,0x96, +0xfd,0x5d,0x24,0x2f,0xad,0x9f,0x56,0xa5,0x0d,0xd2,0x86,0x6b,0xb5,0xda,0x58,0xed, +0xfd,0xda,0x05,0xb2,0x87,0xb5,0x8f,0x6b,0x9f,0xd2,0x3e,0xa7,0xf5,0xf1,0x1c,0xad, +0x1d,0xa3,0x9d,0xa0,0x9d,0xac,0x9d,0xae,0x9d,0xa3,0x9d,0xaf,0x5d,0xa8,0x5d,0xa4, +0x4d,0xd0,0xa6,0x68,0x97,0x6a,0x33,0xb5,0x59,0xd2,0x55,0xda,0xb5,0xda,0x5c,0x6d, +0xa1,0x76,0xb3,0x76,0xbb,0x76,0x97,0xb6,0x42,0xbb,0x4f,0x5b,0xab,0x6d,0xd4,0xbe, +0x2d,0x3b,0xe7,0xde,0xac,0x3d,0xa4,0x7d,0x57,0xdb,0xa6,0x3d,0xa9,0xfd,0x40,0xfb, +0x91,0xf6,0xac,0x36,0x43,0x7e,0x41,0xdb,0xa3,0xbd,0xac,0xbd,0xaa,0xbd,0xa6,0xbd, +0xae,0xd5,0x69,0x79,0x51,0x2b,0xe5,0x66,0x51,0x16,0x51,0xfc,0x28,0x51,0x94,0x7d, +0xd4,0xf0,0x28,0x49,0x94,0x5b,0x94,0x2c,0xca,0x27,0x4a,0x11,0xa5,0x8e,0xca,0x91, +0x87,0x46,0x45,0x46,0xc5,0x44,0xdd,0x17,0xf5,0x50,0xd4,0x63,0x51,0x4f,0x45,0x3d, +0x17,0x35,0x3a,0x6a,0x4c,0xd4,0x04,0xc8,0xe4,0xa8,0xe9,0x51,0x45,0xf2,0xd9,0x51, +0xf3,0xa2,0x16,0x44,0xbd,0x1d,0x15,0x17,0x95,0x1c,0x95,0x16,0x35,0x5a,0x9a,0x19, +0xb5,0x3a,0x6a,0x5d,0x54,0x5e,0x54,0x51,0xd4,0x96,0xa8,0x92,0xa8,0x1a,0xf9,0xae, +0xa8,0x3d,0x51,0xd5,0x51,0x0d,0x51,0xcd,0x51,0x87,0x20,0x0d,0xf2,0x40,0xcf,0x77, +0xa3,0xda,0xa2,0x3a,0xa2,0xde,0x8f,0xfa,0x28,0xaa,0xd5,0xed,0xa0,0xfc,0x6c,0xd4, +0x85,0xa8,0x62,0x59,0x6f,0xd4,0x95,0xa8,0x1f,0x3c,0xbe,0x8e,0xfa,0x2e,0xaa,0x4c, +0xf6,0x63,0x94,0x2e,0x8a,0x17,0x6d,0x0e,0xb1,0x8a,0x16,0x44,0xdb,0x46,0x0f,0x8b, +0x76,0x8a,0x76,0x89,0x76,0x8f,0xf6,0x8a,0xf6,0x8b,0x56,0x45,0x07,0x45,0x87,0x45, +0x6b,0xa2,0x63,0xa3,0xef,0x8f,0x7e,0x38,0xfa,0xb1,0xe8,0x7f,0x44,0x3f,0x1b,0xfd, +0x62,0xf4,0x98,0xe8,0x89,0xd1,0x53,0xa2,0x67,0x46,0xcf,0x8d,0x7e,0x23,0xfa,0xad, +0xe8,0x56,0x19,0x13,0x9d,0x14,0x9d,0x16,0x9d,0x11,0xbd,0x2a,0x7a,0x6d,0x74,0x6e, +0xf4,0x86,0xe8,0x4d,0xd1,0x5b,0xa3,0x77,0x44,0xef,0x8e,0xde,0x13,0x5d,0x1d,0xdd, +0x10,0xdd,0x1c,0x1d,0xa8,0x39,0x1c,0xfd,0x5e,0xf4,0xf1,0xe8,0x93,0xd1,0x1f,0x44, +0x7f,0x14,0x7d,0x36,0xfa,0x42,0x74,0x4f,0xf4,0xe7,0xd1,0x5f,0x46,0x7f,0x13,0x5d, +0x28,0xfd,0x21,0xfa,0x46,0xb4,0x51,0x8c,0x49,0xcc,0xe0,0x18,0xab,0x98,0x4e,0x99, +0x20,0xc6,0x36,0x46,0x1c,0xe3,0x18,0x33,0x32,0xc6,0x3d,0xc6,0x2b,0xc6,0x3f,0x26, +0x20,0x26,0x38,0x26,0x3c,0x46,0x1b,0x73,0x4f,0xcc,0x03,0x31,0xa3,0x62,0x9e,0x88, +0x79,0x3a,0xe6,0x85,0x98,0x57,0x62,0xc6,0xc7,0x54,0xba,0xbd,0x1a,0x33,0x2d,0x66, +0x56,0xcc,0x6b,0x31,0x6f,0xc4,0xbc,0x15,0x73,0x5e,0xce,0xc4,0x24,0xc6,0x2c,0x89, +0x59,0x16,0xb3,0x3c,0x66,0x75,0xcc,0xba,0x98,0xdc,0x98,0x51,0xa2,0x0d,0x31,0xc5, +0x31,0xdb,0x62,0x4a,0x63,0xca,0x62,0x2a,0x63,0xaa,0x63,0x1a,0x62,0x9a,0x63,0x0e, +0xc5,0xbc,0x1b,0xf3,0xad,0xfc,0xba,0x7c,0x8a,0xa8,0x2d,0xe6,0x64,0xcc,0x07,0x31, +0x1f,0xc5,0x9c,0x8d,0xb9,0x10,0xd3,0x1b,0x73,0x25,0xe6,0xab,0x98,0x6f,0x63,0xae, +0xc7,0xe8,0x62,0xfa,0xe4,0xbc,0x58,0xf3,0x58,0xab,0x58,0x41,0xac,0x6d,0xac,0x38, +0xd6,0x29,0xd6,0x25,0xd6,0x3d,0xd6,0x33,0xd6,0x37,0x56,0x19,0xab,0x8e,0x0d,0x8d, +0xd5,0xc4,0xc6,0xc4,0xde,0x17,0xfb,0x50,0xec,0x63,0xb1,0xff,0x88,0x7d,0x36,0xf6, +0xc5,0xd8,0x57,0x62,0x27,0xc4,0x4e,0x89,0x9d,0x11,0x3b,0x27,0x76,0x7e,0xec,0x9b, +0xb1,0x8b,0x63,0xed,0x3c,0xed,0x3c,0x13,0x63,0x97,0xc4,0xa6,0xc7,0xae,0x88,0xcd, +0x8a,0xcd,0x8e,0xcd,0x8b,0x2d,0x8c,0x2d,0x8e,0xdd,0x16,0x3b,0xcc,0x73,0x67,0x6c, +0x79,0xec,0xde,0xd8,0x9a,0xd8,0x86,0xd8,0x77,0x62,0x0f,0xc5,0xbe,0x1b,0x7b,0x3c, +0xb6,0x33,0xd6,0xd3,0xe6,0xc3,0xd8,0x50,0x9b,0x8f,0x63,0xcf,0xc7,0x76,0xc7,0x5e, +0x8a,0x1d,0x65,0x73,0x25,0xf6,0x6e,0xac,0x72,0x6f,0x7b,0x1f,0xca,0xfe,0x77,0x9a, +0x14,0x09,0x35,0xe9,0x74,0x5f,0xf4,0xbf,0x64,0xe5,0x42,0x8d,0xe1,0xe8,0xe2,0xad, +0x73,0x1b,0x8f,0x7e,0x96,0xab,0xd1,0x2d,0x46,0xf8,0xa8,0x8e,0xfb,0xcf,0x52,0xcc, +0x40,0xa9,0x1f,0xd9,0xff,0x21,0x51,0xf0,0x83,0x4e,0x77,0xa3,0xe5,0xeb,0x2b,0x8d, +0x38,0xba,0x71,0xf9,0xeb,0xc6,0x30,0x23,0x6a,0xd3,0xf1,0xfa,0xae,0x70,0xf9,0x97, +0xbf,0xfe,0xfc,0x50,0xc4,0x29,0x87,0x43,0xba,0xe6,0x43,0x11,0x71,0xac,0x6e,0x33, +0xdd,0x27,0x37,0x90,0xaf,0xfb,0xfa,0x93,0x88,0x57,0x82,0xda,0xd8,0xb6,0xb8,0xe3, +0x2f,0xd8,0xe3,0x59,0x6d,0x3a,0x6b,0xe2,0x8e,0x59,0xe3,0x6e,0x7c,0xa9,0x6b,0x63, +0x57,0x71,0xba,0xc5,0x3f,0x41,0x93,0xdf,0xe2,0xc4,0x97,0x75,0x4d,0xba,0x11,0xac, +0x5d,0x7c,0xae,0x5f,0x9f,0xe8,0xcc,0xb8,0x38,0x62,0x71,0x04,0x57,0x81,0x0b,0xd9, +0x83,0xc5,0x06,0xeb,0x22,0x74,0xb7,0xf4,0x41,0x62,0xf0,0x00,0xfb,0x5c,0x90,0xdc, +0xfa,0x92,0x14,0x9d,0x83,0x11,0x8b,0x89,0x6d,0x56,0xf7,0x09,0xfb,0x9f,0x81,0xd0, +0x5b,0x9e,0xbe,0xac,0x6e,0xe0,0x3f,0x69,0x69,0xd8,0xfc,0xc5,0x3a,0xbe,0x8e,0x7f, +0x95,0x3b,0x94,0xe8,0xfd,0xc3,0xe7,0x5a,0x3d,0x64,0x28,0xd4,0x66,0x88,0x59,0x03, +0x0a,0xb8,0x36,0x34,0x37,0xdf,0xc5,0x1a,0xbc,0x6d,0xf8,0xf0,0xbf,0x34,0x24,0xbe, +0xd7,0x7d,0xda,0xff,0x22,0x5b,0xaf,0x51,0xdf,0xb2,0xfe,0xff,0x8c,0xe3,0x32,0xd0, +0xad,0x4d,0x37,0x3a,0x73,0xcd,0xd3,0x62,0xc3,0xa7,0xdf,0x38,0x3e,0xf7,0x2d,0xc1, +0xcd,0x0f,0x67,0xad,0xa1,0x97,0x8b,0x6f,0x7d,0x23,0xce,0x1f,0x18,0x0f,0xfa,0x58, +0xa2,0xe3,0x69,0x9a,0x0c,0x7d,0xd5,0xf1,0x19,0x2e,0xa7,0x51,0xd7,0x6c,0xe8,0x83, +0xbe,0xb6,0x46,0xf7,0xb5,0xfe,0x7f,0x48,0xd0,0xf7,0xec,0xf1,0xa2,0x45,0x8b,0xe8, +0xa6,0x66,0x7d,0x5d,0x3e,0xfb,0xbf,0xb6,0xbf,0xef,0xd7,0x60,0x18,0x77,0x5f,0x70, +0x8d,0xec,0x43,0x19,0xcd,0x2d,0xe3,0xd0,0x2c,0x85,0x8b,0x32,0xd9,0x93,0x12,0xa3, +0x9b,0x23,0x54,0x73,0xd3,0x62,0xae,0xef,0xdc,0xdf,0x80,0xf3,0xcf,0x0e,0x5c,0x03, +0x36,0x6c,0xd4,0xbb,0x5c,0x73,0xb3,0x16,0xdd,0xec,0x18,0xd7,0x6b,0xe4,0x6b,0xb8, +0xe1,0xd3,0xb8,0xc2,0x50,0x9c,0xeb,0x04,0x33,0x70,0x2f,0x04,0x7d,0xaf,0x57,0xae, +0x4b,0xd0,0x7b,0x77,0xc0,0x2e,0x5c,0x8f,0x9f,0xb8,0xc4,0xcc,0x2f,0xbf,0x80,0x2b, +0x35,0x29,0x18,0x19,0x46,0xb7,0x7e,0xc7,0xc0,0x35,0xf4,0x7d,0xbf,0x37,0x35,0x7d, +0x7a,0x93,0x59,0xb3,0x78,0x4e,0xd4,0x87,0xf3,0x46,0xb7,0xde,0x6f,0x66,0x3f,0x19, +0xec,0x83,0x7f,0x7f,0xf6,0xdd,0x84,0xde,0x73,0x61,0x3c,0xfa,0xa9,0x6f,0xe0,0x48, +0x7f,0x95,0xfb,0xad,0xe1,0xae,0x11,0xeb,0x77,0xb6,0x09,0x4d,0xff,0xcd,0xf6,0x89, +0x19,0x71,0xa3,0x95,0x37,0x70,0xeb,0xd2,0xcd,0xab,0xcb,0xbe,0x61,0xd6,0xdf,0x8d, +0x86,0x66,0xf0,0x59,0x5c,0x0f,0x07,0xf4,0xff,0x47,0x2a,0x33,0x1d,0x4f,0x7f,0x9f, +0x5e,0xfe,0xb1,0x20,0x24,0xee,0x6c,0x9b,0x04,0xe5,0x1f,0xe2,0xfc,0xa4,0x2b,0xfe, +0xae,0xd1,0xc8,0x54,0xaf,0xf9,0x0b,0xb6,0x2e,0x6b,0xf3,0xcd,0x7e,0x68,0xf4,0xc3, +0x09,0x1f,0xd4,0xe0,0x41,0x0d,0x0d,0xcc,0x26,0x3c,0xfd,0xc5,0xe6,0xee,0x2f,0x3e, +0x6b,0xc9,0xcf,0xe6,0x1b,0xc3,0xdf,0xf0,0x9b,0x31,0x8b,0xbf,0x9a,0xc9,0xea,0xf9, +0x61,0x31,0x0d,0x98,0x46,0x06,0x57,0xff,0x24,0xd1,0xeb,0x1b,0xf8,0x70,0x7d,0x34, +0xbb,0xc5,0x5f,0x86,0xf6,0x78,0xac,0xee,0x1b,0xfa,0x5b,0xeb,0xe6,0xd8,0x46,0x23, +0x7d,0xb8,0x17,0xb8,0x6e,0x2f,0xde,0xc3,0xda,0xdd,0xc8,0x96,0x59,0xfc,0x63,0xbf, +0x97,0xf8,0x3a,0x1e,0xaf,0xdf,0x26,0x23,0x9d,0xbe,0x81,0x43,0x3f,0xd7,0x60,0xb8, +0xcf,0x74,0x3c,0x86,0x4f,0xfd,0xd7,0xfa,0xd6,0xfb,0xd4,0xec,0x96,0x5c,0x0d,0x0d, +0xdc,0xdf,0xcd,0x03,0x05,0x16,0x73,0xba,0x34,0x1a,0xac,0x04,0x75,0x3f,0xc2,0x94, +0xb3,0xba,0x81,0xb1,0xa6,0xbf,0x15,0x74,0x29,0x86,0x92,0xcc,0xcd,0xef,0xaa,0x24, +0xb4,0xb8,0xbf,0xa7,0x8c,0x7e,0xc4,0xb3,0xe5,0xfb,0xe7,0xdc,0x5b,0xcc,0xa3,0x2f, +0x66,0x12,0x76,0x30,0x5f,0x1a,0x0d,0x5c,0x47,0xc3,0x3d,0xc2,0x47,0xe7,0x1d,0xcf, +0x0e,0xcc,0xde,0x9a,0x9b,0x37,0x9e,0xe6,0x67,0xf7,0x04,0x9f,0x0c,0x63,0xc4,0x08, +0xc9,0xef,0xfb,0xf4,0xbd,0x93,0x70,0x05,0x99,0x5b,0xae,0x97,0x04,0x2d,0x34,0xdf, +0x3a,0x4a,0x07,0xbc,0x90,0x40,0x3f,0x9f,0x89,0x52,0xf4,0xa3,0x56,0x3f,0xaa,0x17, +0xcf,0xd4,0x2d,0x2e,0x30,0x5c,0x79,0x78,0xbb,0xf9,0xd6,0xff,0xd8,0xa3,0xff,0x48, +0xfa,0x53,0xfa,0x9b,0x96,0xfb,0xbf,0x6d,0xb0,0x69,0x71,0xff,0x0a,0x5d,0x9f,0xdd, +0xa4,0x2f,0xf3,0x35,0xec,0x90,0x70,0xd7,0x8d,0x7f,0x73,0x04,0xb1,0xd7,0x75,0xe0, +0x5e,0xd7,0xe8,0xf8,0x3c,0xc3,0x9d,0xc6,0xe5,0x68,0x74,0x92,0xc5,0x57,0x31,0x88, +0x33,0xd9,0x1b,0xf1,0x3b,0xdd,0x2d,0xf3,0xef,0xcd,0x99,0xc4,0x30,0x87,0xd3,0x18, +0x1a,0x4b,0xe3,0x68,0x3c,0x4d,0xa0,0x89,0x34,0x89,0x5e,0xa5,0xc9,0x34,0x85,0xa6, +0xd2,0x34,0x9a,0x4e,0x33,0x68,0x26,0xcd,0xa2,0xd9,0x34,0x87,0xe6,0xd2,0x6b,0x34, +0x8f,0xe6,0xd3,0xeb,0xf4,0x06,0x2d,0xa0,0x85,0xe4,0x4c,0xce,0xef,0x2d,0x01,0x89, +0xc4,0xfe,0x2e,0x9a,0xf3,0x7b,0x71,0x74,0xac,0x0e,0xd1,0x16,0xec,0x25,0x15,0xe7, +0xe3,0x12,0x03,0xb8,0x10,0xa7,0xb8,0x74,0xf3,0x06,0x6a,0x2e,0xa4,0xe6,0x22,0x6a, +0xde,0x48,0xcd,0x9b,0xa8,0xb9,0x98,0x9a,0x37,0x53,0xf3,0x16,0x6a,0xde,0x4a,0xcd, +0xdb,0xa8,0x79,0x3b,0x35,0x97,0x50,0xf3,0x0e,0x6a,0x2e,0xa5,0xe6,0x9d,0xd4,0xbc, +0x8b,0x9a,0x77,0x53,0x73,0x19,0x35,0x97,0x53,0x73,0x05,0x35,0xef,0xa1,0xe6,0x4a, +0x6a,0xde,0x4b,0xcd,0x55,0xd4,0x5c,0x4d,0xcd,0x35,0xd4,0x5c,0x4b,0xcd,0x75,0xd4, +0x5c,0x4f,0xcd,0x0d,0x74,0x20,0x8e,0x0e,0x24,0xd0,0x81,0x24,0x3a,0x90,0x42,0x07, +0x52,0xe9,0xc0,0x52,0x3a,0x90,0x4e,0x07,0x32,0xe9,0xc0,0x0a,0x3a,0xb0,0x8a,0x0e, +0x64,0xd1,0x81,0xb5,0x74,0x20,0x9b,0x0e,0xac,0xa7,0x03,0x79,0x74,0xa0,0x80,0x0e, +0x14,0xd2,0x81,0x8d,0x74,0xa0,0x98,0x0e,0x6c,0xa1,0x03,0xdb,0xe8,0x40,0x09,0x1d, +0x28,0xa5,0x03,0xbb,0x68,0xf2,0x7b,0x29,0x34,0x79,0x0a,0x1d,0xa8,0xa4,0x03,0xfb, +0xe8,0x40,0x0d,0x1d,0xa8,0xa3,0x03,0x0d,0x34,0xed,0x9d,0x7d,0xd4,0x12,0x4f,0x2d, +0x89,0xd4,0x92,0x4c,0x2d,0x4b,0xe8,0x48,0xdd,0x0c,0x6a,0x59,0x4a,0x2d,0xe9,0xd4, +0x92,0x49,0x2d,0x2b,0xa8,0x65,0x15,0xb5,0x64,0x51,0xcb,0x5a,0x6a,0xc9,0xa6,0x96, +0xf5,0xd4,0x92,0x47,0x2d,0x05,0xd4,0x52,0x48,0x2d,0x1b,0xa9,0xa5,0x98,0x5a,0xb6, +0x50,0xcb,0x36,0x6a,0x29,0xa1,0x96,0x52,0x6a,0xd9,0x45,0x2d,0x65,0xd4,0x52,0x41, +0x2d,0x95,0xd4,0xb2,0x8f,0x9a,0x1b,0xa9,0xa5,0x86,0x5a,0xea,0xa8,0xa5,0x81,0x5a, +0x57,0xd1,0xc1,0x04,0x3a,0x98,0x44,0xad,0xab,0xe9,0xe0,0x12,0x6a,0x5d,0x43,0xad, +0x6b,0xe9,0xe0,0x32,0x3a,0x94,0x47,0xad,0xd9,0xd4,0xba,0x9e,0x0e,0xae,0xa4,0xd6, +0x0d,0xd4,0xba,0x91,0x5a,0xb7,0x51,0xeb,0x56,0x3a,0x88,0xcc,0x5d,0xd4,0x5a,0x4e, +0xad,0x95,0x74,0xb0,0x90,0x0e,0x6e,0xa4,0x83,0xc5,0x74,0x84,0xa1,0x83,0x5b,0xe9, +0x08,0xda,0x29,0xa5,0x23,0x4b,0xe8,0xe0,0x6e,0x3a,0x92,0x46,0x47,0x96,0xd2,0xc1, +0x3d,0x74,0x70,0x2f,0x1d,0x59,0x49,0x07,0xab,0xe9,0x60,0x3d,0x8d,0x87,0xbe,0x69, +0x53,0x68,0xc6,0x14,0x3a,0x94,0x41,0x87,0x96,0xd3,0xa1,0x95,0x74,0x68,0x35,0x1d, +0x5a,0x43,0x87,0xd6,0xd1,0xa1,0x1c,0x3a,0x94,0x4b,0x87,0x0a,0xe8,0x50,0x21,0x1d, +0xda,0x48,0x87,0x8a,0xe9,0xd0,0x16,0x3a,0xb4,0x8d,0x0e,0x95,0xd0,0xa1,0x52,0x3a, +0xb4,0x8b,0xc6,0x2f,0xa4,0x43,0x50,0x99,0x45,0x07,0x1b,0xe9,0x50,0x35,0x1d,0xaa, +0xa5,0x43,0xf5,0x74,0xa8,0x91,0x0e,0xc7,0xd1,0xe1,0x04,0x3a,0x9c,0x44,0x87,0x53, +0xe8,0x70,0x2a,0x1d,0x5e,0x4a,0x87,0xd3,0xe9,0x70,0x26,0x1d,0x5e,0x41,0x87,0x57, +0xd1,0xe1,0x2c,0x3a,0xbc,0x96,0x0e,0x67,0xd3,0xe1,0xf5,0x74,0x38,0x8f,0x0e,0x17, +0xd0,0xc1,0x7c,0x3a,0xbc,0x91,0x0e,0x17,0xd3,0xe1,0x2d,0x74,0x78,0x1b,0x1d,0x2e, +0xa1,0xc3,0xa5,0x74,0x78,0x17,0x1d,0x2e,0xa3,0xc3,0x15,0x74,0xbe,0x0c,0x27,0xea, +0xe8,0x60,0x0e,0x52,0x9b,0xa9,0x35,0x9e,0x0e,0x32,0x74,0x24,0x95,0x8e,0x2c,0xa3, +0xd6,0x14,0x6a,0x4d,0xa5,0xd6,0xa5,0xd4,0x9a,0x4e,0xad,0x99,0xd4,0x8a,0xb3,0xd5, +0xd4,0x5a,0x4b,0x47,0xe2,0x30,0xf0,0x92,0x41,0x0a,0x48,0x03,0x5b,0x41,0x02,0x58, +0x4a,0x47,0xb2,0xe8,0x3d,0x86,0x30,0x38,0xdf,0x5b,0x45,0xef,0x2d,0x61,0x07,0x69, +0x35,0x1d,0x2d,0xa3,0xa3,0x15,0x74,0x04,0x89,0x7d,0xe4,0x8c,0xe3,0x30,0x6a,0xab, +0x60,0x07,0x33,0x7b,0x76,0x07,0xe1,0x8a,0x1f,0x2b,0xa5,0x63,0x3b,0xe9,0xd8,0x2e, +0x6a,0x5b,0x46,0x6d,0xe9,0xd4,0x96,0x41,0xc7,0xca,0xe8,0x58,0x39,0x1d,0xab,0xa0, +0x63,0x7b,0xe8,0x58,0x25,0x1d,0xdb,0x4b,0xc7,0x50,0xac,0x8a,0x8e,0xd5,0xd0,0xb1, +0x5a,0x3a,0x56,0x4f,0xc7,0x1a,0xe8,0x58,0x23,0xb5,0x31,0xd4,0x16,0x47,0x6d,0x09, +0xd4,0x96,0x48,0x6d,0x49,0xd4,0x96,0x4c,0x6d,0x29,0xd4,0xb6,0x84,0xda,0x52,0xa9, +0x2d,0x8d,0xda,0x96,0x52,0xdb,0x5a,0x6a,0xcb,0xa6,0xb6,0xf5,0xd4,0x96,0x47,0x6d, +0x05,0xd4,0x56,0x48,0x6d,0x1b,0xa9,0xad,0x98,0xda,0xb6,0x50,0xdb,0x36,0x6a,0x2b, +0xa1,0xb6,0x52,0x6a,0x83,0xde,0x2a,0x6a,0xab,0xa5,0xa3,0xf8,0xa9,0xa3,0xa3,0xf5, +0xd4,0xbe,0x9c,0xda,0x57,0x50,0xfb,0x4a,0x6a,0x5f,0x45,0xed,0xab,0xa9,0x3d,0x8b, +0xda,0xd7,0x50,0xfb,0x5a,0x6a,0x5f,0x47,0xed,0xd9,0xd4,0x9e,0x43,0xed,0xeb,0xa9, +0x3d,0x97,0xda,0xf3,0xa8,0x3d,0x9f,0xda,0x0b,0xe8,0xf8,0x6e,0x3a,0x5e,0x46,0xc7, +0xcb,0xe9,0x78,0x05,0x1d,0xdf,0x43,0xc7,0x2b,0xe9,0xf8,0x5e,0x3a,0xbe,0x8f,0x8e, +0x57,0xd1,0xf1,0x6a,0x3a,0x5e,0x43,0xc7,0x6b,0xe9,0x78,0x1d,0x1d,0xaf,0xa7,0xe3, +0x0d,0x74,0xbc,0x91,0xda,0x19,0x6a,0x8f,0xa3,0xf6,0x78,0x6a,0x4f,0xa0,0xf6,0x44, +0x6a,0x4f,0xa2,0xf6,0x64,0x6a,0x4f,0xa1,0xf6,0x25,0xd4,0x9e,0x4a,0xed,0x69,0xd4, +0xbe,0x94,0xda,0x97,0x51,0x7b,0x3a,0xb5,0x67,0x50,0x7b,0x26,0xb5,0x17,0x52,0xfb, +0x46,0x6a,0x2f,0xa6,0xf6,0x2d,0xd4,0xbe,0x8d,0xda,0x4b,0xa8,0xbd,0x94,0xda,0x77, +0x51,0x7b,0x19,0xb5,0x57,0x50,0x7b,0x25,0xb5,0xef,0xa3,0xf6,0x6a,0x6a,0xaf,0xa5, +0x76,0x18,0xdf,0x48,0x27,0xe2,0xe8,0xc4,0x52,0x3a,0x91,0x4e,0x27,0x32,0xe9,0xc4, +0x0a,0x3a,0xb1,0x8a,0x4e,0x64,0xd1,0x89,0xb5,0x74,0x22,0x9b,0x4e,0xac,0xa7,0x13, +0x79,0x74,0xa2,0x80,0x4e,0x14,0xd2,0x89,0x8d,0x74,0xa2,0x98,0x4e,0x6c,0xa1,0x13, +0xdb,0xe8,0x44,0x09,0x9d,0x28,0xa5,0x13,0xbb,0xe8,0x44,0x19,0x9d,0xa8,0xa0,0x13, +0x95,0x74,0x62,0x1f,0x9d,0xa8,0xa6,0x13,0xb5,0x74,0xa2,0x9e,0x4e,0x34,0x52,0x47, +0x26,0x75,0xc4,0x53,0x47,0x22,0x75,0x24,0x53,0xc7,0x12,0xea,0x48,0xa3,0x8e,0x65, +0xd4,0x91,0x41,0x1d,0x2b,0xa8,0x63,0x15,0x75,0x64,0x51,0xc7,0x5a,0xea,0xc8,0xa6, +0x8e,0xf5,0xd4,0x91,0x47,0x1d,0x05,0xd4,0x51,0x48,0x1d,0x1b,0xa9,0xa3,0x98,0x3a, +0xb6,0x50,0xc7,0x36,0xea,0x28,0xa1,0x8e,0x52,0xea,0xd8,0x45,0x1d,0x65,0xd4,0x51, +0x41,0x1d,0x95,0xd4,0xb1,0x8f,0x3a,0xaa,0xa9,0xa3,0x96,0x3a,0xea,0xa9,0xa3,0x91, +0x4e,0xc6,0xd1,0xc9,0x04,0x3a,0x99,0x44,0x27,0x53,0xe8,0x64,0x2a,0x9d,0x5c,0x4a, +0x27,0xd3,0xe9,0x64,0x26,0x9d,0x5c,0x41,0x27,0x57,0xd1,0xc9,0x2c,0x3a,0xb9,0x96, +0x4e,0x66,0xd3,0xc9,0xf5,0x74,0x32,0x8f,0x4e,0x16,0xd0,0xc9,0x42,0x3a,0xb9,0x91, +0x4e,0x16,0xd3,0xc9,0x2d,0x74,0x72,0x1b,0x9d,0x2c,0xa1,0x93,0xa5,0x74,0x72,0x17, +0x75,0x16,0x52,0x67,0x11,0x75,0x6e,0xa4,0xce,0x4d,0xd4,0x59,0x4c,0x9d,0x9b,0xa9, +0x73,0x0b,0x75,0x6e,0xa5,0xce,0x6d,0xd4,0xb9,0x9d,0x3a,0x4b,0xa8,0x73,0x07,0x75, +0x96,0x52,0xe7,0x4e,0xea,0x44,0xe1,0xdd,0xd4,0x59,0x46,0x9d,0xe5,0xd4,0x59,0x41, +0x9d,0x7b,0xa8,0xb3,0x92,0x3a,0xf7,0x52,0xe7,0x3e,0xea,0xac,0xa2,0xce,0x6a,0xea, +0xac,0xa1,0xce,0x5a,0xea,0xac,0xa3,0xce,0x7a,0xea,0x6c,0xa0,0xce,0x46,0x3a,0xc5, +0xd0,0xa9,0x38,0x3a,0x15,0x4f,0xa7,0x12,0xe8,0x54,0x22,0x9d,0x4a,0xa2,0x53,0xc9, +0xd0,0x82,0x8c,0x0f,0xb6,0x9c,0xde,0x43,0xa7,0x97,0x20,0xf8,0x67,0x0a,0x9b,0x4a, +0x43,0x70,0x76,0x53,0xd6,0xd9,0x4d,0x75,0x88,0xd6,0xe8,0xa3,0xb5,0xfa,0x28,0x57, +0x1f,0x15,0xea,0xa3,0x22,0x7d,0x54,0xa2,0x8f,0x76,0x71,0xd1,0xe6,0xc2,0xb3,0x9b, +0xd9,0xa8,0x48,0x1f,0xed,0xe2,0xa2,0xad,0xe5,0x67,0xb7,0xb2,0x51,0x95,0x3e,0x5a, +0xa3,0x8f,0xd6,0xea,0xa3,0x5c,0x7d,0x54,0xc2,0x45,0x3b,0x0a,0xcf,0xee,0x60,0xa3, +0x22,0x2e,0xaa,0x4e,0x3f,0x5b,0x55,0x4e,0x67,0x6b,0xd3,0xcf,0xd6,0x20,0xaa,0x29, +0x39,0x5b,0x93,0xad,0x8f,0x0a,0xe9,0x6c,0xdd,0x52,0x3a,0x5b,0x1f,0x7f,0xb6,0x61, +0x1f,0xa2,0x65,0xfa,0x68,0x85,0x3e,0x5a,0xa3,0x8f,0xd6,0xeb,0x23,0xe6,0x6c,0x43, +0x25,0xa2,0xb2,0xb3,0xf5,0xe5,0xfa,0x08,0x9d,0x6b,0x28,0x3f,0xdb,0xc0,0x70,0x11, +0x32,0xb8,0x54,0x45,0x7f,0x64,0xc8,0xe8,0xcf,0x5f,0xc9,0x35,0xd2,0x90,0xab,0x8f, +0x0a,0xf5,0xd1,0x66,0x7d,0x54,0xa2,0x8f,0x96,0xb3,0x0a,0xce,0xef,0x61,0x40,0x1c, +0x88,0x07,0x09,0x20,0x11,0x24,0x81,0x64,0x90,0x02,0x96,0x80,0x54,0x90,0x06,0x96, +0x82,0x65,0x20,0x1d,0x64,0x80,0x4c,0xb0,0x1c,0xac,0x00,0x2b,0xc1,0x2a,0xb0,0x1a, +0x64,0x81,0x35,0x60,0x2d,0x58,0x07,0xb2,0x01,0xa6,0xba,0x3d,0xeb,0x41,0x2e,0xc8, +0x03,0xf9,0xa0,0x00,0x6c,0x00,0x85,0xa0,0x08,0x6c,0x04,0x9b,0x40,0x31,0xd8,0x02, +0x4a,0xe9,0x5c,0x42,0x2e,0x9d,0xcb,0xdc,0x0d,0xca,0x40,0x39,0xa8,0x00,0x7b,0x40, +0x25,0x5d,0xca,0x5e,0x4a,0xe7,0xca,0xd3,0x50,0x66,0x39,0x58,0x01,0x56,0x82,0x55, +0x60,0x35,0xc8,0x02,0x6b,0xc0,0x5a,0xb0,0x0e,0x64,0x83,0x1c,0xb0,0x1e,0xe4,0x81, +0x7c,0x50,0x00,0x36,0x80,0x42,0x50,0x04,0x36,0x82,0x4d,0xa0,0x18,0x6c,0x06,0x5b, +0xc0,0x56,0xb0,0x0d,0x6c,0x07,0x25,0x60,0x07,0x60,0xed,0xda,0x09,0x76,0x01,0xd8, +0x96,0x00,0xdb,0x12,0x60,0x5b,0x02,0x6c,0x4b,0x80,0x6d,0x09,0x95,0x60,0x2f,0xd8, +0x07,0xaa,0x40,0x35,0xa8,0x01,0xf5,0xa0,0x01,0x34,0x52,0xeb,0x72,0x6a,0x85,0xc5, +0xf0,0x7a,0x2b,0x3a,0x08,0x67,0x9d,0x83,0xb3,0xce,0xc1,0x31,0xe7,0xd0,0xf9,0x56, +0x3c,0x0b,0xb3,0xa8,0xb5,0x80,0x5a,0x0b,0xa9,0x15,0x87,0x50,0x5d,0x89,0x27,0x00, +0x1e,0x95,0x50,0xbc,0x37,0x89,0x8e,0xe0,0x4c,0x19,0xb5,0xee,0xa6,0xd6,0x0a,0x6a, +0xdd,0x43,0xad,0x55,0x74,0x04,0x4f,0x10,0x18,0x07,0xe7,0x1e,0x59,0x4e,0x47,0xd0, +0x70,0x55,0x1c,0x48,0x00,0x49,0x20,0x05,0xa4,0x02,0xb8,0xab,0x2a,0x1d,0x64,0x02, +0xb6,0x0c,0x5c,0x55,0x05,0x37,0x55,0x41,0x73,0x15,0xdc,0x53,0x05,0xd7,0x54,0xc1, +0x82,0x2a,0xb8,0xa5,0x0a,0x2e,0xa9,0x82,0x3b,0xaa,0xe0,0x8a,0x2a,0xb8,0xa1,0x0a, +0x2e,0xa8,0x82,0x86,0x2a,0x58,0x50,0x85,0x6e,0x57,0xa1,0xcb,0x55,0xe8,0x6e,0x15, +0xba,0x5a,0x85,0x6e,0x56,0xa1,0x8b,0x55,0xb5,0x00,0x5d,0xac,0x6a,0xa4,0x73,0xd5, +0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0, +0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f, +0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d, +0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd, +0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0xd5,0xd0,0x5f,0x0d,0xfd,0x35, +0xd0,0x5f,0x03,0xfd,0x35,0xd0,0x5f,0x03,0xfd,0x35,0xd0,0x5f,0x03,0xfd,0x35,0xd0, +0x5f,0x03,0xfd,0x35,0xd0,0x5f,0x03,0xfd,0x35,0x59,0x34,0xe6,0x48,0x03,0x35,0x43, +0x25,0x6e,0xce,0x73,0x35,0x50,0x59,0x03,0x95,0x35,0x50,0x59,0x03,0x95,0x35,0x50, +0x59,0x03,0x95,0x35,0x50,0x59,0x03,0x95,0x35,0x50,0x59,0x03,0x95,0x35,0x50,0x59, +0x03,0x95,0x35,0x50,0x59,0x03,0x95,0x35,0x50,0x59,0x0b,0x95,0xb5,0x50,0x59,0x0b, +0x95,0xb5,0x50,0x59,0x0b,0x95,0xb5,0x50,0x59,0x0b,0x95,0xb5,0x50,0x59,0x0b,0x95, +0xb5,0x50,0x59,0x8b,0x2e,0xd7,0xa2,0xcb,0xb5,0xe8,0x72,0x2d,0xba,0x5c,0x8b,0x2e, +0xd7,0x42,0x7f,0x2d,0xf4,0xd7,0x42,0x7f,0x2d,0xf4,0xd7,0x42,0x7f,0x2d,0xf4,0xd7, +0x42,0x7f,0x2d,0xf4,0xd7,0x42,0x7f,0x2d,0xf4,0xd7,0x42,0x7f,0x2d,0xf4,0xd7,0x42, +0x7f,0x2d,0xf4,0xd7,0x42,0x7f,0x2d,0xf4,0xd7,0x42,0x7f,0x1d,0x03,0x60,0x43,0x5d, +0x3c,0x80,0x1d,0x75,0x89,0x00,0xb6,0xd4,0x25,0x03,0xd8,0x53,0x87,0xbb,0xa4,0x0e, +0x36,0xd4,0xe1,0x2e,0xa9,0x83,0x1d,0x75,0xb8,0x4b,0xea,0x60,0x4b,0x1d,0xee,0x80, +0x3a,0xe8,0xae,0xc3,0x1d,0x50,0x07,0xfd,0x75,0xb8,0x03,0xea,0x60,0x43,0x1d,0xee, +0x80,0x3a,0xd8,0x51,0x87,0x11,0x5e,0x07,0xdd,0x75,0x18,0xe1,0x75,0xd0,0x5f,0x87, +0x11,0x5e,0x07,0x1b,0xea,0x30,0xc2,0xeb,0x60,0x47,0x3d,0xf4,0xd6,0x43,0x6f,0x3d, +0xf4,0xd6,0x43,0x6f,0x3d,0xf4,0xd6,0x43,0x6f,0x3d,0x74,0xd5,0x43,0x4f,0x3d,0x74, +0xd4,0xa3,0xbf,0xf5,0xd0,0x53,0x0f,0x3d,0xf5,0xd0,0x53,0x0f,0x3d,0xf5,0xd0,0x53, +0x0f,0x3d,0xf5,0xd0,0x53,0xcf,0xea,0x61,0xb0,0x4e,0x41,0x0f,0xb8,0x30,0x9e,0x0b, +0x13,0xb8,0x30,0x91,0x0b,0x93,0xb8,0x30,0x99,0x0b,0x53,0xb8,0x70,0x03,0x17,0x16, +0x72,0x61,0x11,0x17,0x6e,0xe4,0xc2,0x4d,0x5c,0x58,0xcc,0x85,0x9b,0xb9,0x70,0x0b, +0x1b,0xd6,0x73,0xe5,0xeb,0xb9,0xf2,0xf5,0x5c,0xf9,0x7a,0xae,0x7c,0x3d,0x57,0xbe, +0x9e,0x2b,0x5f,0xcf,0x95,0xaf,0xd7,0x97,0xdf,0x8d,0xf0,0x58,0x19,0x1b,0xec,0x60, +0x8f,0x1b,0xf6,0x72,0x21,0xbc,0xd1,0x50,0xc6,0x9e,0xc5,0x72,0x6a,0x15,0x39,0x1f, +0x8d,0x67,0x97,0x55,0x47,0xd9,0xbe,0xef,0x61,0x8b,0xee,0x63,0x83,0x9d,0x6c,0xc9, +0x46,0xce,0x56,0xcc,0xde,0x38,0xc3,0x96,0xc5,0x1a,0x8d,0x0d,0xd9,0x75,0xdc,0x2a, +0x94,0x3f,0x86,0xcb,0xd1,0xc8,0xc2,0xba,0x69,0x2f,0x32,0x57,0x73,0x05,0x56,0x73, +0x05,0x56,0xb3,0x05,0xa0,0xa9,0x11,0x3e,0x6b,0x64,0x7d,0x86,0xd9,0xa3,0xb1,0x98, +0x5b,0xc0,0x31,0xf4,0x0a,0x8e,0xeb,0xd0,0x76,0x5b,0x2a,0x1b,0x64,0x70,0xba,0x38, +0xdb,0xea,0xab,0xd8,0x33,0x6c,0x75,0x3a,0xcf,0x2c,0x47,0x8c,0x85,0x26,0x53,0x8e, +0x1f,0x43,0xa4,0x4f,0x55,0xe2,0xc7,0x10,0xb1,0xa9,0x91,0x23,0x51,0x30,0x89,0xd8, +0x2d,0xec,0x48,0x1a,0xa9,0xb9,0x59,0x94,0x2d,0xed,0x4f,0x01,0x14,0x48,0x6a,0x0a, +0xa2,0x60,0x0a,0x21,0x2f,0x3a,0xbf,0x64,0x25,0x45,0x90,0x8c,0xe4,0x34,0x67,0x2e, +0x8d,0xf1,0x1b,0x07,0xe6,0xd2,0x3b,0xbb,0xc7,0xd1,0x38,0xbf,0x99,0x60,0x1e,0xd2, +0x13,0x69,0xc6,0x4c,0x9a,0x3b,0x9d,0x5e,0x9b,0x30,0x8d,0x5e,0x9b,0x4e,0xe7,0x93, +0x32,0xe8,0xfd,0xe5,0xf4,0xfe,0x0a,0x7a,0x7f,0x25,0xbd,0xbf,0x8a,0x26,0x8e,0x79, +0x03,0xad,0xac,0xe0,0x76,0x4e,0x41,0x5c,0x18,0xc2,0x85,0x0a,0x7f,0x2e,0x52,0x91, +0x92,0x0b,0xd9,0x74,0x20,0x97,0x0e,0xe4,0xb6,0x57,0x81,0x14,0xc0,0x85,0x6c,0xbe, +0x9a,0x02,0xb9,0x90,0x4d,0x07,0x73,0x67,0x83,0xb9,0x9c,0x60,0x0a,0xe2,0x42,0x36, +0x9f,0x26,0x4f,0xc6,0x0f,0x98,0x4f,0xf3,0x27,0xe3,0x87,0x03,0x87,0x6f,0xd0,0x1b, +0x93,0xf1,0x33,0x99,0xce,0x27,0x27,0x92,0x3f,0xa7,0xea,0xfc,0x92,0x12,0xfc,0x18, +0x22,0x7d,0x6a,0x27,0x7e,0x0c,0x11,0x9b,0xfa,0x94,0x59,0x02,0x52,0x89,0xb5,0x11, +0x3b,0x3f,0x25,0x29,0x60,0x20,0x36,0x7f,0x30,0x07,0x56,0xa0,0x17,0xd0,0x19,0x42, +0x4a,0x7f,0x92,0x29,0xe4,0x24,0x53,0x02,0x15,0x08,0x00,0x81,0x40,0x0d,0x82,0x40, +0x30,0x08,0x01,0x0a,0x7f,0x36,0x60,0x4b,0x2a,0xd8,0xa2,0x0a,0xb6,0xac,0x82,0x2d, +0xac,0x60,0x4b,0x2b,0xd8,0xe2,0x0a,0xb6,0xbc,0x82,0xad,0xa0,0x60,0x6b,0x28,0xd9, +0x1a,0x63,0xc0,0x58,0x30,0x0e,0x8c,0x07,0x13,0xc0,0x44,0x30,0x09,0xbc,0x0a,0x26, +0x83,0x29,0x60,0x2a,0x98,0x06,0xa6,0x83,0x19,0x60,0x26,0x98,0x05,0x66,0x83,0x39, +0x60,0x2e,0x78,0x0d,0xcc,0x03,0xf3,0xc1,0xeb,0xe0,0x0d,0xb0,0x00,0x2c,0x94,0xdf, +0x74,0x03,0xeb,0x89,0xd0,0xd0,0x08,0x8a,0x60,0x7f,0x22,0xe8,0x7c,0x49,0xde,0x7b, +0x55,0x74,0x7e,0xf7,0x6e,0x50,0x06,0x30,0x92,0x76,0x63,0x78,0xed,0xde,0x03,0x30, +0x9c,0x76,0xef,0x05,0xfb,0x00,0x5b,0xa6,0x1a,0xd4,0x80,0x5a,0x50,0x07,0xea,0x41, +0x03,0x68,0xc4,0x6e,0x07,0xcb,0x8d,0x32,0x2c,0x37,0xca,0xb0,0xdc,0x28,0xc3,0x72, +0xa3,0x0c,0xcb,0x8d,0x32,0x2c,0x37,0xca,0xb0,0xdc,0x28,0xc3,0x72,0xa3,0x0c,0xcb, +0x8d,0x32,0x2c,0x37,0xca,0xb0,0xdc,0x28,0xc3,0x72,0xa3,0x0c,0xcb,0x8d,0x32,0x2c, +0x37,0xca,0xb0,0xdc,0x28,0xc3,0x72,0xa3,0x0c,0xcb,0x8d,0x32,0x2c,0x37,0xca,0xb0, +0xdc,0x28,0xc3,0x72,0xa3,0x0c,0x43,0xbd,0x0c,0xcb,0x8d,0x32,0x2c,0x37,0xca,0xb0, +0xdc,0x28,0xc3,0x72,0xa3,0x0c,0xcb,0x8d,0x32,0x76,0x67,0x85,0xe5,0x46,0x19,0x96, +0x1b,0x65,0x58,0x6e,0x94,0x61,0xb9,0x51,0x86,0xe5,0x46,0x19,0x9e,0xa8,0x98,0x53, +0x2b,0xeb,0xa9,0x15,0x56,0x95,0x6d,0x05,0xdb,0xc1,0x0e,0xc0,0xee,0xca,0xf6,0xd2, +0x61,0x3c,0x9b,0x61,0x63,0x39,0x6c,0x2c,0x87,0x7d,0xe5,0xb0,0xad,0x1c,0x76,0x95, +0xc3,0xa6,0x72,0xd8,0x53,0x0e,0x5b,0xca,0x61,0x47,0x39,0x6c,0x28,0x87,0xfe,0x72, +0xe8,0x2e,0x87,0xde,0x72,0xe8,0x2c,0x87,0xbe,0x72,0xe8,0x2a,0x87,0x9e,0x72,0x2c, +0x69,0xca,0xb1,0x9c,0x29,0xc7,0x52,0xa6,0x1c,0x4b,0x99,0xf2,0x6d,0x00,0x43,0xab, +0xbc,0x14,0xec,0x02,0xf0,0x61,0x39,0x34,0x96,0xc3,0x77,0xe5,0xf0,0x5b,0x39,0x7c, +0x56,0x0e,0x7f,0x95,0xc3,0xaa,0x72,0xf8,0xa9,0x02,0xfa,0x2b,0xa0,0xbf,0x02,0xfa, +0x2b,0xa0,0xbf,0x02,0xfa,0x2b,0xa0,0xbf,0x02,0xfa,0x2b,0xa0,0xbf,0x02,0xfa,0x2b, +0xa0,0xbf,0x02,0xfa,0x2b,0xa0,0xbf,0x02,0xfa,0x2b,0xa0,0xbf,0x02,0xfa,0x2b,0xa0, +0xbf,0x02,0xfa,0x2b,0xa0,0xbf,0x02,0x3d,0xab,0xc0,0x58,0xae,0x80,0xae,0xca,0x42, +0xea,0xde,0x95,0x4e,0xbd,0x0d,0x05,0x74,0xa1,0x8a,0x01,0x5b,0xc1,0x5e,0xd0,0x48, +0x17,0xf0,0xfc,0xbd,0x80,0x67,0xe5,0x85,0x9a,0x65,0x60,0x03,0xa8,0xa1,0xae,0xc4, +0x46,0xea,0x4a,0x2a,0x06,0x25,0xd4,0x95,0x1c,0x0f,0xd6,0x00,0xa4,0x53,0x36,0x80, +0x4a,0xea,0x5a,0xc2,0x50,0x57,0xda,0x7a,0xea,0x5a,0x5a,0x4d,0x5d,0xcb,0xb2,0x40, +0x0e,0xa8,0xa2,0xae,0xf4,0x38,0x90,0x0b,0xb6,0x51,0x57,0x06,0xea,0x65,0xec,0xa5, +0xae,0xcc,0x25,0x60,0x23,0x75,0xad,0x5f,0x4b,0x5d,0xb9,0x05,0xd4,0xb5,0x11,0xed, +0x6c,0xc2,0xb9,0x4d,0x69,0x00,0x75,0x37,0x6d,0xa1,0xae,0xe2,0x0a,0xea,0x2a,0x5d, +0x4e,0x5d,0x3b,0xd1,0xee,0x2e,0xb4,0xb3,0x3b,0x13,0x14,0x01,0xa4,0xcb,0x76,0x82, +0x32,0xea,0xda,0x07,0x7d,0xfb,0x60,0xd3,0x3e,0x36,0xdd,0x40,0x5d,0xd5,0xe5,0x00, +0xb6,0xe2,0x99,0xdf,0x55,0xbb,0x07,0x20,0x0f,0x2b,0xec,0x2e,0x3c,0xe0,0xba,0xea, +0xd1,0x16,0x1e,0x38,0x5d,0xf5,0x68,0xb7,0x31,0x81,0xba,0x97,0x2c,0x01,0x7b,0xa9, +0x3b,0x75,0x29,0x75,0xaf,0xde,0x05,0xf6,0x50,0xf7,0x9a,0x14,0xb0,0x16,0x6c,0x02, +0xd5,0xd4,0xbd,0x76,0x03,0x28,0xa6,0xee,0xf5,0xbb,0xa9,0x3b,0x17,0xe5,0x73,0xb7, +0x52,0xf7,0x0e,0xe4,0x95,0x16,0x01,0x9c,0xdf,0x59,0x01,0x1f,0xa2,0xfe,0xae,0xd5, +0x60,0x3d,0x75,0xc3,0xc6,0xee,0xdd,0x48,0xe3,0x3e,0xb8,0x18,0x57,0x42,0x17,0x97, +0x6c,0x07,0x7b,0x41,0x2d,0x68,0xa4,0x8b,0xa9,0x29,0x20,0x1b,0xac,0xa7,0x8b,0x69, +0x3b,0xe8,0x62,0x46,0x22,0x48,0xa5,0x8b,0xab,0x72,0xc1,0x66,0xba,0xb8,0x7a,0x1d, +0x28,0x00,0x5b,0xc1,0x6e,0xba,0xb8,0x66,0x29,0x58,0x49,0x17,0xb3,0xd1,0x46,0x76, +0x3d,0x5d,0xcc,0xd9,0x09,0xd0,0xce,0x7a,0xc4,0x05,0x68,0xa3,0xa0,0x08,0x54,0xd0, +0xc5,0x4d,0x35,0x74,0x71,0x73,0x15,0x68,0xa0,0x8b,0xdb,0xa0,0xbb,0x04,0xf5,0x4a, +0xaa,0xe9,0x22,0x46,0xf1,0xc5,0x0a,0xe4,0xe3,0xe1,0x7c,0x11,0x0f,0xe0,0x8b,0x0d, +0x69,0xa0,0x9e,0x7a,0x98,0x38,0xb0,0x0c,0xac,0x04,0x15,0xd4,0x13,0xd7,0x48,0x3d, +0xf1,0xa9,0xd4,0x93,0xb2,0x11,0x6c,0x07,0xc8,0x4b,0xa9,0xa3,0x9e,0x25,0x28,0xb3, +0x64,0x3d,0x28,0xa0,0x9e,0xd4,0x9d,0xa0,0x1c,0x54,0x51,0x4f,0x76,0x3a,0x28,0xa1, +0x9e,0x42,0x06,0xa0,0x4c,0x21,0xea,0x15,0x37,0x50,0xcf,0xe6,0xa5,0xd4,0xb3,0x05, +0x6d,0x6e,0x45,0x3e,0xee,0xff,0x1e,0xdc,0xc7,0x3d,0xb8,0x1f,0x7b,0xca,0x50,0x07, +0xf7,0x42,0x4f,0xe5,0x26,0xb0,0x9b,0x7a,0xf6,0xa2,0x7d,0x2c,0xa6,0x7a,0x6a,0xd3, +0xa8,0xa7,0x01,0xed,0xe3,0x31,0xda,0x83,0xed,0x47,0x6f,0xfc,0x0a,0xea,0x4d,0x4a, +0xa5,0xde,0x94,0x64,0xb0,0x0c,0xe0,0x38,0x6b,0x1f,0xf5,0xae,0x61,0xa8,0x77,0x5d, +0x2e,0xf5,0xe6,0xec,0x05,0xd5,0xd4,0xbb,0x7e,0x2b,0xf5,0xe6,0xe1,0x5c,0x5e,0x3e, +0x28,0x02,0xdb,0xa8,0xb7,0x60,0x29,0x28,0x05,0x15,0xd4,0xbb,0x21,0x8e,0x7a,0x8b, +0x50,0x66,0xe3,0x7a,0x50,0x40,0xbd,0x9b,0xd7,0x80,0x6c,0xb0,0x83,0x7a,0xb7,0x23, +0xbf,0x64,0x1d,0x40,0xfe,0x8e,0x62,0xb0,0x0b,0x94,0x83,0x3a,0xea,0x2d,0xcd,0xa1, +0xde,0x0a,0xe4,0x61,0x1d,0xd9,0x8b,0x31,0xd4,0x8b,0xc5,0x5f,0x2f,0x16,0x75,0xbd, +0x58,0xc8,0xf5,0x62,0xe1,0xd6,0x8b,0x45,0x5b,0x2f,0x16,0x5a,0xbd,0x58,0x64,0xf5, +0xd6,0x65,0x80,0x55,0x60,0x03,0x40,0x99,0xfa,0x34,0xb0,0x12,0xf7,0x13,0x7b,0x4f, +0xc1,0xd6,0x86,0x0d,0xe4,0x8b,0xe7,0xc4,0x4a,0x8c,0xfc,0x44,0x90,0x44,0xce,0x9f, +0xc6,0x67,0xb3,0x41,0x0e,0x7d,0x1a,0xbf,0xe4,0xd3,0xf8,0x34,0x44,0x15,0x9f,0x26, +0x2c,0xa1,0x73,0x89,0x58,0x32,0x25,0x62,0xc9,0x94,0x8c,0x95,0x7d,0x22,0x96,0x0e, +0xc9,0xd8,0x54,0x24,0x63,0x99,0x97,0x88,0xe5,0x53,0x22,0x96,0x4f,0x89,0x58,0x3e, +0x25,0xe3,0xf1,0x9f,0x8c,0x85,0x46,0x32,0x16,0x10,0xc9,0x58,0x76,0x25,0x63,0xd9, +0x95,0x8c,0x65,0x57,0x22,0x36,0x31,0x89,0x58,0xd2,0x25,0x62,0x49,0x97,0xc8,0xb6, +0x85,0xe5,0x41,0x22,0x96,0x9a,0x89,0xd8,0x08,0x25,0x62,0xb9,0x99,0xb8,0x0c,0x60, +0xc9,0x99,0x98,0x01,0xb0,0xec,0x4c,0xc4,0x1a,0x23,0x11,0x6b,0x8c,0x44,0x2c,0xfb, +0x92,0x50,0x36,0x09,0xcb,0xaf,0x24,0x2c,0xbf,0x92,0xb0,0xfc,0xc2,0xdd,0x7d,0x2e, +0x09,0xcb,0xaf,0x24,0x2c,0xbf,0x92,0xb0,0xd1,0x49,0xc2,0x92,0x33,0x09,0x36,0xe1, +0x8e,0x3f,0x97,0x04,0x9b,0x92,0x60,0x53,0x12,0x36,0x3a,0x49,0x58,0x7e,0x26,0xc1, +0x9e,0x24,0xd8,0x93,0x04,0x7b,0x92,0x60,0x4f,0x12,0xec,0x49,0x62,0xed,0xc1,0x32, +0x32,0x11,0x4b,0xbc,0x14,0xd8,0x93,0x02,0x7b,0x70,0x15,0xcf,0xa5,0x40,0x77,0x0a, +0x96,0x7e,0x29,0x58,0xf6,0xa5,0x60,0x99,0x9b,0x88,0x3d,0x4e,0x0a,0x96,0xb9,0x29, +0x58,0xe6,0x26,0x22,0x4e,0xc4,0xe6,0x2b,0x11,0x4b,0x9b,0x44,0xd8,0x92,0x08,0x5b, +0x12,0xa1,0x3f,0x11,0xba,0x13,0xa1,0x37,0x11,0x7a,0x13,0x59,0x5f,0x40,0x6f,0x22, +0xf4,0x26,0x42,0x5f,0x22,0x96,0x9a,0x49,0xf0,0x59,0x12,0x74,0x24,0xb1,0xed,0xc3, +0x8e,0x14,0xd6,0x0e,0xb4,0x9f,0x84,0xcd,0x5d,0x12,0x74,0xe0,0x79,0x7e,0x2e,0x99, +0xf5,0x1b,0x6c,0x48,0x46,0x7f,0x93,0xd1,0xdf,0x64,0xd8,0x96,0x0c,0x5d,0xc9,0x85, +0x98,0xe5,0x52,0x31,0xfb,0xac,0x47,0x9c,0x06,0x4a,0x01,0xee,0x98,0xd5,0xe5,0x88, +0x31,0xf3,0x61,0xb7,0xd4,0xb5,0x09,0xb3,0x55,0xee,0x6e,0x92,0xe1,0xe2,0xc8,0xd9, +0x30,0x9e,0x0b,0x13,0xb8,0x30,0x89,0x0b,0x93,0xb9,0x30,0x85,0x0b,0x53,0xb9,0x70, +0x29,0x17,0x2e,0xe3,0xc2,0x0c,0x2e,0xcc,0xe4,0xc2,0xe5,0x5c,0xb8,0x82,0x0b,0x57, +0x22,0xbc,0xb4,0x9b,0x6d,0xf3,0xb3,0xf8,0x75,0x6c,0xb8,0x74,0x13,0x1b,0xe6,0xd5, +0xb1,0xe1,0x96,0x25,0x6c,0xb8,0x7b,0x35,0xc2,0xcf,0xe3,0x77,0xb0,0x61,0x56,0x22, +0x1b,0xe6,0xb3,0x2d,0x7c,0xbe,0x7b,0x2b,0x1b,0x56,0xef,0x41,0x78,0x39,0x81,0x6d, +0xe1,0xf2,0x32,0x56,0xd7,0xe5,0x2c,0xb6,0x9d,0xcf,0x37,0xb2,0x2d,0x7c,0xbe,0x6e, +0xd3,0xe7,0x1b,0x12,0xf5,0x89,0xcb,0xeb,0xd9,0x04,0xa6,0x76,0x36,0xac,0x59,0xc6, +0xa5,0x59,0x3b,0xd1,0x6d,0x2e,0x87,0xd5,0xd2,0x95,0x54,0xca,0xe5,0x27,0x70,0xe9, +0x12,0x36,0x5d,0x9d,0xc7,0xa6,0xd3,0xe3,0x10,0x62,0xca,0x43,0x88,0x89,0x8c,0x4d, +0xef,0xde,0xc3,0xe5,0xb0,0x36,0xe0,0xb6,0x64,0xcb,0xe4,0x16,0xb0,0x39,0x6b,0x8b, +0xd9,0x70,0xc3,0x76,0xee,0x2c,0xdb,0xfe,0xc5,0x4d,0x0d,0xec,0xd9,0xe5,0xe9,0x6c, +0x3a,0xb5,0x1a,0x61,0x4f,0x79,0x21,0x9b,0x2e,0xe6,0x5a,0x4e,0x63,0xdb,0xb9,0x50, +0xbb,0x91,0x4d,0xaf,0x60,0x6d,0xee,0x2a,0xdd,0xcc,0x9e,0x5d,0xcf,0xe6,0x5c,0xa8, +0x63,0xf5,0xf6,0x54,0xa4,0x70,0x36,0xac,0xe6,0x6a,0x71,0x16,0xd6,0xb1,0x1a,0x31, +0x35,0x71,0x61,0x85,0x9c,0xba,0xb2,0xf0,0x34,0xa8,0xae,0xa3,0x8b,0x3b,0x33,0x69, +0xd6,0x6b,0x13,0x48,0xa9,0x20,0xa5,0x92,0x94,0x58,0x2f,0x06,0x90,0x12,0x2b,0x45, +0x35,0x29,0x83,0x48,0x19,0x4c,0xca,0x10,0x52,0xf9,0x93,0x4a,0x41,0x2a,0x25,0xa9, +0x54,0xa4,0x0a,0x20,0x55,0x20,0xc1,0xff,0x04,0xef,0x13,0x7c,0x4f,0xf0,0x3c,0xc1, +0xef,0x04,0xaf,0x13,0x7c,0x4e,0xf0,0x38,0xc1,0xdf,0x04,0x6f,0x13,0x7c,0x4d,0xf0, +0x34,0xc1,0xcf,0x04,0x2f,0x23,0xaf,0xea,0x52,0xc5,0x06,0x82,0xab,0x3f,0xcf,0xc3, +0x51,0xce,0x6e,0x3c,0x18,0x57,0xe3,0x81,0xc8,0x0e,0x9f,0x04,0x3c,0x34,0xf3,0x08, +0x7e,0xc0,0x43,0x02,0x13,0xfa,0x26,0x3c,0x78,0x96,0xa7,0x63,0xa2,0xaf,0xc6,0xc4, +0x57,0x48,0xe8,0x3b,0x1e,0x8e,0x98,0x98,0xb7,0xb0,0x13,0x3c,0x26,0xb4,0x38,0x0c, +0xaf,0xc4,0xed,0x98,0x16,0xf0,0x60,0xa9,0xc0,0x84,0xb4,0x01,0x0f,0x5b,0xec,0xc6, +0xba,0x92,0xb3,0xf1,0x60,0xc1,0x83,0x71,0xdf,0x66,0x3c,0x20,0xf1,0xa0,0x5a,0x56, +0x8b,0x07,0x20,0x1e,0x92,0xa5,0x78,0x38,0xac,0xdf,0x88,0x32,0x98,0xb8,0xb1,0x00, +0x80,0x6f,0x30,0x44,0x73,0x49,0xa5,0x26,0x55,0x10,0xa9,0xb0,0xec,0x0d,0xa1,0x00, +0xac,0xce,0x15,0x14,0xa0,0xa4,0x00,0x15,0x05,0x04,0x50,0x00,0xd6,0xc8,0x6a,0x0a, +0x08,0xa2,0x80,0x60,0x0a,0x08,0xa1,0x40,0x2c,0x56,0xd9,0x47,0x98,0x92,0x0d,0x54, +0x6c,0x10,0xc0,0x06,0x81,0x6c,0xa0,0x66,0x83,0x20,0x36,0x08,0x66,0x83,0x10,0x36, +0x50,0xf8,0x73,0x21,0x57,0x47,0xc1,0x55,0x7a,0x75,0x12,0x4d,0x98,0x03,0xe6,0xd3, +0xb4,0xd7,0xc6,0x63,0xee,0x2a,0x02,0x9b,0xc0,0x66,0xb0,0x15,0x6c,0x07,0x25,0xa0, +0x14,0xec,0x02,0x65,0xec,0xfc,0x06,0x2a,0xc1,0x3e,0x50,0x0d,0x6a,0x41,0x3d,0x68, +0xa4,0x4f,0x13,0xe2,0x40,0x22,0x48,0x26,0x76,0x12,0xfc,0x34,0x01,0xf3,0x61,0xc2, +0x52,0xb0,0x0c,0xa4,0x83,0x0c,0x90,0x09,0x56,0x82,0x2c,0xb0,0x0e,0xac,0x07,0xf9, +0xa0,0x00,0x6c,0x00,0x85,0x00,0x76,0x24,0xc0,0x8e,0x04,0xd8,0x91,0x00,0x3b,0x12, +0xb6,0x01,0xd8,0x92,0x00,0x5b,0x12,0x76,0x00,0xd8,0x93,0x00,0x7b,0x12,0x76,0x03, +0xd8,0x94,0x80,0x9b,0xbc,0x76,0x53,0xd7,0xca,0x65,0x6c,0x17,0x3e,0x4d,0x58,0xf1, +0x69,0x42,0x1d,0xa7,0x9f,0x3d,0x28,0x81,0xa6,0x4f,0xe3,0x0b,0xf5,0x07,0x98,0x9b, +0x73,0xf4,0xbd,0x2c,0xe2,0xca,0xb0,0x7d,0xdb,0x04,0x13,0xd9,0x33,0xf1,0xbb,0xf5, +0x07,0x15,0x5c,0x37,0xe2,0x37,0x7f,0x1a,0xbf,0x0d,0x07,0xac,0x23,0xd0,0x4f,0x74, +0x9f,0xab,0x90,0xca,0x1d,0x23,0x15,0x8f,0x76,0xeb,0x58,0x0f,0x71,0x55,0xab,0xf5, +0xa9,0x3a,0xae,0x07,0x38,0xc5,0xb6,0xc3,0xf9,0x0e,0xa6,0x7f,0x9a,0x90,0xa0,0x37, +0x06,0x07,0xa5,0xc8,0xd6,0xd7,0xdb,0xc1,0x1d,0x54,0xe8,0x53,0x15,0x9c,0x07,0xe2, +0x77,0xe2,0x80,0x8b,0x58,0x83,0xd8,0x42,0x28,0x51,0x3c,0x50,0x63,0x27,0xd7,0x17, +0x66,0xe0,0x4c,0xa9,0x21,0x82,0xe1,0x9c,0x96,0x0d,0xfd,0xc7,0x09,0x85,0xfa,0xfe, +0xeb,0xbb,0xa7,0xcf,0xda,0x35,0x60,0xc5,0xcd,0xc2,0x86,0x14,0x57,0x92,0x35,0x64, +0x17,0xab,0x20,0xbe,0x8e,0x33,0xbe,0x54,0x7f,0x5c,0xca,0xb5,0x94,0xce,0x5e,0x79, +0xae,0xd3,0xd5,0xfa,0xe7,0x5b,0x09,0x77,0x65,0xd9,0x14,0xce,0xe6,0xb1,0xe3,0x81, +0xad,0xc4,0x35,0xc0,0x1d,0x70,0x3e,0x1c,0x70,0xc7,0x3e,0xae,0x0b,0x06,0x07,0xd7, +0x0e,0x38,0x58,0x9f,0x62,0x47,0x09,0xd3,0xdf,0x76,0x42,0x0a,0x37,0xac,0x12,0x52, +0xf5,0x57,0x5a,0x6f,0x57,0x42,0x9a,0x7e,0xdc,0x64,0xf4,0x77,0x21,0x21,0x93,0x33, +0x91,0x1d,0x67,0xdc,0x95,0xbe,0xa5,0x25,0xfd,0x95,0x67,0xcf,0x2c,0xe7,0x52,0x3b, +0xf4,0x0d,0xad,0x66,0xaf,0x37,0x2e,0xa2,0xc1,0x27,0xec,0xf1,0xae,0x81,0x14,0xab, +0x62,0x95,0xfe,0x88,0x1d,0x28,0xfd,0x57,0x2c,0x55,0x7f,0xbc,0xb1,0x7f,0x2c,0x25, +0xac,0x61,0xb3,0xd1,0x99,0xf8,0x2d,0xfd,0x85,0x13,0xf4,0x03,0x24,0x61,0x1d,0xdb, +0x5c,0x7c,0x63,0xff,0x88,0x62,0x87,0x58,0x3d,0x17,0xb1,0xd7,0x71,0x25,0x57,0x80, +0x75,0x59,0xa2,0x3e,0x4f,0x3f,0x5c,0xd8,0x14,0x4c,0xaf,0x42,0x2a,0x9b,0x4b,0xb1, +0xb7,0x4f,0x5e,0xff,0x00,0x64,0xf5,0xe5,0x72,0x95,0xd8,0xd4,0x7a,0xbd,0x9a,0x3c, +0xee,0x54,0xaa,0x3e,0xc3,0xa0,0x4a,0x9f,0x62,0xcf,0xe6,0xf7,0x5f,0x82,0xd2,0xfe, +0x03,0xae,0x40,0x3e,0xd7,0x99,0x4c,0x7d,0xaa,0x84,0xbb,0x8b,0xd9,0x54,0x05,0x77, +0x59,0xb6,0xe8,0xab,0x16,0xf4,0x5f,0x6b,0xfd,0x01,0x77,0xa7,0x15,0x70,0x17,0x6d, +0xf9,0x80,0xa2,0x42,0x6e,0x6c,0x72,0xd1,0xc0,0x85,0xb9,0x75,0x9c,0x25,0x6c,0xea, +0xbf,0x3f,0x0c,0x29,0x36,0x6f,0xb3,0xfe,0xa6,0x23,0xae,0xad,0x84,0x81,0xa2,0xdb, +0xf5,0x37,0x74,0x09,0xeb,0x7e,0x76,0x34,0xb3,0xa9,0x3a,0xce,0xc1,0xdc,0xfd,0xad, +0x9f,0x06,0xf4,0xb7,0x05,0xd6,0x54,0xe5,0xfa,0x16,0xfa,0x47,0xb0,0xff,0x45,0xb8, +0x4f,0xc1,0x06,0x4a,0x36,0x50,0xb1,0x41,0x00,0x1b,0x04,0xb2,0x81,0x9a,0x0d,0x82, +0xd8,0x20,0x98,0x0d,0x42,0xb8,0xc2,0xfa,0x2a,0x5c,0x1d,0x05,0x57,0x49,0xc1,0xd5, +0x52,0x70,0xd5,0x14,0x5c,0x3d,0x05,0x57,0x51,0xc1,0xd5,0x54,0x70,0x55,0x15,0x5c, +0x5d,0x25,0x57,0x57,0xa9,0xd7,0xc7,0xd5,0x55,0x72,0x75,0x95,0x5c,0xdd,0x57,0x67, +0x8d,0xa1,0xf1,0x63,0x68,0xcc,0x3c,0x1a,0x3b,0x66,0x0e,0xcd,0x9c,0x4f,0xb3,0xc6, +0xd1,0xf8,0xe9,0xf8,0x51,0x02,0x15,0x4d,0x9e,0x87,0xe7,0x59,0x45,0xf7,0x92,0xe5, +0xd4,0xbd,0xae,0x94,0x9d,0x9d,0xb0,0x07,0x62,0x9f,0x04,0xdd,0xeb,0x32,0xba,0xb1, +0x13,0xc4,0x83,0xa5,0xab,0x2e,0xf3,0x42,0x5d,0x0e,0xfb,0x64,0x41,0x4b,0x33,0xc6, +0xd0,0xb1,0xba,0x31,0x34,0x7d,0x0c,0x4d,0xc5,0xcf,0x58,0x9a,0x3e,0x96,0x26,0x8d, +0xa5,0x71,0x63,0xa6,0xd1,0x54,0x36,0x98,0x35,0x91,0x66,0x4c,0x44,0x09,0x96,0x49, +0x34,0x7d,0x12,0x4d,0x9d,0x44,0xaf,0x2e,0xa4,0xa9,0x60,0x3a,0x98,0x04,0x5e,0x03, +0xc7,0xea,0xa6,0xd1,0xf4,0x69,0x34,0x1e,0xb5,0xa6,0xd1,0xc4,0xe9,0x34,0x63,0x3a, +0xb2,0xa6,0xd3,0xf4,0xe9,0x34,0x6e,0x3a,0x4d,0x65,0x13,0x4a,0xa4,0x94,0x84,0x9f, +0xa9,0x6c,0x04,0x3b,0xc7,0x01,0xfc,0x4c,0x65,0xa3,0xf3,0x4b,0xb2,0xe6,0xea,0x43, +0x9c,0x87,0x51,0xd3,0xc1,0x24,0x30,0x67,0xcc,0x78,0x16,0xee,0xb4,0x21,0x56,0xd2, +0xac,0xb9,0x34,0x63,0x2e,0x9a,0x47,0x8d,0xb9,0x34,0x6b,0x3e,0xcd,0x98,0x8f,0x83, +0xf9,0x34,0x7d,0x3e,0x4d,0x85,0x2f,0x5e,0xa7,0x19,0xaf,0xe3,0xf8,0x75,0x9a,0xfe, +0x3a,0x4d,0xc5,0x4f,0x5b,0x2a,0x4d,0x07,0x63,0x67,0xd3,0xb8,0x71,0x34,0x6e,0x3c, +0x8d,0x43,0x23,0xe8,0xc3,0x78,0x74,0x73,0x01,0xbd,0x3a,0x06,0xde,0xa4,0xc9,0x33, +0x68,0xea,0x54,0x9a,0xfa,0x1a,0x4d,0x9b,0x4e,0xd3,0x66,0xd0,0xb4,0x99,0x93,0x68, +0xda,0x1b,0x34,0x7d,0x32,0xba,0x34,0x13,0x1e,0x78,0x95,0x66,0xcd,0x9a,0x4e,0xb3, +0xe6,0xd0,0x5c,0xfc,0xcc,0xa7,0xd7,0xc7,0xd2,0x7c,0xb4,0x31,0x9d,0xc6,0x70,0xa1, +0x82,0xdd,0xd6,0x29,0xd9,0x40,0xc5,0x06,0x01,0x6c,0x10,0xc8,0x06,0x6a,0x36,0x08, +0x62,0x83,0x60,0x36,0x08,0x61,0x03,0x3c,0x0b,0xd9,0x90,0xab,0xa3,0xe0,0x2a,0x29, +0xb8,0x5a,0x0a,0xae,0x9a,0x82,0xab,0xa7,0xe0,0x2a,0x2a,0xb8,0x9a,0x0a,0xae,0xaa, +0x82,0xab,0xab,0xe4,0xea,0x2a,0xf5,0xfa,0xb8,0xba,0x4a,0xae,0xae,0x92,0xab,0xab, +0xe4,0xea,0x2a,0xb9,0xba,0x4a,0xae,0xae,0x92,0xab,0xab,0xe4,0xea,0xaa,0xb8,0xba, +0x2a,0xae,0xee,0x24,0x5c,0xd5,0x4b,0xd9,0x71,0x20,0x01,0x24,0x81,0x14,0x90,0x0a, +0xd2,0x41,0x26,0x58,0x01,0x56,0x81,0x2c,0xb0,0x16,0x64,0x83,0xf5,0x20,0x0f,0x14, +0x80,0x42,0xb0,0x11,0x14,0x83,0x2d,0x60,0x1b,0x28,0x01,0xa5,0x74,0x29,0x07,0xed, +0xe6,0xa0,0xdd,0x1c,0xb4,0x9b,0x83,0x76,0x73,0xd0,0x6e,0xce,0x52,0x80,0xb6,0x73, +0xd0,0x76,0x0e,0xda,0xce,0x41,0xdb,0x39,0x68,0x3b,0x07,0x6d,0xe7,0xa0,0xed,0x1c, +0xb4,0x9d,0x8b,0xf6,0x72,0xd1,0x5e,0x2e,0xda,0xcb,0x45,0x7b,0xb9,0x68,0x2f,0x17, +0xed,0xe5,0xee,0x02,0x15,0xa0,0x12,0xec,0x03,0xd5,0xa0,0x16,0xd4,0x83,0x46,0xba, +0x94,0x07,0x7d,0x79,0xd0,0x97,0x07,0x7d,0x79,0xd0,0x97,0x07,0x7d,0x79,0xd0,0x97, +0x07,0x7d,0x79,0xd0,0x87,0xad,0xdd,0xa5,0x3c,0xe8,0xcb,0x83,0xbe,0x3c,0xe8,0xcb, +0x83,0xbe,0x3c,0xe8,0xcb,0x43,0x5f,0xf2,0xd0,0x97,0x3c,0xf4,0x25,0x0f,0xba,0xf3, +0xa0,0x3b,0x0f,0xba,0xb1,0xfd,0xbb,0x94,0x07,0xdd,0x79,0xd0,0x9d,0x07,0xdd,0x79, +0x35,0xa0,0x8e,0xce,0x55,0x42,0x6f,0x1e,0xf4,0xe5,0x43,0x5f,0x3e,0xf4,0xe5,0x43, +0x5f,0x3e,0xf4,0xe5,0x2f,0x03,0xd0,0x91,0x0f,0x1d,0xf9,0x68,0x3f,0x1f,0xed,0xe7, +0xa3,0xfd,0x7c,0xb4,0x9f,0x8f,0xf6,0xf3,0xd1,0x7e,0x3e,0xda,0xcf,0x47,0xfb,0xf9, +0x68,0x3f,0x7f,0x1b,0xb5,0xee,0xa0,0x23,0xf9,0x74,0x04,0x95,0x4b,0xd9,0x4a,0xe8, +0x58,0x3e,0x3a,0x96,0x0f,0x05,0xf9,0xe8,0x58,0x3e,0x3a,0x96,0x0f,0x45,0x05,0x50, +0x54,0xc0,0x2a,0xc2,0x4e,0x63,0x6f,0x06,0xd2,0x4b,0x40,0x1a,0xb5,0x6e,0x42,0x84, +0xbe,0x15,0xa0,0x6f,0x05,0xd0,0x5b,0x80,0x26,0x0a,0xd0,0xb7,0x02,0xe8,0x2e,0x80, +0x6e,0x6c,0xe5,0x0f,0xae,0xa7,0xd6,0x7d,0xd4,0x5a,0x87,0x83,0xbd,0x74,0x69,0x07, +0xda,0x2e,0x5d,0x49,0x47,0x50,0xa7,0x14,0x7e,0x29,0xc5,0x26,0x27,0x03,0x1b,0xa4, +0x0c,0x6c,0xd8,0x32,0xb0,0x49,0xca,0xc0,0x26,0x29,0x03,0x1b,0xb6,0x0c,0x6c,0xd8, +0x32,0xb0,0x61,0xcb,0xc0,0x86,0x29,0x03,0x1b,0xb6,0x0c,0x6c,0x9a,0x32,0xb0,0x61, +0xcb,0xc0,0xc6,0x29,0x03,0x1b,0xa7,0x0c,0x6c,0x9c,0x32,0xb0,0x71,0xca,0xc0,0xc6, +0x29,0x03,0x1b,0xb6,0x0c,0x6c,0x94,0x32,0xb0,0x51,0xca,0xc0,0x86,0x2d,0x03,0x1b, +0xb6,0x0c,0x6c,0xd8,0x32,0xb0,0x99,0xca,0xd8,0x07,0xaa,0x40,0x35,0xa8,0x01,0xb5, +0x00,0xfe,0xcb,0xa8,0x07,0x0d,0xa0,0x91,0xce,0x65,0x62,0xc3,0x95,0x89,0x4d,0x6a, +0x26,0x36,0xa8,0x99,0xd8,0x98,0x66,0x62,0x83,0x95,0x89,0x0d,0x56,0x26,0x36,0x9f, +0x99,0xd8,0x88,0x65,0x62,0xa3,0x95,0x89,0x8d,0x67,0x26,0x36,0x9e,0x99,0xd8,0x78, +0x66,0xc2,0xe6,0x4c,0x6c,0x3c,0x33,0xb1,0xf9,0xcb,0xc4,0xc6,0x33,0x13,0x1b,0xcf, +0x4c,0x6c,0xc4,0x32,0xb1,0x11,0xcb,0xc4,0x66,0x30,0x13,0x2e,0xca,0xc4,0x46,0x31, +0x73,0x0d,0xc0,0xc6,0x2d,0x13,0x1b,0xb7,0x4c,0x6c,0xdc,0x32,0xb1,0xa1,0xcd,0x5c, +0x0f,0xd8,0x6f,0xfa,0xb0,0x39,0xcc,0xc4,0x86,0x2d,0x13,0x1b,0xc5,0x4c,0xf4,0x3f, +0x13,0xfd,0xcf,0x44,0xff,0x33,0xd1,0xff,0x4c,0xf4,0x3f,0x13,0xfd,0xcf,0x44,0xff, +0x33,0xd1,0xff,0x4c,0xf4,0x3f,0x13,0xfd,0xcf,0x44,0xff,0x33,0xd1,0xff,0x4c,0xf4, +0x3f,0x13,0xfd,0xcf,0x44,0xff,0x33,0x77,0x51,0x4f,0xd9,0x12,0xea,0x5e,0xbf,0x07, +0xab,0x67,0xc4,0xd8,0xc6,0x5f,0xa8,0x2a,0xc7,0x0a,0xbb,0x98,0xba,0x8a,0xb1,0xea, +0x5e,0x83,0x15,0x75,0x31,0xf2,0x53,0xd8,0xd7,0x2c,0xdb,0xe8,0x62,0x43,0x12,0xf5, +0xac,0x6b,0xa4,0x9e,0xfc,0x1a,0xea,0xd9,0x58,0x45,0xbd,0xf1,0x99,0xd4,0xbd,0x35, +0x9e,0xba,0xf7,0xac,0xa7,0x8b,0x09,0xd9,0x74,0x11,0x36,0xf5,0x2c,0xaf,0xa7,0x5e, +0x6c,0x8e,0x7b,0xb7,0x94,0x61,0x17,0x10,0x8f,0x15,0x79,0x25,0x75,0xef,0x48,0xa4, +0x8b,0xec,0xeb,0x92,0x75,0xa5,0xd4,0x5b,0x95,0x4f,0x5d,0x95,0x98,0xcd,0x1b,0x4b, +0xa8,0x67,0x6d,0x3a,0xf5,0x14,0x6f,0xa2,0xee,0xa5,0xec,0x2b,0x96,0x75,0xd4,0xb3, +0xa1,0x80,0xba,0x6a,0xd3,0xb0,0x53,0x58,0x4b,0xdd,0x95,0xdb,0xe9,0xe2,0xd2,0x3a, +0xea,0xc5,0xba,0xe5,0x42,0x43,0x32,0x76,0x00,0xfb,0xa8,0x6b,0x69,0x3e,0x75,0xaf, +0x4a,0xa4,0xee,0x92,0x55,0x68,0x6f,0x39,0x56,0xfe,0x5b,0xd0,0x66,0x32,0xf5,0x64, +0xe7,0x52,0xcf,0xbe,0x5d,0xd4,0x9b,0x5b,0x4e,0xbd,0xa5,0x88,0xf7,0xd5,0xd0,0xc5, +0xa2,0x65,0xd8,0x5d,0x34,0xd2,0xc5,0xbd,0x1b,0xa8,0x07,0xfe,0xef,0x5d,0x96,0x48, +0x3d,0x25,0x6b,0xa8,0x6b,0x23,0x74,0xd4,0xc1,0x9e,0x32,0xe4,0xc7,0x35,0x60,0x27, +0x52,0x44,0x17,0x37,0xa6,0xa1,0xff,0xf1,0xd4,0xbb,0x1e,0x3a,0x36,0xae,0xa3,0xae, +0xb2,0x22,0xf4,0x6b,0x15,0x75,0xef,0xcb,0xa1,0xee,0xba,0x4c,0xba,0xb8,0x67,0x17, +0x5d,0xac,0xc2,0xee,0x24,0x7b,0x29,0x6c,0x58,0x49,0x3d,0xf1,0x88,0x53,0x72,0x01, +0x74,0x6c,0xcd,0x85,0x8e,0x06,0xe8,0x28,0xc3,0xf9,0x4a,0xea,0xd9,0xc9,0xa0,0x3f, +0x99,0xd0,0xd5,0x00,0x5f,0x56,0x53,0xd7,0xae,0x2d,0xd4,0xcd,0xac,0xa4,0x8b,0x19, +0x29,0x74,0x31,0x6b,0x37,0x76,0x2e,0x6b,0xa1,0xaf,0x16,0x7d,0x6a,0xa4,0xae,0x86, +0x6d,0x28,0x93,0x8e,0x9d,0xce,0x32,0xea,0xce,0xaa,0x82,0x9e,0x22,0xf8,0x3e,0x81, +0xba,0x0a,0xf3,0xe9,0x62,0x2e,0x76,0x34,0x2b,0xe0,0x97,0xed,0xd8,0x39,0xed,0xac, +0xa1,0xee,0x72,0x5c,0x87,0xa5,0xd0,0xb3,0xb4,0x98,0xba,0x31,0xe6,0x2f,0x66,0x15, +0xc3,0xbf,0x3b,0xb1,0xcb,0xc2,0x8e,0x29,0x25,0x95,0xba,0x8b,0xe2,0xe8,0x62,0x05, +0xfc,0x91,0x8a,0x6b,0x5a,0xb2,0x92,0x7a,0x53,0xb0,0x11,0x5c,0x5a,0x49,0x5d,0x2b, +0x70,0x0d,0x6a,0x77,0x50,0xf7,0xda,0x24,0xf8,0x1c,0xfd,0xdd,0x84,0x6b,0xb3,0x06, +0xd7,0x61,0x1b,0xe2,0x9a,0xb5,0xd4,0x5b,0x9b,0x81,0xeb,0x9f,0x8c,0xdd,0xd5,0x3e, +0xea,0xa9,0x87,0x7e,0xec,0xed,0xba,0x93,0x71,0x7d,0x96,0xa0,0x1f,0x2b,0xd9,0xfe, +0x6f,0xa4,0x8b,0x49,0xd8,0xb9,0xad,0x04,0x5b,0xd2,0xe8,0xe2,0xff,0x63,0xd7,0x6d, +0x80,0x9a,0xba,0xd6,0xfd,0xff,0x85,0x82,0x12,0x0b,0x05,0x94,0x28,0x58,0xb0,0xa0, +0x44,0xc5,0x12,0x48,0x4e,0x93,0x96,0x60,0x68,0x45,0x41,0x09,0x24,0xbc,0xa3,0xa0, +0xa0,0xd2,0x02,0x26,0x90,0x28,0x81,0x04,0x08,0x24,0x90,0x57,0x48,0x42,0xc2,0x4b, +0x05,0x0a,0x15,0x5a,0x50,0x50,0xb0,0x60,0x45,0x88,0x82,0x05,0x2b,0x77,0x64,0xae, +0xf4,0x27,0x33,0x32,0x23,0xb7,0xd2,0xca,0x8c,0x9c,0x12,0x24,0x77,0x64,0x06,0x7e, +0x23,0xff,0x29,0xff,0x91,0x99,0xff,0xb3,0x42,0xdb,0x7f,0xcf,0xb9,0xe7,0xdc,0xf3, +0xd6,0xd3,0x7b,0x7b,0x4a,0x3e,0xac,0xef,0x5e,0x7b,0xad,0xbd,0xd7,0x5e,0xeb,0x79, +0x9e,0xb5,0xf6,0xde,0x24,0xb7,0x20,0x56,0x14,0x70,0x8d,0xc1,0xcb,0x68,0xee,0xfc, +0x35,0x64,0x91,0x5f,0x42,0x16,0xa3,0x1e,0x99,0xb5,0xf0,0x36,0xa6,0x87,0x37,0xb4, +0x0f,0x86,0x20,0x16,0xb4,0x10,0x1f,0xf8,0xba,0x3a,0x64,0xfe,0x02,0xfc,0x6f,0x84, +0x1b,0xf5,0xb5,0x6b,0xe8,0xd9,0x75,0xb8,0x3e,0xc4,0x03,0xbc,0x67,0x20,0xf3,0x05, +0xb0,0xcd,0x4d,0x18,0x97,0x1c,0xec,0x07,0x73,0xef,0x59,0x0d,0x8e,0xaf,0x8f,0xa0, +0xed,0x32,0x64,0xd1,0xf6,0x81,0x2f,0x6e,0x22,0x4b,0xb3,0x16,0xde,0x00,0x1b,0xc0, +0x56,0x15,0xe8,0xd9,0x65,0xb8,0x56,0x19,0x94,0x7f,0xd4,0x8f,0x66,0xe1,0xfd,0x66, +0xe6,0x36,0xc4,0x84,0xea,0x23,0xb0,0x2f,0xd8,0xe0,0xfa,0x17,0x68,0xb6,0x1e,0xe2, +0xaf,0xbc,0x12,0xe2,0x54,0x09,0xfd,0x82,0xb8,0x51,0x0c,0xa2,0xd9,0x8f,0xe0,0xfc, +0x06,0xa8,0xd7,0x83,0x7d,0x9a,0xa1,0x0f,0x9f,0xf4,0x42,0x5c,0x29,0xd0,0xec,0x6d, +0xb8,0x66,0x35,0x8c,0xa7,0x0e,0xce,0x69,0xfd,0x14,0xec,0x5e,0x8d,0x2c,0x60,0xf3, +0x59,0x2d,0x5c,0xa3,0xb1,0x1f,0x99,0xe5,0x9f,0x22,0x73,0x1f,0xbc,0x71,0xde,0xba, +0x0a,0xe3,0x84,0xb7,0x51,0xb8,0xfe,0xac,0x06,0xe2,0xae,0x05,0xec,0xf5,0x11,0x5c, +0x57,0x0b,0x36,0xaf,0x06,0xfb,0xf6,0x80,0x2f,0x1a,0x20,0x4e,0x9a,0xc1,0x86,0x17, +0x3b,0xc0,0x8f,0xed,0xd0,0x6e,0x19,0x7a,0xf6,0x21,0xc4,0xd4,0x10,0xbc,0xe1,0x5e, +0x82,0x38,0xb8,0xd4,0x0a,0x63,0x01,0xbb,0x1a,0xa0,0x8f,0xf8,0xdf,0xc5,0xd5,0xcd, +0xd0,0x4f,0x88,0xdd,0x0f,0x20,0xde,0x3f,0xbc,0x0d,0xed,0x81,0xfd,0x7a,0xa0,0xdd, +0xdb,0x9f,0xa0,0x59,0x58,0x73,0x67,0x6f,0x55,0xc0,0x5c,0xe8,0x40,0xcf,0xba,0xc0, +0xc7,0x37,0x20,0x6e,0x2a,0xe4,0xe8,0x99,0xb2,0x11,0xcd,0x75,0x83,0x1d,0x3e,0x97, +0xa3,0x39,0xc3,0x4d,0xb8,0x3e,0xb4,0xa3,0x85,0xb9,0x79,0xfb,0x32,0xc4,0x04,0xcc, +0x85,0x5e,0x88,0xeb,0x6b,0xe0,0xdf,0x3e,0x18,0xc3,0x47,0xe0,0x1f,0xfc,0x6f,0x37, +0xb8,0xff,0x99,0x3f,0x3f,0x0f,0xf1,0x21,0x47,0xe6,0x0f,0x21,0xb5,0x82,0x2f,0x1b, +0xfb,0x20,0x56,0x20,0xb6,0x0c,0x30,0xb7,0x2e,0x80,0x2f,0xdb,0x06,0x61,0x8e,0xc0, +0x7e,0x3b,0xf4,0xfb,0x72,0x15,0xd8,0xbb,0x1e,0xae,0x09,0x31,0xd6,0x00,0x31,0xfe, +0x29,0xcc,0x6f,0x39,0x24,0x15,0xcc,0xe7,0x4b,0x30,0xa7,0x2e,0x81,0x4d,0xdb,0xe0, +0x8d,0xfc,0x26,0xf8,0x00,0xde,0xb4,0x2c,0x1f,0xdd,0x02,0xbf,0x80,0x6d,0x55,0x57, +0xe0,0x1a,0x70,0x2d,0x98,0xc3,0xe6,0x0a,0xf0,0xab,0x11,0xaf,0x1b,0xf0,0x56,0x0f, +0xf3,0xd2,0xdc,0xd8,0x01,0xd7,0x85,0x6b,0x83,0x6d,0xcc,0x3d,0x30,0xcf,0x95,0xb5, +0x60,0x47,0xb0,0x53,0x19,0xd8,0xab,0xfc,0x06,0xc4,0x3c,0xac,0x1f,0x60,0xab,0x59, +0xb8,0x8f,0xce,0x5e,0x84,0xfe,0x9b,0x6e,0xa1,0xd9,0x7e,0x1c,0x73,0x60,0x3f,0x0d, +0xc4,0x8b,0x16,0x7c,0x53,0x0d,0xf9,0x8b,0x35,0xd0,0x47,0xf0,0x17,0xac,0x45,0xcf, +0xda,0xc1,0x76,0xed,0xd0,0xcf,0xcb,0x46,0x48,0xe0,0xef,0x4e,0xb0,0xcf,0x55,0x88, +0xfd,0xcf,0x60,0xdb,0x0f,0xc7,0x0c,0x40,0x7e,0xe8,0x06,0x9a,0x93,0xc3,0x5a,0x55, +0xde,0x0d,0xf3,0x01,0xfc,0x50,0xf3,0x21,0x9a,0x6b,0xab,0x46,0x73,0x97,0xeb,0xd1, +0x5c,0x17,0xcc,0xab,0x2e,0x28,0xeb,0x3d,0x8f,0xe6,0xfa,0x20,0x4e,0xef,0x40,0x9c, +0x5d,0x00,0x1f,0x7c,0xf2,0x05,0xc4,0x1a,0xc4,0x88,0xc2,0x84,0x16,0xda,0x2a,0xae, +0xa1,0x39,0x2d,0x18,0xbc,0xff,0x32,0x2c,0x3c,0x30,0x89,0xa0,0xd3,0x33,0x77,0x60, +0x20,0x1a,0x0d,0xec,0xc3,0xb6,0x02,0x8c,0x5f,0x01,0x4e,0xa8,0xab,0x83,0xc1,0x36, +0x82,0x81,0xc1,0xc1,0x17,0x7b,0x61,0xb1,0x54,0x43,0xaa,0x45,0xe6,0x4e,0xd8,0xef, +0x82,0x41,0x7f,0xfe,0x01,0x24,0xa8,0x1f,0x82,0x80,0xb9,0xd3,0x0d,0x81,0xdb,0x00, +0x06,0x80,0xc1,0xab,0x61,0x32,0x6b,0x5a,0x20,0xe0,0x60,0xb2,0xc1,0x0d,0x63,0xb6, +0xba,0x09,0xcd,0xd6,0x7c,0x00,0x06,0xa9,0x87,0xc5,0xef,0x02,0x04,0x14,0x6c,0x3f, +0x87,0xed,0xe7,0x10,0xf8,0x72,0x70,0x10,0xdc,0x6c,0x9f,0x69,0x4d,0xe8,0x99,0x1e, +0x16,0xa2,0x9a,0x1e,0xf4,0xac,0x16,0x82,0xac,0xf6,0x73,0xf4,0xac,0x01,0x82,0xa9, +0xe1,0x13,0x70,0x26,0x2c,0xc0,0xb0,0x88,0x3f,0x6b,0x06,0xa7,0x36,0x83,0x21,0x2e, +0xc1,0xc2,0x74,0x15,0x8e,0xeb,0x81,0x63,0x4c,0x50,0x37,0x08,0x4e,0x35,0x82,0x53, +0xf1,0x82,0xdf,0x0c,0x83,0x6f,0x07,0x23,0x5c,0x86,0x85,0xf3,0x2a,0x2c,0xe6,0x9f, +0x42,0xc0,0x7d,0x0a,0x86,0xba,0x06,0x8b,0xe0,0x20,0x38,0x5c,0x01,0x8b,0x68,0x59, +0x23,0xb2,0xe8,0xc0,0x30,0x8d,0xe0,0x74,0xb8,0x09,0x5b,0x5a,0x2a,0x90,0xa5,0xeb, +0x03,0xb4,0x70,0xb1,0x55,0x8f,0x45,0x8d,0x16,0x2e,0xc1,0x3d,0xea,0xdb,0x6b,0xcd, +0x68,0x46,0x0e,0x66,0x92,0x0f,0xa0,0x85,0x76,0x9d,0x0e,0xa4,0xb7,0x1a,0x2d,0x5c, +0x81,0xb0,0xb3,0x0c,0xa9,0x90,0xe5,0x4e,0x25,0xca,0xcc,0x44,0x99,0x3c,0x94,0x09, +0x4f,0xd1,0x78,0x03,0xdb,0x3c,0x11,0x9a,0xe8,0xc3,0x3f,0x65,0xea,0xc3,0x3f,0x81, +0xea,0xc3,0xbf,0x7a,0xba,0xb3,0xba,0xdb,0x8d,0xbe,0x6a,0xfc,0x8f,0x3e,0xf4,0xd5, +0x8d,0xff,0xb8,0x85,0xbe,0xba,0x88,0xbe,0xaa,0x45,0x5f,0x5d,0x40,0x5f,0x35,0xa1, +0xaf,0x9a,0xd1,0x57,0x1d,0xe8,0xab,0xab,0xe8,0xab,0xce,0xaf,0x14,0x58,0x94,0x20, +0xff,0x31,0x68,0xcd,0xc3,0x06,0xf6,0xaa,0xf1,0x19,0xd5,0xff,0xd1,0x8f,0x65,0x10, +0x7d,0x55,0x83,0xe5,0x03,0x2c,0xe7,0xb1,0xd4,0x62,0xa9,0xc3,0x52,0x8f,0xa5,0x01, +0x4b,0x23,0x96,0x8f,0xb0,0x5c,0xc0,0xd2,0x84,0xe5,0x63,0x2c,0x2d,0x58,0x5a,0xb1, +0x5c,0xc2,0xd2,0x86,0xe5,0x32,0x96,0x2b,0x58,0x3a,0xb0,0x74,0x62,0xb9,0xba,0xda, +0xe8,0x00,0xbe,0xda,0x17,0xb8,0x95,0x2f,0xf0,0xc1,0x20,0xd5,0xd0,0xe3,0xc9,0x1e, +0x34,0xf9,0x39,0x9a,0xbc,0x83,0xbe,0x96,0xa3,0xc9,0xdb,0x68,0xf2,0x0b,0x34,0x39, +0x80,0xbe,0x6e,0x43,0x5f,0x5f,0x46,0x5f,0xab,0xd1,0xd7,0x2a,0xf4,0x75,0x19,0xfa, +0xba,0x1c,0x7d,0x6d,0x44,0x5f,0x1b,0xd0,0xd7,0x95,0xe8,0x6b,0x2d,0xfa,0xba,0x01, +0x7d,0x5d,0x83,0xbe,0xee,0x44,0x5f,0x7f,0x86,0xbe,0xee,0x45,0x5f,0xf7,0xa0,0xaf, +0x6f,0xa3,0xaf,0x3f,0x47,0xdf,0xc8,0xd1,0x37,0x0a,0xf4,0xf5,0x1d,0xf4,0xcd,0x07, +0xe8,0x9b,0xf3,0xe8,0xeb,0x6e,0xf4,0x4d,0x39,0xfa,0xa6,0x0c,0x7d,0xa3,0x45,0xdf, +0x54,0xa0,0x6f,0x34,0xe8,0x1b,0x1d,0xfa,0xa6,0x1a,0x4d,0xea,0xd0,0xe3,0xcb,0x8f, +0xaf,0x80,0x7c,0x53,0x07,0x32,0xa9,0xc5,0xb9,0x72,0x2c,0x65,0x58,0xac,0xbb,0xd5, +0xb8,0x02,0x8e,0x36,0xe0,0x43,0xbb,0xb0,0x74,0xe3,0x12,0x0d,0x16,0x3d,0x7a,0xdc, +0x81,0xcb,0x3a,0x70,0x59,0xc7,0xe3,0x6b,0x20,0xb8,0xa2,0x03,0xb7,0xdb,0x81,0x6b, +0xaf,0xe2,0xda,0xab,0xb8,0xf6,0x2a,0xae,0xbd,0x8a,0x6b,0xaf,0xe2,0xda,0xab,0xb8, +0xf6,0x53,0x5c,0xfb,0x29,0x2e,0xfb,0x14,0x97,0x7d,0x8a,0xcb,0xba,0xf0,0xc1,0x5d, +0xb8,0xac,0x1b,0xd7,0x76,0xe3,0xdc,0x35,0x9c,0xbb,0x86,0x2b,0xae,0xe1,0xdd,0x5e, +0xbc,0xdb,0x8b,0x77,0x7b,0x71,0xa3,0xbd,0xb8,0xcc,0x84,0x77,0x4d,0x38,0x77,0x13, +0xd7,0xde,0xc4,0xbb,0x37,0x71,0xed,0x4d,0x5c,0x76,0x0b,0xef,0xde,0xc2,0xb9,0x7e, +0x2c,0x03,0xf8,0x90,0x01,0x9c,0xbb,0x8d,0x73,0xb7,0x21,0x37,0xa9,0x80,0x1c,0x48, +0x37,0x96,0x6b,0x20,0xd6,0x32,0xe8,0x15,0x88,0x1e,0x4d,0x2a,0x71,0x85,0x12,0x97, +0x29,0x71,0x99,0x12,0x97,0xa9,0xc0,0x70,0x20,0x5d,0x58,0xba,0xb1,0xc0,0x69,0xaa, +0x49,0x35,0x16,0x0d,0x16,0x1d,0x16,0x38,0x4e,0x8d,0x0f,0x51,0xe3,0x43,0xd4,0xf8, +0x10,0x35,0xae,0x55,0xe3,0x5a,0x35,0xae,0xd5,0xe0,0x5a,0x0d,0xae,0xd5,0xe0,0x5a, +0x0d,0xae,0xd5,0xe0,0x5a,0x0d,0xae,0x2d,0xc3,0xb5,0x65,0xb8,0xb6,0x0c,0xd7,0x96, +0xe1,0xda,0x32,0x5c,0x5b,0x86,0x6b,0xcb,0x71,0x6d,0x39,0x2e,0x2b,0xc7,0x65,0xe5, +0xb8,0x4c,0x8f,0xcb,0xf4,0xf8,0x0c,0x3d,0x3e,0x43,0x8f,0x6b,0xf5,0xb8,0x56,0x8f, +0xad,0x7b,0x7d,0xf2,0x3a,0x7a,0xdc,0x03,0x32,0xa9,0x03,0xf1,0x9a,0x34,0x4c,0xd6, +0x80,0x1a,0xad,0x5a,0x69,0xd5,0x2a,0xab,0x56,0x5b,0xb5,0x06,0x1f,0x7d,0xf9,0x71, +0x0f,0x96,0x1b,0xd8,0xdf,0x65,0xd8,0xcb,0x3d,0x58,0x6e,0x60,0x07,0x97,0x61,0xb7, +0xf6,0x60,0xb9,0x81,0x3d,0x5a,0x86,0x3d,0xda,0x83,0xe5,0x06,0x76,0x66,0x19,0x1e, +0xd2,0x15,0xdc,0xf3,0x1e,0x2c,0x37,0x70,0xa7,0xcb,0x70,0xb7,0x7a,0xb0,0xdc,0xc0, +0x3d,0xc2,0x51,0x86,0x9d,0x74,0x79,0xb2,0x1c,0xb7,0x57,0x8e,0x5b,0x29,0xc7,0xce, +0xb4,0xda,0xa9,0x1c,0x9f,0x51,0x8e,0xc7,0x75,0x1d,0x1f,0x5c,0x8e,0x1b,0x2d,0xc7, +0xfe,0x06,0xe9,0xc3,0xde,0xeb,0xc3,0xb5,0x72,0x6b,0xc7,0x61,0x53,0xb5,0xba,0xc1, +0x5d,0x07,0x5f,0xeb,0xb0,0xe8,0xb1,0x9b,0x75,0x58,0xf4,0xd8,0xcd,0x3a,0x2c,0x7a, +0xdc,0x82,0x0e,0x8b,0x1e,0xb7,0xa0,0xc3,0xa2,0xc7,0x81,0xa6,0xc3,0x82,0x23,0x10, +0xe7,0xba,0x70,0xee,0x1a,0xce,0x5d,0xc3,0x39,0x13,0xce,0x99,0x70,0xee,0x26,0xce, +0xdd,0xb4,0x9e,0x8b,0x63,0xa7,0x0f,0x47,0x56,0x1f,0x1e,0x43,0x1f,0x1e,0x7a,0x2f, +0x16,0x13,0x96,0x9b,0x58,0xae,0x4c,0x56,0x58,0xe7,0x80,0x35,0xec,0x57,0x03,0xfa, +0xea,0x6a,0x48,0x5f,0x5d,0x0d,0xe5,0xab,0x56,0xff,0x5b,0x37,0xdd,0xab,0x9b,0x6b, +0xd6,0xe8,0xc7,0x7b,0xdd,0xd6,0x10,0xb0,0x6e,0x74,0xd6,0x78,0x5f,0x0d,0xfb,0xae, +0xd5,0xc0,0xef,0x5a,0x1d,0x83,0xf5,0xc8,0xde,0xd5,0x56,0x7a,0xad,0xd1,0x83,0xa7, +0xc2,0xf7,0x93,0xc1,0x6a,0xa3,0xd5,0xeb,0xf5,0xad,0x8e,0xa8,0x6f,0xf5,0x0a,0x7d, +0xab,0x75,0x37,0x57,0x47,0x7d,0x73,0xb5,0x2f,0xb7,0x56,0x1b,0xbb,0xb5,0x5a,0x77, +0x6b,0xf5,0xea,0x03,0xab,0x9d,0x1f,0x58,0x2d,0x1c,0x58,0xed,0xcb,0xed,0xd5,0xbd, +0xdb,0xab,0x87,0xdc,0x5e,0x8d,0x57,0x85,0xb5,0x15,0x3c,0x49,0xbe,0x9f,0x2b,0xd6, +0x38,0xb7,0x5e,0xdd,0xba,0xd1,0xaf,0x6e,0x74,0xd6,0x09,0xb1,0x3a,0x25,0xae,0xad, +0x4e,0x85,0xef,0xa3,0xbf,0xfb,0xfb,0x99,0x60,0x9d,0x01,0xab,0x27,0x68,0xac,0xa3, +0xc5,0x9b,0xd5,0xc2,0x6b,0xab,0x87,0x5c,0x5b,0xdd,0xeb,0xc2,0x61,0x52,0xbe,0x3a, +0x83,0xca,0x57,0xaf,0x57,0xb6,0x7a,0x7a,0xd9,0xea,0x85,0xca,0x56,0xcf,0x2b,0xb3, +0x1a,0x0b,0x4f,0x1e,0xeb,0x94,0x5a,0xed,0xae,0x7e,0x75,0x0c,0x1d,0xab,0xfe,0xbd, +0xba,0x6a,0x9e,0xab,0xab,0x66,0xbd,0xfa,0x43,0xe1,0xb5,0xd5,0xa5,0xca,0x3a,0xcc, +0xab,0xab,0x63,0xef,0x5a,0xdd,0xeb,0x5a,0x35,0x5d,0xd7,0x0f,0xce,0xb1,0x1e,0x69, +0x5a,0x0d,0xa0,0xbe,0xd5,0xcd,0xcd,0x1f,0x06,0xdd,0x65,0xdd,0xac,0x5e,0x5d,0xbf, +0x5a,0xa8,0x5f,0x2d,0xd4,0xaf,0x16,0x6a,0x56,0x37,0xca,0x1f,0xe6,0x7c,0xf7,0x6a, +0xe0,0x5a,0xf7,0x54,0x3f,0x2e,0x04,0xdf,0xaf,0x11,0x3f,0xb4,0xa9,0x59,0xad,0xd3, +0xac,0xf6,0x45,0x6f,0x5d,0x2f,0xbf,0xb7,0x19,0xde,0x28,0x56,0xfb,0xd9,0xb1,0x5a, +0xd7,0xbb,0x7a,0x5e,0xd9,0xea,0x30,0x4d,0x93,0x6a,0xb8,0x2f,0xc0,0xf5,0xf0,0x06, +0x82,0x54,0x6d,0x9d,0x6c,0x90,0x51,0x59,0xa7,0xf7,0xaa,0x13,0x1e,0x7f,0x66,0x3d, +0x70,0x75,0x9d,0xec,0x81,0xe0,0xd2,0xc2,0xda,0x06,0x7b,0x6a,0xeb,0x54,0x9c,0xd4, +0x42,0x89,0xda,0x1a,0x6e,0xd6,0xc5,0x6c,0x75,0xe3,0xf5,0x43,0x63,0x5e,0x3f,0x1c, +0xe8,0xf5,0xff,0x1f,0xd8,0x35,0xa9,0xf6,0xc2,0x62,0x3d,0x06,0x2e,0xd7,0xf3,0x8d, +0x01,0x67,0x91,0x1f,0xfa,0x56,0xae,0x40,0x41,0xc8,0x1b,0xbd,0x0b,0xb9,0x7a,0x48, +0x1f,0xa2,0xdf,0xcb,0xf1,0x8f,0xac,0xce,0xa3,0x53,0xa8,0x18,0xc9,0xa0,0xa4,0x16, +0x12,0x3c,0x38,0xc8,0xab,0x21,0xd5,0x40,0xd2,0x43,0xaa,0x80,0x64,0x80,0x64,0x84, +0x54,0x09,0xa9,0x0a,0x9d,0x40,0xa9,0x68,0x17,0xda,0x8d,0xf6,0x21,0x32,0x62,0xa2, +0x77,0x50,0x0a,0xf2,0x41,0x24,0x74,0x00,0x56,0xb2,0x0a,0xbc,0x32,0x54,0xe0,0x05, +0x0f,0x2f,0x77,0x78,0xb1,0xb3,0x2e,0x1c,0x78,0xbd,0xb3,0x2e,0x1d,0x78,0xc9,0xb3, +0x2e,0x1e,0x78,0xd5,0xc3,0x19,0xbc,0xfc,0x7d,0x80,0x33,0x60,0xa0,0x56,0xf4,0xf8, +0x22,0x7a,0x7c,0x09,0x3d,0x6e,0x43,0x8f,0xdb,0x61,0xb1,0x42,0xf8,0x8e,0xd9,0x81, +0x1e,0x77,0x42,0x50,0xc0,0x9a,0x84,0xac,0xf7,0x29,0x84,0xe7,0x15,0x98,0x0c,0xaf, +0xaf,0x08,0x2f,0x80,0xbd,0x10,0x08,0x60,0x16,0x88,0x03,0x98,0x4c,0x70,0xe3,0x01, +0xdb,0xc1,0x5c,0x01,0xc7,0x80,0xe1,0xc1,0x75,0x08,0xdf,0x29,0x70,0x70,0x22,0xab, +0x35,0xd1,0xaa,0x5b,0x2f,0x62,0xb9,0x84,0xa5,0x1d,0xcb,0x15,0xb4,0x13,0xed,0x41, +0x01,0xe8,0x24,0x92,0xa2,0x12,0xf4,0xfb,0xcb,0x1a,0x48,0xf8,0xfb,0x1d,0xfc,0xbd, +0x0f,0xfe,0x5a,0xe5,0x12,0xa4,0x76,0x48,0x57,0x20,0xe1,0x7f,0xeb,0xc2,0xbe,0x0a, +0xf6,0xe1,0xd9,0xfa,0x5b,0x95,0x0a,0xad,0xfe,0x83,0x17,0x7f,0xbd,0xd0,0x88,0xf0, +0xd7,0xe4,0xff,0x76,0x11,0xfd,0xdb,0x25,0xf4,0x6f,0x5d,0xe8,0xdf,0x2e,0xa3,0x7f, +0x6b,0x47,0xbf,0x87,0x53,0x7e,0x5f,0xab,0x44,0xbf,0x87,0xd7,0xb6,0xdf,0x97,0xd5, +0x40,0xfa,0x00,0xd2,0x79,0xf4,0xfb,0xfa,0x16,0xf4,0xfb,0x0f,0x2b,0xd0,0x42,0x75, +0x75,0x07,0x96,0x4e,0x2c,0x57,0xb1,0x7c,0x8a,0xa5,0x0b,0x4b,0x37,0x96,0x6b,0x58, +0x3e,0xc3,0x72,0x1d,0x4b,0x0f,0x96,0x1b,0x58,0x7a,0xb1,0xf4,0x61,0x31,0x61,0xb9, +0x89,0xe5,0x16,0x96,0x7e,0x2c,0x03,0x58,0x6e,0x63,0xf9,0x1c,0xcb,0x20,0x96,0x21, +0x2c,0x77,0xb0,0x7c,0x01,0x52,0x23,0xc7,0xa2,0xc0,0xa2,0xc4,0xa2,0xc2,0xa2,0xc6, +0xa2,0xc1,0x52,0x86,0xa5,0x1c,0x8b,0x16,0x8b,0x0e,0x8b,0x1e,0x0b,0xee,0x73,0x8d, +0x01,0x8b,0x11,0x4b,0x25,0x96,0x2a,0x90,0xf3,0x0d,0x58,0x1a,0xb1,0x7c,0x84,0xe5, +0x02,0x96,0x26,0x2c,0xcd,0x58,0x3e,0xc6,0xf2,0x09,0x96,0x16,0x2c,0xad,0x58,0x2e, +0x62,0xb9,0x84,0xa5,0x0d,0x4b,0x3b,0x96,0xcb,0x58,0xae,0x60,0xc1,0x76,0x39,0x8f, +0xed,0x72,0x1e,0xdb,0xe5,0x3c,0xb6,0xcb,0x79,0x6c,0x97,0xf3,0xd8,0x2e,0xe7,0xb1, +0x5d,0xce,0x63,0xbb,0x9c,0xc7,0x76,0x39,0x8f,0xed,0x72,0x1e,0xdb,0xe5,0x3c,0xb6, +0xcb,0x79,0x6c,0x97,0xf3,0xd8,0x2e,0xe7,0xb1,0x5d,0xce,0x63,0xbb,0x9c,0xc7,0x76, +0x39,0x8f,0xed,0x72,0x1e,0xdb,0xe5,0x3c,0xb6,0x4b,0xfd,0x87,0x58,0x70,0xc7,0xeb, +0x71,0xc7,0xeb,0x71,0xc7,0xeb,0x71,0xc7,0xeb,0x71,0xc7,0xeb,0x71,0xc7,0xeb,0x71, +0xc7,0xeb,0x71,0xc7,0xeb,0x71,0xc7,0xeb,0x71,0xc7,0xeb,0x71,0x9f,0xeb,0x71,0x9f, +0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb, +0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71, +0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x9f,0xeb,0x71,0x77,0xeb,0x71,0x77,0xeb,0x71,0x77, +0xeb,0x71,0x77,0xeb,0x71,0x77,0xeb,0x71,0x77,0xeb,0x71,0x77,0xeb,0xad,0x3d,0x1d, +0x44,0xff,0xa7,0x1a,0xfd,0x9f,0x1a,0xf4,0x65,0x23,0xfa,0xf2,0x12,0xfa,0xcf,0xee, +0xcb,0xe8,0xcb,0x76,0xf4,0x65,0x1b,0x9a,0xbe,0x59,0x83,0x46,0x1b,0xd0,0xe8,0xc7, +0xe8,0xcb,0x4e,0x34,0x7a,0x11,0x7d,0x79,0x01,0x7d,0xd9,0x84,0x46,0xaf,0xa0,0x2f, +0xd5,0xe8,0xcb,0xab,0xe8,0x4b,0xe8,0x42,0xf3,0xa0,0x1a,0xfd,0xe7,0xc7,0x95,0x68, +0xf4,0x1a,0xce,0x6b,0xd0,0x97,0x95,0x78,0x5b,0x86,0x46,0x6f,0xa2,0xd1,0xdb,0x38, +0xab,0x45,0xa3,0x77,0xd0,0x97,0x1d,0xe8,0xcb,0xcb,0xd0,0x30,0x9c,0x79,0x05,0xfd, +0xbe,0xa7,0x07,0x7d,0x59,0x85,0xbe,0x6c,0x45,0x5f,0x42,0x93,0x0d,0xe8,0xdf,0xe5, +0xe8,0xdf,0x15,0xe8,0xdf,0x95,0xf8,0x68,0x3d,0x16,0xb8,0x5c,0x3d,0xfa,0xf2,0x43, +0x9c,0xc5,0x01,0xd1,0x8b,0x83,0xa9,0x17,0x07,0x53,0x2f,0x0e,0xa6,0x5e,0x1c,0x4c, +0xbd,0x38,0x98,0x7a,0x71,0x30,0xf5,0xe2,0x60,0xea,0xc5,0xc1,0xd4,0x8b,0x83,0xa9, +0x17,0x07,0x53,0x2f,0x0e,0xa6,0x5e,0xeb,0xb9,0x38,0x98,0x7a,0x71,0x30,0xf5,0xe2, +0x60,0xea,0xc5,0xc1,0x84,0x5f,0x55,0xaa,0x7b,0x6b,0xb0,0x7c,0x80,0xe5,0x3c,0x96, +0x5a,0x2c,0x75,0x58,0xea,0xb1,0x60,0xdf,0xf5,0x62,0xdf,0xf5,0x62,0xdf,0xf5,0x62, +0xdf,0xf5,0x62,0xdf,0xf5,0x62,0xdf,0xf5,0x62,0xdf,0xf5,0x62,0xdf,0xf5,0x62,0xdf, +0xf5,0x62,0xdf,0xf5,0x62,0xdf,0xf5,0xe2,0xa0,0xeb,0xc5,0x0e,0xec,0xc5,0x0e,0xec, +0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5, +0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x0e, +0xec,0xc5,0x0e,0xec,0xc5,0x0e,0xec,0xc5,0x41,0x67,0xc2,0xbb,0x26,0xbc,0x6b,0xb2, +0xee,0x62,0xa7,0x9a,0xb0,0x53,0x4d,0xd8,0xa9,0x26,0xec,0x54,0x13,0x76,0xaa,0x09, +0x3b,0xd5,0x84,0x9d,0x6a,0xc2,0x31,0x68,0xc2,0x9e,0x35,0xe1,0xb9,0x69,0xc2,0x73, +0xd3,0x84,0xe7,0xa6,0x09,0xcf,0xcd,0x9b,0xd8,0x9c,0x37,0xb1,0x39,0x6f,0x62,0x73, +0xde,0xc4,0xe6,0xbc,0x89,0xcd,0x79,0x13,0xcc,0x59,0x73,0x49,0x8e,0x45,0x81,0x45, +0x89,0x45,0x85,0x45,0x8d,0xc5,0x5a,0x5b,0x86,0xa5,0x1c,0x8b,0x16,0x8b,0x0e,0x8b, +0x1e,0x4b,0x05,0x16,0x03,0x16,0x23,0x96,0x4a,0x2c,0x55,0x58,0xaa,0xb1,0xd4,0x60, +0xf9,0x00,0xcb,0x79,0x2c,0xb5,0x58,0xea,0xb0,0xd4,0x63,0xf9,0x10,0x4b,0x03,0x96, +0x46,0x2c,0x1f,0x61,0xb9,0x80,0xa5,0x09,0x4b,0x33,0x96,0x8f,0xb1,0x80,0xb1,0xeb, +0x07,0x5a,0xb0,0xb4,0x62,0xb9,0x88,0xe5,0x12,0x96,0x36,0x2c,0xed,0x58,0x2e,0x63, +0xb9,0x82,0xa5,0x03,0x4b,0x27,0x96,0xab,0x58,0x3e,0xc5,0xd2,0x85,0xa5,0x1b,0xcb, +0x35,0x2c,0x9f,0x61,0xb9,0x8e,0xa5,0x07,0xcb,0x0d,0x2c,0xbd,0x58,0xfa,0xb0,0x98, +0xb0,0xdc,0xc4,0x72,0x0b,0x4b,0x3f,0x96,0x01,0x2c,0xb7,0xb1,0x7c,0x8e,0x65,0x10, +0xcb,0x10,0x96,0x3b,0x58,0xc0,0xba,0xf5,0xb7,0x71,0xc5,0x6d,0x5c,0x71,0x1b,0x57, +0xdc,0xc6,0x15,0xb7,0x71,0xc5,0xe7,0x72,0x2c,0x0a,0x2c,0x4a,0x2c,0x2a,0x2c,0x6a, +0x2c,0x1a,0x2c,0x65,0x58,0xca,0xb1,0x68,0xb1,0xe8,0xb0,0xe8,0xb1,0x54,0x60,0x31, +0x60,0x31,0x62,0xa9,0xc4,0x52,0x85,0xa5,0x1a,0x4b,0x0d,0x96,0x0f,0xb0,0x9c,0x47, +0xdf,0x2a,0xce,0x7f,0xab,0xe8,0xb0,0x7e,0xf5,0x8b,0x7f,0x73,0x80,0xbf,0x30,0xc4, +0xb7,0x9a,0x0e,0xfc,0x9d,0xe4,0x42,0xb3,0xe6,0x43,0x48,0xed,0x38,0xd3,0xf0,0x07, +0x19,0x48,0xd7,0x7e,0xba,0xf3,0xd9,0x4f,0x77,0xae,0xff,0x74,0xa7,0xe7,0xa7,0x3b, +0x60,0xac,0xe6,0xb2,0x81,0xef,0x5b,0x2a,0xbb,0xfd,0x43,0x66,0xe0,0x27,0x4d,0xae, +0x96,0xfe,0xb0,0x33,0xf0,0x93,0xf6,0x7f,0xac,0xf9,0x0c,0xdd,0xeb,0x41,0xf7,0x6f, +0xa1,0xbc,0x3c,0xf4,0x7b,0x6d,0x39,0x24,0xbc,0x08,0x0c,0x29,0xb0,0xe8,0xb0,0x54, +0x60,0xc1,0x2b,0xca,0xd0,0x07,0x58,0x3a,0xb1,0xe0,0x45,0x67,0xa8,0x1b,0x0b,0x6e, +0x6a,0xa8,0x17,0x8b,0x09,0xcb,0x2d,0x2c,0x03,0x58,0x3e,0xc7,0x32,0x84,0xe5,0x0b, +0x2c,0x78,0x25,0x19,0x6a,0xc0,0xd2,0x88,0xa6,0xfb,0xac,0x99,0x6a,0xbc,0xb8,0xdc, +0x41,0xd3,0x78,0x46,0x34,0x0f,0x7e,0x81,0xee,0xf7,0xa3,0xfb,0xf8,0xd4,0x41,0xeb, +0x92,0x06,0xcb,0x60,0x19,0x2c,0x7e,0xf8,0xc8,0xc1,0x2e,0x2c,0x4d,0xe8,0xcb,0xf3, +0x50,0xf0,0x11,0x9c,0xae,0x81,0x24,0x87,0x54,0x8e,0x46,0xbf,0x40,0x5f,0xc2,0x82, +0x77,0x0d,0x7d,0xf9,0x19,0xba,0xdf,0x8a,0xee,0xf7,0xa1,0xfb,0x26,0x74,0xff,0x26, +0x1c,0x87,0xbf,0x5d,0xa9,0x83,0x6d,0x39,0x24,0x3d,0xfa,0xb2,0x05,0x37,0x01,0xe3, +0xf9,0xb8,0xed,0x22,0x96,0x4b,0x58,0xda,0xb0,0xb4,0x63,0xb9,0x8c,0xe5,0x0a,0x96, +0x0e,0x2c,0x9d,0x58,0xae,0x62,0xf9,0x14,0x4b,0x17,0x96,0x6e,0x2c,0xd7,0xb0,0x7c, +0x86,0xe5,0x3a,0x96,0x1e,0x2c,0x37,0xb0,0xf4,0x62,0xe9,0xc3,0x62,0xc2,0x72,0x13, +0xcb,0x2d,0x2c,0xfd,0x58,0x06,0xb0,0xdc,0xc6,0xf2,0x39,0x96,0x41,0x2c,0x43,0x58, +0xee,0x60,0x81,0xe1,0x7f,0xdc,0x2e,0xc7,0xa2,0xc0,0xa2,0xc4,0x02,0x4f,0x36,0xd7, +0xd0,0xd7,0xad,0x68,0xf2,0x33,0x44,0xf1,0x43,0x54,0x3f,0xf4,0x3b,0x3f,0xf4,0xa6, +0x1f,0xa2,0xf9,0x21,0xba,0x1f,0x7a,0xcb,0x0f,0xbd,0xed,0x87,0x02,0xfd,0x10,0x03, +0x3f,0xf5,0xd5,0xe6,0xe1,0xa7,0xba,0x82,0x22,0xc4,0xcd,0x47,0x79,0xe9,0x28,0x27, +0x27,0x1f,0x15,0xbc,0x8f,0x04,0xf0,0x97,0x8e,0x04,0xb9,0x28,0x3d,0x0b,0x82,0xf2, +0xf3,0x6f,0x15,0x15,0xd6,0xdf,0x3b,0x28,0xf1,0xef,0x57,0x3f,0x44,0xe6,0x2a,0xfc, +0x83,0x96,0x72,0x64,0x6e,0xfb,0x08,0xcd,0x5d,0xb9,0x84,0x66,0x6e,0xb7,0xa1,0xd9, +0x86,0x16,0xf4,0x4c,0xdd,0x8a,0xcc,0x3a,0x23,0x32,0xdf,0x31,0x20,0x73,0x99,0x11, +0xcd,0xc2,0x8d,0xcc,0xac,0x6d,0x46,0xcf,0x4c,0x4a,0x34,0x77,0xa3,0x13,0x99,0x2f, +0xc1,0x3e,0x3c,0x7b,0xcc,0x0e,0xd6,0xa2,0x59,0x7d,0x1d,0x9a,0x35,0xd6,0x21,0x8b, +0x42,0x8f,0x66,0x0d,0xe5,0x68,0x56,0x77,0x1e,0x3d,0xbb,0xac,0x40,0xcf,0x3a,0xf1, +0x3f,0x5a,0xb5,0x68,0xf6,0xb6,0x1c,0x3d,0xab,0x85,0xeb,0xe9,0x6e,0x20,0x33,0xdc, +0xf7,0x2c,0x1a,0xfc,0x8c,0x59,0x3b,0xdb,0xd4,0xb5,0xfa,0x14,0x5a,0x3b,0xd3,0xaf, +0xfb,0x21,0x77,0xdb,0xf0,0x7d,0xce,0x7c,0xed,0x87,0xb2,0x67,0xca,0x81,0xef,0x73, +0xd0,0xf0,0x0f,0x65,0x17,0x3e,0xfc,0xe1,0xb8,0x8a,0xe6,0x1f,0x6a,0xeb,0xac,0x65, +0xe6,0x3b,0x78,0x54,0x9f,0xa1,0x99,0xfe,0x21,0x48,0xfd,0x68,0x66,0x00,0x8c,0xd9, +0xa2,0xbe,0x88,0x66,0x86,0x5a,0xd0,0xcc,0x9d,0xcf,0x91,0x59,0xae,0x44,0x66,0x05, +0x74,0x0d,0x9e,0xe3,0xcc,0xf8,0xf7,0x04,0x1f,0xc0,0x7a,0xd6,0xd2,0x00,0x05,0x1a, +0xfc,0x73,0xa9,0x36,0x48,0xe0,0xb0,0x96,0xda,0x26,0xa8,0x19,0x80,0x1d,0x88,0x86, +0x96,0xba,0x0a,0xb0,0x02,0xb4,0x5b,0xd6,0x86,0x66,0x3e,0xc7,0x16,0x81,0x48,0xe8, +0x2c,0xff,0x04,0x4c,0x02,0xcf,0x85,0xe7,0xf1,0x16,0xda,0xd5,0x95,0x41,0xba,0x85, +0xbe,0xad,0xc5,0x3f,0x2f,0xd6,0x40,0x82,0x7d,0xa3,0x0e,0xd2,0x47,0x90,0x60,0xf8, +0xc6,0x21,0x48,0xe0,0xe3,0x96,0x8e,0x2e,0xf4,0x4c,0x01,0xf6,0xab,0xd2,0x43,0x82, +0x75,0xb4,0x05,0xff,0xa6,0xaa,0xea,0x53,0x48,0x3d,0x60,0x30,0x38,0x0b,0x7a,0x64, +0x86,0xa7,0x3b,0x33,0x3c,0x91,0x99,0x6b,0x3a,0x60,0xff,0x22,0x32,0xc3,0xf3,0x8d, +0xb9,0xb6,0x1a,0x99,0xeb,0xce,0x43,0x82,0xe3,0xeb,0xd5,0x90,0xe0,0x1c,0x78,0xae, +0x30,0x7f,0x08,0x23,0x6a,0xaa,0x87,0x04,0x5d,0x6c,0xac,0x81,0xd4,0x07,0x0e,0xba, +0x86,0xcc,0x9f,0x54,0x42,0x82,0x7c,0x0b,0x38,0xf2,0x63,0x18,0x42,0x0b,0x38,0xa0, +0x05,0xae,0x71,0x11,0xba,0xdf,0x0a,0x8f,0x62,0xe6,0x4b,0x50,0x70,0xe9,0x16,0x78, +0x1f,0x2e,0x0a,0xf3,0xc1,0xdc,0x0e,0x73,0xa2,0xf5,0x23,0x08,0xfd,0xd6,0x0b,0x57, +0x91,0xf9,0x4a,0x17,0x32,0x77,0x5c,0x80,0x74,0x05,0xf2,0x0d,0xc8,0xdc,0x79,0x19, +0x7d,0x7b,0xe1,0x1a,0xa4,0x41,0x64,0xee,0x82,0xae,0x75,0x41,0xd4,0xb6,0x5e,0x81, +0xcc,0x67,0x2a,0x48,0x70,0xc0,0x67,0x10,0xfd,0xad,0x5d,0x38,0xf3,0x05,0x32,0x5f, +0x87,0x36,0x87,0x60,0x21,0xfc,0x58,0x81,0xcc,0x3d,0x2d,0xc8,0x0c,0x4f,0x0e,0xe6, +0x1b,0xb0,0x6c,0xb6,0xde,0x82,0x0b,0x9b,0x54,0x38,0x73,0x19,0x32,0xd0,0x4d,0x13, +0x0c,0x03,0x6e,0x8e,0xe6,0x5b,0x10,0x73,0xb7,0x2e,0xa2,0x6f,0x5b,0x3e,0x83,0x2d, +0x18,0xab,0x1f,0x86,0x0e,0x5e,0x34,0xc3,0x9d,0xe3,0xdb,0x56,0xe8,0xd9,0xc5,0x32, +0xb0,0x76,0x2b,0x1c,0x78,0x1b,0x8c,0x77,0x1b,0xc6,0x7d,0x1b,0xa6,0xd7,0xd5,0x4a, +0xfc,0x1f,0x51,0x43,0x0f,0x9a,0xd3,0xc2,0x85,0x06,0xe1,0x74,0x7c,0x4b,0xbc,0xa4, +0x87,0xf9,0x76,0xb9,0x1c,0x2c,0x8f,0xbf,0x4d,0x81,0x65,0xea,0xdb,0x4b,0x60,0xb3, +0x3b,0xb0,0xff,0x05,0xd8,0xe2,0x0b,0xb0,0xd3,0x17,0x10,0xbc,0x4a,0x05,0xfa,0x16, +0xa6,0xe3,0xb7,0x6d,0x70,0x6f,0xbb,0x78,0x01,0x22,0x19,0x66,0xc2,0xac,0x06,0xff, +0x57,0xd8,0x00,0xe9,0x36,0x9a,0x2d,0xbb,0x01,0x09,0x66,0x44,0xd9,0x67,0x68,0xb6, +0x1c,0x7f,0x35,0x81,0xbf,0x92,0xb9,0x00,0x11,0xde,0x0c,0x51,0xdf,0x83,0x66,0x2b, +0xe0,0x1c,0x23,0x2c,0x5f,0x17,0xbb,0xe0,0x04,0xc3,0x10,0x14,0x0c,0x42,0x41,0x07, +0x9a,0xad,0x54,0xa1,0xd9,0x2a,0x58,0x56,0x2e,0x7e,0x06,0x47,0x55,0x5f,0x84,0x1d, +0x0d,0x14,0xc2,0x38,0x3a,0xae,0xa1,0xd9,0x9a,0x4e,0x48,0x77,0xd0,0xec,0x07,0xd0, +0x4a,0x0d,0x04,0x4c,0x67,0x17,0x9a,0xad,0x03,0x97,0x5c,0x82,0x17,0xb1,0xd9,0x0f, +0x2f,0xa1,0xd9,0x0b,0xfd,0x68,0xb6,0x51,0x87,0xbe,0xed,0x82,0x37,0x0d,0x30,0xf4, +0xb7,0x9f,0x82,0xc5,0xe0,0x75,0xc2,0x5c,0x06,0x13,0xad,0x49,0x8e,0x66,0x3f,0x6a, +0x42,0x73,0x70,0x57,0x99,0xa9,0x6a,0x84,0xfd,0x56,0x34,0xdb,0x0c,0x5d,0x6b,0x3e, +0x8f,0xff,0x1d,0x0c,0x06,0xea,0xd6,0xa1,0xd9,0x4f,0xa0,0xef,0x1f,0xc3,0x15,0x5b, +0xc1,0x36,0x97,0x6a,0xba,0xd1,0xec,0xc5,0x4a,0x34,0xdb,0xf2,0x09,0x9a,0x6d,0x83, +0x0e,0xc3,0xc2,0x32,0x7b,0x19,0xae,0x72,0xe5,0x2a,0x9a,0xbd,0x0a,0xbe,0xbe,0xf4, +0x11,0xec,0x7c,0x7a,0x01,0x7d,0x7b,0xbd,0x01,0xcd,0x76,0xc1,0xdd,0xfc,0xd2,0xc5, +0x2b,0x68,0xb6,0x1b,0x5e,0x12,0x7b,0xe0,0xac,0x6e,0x30,0xc1,0x35,0x38,0xf3,0x1a, +0xac,0x58,0x97,0xae,0x62,0xff,0xf5,0xc1,0x8d,0xe0,0xd2,0xa7,0x70,0x05,0xa8,0x5e, +0xb8,0x74,0x03,0x46,0x7c,0xe3,0x0b,0x34,0x0b,0xcf,0x75,0xb3,0x3d,0x70,0x5e,0x5f, +0x3d,0x24,0x18,0x9c,0x09,0x06,0x09,0x4f,0x41,0xb3,0xf8,0x41,0xe6,0x12,0xfe,0x4a, +0xa4,0xaf,0x0f,0xcd,0xf6,0x83,0x1d,0xe1,0x76,0xff,0x6d,0x5f,0x2f,0x9a,0xc5,0x37, +0xd8,0x4b,0x70,0xcf,0x9c,0xbd,0x05,0x9e,0x18,0x82,0x05,0xf5,0xd2,0x10,0x4c,0xc4, +0x4b,0x77,0xe0,0x9a,0x5f,0x94,0xa1,0x67,0xf2,0x01,0x48,0xd0,0xa9,0x9b,0xf5,0x30, +0x59,0xf4,0x90,0x86,0x20,0xdd,0x42,0xcf,0x60,0xdc,0x30,0x39,0xdb,0xd1,0x33,0x0d, +0x34,0xdc,0xa6,0xbb,0x84,0x9e,0x95,0x81,0xf7,0xda,0x2a,0xf1,0xef,0xd9,0x3b,0xd0, +0x33,0x1d,0x78,0xa3,0xad,0x41,0x8b,0x9e,0xe9,0x61,0xd1,0x81,0x85,0x69,0xa1,0xad, +0x09,0x7f,0x95,0xd0,0x52,0x8b,0x9e,0x19,0x6f,0xa3,0x67,0x95,0xb0,0xfa,0xdd,0xc6, +0x3f,0x6d,0x87,0xf7,0xba,0xdb,0xfd,0xe8,0x19,0xbc,0xf8,0x3c,0xab,0x69,0x42,0xcf, +0x3e,0xd0,0xa0,0x67,0xe7,0xe1,0x35,0x78,0xf0,0x02,0x2c,0x55,0xe0,0xb7,0xb6,0xeb, +0x37,0x21,0x03,0xf1,0xdd,0x76,0x03,0x87,0x57,0xd9,0x27,0xe8,0x59,0x03,0x6e,0xf9, +0x4e,0x2b,0x16,0x88,0xad,0x76,0x85,0x1a,0x7d,0xfb,0xc5,0x20,0x9a,0x91,0xc3,0x23, +0x42,0x3b,0xbc,0x16,0x82,0xc0,0x0d,0xa0,0x5d,0xdd,0x88,0xa5,0x17,0x3d,0x6b,0xc2, +0xdf,0x1e,0xc2,0x69,0x30,0xef,0x66,0x14,0x65,0x68,0x46,0x09,0x4f,0x57,0xed,0xf8, +0x6b,0xa7,0xd6,0x4a,0x34,0x03,0xaf,0x96,0x0b,0xed,0x0d,0x70,0xb3,0x69,0xff,0x08, +0x1e,0xb0,0xda,0x2f,0xc0,0xd5,0xaf,0x7c,0x8a,0x66,0xd4,0x9f,0xc1,0xa2,0x09,0x63, +0xed,0x84,0x67,0x8a,0xf6,0x76,0xb8,0x3b,0xb4,0x5f,0xbd,0x82,0x9e,0x7d,0x7a,0x0d, +0xcd,0xe0,0x7b,0x71,0xfb,0x35,0x18,0xe3,0x67,0x60,0x9a,0xcf,0x74,0x50,0x00,0xcb, +0x52,0xfb,0x0d,0x18,0x23,0x3c,0x36,0xcf,0xe8,0x61,0xc1,0x86,0x07,0xda,0x67,0xf0, +0xb4,0xfb,0x0c,0xee,0x87,0x0b,0xed,0x77,0xe0,0x28,0x13,0xac,0xe6,0x06,0x58,0x85, +0x6f,0xc1,0x10,0xfb,0x95,0xe8,0xd9,0x80,0x06,0xf6,0xe1,0xce,0x74,0x19,0xcc,0xb4, +0x70,0x59,0x57,0x8e,0x66,0x8c,0xd0,0xd7,0xcb,0x15,0x8d,0xe8,0xd9,0x10,0xdc,0x92, +0x2e,0x1b,0xee,0xa0,0x67,0x77,0xea,0xd0,0xb3,0x2f,0xf0,0x0e,0x7e,0xb3,0xbb,0x5c, +0x7b,0x09,0xcd,0x29,0xe0,0x7e,0x79,0x19,0xde,0x76,0xe6,0x60,0xc1,0x5a,0xb8,0x64, +0xfc,0x04,0x82,0xae,0x0e,0x82,0xef,0x06,0x9a,0x53,0xab,0xd0,0x4c,0x75,0x05,0x6c, +0xef,0x20,0xf3,0x55,0xb0,0xf1,0xe5,0x8f,0xaf,0x60,0x81,0xdc,0xa5,0x4a,0x1c,0x8b, +0x95,0x10,0xa4,0x5a,0x35,0x9a,0xbb,0xf3,0x31,0x9a,0xa9,0xf9,0x14,0xcd,0xe9,0x6b, +0x20,0xc1,0xf1,0x7a,0xfc,0x63,0xd3,0x5e,0xd8,0xc2,0x94,0xb5,0x6e,0x87,0xd0,0x5c, +0x05,0x98,0xe2,0x72,0xd7,0x20,0x9a,0x33,0x34,0xa3,0x39,0x23,0x5c,0xb6,0xb2,0x1b, +0xf2,0x78,0x0b,0x95,0x55,0x57,0xa0,0xec,0x3c,0x6c,0xf5,0x90,0x0c,0x90,0xc0,0xdf, +0x97,0xc1,0x3f,0x0b,0x97,0x61,0xe1,0x58,0xb8,0x0c,0x2f,0x0a,0x33,0xb5,0xd0,0x3e, +0xbc,0x19,0xce,0xc1,0x3b,0xe1,0x5c,0x2d,0x18,0xfa,0x0a,0x3e,0xb6,0x0e,0xfc,0x78, +0x19,0x1e,0x19,0x66,0xea,0x9a,0x21,0x81,0xe3,0x2e,0xdf,0x81,0xfb,0xf4,0x15,0x15, +0x18,0xac,0x0e,0x8e,0x6f,0xac,0x86,0x04,0x4d,0x37,0x76,0xa2,0xb9,0x8f,0x70,0xd2, +0xa2,0xb9,0xa6,0x4a,0x34,0x77,0xe1,0x22,0x6c,0x61,0xc0,0xcd,0x70,0xcc,0xc7,0xe0, +0xb8,0x0f,0x3f,0x44,0x73,0x9f,0xb4,0xa2,0xb9,0x16,0x05,0xe4,0x07,0xd0,0x5c,0x2b, +0x58,0xe4,0x0a,0x3e,0x11,0x1e,0x95,0xe7,0xe0,0x59,0x78,0xa6,0xc1,0x04,0x5b,0x58, +0x45,0x3e,0x80,0x19,0x72,0xe5,0x22,0x04,0xf2,0x95,0xf6,0xcb,0x68,0xe6,0xa3,0x3b, +0x68,0xe6,0x42,0x39,0x9a,0xbb,0x8a,0x0f,0xbf,0x01,0xed,0xdd,0x80,0xf6,0xe0,0xc5, +0x69,0xae,0xef,0x02,0x9a,0xc3,0xef,0x08,0x57,0x06,0xe1,0xf9,0xa1,0xa5,0x05,0x2c, +0x84,0xbf,0x6c,0xbc,0x09,0x83,0xbf,0x05,0x26,0x6e,0x81,0x16,0xe7,0x3e,0x87,0x67, +0xf2,0x8e,0x0f,0x3f,0xc0,0xd2,0x8d,0x2c,0xca,0x5a,0x64,0x51,0xf5,0x20,0x8b,0x1a, +0x9e,0x2f,0x3b,0x9a,0xae,0x41,0xe6,0x02,0xb2,0x68,0xfb,0x91,0xa5,0xe2,0x43,0x48, +0x0d,0xc8,0xa2,0x1b,0x44,0x96,0xaa,0x01,0x64,0xa9,0x86,0x70,0xef,0xf8,0xec,0x36, +0xb2,0xd4,0x43,0xcc,0x5d,0x86,0x1b,0x32,0x7e,0xbf,0xec,0x80,0x6b,0xcd,0x5c,0xb9, +0x8c,0x2c,0x17,0x60,0x91,0xbe,0x79,0x03,0x59,0x9a,0x20,0xf6,0x3a,0xf1,0xe4,0xe9, +0xd4,0x7e,0x84,0x66,0x3a,0x21,0xb8,0x3a,0xe1,0x9e,0xfc,0x09,0x74,0xb3,0xb3,0x5a, +0x8f,0x66,0xae,0x42,0x14,0x77,0x7e,0x50,0x8f,0x2c,0x2d,0xf0,0xf0,0xd3,0x89,0x6f, +0xd7,0x97,0xe0,0xde,0xd9,0xd5,0x8b,0x2c,0xf0,0x34,0x64,0xb9,0x7c,0x05,0x59,0xae, +0x28,0x21,0xc1,0xe8,0x3e,0x83,0xe9,0xdf,0xd9,0x75,0x1d,0x59,0x7a,0xe4,0xc8,0xd2, +0x0b,0x77,0x5b,0x78,0xab,0x9b,0x81,0xd7,0x27,0x8b,0x09,0x02,0xe1,0x2a,0xfe,0xc5, +0x40,0x2f,0x4c,0x94,0xab,0x6a,0xb8,0xd4,0x55,0x2d,0x1c,0x7b,0x15,0x22,0x60,0xc6, +0x04,0x2d,0x7f,0x7e,0x07,0x59,0xe0,0xed,0xd4,0x32,0x58,0x05,0x09,0xbc,0x75,0xb5, +0x41,0x8e,0x90,0xcd,0xba,0xf5,0xb6,0x76,0x1b,0x36,0x6e,0xb4,0x27,0x6c,0x7a,0xc5, +0xc1,0xf1,0x55,0xa7,0x8d,0x3f,0x7e,0x9c,0x37,0xba,0x6c,0xde,0xe2,0x4a,0xdc,0xba, +0xcd,0xcd,0xba,0xeb,0xbe,0x71,0xfb,0x6b,0x1e,0x9e,0x3b,0x5e,0xf7,0xf2,0xde,0xf8, +0x8b,0x7f,0x76,0xee,0x02,0xf1,0xf9,0x59,0x9b,0x24,0xed,0xde,0xb3,0xd7,0x77,0xdf, +0x1b,0xd6,0xbc,0xdf,0x46,0xf2,0x0f,0xc5,0xfe,0x01,0x1b,0x29,0xd4,0xdf,0x41,0xe6, +0xcd,0x9f,0xe9,0x3a,0xb4,0x9f,0xe4,0xe9,0x3f,0x43,0x7b,0x6f,0xfd,0xf9,0xaa,0xb7, +0xb1,0x04,0x6e,0xdc,0xc8,0x08,0xda,0xcf,0xfc,0xbe,0x28,0xf8,0x9d,0x3f,0x38,0xe2, +0xdd,0x8d,0x1b,0x0f,0x84,0xfc,0xb0,0x73,0x70,0xe3,0x6f,0xf8,0x73,0x28,0x34,0x6c, +0xe3,0xda,0x67,0xed,0xb3,0xf6,0x59,0xfb,0xac,0x7d,0xd6,0x3e,0x6b,0x9f,0xb5,0xcf, +0xda,0x67,0xed,0xb3,0xf6,0x59,0xfb,0xac,0x7d,0x7e,0x3b,0x1f,0x64,0xbb,0xc6,0x3f, +0x84,0x1d,0xb2,0xff,0x03,0x08,0xc8,0x19,0xb9,0x20,0xd7,0xef,0x21,0x22,0x0f,0xc0, +0x13,0x79,0x23,0x12,0x22,0x23,0x0a,0x40,0x45,0x0c,0x14,0x8c,0x0e,0xa0,0x10,0xc4, +0x41,0xc9,0x28,0x1d,0xe0,0x23,0x11,0x92,0x22,0x35,0x32,0xa0,0x5a,0xa0,0x09,0xb5, +0xa1,0x2e,0xd4,0x87,0x06,0xd1,0x3d,0xf4,0x00,0x3d,0x42,0x4f,0x80,0x19,0xf4,0x1c, +0xbd,0x40,0x2f,0x91,0xad,0x8d,0x83,0x15,0x57,0x1b,0x0f,0x1b,0x1f,0x1b,0x3f,0x1b, +0x9a,0x15,0xa6,0x4d,0xa8,0x0d,0xdb,0x26,0xc1,0x26,0xc5,0x26,0x1d,0xe0,0xdb,0x88, +0x6c,0xa4,0x36,0x6a,0x1b,0x83,0x4d,0xad,0x4d,0x93,0x4d,0x9b,0x4d,0x17,0xd0,0x67, +0x33,0x68,0x73,0xcf,0xe6,0x81,0xcd,0x23,0x9b,0x27,0x56,0x66,0x6c,0x9e,0xdb,0xbc, +0xb0,0x79,0x69,0x63,0xbb,0xce,0x76,0x9d,0x03,0xe0,0xba,0xce,0x63,0x9d,0xcf,0x3a, +0xbf,0x75,0xb4,0x75,0xcc,0x75,0xa1,0xeb,0xd8,0xeb,0x12,0xd6,0xa5,0xac,0x4b,0x5f, +0xc7,0x5f,0x27,0x5a,0x27,0x5d,0xa7,0x5e,0x67,0xb0,0x52,0xbb,0xae,0x69,0x5d,0xdb, +0xba,0xae,0x75,0x7d,0xeb,0x06,0xd7,0xdd,0x5b,0xf7,0x60,0xdd,0xa3,0x75,0x4f,0xd6, +0xcd,0xac,0x7b,0xbe,0xee,0xc5,0xba,0x97,0xeb,0x6c,0xd7,0x3b,0xac,0x77,0x5d,0xef, +0xb1,0xde,0x67,0xbd,0x9f,0x15,0xda,0x7a,0xe6,0xfa,0xd0,0xf5,0xec,0xf5,0x09,0xeb, +0x53,0xd6,0xa7,0xaf,0xe7,0xaf,0x17,0xad,0x17,0xaf,0x97,0xad,0x57,0xaf,0x37,0xac, +0xaf,0x5d,0xdf,0xb4,0xbe,0x0d,0xe8,0x5a,0xdf,0xb7,0x7e,0x70,0xfd,0xbd,0xf5,0x0f, +0xd6,0x4f,0xac,0x9f,0x5a,0x3f,0x63,0xe5,0xf9,0xfa,0x17,0xeb,0x5f,0xae,0xb7,0xb5, +0x75,0xb0,0x25,0xda,0x7a,0x58,0xf1,0xb1,0xf5,0xb3,0xa5,0xd9,0x32,0x6d,0x43,0x6d, +0xd9,0x56,0x12,0x6c,0x53,0x6c,0xd3,0x6d,0xf9,0xb6,0x22,0x5b,0xa9,0xad,0xda,0xd6, +0x60,0x5b,0x6b,0xdb,0x64,0xdb,0x66,0xdb,0x65,0xdb,0x67,0x3b,0x68,0x7b,0xcf,0xf6, +0x81,0xed,0x23,0xdb,0x27,0x56,0x66,0x6c,0x9f,0xdb,0xbe,0xb0,0x7d,0x69,0x6b,0x6b, +0xe7,0x60,0xe7,0x6a,0xe7,0x61,0xe7,0x63,0xe7,0x67,0x47,0xb3,0x63,0xda,0x85,0xda, +0xb1,0xed,0x12,0xec,0x52,0xec,0xd2,0xed,0xf8,0x76,0x22,0x3b,0xa9,0x9d,0xda,0xce, +0x60,0x57,0x67,0xd7,0xf0,0x0f,0xd3,0x62,0xd7,0xf1,0xdf,0x70,0xdd,0xae,0xff,0xaf, +0x62,0xc0,0x6e,0xc4,0x6e,0xdc,0x6e,0xca,0xce,0x6c,0x37,0x6f,0xb7,0x64,0xb7,0x62, +0x67,0xb7,0xc1,0x61,0x83,0xeb,0x06,0x8f,0x0d,0x3e,0x1b,0xfc,0x36,0xd0,0x36,0x30, +0x37,0x84,0x6e,0x60,0x6f,0x48,0xda,0x90,0xbe,0x21,0x67,0x83,0x74,0x83,0x76,0x43, +0xed,0x86,0x96,0x0d,0x5d,0x40,0xff,0x86,0x7b,0x1b,0x1e,0x6e,0x78,0xb2,0x61,0x66, +0xc3,0x73,0x2b,0x2f,0x36,0xbc,0xdc,0x60,0xbb,0xd1,0x61,0xa3,0xeb,0x46,0x8f,0x8d, +0x7b,0x37,0xd2,0x36,0x32,0x37,0x86,0x6e,0xe4,0x6c,0x4c,0xdc,0x98,0xba,0x31,0x7d, +0x23,0x7f,0xa3,0xc8,0x8a,0x74,0xa3,0x7a,0x63,0xf5,0xc6,0xa6,0x8d,0x6d,0x1b,0xbb, +0x36,0xf6,0x6d,0x1c,0x04,0xee,0x6d,0x7c,0xb0,0xf1,0xd1,0xc6,0x27,0x1b,0x67,0x36, +0x3e,0xdf,0xf8,0x62,0xe3,0xcb,0x8d,0xb6,0xf6,0x0e,0xf6,0xae,0xf6,0x1e,0xf6,0x3e, +0xf6,0x7e,0xf6,0x34,0x7b,0xa6,0x7d,0xa8,0x3d,0xdb,0x3e,0xc1,0x3e,0xc5,0x3e,0xdd, +0x9e,0x6f,0x2f,0xb2,0x97,0xda,0xab,0xed,0x0d,0xf6,0xb5,0xf6,0x4d,0x56,0xda,0xec, +0xbb,0xfe,0x80,0x3e,0xfb,0x41,0xfb,0x7b,0xf6,0x0f,0xec,0x1f,0xdb,0xcf,0xd8,0x2f, +0xd8,0xbf,0xb4,0xb7,0x25,0x38,0x10,0xdc,0x08,0x3e,0x04,0x3f,0x02,0xed,0x37,0x0a, +0x9d,0xc0,0x20,0x04,0x13,0x42,0x08,0x61,0x04,0x16,0x81,0x43,0x88,0x25,0x24,0x12, +0x92,0xfe,0x21,0x92,0x09,0x69,0x04,0x1e,0x41,0x48,0x90,0x10,0x14,0x04,0x2d,0xa0, +0x23,0x18,0x09,0x35,0x84,0x3a,0x42,0x23,0xa1,0xe9,0x57,0x4b,0x0b,0xa1,0x0d,0xe8, +0x20,0x5c,0xff,0x27,0xd3,0xf7,0x23,0x26,0xc2,0xe0,0xf7,0xdc,0xfd,0x91,0x61,0xc2, +0x97,0x84,0x87,0x84,0xc7,0x84,0x27,0x84,0x19,0xc2,0x73,0xc2,0x0b,0xe0,0x25,0x60, +0xbb,0xc9,0x61,0x93,0xdb,0xdf,0x81,0xd7,0xa6,0xbd,0x9b,0x28,0x9b,0x02,0x37,0x1d, +0xd8,0x14,0xbe,0x29,0xe1,0xef,0x20,0x65,0x53,0xfa,0x26,0xfe,0x26,0xd1,0x26,0xe9, +0x26,0xd9,0x26,0xc5,0x26,0xcd,0x26,0xfd,0xa6,0x0f,0x36,0x35,0x6e,0x6a,0xde,0xd4, +0xf2,0x37,0xd3,0xba,0xa9,0x7d,0x53,0xe7,0xa6,0xae,0x4d,0xdd,0x9b,0x7a,0x36,0xf5, +0x59,0x31,0x6d,0xea,0xff,0x23,0xee,0x6e,0xba,0x0f,0x3c,0xfc,0x9e,0xc7,0x3f,0xf2, +0x74,0xd3,0xdc,0xa6,0x85,0x3f,0xc9,0x77,0xff,0x20,0xe8,0x95,0xbf,0x05,0xfb,0x57, +0x9c,0x01,0xb7,0xef,0xf1,0xfa,0x91,0xbd,0xaf,0x50,0x5e,0x09,0xfc,0x1b,0x39,0xf0, +0x4a,0xf8,0xff,0x42,0x62,0x5e,0x49,0xfa,0x6f,0x38,0xfd,0x0a,0xf7,0x95,0x9c,0x57, +0x0a,0xad,0xc8,0x5f,0xd1,0x5a,0xa9,0x7e,0xa5,0xe1,0x95,0x96,0x57,0x3a,0x5e,0xb9, +0xfe,0x4a,0xbf,0x95,0xbb,0xaf,0xdc,0x7f,0xe5,0xe1,0x2b,0x8f,0x5f,0x79,0xfa,0xca, +0x9c,0x95,0x85,0x57,0xbe,0x7b,0x05,0x39,0xd8,0x3b,0x38,0x3b,0xb8,0x39,0x78,0x39, +0xec,0x75,0xa0,0x38,0x04,0x3a,0x1c,0x70,0x08,0xb7,0x12,0xe3,0x90,0xf4,0xab,0x26, +0xd9,0x21,0xe5,0x9f,0x48,0xaa,0x43,0xba,0x95,0x0c,0x07,0x9e,0x03,0x7f,0x8d,0xbf, +0x01,0x91,0x83,0xd4,0x41,0xed,0x60,0x70,0xa8,0xfd,0x5f,0x4c,0x9d,0x43,0xb3,0x43, +0xbb,0x43,0xb7,0x43,0xdf,0xff,0x32,0x06,0x81,0x7b,0x7f,0x91,0x07,0xff,0x34,0xd0, +0xda,0xe7,0x37,0xfe,0xf9,0x67,0x44,0xd5,0xa3,0x3f,0xe2,0x89,0x95,0x99,0x9f,0x89, +0xe7,0x0e,0x2f,0x1c,0x5e,0x3a,0xd8,0x3a,0x3a,0x38,0xba,0x3a,0x7a,0x38,0xfa,0xfc, +0x8b,0xe2,0xe7,0x48,0xfb,0x0b,0x30,0x1d,0x43,0x01,0xf6,0xaf,0x86,0x04,0x2b,0x29, +0x3f,0x0b,0xe9,0x8e,0x7c,0x47,0x91,0x15,0xe9,0x1a,0xff,0x82,0xa8,0xad,0x18,0x1c, +0x6b,0xff,0x02,0x4d,0x8e,0x6d,0xbf,0x28,0x5d,0xbf,0x20,0x7d,0x8e,0x83,0x8e,0xf7, +0x7e,0xb3,0x3c,0xf8,0x8d,0xf1,0xe8,0x0f,0x78,0xe2,0x38,0x03,0x3c,0x77,0xfc,0xee, +0x37,0x0e,0x7a,0xd5,0xfe,0x55,0xe7,0x35,0xfe,0x2c,0x6e,0x80,0xd7,0xab,0x7e,0xaf, +0xd2,0x7e,0x35,0xd0,0x5f,0x65,0xfe,0xa6,0x09,0x7e,0x35,0xf4,0x67,0x26,0xec,0x55, +0xce,0xab,0x09,0xff,0x54,0x12,0x5f,0x4d,0xfa,0x45,0x39,0xfd,0x27,0xe0,0xfe,0x48, +0xce,0x8f,0x14,0xfe,0x88,0xfc,0xcf,0xa2,0xfd,0x13,0x54,0x03,0x0d,0xaf,0xb6,0xbe, +0xda,0xf5,0xaa,0xe9,0xd5,0xbb,0x7f,0xc4,0xfd,0xbf,0x82,0x87,0x7f,0x82,0xc7,0x3f, +0xf2,0xf4,0x47,0xe6,0x7e,0x64,0xe1,0xcf,0xf2,0xdd,0xbf,0x30,0xc8,0x69,0x8d,0x5f, +0x07,0x36,0x4e,0xb6,0x7f,0x12,0x07,0xc0,0x15,0xf0,0x00,0x7c,0x00,0xbf,0xef,0xa1, +0xfd,0xec,0x30,0x81,0x50,0x2b,0x6c,0xa7,0x04,0x20,0x65,0x8d,0x7f,0x31,0x52,0x9d, +0xd2,0x9c,0x32,0x9c,0xb8,0x4e,0x3c,0x27,0x81,0x93,0xd0,0x49,0xec,0x24,0x71,0x92, +0x39,0x29,0x9c,0x34,0x4e,0x3a,0x27,0xa3,0x53,0x8d,0x53,0xad,0x53,0x9d,0x53,0xa3, +0x53,0xb3,0x53,0xab,0x53,0xbb,0x53,0xa7,0x53,0xb7,0x53,0x8f,0x93,0xc9,0x69,0xc0, +0x69,0xc8,0x69,0xd8,0x69,0xc4,0x69,0xd4,0x69,0xcc,0x69,0xdc,0x69,0xc2,0x69,0xd2, +0xe9,0x89,0xd3,0x94,0xd3,0xb4,0x93,0xd9,0xc9,0xe2,0x34,0xef,0xb4,0xe8,0xb4,0xe4, +0xb4,0xec,0xb4,0xe2,0x64,0xe3,0x6c,0xe7,0x4c,0x70,0x76,0x74,0x76,0x71,0x26,0x3a, +0xbb,0x3b,0x7b,0x3a,0x7b,0x3b,0x93,0x9c,0x7d,0x9d,0xc9,0xce,0x54,0x67,0xba,0x33, +0xc3,0x39,0xd8,0x39,0xc4,0x39,0xcc,0x99,0xe5,0xcc,0xfe,0xb3,0x70,0x9c,0x63,0x7e, +0x06,0x62,0x9d,0x13,0x9d,0x93,0x9d,0x53,0x9d,0xd3,0x9c,0x33,0x9c,0x79,0xce,0x02, +0x67,0xa1,0xb3,0xd8,0x59,0xe2,0x2c,0x73,0x56,0x38,0x6b,0x9c,0x75,0xce,0x46,0xe7, +0x1a,0xe7,0x3a,0xe7,0x46,0xe7,0x66,0xe7,0x56,0xe7,0x76,0xe7,0x4e,0xe7,0x6e,0xe7, +0x1e,0x67,0x93,0xf3,0x80,0xf3,0x90,0xf3,0xb0,0xf3,0x88,0xf3,0xa8,0xf3,0x98,0xf3, +0xb8,0xf3,0x84,0xf3,0xa4,0xf3,0x94,0xf3,0xb4,0xf3,0xcc,0xff,0x02,0x9e,0x3b,0xbf, +0x70,0x7e,0xe9,0x6c,0xeb,0xe2,0xe0,0xe2,0xea,0xe2,0xe1,0xe2,0xe3,0x42,0x71,0x61, +0xba,0x84,0xba,0xb0,0x5d,0x12,0x5c,0x52,0x5c,0xd2,0x5d,0xf8,0x2e,0x22,0x17,0xa9, +0x8b,0xda,0xc5,0xe0,0xd2,0xe0,0xd2,0xe6,0x72,0xdd,0x65,0xd0,0xe5,0x9e,0xcb,0x03, +0x97,0x47,0x2e,0x4f,0x5c,0xe6,0x5c,0x5e,0xb8,0xbc,0x74,0xb1,0xdd,0xec,0xb0,0xd9, +0x75,0xb3,0xc7,0x66,0x9f,0xcd,0x7e,0x9b,0x69,0x9b,0x99,0x9b,0x43,0x37,0xb3,0x37, +0x27,0x6c,0x4e,0xd9,0x9c,0xbe,0x99,0xbf,0x59,0xb4,0x59,0xbe,0xd9,0xb0,0xb9,0x76, +0x73,0xd3,0xe6,0xb6,0xcd,0x5d,0x9b,0xfb,0x36,0x0f,0x6e,0xbe,0xb7,0xf9,0xc1,0xe6, +0xc7,0x9b,0x67,0x36,0x3f,0xdf,0xfc,0x62,0xf3,0xcb,0xcd,0xb6,0x5b,0x1c,0xb6,0xb8, +0x6e,0xf1,0xd8,0xe2,0xb3,0xc5,0x6f,0x0b,0x6d,0x0b,0x73,0x4b,0xe8,0x16,0xf6,0x96, +0x84,0x2d,0x29,0x5b,0xd2,0xb7,0xf0,0xb7,0x88,0xb6,0xc8,0xb7,0x18,0xb6,0x34,0x6c, +0x69,0xdb,0x72,0x7d,0xcb,0xe0,0x96,0xfb,0x5b,0x1e,0x6d,0x79,0xb2,0x65,0x66,0xcb, +0xf3,0x2d,0x2f,0xb6,0xbc,0xdc,0x62,0xeb,0xea,0xe0,0xea,0xea,0xea,0xe5,0xea,0xe7, +0x4a,0x73,0x65,0xba,0x86,0xba,0xb2,0x5d,0x13,0x5c,0x53,0x5c,0xb9,0xae,0x22,0x57, +0xb9,0xab,0xc1,0xb5,0xc1,0xb5,0xcd,0xb5,0xcb,0xb5,0xcf,0x75,0xd0,0xf5,0x9e,0xeb, +0x03,0xd7,0x47,0xae,0x4f,0x5c,0x67,0x5c,0x9f,0xbb,0xbe,0x70,0x7d,0xe9,0x6a,0x4b, +0x74,0x20,0xba,0x12,0xbd,0x88,0x7e,0xc4,0x40,0x62,0x28,0x91,0x4d,0x4c,0x20,0xa6, +0x10,0xd3,0x89,0x7c,0xa2,0x88,0x28,0x25,0xaa,0x89,0x06,0x62,0x2d,0xb1,0x89,0xd8, +0x46,0xec,0x22,0xf6,0x11,0x07,0x89,0xf7,0x88,0x0f,0x88,0x8f,0x88,0x4f,0x88,0x33, +0xc4,0xe7,0xc4,0x17,0xc4,0x97,0x44,0xdb,0xad,0x0e,0x5b,0x5d,0xb7,0x7a,0x6c,0xf5, +0xd9,0xea,0xb7,0x95,0xbe,0xf5,0x9d,0xad,0xa1,0x3f,0xc2,0xde,0x9a,0xb0,0x35,0x65, +0x6b,0xfa,0xd6,0x9c,0xad,0xd2,0xad,0xda,0xad,0xb5,0x5b,0x5b,0xb6,0x76,0x6d,0xed, +0xdf,0x7a,0x6f,0xeb,0xc3,0xad,0x4f,0xb6,0xce,0x6d,0x7d,0xb1,0x15,0x6d,0x73,0xd8, +0xe6,0xb6,0xcd,0x67,0x1b,0x65,0x1b,0x73,0x5b,0xf8,0xb6,0x84,0x6d,0x29,0xdb,0xd2, +0xb7,0xf1,0xb7,0x89,0xb6,0x49,0xb7,0xa9,0xb7,0x55,0x6f,0x6b,0xda,0xd6,0xb1,0xad, +0x6f,0xdb,0xdd,0x6d,0x0f,0xb6,0x3d,0xde,0x36,0xb3,0x6d,0x61,0xdb,0xcb,0x6d,0xb6, +0x6e,0x0e,0x6e,0xae,0x6e,0x1e,0x6e,0x3e,0x6e,0x7e,0x6e,0x34,0x37,0xa6,0x5b,0xb8, +0x5b,0x82,0xdb,0x69,0x37,0xbe,0x5b,0xa1,0x9b,0xda,0xad,0xda,0xad,0xc9,0xad,0xc3, +0xad,0xcf,0xed,0xae,0xdb,0x03,0xb7,0xc7,0x6e,0x33,0x6e,0x0b,0x6e,0x2f,0xdd,0xec, +0xdd,0x5d,0xdd,0xbd,0xdc,0xfd,0xdc,0x69,0xee,0x4c,0xf7,0x50,0x77,0xb6,0x7b,0x92, +0x7b,0xba,0x7b,0x8e,0xbb,0xd4,0x5d,0xeb,0x5e,0xeb,0xde,0xe2,0xde,0xe5,0xde,0xef, +0x7e,0xcf,0xfd,0x81,0xfb,0x23,0xf7,0x27,0xee,0x33,0xee,0xcf,0xdd,0x5f,0xb8,0xbf, +0x74,0xb7,0xdd,0xfe,0x87,0x38,0x6c,0x77,0xdd,0xee,0xb5,0xdd,0x6f,0x7b,0xe0,0xf6, +0xd0,0xed,0x31,0xdb,0x53,0xb6,0xa7,0x6f,0xe7,0x6f,0x2f,0xdc,0xae,0xde,0x5e,0xbd, +0xbd,0x69,0x7b,0xc7,0xf6,0xbe,0xed,0x83,0xdb,0xef,0x6d,0x7f,0xb8,0xfd,0xc9,0xf6, +0xb9,0xed,0x2f,0xac,0xbc,0xdc,0x6e,0xfb,0x9a,0xf3,0x6b,0x1e,0xaf,0xed,0x7d,0x8d, +0x66,0x85,0xf9,0x5a,0xe8,0x6b,0x31,0xaf,0xa5,0xbc,0xc6,0x7d,0x4d,0xf4,0x9a,0xfc, +0x35,0xc3,0x6b,0xb5,0xaf,0x35,0xbd,0xd6,0xf1,0x5a,0xdf,0x6b,0x77,0x5f,0x7b,0xf0, +0xda,0xe3,0xd7,0x66,0x5e,0x7b,0xfe,0xda,0x8b,0xd7,0x90,0x87,0x83,0x87,0x9b,0x87, +0x8f,0x07,0xc5,0x83,0xe9,0x11,0xea,0xc1,0xf6,0x48,0xf2,0x48,0xf7,0xc8,0xf1,0x90, +0x7a,0x68,0x3d,0x6a,0x3d,0x9a,0x3c,0xda,0x3c,0xae,0x7b,0x0c,0x7a,0xdc,0xf7,0x78, +0x64,0xe5,0x89,0xc7,0x8c,0xc7,0x82,0xc7,0x4b,0x0f,0x7b,0x4f,0x57,0x2b,0x1e,0x9e, +0x3e,0x9e,0x14,0x4f,0xa6,0x67,0xb8,0x67,0x82,0xe7,0x69,0x4f,0x3e,0x20,0x02,0xe4, +0x80,0x01,0x68,0xf0,0x6c,0xf1,0xec,0xf0,0xec,0xf3,0xbc,0xeb,0xf9,0xc0,0xf3,0xb1, +0xe7,0x8c,0xe7,0x82,0xe7,0x77,0x9e,0x68,0x87,0xc3,0x0e,0xb7,0x1d,0x3e,0x3b,0x28, +0x3b,0x98,0x3b,0xc2,0x77,0xc4,0xec,0x48,0xda,0x71,0x7a,0x07,0x77,0x47,0xce,0x8e, +0xc2,0x1d,0xf2,0x1d,0xda,0x1d,0xd5,0x3b,0x1a,0x76,0xb4,0xec,0xe8,0xd8,0x71,0x7d, +0x47,0xbf,0x95,0x7b,0x3b,0x1e,0xee,0x78,0xba,0x63,0x61,0x07,0x7a,0xdd,0xf9,0x75, +0xaf,0xd7,0x29,0xaf,0x33,0x5f,0x0f,0x7f,0x3d,0xe9,0x75,0xee,0xeb,0x85,0xaf,0x6b, +0x5f,0x6f,0x78,0xbd,0xe3,0xf5,0xbe,0xd7,0xef,0xbe,0xfe,0xf0,0xf5,0xa7,0xaf,0x2f, +0xbc,0x8e,0xbc,0x9c,0xbd,0xbc,0xbc,0xfc,0xbc,0x02,0xbd,0xc2,0xbd,0x92,0xbc,0xb8, +0x5e,0x85,0x5e,0x5a,0xaf,0x06,0xaf,0x36,0xaf,0xeb,0x5e,0x77,0xbd,0x1e,0x7a,0x3d, +0xf5,0x5a,0xf0,0x42,0xde,0xce,0xde,0x1e,0xde,0x7b,0xbd,0x03,0xbd,0xc3,0xbd,0x93, +0xbc,0xb9,0xde,0x85,0xde,0x5a,0xef,0x6a,0xef,0x06,0xef,0x36,0xef,0x2e,0xef,0x7e, +0xe0,0xae,0xf7,0x03,0xef,0x47,0xde,0x4f,0xbc,0x67,0xbc,0x9f,0x7b,0x2f,0x79,0xbf, +0xf4,0xb6,0xd9,0x49,0xd8,0xb9,0x79,0xa7,0xdb,0x4e,0x9f,0x9d,0x7e,0x3b,0x03,0x81, +0x03,0x3b,0xd9,0x3b,0x13,0x76,0xa6,0xec,0x4c,0xdf,0xc9,0xdf,0x99,0xbf,0xb3,0x64, +0x67,0xd9,0x4e,0xc3,0xce,0xda,0x9d,0x4d,0x3b,0x3b,0x76,0xf6,0x59,0x19,0xdc,0x79, +0x7f,0xe7,0xc3,0x9d,0x8f,0x77,0x3e,0xdd,0x39,0xb7,0xf3,0x3f,0x77,0xfe,0xdf,0x9d, +0xff,0xef,0x4e,0xb4,0xcb,0x7e,0x97,0xf3,0x2e,0x8f,0x5d,0x7b,0x77,0x51,0x76,0x05, +0xee,0x3a,0xb0,0x8b,0xbd,0x2b,0x61,0x57,0xca,0xae,0xf4,0x5d,0xfc,0x5d,0xf9,0xbb, +0x4a,0x76,0xa9,0x77,0x69,0xad,0xd4,0xee,0x6a,0xda,0xd5,0x01,0x5c,0xdf,0x35,0xb8, +0xeb,0xde,0xae,0x07,0xbb,0x1e,0xed,0x7a,0xb2,0x6b,0x76,0x97,0x65,0xd7,0xc2,0xae, +0xff,0x0b,0xfc,0x3f,0xbb,0x96,0x77,0xad,0xec,0xb2,0xf1,0xb1,0xf3,0x21,0xf8,0x38, +0xfa,0xb8,0xf8,0x10,0x7d,0xdc,0x7d,0x3c,0x7e,0x82,0xa7,0x8f,0xd7,0x8f,0x78,0xfb, +0xec,0xfd,0x33,0xf8,0xfa,0x90,0x7d,0xe8,0x3e,0x07,0xfe,0x88,0x10,0x9f,0x50,0x2b, +0x61,0x3e,0x1c,0x9f,0x24,0x9f,0x64,0x9f,0x34,0x1f,0xfe,0xf7,0x08,0x7c,0x44,0x3e, +0x62,0x1f,0xe9,0x1f,0x21,0xf3,0xd1,0xf8,0x18,0x7d,0x6a,0xff,0x2c,0x75,0x3e,0x6d, +0x7f,0x40,0xbb,0x4f,0xc7,0x5f,0xa0,0xd3,0xa7,0xdb,0xe7,0x3a,0xd0,0xe3,0x63,0xf2, +0x19,0xf0,0x19,0xf2,0x19,0xf6,0x19,0xf1,0x19,0xf5,0x19,0xf3,0x19,0xf7,0x99,0xf0, +0x99,0xf4,0x99,0xf2,0x99,0xf6,0x31,0xfb,0x58,0x7c,0xe6,0x7d,0x16,0x7d,0x96,0x7c, +0x96,0x7d,0x56,0x7c,0x6c,0x48,0x76,0x24,0x02,0xc9,0x91,0xe4,0x42,0x22,0x92,0xdc, +0x49,0x1e,0x24,0x4f,0x92,0x37,0x89,0x44,0xf2,0x25,0x91,0x49,0x54,0x12,0x9d,0xc4, +0x20,0x05,0x93,0x42,0x48,0x61,0x24,0x16,0x89,0x43,0x8a,0x25,0x25,0x92,0x92,0x49, +0x29,0x7f,0x44,0x2a,0x29,0xfd,0x57,0x45,0x06,0x20,0x24,0xc9,0x48,0x0a,0x92,0x96, +0xa4,0x23,0xd5,0x91,0x5a,0x49,0x6d,0xa4,0x76,0x52,0x37,0xa9,0x87,0x64,0x22,0x0d, +0x90,0x86,0x48,0xc3,0xa4,0x11,0xd2,0x28,0x69,0x8c,0x34,0x4e,0x7a,0x44,0x9a,0x20, +0x4d,0x92,0x9e,0x02,0xd3,0x24,0x33,0xc9,0x42,0x9a,0x27,0x2d,0x92,0x5e,0x00,0x4b, +0xa4,0x15,0x12,0x61,0xb7,0xf3,0x6e,0x97,0xdd,0xae,0x80,0xdb,0x6e,0xf7,0xdd,0x1e, +0x80,0xd7,0x6e,0xdf,0xdd,0xe4,0xdd,0x94,0xdd,0xd4,0xdd,0xf4,0xdd,0x8c,0xdd,0xcc, +0xdd,0xc1,0xbb,0x43,0x76,0x87,0xed,0x66,0xed,0xe6,0xec,0x8e,0xdd,0x9d,0xb8,0x3b, +0x69,0x77,0xf2,0xee,0x8c,0xdd,0xbc,0xdd,0x82,0xdd,0xc2,0xdd,0xe2,0xdd,0x85,0xdf, +0x23,0xd9,0x2d,0xdb,0xad,0xd8,0xad,0xd9,0xad,0xdb,0x6d,0xf8,0x09,0xc6,0xdd,0x8d, +0xbb,0xdb,0x77,0x9b,0x76,0x0f,0xef,0x1e,0xdb,0x3d,0xb9,0xdb,0xbc,0x7b,0x71,0xf7, +0xca,0x6e,0xc2,0x1e,0xe2,0x1e,0xef,0x3d,0xe4,0x3d,0x8c,0x3d,0x61,0x7b,0x38,0x7b, +0x62,0xf7,0x24,0xef,0xc9,0xd8,0x23,0xd8,0x23,0xdc,0x23,0xd9,0xa3,0xd9,0x53,0xb7, +0xa7,0x79,0x4f,0xeb,0x9e,0xce,0x3d,0xa6,0x3d,0x03,0x7b,0x86,0xf6,0x0c,0xef,0x19, +0xd9,0x33,0xba,0x67,0x7c,0xcf,0xd4,0x1e,0xf3,0x1e,0xcb,0x9e,0xc5,0x3d,0x2b,0x7b, +0x1c,0xf7,0x12,0xf7,0xba,0xef,0xf5,0xde,0x4b,0xde,0x4b,0xdd,0x4b,0xdf,0xcb,0xd8, +0xcb,0xfc,0x2f,0x04,0xef,0x0d,0xff,0x8b,0xc4,0xec,0x4d,0xfa,0xab,0x38,0xfd,0x0f, +0xc1,0xdd,0x9b,0xb3,0xb7,0xf0,0x17,0x44,0xfe,0x23,0x5a,0x2b,0xd5,0x7f,0x23,0x0d, +0x40,0xcb,0x8f,0xb4,0xee,0xed,0xdc,0xdb,0xb7,0xd7,0xb4,0x77,0x68,0xef,0xfd,0xbf, +0xc8,0x43,0x2b,0x8f,0xad,0x3c,0x05,0xe6,0xfe,0x26,0x16,0x80,0xef,0xfe,0x24,0xc8, +0xd7,0xde,0xd7,0xd9,0xd7,0xcd,0xd7,0xcb,0xca,0x5e,0x5f,0x8a,0x95,0x40,0xdf,0x03, +0x7f,0x40,0xb8,0x6f,0x8c,0x95,0x24,0xdf,0xd3,0x56,0xb8,0xbe,0x39,0x3f,0x0b,0x85, +0xbe,0x72,0x5f,0xad,0x6f,0xf5,0x3f,0x9d,0x06,0xdf,0x16,0xdf,0x0e,0xdf,0xeb,0x7f, +0x40,0xbf,0xef,0x5d,0xdf,0xfb,0xbe,0x0f,0xff,0xc7,0x78,0xe4,0xfb,0x78,0x8d,0x35, +0x7e,0x21,0x26,0x7d,0xa7,0x7c,0xa7,0x7d,0xcd,0xbe,0x16,0xdf,0x79,0xdf,0x45,0xdf, +0x25,0xdf,0x65,0xdf,0x15,0x5f,0xbb,0x7d,0x8e,0xfb,0x88,0xfb,0x3c,0xf7,0x91,0xf6, +0x91,0xf7,0xd1,0xf7,0x05,0xef,0x0b,0xdb,0xc7,0xd9,0x97,0xb8,0x2f,0x6d,0x9f,0x60, +0x9f,0x64,0x9f,0x66,0x5f,0xcd,0xbe,0xe6,0x7d,0x9d,0xfb,0x4c,0xfb,0x86,0xf7,0x8d, +0xef,0x9b,0xde,0xb7,0xb8,0xcf,0xe6,0x0d,0x97,0x37,0xbc,0xdf,0xa0,0xbe,0x11,0xf2, +0x46,0xec,0x1b,0x69,0x6f,0x08,0xdf,0x90,0xbc,0xa1,0x78,0x43,0xf7,0x46,0xcd,0x1b, +0x8d,0x6f,0xb4,0xbe,0xd1,0xf9,0x46,0xcf,0x1b,0x03,0x6f,0x8c,0xbc,0x31,0xfe,0xc6, +0xd4,0x1b,0x96,0x37,0x96,0xde,0xb0,0xf1,0x73,0xf4,0x73,0xf7,0x23,0xf9,0x51,0xfd, +0x82,0xfd,0x58,0x7e,0x89,0x7e,0x69,0x7e,0x02,0x3f,0x89,0x9f,0xc6,0xaf,0xc6,0xaf, +0xd9,0xaf,0xd3,0xcf,0xe4,0x37,0xec,0x37,0xe6,0x37,0xe9,0x67,0xf6,0x5b,0xf4,0x5b, +0xf1,0x23,0x90,0x89,0x64,0x6f,0x32,0x99,0xcc,0x20,0x87,0x91,0x63,0xc9,0xa9,0x64, +0x1e,0x59,0x4c,0x96,0x90,0x65,0x64,0x05,0x59,0x43,0xd6,0x91,0x8d,0xe4,0x1a,0x72, +0x1d,0xb9,0x91,0xdc,0x4c,0x6e,0x25,0xb7,0x93,0x3b,0xc9,0xdd,0xe4,0x1e,0xb2,0x89, +0x3c,0x40,0x1e,0x22,0x0f,0x93,0x47,0xc8,0xa3,0xe4,0x31,0xf2,0x38,0x79,0x82,0x3c, +0x49,0x9e,0x22,0x4f,0x93,0xcd,0x64,0x0b,0x79,0x9e,0xbc,0x48,0x5e,0x22,0x2f,0x93, +0x57,0xc8,0x36,0xfe,0x76,0xfe,0x04,0x7f,0x47,0x7f,0x17,0x7f,0xa2,0xbf,0xbb,0xbf, +0xa7,0xbf,0xb7,0x3f,0xc9,0xdf,0xd7,0x9f,0xec,0x4f,0xf5,0xa7,0xfb,0x33,0xfc,0x83, +0xfd,0x43,0xfc,0xc3,0xfc,0xc3,0x7f,0x06,0x58,0xfe,0x49,0xff,0x52,0x24,0xfb,0x67, +0xf8,0x0b,0xfc,0x0b,0xff,0x85,0x90,0xaf,0xf1,0x0f,0xa1,0xf0,0xd7,0xf8,0x6b,0xd7, +0xf8,0x97,0x47,0xe7,0x6f,0x58,0x63,0x8d,0x7f,0x22,0x46,0xff,0xea,0x5f,0x05,0x35, +0xfe,0xb5,0x7f,0x86,0x3a,0xa0,0xd1,0xbf,0xd9,0xbf,0xd5,0xbf,0xdd,0xbf,0xd3,0xbf, +0xdb,0xbf,0xc7,0xdf,0xe4,0x3f,0xe0,0x3f,0xe4,0x3f,0xec,0x3f,0xe2,0x3f,0xea,0x3f, +0xe6,0x3f,0xee,0x3f,0xe1,0x3f,0xe9,0x3f,0xe5,0x3f,0xed,0x6f,0xf6,0xb7,0xf8,0xcf, +0xfb,0x2f,0xfa,0x2f,0xf9,0x2f,0xfb,0xaf,0xf8,0xdb,0x04,0xd8,0x05,0x10,0x02,0x1c, +0x03,0x5c,0x02,0x88,0x01,0xee,0x01,0x9e,0x01,0xde,0x01,0xa4,0x00,0xdf,0x00,0x72, +0x00,0x35,0x80,0x1e,0xc0,0x08,0x08,0x0e,0x08,0x09,0x08,0x0b,0x60,0x05,0x70,0x02, +0x62,0x03,0x12,0x03,0x92,0x03,0x52,0x03,0xd2,0x02,0x32,0x02,0x78,0x01,0x82,0x00, +0x61,0x80,0x38,0x40,0x12,0x20,0x0b,0x50,0x04,0x68,0x02,0x74,0x01,0xc6,0x80,0x9a, +0x80,0xba,0x80,0xc6,0x80,0xe6,0x80,0xd6,0x80,0xf6,0x80,0xce,0x80,0xee,0x80,0x9e, +0x00,0x53,0xc0,0x40,0xc0,0x50,0xc0,0x70,0xc0,0x48,0xc0,0x68,0xc0,0x58,0xc0,0x78, +0xc0,0x44,0xc0,0x64,0xc0,0x54,0xc0,0x74,0x80,0x39,0xc0,0x12,0x30,0x1f,0xb0,0x18, +0xb0,0x14,0xb0,0x1c,0xb0,0x12,0x60,0x43,0xb1,0xa3,0x10,0x28,0x8e,0x14,0x17,0x0a, +0x91,0xe2,0x4e,0xf1,0xa4,0x78,0x53,0x48,0xf0,0xa2,0x47,0xa6,0x50,0x29,0x74,0x0a, +0x83,0x12,0x4c,0x09,0xa1,0x84,0x51,0x58,0x14,0x0e,0x25,0x96,0x92,0x48,0x49,0xa6, +0xa4,0x52,0xd2,0x28,0x19,0x14,0x1e,0x45,0x40,0x11,0x52,0xc4,0x14,0x09,0x45,0x46, +0x51,0x50,0x34,0x14,0x1d,0xc5,0x48,0xa9,0xa1,0xd4,0x51,0x1a,0x29,0xcd,0x94,0x56, +0x4a,0x3b,0xa5,0x93,0xd2,0x4d,0xe9,0xa1,0x98,0x28,0x03,0x94,0x21,0xca,0x30,0x65, +0x84,0x32,0x4a,0x19,0xa3,0x8c,0x53,0x26,0x28,0x93,0x94,0x29,0xca,0x34,0xc5,0x4c, +0xb1,0x50,0xe6,0x29,0x8b,0x94,0x25,0xca,0x32,0x65,0x85,0x62,0x43,0xb5,0xa3,0x12, +0xa8,0x8e,0x54,0x17,0x2a,0x91,0xea,0x4e,0xf5,0xa4,0x7a,0x53,0x49,0x54,0x5f,0x2a, +0x99,0x4a,0xa5,0xd2,0xa9,0x0c,0x6a,0x30,0x35,0x84,0x1a,0x46,0x65,0x51,0x39,0xd4, +0x58,0x6a,0x22,0x35,0x99,0x9a,0x4a,0x4d,0xa3,0x66,0x50,0x79,0x54,0x01,0x55,0x48, +0x15,0x53,0x25,0x54,0x19,0x55,0x41,0xd5,0x50,0x75,0x54,0x23,0xb5,0x86,0x5a,0x47, +0x6d,0xa4,0x36,0x53,0x5b,0xa9,0xed,0xd4,0x4e,0x6a,0x37,0xb5,0x87,0x6a,0xa2,0x0e, +0x50,0x87,0xa8,0xc3,0xd4,0x11,0xea,0x28,0x75,0x8c,0x3a,0x4e,0x9d,0xa0,0x4e,0x52, +0xa7,0xa8,0xd3,0x54,0x33,0xd5,0x42,0x7d,0xfe,0x4f,0x60,0x1e,0x58,0xf8,0xc5,0x58, +0xa4,0xbe,0xa0,0x2e,0x51,0x97,0xa9,0x2b,0x54,0xf4,0xbb,0xbf,0x8c,0x3d,0xe0,0x0c, +0xb8,0x01,0x5e,0xc0,0x5e,0x80,0x02,0x04,0x02,0x07,0x80,0x70,0x20,0x06,0x48,0x02, +0x4e,0x5b,0xe1,0x02,0x39,0x40,0xe1,0x1f,0x20,0xff,0x9d,0x16,0xa8,0xfe,0x5d,0x03, +0xd0,0xf2,0xbb,0x0e,0xe0,0xfa,0xef,0xfa,0x81,0xbb,0xbf,0xbb,0xff,0x37,0xf1,0xf0, +0x27,0x8c,0xff,0x6e,0xf2,0x77,0x4f,0x01,0xcb,0xef,0x16,0xfe,0x2c,0xdf,0x01,0xe8, +0x4d,0xf4,0xa6,0x3d,0xe0,0x0c,0xb8,0x01,0x5e,0xc0,0x5e,0x80,0x02,0x04,0x02,0x07, +0x80,0x70,0x20,0xc6,0x4a,0x12,0x70,0x1a,0xe0,0xfe,0x01,0x39,0x6f,0x16,0x02,0xf2, +0x37,0xb5,0x40,0xf5,0x9b,0x0d,0x40,0xcb,0x9b,0x1d,0xc0,0xf5,0x37,0xfb,0xff,0x26, +0xee,0x5a,0xb9,0xff,0xe6,0xc3,0x37,0x1f,0xbf,0xf9,0xf4,0x7b,0x2c,0x6f,0x2e,0xfc, +0x02,0x2c,0xbe,0xb9,0xf4,0xe6,0xf2,0x9b,0x2b,0x6f,0xda,0xd0,0xec,0x68,0x04,0x9a, +0x23,0xcd,0x85,0x46,0xa4,0xb9,0xd3,0x3c,0x69,0xde,0x34,0x12,0xcd,0x97,0x46,0xa6, +0x51,0x69,0x74,0x1a,0x83,0x16,0x4c,0x0b,0xa1,0x85,0xd1,0x58,0x34,0x0e,0x2d,0x96, +0x96,0x48,0x4b,0xa6,0xa5,0xd2,0xd2,0x68,0x19,0x34,0x1e,0x4d,0x40,0x13,0xd2,0xc4, +0x34,0x09,0x4d,0x46,0x53,0xd0,0x34,0x34,0x1d,0xcd,0x48,0xab,0xa1,0xd5,0xd1,0x1a, +0x69,0xcd,0xb4,0x56,0x5a,0x3b,0xad,0x93,0xd6,0x4d,0xeb,0xa1,0x99,0x68,0x03,0xb4, +0x21,0xda,0x30,0x6d,0x84,0x36,0x4a,0x1b,0xa3,0x8d,0xd3,0x26,0x68,0x93,0xb4,0x29, +0xda,0x34,0xcd,0x4c,0xb3,0xd0,0xe6,0x69,0x8b,0xb4,0x25,0xda,0x32,0x6d,0x85,0x66, +0x43,0xb7,0xa3,0x13,0xe8,0x8e,0x74,0x17,0x3a,0x91,0xee,0x4e,0xf7,0xa4,0x7b,0xd3, +0x49,0x74,0x5f,0x3a,0x99,0x4e,0xa5,0xd3,0xe9,0x0c,0x7a,0x30,0x3d,0x84,0x1e,0x46, +0x67,0xd1,0x39,0xf4,0x58,0x7a,0x22,0x3d,0x99,0x9e,0x4a,0x4f,0xa3,0x67,0xd0,0xb9, +0x56,0x78,0x74,0x01,0x5d,0x48,0x17,0xd3,0x25,0x74,0x19,0x5d,0x41,0xd7,0xd0,0x75, +0x74,0x23,0xbd,0x86,0x5e,0x47,0x6f,0xa4,0x37,0xd3,0x5b,0x7e,0xe5,0xb4,0x02,0xdd, +0xf4,0x01,0xfa,0x08,0x7d,0x9c,0x3e,0x45,0xb7,0xd0,0x97,0xe8,0x36,0x6f,0x39,0xbe, +0xe5,0xfe,0x16,0xe9,0x2d,0xea,0x5b,0xc1,0x6f,0xb1,0xde,0x4a,0x7e,0x8b,0xf7,0x96, +0xe4,0x2d,0xdd,0x5b,0x8d,0x6f,0x75,0xbe,0x35,0xf0,0xd6,0xe8,0x5b,0x93,0x6f,0x59, +0xde,0x5a,0x7e,0x8b,0xf0,0xb6,0xfb,0xdb,0xbe,0x6f,0x33,0xde,0x4e,0x7c,0x9b,0xff, +0xb6,0xe0,0x6d,0xc9,0xdb,0x9a,0xb7,0x6b,0xde,0x6e,0x7e,0xbb,0xf3,0x6d,0xd3,0xdb, +0xc3,0x6f,0x8f,0xbd,0x3d,0xf9,0xb6,0xf9,0xed,0xc5,0xb7,0x57,0xde,0x26,0x04,0x12, +0x03,0xbd,0x03,0xc9,0x81,0x8c,0xc0,0xb0,0xc0,0xd8,0xc0,0xd4,0x40,0x5e,0xa0,0x38, +0x50,0x11,0x68,0x0c,0x6c,0x0c,0x6c,0x0f,0xec,0x09,0x1c,0x0a,0x1c,0x0d,0x9c,0x08, +0x9c,0x0e,0x9c,0x0f,0x5c,0x0e,0xb4,0x63,0xb8,0x30,0x3c,0x19,0xde,0x0c,0x12,0xc3, +0x97,0xe1,0xf7,0x47,0x90,0x19,0x0c,0x46,0x08,0x83,0xc5,0x88,0x65,0x24,0x33,0xd2, +0x18,0x3c,0x86,0x90,0x21,0x61,0x28,0x18,0x3a,0x46,0x0d,0xa3,0x91,0xd1,0xca,0xe8, +0x64,0xf4,0x30,0x4c,0x8c,0x01,0xc6,0x10,0x63,0x98,0x31,0xc2,0x18,0x65,0x8c,0x31, +0xc6,0x19,0x13,0x8c,0x49,0xc6,0x14,0x63,0x9a,0x61,0x66,0x58,0x18,0x8b,0x8c,0x65, +0x86,0x4d,0x10,0x21,0xc8,0x25,0xc8,0x3d,0xc8,0x3b,0xc8,0x37,0x88,0x1a,0xc4,0x08, +0x0a,0x09,0x62,0x05,0xc5,0x06,0x25,0x07,0x09,0x82,0x64,0x41,0xea,0x20,0x4d,0x90, +0x2e,0xc8,0x18,0x54,0x13,0x54,0x17,0xd4,0x18,0xd4,0x1c,0xd4,0x1a,0xd4,0x1e,0xd4, +0x19,0xd4,0x1d,0xd4,0x13,0x64,0x0a,0x1a,0x08,0x1a,0x0a,0x1a,0x0e,0x1a,0x09,0x1a, +0x0d,0x1a,0x0b,0x1a,0x0f,0x9a,0x08,0x9a,0x0c,0x9a,0x0a,0x9a,0x0e,0x32,0x07,0x59, +0x82,0xe6,0x83,0x16,0x83,0x96,0x82,0x96,0x83,0x56,0x82,0x6c,0xf6,0xdb,0xed,0x27, +0xec,0x77,0xdc,0xef,0xb2,0x9f,0xb8,0xdf,0x7d,0xbf,0xe7,0x7e,0xef,0xfd,0xa4,0xfd, +0xbe,0xfb,0xc9,0xfb,0xa9,0xfb,0xe9,0xfb,0x19,0xfb,0x83,0xf7,0x87,0xec,0x0f,0xdb, +0xcf,0xda,0x1f,0xbb,0x3f,0x79,0x7f,0xda,0x7e,0xde,0x7e,0xe1,0x7e,0xc9,0x7e,0xc5, +0x7e,0xdd,0xfe,0x9a,0xfd,0x8d,0xfb,0x5b,0xf7,0x77,0xee,0xef,0xd9,0x3f,0xb0,0x7f, +0x78,0xff,0xe8,0xfe,0xf1,0xfd,0x93,0xfb,0xa7,0xf7,0x5b,0xf6,0x2f,0xee,0x5f,0xde, +0x6f,0xc3,0x24,0x30,0x89,0x4c,0x6f,0x26,0x99,0x49,0x67,0x86,0x30,0x59,0xcc,0x44, +0x66,0x32,0x33,0x95,0x99,0xc6,0xcc,0x60,0xf2,0x98,0x02,0xa6,0x90,0x29,0x66,0x4a, +0x98,0x32,0xa6,0x82,0xa9,0x61,0xea,0x98,0x46,0x66,0x0d,0xb3,0x8e,0xd9,0xc8,0x6c, +0x66,0xb6,0x32,0xdb,0x99,0x9d,0xcc,0x6e,0x66,0x0f,0xd3,0xc4,0x1c,0x60,0x0e,0x31, +0x87,0x99,0x23,0xcc,0x51,0xe6,0x18,0x73,0x9c,0x39,0xc1,0x9c,0x64,0x4e,0x31,0xa7, +0x99,0x66,0xa6,0x85,0x39,0xcf,0x5c,0x64,0x2e,0x31,0x97,0x99,0x2b,0x4c,0x9b,0x60, +0xbb,0x60,0x42,0xb0,0x63,0xb0,0x4b,0xb0,0x3b,0x40,0x0e,0x0e,0x0e,0x8e,0x0d,0x4e, +0x0d,0x16,0x06,0xcb,0x82,0x75,0xc1,0xad,0xc1,0x3d,0xc1,0x43,0xc1,0xa3,0xc1,0x13, +0xc1,0xe6,0xe0,0xa5,0x60,0xbb,0x77,0x88,0xef,0x90,0xde,0xa1,0xbf,0x13,0xf6,0x4e, +0xea,0x3b,0x19,0xef,0xc8,0xde,0xa9,0x7b,0xa7,0xf3,0x9d,0x81,0x77,0xc6,0xdf,0xb1, +0xbc,0xb3,0xfc,0x8e,0xdd,0xbb,0x2e,0xef,0x7a,0xbf,0x4b,0x7d,0x37,0xec,0xdd,0xe4, +0x77,0x33,0xde,0x15,0xbe,0xab,0x78,0xd7,0xf8,0x6e,0xe3,0xbb,0xad,0xef,0x76,0xbe, +0x6b,0x7a,0x77,0xf8,0xdd,0xc9,0x77,0x2d,0xef,0xae,0xbc,0x4b,0x3c,0x40,0x3a,0x40, +0x3d,0x10,0x7c,0x20,0xf1,0x40,0xc6,0x01,0xd9,0x01,0xdd,0x81,0xe6,0x03,0x9d,0x07, +0x06,0x0e,0x8c,0x1c,0x98,0x38,0x60,0x39,0xb0,0x7c,0xc0,0x31,0xc4,0x33,0x84,0x14, +0xc2,0x08,0x09,0x0b,0x89,0x0d,0x49,0x0b,0x11,0x84,0x48,0x42,0x34,0x21,0x8d,0x21, +0x9d,0x21,0x3d,0x21,0xa3,0x21,0x13,0x21,0x96,0x90,0xe5,0x10,0xc2,0x41,0xe2,0x41, +0xef,0x83,0xd4,0x83,0x8c,0x83,0xac,0x83,0xa9,0x07,0x33,0x0e,0xca,0x0e,0xea,0x0e, +0xd6,0x1c,0x6c,0x3c,0xd8,0x7a,0xb0,0xf3,0x60,0xcf,0xc1,0x81,0x83,0xc3,0x07,0x47, +0x0f,0x8e,0x1f,0x9c,0x3c,0x68,0x3e,0xb8,0x78,0x70,0xe5,0x20,0xe1,0x10,0xf1,0x90, +0xf7,0x21,0xf2,0x21,0xc6,0xa1,0xb0,0x43,0xb1,0x87,0x52,0x0f,0xf1,0x0e,0x89,0x0f, +0x29,0x0e,0x19,0x0f,0x35,0x1e,0x6a,0x3d,0xd4,0x79,0xc8,0x74,0x68,0xe8,0xd0,0xc8, +0xa1,0xb1,0x43,0x93,0x87,0xcc,0x87,0xe6,0x0f,0x2d,0x1d,0x5a,0x39,0x64,0x17,0xea, +0x18,0xea,0x19,0x4a,0x0a,0x25,0x87,0xd2,0x43,0x83,0x43,0xc3,0x42,0x39,0xa1,0x89, +0xa1,0xa9,0xa1,0xbc,0x50,0x49,0xa8,0x22,0x54,0x17,0x5a,0x13,0xda,0x18,0xda,0x1a, +0xda,0x19,0xda,0x13,0x3a,0x14,0x3a,0x1a,0x3a,0x11,0x3a,0x1d,0x6a,0x09,0x5d,0x0c, +0x5d,0x0e,0xb5,0x09,0x23,0x84,0xb9,0x84,0xb9,0x87,0x79,0x87,0xf9,0x86,0x51,0xc3, +0x82,0xc3,0x58,0x61,0xb1,0x61,0xa9,0x61,0xbc,0x30,0x71,0x98,0x2c,0x4c,0x17,0x56, +0x17,0xd6,0x1e,0xd6,0x1d,0x36,0x10,0x36,0x12,0x36,0x1e,0x36,0x15,0xb6,0x18,0x46, +0x38,0xec,0x72,0xd8,0xfd,0xb0,0xf7,0x61,0xdf,0xc3,0xd4,0xc3,0x8c,0xc3,0x21,0x87, +0x59,0x87,0x63,0x0f,0x27,0x1f,0x4e,0x3b,0xcc,0x3b,0x2c,0x3c,0x2c,0x39,0xac,0x38, +0xac,0x3b,0x5c,0x73,0xb8,0xf1,0x70,0xe7,0xe1,0x9e,0xc3,0x03,0x87,0x87,0x0f,0x8f, +0x1f,0x9e,0x3a,0x6c,0x3e,0x3c,0x7f,0x78,0xe9,0xf0,0xca,0x61,0xbb,0x23,0x8e,0x47, +0x88,0x47,0x3c,0x8f,0x90,0x8e,0x90,0x8f,0x30,0x8e,0x84,0x1c,0x61,0x1d,0x49,0x3c, +0x92,0x76,0x84,0x77,0x44,0x72,0x44,0x73,0xc4,0x78,0xa4,0xee,0x48,0xf3,0x91,0xf6, +0x23,0x3d,0x47,0x86,0x8e,0x8c,0x1c,0x19,0x3b,0x32,0x71,0x64,0xea,0x88,0xf9,0xc8, +0xfc,0x91,0xa5,0x23,0x2b,0x47,0xec,0xc2,0x5d,0xc2,0x3d,0xc3,0x7d,0xc3,0xe9,0xe1, +0x21,0xe1,0x9c,0xf0,0xe4,0xf0,0x8c,0x70,0x61,0xb8,0x2c,0x5c,0x17,0x5e,0x17,0xde, +0x1a,0xde,0x1d,0x3e,0x10,0x3e,0x12,0x3e,0x1e,0x3e,0x15,0x6e,0x09,0x5f,0x0a,0xb7, +0x61,0x39,0xb2,0xdc,0xd6,0xf8,0x3b,0x71,0x67,0x79,0xb2,0xbc,0xd6,0xf8,0x15,0xe0, +0xcd,0xf2,0xf9,0x8d,0x43,0x62,0xf9,0xb2,0xc8,0x2c,0x2a,0x8b,0x66,0x85,0xce,0x62, +0xb0,0x98,0xff,0x12,0x04,0xb3,0x42,0x58,0x61,0x2c,0x16,0x8b,0xfd,0x5f,0xe0,0xb0, +0x62,0xd6,0xf8,0x9b,0x48,0x60,0x25,0xb1,0x52,0x58,0xa7,0x59,0xe9,0x2c,0x2e,0x8b, +0xcf,0xca,0x61,0x89,0x58,0x85,0x2c,0x29,0x4b,0xce,0x52,0xb3,0xb4,0x2c,0x03,0xab, +0x9a,0x55,0xcb,0x6a,0x60,0x35,0xb1,0x5a,0x58,0x6d,0xac,0x0e,0x56,0x17,0xeb,0x3a, +0xab,0x8f,0xd5,0xcf,0x1a,0x64,0xdd,0x65,0xdd,0x63,0xdd,0x67,0x3d,0x60,0x3d,0x64, +0x3d,0x62,0x3d,0x66,0x3d,0x61,0x3d,0x65,0xcd,0xb0,0xe6,0x58,0xcf,0x59,0x0b,0xac, +0x17,0xac,0xef,0x58,0x2f,0x59,0x28,0xc2,0x36,0xc2,0x3e,0xc2,0x21,0xc2,0x39,0xc2, +0x35,0xc2,0x2d,0xc2,0x23,0xc2,0x2b,0xc2,0x27,0x62,0x6f,0x84,0x5f,0x04,0x25,0x82, +0x16,0x11,0x18,0xc1,0x8c,0x38,0x10,0x11,0x1a,0x11,0x1e,0xc1,0x8e,0x88,0x89,0x48, +0x88,0x48,0x8a,0x48,0x89,0x38,0x1d,0x91,0x1e,0xc1,0x8d,0xe0,0x47,0xe4,0x44,0x88, +0x22,0x0a,0x23,0xa4,0x11,0xf2,0x08,0x75,0x84,0x36,0xc2,0x10,0x51,0x1d,0x51,0x1b, +0xd1,0x10,0xd1,0x14,0xd1,0x12,0xd1,0x16,0xd1,0x11,0xd1,0x15,0x71,0x3d,0xa2,0x2f, +0xa2,0x3f,0x62,0x30,0xe2,0x6e,0xc4,0xbd,0x88,0xfb,0x11,0x0f,0x22,0x1e,0x46,0x3c, +0x8a,0x78,0x1c,0xf1,0x24,0xe2,0x69,0xc4,0x4c,0xc4,0x5c,0xc4,0xf3,0x88,0x85,0x88, +0x17,0x11,0xdf,0x45,0xbc,0x8c,0x40,0x91,0xb6,0x91,0xf6,0x91,0x0e,0x91,0xce,0x91, +0xae,0x91,0x6e,0x91,0x1e,0x91,0x5e,0x91,0x3e,0x91,0x7b,0x23,0xfd,0x22,0x29,0x91, +0xb4,0xc8,0xc0,0x48,0x66,0xe4,0x81,0xc8,0xd0,0xc8,0xf0,0x48,0x76,0x64,0x4c,0x64, +0x42,0x64,0x52,0x64,0x4a,0xe4,0xe9,0xc8,0xf4,0x48,0x6e,0x24,0x3f,0x32,0x27,0x52, +0x14,0x59,0x18,0x29,0x8d,0x94,0x47,0xaa,0x23,0xb5,0x91,0x86,0xc8,0xea,0xc8,0xda, +0xc8,0x86,0xc8,0xa6,0xc8,0x96,0xc8,0xb6,0xc8,0x8e,0xc8,0xae,0xc8,0xeb,0x91,0x7d, +0x91,0xfd,0x91,0x83,0x91,0x77,0x23,0xef,0x45,0xde,0x8f,0x7c,0x10,0xf9,0x30,0xf2, +0x51,0xe4,0xe3,0xc8,0x27,0x91,0x4f,0x23,0x67,0x22,0xe7,0x22,0x9f,0x47,0x2e,0x44, +0xbe,0x88,0xfc,0x2e,0xf2,0x65,0x24,0x62,0xdb,0xb2,0xed,0xd9,0x0e,0x6c,0x67,0xb6, +0x2b,0xdb,0x8d,0xed,0xc1,0xf6,0x62,0xfb,0xb0,0xf7,0xb2,0xfd,0xd8,0x14,0x36,0x8d, +0x1d,0xc8,0x66,0xb2,0x0f,0xb0,0x43,0xd9,0xe1,0x6c,0x36,0x3b,0x86,0x9d,0xc0,0x4e, +0x62,0xa7,0xb0,0x4f,0xb3,0xd3,0xd9,0x5c,0x36,0x9f,0x9d,0xc3,0x16,0xb1,0x0b,0xd9, +0x52,0xb6,0x9c,0xad,0x66,0x6b,0xd9,0x06,0x76,0x35,0xbb,0x96,0xdd,0xc0,0x6e,0x62, +0xb7,0xb0,0xdb,0xd8,0x1d,0xec,0x2e,0xf6,0x75,0x76,0x1f,0xbb,0x9f,0x3d,0xc8,0xbe, +0xcb,0xbe,0xc7,0xbe,0xcf,0x7e,0xc0,0x7e,0xc8,0x7e,0xc4,0x7e,0xcc,0x7e,0xc2,0x7e, +0xca,0x9e,0x61,0xcf,0xb1,0x9f,0xb3,0x17,0xd8,0x2f,0xd8,0xdf,0xb1,0x5f,0xb2,0x11, +0xc7,0x96,0x63,0xcf,0x71,0xe0,0x38,0x73,0x5c,0x39,0x6e,0x1c,0x0f,0x8e,0x17,0xc7, +0x87,0xb3,0x97,0xe3,0xc7,0xa1,0x70,0x68,0x9c,0x40,0x0e,0x93,0x73,0x80,0x13,0xca, +0x09,0xe7,0xb0,0x39,0x31,0x40,0x02,0x27,0x89,0x93,0xc2,0x39,0xcd,0x49,0xe7,0x70, +0x39,0x7c,0x4e,0x0e,0x47,0xc4,0x29,0xe4,0x48,0x39,0x72,0x8e,0x9a,0xa3,0xb5,0x62, +0x00,0xaa,0xad,0xd4,0x72,0x1a,0x38,0x4d,0x9c,0x16,0x4e,0x1b,0xa7,0x83,0xd3,0xc5, +0xb9,0xce,0xe9,0xe3,0xf4,0x03,0x83,0xc0,0x5d,0x2b,0xf7,0x38,0xf7,0xbf,0xe7,0x01, +0xe7,0x21,0xe7,0x11,0xe7,0x31,0xe7,0x09,0xe7,0x29,0x67,0x86,0x33,0xc7,0x79,0xce, +0x59,0xe0,0xbc,0xe0,0x7c,0xc7,0x79,0xc9,0x41,0x51,0xb6,0x51,0xf6,0x51,0x0e,0x51, +0xce,0x51,0xae,0x51,0x6e,0x51,0x1e,0x51,0x5e,0x51,0x3e,0x51,0x7b,0xa3,0xfc,0xa2, +0x28,0x51,0xb4,0xa8,0xc0,0x28,0x66,0xd4,0x81,0xa8,0xd0,0xa8,0xf0,0x28,0x76,0x54, +0x4c,0x54,0x42,0x54,0x52,0x54,0x4a,0xd4,0xe9,0xa8,0xf4,0x28,0x6e,0x14,0x3f,0x2a, +0x27,0x4a,0x14,0x55,0x18,0x25,0x8d,0x92,0x47,0xa9,0xa3,0xb4,0x51,0x86,0xa8,0xea, +0xa8,0xda,0xa8,0x86,0xa8,0xa6,0xa8,0x96,0xa8,0xb6,0xa8,0x8e,0xa8,0xae,0xa8,0xeb, +0x51,0x7d,0x51,0xfd,0x51,0x83,0x51,0x77,0xa3,0xee,0x45,0xdd,0x8f,0x7a,0x10,0xf5, +0x30,0xea,0x51,0xd4,0x63,0x2b,0x4f,0xa2,0x9e,0x46,0xcd,0x44,0xcd,0x45,0x3d,0x8f, +0x5a,0x88,0x7a,0x11,0xf5,0x5d,0xd4,0xcb,0x28,0x14,0x6d,0x1b,0x6d,0x1f,0xed,0x10, +0xed,0x1c,0xed,0x1a,0xed,0x16,0xed,0x11,0xed,0x15,0xed,0x13,0xbd,0x37,0xda,0x2f, +0x9a,0x12,0x4d,0x8b,0x0e,0x8c,0x66,0x46,0x1f,0x88,0x0e,0x8d,0x0e,0x8f,0x66,0x47, +0xc7,0x44,0x27,0x44,0x27,0x45,0xa7,0x44,0x9f,0x8e,0x4e,0x8f,0xe6,0x46,0xf3,0xa3, +0x73,0xa2,0x45,0xd1,0x85,0xd1,0xd2,0x68,0x79,0xb4,0x3a,0x5a,0x1b,0x6d,0x88,0xae, +0x8e,0xae,0x8d,0x6e,0x88,0x6e,0x8a,0x6e,0x89,0x6e,0x8b,0xee,0x88,0xee,0x8a,0xbe, +0x1e,0xdd,0x17,0xdd,0x1f,0x3d,0x18,0x7d,0x37,0xfa,0x5e,0xf4,0xfd,0xe8,0x07,0xd1, +0x0f,0xa3,0x1f,0x45,0x3f,0x8e,0x7e,0x12,0xfd,0x34,0x7a,0x26,0x7a,0x2e,0xfa,0x79, +0xf4,0x42,0xf4,0x8b,0xe8,0xef,0xa2,0x5f,0x46,0xa3,0x18,0xdb,0x18,0xfb,0x18,0x87, +0x18,0xe7,0x18,0xd7,0x18,0xb7,0x18,0x8f,0x18,0xaf,0x18,0x9f,0x98,0xbd,0x31,0x7e, +0x31,0x94,0x18,0x5a,0x4c,0x60,0x0c,0x33,0xe6,0x40,0x4c,0x68,0x4c,0x78,0x0c,0x3b, +0x26,0x26,0x26,0x21,0x26,0x29,0x26,0x25,0xe6,0x74,0x4c,0x7a,0x0c,0x37,0x86,0x1f, +0x93,0x13,0x23,0x8a,0x29,0x8c,0x91,0xc6,0xc8,0x7f,0x46,0x14,0x80,0x2e,0xa6,0x26, +0xa6,0x31,0xa6,0x3d,0xa6,0x27,0x66,0x20,0xe6,0xee,0x9f,0x61,0x38,0x66,0x34,0x66, +0x3c,0x66,0x32,0x66,0x3a,0x66,0xee,0x27,0x2c,0x00,0xcb,0x31,0x2b,0x31,0x36,0xb1, +0x76,0xb1,0x84,0x58,0xc7,0x58,0x97,0x58,0x62,0xac,0x7b,0xac,0x67,0xac,0x57,0xec, +0xde,0x58,0x4a,0x2c,0x33,0x36,0x3c,0x36,0x26,0x36,0x29,0xf6,0x74,0x2c,0x37,0x36, +0x27,0xb6,0x30,0x56,0x1e,0xab,0x8d,0xad,0x06,0x1a,0x62,0x5b,0x62,0x3b,0x62,0xaf, +0xc7,0xf6,0x03,0x77,0x81,0xfb,0xb1,0x0f,0x81,0xc7,0xb1,0x4f,0x81,0xb9,0xd8,0x85, +0xd8,0xef,0x62,0x51,0x9c,0x7d,0x9c,0x73,0x9c,0x5b,0x9c,0x57,0x9c,0x6f,0x1c,0x35, +0x8e,0x1e,0xc7,0x88,0x0b,0x8e,0x0b,0x89,0x0b,0x8b,0x63,0xc5,0x71,0xe2,0x62,0xe3, +0x12,0xe3,0x92,0xe3,0x52,0xe3,0xd2,0xe2,0x32,0xe2,0x78,0x71,0x82,0x38,0x61,0x9c, +0x38,0x4e,0x12,0x27,0x8b,0x53,0xc4,0x69,0xe2,0x74,0x71,0xc6,0xb8,0x9a,0xb8,0xba, +0xb8,0xc6,0xb8,0xe6,0xb8,0xd6,0xb8,0xf6,0xb8,0xce,0xb8,0xee,0xb8,0x9e,0x38,0x53, +0xdc,0x40,0xdc,0x50,0xdc,0x70,0xdc,0x48,0xdc,0x68,0xdc,0x58,0xdc,0x78,0xdc,0x44, +0xdc,0x64,0xdc,0x54,0xdc,0x74,0x9c,0x39,0xce,0x12,0x37,0x1f,0xb7,0x18,0xb7,0x14, +0xb7,0x1c,0xb7,0x12,0x67,0x13,0x6f,0x17,0x4f,0x88,0x77,0x8c,0x77,0x89,0x27,0xc6, +0xbb,0xc7,0x7b,0xc6,0x7b,0xc7,0x93,0xe2,0x7d,0xe3,0xc9,0xf1,0xd4,0x78,0x7a,0x3c, +0x23,0x3e,0x38,0x3e,0x24,0x3e,0x2c,0x9e,0x15,0xcf,0x89,0x8f,0x8d,0x4f,0x8c,0x4f, +0x8e,0x4f,0x8d,0x4f,0x8b,0xcf,0x88,0xe7,0xc5,0x0b,0xe2,0x85,0xf1,0xe2,0x78,0x49, +0xbc,0x2c,0x5e,0x11,0xaf,0x8b,0xaf,0x89,0xaf,0x8b,0x6f,0x8c,0x6f,0x8e,0x6f,0x8d, +0x6f,0x8f,0xef,0x8c,0xef,0x8e,0xef,0x89,0x37,0xc5,0x0f,0xc4,0x0f,0xc7,0xdf,0xff, +0x87,0x19,0x8d,0x1f,0x8b,0x1f,0x8f,0x9f,0x88,0x9f,0x8c,0x9f,0x8a,0x9f,0x8e,0x37, +0xc7,0x5b,0xe2,0xe7,0xe3,0x17,0xe3,0x97,0xe3,0x57,0xe2,0x6d,0x12,0xec,0x12,0x08, +0x09,0x8e,0x09,0x2e,0x09,0xc4,0x04,0xf7,0x04,0xcf,0x04,0xef,0x04,0x52,0x82,0x6f, +0x02,0x3d,0x21,0x24,0x81,0x93,0x90,0x9c,0x90,0x91,0x20,0x4c,0x90,0x25,0xe8,0x12, +0xea,0x12,0x5a,0x13,0xba,0x13,0x06,0x12,0x46,0x12,0xc6,0x13,0xa6,0x12,0x2c,0x09, +0x4b,0x09,0x36,0x89,0x76,0x89,0x84,0x44,0xc7,0x44,0x17,0xc0,0x33,0xd1,0x37,0x91, +0x9e,0x18,0x92,0xc8,0x49,0x4c,0x4c,0x4c,0x4d,0xcc,0x48,0x14,0x24,0x8a,0x13,0x65, +0x89,0x9a,0x44,0x63,0x62,0x5d,0x62,0x73,0x62,0x7b,0x62,0x77,0xa2,0x29,0x71,0x28, +0x71,0x24,0x71,0x2c,0x71,0x22,0x71,0x2a,0xd1,0x9c,0x38,0x9f,0xb8,0x94,0xb8,0x92, +0x68,0x77,0xd4,0xf1,0x28,0xf1,0xa8,0xe7,0x51,0xd2,0x51,0xf2,0x51,0xfa,0xd1,0xe0, +0xa3,0x61,0x47,0x39,0x47,0x13,0x8f,0xa6,0x1e,0xcd,0x38,0x2a,0x38,0x2a,0x3e,0x2a, +0x3b,0xaa,0x39,0x6a,0x3c,0x5a,0x77,0xb4,0xf9,0x68,0xfb,0xd1,0xee,0xa3,0xa6,0xa3, +0x43,0x47,0x47,0x8e,0x8e,0x1d,0x9d,0x38,0x3a,0x75,0xd4,0x7c,0x74,0xfe,0xe8,0xd2, +0xd1,0x95,0xa3,0x76,0xc7,0x1c,0x8f,0x11,0x8f,0x79,0x1e,0x23,0x1d,0x23,0x1f,0xa3, +0x1f,0x0b,0x3e,0x16,0x76,0x8c,0x73,0x2c,0xf1,0x58,0xea,0xb1,0x8c,0x63,0x82,0x63, +0xe2,0x63,0xb2,0x63,0x9a,0x63,0xc6,0x63,0x75,0xc7,0x9a,0x8f,0xb5,0x1f,0xeb,0x3e, +0x66,0x3a,0x36,0x74,0x6c,0xe4,0xd8,0xd8,0xb1,0x89,0x63,0x53,0xc7,0xcc,0xc7,0xe6, +0x8f,0x2d,0x1d,0x5b,0x39,0x66,0x97,0xe4,0x98,0x44,0x4c,0xf2,0x4e,0x22,0x27,0x31, +0x92,0xc2,0x92,0x62,0x93,0x52,0x93,0x78,0x49,0xe2,0x24,0x45,0x92,0x31,0xa9,0x31, +0xa9,0x3d,0xa9,0x3b,0xc9,0x94,0x34,0x94,0x34,0x92,0x34,0x96,0x34,0x91,0x34,0x95, +0x64,0x4e,0x9a,0x4f,0x5a,0x4a,0x5a,0x49,0xb2,0x4b,0x76,0x4c,0x26,0x26,0x7b,0x26, +0x93,0x92,0xc9,0xc9,0xf4,0xe4,0xe0,0xe4,0xb0,0x64,0x4e,0x72,0x62,0x72,0x6a,0x72, +0x46,0xb2,0x20,0x59,0x9c,0x2c,0x4b,0xd6,0x24,0x1b,0x93,0xeb,0x92,0x9b,0x93,0xdb, +0x93,0xbb,0x93,0x4d,0xc9,0x43,0xc9,0x23,0xc9,0x63,0xc9,0x13,0xc9,0x53,0xc9,0xe6, +0xe4,0xf9,0xe4,0xa5,0xe4,0x95,0x64,0xbb,0xe3,0x8e,0xc7,0xdd,0x8f,0x93,0x8e,0x53, +0x8f,0x07,0x1f,0x67,0x1d,0x8f,0x3d,0x9e,0x7c,0x3c,0xed,0x38,0xef,0xb8,0xf0,0xb8, +0xe4,0xb8,0xe2,0xb8,0xee,0x78,0xcd,0xf1,0xc6,0xe3,0xad,0xc7,0x3b,0x8f,0xf7,0x1c, +0x1f,0x38,0x3e,0x7c,0x7c,0xf4,0xf8,0xf8,0xf1,0xc9,0xe3,0xd3,0xc7,0x2d,0xc7,0x17, +0x8f,0x2f,0x1f,0xb7,0x39,0x41,0x38,0xe1,0x72,0xc2,0xfd,0x84,0xf7,0x09,0xdf,0x13, +0xd4,0x13,0x8c,0x13,0x21,0x27,0x58,0x27,0x62,0x4f,0x24,0x9f,0x48,0x3b,0xc1,0x3b, +0x21,0x3c,0x21,0x39,0xa1,0x38,0xa1,0x3b,0x51,0x73,0xa2,0xf1,0x44,0xeb,0x89,0xce, +0x13,0x3d,0x27,0x06,0x4e,0x0c,0x9f,0x18,0x3d,0x31,0x7e,0x62,0xf2,0xc4,0xf4,0x09, +0xcb,0x89,0xc5,0x13,0xcb,0x27,0x6c,0x52,0x08,0x29,0x2e,0x29,0xee,0x29,0xde,0x29, +0xbe,0x29,0xd4,0x14,0x46,0x4a,0x48,0x0a,0x2b,0x25,0x36,0x25,0x39,0x25,0x2d,0x45, +0x90,0x22,0x49,0x51,0xa4,0xe8,0x52,0x6a,0x52,0x1a,0x53,0x5a,0x53,0x3a,0x53,0x7a, +0x52,0x06,0x52,0x86,0x53,0x46,0x53,0xc6,0x53,0x26,0x53,0xa6,0x53,0x2c,0x29,0x8b, +0x29,0xcb,0x29,0x36,0xa9,0x8e,0xa9,0xee,0xa9,0xa4,0x54,0x72,0x2a,0x3d,0x35,0x38, +0x35,0x2c,0x95,0x93,0x9a,0x98,0x9a,0x9a,0x9a,0x91,0x2a,0x48,0x15,0xa7,0xca,0x00, +0x4d,0xaa,0x31,0xb5,0x2e,0xb5,0x39,0xb5,0x3d,0xb5,0x3b,0xd5,0x94,0x3a,0x94,0x3a, +0x92,0x3a,0x96,0x3a,0x91,0x3a,0x95,0x6a,0x4e,0x9d,0x4f,0x5d,0x4a,0x5d,0x49,0xb5, +0x3b,0xe9,0x78,0x92,0x78,0xd2,0xf3,0x24,0xe9,0x24,0xf9,0x24,0xfd,0x64,0xf0,0xc9, +0xb0,0x93,0x9c,0x93,0x89,0x27,0x53,0x4f,0x66,0x9c,0x14,0x9c,0x14,0x9f,0x94,0x9d, +0xd4,0x9c,0x34,0x9e,0xac,0x3b,0xd9,0x7c,0xb2,0xfd,0x64,0xf7,0x49,0xd3,0xc9,0xa1, +0x93,0x23,0x27,0xc7,0x4e,0x4e,0x9c,0x9c,0x3a,0x69,0x3e,0x39,0x7f,0x72,0xe9,0xe4, +0xca,0x49,0xbb,0x53,0x8e,0xa7,0x88,0xa7,0x3c,0x4f,0x91,0x4e,0x91,0x4f,0xd1,0x4f, +0x05,0x9f,0x0a,0x3b,0xc5,0x39,0x95,0x78,0x2a,0xf5,0x54,0xc6,0x29,0xfe,0x5f,0x81, +0xe0,0x94,0xe4,0x94,0xe6,0x54,0xcd,0xa9,0xe6,0x53,0x9d,0xa7,0x4c,0xa7,0x86,0x4f, +0x8d,0x9d,0x9a,0x3c,0x65,0x3e,0xb5,0x78,0x6a,0xe5,0x14,0xe1,0x34,0xf1,0xb4,0xf7, +0x69,0xf2,0x69,0xc6,0xe9,0xb0,0xd3,0xb1,0xa7,0x53,0x4f,0xf3,0x4e,0x8b,0x4f,0x2b, +0x4e,0x1b,0x4f,0x37,0x9e,0x6e,0x3f,0xdd,0x73,0x7a,0xe8,0xf4,0xe8,0xe9,0x89,0xd3, +0xd3,0xa7,0xe7,0x4f,0x2f,0x9f,0xb6,0x4b,0x73,0x49,0xf3,0x4c,0xf3,0x4d,0xa3,0xa7, +0x85,0xa4,0x71,0xd2,0x92,0xd3,0x32,0xd2,0x84,0x69,0xb2,0x34,0x5d,0x5a,0x5d,0x5a, +0x6b,0x5a,0x77,0xda,0x40,0xda,0x48,0xda,0x78,0xda,0x54,0x9a,0x25,0x6d,0x29,0xcd, +0xe6,0x3d,0xc7,0xf7,0xdc,0xdf,0x23,0xbd,0x47,0x7d,0x2f,0xf8,0x3d,0xd6,0x7b,0x89, +0xef,0xa5,0xbd,0xc7,0x07,0x04,0xef,0x49,0xde,0xd3,0xbc,0x57,0xf3,0x5e,0xf3,0x7b, +0x9d,0xef,0x99,0xde,0x1b,0x7e,0x6f,0xec,0xbd,0xc9,0xf7,0xcc,0xef,0x2d,0xbe,0xb7, +0xf2,0x1e,0xe1,0x7d,0xe2,0xfb,0xde,0xef,0x93,0xdf,0x67,0xbc,0x1f,0xf6,0x7e,0xec, +0xfb,0xa9,0xef,0xf3,0xde,0x17,0xbf,0xaf,0x78,0xdf,0xf8,0x7e,0xe3,0xfb,0xed,0xef, +0xf7,0xbc,0x3f,0xf4,0xfe,0xe8,0xfb,0x13,0xef,0x4f,0xbf,0x3f,0xff,0xfe,0xf2,0xfb, +0x76,0xe9,0x2e,0xe9,0x9e,0xe9,0xbe,0xe9,0xf4,0xf4,0x90,0x74,0x4e,0x7a,0x72,0x7a, +0x46,0xba,0x30,0x5d,0x96,0xae,0x4b,0xaf,0x4b,0x6f,0x4d,0xef,0x4e,0x1f,0x48,0x1f, +0x49,0x1f,0x4f,0x9f,0x4a,0xb7,0xa4,0xbf,0xf8,0x99,0x59,0x4a,0xb7,0xc9,0x70,0xcc, +0xf0,0xcc,0x20,0x67,0x04,0x67,0x70,0x32,0x52,0x33,0x04,0x19,0xb2,0x0c,0x5d,0xc6, +0x78,0xc6,0x62,0x06,0xca,0xfc,0xeb,0xb0,0xc9,0xb4,0xcb,0x24,0x64,0x3a,0x66,0xba, +0x64,0x12,0x33,0xdd,0x33,0x3d,0x33,0xbd,0x33,0x49,0x99,0x94,0xbf,0x01,0x6a,0x26, +0x23,0x33,0x38,0x33,0x24,0x33,0x2c,0x93,0x95,0xc9,0xc9,0x8c,0xcd,0x4c,0xcc,0x4c, +0xce,0x4c,0xcd,0x4c,0xcb,0xcc,0xc8,0xe4,0x65,0x0a,0x32,0x85,0x99,0xe2,0x4c,0x49, +0xa6,0x2c,0x53,0x91,0xa9,0xc9,0xd4,0x02,0xba,0x4c,0x63,0x66,0x4d,0x66,0x63,0x66, +0x6b,0x66,0x67,0x66,0x4f,0xa6,0x29,0x73,0x20,0x73,0x28,0x73,0x38,0x73,0x24,0xf3, +0x7e,0xe6,0x68,0xe6,0x58,0xe6,0x78,0xe6,0x44,0xe6,0x64,0xe6,0x54,0xe6,0x74,0xa6, +0x39,0xd3,0x92,0x39,0x9f,0xb9,0x98,0xb9,0x94,0xb9,0x9c,0xb9,0x92,0x69,0x73,0xc6, +0xee,0x0c,0xe1,0x8c,0xe3,0x19,0x97,0x33,0xae,0x67,0x88,0x67,0xdc,0xcf,0x78,0x9e, +0xf1,0x3e,0xe3,0xf3,0x3d,0xa4,0x33,0xe4,0x33,0xf4,0x33,0xcc,0x33,0xc1,0x67,0x42, +0xcf,0x84,0x9d,0xe1,0x9c,0x49,0x3c,0x93,0x7a,0x26,0xe3,0x8c,0xe0,0x8c,0xf8,0x8c, +0xec,0x8c,0xe6,0x8c,0xf1,0x4c,0xdd,0x99,0xc6,0x33,0xad,0x67,0x3a,0xcf,0xf4,0x9c, +0x19,0x38,0x33,0x7c,0x66,0xf4,0xcc,0xf8,0x99,0xc9,0x33,0xd3,0x67,0x2c,0x67,0x16, +0xcf,0x2c,0x9f,0x59,0x39,0x63,0xc3,0xb5,0xe3,0x12,0xb8,0x8e,0x5c,0x17,0x2e,0x91, +0xeb,0xce,0xf5,0xe4,0x7a,0x73,0x49,0x5c,0x5f,0x2e,0x99,0x4b,0xe5,0xd2,0xb9,0x0c, +0x6e,0x30,0x37,0x84,0x1b,0xc6,0x65,0x71,0x39,0xdc,0x58,0x6e,0x22,0x37,0x99,0x9b, +0xca,0x4d,0xe3,0x66,0x70,0x79,0x5c,0x01,0x57,0xc8,0x15,0x73,0x25,0x5c,0x19,0x57, +0xc1,0xd5,0x70,0x75,0x5c,0x23,0xb7,0x86,0x5b,0xc7,0x6d,0xe4,0x36,0x73,0x5b,0xb9, +0xed,0xdc,0x4e,0x6e,0x37,0xb7,0x87,0x6b,0xe2,0x0e,0x70,0x87,0xb8,0xc3,0xdc,0x11, +0xee,0x28,0x77,0x8c,0x3b,0xce,0x9d,0xe0,0x4e,0x72,0xa7,0xb8,0xd3,0x5c,0x33,0xd7, +0xc2,0x9d,0xe7,0x2e,0x72,0x97,0xb8,0xcb,0xdc,0x15,0xae,0x0d,0xcf,0x8e,0x47,0xe0, +0x39,0xf2,0x5c,0x78,0x44,0x9e,0x3b,0xcf,0x93,0xe7,0xcd,0x23,0xf1,0x7c,0x79,0x64, +0x1e,0x95,0x47,0xe7,0x31,0x78,0xc1,0xbc,0x10,0x5e,0x18,0x8f,0xc5,0xe3,0xf0,0x62, +0x79,0x89,0xbc,0x64,0x5e,0x2a,0x2f,0x8d,0x97,0xc1,0xe3,0xf1,0x04,0x3c,0x21,0x4f, +0xcc,0x93,0xf0,0x64,0x3c,0x05,0x4f,0xc3,0xd3,0xf1,0x8c,0xbc,0x1a,0x5e,0x1d,0xaf, +0x91,0xd7,0xce,0xeb,0xe1,0x0d,0xf1,0x46,0x79,0x13,0xbc,0x69,0x9e,0x85,0xb7,0xf0, +0x23,0x8b,0xbc,0x25,0xde,0x32,0x6f,0x85,0x67,0x93,0x65,0x97,0x45,0xc8,0x72,0xcc, +0x72,0xc9,0x22,0x66,0xb9,0x67,0x79,0x66,0x79,0x67,0x91,0xb2,0x7c,0xb3,0xc8,0x59, +0xd4,0x2c,0x7a,0x16,0x23,0x2b,0x38,0x2b,0x24,0x2b,0x2c,0x8b,0x95,0xc5,0xc9,0x8a, +0xcd,0x4a,0xcc,0x4a,0xce,0x4a,0xcd,0x4a,0xcb,0xca,0xc8,0xe2,0x65,0x09,0xb2,0x84, +0x59,0xe2,0x2c,0x49,0x96,0x2c,0x4b,0x91,0xa5,0xc9,0xd2,0x65,0x19,0xb3,0x6a,0xb2, +0xea,0xb2,0x1a,0xb3,0x9a,0xb3,0x5a,0xb3,0xda,0xb3,0x3a,0xb3,0xba,0xb3,0x7a,0xb2, +0x4c,0x59,0x03,0x59,0x43,0x59,0xc3,0x59,0x23,0x59,0xa3,0x59,0x63,0x59,0xe3,0x59, +0x13,0x59,0x93,0x59,0x53,0x59,0xd3,0x59,0xe6,0x2c,0x4b,0xd6,0x7c,0xd6,0x62,0xd6, +0x52,0xd6,0x72,0xd6,0x4a,0x96,0x4d,0xb6,0x5d,0x36,0x21,0xdb,0x31,0xdb,0x25,0x9b, +0x98,0xed,0x9e,0xed,0x99,0xed,0x9d,0x4d,0xca,0xf6,0xcd,0x26,0x67,0x53,0xb3,0xe9, +0xd9,0x8c,0xec,0xe0,0xec,0x90,0xec,0xb0,0x6c,0x56,0x36,0x27,0x3b,0x36,0x3b,0x31, +0x3b,0x39,0x3b,0x35,0x3b,0x2d,0x3b,0x23,0x9b,0x97,0x2d,0xc8,0x16,0x66,0x8b,0xb3, +0x25,0xd9,0xb2,0x6c,0x45,0xb6,0x26,0x5b,0x97,0x6d,0xcc,0xae,0xc9,0xae,0xcb,0x6e, +0xcc,0x6e,0xce,0x6e,0xcd,0x6e,0xcf,0xee,0xcc,0xee,0xce,0xee,0xc9,0x36,0x65,0x0f, +0x64,0x0f,0x65,0x0f,0x67,0x8f,0x64,0x8f,0x66,0x8f,0x65,0x8f,0x67,0x4f,0x64,0x4f, +0x66,0x4f,0x65,0x4f,0x67,0x9b,0xb3,0x2d,0xd9,0xf3,0xd9,0x8b,0xd9,0x4b,0xd9,0xcb, +0xd9,0x2b,0xd9,0x36,0x7c,0x3b,0x3e,0x81,0xef,0xc8,0x77,0xe1,0x13,0xf9,0xee,0x7c, +0x4f,0xbe,0x37,0x9f,0xc4,0xf7,0xe5,0x93,0xf9,0x54,0x3e,0x9d,0xcf,0xe0,0x07,0xf3, +0x43,0xf8,0x61,0x7c,0x16,0x9f,0xc3,0x8f,0xe5,0x27,0xf2,0x93,0xf9,0xa9,0xfc,0x34, +0x7e,0x06,0x9f,0xc7,0x17,0xf0,0x85,0x7c,0x31,0x5f,0xc2,0x97,0xf1,0x15,0x7c,0x0d, +0x5f,0xc7,0x37,0xf2,0x6b,0xf8,0x75,0xfc,0x46,0x7e,0x33,0xbf,0x95,0xdf,0xce,0xef, +0xe4,0x77,0xf3,0x7b,0xf8,0x26,0xfe,0x00,0x7f,0x88,0x3f,0xcc,0x1f,0xe1,0x8f,0xf2, +0xc7,0xf8,0xe3,0xfc,0x09,0xfe,0x24,0x7f,0x8a,0x3f,0xcd,0x37,0xf3,0xe7,0xac,0x58, +0xf8,0xf3,0xfc,0x45,0xfe,0x12,0x7f,0x99,0xbf,0xc2,0x47,0x02,0x24,0xb0,0x11,0xd8, +0x09,0x08,0x02,0x47,0x81,0x8b,0x80,0x28,0x70,0x03,0xdc,0x05,0x9e,0x02,0x6f,0x01, +0x49,0xe0,0x2b,0x20,0x0b,0x28,0x00,0x55,0x40,0x17,0x30,0x04,0x4c,0x2b,0xc1,0x82, +0x10,0x41,0x98,0x80,0x25,0x88,0x15,0x24,0x0a,0x92,0x05,0x29,0x82,0x54,0x41,0x9a, +0x20,0x43,0xc0,0x13,0x08,0x04,0x42,0x81,0x58,0x50,0xb8,0xc6,0xaf,0x12,0xf9,0xdf, +0x85,0x76,0x8d,0xbf,0x13,0x9d,0xc0,0x28,0xa8,0x11,0xd4,0x09,0x1a,0x05,0x4d,0x82, +0x66,0x41,0xab,0xa0,0x5d,0xd0,0x29,0xe8,0x16,0xf4,0x08,0x4c,0x82,0x01,0xc1,0x90, +0x60,0x58,0x30,0x22,0x18,0x15,0x8c,0x09,0xc6,0x05,0x13,0x82,0x49,0xc1,0x94,0x60, +0x5a,0x60,0x16,0x58,0x04,0xf3,0x82,0x45,0xc1,0x92,0x60,0x59,0xb0,0x22,0xb0,0x39, +0x6b,0x77,0x96,0x70,0xd6,0xf1,0xac,0xcb,0x59,0xe2,0x59,0xf7,0xb3,0x9e,0x67,0xbd, +0xcf,0x92,0xce,0xfa,0x9e,0x25,0x9f,0xa5,0x9e,0xa5,0x9f,0x65,0x9c,0x0d,0x3e,0x1b, +0x72,0x36,0xf4,0x6c,0xd8,0x59,0xd6,0x59,0xce,0xd9,0xd8,0xb3,0x89,0x67,0x93,0xcf, +0xa6,0x9e,0x4d,0x3b,0x9b,0x71,0x96,0x77,0x56,0x70,0x56,0x78,0x56,0x7c,0x56,0x72, +0x56,0xba,0xc6,0xaf,0x12,0x35,0x60,0xf8,0x6f,0xa9,0x5d,0xc3,0x4a,0xd3,0xd9,0xb6, +0x35,0xd6,0xf8,0xbb,0xe8,0x3a,0xdb,0xf7,0x8b,0x32,0x08,0xdc,0xfb,0x2f,0x3c,0xb0, +0xf2,0xe8,0x17,0xe2,0x09,0x30,0x73,0xf6,0xf9,0x1a,0xbf,0x09,0x5e,0x9c,0x7d,0x09, +0xd8,0x9e,0x5b,0xe3,0xb7,0x89,0xc3,0x39,0xd7,0xdf,0x30,0x1e,0x6b,0xfc,0xcb,0xe1, +0x73,0xce,0xef,0x1c,0xed,0x1c,0xf3,0x5c,0xe8,0xb9,0x98,0x73,0x29,0xe7,0xb8,0x6b, +0xac,0xf1,0x3f,0x4a,0xce,0xb9,0xc2,0x73,0xea,0x35,0x7e,0x61,0x34,0xe7,0x8c,0xe7, +0xea,0xce,0x35,0x9f,0x6b,0x5b,0x63,0x8d,0x35,0xfe,0x69,0xb4,0x9f,0xeb,0x3c,0xd7, +0x7d,0xae,0xe7,0x9c,0xe9,0xdc,0xc0,0xb9,0xa1,0x73,0xc3,0xe7,0x46,0xce,0x8d,0x9e, +0x1b,0x3b,0x37,0x7e,0x6e,0xe2,0xdc,0xe4,0xb9,0xa9,0x73,0xd3,0xe7,0xcc,0xe7,0x2c, +0xe7,0xe6,0xcf,0x2d,0x9e,0x5b,0x3a,0xb7,0x7c,0x6e,0xe5,0x9c,0x4d,0x8e,0x5d,0x0e, +0x21,0xc7,0x31,0xc7,0x25,0x87,0x98,0xe3,0x9e,0xe3,0x99,0xe3,0x9d,0x43,0xca,0xf1, +0xcd,0x21,0xe7,0x50,0x73,0x68,0xff,0x42,0x30,0x73,0x42,0x73,0x62,0x72,0x52,0x72, +0xb8,0x39,0xa2,0x1c,0xf9,0xaf,0x0a,0x6d,0x4e,0x75,0x4e,0x53,0x4e,0x47,0x4e,0x5f, +0xce,0xdd,0xff,0x61,0x86,0x73,0x46,0x72,0x46,0x73,0xc6,0x72,0xc6,0x73,0x26,0x72, +0x26,0x73,0xa6,0x72,0xa6,0x73,0xcc,0x39,0x96,0x9c,0xf9,0x9c,0xc5,0x9c,0xa5,0x9c, +0xe5,0x9c,0x95,0x1c,0x1b,0xa1,0x9d,0x90,0x20,0x74,0x14,0xba,0x08,0x89,0x42,0x77, +0xa1,0xa7,0xd0,0x5b,0x48,0x12,0xfa,0x0a,0xc9,0x42,0xaa,0x90,0x2e,0x64,0x08,0x83, +0x85,0x21,0xc2,0x30,0x21,0x4b,0xc8,0x11,0xc6,0x0a,0x13,0x85,0xc9,0xc2,0x54,0x61, +0x9a,0x30,0x43,0xc8,0x13,0x0a,0x84,0x42,0xa1,0x58,0x28,0x11,0xca,0x84,0x0a,0xa1, +0x46,0xa8,0x13,0x1a,0x85,0x35,0xc2,0x3a,0x61,0xa3,0xb0,0x59,0xd8,0x2a,0x6c,0x17, +0x76,0x0a,0xbb,0x85,0x3d,0x42,0x93,0x70,0x40,0x38,0x24,0x1c,0x16,0x8e,0x08,0x47, +0x85,0x63,0xc2,0x71,0xe1,0x84,0x70,0x52,0x38,0x25,0x9c,0x16,0x9a,0x85,0x16,0xe1, +0xbc,0x70,0x51,0xb8,0x24,0x5c,0x16,0xae,0x08,0x6d,0x72,0xed,0x72,0x09,0xb9,0x8e, +0xb9,0x2e,0xb9,0xae,0xb9,0xc4,0x5c,0xf7,0x5c,0xcf,0x5c,0xef,0x5c,0x52,0xae,0x6f, +0x2e,0x39,0x97,0x9a,0x4b,0xcf,0x65,0xe4,0x06,0xe7,0x86,0xe4,0x86,0xe5,0xb2,0x72, +0x39,0xb9,0xb1,0xb9,0x89,0xb9,0xc9,0xb9,0xa9,0xb9,0x69,0xb9,0x19,0xb9,0xbc,0x5c, +0x41,0xae,0x30,0x57,0x9c,0x2b,0xc9,0x95,0xe5,0x2a,0x72,0x35,0xb9,0xba,0x5c,0x63, +0x6e,0x4d,0x6e,0x5d,0x6e,0x63,0x6e,0x73,0x6e,0x6b,0x6e,0x7b,0x6e,0x67,0x6e,0x77, +0x6e,0x4f,0xae,0x29,0x77,0x20,0x77,0x28,0x77,0x38,0x77,0x24,0x77,0x34,0x77,0x2c, +0x77,0x3c,0x77,0x22,0x77,0x32,0x77,0x2a,0x77,0x3a,0xd7,0x9c,0x6b,0xc9,0x9d,0xcf, +0x5d,0xcc,0x5d,0xca,0x5d,0xce,0x5d,0xc9,0xb5,0xc9,0xb3,0xcb,0x23,0xe4,0x39,0xe6, +0xb9,0xe4,0x11,0xf3,0xdc,0xf3,0x3c,0xf3,0xbc,0xf3,0x48,0x79,0xbe,0x79,0xe4,0x3c, +0x4a,0x1e,0x35,0x8f,0x9e,0x17,0x08,0x30,0xf2,0x98,0x40,0x70,0x5e,0x48,0x5e,0x28, +0x10,0x96,0xc7,0xca,0xe3,0xe4,0xc5,0xe6,0x25,0xe4,0x25,0xe6,0x25,0xe7,0xa5,0xe6, +0xa5,0xe5,0x65,0xe4,0xf1,0xf2,0x04,0x79,0xc2,0x3c,0x71,0x9e,0x24,0x4f,0x96,0xa7, +0xc8,0x53,0xe7,0x69,0xf2,0xb4,0x79,0xba,0x3c,0x63,0x5e,0x4d,0x5e,0x5d,0x5e,0x63, +0x5e,0x73,0x5e,0x6b,0x5e,0x5b,0x5e,0x7b,0x5e,0x67,0x5e,0x77,0x5e,0x4f,0x9e,0x29, +0x6f,0x20,0x6f,0x28,0x6f,0x38,0x6f,0x24,0x6f,0x34,0x6f,0x2c,0x6f,0x3c,0x6f,0x22, +0x6f,0x32,0x6f,0x2a,0x6f,0x3a,0xcf,0x9c,0x67,0xc9,0x9b,0xcf,0x5b,0xcc,0x5b,0xca, +0x5b,0xce,0x5b,0xc9,0xb3,0x11,0xd9,0x89,0x08,0x22,0x47,0x91,0x8b,0x88,0x28,0x72, +0x17,0x79,0x8a,0xbc,0x45,0x24,0x91,0xaf,0x88,0x2c,0xa2,0x8a,0xe8,0x22,0x86,0x28, +0x58,0x14,0x22,0x0a,0x13,0xb1,0x44,0x1c,0x51,0xac,0x28,0x51,0x94,0x2c,0x4a,0x15, +0xa5,0x89,0x32,0x44,0x3c,0x91,0x40,0x24,0x14,0x89,0x45,0x12,0x91,0x4c,0xa4,0x10, +0x69,0x44,0x3a,0x91,0x51,0x54,0x03,0xd4,0x89,0x1a,0x45,0xcd,0xa2,0x56,0x51,0xbb, +0xa8,0x43,0xd4,0x29,0xea,0x16,0xf5,0x88,0x4c,0xa2,0x7e,0x60,0x40,0x34,0x24,0x1a, +0x16,0x8d,0x88,0x46,0x45,0x63,0xa2,0x71,0xd1,0x84,0xe8,0xb1,0x68,0x52,0x34,0x25, +0x9a,0x16,0x99,0x45,0x16,0xd1,0xbc,0x68,0x51,0xf4,0x42,0xb4,0x24,0x5a,0x16,0xad, +0x88,0x6c,0xc4,0x76,0x62,0x82,0xd8,0x51,0xec,0x22,0x26,0x8a,0xdd,0xc5,0x9e,0x62, +0x6f,0x31,0x49,0xec,0x2b,0x26,0x8b,0xa9,0x62,0xba,0x98,0x21,0x0e,0x16,0x87,0x88, +0xc3,0xc4,0x2c,0x31,0x47,0x1c,0x2b,0x4e,0x14,0x27,0x8b,0x53,0xc5,0x69,0xe2,0x74, +0x71,0x86,0x98,0x27,0x16,0x88,0x85,0x62,0x91,0x58,0x2c,0x96,0x88,0x65,0x62,0x85, +0x58,0x23,0xd6,0x8a,0x75,0x62,0x83,0x15,0xa3,0xb8,0x46,0x5c,0x27,0x6e,0x14,0x37, +0x8b,0x5b,0xc5,0xed,0xe2,0x0e,0x71,0xa7,0xb8,0x5b,0xdc,0x23,0x36,0x89,0x07,0xc4, +0x43,0xe2,0x61,0xf1,0x88,0x78,0x54,0x3c,0x26,0x1e,0x17,0x4f,0x88,0x27,0xc5,0x53, +0xe2,0x69,0xb1,0x59,0x6c,0x11,0xcf,0x8b,0x17,0xc5,0x4b,0xe2,0x65,0xf1,0x8a,0xd8, +0x26,0xdf,0x2e,0x9f,0x90,0xef,0x98,0xef,0x92,0x4f,0xcc,0x77,0xcf,0xf7,0xcc,0xf7, +0xce,0x27,0xe5,0xfb,0xe6,0x93,0xf3,0xa9,0xf9,0xf4,0x7c,0x46,0x7e,0x70,0x7e,0x48, +0x7e,0x58,0x3e,0x2b,0x9f,0x93,0x1f,0x9b,0x9f,0x98,0x9f,0x9c,0x9f,0x9a,0x9f,0x96, +0x9f,0x91,0xcf,0xcb,0x17,0xe4,0x0b,0xf3,0xc5,0xf9,0x92,0x7c,0x59,0xbe,0x22,0x5f, +0x93,0xaf,0xcb,0x37,0xe6,0xd7,0xe4,0xd7,0xe5,0x37,0xe6,0x37,0xe7,0xb7,0xe6,0xb7, +0xe7,0x77,0xe6,0x77,0xe7,0xf7,0xe4,0x9b,0xf2,0x07,0xf2,0x87,0xf2,0x87,0xf3,0x47, +0xf2,0x47,0xf3,0xc7,0xf2,0xc7,0xf3,0x27,0xf2,0x27,0xf3,0xa7,0xf2,0xa7,0xf3,0xcd, +0xf9,0x96,0xfc,0xf9,0xfc,0xc5,0xfc,0xa5,0xfc,0xe5,0xfc,0x95,0x7c,0x9b,0x02,0xbb, +0x02,0x42,0x81,0x63,0x81,0x4b,0x01,0xb1,0xc0,0xbd,0xc0,0xb3,0xc0,0xbb,0x80,0x54, +0xe0,0x5b,0x40,0x2e,0xa0,0x16,0xd0,0x0b,0x18,0x05,0xc1,0x05,0x21,0x05,0x61,0x05, +0xac,0x02,0x4e,0x41,0x6c,0x41,0x62,0x41,0x72,0x41,0x6a,0x41,0x5a,0x41,0x46,0x01, +0xaf,0x40,0x50,0x20,0x2c,0x10,0x17,0x48,0x0a,0x64,0x05,0x8a,0x02,0x4d,0x81,0xae, +0xc0,0x58,0x50,0x53,0x50,0x57,0xd0,0x58,0xd0,0x5c,0xd0,0x5a,0xd0,0x5e,0xd0,0x59, +0xd0,0x5d,0xd0,0x53,0x60,0x2a,0x18,0x28,0x18,0x2a,0x18,0x2e,0x18,0x29,0x18,0x2d, +0x18,0x2b,0x18,0x2f,0x98,0x28,0x98,0x2c,0x98,0x2a,0x98,0x2e,0x30,0x17,0x58,0x0a, +0xe6,0x0b,0x16,0x0b,0x96,0x0a,0x96,0x0b,0x56,0x0a,0x6c,0x0a,0xed,0x0a,0x09,0x85, +0x8e,0x85,0x2e,0x85,0xc4,0x42,0xf7,0x42,0xcf,0x42,0xef,0x42,0x52,0xa1,0x6f,0x21, +0xb9,0x90,0x5a,0x48,0x2f,0x64,0x14,0x06,0x17,0x86,0x14,0x86,0x15,0xb2,0x0a,0x39, +0x85,0xb1,0x85,0x89,0x85,0xc9,0x85,0xa9,0x85,0x69,0x40,0x46,0x21,0xaf,0x50,0x50, +0x28,0x2c,0x14,0x17,0x4a,0x0a,0x65,0x85,0x8a,0x42,0x4d,0xa1,0xae,0xd0,0x58,0x58, +0x53,0x58,0x57,0xd8,0x58,0xd8,0x5c,0xd8,0x5a,0xd8,0x5e,0xd8,0x59,0xd8,0x5d,0xd8, +0x53,0x68,0x2a,0x1c,0x28,0x1c,0x2a,0x1c,0x2e,0x1c,0x29,0x1c,0x2d,0x1c,0x2b,0x1c, +0x2f,0x9c,0x28,0x9c,0x2c,0x9c,0x2a,0x9c,0x2e,0x34,0x17,0x5a,0x0a,0xe7,0x0b,0x17, +0x0b,0x97,0x0a,0x97,0x0b,0x57,0x0a,0x6d,0x24,0x76,0x12,0x82,0xc4,0x51,0xe2,0x22, +0x21,0x4a,0xdc,0x25,0x9e,0x12,0x6f,0x09,0x49,0xe2,0x2b,0x21,0x4b,0xa8,0x12,0xba, +0x84,0x21,0x09,0x96,0x84,0x48,0xc2,0x24,0x2c,0x09,0x47,0x12,0x2b,0x49,0x94,0x24, +0x4b,0x52,0x25,0x69,0x92,0x0c,0x09,0x4f,0x22,0x90,0x08,0x25,0x62,0x89,0x44,0x22, +0x93,0x28,0x24,0x1a,0x89,0x4e,0x62,0x94,0xd4,0x48,0xea,0x24,0x8d,0x92,0x66,0x49, +0xab,0xa4,0x5d,0xd2,0x29,0xe9,0x96,0xf4,0x48,0x4c,0x92,0x01,0xc9,0x90,0x64,0x58, +0x32,0x22,0x19,0x95,0x8c,0x49,0xc6,0x25,0x13,0x92,0x49,0xc9,0x94,0x64,0x5a,0x62, +0x96,0x58,0x24,0xf3,0x92,0x45,0xc9,0x92,0x64,0x59,0xb2,0x22,0xb1,0x29,0xb2,0x2b, +0x22,0x14,0x39,0x16,0xb9,0x14,0x11,0x8b,0xdc,0x8b,0x3c,0x8b,0xbc,0x8b,0x48,0x45, +0xbe,0x45,0xe4,0x22,0x6a,0x11,0xbd,0x88,0x51,0x14,0x5c,0x14,0x52,0x14,0x56,0xc4, +0x2a,0xe2,0x14,0xc5,0x16,0x25,0x16,0x25,0x17,0xa5,0x16,0xa5,0x15,0x65,0x14,0xf1, +0x8a,0x04,0x45,0xc2,0x22,0x71,0x91,0xa4,0x48,0x56,0xa4,0x28,0xd2,0x14,0xe9,0x8a, +0x8c,0x45,0x35,0x45,0x75,0x45,0x8d,0x45,0xcd,0x45,0xad,0x45,0xed,0x45,0x9d,0x45, +0xdd,0x45,0x3d,0x45,0xa6,0xa2,0x81,0xa2,0xa1,0xa2,0xe1,0xa2,0x91,0xa2,0xd1,0xa2, +0xb1,0xa2,0xf1,0xa2,0x89,0xa2,0xc9,0xa2,0xa9,0xa2,0xe9,0x22,0x73,0x91,0xa5,0x68, +0xbe,0x68,0xb1,0x68,0xa9,0x68,0xb9,0xe8,0x65,0xd1,0x4a,0x91,0x4d,0xb1,0x5d,0x31, +0xa1,0xd8,0xb1,0xd8,0xa5,0x98,0x58,0xec,0x5e,0xec,0x59,0xec,0x5d,0x4c,0x2a,0xf6, +0x2d,0x26,0x17,0x53,0x8b,0xe9,0xc5,0x8c,0xe2,0xe0,0xe2,0x90,0xe2,0xb0,0x62,0x56, +0x31,0xa7,0x38,0xb6,0x38,0xb1,0x38,0xb9,0x38,0xb5,0x38,0xad,0x38,0xa3,0x98,0x57, +0x2c,0x28,0x16,0x16,0x8b,0x8b,0x25,0xc5,0xb2,0x62,0x45,0xb1,0xa6,0x58,0x57,0x6c, +0x2c,0xae,0x29,0xae,0x2b,0x6e,0x2c,0x6e,0x2e,0x6e,0x2d,0x6e,0x2f,0xee,0x2c,0xee, +0x2e,0xee,0x29,0x36,0x15,0x0f,0x14,0x0f,0x15,0x0f,0x17,0x8f,0x14,0x8f,0x16,0x8f, +0x15,0x8f,0x17,0x4f,0x14,0x4f,0x16,0x4f,0x15,0x4f,0x17,0x9b,0x8b,0x2d,0xc5,0xf3, +0xc5,0x8b,0xc5,0x4b,0xc5,0xcb,0xc5,0x2b,0xc5,0x36,0x52,0x3b,0x29,0x41,0xea,0x28, +0x75,0x91,0x12,0xa5,0xee,0x52,0x4f,0xa9,0xb7,0x94,0x24,0xf5,0x95,0x92,0xa5,0x54, +0x29,0x5d,0xca,0x90,0x06,0x4b,0x43,0xa4,0x61,0x52,0x96,0x94,0x23,0x8d,0x95,0x26, +0x4a,0x93,0xa5,0xa9,0x40,0x9a,0x34,0x43,0xca,0x93,0x0a,0xa4,0x42,0xa9,0x58,0x2a, +0x91,0xca,0xa4,0x0a,0xa9,0x46,0xaa,0x93,0x1a,0xa5,0x35,0xd2,0x3a,0x69,0xa3,0xb4, +0x59,0xda,0x2a,0x6d,0x97,0x76,0x4a,0xbb,0xa5,0x3d,0x52,0x93,0x74,0x40,0x3a,0x24, +0x1d,0x96,0x8e,0x48,0x47,0xa5,0x63,0xd2,0x71,0xe9,0x84,0x74,0x52,0x3a,0x25,0x9d, +0x96,0x9a,0xa5,0x16,0xe9,0xbc,0x74,0x51,0xba,0x24,0x5d,0x96,0xae,0x48,0x6d,0x64, +0x76,0x32,0x82,0xcc,0x51,0xe6,0x22,0x23,0xca,0xdc,0x65,0x9e,0x32,0x6f,0x19,0x49, +0xe6,0x2b,0x23,0xcb,0xa8,0x32,0xba,0x8c,0x21,0x0b,0x96,0x85,0xc8,0xc2,0x64,0x2c, +0x19,0x47,0x16,0x2b,0x4b,0x94,0x25,0xcb,0x52,0x65,0x69,0xb2,0x0c,0x19,0x4f,0x26, +0x90,0x09,0x65,0x62,0x99,0x44,0x26,0x93,0x29,0x64,0x1a,0x99,0x4e,0x66,0x94,0xd5, +0xc8,0xea,0x64,0x8d,0xb2,0x66,0x59,0xab,0xac,0x5d,0xd6,0x29,0xeb,0x96,0xf5,0xc8, +0x4c,0xb2,0x01,0xd9,0x90,0x6c,0x58,0x36,0x22,0x1b,0x95,0x8d,0xc9,0xc6,0x65,0x13, +0xb2,0x49,0xd9,0x94,0x6c,0x5a,0x66,0x96,0x59,0x64,0xf3,0xb2,0x45,0xd9,0x92,0x6c, +0x59,0xb6,0x22,0xb3,0x29,0xb1,0x2b,0x21,0x94,0x38,0x96,0xb8,0x94,0x10,0x4b,0xdc, +0x4b,0x3c,0x4b,0xbc,0x4b,0x48,0x25,0xbe,0x25,0xe4,0x12,0x6a,0x09,0xbd,0x84,0x51, +0x12,0x5c,0x12,0x52,0x12,0x56,0xc2,0x2a,0xe1,0x94,0xc4,0x96,0x24,0x96,0x24,0x97, +0xa4,0x96,0xa4,0x95,0x64,0x94,0xf0,0x4a,0x04,0x25,0xc2,0x12,0x71,0x89,0xa4,0x44, +0x56,0xa2,0x28,0xd1,0x94,0xe8,0x4a,0x8c,0x25,0x35,0x25,0x75,0x25,0x8d,0x25,0xcd, +0x25,0xad,0x25,0xed,0x25,0x9d,0x25,0xdd,0x25,0x3d,0x25,0xa6,0x92,0x81,0x92,0xa1, +0x92,0xe1,0x92,0x91,0x92,0xd1,0x92,0xb1,0x92,0xf1,0x92,0x89,0x92,0xc9,0x92,0xa9, +0x92,0xe9,0x12,0x73,0x89,0xa5,0x64,0xbe,0x64,0xb1,0x64,0xa9,0x64,0xb9,0x64,0xa5, +0xc4,0xa6,0xd4,0xae,0x94,0x50,0xea,0x58,0xea,0x52,0x4a,0x2c,0x75,0x2f,0xf5,0x2c, +0xf5,0x2e,0x25,0x95,0xfa,0x96,0x92,0x4b,0xa9,0xa5,0xf4,0x52,0x46,0x69,0x70,0x69, +0x48,0x69,0x58,0x29,0xab,0x94,0x53,0x1a,0x5b,0x9a,0x58,0x9a,0x5c,0x9a,0x5a,0x9a, +0x56,0x9a,0x51,0xca,0x2b,0x15,0x94,0x0a,0x4b,0xc5,0xa5,0x92,0x52,0x59,0xa9,0xa2, +0x54,0x53,0xaa,0x2b,0x35,0x00,0xc6,0xd2,0x9a,0xd2,0xba,0xd2,0xc6,0xd2,0xe6,0xd2, +0xd6,0xd2,0xf6,0xd2,0xce,0xd2,0xee,0xd2,0x9e,0x52,0x53,0xe9,0x40,0xe9,0x50,0xe9, +0x70,0xe9,0x48,0xe9,0x68,0xe9,0x58,0xe9,0x78,0xe9,0x44,0xe9,0x64,0xe9,0x54,0xe9, +0x74,0xa9,0xb9,0xd4,0x52,0x3a,0x5f,0xba,0x58,0xba,0x54,0xba,0x5c,0xba,0x52,0x6a, +0x23,0xb7,0x93,0x13,0xe4,0x8e,0x72,0x17,0x39,0x51,0xee,0x2e,0xf7,0x94,0x7b,0xcb, +0x49,0x72,0x5f,0x39,0x59,0x4e,0x95,0xd3,0xe5,0x0c,0x79,0xb0,0x3c,0x44,0x1e,0x26, +0x67,0xc9,0x39,0xf2,0x58,0x79,0xc2,0x1a,0x7f,0x35,0x89,0xf2,0xa4,0x5f,0x94,0x64, +0x79,0xaa,0x3c,0x4d,0x9e,0x21,0xe7,0xc9,0x05,0x72,0xa1,0x5c,0x2c,0x97,0xc8,0x65, +0x72,0x85,0x5c,0x23,0xd7,0xc9,0x8d,0xf2,0x1a,0x79,0x9d,0xbc,0x51,0xde,0x2c,0x6f, +0x95,0xb7,0xcb,0x3b,0xe5,0xdd,0xf2,0x1e,0xb9,0x49,0x3e,0x20,0x1f,0x92,0x0f,0xcb, +0x47,0xe4,0xa3,0xf2,0x31,0xf9,0xb8,0x7c,0x42,0x3e,0x29,0x9f,0x92,0x4f,0xcb,0xcd, +0x72,0x8b,0x7c,0x5e,0xbe,0x28,0x5f,0x92,0x2f,0xcb,0x57,0xe4,0x36,0x0a,0x3b,0x05, +0x41,0xe1,0xa8,0x70,0x51,0x10,0x15,0xee,0x0a,0x4f,0x85,0xb7,0xc2,0xe7,0x9f,0x0e, +0x49,0xe1,0xab,0x20,0x2b,0xa8,0x0a,0xba,0x82,0xa1,0x08,0x56,0x84,0x28,0xc2,0x14, +0x2c,0x05,0x47,0x11,0xab,0x48,0x54,0x24,0x2b,0x52,0x15,0x69,0x8a,0x0c,0x05,0x4f, +0x21,0x50,0x08,0x15,0x62,0x85,0x44,0x21,0x53,0x28,0x14,0x1a,0x85,0x4e,0x61,0x54, +0xd4,0x28,0xea,0x14,0x8d,0x8a,0x66,0x45,0xab,0xa2,0x5d,0xd1,0xa9,0xe8,0x56,0xf4, +0x28,0x4c,0x8a,0x01,0xc5,0x90,0x62,0x58,0x31,0xa2,0x18,0x55,0x8c,0x29,0xc6,0x15, +0x13,0x8a,0x49,0xc5,0x94,0x62,0x5a,0x61,0x56,0x58,0x14,0xf3,0x8a,0x45,0xc5,0x92, +0x62,0x59,0xb1,0xa2,0xb0,0x51,0xda,0x29,0x09,0x4a,0x47,0xa5,0x8b,0x92,0xa8,0x74, +0x57,0x7a,0xac,0xf1,0x57,0xe0,0xa9,0xf4,0x56,0x92,0x94,0xbe,0x4a,0x3f,0x25,0x59, +0x49,0x55,0xd2,0x95,0x0c,0x65,0xb0,0x32,0x44,0x19,0xa6,0x64,0x29,0x39,0xca,0x58, +0x65,0xa2,0x32,0x59,0x99,0xaa,0x4c,0x53,0x66,0x28,0x79,0x4a,0x81,0x52,0xa8,0x14, +0x2b,0x25,0x4a,0x99,0x52,0xa1,0xd4,0x28,0x75,0x4a,0xa3,0xb2,0x46,0x59,0xa7,0x6c, +0x50,0x36,0x2a,0x9b,0x95,0x2d,0xca,0x56,0x65,0x1b,0xd0,0xae,0xec,0x50,0x76,0x2a, +0xbb,0x95,0x3d,0x4a,0x93,0x72,0x40,0x39,0xa4,0x1c,0x56,0x8e,0x28,0x47,0x95,0x63, +0xca,0x87,0xca,0x71,0xe5,0x84,0x72,0x52,0x39,0xa5,0x7c,0xaa,0x9c,0x56,0xce,0x28, +0xcd,0xca,0xb9,0x9f,0x60,0x51,0x3e,0xff,0x9e,0x79,0xe5,0x82,0x72,0x51,0xf9,0x42, +0xb9,0xa4,0xfc,0x4e,0xb9,0xac,0x5c,0x51,0xda,0xa8,0x6c,0x55,0x76,0x2a,0x82,0xca, +0x41,0xe5,0xa8,0x72,0x06,0x5c,0x54,0xae,0x2a,0xa2,0xca,0x4d,0xe5,0xae,0xf2,0x50, +0x79,0xaa,0xbc,0x54,0xde,0x2a,0x1f,0x15,0x49,0xe5,0xab,0xf2,0x53,0x91,0x55,0x14, +0x80,0xaa,0xa2,0xab,0x18,0xaa,0x60,0xd5,0x01,0x55,0x88,0x2a,0x4c,0xc5,0x52,0x71, +0x54,0xb1,0xaa,0x44,0x55,0xb2,0x2a,0x45,0x95,0xaa,0x4a,0x53,0x65,0xa8,0x78,0x2a, +0xbe,0x4a,0xa0,0x12,0xaa,0xc4,0x2a,0x89,0x4a,0xaa,0x92,0xa9,0xe4,0x2a,0x85,0x4a, +0xa3,0xd2,0xa9,0x8c,0xaa,0x1a,0x55,0x9d,0xaa,0x51,0xd5,0xac,0x6a,0x55,0xb5,0xab, +0x3a,0x54,0x9d,0xaa,0x6e,0x55,0x8f,0xca,0xa4,0x1a,0x50,0x0d,0xa9,0x86,0x55,0x23, +0xaa,0x51,0xd5,0x98,0x6a,0x5c,0x35,0xa1,0x9a,0x54,0x4d,0xa9,0xa6,0x55,0x66,0x95, +0x45,0xf5,0xfc,0x47,0xe6,0x55,0x8b,0xaa,0x25,0xd5,0x77,0xaa,0x65,0xd5,0x8a,0xca, +0x46,0x6d,0xa7,0x26,0xa8,0x1d,0xd4,0x8e,0x6a,0x17,0x35,0x51,0xed,0xae,0xf6,0x54, +0x7b,0xab,0x49,0x6a,0x5f,0x35,0x59,0x4d,0x55,0xd3,0xd5,0x0c,0x75,0xb0,0x3a,0x44, +0x1d,0xa6,0x66,0xa9,0x39,0xea,0x98,0xff,0x35,0xc4,0xaa,0x93,0xd5,0x69,0x6a,0x9e, +0x5a,0xa8,0x96,0xa8,0x15,0x6a,0x9d,0xba,0x46,0xdd,0xa8,0x6e,0x55,0x77,0xfc,0x48, +0xa7,0xda,0xa4,0x1e,0x56,0x8f,0xa9,0x27,0xd5,0x66,0xf5,0xa2,0x7a,0x45,0x4d,0xd0, +0x10,0x35,0xde,0x1a,0xb2,0x86,0xa1,0x09,0xd3,0xc4,0x6a,0x52,0x35,0x3c,0x8d,0x58, +0xa3,0xd0,0x18,0x35,0x8d,0x9a,0x76,0x4d,0x8f,0x66,0x48,0x33,0xaa,0x99,0xd0,0x4c, +0x6b,0xe6,0x35,0x8b,0x9a,0x25,0xcd,0x8a,0xc6,0xb6,0xcc,0xae,0x8c,0x50,0xe6,0x58, +0xe6,0x52,0x46,0x2c,0x73,0x2f,0xf3,0x2c,0xf3,0x2e,0x23,0x95,0xf9,0x96,0x91,0xcb, +0xa8,0x65,0xf4,0x32,0x46,0x59,0x70,0x59,0x48,0x59,0x58,0x19,0xab,0x8c,0x53,0x16, +0x5b,0x96,0x58,0x96,0x5c,0x96,0x5a,0x96,0x56,0x96,0x51,0xc6,0x2b,0x13,0x94,0x89, +0xcb,0x64,0x65,0x9a,0x32,0x63,0x59,0x63,0x59,0xcb,0xdf,0x41,0x6b,0x59,0x67,0x59, +0x4f,0x59,0xff,0xcf,0xc2,0x40,0xd9,0xdd,0x7f,0x69,0x86,0x81,0xd1,0xb2,0xf1,0xb2, +0x47,0x7f,0x96,0x89,0xb2,0xc9,0xb2,0xa9,0xb2,0xe9,0x32,0x4b,0xd9,0x7c,0xd9,0x62, +0xd9,0x52,0xd9,0x72,0xd9,0x4a,0x99,0x4d,0xb9,0x5d,0x39,0xa1,0xdc,0xb1,0xdc,0xa5, +0x9c,0x58,0xee,0x5e,0xee,0x59,0xee,0x5d,0x4e,0x2a,0xf7,0x2d,0x27,0x97,0x53,0xcb, +0xe9,0xe5,0x8c,0xf2,0xe0,0xf2,0x90,0xf2,0xb0,0x72,0x56,0x39,0xa7,0x3c,0xb6,0x3c, +0xb1,0x3c,0xb9,0x3c,0xb5,0x3c,0xad,0x3c,0xa3,0x9c,0x57,0x2e,0x28,0x17,0x96,0x8b, +0xcb,0x25,0xe5,0xb2,0x72,0x45,0xb9,0xa6,0x5c,0xfb,0x3d,0xba,0xf2,0xba,0xf2,0xd6, +0xf2,0xee,0xf2,0x81,0xf2,0x91,0xf2,0xf1,0xf2,0xa9,0x72,0x4b,0xf9,0x8b,0x3f,0x60, +0xa9,0x7c,0xb9,0xfc,0xe5,0x1a,0x6b,0xac,0xf1,0x77,0xb2,0x52,0x6e,0xa3,0xb5,0xd3, +0x12,0xb4,0x8e,0x5a,0x17,0x2d,0x51,0xeb,0xae,0xf5,0xd4,0x7a,0x6b,0x7d,0xfe,0x88, +0xbd,0x5a,0x3f,0x2d,0x45,0x4b,0xd3,0x06,0x6a,0x99,0xda,0x03,0xda,0x50,0x6d,0xb8, +0x96,0xad,0x8d,0xd1,0x26,0x68,0x93,0xb4,0x29,0xda,0xd3,0xda,0x74,0x2d,0x57,0xcb, +0xd7,0xe6,0x68,0x45,0xda,0x42,0xad,0x54,0x2b,0xd7,0xaa,0xb5,0x5a,0xad,0x41,0x5b, +0xad,0xad,0xd5,0x36,0x68,0x9b,0xb4,0x2d,0xda,0x36,0x6d,0x87,0xb6,0x4b,0x7b,0x5d, +0xdb,0xa7,0xed,0xd7,0x0e,0x6a,0xef,0x6a,0xef,0x69,0xef,0x6b,0x1f,0x68,0x1f,0x6a, +0x1f,0x69,0x1f,0x6b,0x9f,0x68,0x9f,0x6a,0x67,0xb4,0x73,0xda,0xe7,0xda,0x05,0xed, +0x0b,0xed,0x77,0xda,0x97,0x5a,0xa4,0xb3,0xd5,0xd9,0xeb,0x1c,0x74,0xce,0x3a,0x57, +0x9d,0x9b,0xce,0x43,0xe7,0xa5,0xf3,0xd1,0xed,0xd5,0xf9,0xe9,0x28,0x3a,0x9a,0x2e, +0x50,0xc7,0xd4,0x1d,0xd0,0x85,0xea,0xc2,0x75,0x6c,0x5d,0x8c,0x2e,0x41,0x97,0xa4, +0x4b,0xd1,0x9d,0xd6,0xa5,0xeb,0xb8,0x3a,0xbe,0x2e,0x47,0x27,0xd2,0x15,0xea,0xa4, +0x3a,0xb9,0x4e,0xad,0xd3,0xea,0x0c,0xba,0x6a,0x5d,0xad,0xae,0x41,0xd7,0xa4,0x6b, +0xd1,0xb5,0xe9,0x3a,0x74,0x5d,0xba,0xeb,0xba,0x3e,0x5d,0xbf,0x6e,0x50,0x77,0x57, +0x77,0x4f,0x77,0x5f,0xf7,0x40,0xf7,0x50,0xf7,0x48,0xf7,0x58,0xf7,0x44,0xf7,0x54, +0x37,0xa3,0x9b,0xd3,0x3d,0xd7,0x2d,0xe8,0x5e,0xe8,0xbe,0xd3,0xbd,0xd4,0x21,0xbd, +0xad,0xde,0x5e,0xef,0xa0,0x77,0xd6,0xbb,0xea,0xdd,0xf4,0x1e,0x7a,0x2f,0xbd,0x8f, +0x7e,0xaf,0xde,0x4f,0x4f,0xd1,0xd3,0xf4,0x81,0x7a,0xa6,0xfe,0x80,0x3e,0x54,0x1f, +0xae,0x67,0xeb,0x63,0xf4,0x09,0xfa,0x24,0x7d,0x8a,0xfe,0xb4,0x3e,0x5d,0xcf,0xd5, +0xf3,0xf5,0x39,0x7a,0x91,0xbe,0x50,0x2f,0xd5,0xcb,0xf5,0x6a,0xbd,0x56,0x6f,0xd0, +0x57,0xeb,0x6b,0xf5,0x0d,0xfa,0x26,0x7d,0x8b,0xbe,0x4d,0xdf,0xa1,0xef,0xd2,0x5f, +0xd7,0xf7,0xe9,0xfb,0xf5,0x83,0xfa,0xbb,0xfa,0x7b,0xfa,0xfb,0xfa,0x07,0xfa,0x87, +0xfa,0x47,0xfa,0xc7,0xfa,0x27,0xfa,0xa7,0xfa,0x19,0xfd,0x9c,0xfe,0xb9,0x7e,0x41, +0xff,0x42,0xff,0x9d,0xfe,0xa5,0x1e,0x55,0xd8,0x56,0xd8,0x57,0x38,0x54,0x38,0x57, +0xb8,0x56,0xb8,0x55,0x78,0x54,0x78,0x55,0xf8,0x54,0xec,0xad,0xf0,0xab,0xa0,0x54, +0xd0,0x2a,0x02,0x2b,0x98,0x15,0x07,0x2a,0x42,0x2b,0xc2,0x2b,0xd8,0x15,0x31,0x15, +0x09,0x15,0x49,0x15,0x29,0x15,0xa7,0x2b,0xd2,0x2b,0xb8,0x15,0xfc,0x8a,0x9c,0x0a, +0x51,0x45,0x61,0x85,0xb4,0x42,0x5e,0xa1,0xae,0xd0,0x56,0x18,0x2a,0xaa,0x2b,0x6a, +0x2b,0x1a,0x2a,0x9a,0x2a,0x5a,0x2a,0xda,0x2a,0x3a,0x2a,0xba,0x2a,0xae,0x57,0xf4, +0x55,0xf4,0x57,0x0c,0x56,0xdc,0xad,0xb8,0x57,0x71,0xbf,0xe2,0x41,0xc5,0xc3,0x8a, +0x47,0x15,0x8f,0x2b,0x9e,0x54,0x3c,0xad,0x98,0xa9,0x98,0xab,0x78,0x5e,0xb1,0x50, +0xf1,0xa2,0xe2,0xbb,0x8a,0x97,0x15,0xc8,0x60,0x6b,0xb0,0x37,0x38,0x18,0x9c,0x0d, +0xae,0x06,0x37,0x83,0x87,0xc1,0xcb,0xe0,0x03,0xec,0x35,0xf8,0x19,0x28,0x06,0x9a, +0x21,0xd0,0xc0,0x34,0x1c,0x30,0x84,0x1a,0xc2,0x0d,0x6c,0x43,0x8c,0x21,0xc1,0x90, +0x64,0x48,0x31,0x9c,0x36,0xa4,0x1b,0xb8,0x06,0xbe,0x21,0xc7,0x20,0x32,0x14,0x1a, +0xa4,0x06,0xb9,0x41,0x6d,0xd0,0x1a,0x0c,0x86,0x6a,0x43,0xad,0xa1,0xc1,0xd0,0x64, +0x68,0x31,0xb4,0x19,0x3a,0x0c,0x5d,0x86,0xeb,0x86,0x3e,0x43,0xbf,0x61,0xd0,0x70, +0xd7,0x70,0xcf,0x70,0xdf,0xf0,0xc0,0xf0,0xd0,0xf0,0xc8,0xf0,0xd8,0xf0,0xc4,0xf0, +0xd4,0x30,0x63,0x98,0x33,0x3c,0x37,0x2c,0x18,0x5e,0x18,0xbe,0x33,0xbc,0x34,0x20, +0xa3,0xad,0xd1,0xde,0xe8,0x60,0x74,0x36,0xba,0x1a,0xdd,0x8c,0x1e,0x46,0x2f,0xa3, +0x8f,0x71,0xaf,0xd1,0xcf,0x48,0x31,0xd2,0x8c,0x81,0x46,0xa6,0xf1,0x80,0x31,0xd4, +0x18,0x6e,0x64,0x1b,0x63,0x8c,0x09,0xc6,0x24,0x63,0x8a,0xf1,0xb4,0x31,0xdd,0xc8, +0x35,0xf2,0x8d,0x39,0x46,0x91,0xb1,0xd0,0x28,0x35,0xca,0x8d,0x6a,0xa3,0xd6,0x68, +0x30,0x56,0x1b,0x6b,0x8d,0x0d,0xc6,0x26,0x63,0x8b,0xb1,0xcd,0xd8,0x61,0xec,0x32, +0x5e,0x37,0xf6,0x19,0xfb,0x8d,0x83,0xc6,0xbb,0xc6,0x7b,0xc6,0xfb,0xc6,0x07,0xc6, +0x87,0xc6,0x47,0xc6,0xc7,0xc6,0x27,0xc6,0xa7,0xc6,0x19,0xe3,0x9c,0xf1,0xb9,0x71, +0xc1,0xf8,0xc2,0xf8,0x9d,0xf1,0xa5,0x11,0x55,0xda,0x56,0xda,0x57,0x3a,0x54,0x3a, +0x57,0xba,0x56,0xba,0x55,0x7a,0x54,0x7a,0x55,0xfa,0x54,0xee,0xad,0xf4,0xab,0xa4, +0x54,0xd2,0x2a,0x03,0x2b,0x99,0x95,0x07,0x2a,0x43,0x2b,0xc3,0x2b,0xd9,0x95,0x31, +0x95,0x09,0x95,0x49,0x95,0x29,0x95,0xa7,0x2b,0xd3,0x2b,0xb9,0x95,0xfc,0xca,0x9c, +0x4a,0x51,0x65,0x61,0xa5,0xb4,0x52,0x5e,0xa9,0xae,0xd4,0x56,0x1a,0x2a,0xab,0x2b, +0x6b,0x2b,0x1b,0x2a,0x9b,0x2a,0x5b,0x2a,0xdb,0x2a,0x3b,0x2a,0xbb,0x2a,0xaf,0x57, +0xf6,0x55,0xf6,0x57,0x0e,0x56,0xde,0xad,0xbc,0x57,0x79,0xbf,0xf2,0x41,0xe5,0xc3, +0xca,0x47,0x95,0x8f,0x2b,0x9f,0x54,0x3e,0xad,0x9c,0xa9,0x9c,0xab,0x7c,0x5e,0xb9, +0x50,0xf9,0xa2,0xf2,0xbb,0xca,0x97,0x95,0xa8,0xca,0xb6,0xca,0xbe,0xca,0xa1,0xca, +0xb9,0xca,0xb5,0xca,0xad,0xca,0xa3,0xca,0xab,0xca,0xa7,0x6a,0x6f,0x95,0x5f,0x15, +0xa5,0x8a,0x56,0x15,0x58,0xc5,0xac,0x3a,0x50,0x15,0x5a,0x15,0x5e,0xc5,0xae,0x8a, +0xa9,0x4a,0xa8,0x4a,0xaa,0x4a,0xa9,0x3a,0x5d,0x95,0x5e,0xc5,0xad,0xe2,0x57,0xe5, +0x54,0x89,0xaa,0x0a,0xab,0xa4,0x55,0xf2,0x2a,0x75,0x95,0xb6,0xca,0x50,0x55,0x5d, +0x55,0x5b,0xd5,0x50,0xd5,0x54,0xd5,0x52,0xd5,0x56,0xd5,0x51,0xd5,0x55,0x75,0xbd, +0xaa,0xaf,0xaa,0xbf,0xea,0xff,0x63,0xef,0x4c,0x00,0x74,0xaa,0x1a,0x3e,0x7e,0x9f, +0x67,0xe6,0x99,0x31,0x28,0x84,0x4a,0xb2,0x4e,0x96,0x30,0x63,0x76,0xc6,0x3a,0x86, +0xc7,0x18,0xc2,0xc8,0x96,0xb4,0x18,0xb2,0x65,0xdf,0x97,0x54,0x96,0x44,0xab,0x51, +0xa9,0xb4,0xd2,0x4a,0x2a,0x5b,0x92,0xb2,0x57,0x88,0x94,0x68,0x51,0xa6,0x08,0x49, +0x24,0xa4,0xde,0x37,0xa5,0xfa,0x7e,0x67,0xee,0xff,0xe6,0x78,0x3e,0xde,0xf4,0xd6, +0xdb,0x3a,0xcf,0xf1,0xf3,0x3f,0xe7,0xdc,0x73,0xcf,0x7e,0xce,0x3d,0x77,0x9d,0xa5, +0x53,0x56,0x4e,0x79,0x65,0xca,0xba,0x29,0xaf,0x4f,0xd9,0x34,0xe5,0xed,0x29,0x5b, +0xa7,0xe4,0x4e,0xd9,0x31,0x65,0xf7,0x94,0xbd,0x53,0x3e,0x9f,0x72,0x68,0xca,0x57, +0x53,0xbe,0x99,0x72,0x6c,0x8a,0x93,0x13,0x9e,0x53,0x20,0xa7,0x70,0x4e,0xd1,0x9c, +0x12,0x39,0xe7,0xe6,0x9c,0x9f,0x53,0x3e,0xe7,0x02,0x4c,0xd5,0x9c,0x1a,0x39,0x71, +0x39,0x49,0x39,0xb5,0x73,0xea,0xe5,0xa4,0xe5,0x34,0xc9,0x69,0x96,0x73,0x51,0x4e, +0x56,0x4e,0xbb,0x9c,0x4b,0x72,0x2e,0xcb,0xe9,0x92,0x73,0x55,0x4e,0xaf,0x9c,0xbe, +0x39,0x03,0x73,0x86,0xe6,0x8c,0xcc,0x19,0x93,0x33,0x36,0xe7,0x86,0x9c,0xc9,0x39, +0xb7,0xe6,0xe4,0xe4,0xdc,0x95,0x73,0x6f,0xce,0x03,0xf9,0xe6,0x6f,0x60,0xcc,0xdf, +0x1f,0x2f,0x2f,0x0a,0x84,0x39,0x4e,0xb6,0xec,0xe1,0xd8,0x13,0xd0,0x44,0xb9,0x7d, +0xb8,0x97,0x86,0xb9,0xf6,0x2a,0x68,0x3c,0x3a,0xc0,0x71,0xb5,0x09,0x9e,0x49,0x96, +0xdd,0xdb,0xcf,0xf3,0x6f,0x64,0x12,0x09,0x73,0xd5,0x27,0xf5,0x4b,0xc3,0xa4,0x05, +0xa4,0x05,0xd1,0xc6,0x4a,0x23,0xa8,0xfd,0x82,0xda,0x2f,0xa8,0xfd,0x82,0x0a,0x9f, +0xa9,0xed,0x99,0xda,0x9e,0xa9,0xed,0x99,0xda,0xde,0x4a,0xf1,0xb7,0x56,0xb8,0xd6, +0x0a,0xd7,0x5a,0xe1,0x5a,0x5b,0xdb,0x4d,0xf8,0xf6,0x0a,0xd7,0x5e,0xe1,0xda,0x2b, +0x5c,0x7b,0x6d,0xef,0x24,0xff,0x6c,0x85,0xcb,0xb6,0xdc,0x7e,0x69,0x98,0xd4,0xab, +0x4b,0x53,0x9e,0x6e,0x2a,0x4f,0x77,0xed,0xd7,0x5d,0xfb,0x75,0xd7,0x7e,0xdd,0x15, +0xbe,0xb7,0xb6,0xf7,0xd6,0xf6,0xde,0xda,0xde,0x5b,0xdb,0xfb,0x2b,0xfe,0x01,0x0a, +0x37,0x40,0xe1,0x06,0x28,0xdc,0x00,0x6b,0xbb,0x09,0x3f,0x4c,0xe1,0x86,0x29,0xdc, +0x30,0x85,0x1b,0xa6,0xed,0xa3,0xe4,0x3f,0xca,0xaa,0xff,0x70,0xe5,0x3b,0x5c,0xee, +0x08,0xb9,0x23,0xe4,0xae,0x2a,0x77,0x55,0xb5,0x93,0x4f,0xe5,0xf3,0xc9,0xed,0x97, +0xdb,0x2f,0x77,0xa4,0xdc,0x91,0x72,0x17,0x96,0xdb,0x68,0x13,0xe9,0x55,0xd2,0xa0, +0xd2,0xed,0x2e,0x0d,0x2a,0xdd,0xee,0xd2,0xa0,0xe2,0xe9,0x2e,0x0d,0x2a,0x1f,0xdd, +0xa5,0x41,0xc5,0xd3,0x5d,0x9a,0xa1,0x7c,0xf4,0x94,0x66,0x28,0x9e,0x9e,0xd2,0x0c, +0xc5,0xd3,0x53,0x9a,0xa1,0x76,0xea,0x29,0x6d,0xa6,0xfd,0x7a,0x59,0xfd,0x2a,0x4c, +0xed,0x11,0x26,0x77,0xb8,0xdc,0xe1,0x72,0x47,0xc8,0x1d,0x21,0x77,0x55,0xb9,0xab, +0xca,0x1d,0x29,0x6d,0xee,0xb8,0xfe,0x57,0xcb,0x6e,0xe2,0xbf,0x5a,0xda,0x42,0xe9, +0xf7,0x91,0x5e,0xa4,0xfa,0xed,0x2b,0xbd,0x48,0xfe,0x7d,0xad,0xed,0x85,0xe5,0x2e, +0x2c,0xf7,0x62,0xc7,0x75,0x1b,0x6d,0xa5,0xfd,0xfa,0x4b,0x5b,0x69,0xbf,0xfe,0xd2, +0x56,0xda,0xaf,0xbf,0x74,0xa9,0xdf,0xb5,0xb7,0x56,0xb9,0x06,0x48,0x5b,0xab,0x5c, +0x03,0xa4,0xc6,0x5d,0x48,0x6e,0xa3,0x17,0x2b,0xfe,0xc1,0xd2,0x8b,0x15,0xff,0x60, +0xe9,0xc5,0x8a,0x7f,0xb0,0xb4,0xad,0xc2,0x0d,0x91,0xb6,0x55,0xf9,0x87,0x48,0xdb, +0x6a,0xbf,0x21,0xd2,0xb6,0xda,0x6f,0x88,0xb4,0x9d,0xfc,0x87,0x4a,0xdb,0xc9,0x7f, +0xa8,0xb4,0xbd,0xda,0x69,0x98,0xb4,0xbd,0xca,0x31,0x4c,0xda,0x5e,0xe5,0x18,0x26, +0x6d,0xaf,0xf1,0x3a,0x4c,0xda,0x5e,0xe5,0x1a,0x26,0x6d,0xaf,0x76,0x1c,0x26,0xed, +0xa8,0x7c,0x8e,0x90,0x76,0x92,0x8e,0xb2,0xdc,0x66,0x5c,0x5d,0xaa,0xf2,0x8d,0x96, +0x5e,0xaa,0x7e,0x30,0x5a,0x7a,0xa9,0xf2,0x3b,0xda,0x2a,0x9f,0xa9,0xdb,0xd2,0xaa, +0xdb,0xd2,0x4a,0xbb,0xb4,0xd2,0x2e,0xad,0xb1,0x73,0xa9,0x35,0x8e,0x46,0x5b,0x63, +0x69,0xb4,0xd5,0x0f,0x4c,0xdf,0xba,0x48,0xfd,0xac,0xaf,0xb4,0x95,0xfc,0x5b,0xc9, +0xdd,0x5f,0xda,0x48,0xfb,0x65,0x4b,0x33,0xa5,0xbd,0xa5,0xad,0xa5,0x03,0xac,0xfa, +0x2d,0xac,0x3c,0x15,0xb6,0xe6,0xc9,0x70,0x6b,0x8e,0x09,0xb7,0xfc,0x7d,0x96,0xbf, +0xcf,0xf2,0x2f,0x6c,0xf9,0xdb,0xf1,0x38,0x96,0xbf,0x63,0x1d,0x27,0xc2,0xad,0x39, +0xd6,0x9b,0xa7,0x22,0x2d,0x7f,0xcf,0xbe,0x46,0xed,0xbc,0x47,0x9a,0xa1,0x7c,0xf6, +0x94,0xb6,0x90,0xf6,0xb1,0xca,0x57,0x55,0xe5,0xab,0x6a,0xb9,0xc3,0x2d,0x3f,0x63, +0x5f,0xec,0x73,0xc3,0xdf,0xe1,0x77,0xf5,0x6a,0xab,0x1d,0x4c,0x9b,0x78,0xed,0xe1, +0xb5,0x45,0x86,0xda,0xbd,0xa7,0x35,0xfe,0x1c,0x8d,0x37,0xc7,0x3a,0xee,0xf9,0xac, +0x63,0x86,0x4f,0xf9,0xf7,0x29,0xff,0x46,0xb7,0x4a,0xbf,0xb1,0x8e,0xa3,0x45,0xb4, +0x4f,0x11,0xb9,0x8b,0xc9,0x5d,0x4c,0xf3,0x61,0x11,0xcd,0x87,0x45,0xe4,0x2e,0x26, +0x77,0x31,0xb5,0x6f,0x11,0xb5,0x6f,0x11,0xb9,0x8b,0xc9,0x5d,0x4c,0xe5,0x2f,0xa2, +0xb2,0x17,0x91,0xbb,0x98,0xdc,0xc5,0x34,0x9e,0x8b,0x68,0x3c,0x17,0x91,0xbb,0x98, +0xdc,0xc5,0xd4,0x8e,0x45,0xd4,0x86,0x45,0xe4,0x2e,0x26,0x77,0x31,0x8d,0xe7,0xca, +0xea,0xef,0x95,0x35,0x7e,0x2b,0x6b,0xfc,0x56,0xd6,0xfc,0x5b,0x58,0xf3,0x6f,0x61, +0xab,0x9d,0xb3,0xad,0xf9,0xdf,0x3b,0xae,0x56,0xb1,0x8e,0xe3,0xe1,0xd6,0x31,0x30, +0xdc,0x3a,0xce,0x87,0x5b,0xc7,0x48,0xcf,0x3f,0x52,0x7e,0x91,0x96,0x3b,0xdc,0xf2, +0x0b,0xd7,0x38,0x0e,0xd7,0xb8,0x0e,0x57,0x7e,0x7a,0xf8,0xdd,0x76,0x37,0x65,0x1d, +0x85,0xfd,0x1a,0x18,0xe7,0x77,0xe7,0x82,0x51,0x5a,0x33,0x45,0x68,0xbd,0x14,0x29, +0x2d,0x28,0xad,0x2a,0x0d,0x93,0x9a,0xb9,0xa5,0x9b,0xdf,0x1d,0x9f,0xa6,0x2e,0x46, +0xc2,0x34,0xbf,0xdb,0x37,0x4c,0x3b,0x17,0x0f,0x3b,0x3e,0x66,0x96,0xf8,0xdd,0x7d, +0x82,0xd8,0xeb,0x5a,0x6b,0xb3,0x59,0xd2,0xa9,0x0a,0x67,0xe6,0xfd,0x69,0xb2,0xdf, +0x23,0x9d,0x2e,0x7d,0x58,0xfa,0xb8,0x74,0xb6,0x17,0xb7,0x95,0xce,0x74,0xd9,0x1f, +0x97,0xce,0x97,0xff,0x22,0x2f,0x7e,0x6b,0x1f,0xa3,0xaf,0xda,0x79,0x94,0xdd,0xf3, +0x5b,0x61,0x85,0x31,0xfa,0x9a,0x74,0x01,0xbc,0xa0,0x34,0x36,0xcb,0x6f,0xb3,0xf6, +0x59,0x03,0x2b,0xe1,0x45,0x58,0x05,0xab,0xe1,0x5e,0xa5,0xff,0x28,0x94,0x0c,0x77, +0xeb,0xc7,0xa8,0x09,0x5f,0x3c,0xdc,0xdd,0x3f,0x42,0xee,0xf3,0xe4,0x3e,0x57,0xe1, +0xa2,0xc3,0xdd,0xf6,0x38,0x57,0x5a,0x5b,0x9a,0xac,0xed,0xc9,0xda,0x2f,0x51,0xfb, +0x75,0x90,0xbb,0x8e,0xdc,0xb5,0x15,0xae,0xb1,0xf6,0x1b,0x1a,0xae,0xbe,0x2d,0x3d, +0x5b,0xfe,0x29,0xd2,0xa2,0xd2,0x38,0xcb,0x5d,0x40,0xee,0x02,0xca,0xb7,0x97,0xbe, +0xd1,0xad,0xf2,0x7f,0x5f,0x7a,0xb6,0x34,0x45,0x7a,0x8e,0xb4,0x96,0xd4,0x94,0x23, +0x5c,0xf9,0x0a,0x97,0xbb,0x80,0xdc,0x46,0xcb,0x4a,0x1b,0x48,0xf7,0x4a,0x3f,0x93, +0xc6,0x48,0x5b,0x4a,0xa3,0x15,0x4f,0x63,0x69,0xb4,0xfc,0x1b,0x5b,0xdb,0x0b,0xc9, +0x6d,0xb4,0x8a,0xfc,0x33,0xa4,0xd5,0xa5,0x2d,0xa4,0x3d,0x03,0x8c,0x4b,0x18,0x0f, +0x7d,0x60,0x18,0x54,0x89,0x60,0xcc,0x47,0xb8,0xda,0x0e,0x9a,0x49,0x8d,0xbb,0x3d, +0x34,0xb7,0xdc,0x43,0xb5,0xdd,0xe8,0x5a,0x69,0x73,0xe9,0x3b,0x0a,0xb7,0x4a,0xba, +0x59,0x5a,0x35,0xca,0x71,0xea,0x41,0x9c,0x34,0x51,0x5a,0x52,0x7a,0xb6,0xf4,0x1c, +0xe9,0xf9,0xd2,0x0a,0xd2,0x8a,0xd2,0xea,0xd2,0x9a,0xd2,0xb5,0xb0,0x5c,0xfa,0x1e, +0xcc,0x84,0xa5,0xf0,0x88,0x74,0xae,0x34,0xa1,0x20,0xe1,0xa1,0xb6,0xf4,0x6c,0xe9, +0x39,0xd2,0xf3,0xa5,0xd5,0xa5,0x19,0x85,0xe8,0x67,0x85,0x5c,0x6d,0x20,0xed,0x08, +0x15,0xa0,0x1e,0x54,0x94,0xde,0x01,0xef,0xc1,0x1a,0x58,0x0e,0x6b,0xa5,0x6b,0xe4, +0xdf,0xb4,0x30,0xf1,0xc0,0x0a,0x78,0x07,0xd6,0x58,0xfa,0xae,0x74,0xb5,0xa5,0x66, +0x5b,0xd3,0x33,0x48,0x13,0x32,0xa4,0xc6,0xdd,0x11,0xde,0x87,0xf5,0xd2,0x37,0x2d, +0xf5,0xfc,0xb6,0x43,0xcb,0x33,0x29,0x2b,0x6c,0x84,0x05,0x30,0x07,0xa6,0x4b,0x67, +0x42,0xa1,0x22,0x8e,0x93,0x0e,0x8b,0xe1,0x22,0x69,0x1b,0x69,0x07,0x69,0x67,0x69, +0x1a,0x2c,0x82,0x41,0x30,0x58,0x3a,0x14,0x16,0xc0,0x58,0xe9,0x20,0xd9,0x17,0x5a, +0xea,0xf9,0x79,0x7a,0x87,0xe2,0x7b,0x40,0x3a,0x53,0xfa,0x84,0x74,0x8e,0x34,0x47, +0xe9,0x55,0x2a,0xea,0x38,0xb1,0x90,0x0b,0x81,0xd2,0x8c,0x43,0x88,0x94,0x46,0x49, +0x0b,0x49,0xcf,0x90,0x16,0x93,0xd6,0x91,0xd6,0x93,0x36,0x90,0x36,0x94,0xa6,0x4b, +0xcd,0xf1,0xca,0x1c,0xc3,0xd3,0xb5,0x26,0x30,0xc7,0xab,0xdb,0x7d,0xee,0x7a,0xc0, +0x1c,0xdb,0xbc,0xf3,0x80,0x16,0x5a,0xa3,0xb5,0xd4,0x9a,0xcc,0x1c,0x87,0x2a,0x32, +0xcf,0x67,0x39,0xee,0x31,0xd5,0x1c,0x17,0xcd,0xb1,0xd3,0xac,0x37,0xcd,0xb1,0x2f, +0x8b,0x6d,0x6d,0xc0,0x5f,0xc6,0x71,0xba,0x6a,0x9d,0x61,0x8e,0x81,0x9d,0xf0,0xeb, +0x0c,0x97,0xf9,0xdd,0xb5,0x86,0x59,0xd7,0xf4,0x33,0xf1,0xfb,0xdc,0xe3,0x59,0x3b, +0xfc,0xcf,0x66,0x9f,0x73,0x60,0xa0,0xe3,0x1e,0x67,0xcd,0xb1,0xb8,0x0c,0xee,0x01, +0x6c,0x1b,0x8e,0xbd,0x52,0x19,0x77,0x5e,0x5e,0x08,0xcf,0x69,0x1e,0x5e,0xab,0x35, +0xc1,0x60,0x85,0x37,0xe1,0xbc,0x30,0xab,0xac,0x30,0xf5,0x19,0xfb,0x17,0xfb,0xdd, +0xf3,0xbb,0xf6,0xe8,0x21,0xc7,0xcd,0x4b,0x0f,0xf4,0x4a,0x34,0x1b,0xba,0x43,0x2f, +0xe8,0x6d,0x8e,0x9f,0xe6,0xb8,0x49,0x7a,0x0f,0xa2,0xfd,0x60,0x22,0xf6,0x87,0xd1, +0x41,0x30,0x10,0x06,0xc3,0x10,0x18,0x0a,0xc3,0x60,0x24,0x8c,0x87,0x09,0x30,0x87, +0x32,0xdd,0x84,0xde,0x0c,0xe7,0xb3,0xdf,0x2d,0xe8,0xad,0x7e,0x77,0xbd,0x95,0x83, +0x4e,0xf5,0xbb,0xeb,0xb3,0x17,0xb4,0x6e,0xa8,0xa4,0x75,0x83,0xd1,0x74,0x1d,0x93, +0xbb,0x4a,0x8d,0x3b,0x5a,0xee,0x68,0xb9,0xe3,0xe5,0x8e,0xb7,0xae,0x47,0xf8,0xac, +0x73,0x79,0x9f,0xd6,0x7b,0x91,0x5a,0x73,0x47,0xca,0x1d,0x2d,0x77,0xb4,0xdc,0xf1, +0x72,0xc7,0xcb,0x5d,0x45,0xee,0x2a,0x72,0xc7,0xc8,0x1d,0x63,0x9d,0xff,0x3a,0xd6, +0x39,0xb0,0x63,0xf9,0xfb,0x2c,0x7f,0xef,0x7a,0x48,0x8c,0xfc,0xbc,0xfd,0xe3,0xe4, +0x8e,0xb3,0xd6,0x47,0x11,0xd6,0x1a,0xc9,0xd8,0x9b,0x2a,0xbf,0x3d,0xac,0xf3,0xde, +0x70,0xad,0x4f,0xc3,0xb5,0xee,0x8a,0xd4,0x3a,0x27,0x52,0xee,0x68,0xb9,0xa3,0xe5, +0x2e,0x20,0x77,0x01,0xb9,0xab,0xc8,0xed,0x9d,0x37,0xc7,0xca,0x1d,0xab,0x75,0x65, +0x9c,0xfa,0x50,0x9c,0x75,0x7d,0xc6,0x67,0x5d,0xdb,0xf0,0x69,0x3d,0xee,0xd3,0x7a, +0xdc,0x73,0x47,0xcb,0x1d,0x2d,0x77,0xbc,0xdc,0xf1,0x3a,0xbf,0x89,0xd6,0x79,0x6f, +0xb4,0xe5,0x0e,0xb7,0xfc,0xc2,0xe5,0x1f,0x2f,0x3f,0x6f,0xbf,0x18,0xb9,0x8d,0xb6, +0x54,0x7a,0xfd,0xa4,0x2d,0x55,0xee,0x7e,0xd2,0x96,0x8a,0xab,0x9f,0xb4,0x95,0xfc, +0xfb,0x4b,0x5b,0xc9,0xbf,0xbf,0xb5,0x3d,0x5e,0xee,0x78,0xb9,0x63,0xe4,0x8e,0xb1, +0xd6,0xa3,0x3e,0x6b,0x3d,0xea,0xb3,0xfc,0x0b,0x58,0xfe,0x05,0xc2,0x8e,0x9f,0x87, +0x3b,0xd6,0xb9,0xb8,0x63,0xf9,0xfb,0x2c,0x7f,0x63,0xcf,0x52,0x39,0x06,0x3a,0xc7, +0xdd,0x91,0x72,0x47,0x6a,0x9d,0x1e,0xa9,0x75,0xba,0xe7,0x8e,0x96,0x3b,0xda,0x72, +0x87,0x5b,0x7e,0xe1,0xf2,0x8f,0x97,0x5f,0xbc,0xd6,0xef,0x91,0x5a,0xbf,0x47,0xca, +0x1d,0x2d,0x77,0xb4,0x75,0x7e,0x1f,0x69,0x9d,0xe3,0x47,0x5a,0xe7,0xf1,0x91,0xd6, +0xb9,0xbc,0xbd,0x7f,0xa4,0x15,0x47,0xa4,0xce,0x0b,0x22,0x75,0x5e,0xe0,0xb9,0xa3, +0xe5,0x8e,0x96,0x3b,0x5e,0xee,0x78,0xb9,0x63,0xe4,0x8e,0xd1,0x79,0xc7,0x05,0x3a, +0xef,0xb8,0x40,0xee,0x38,0xb9,0xe3,0xe4,0x8e,0x91,0x3b,0xc6,0xba,0x6e,0xe0,0xb3, +0xae,0x1d,0xf8,0xac,0xeb,0x07,0x05,0xac,0x6b,0x08,0xc6,0xde,0x41,0x61,0x86,0x4b, +0x3b,0x28,0x5f,0xc3,0xa5,0x1d,0x75,0x9e,0x37,0x42,0xda,0x51,0x75,0x31,0x42,0xda, +0x51,0x63,0x60,0x84,0xb4,0xa3,0xca,0x39,0x42,0xda,0x51,0xf1,0x8c,0x90,0x5e,0x22, +0xff,0x91,0xd2,0x4b,0xb4,0xdf,0x48,0xeb,0x3a,0x65,0xa4,0xce,0x57,0xbc,0xeb,0x0b, +0x7e,0x5d,0x5f,0xf0,0xcb,0x1d,0x2d,0x77,0xb4,0xdc,0xf1,0x72,0xc7,0x6b,0xdc,0x7a, +0xf5,0xe9,0xe5,0xab,0xa0,0xe2,0x2b,0xa8,0x79,0x74,0x39,0x73,0xeb,0xf5,0x3e,0x37, +0xfe,0x46,0x8a,0x27,0x5b,0x6a,0xdc,0x51,0x72,0x47,0x59,0xd7,0x7b,0xed,0x6b,0xa5, +0xf6,0x75,0x60,0xc7,0xf2,0x77,0x2c,0xff,0x28,0xcb,0xdf,0x8e,0x27,0xcc,0xf2,0x0f, +0xb3,0xd2,0xf7,0x5b,0x79,0xf0,0x5b,0xd7,0x2f,0x7d,0xd6,0x35,0x4c,0x9f,0xe5,0xef, +0x58,0xfe,0x8e,0xe5,0x1f,0x65,0xf9,0x47,0x59,0xfe,0x61,0x96,0xbf,0x9d,0x6e,0x84, +0x95,0xae,0x77,0x9d,0x32,0x5a,0x73,0x6e,0xb4,0xdc,0x51,0x72,0x47,0xc9,0x1d,0x26, +0x77,0x98,0x75,0x5d,0xdb,0xbe,0x26,0x6c,0x5f,0xef,0x76,0x2c,0x7f,0xc7,0xf2,0x8f, +0xb2,0xfc,0xa3,0x2c,0xff,0x30,0xcb,0x3f,0xcc,0xca,0x8f,0xdf,0xca,0x93,0x77,0x3d, +0x33,0x4a,0x73,0x70,0x94,0xdc,0xd1,0x72,0x47,0x6b,0x7e,0x89,0xd6,0xdc,0xe2,0xb9, +0xa3,0xe4,0x8e,0xb2,0xae,0xa3,0xdb,0xd7,0xa0,0xed,0xeb,0xeb,0x8e,0xe5,0xef,0x58, +0xfe,0x51,0x96,0xbf,0x1d,0x4f,0x98,0xe5,0x1f,0x66,0xa5,0xef,0xb7,0xf2,0xe0,0x5d, +0xb7,0x2f,0x6d,0xa5,0x5b,0xda,0x4a,0xb7,0xb4,0x95,0x6e,0x69,0x2b,0xdd,0xd2,0x56, +0xba,0xa5,0xad,0x74,0x4b,0x5b,0xe9,0x96,0xb6,0xd2,0x35,0xf6,0x68,0xcb,0x3f,0x5a, +0xe3,0x3f,0x5a,0x63,0xdf,0x73,0x47,0xc9,0x1d,0x65,0x5d,0xa3,0xf3,0x59,0xd7,0xe9, +0x7c,0x96,0xbf,0x63,0xf9,0x3b,0x96,0x7f,0x94,0xe5,0x6f,0xc7,0x13,0x66,0xf9,0x87, +0x59,0xfe,0xd1,0x96,0x7f,0xb4,0xc6,0xbb,0xa3,0xf1,0xe9,0xc8,0x1d,0x2d,0xb7,0xb7, +0x3d,0x4a,0xee,0x28,0xb9,0xc3,0xe4,0x0e,0xd3,0xb9,0x7d,0x71,0x69,0x09,0xcb,0xed, +0x58,0x7e,0x8e,0xe5,0xef,0xb3,0xfc,0x7d,0x96,0x7f,0xba,0xe5,0x9f,0xae,0x6b,0x11, +0xc5,0xa5,0x25,0x2c,0xb7,0x63,0xf9,0x39,0x96,0xbf,0xcf,0xf2,0xf7,0x59,0xfe,0xe9, +0x96,0x7f,0xba,0xae,0x01,0x14,0x97,0x96,0xb0,0xdc,0x8e,0xe5,0xe7,0x58,0xfe,0x3e, +0xcb,0xdf,0xd8,0xa7,0xc9,0x7f,0x9a,0xfc,0xa6,0x59,0xfb,0x4f,0xb3,0xf6,0x9f,0x66, +0xed,0x3f,0xcd,0xda,0x7f,0xb1,0xfc,0x17,0xcb,0x6f,0xb1,0xb5,0xff,0x62,0x6b,0xff, +0xc5,0xd6,0xfe,0x8b,0x4f,0xb2,0x7f,0xba,0xe5,0x9f,0xae,0xeb,0x34,0xc5,0xa5,0x25, +0x2c,0xb7,0x63,0xf9,0x39,0x96,0xbf,0xcf,0xf2,0xf7,0x59,0xfe,0xe9,0x96,0x7f,0xba, +0xae,0xc7,0x14,0x97,0x96,0xb0,0xdc,0x8e,0xe5,0xe7,0x58,0xfe,0x3e,0xcb,0xdf,0x67, +0xf9,0xa7,0x5b,0xfe,0xe9,0xba,0x46,0x54,0x5c,0x5a,0xc2,0x72,0x3b,0x96,0x9f,0x63, +0xf9,0xfb,0x2c,0x7f,0x9f,0xe5,0x9f,0x6e,0xf9,0xa7,0xeb,0x7a,0x51,0x71,0x69,0x09, +0xcb,0xed,0x58,0x7e,0x8e,0xe5,0xef,0xb3,0xfc,0xbd,0xeb,0x5b,0xc5,0xa5,0x25,0x2c, +0xb7,0x63,0xf9,0x39,0x96,0xbf,0xcf,0xf2,0xf7,0xae,0x53,0x15,0x97,0x96,0xb0,0xdc, +0x8e,0xe5,0xe7,0x58,0xfe,0x3e,0xcb,0xdf,0xde,0x3f,0xdd,0xf2,0x4f,0xd7,0x75,0xae, +0x12,0x96,0x3a,0x96,0xdd,0x67,0xd9,0xd3,0x75,0x8d,0xac,0xb8,0xb4,0x84,0xe5,0x76, +0x2c,0x3f,0xc7,0xf2,0xf7,0x59,0xfe,0x3e,0xcb,0x3f,0xdd,0xf2,0x4f,0xd7,0xb5,0xbe, +0xe2,0xd2,0x12,0x96,0xdb,0xb1,0xfc,0x1c,0xcb,0xdf,0x67,0xf9,0xfb,0x2c,0xff,0x74, +0xcb,0xdf,0x1b,0xf7,0x4e,0xc8,0x75,0x42,0x27,0xe4,0x7a,0xa1,0x13,0x72,0xdd,0xd0, +0xb1,0xae,0x1f,0xae,0xb0,0xda,0xd4,0xab,0x43,0x27,0xe4,0x9a,0xa1,0x63,0x5d,0x3b, +0xf4,0xe6,0x9c,0xa0,0x35,0xe7,0x04,0x43,0xe6,0xae,0x60,0xc8,0xfc,0x15,0x0c,0x99, +0xc3,0x82,0x21,0xf3,0x58,0x30,0x64,0x2e,0x0b,0x86,0xcc,0x67,0x41,0x6b,0x4e,0x0a, +0x5a,0x73,0x52,0x30,0x64,0x6e,0x0b,0x86,0xcc,0x6f,0xc1,0x90,0x39,0x2e,0x18,0x32, +0xcf,0x05,0x43,0xe6,0xba,0x60,0xc8,0x7c,0x17,0xb4,0xe6,0x8c,0xa0,0x35,0x67,0x04, +0x43,0xe6,0x9e,0x60,0xc8,0xfc,0x13,0x0c,0x99,0x83,0x82,0x21,0xf3,0x50,0x30,0x64, +0x2e,0x0a,0x86,0xcc,0x47,0x41,0x6b,0x4e,0x09,0x5a,0x73,0x4a,0x30,0x64,0x6e,0x0a, +0x86,0xcc,0x4f,0xc1,0x90,0x39,0x2a,0x18,0x32,0x4f,0x05,0x43,0xe6,0xaa,0x60,0xc8, +0x7c,0x15,0xb4,0xfa,0x6f,0xd0,0xea,0xbf,0xc1,0x90,0x71,0x10,0x0c,0x19,0x0b,0xc1, +0x90,0xf1,0x10,0x0c,0x19,0x13,0xc1,0x90,0x71,0x11,0x0c,0x19,0x1b,0x41,0xab,0x7f, +0x07,0xad,0xfe,0x1d,0x0c,0x19,0x27,0xc1,0x90,0xb1,0x12,0x0c,0x19,0x2f,0xc1,0x90, +0x31,0x13,0x0c,0x19,0x37,0xc1,0x90,0xb1,0xe3,0xf5,0xb3,0x08,0x69,0xb8,0x35,0x9e, +0xbc,0x6d,0x41,0x6b,0x6c,0x79,0xf6,0x74,0x4b,0xbd,0x3e,0x13,0x21,0x0d,0x97,0x3a, +0xd6,0x3d,0x81,0xa9,0x0a,0x67,0xee,0x19,0x78,0xc7,0x03,0xcf,0x6e,0x34,0x5d,0xf7, +0x11,0xd2,0xad,0xf1,0xea,0xf5,0x89,0xa0,0x35,0x76,0x3d,0x7b,0xba,0xa5,0x41,0x1d, +0x23,0xbd,0xe3,0xa6,0x77,0x3c,0x72,0xac,0xfb,0x0f,0xf7,0x28,0xdc,0x8a,0x72,0x1a, +0xeb,0xe5,0x34,0xf6,0xcb,0x1d,0x3f,0xb6,0x44,0x48,0xc3,0xad,0xfb,0x08,0x4e,0xc8, +0xbd,0x89,0x25,0xd6,0xb1,0xa8,0x80,0x75,0xfc,0x88,0x90,0x86,0x4b,0x1d,0xeb,0x9e, +0xc7,0x0f,0x4a,0xf3,0x87,0x72,0xc7,0xdd,0xde,0xfc,0x1c,0x21,0x0d,0xb7,0xee,0x59, +0x38,0x21,0xf7,0x34,0x56,0xa9,0xfd,0x56,0x59,0xc7,0x84,0x74,0x2b,0x8c,0x37,0xbf, +0x47,0x48,0xc3,0xa5,0x8e,0x75,0x9f,0x65,0xa6,0xf6,0x9d,0xa5,0x75,0x9a,0x77,0xcf, +0xa6,0x8b,0x73,0x7c,0x7e,0xf3,0xfa,0x64,0xd0,0x9a,0xeb,0x3c,0x7b,0xba,0xa5,0x41, +0x1d,0xb3,0x1c,0xeb,0x7e,0xce,0x6c,0x6b,0xee,0xf6,0xdc,0x26,0xdc,0x73,0xba,0x4f, +0x64,0xd2,0xf6,0x63,0x09,0x2b,0x7f,0xfc,0x99,0x9f,0xff,0x44,0x51,0x85,0x4b,0x64, +0xbf,0x58,0xe7,0xe4,0x98,0xed,0x09,0xe5,0xff,0x3f,0xc9,0x27,0xa1,0x82,0xe3,0x62, +0xf6,0x09,0x10,0x67,0x43,0xe7,0x38,0xde,0xb6,0x86,0x27,0x89,0xcf,0x84,0x8f,0xd3, +0xf3,0x12,0xe6,0x79,0xa2,0x64,0x48,0x81,0x5a,0x50,0x1b,0x52,0xa1,0x3a,0x9c,0x55, +0xd1,0x71,0xea,0x9b,0xfb,0x6b,0x70,0xa1,0xee,0x6b,0xc7,0xe9,0xb9,0x24,0xef,0x99, +0xa4,0x5f,0xb2,0x7f,0xb6,0xae,0xab,0x0e,0xd0,0x3d,0x39,0x73,0x7d,0xb5,0x97,0xae, +0xab,0xf6,0xd5,0xb5,0x55,0x93,0xc6,0x40,0xdd,0xb7,0x33,0xe7,0xcb,0xde,0xfd,0xbf, +0xd1,0xba,0x76,0x3b,0x44,0xf1,0xd4,0x74,0xdc,0x6b,0x87,0x9e,0xdd,0xf8,0x9b,0xeb, +0x8a,0xf3,0xa4,0xdd,0xe4,0x3f,0xc0,0xb2,0x9b,0x35,0x7e,0x8e,0xcf,0x0d,0x63,0xae, +0xd9,0xf5,0xd4,0x75,0x63,0x8f,0xbc,0xeb,0x6d,0x3e,0xf7,0xbc,0x2d,0x53,0xd7,0x90, +0xfb,0xea,0x1a,0x72,0x2b,0xc5,0x65,0xae,0xfd,0xb4,0x51,0x5e,0x3c,0xda,0xea,0x5a, +0x73,0x3b,0x5d,0x93,0xbe,0x48,0xf6,0x96,0xba,0x7f,0x3d,0x5b,0xd7,0x04,0x5a,0x38, +0xc7,0xef,0x4d,0xa7,0x2b,0x9f,0xdd,0xb5,0x4f,0x53,0x85,0x37,0x69,0x6c,0x0a,0x38, +0xce,0x5b,0xb0,0x19,0xb6,0x04,0xdc,0x76,0x6a,0xaa,0x7d,0xcd,0xb5,0x89,0x95,0xba, +0x56,0x7c,0x27,0xcc,0x80,0x62,0x15,0xdd,0x6b,0x9f,0xde,0x75,0x6b,0xef,0x39,0x18, +0xef,0xf9,0xb1,0x5a,0x96,0x3d,0xd5,0xb2,0xc7,0x5b,0xed,0x69,0xdc,0x89,0x6a,0x57, +0xcf,0xee,0xf9,0x27,0x5b,0xfe,0xc9,0xd6,0xb3,0x68,0xc9,0x6a,0x7f,0xcf,0xee,0x85, +0x4f,0x51,0x9f,0xf0,0xec,0x9e,0x7f,0x6d,0x6b,0xdf,0xda,0x56,0x98,0xda,0xea,0x3b, +0x9e,0xdd,0x0b,0xef,0xb5,0xc3,0xc9,0xe8,0x60,0x91,0x69,0x69,0xa8,0xdd,0xe3,0x12, +0x8b,0x4c,0x4b,0xbd,0x76,0x6e,0xac,0x7b,0x0a,0x2d,0x55,0x7f,0xa7,0x62,0xb8,0x45, +0x6f,0x4b,0x43,0xed,0x1e,0x23,0x2d,0x7a,0x5b,0xda,0x5b,0x7d,0xab,0x9b,0xda,0xad, +0x9f,0xda,0xc2,0xab,0xfb,0x1c,0x06,0x6f,0x6d,0xf3,0x4c,0x84,0xf4,0x2e,0xe9,0x26, +0xe9,0xdb,0xd2,0xcd,0xd2,0xb0,0x8a,0xae,0x16,0x90,0x16,0x92,0x46,0x4b,0x2b,0x49, +0xab,0x57,0xfc,0xff,0xc4,0x9e,0x84,0x7a,0x0a,0xdf,0x58,0x1a,0x94,0x36,0x93,0x9a, +0x71,0x6d,0x34,0x5b,0xee,0x96,0xd2,0x7a,0xf2,0x6f,0x20,0xbd,0x4a,0xfe,0xdd,0xa5, +0x83,0xa5,0x43,0xa4,0xc3,0xa5,0x23,0xa4,0xa3,0xa5,0xd7,0x48,0xc7,0x4b,0x27,0x48, +0x6f,0x94,0x4e,0x92,0x3e,0x22,0x9d,0x25,0x9d,0x2d,0x9d,0x23,0x1d,0x23,0xbd,0x56, +0x3a,0x55,0x7a,0x87,0x74,0x81,0x74,0xa1,0xf4,0x39,0xe9,0x22,0xaf,0x3e,0x69,0x94, +0xa8,0xb8,0xd3,0x9b,0xf3,0xec,0xf1,0x14,0x6f,0xcd,0x93,0xf1,0xce,0xf1,0xf1,0xe4, +0x3d,0xd7,0xe9,0x8d,0x17,0x6f,0x7c,0x78,0x63,0xd4,0xeb,0xff,0xa9,0xda,0x37,0x4e, +0xf3,0x67,0xbc,0xe6,0xd0,0xaa,0xf2,0xf7,0xec,0x89,0x96,0x3d,0xc9,0xb2,0x27,0x5b, +0xf6,0x14,0xcb,0x5e,0xcb,0xb2,0xd7,0xb6,0xec,0xa9,0x96,0xdd,0x2b,0x87,0xed,0x8e, +0x0f,0x71,0x27,0x84,0xb8,0x13,0x43,0xdc,0x49,0x21,0xee,0xe4,0x10,0x77,0x4a,0x88, +0xbb,0x56,0x88,0xbb,0x76,0x88,0x3b,0x35,0xa4,0xfc,0x5e,0xfe,0xe2,0x75,0xdc,0x4c, +0x90,0x26,0x4a,0x93,0xa4,0xc9,0xd2,0x14,0x69,0x2d,0x69,0x6d,0x69,0xaa,0xd4,0x2b, +0x73,0xac,0x55,0xde,0x58,0xab,0xac,0xb1,0x56,0x39,0x63,0xad,0x32,0xc6,0x5a,0xe5, +0x8b,0xb5,0xca,0x16,0x6b,0x95,0x2b,0xd6,0x2a,0x53,0xac,0x55,0x9e,0x58,0xab,0x2c, +0xb1,0x2a,0x5b,0xb6,0x55,0xce,0xae,0x96,0xbd,0x9b,0x65,0xbf,0xca,0xb2,0x77,0xb7, +0xec,0x3d,0x2c,0x7b,0x4f,0xcb,0xde,0xcb,0xb2,0xf7,0xb6,0xec,0x57,0x5b,0xf6,0x3e, +0x96,0xbd,0xaf,0x65,0xef,0x67,0xd9,0xfb,0x5b,0xf6,0x01,0x96,0x7d,0xa0,0x65,0x1f, +0x64,0xd9,0x07,0x5b,0xf6,0x21,0x96,0x7d,0xa8,0x65,0x1f,0x66,0xd9,0x87,0x5b,0xf6, +0x11,0x96,0x7d,0xa4,0x65,0x1f,0x65,0xd9,0x47,0xcb,0xde,0xc8,0x39,0x7e,0x3c,0x6d, +0x62,0x1d,0x4f,0x4f,0xe7,0xbe,0xb0,0x7d,0x3c,0x6f,0x6b,0xdd,0x1b,0xee,0xa0,0xfb, +0xc3,0xe6,0x38,0xd1,0x49,0xc7,0xf1,0x6c,0xb5,0x49,0x37,0xeb,0x58,0xdb,0x43,0x75, +0xdd,0xcb,0x3a,0xee,0x86,0xae,0x67,0x06,0xa8,0x8e,0x06,0xa9,0x4e,0x86,0x58,0xf7, +0x8a,0x87,0xab,0xac,0x23,0xad,0x75,0x8e,0xe9,0x0f,0xa1,0x73,0x74,0x1d,0xc7,0xa5, +0xfe,0x29,0xf8,0xb0,0x9a,0x3b,0x5f,0x5d,0xad,0xbc,0x67,0xc7,0x38,0xce,0x46,0x32, +0xf2,0xf0,0xc3,0x6e,0x61,0xab,0x42,0x0a,0x34,0x84,0x4e,0x30,0x11,0x6e,0x85,0x19, +0xf0,0xa2,0xf1,0xa7,0x12,0xba,0x43,0x1f,0x18,0x0f,0x77,0xc3,0x1c,0xd8,0x01,0x5f, +0xab,0x82,0xee,0x87,0xa3,0x50,0x92,0x8a,0x3a,0x0f,0x6a,0x43,0x23,0xb8,0x0c,0x7a, +0xc3,0x78,0x78,0x1e,0xd6,0xc1,0x2e,0x78,0x8f,0x8c,0x94,0xa3,0x12,0xf7,0x53,0x89, +0x7e,0x2a,0xb1,0x20,0x94,0x84,0x2a,0x30,0x04,0xb2,0x3a,0x3b,0xce,0x58,0xf8,0x06, +0x8a,0x5c,0xe6,0x38,0x15,0xa1,0x36,0xf4,0x87,0x41,0xb0,0xed,0x72,0xc7,0xf9,0x04, +0x0e,0xc3,0x0f,0x30,0xf8,0x0a,0xea,0x07,0xae,0x87,0xaf,0xe0,0x07,0x28,0x74,0x25, +0xe7,0x11,0x90,0x05,0xd9,0x30,0x04,0x5e,0x86,0x02,0x34,0x54,0x0a,0xb4,0x80,0x9a, +0x34,0x54,0x12,0x4c,0x82,0x7b,0xe0,0x31,0x58,0x02,0x3b,0xe0,0x13,0x38,0x44,0x23, +0x16,0xa0,0x11,0xab,0x42,0x79,0xea,0xac,0x2b,0x8c,0x82,0x85,0xb0,0x01,0xde,0x86, +0x6d,0x50,0x84,0x46,0x2d,0x01,0x49,0xd0,0x87,0x06,0xad,0x46,0x63,0xa6,0x40,0x5d, +0x68,0x08,0x19,0xd0,0x09,0x3a,0xc3,0xd3,0x70,0x03,0x0d,0x7d,0x13,0xe4,0xd2,0xd8, +0x7b,0xe0,0x5c,0x1a,0xbc,0x1c,0x54,0x85,0x38,0xb8,0x05,0xee,0x80,0xe1,0x74,0x82, +0x6b,0xe1,0x59,0x58,0x01,0x5f,0xc0,0x36,0x3a,0xc5,0x4e,0x38,0x02,0x75,0xe8,0x18, +0x2f,0xc0,0x72,0x18,0x4a,0x07,0xd9,0x00,0x47,0x61,0xc8,0x18,0xea,0x0e,0x52,0xae, +0xa7,0x0f,0xc3,0xcd,0xb0,0x0c,0x7c,0x63,0x1d,0xa7,0x30,0x9c,0x05,0x89,0x70,0x3d, +0xdc,0x04,0xbb,0xc6,0x39,0xce,0x3e,0x38,0x02,0xc7,0xa0,0xf0,0x78,0xc7,0x29,0x0d, +0xe5,0xa0,0x3f,0x0c,0x86,0x91,0xd0,0xf2,0x46,0xca,0x07,0x69,0x93,0x19,0x2f,0xd0, +0x0d,0xae,0xbb,0x89,0xfc,0xc2,0x66,0x70,0x6e,0x66,0x5e,0xbb,0x95,0x31,0x06,0xed, +0x61,0x24,0x3c,0x08,0x57,0xdd,0x46,0x3f,0x87,0x85,0x30,0xe7,0x76,0xc7,0x59,0x0f, +0xf7,0x4f,0x61,0xbd,0x0d,0x8b,0x60,0x6a,0x0e,0x63,0x71,0xaa,0xe3,0xac,0x81,0xd7, +0xe1,0x2d,0x18,0x31,0x8d,0x3e,0x00,0xe7,0xdf,0x4d,0xdf,0x81,0x25,0xb0,0x17,0xda, +0xdc,0xe3,0x38,0x57,0x40,0x57,0xe8,0x0d,0x1b,0xe0,0x00,0x1c,0x01,0xdf,0xbd,0x1c, +0xef,0x61,0x1b,0x6c,0x87,0xbb,0xa7,0x73,0x5e,0x0a,0x4f,0xc3,0xac,0xfb,0x1c,0x67, +0x2b,0x6c,0x87,0x4a,0xf7,0xd3,0xf6,0x90,0x00,0xf5,0xe0,0x52,0xf8,0xe4,0x01,0xc6, +0xdd,0x43,0xd4,0x09,0x3c,0x0e,0x2f,0xc1,0xcb,0xb0,0x11,0xde,0x82,0xa3,0xf0,0x3d, +0x9c,0xc9,0xb8,0x29,0x0e,0xe5,0xa1,0x2e,0x34,0x87,0x8b,0xe1,0x36,0x78,0x00,0x66, +0x3c,0xec,0x9e,0x47,0x9d,0x15,0xe7,0x8e,0x81,0x26,0x10,0x84,0x16,0xb8,0xa7,0x43, +0x4b,0x69,0x6b,0x69,0x1b,0x69,0x5b,0x69,0x7b,0x69,0x47,0x69,0x27,0x69,0x67,0xe9, +0xe5,0xd2,0x2b,0xa5,0xd9,0xd2,0xab,0xa4,0x3d,0xa4,0xbd,0xa4,0x03,0x2c,0xbd,0x0f, +0x06,0xcb,0x3d,0x58,0xee,0x61,0x72,0x0f,0x93,0x7b,0xa4,0xdc,0x23,0xe5,0xbe,0x46, +0xee,0x6b,0xe4,0x6e,0x2a,0xb7,0x29,0xa3,0xa7,0xc6,0xff,0x41,0xf9,0x4f,0x86,0x9b, +0x61,0x8e,0xdc,0xcf,0x48,0xe7,0x4a,0xe7,0x4b,0x17,0x4a,0x17,0x49,0x17,0x4b,0x97, +0x48,0x5f,0x92,0x2e,0x93,0xae,0x90,0xae,0x92,0xbe,0x22,0x5d,0x23,0x5d,0x27,0x7d, +0xd3,0x52,0x93,0xaf,0xcd,0x72,0x6f,0x96,0xfb,0x1d,0xb9,0xdf,0x91,0x7b,0xab,0xdc, +0x5b,0xe5,0xde,0x26,0xf7,0x36,0xb9,0x9f,0x90,0xfb,0xa0,0xf4,0x90,0xf4,0xb0,0xf4, +0x4b,0xe9,0xf7,0x56,0xb9,0x4c,0x5e,0x9c,0x62,0xf4,0x47,0x78,0x0a,0xfc,0xf0,0x34, +0x3c,0x03,0x61,0x10,0x0e,0x01,0x98,0x07,0xf3,0x61,0x01,0x2c,0x84,0xe7,0x60,0x11, +0x9c,0x07,0x11,0x10,0x09,0x05,0xa0,0x02,0x44,0x41,0x41,0x28,0x04,0x85,0xe1,0x0c, +0x38,0x13,0x8a,0x40,0x51,0x28,0x06,0x67,0x41,0x36,0x74,0x85,0x6e,0x70,0x15,0x74, +0x87,0x1e,0xd0,0x13,0x7a,0x41,0x6f,0xb8,0x1a,0xfa,0x40,0x5f,0xe8,0x07,0xfd,0x61, +0x00,0x0c,0x84,0x41,0x30,0x18,0x86,0xc0,0x50,0x18,0x06,0x5d,0xa0,0x04,0x94,0x84, +0xb5,0xb0,0x0e,0x5e,0x87,0x37,0x60,0x0b,0xbc,0x07,0xef,0xc3,0xf9,0xf0,0x21,0x6c, +0x87,0x32,0x50,0x16,0xca,0x43,0x45,0x88,0x86,0x2a,0x70,0x21,0x54,0x87,0x1a,0x10, +0x03,0xb1,0x50,0x13,0x12,0x20,0x05,0xd2,0x20,0x03,0x2e,0x82,0xc3,0xf0,0x25,0x74, +0x84,0x4b,0xa0,0x13,0xdc,0x00,0x13,0x61,0x32,0x4c,0x85,0x3b,0xe0,0x2e,0x78,0x08, +0x66,0x16,0x73,0x8f,0x69,0xe6,0xf8,0x15,0x05,0xdb,0x38,0xce,0x14,0x44,0x63,0xa0, +0x10,0x24,0x0c,0x73,0x8f,0x71,0xa5,0xc0,0x07,0x17,0x72,0xac,0x89,0xeb,0xe8,0x1e, +0xe7,0xcc,0xba,0xc1,0xb4,0x99,0xb7,0x86,0xf0,0x5b,0xf6,0x30,0xcb,0x1e,0xb0,0xec, +0x11,0x96,0x3d,0xd2,0xb2,0x47,0x59,0xf6,0x42,0x96,0xbd,0xb0,0x65,0x3f,0xd3,0xb2, +0x17,0xb1,0xec,0x45,0x2d,0x7b,0x31,0xcb,0x7e,0x96,0x65,0x77,0xd4,0xce,0x76,0x5e, +0xb3,0x43,0xf2,0x9b,0x1d,0x92,0xe7,0xec,0x90,0x7c,0x67,0x87,0xe4,0x3d,0x3b,0x24, +0xff,0xd9,0x21,0x65,0xc8,0x0e,0x29,0x47,0x76,0x48,0x59,0xb2,0x43,0xca,0x93,0x1d, +0x52,0xa6,0xec,0x90,0x72,0x65,0x87,0x94,0x2d,0x34,0xfe,0xfe,0x21,0xe9,0xf7,0x56, +0xbf,0x37,0xfd,0x79,0xce,0x49,0xb6,0x9d,0x15,0xb2,0x8f,0xe9,0x07,0x9e,0xfd,0x56, +0xcb,0x1e,0x65,0xd9,0x4d,0xff,0xf0,0xec,0x77,0x59,0xfe,0xfd,0xda,0x58,0x75,0x69, +0xf9,0xf7,0xb1,0xfc,0x2f,0xb7,0xfc,0xcd,0x3c,0xef,0xd9,0xcd,0x7a,0xe1,0xa7,0xf0, +0x03,0xad,0x73,0xb0,0xbe,0xc7,0xed,0x55,0xad,0x30,0xe6,0x58,0xe7,0xd9,0xcd,0x9a, +0xc8,0xb3,0x9b,0xf5,0x87,0x67,0xaf,0xd6,0xcb,0xca,0xbf,0xb5,0x6f,0x83,0x51,0xc7, +0xed,0x67,0xb4,0xb3,0xd6,0xc2,0x83,0x8f,0xdb,0x67,0xde,0x6a,0xe5,0xd9,0x0a,0xff, +0xdc,0xc5,0xc7,0xed,0xbb,0xac,0xb2,0x8c,0xb1,0xe2,0xe9,0xd1,0xd9,0x0a,0x33,0xfc, +0xb8,0xdd,0xd7,0xfa,0xb8,0x7d,0xad,0x15,0x7f,0x3b,0xab,0x1e,0xfa,0x59,0x69,0x15, +0xb3,0xc2,0x9b,0x75,0x86,0x67,0x3f,0x22,0x7b,0x6b,0x16,0xd6,0x63,0xae,0x70,0xd7, +0x61,0x53,0xae,0x71,0xd7,0xde,0xde,0x35,0xb3,0x04,0xeb,0x5c,0x2b,0xc1,0x3a,0xd7, +0x4e,0xd0,0x79,0x56,0x82,0x73,0xfc,0x3a,0x54,0x8a,0xb4,0x96,0xb4,0xb6,0x34,0x55, +0xfb,0xc4,0x59,0xe7,0xdb,0x89,0x56,0x5c,0x89,0xd6,0xf9,0x7b,0xa2,0xe2,0x73,0x34, +0x6f,0x87,0x69,0xae,0xf6,0xe6,0xe3,0x28,0x6b,0x0e,0x3e,0xd9,0xfc,0xeb,0x8d,0x4d, +0x6f,0x4c,0x7a,0x63,0xd1,0x1b,0x83,0xde,0xd8,0xf3,0xc6,0x9c,0x37,0xd6,0xbc,0x31, +0xe6,0x8d,0x2d,0x6f,0x4c,0x79,0x63,0xc9,0x1b,0x43,0xde,0xd8,0x39,0x2b,0x24,0xdc, +0x62,0xa5,0xed,0x8d,0x93,0xfe,0x8a,0x73,0xa8,0xb4,0xff,0x49,0xe6,0x46,0xd3,0xe7, +0x4d,0x5f,0x37,0x7d,0xdc,0xf4,0x6d,0xd3,0xa7,0x4d,0x5f,0x36,0x7d,0xd8,0xf4,0x5d, +0xd3,0x67,0x4d,0x5f,0x35,0x7d,0xd4,0xf4,0x4d,0xd3,0x27,0x4d,0x5f,0x34,0x7d,0xd0, +0xf4,0x3d,0xd3,0xe7,0x4c,0x5f,0x33,0x7d,0xcc,0xf4,0x2d,0xd3,0xa7,0xb6,0xa2,0xb5, +0x86,0xb9,0xeb,0xf8,0xde,0xac,0xeb,0xaa,0x11,0xef,0x40,0xe2,0xdc,0x4b,0x5c,0x81, +0x7b,0xdd,0xbe,0x30,0x1d,0xbf,0x6e,0x7d,0x4e,0x9c,0x9b,0xf7,0xb0,0x8e,0x3f,0x42, +0xb8,0xba,0x70,0x4f,0x67,0xb7,0xef,0x99,0x3e,0x67,0xfa,0x9a,0xe9,0x63,0xa6,0x6f, +0x9d,0xdf,0xc9,0x6d,0x9f,0x14,0xb5,0x53,0x2d,0xa9,0x77,0xfd,0x30,0x55,0x6d,0x18, +0x67,0x5d,0x4f,0x49,0xb2,0xfa,0x8a,0xd7,0xc6,0x49,0xd6,0xb5,0x9a,0x24,0xc5,0x97, +0xa4,0xf8,0x92,0x14,0x5f,0x92,0xe2,0x4b,0xb6,0xae,0xdd,0x98,0x7a,0x49,0x90,0x26, +0x4a,0x93,0xa4,0xc9,0xd2,0x14,0x69,0x2d,0x69,0x6d,0x69,0xaa,0xd4,0xbb,0x9e,0xe0, +0xd9,0xe3,0x2d,0xbb,0x17,0x77,0x33,0x9d,0x3b,0x76,0xd7,0x79,0xa1,0x67,0xef,0x60, +0x5d,0x43,0x36,0xe7,0xb3,0x8f,0x10,0xd1,0x63,0x5a,0xa3,0xcc,0x82,0xa7,0xb4,0xee, +0x7a,0x46,0xeb,0xad,0xf9,0x5a,0x8f,0x2c,0xd2,0xfa,0x6a,0x89,0xd6,0x55,0xcb,0xb4, +0x9e,0x5a,0xa5,0x75,0xd4,0x1a,0xad,0x59,0xd6,0xc3,0x06,0x78,0x1d,0x36,0xc2,0x1b, +0x5a,0x47,0x6d,0xd6,0x7a,0x69,0xab,0xd6,0x45,0x1f,0xc1,0x76,0xd8,0x01,0x1f,0xc3, +0x4e,0xd8,0x0d,0x7b,0x60,0x2f,0x7c,0x06,0xfb,0x60,0x3f,0x7c,0x0e,0x07,0xb4,0x7e, +0x3a,0xa4,0x75,0x93,0x59,0x33,0xed,0x36,0x7d,0xb1,0x9d,0x5b,0x06,0x6f,0xad,0x76, +0x4c,0xf9,0x78,0x44,0xfb,0x9a,0x34,0x67,0xca,0x7d,0xc4,0x5a,0xa3,0x3d,0x22,0x8e, +0x29,0xdc,0x63,0xca,0xf7,0x11,0x6b,0x9d,0xf9,0x98,0xdc,0xab,0x54,0x3f,0xb3,0xe5, +0x9e,0xa5,0x7a,0x98,0x6b,0xa5,0x37,0x5d,0xfe,0xc7,0x54,0x7f,0xc7,0x54,0x97,0x47, +0x14,0xf6,0x29,0xf9,0xed,0xd0,0xf6,0xc7,0x54,0xbe,0x39,0x2a,0xeb,0xcb,0x8a,0x67, +0x8e,0xca,0xba,0xcf,0x8a,0x6b,0xba,0xfc,0x8e,0x58,0xee,0x23,0xaa,0x43,0x6f,0x6d, +0x1c,0xba,0x56,0xde,0xa0,0xfd,0x8d,0xfb,0x13,0x2b,0x3e,0x6f,0xfb,0x7e,0x6b,0x3d, +0xec,0xf9,0x1f,0xb0,0xd4,0xab,0x83,0xcf,0x94,0x67,0xcf,0xff,0x63,0xab,0xcc,0xfb, +0x2d,0xff,0x83,0x56,0x19,0x42,0xf7,0x0d,0x75,0xaf,0xb3,0xea,0x79,0xbf,0xb5,0x4e, +0x7f,0xcc,0x4a,0xfb,0x80,0xd2,0xd9,0xa8,0x3e,0x78,0x4c,0xf5,0xb8,0x50,0xfb,0xac, +0x97,0xfd,0x98,0xb5,0xce,0x5e,0xa4,0x38,0xbc,0x78,0x17,0x59,0xed,0xe7,0xd5,0xfd, +0x62,0xd5,0x85,0xdd,0xce,0x2f,0x59,0xe1,0x3c,0xfb,0xba,0x90,0xfa,0x59,0x62,0x9d, +0x27,0x2c,0xb6,0xda,0x7c,0xbf,0x55,0x9e,0xf5,0xea,0xef,0x6f,0x58,0x75,0xf1,0xa6, +0xf2,0xf4,0x4a,0x48,0x1f,0xb5,0xd3,0xb1,0xfd,0x5f,0xb1,0xce,0x3f,0x8e,0xa9,0xef, +0xef,0xb7,0xce,0x3d,0x1e,0x51,0x5e,0xd6,0x85,0xf8,0xcf,0x0d,0x71,0x2f,0xb4,0xce, +0x5b,0xec,0x71,0x60,0xf7,0x35,0xef,0x1c,0xe6,0x51,0xab,0x4d,0xbd,0x73,0x9b,0x97, +0x55,0xce,0x27,0xad,0xfd,0x3f,0xb3,0xc6,0xd0,0x5c,0xd5,0x8f,0x37,0x7e,0xbc,0x71, +0xb5,0xcc,0xb2,0x6f,0x50,0x1e,0xb6,0x2a,0xcc,0x2b,0xd6,0x36,0x6f,0x5c,0x6c,0xb5, +0xca,0xbe,0xd8,0x3a,0x8f,0xf2,0xca,0xbf,0xc2,0x6a,0xdf,0xc7,0xac,0x3a,0xdb,0x16, +0x52,0xff,0xdb,0xb4,0x6d,0x9b,0x15,0xff,0x3a,0xeb,0x3c,0xcc,0xcb,0xa7,0x67,0xf7, +0xc6,0xcf,0x63,0x56,0x7f,0xf3,0xdc,0xfb,0x65,0x7f,0x59,0x6d,0xf1,0x91,0xfc,0xe6, +0xca,0x7e,0x44,0x79,0xfd,0x54,0xf6,0xed,0x56,0x1c,0x9e,0x7b,0x9f,0xa5,0x76,0x7b, +0xee,0xd7,0x18,0xf2,0xc6,0xab,0x6d,0xf7,0xfa,0x51,0xe8,0x18,0xdb,0x1d,0x32,0xcf, +0xec,0xb6,0xe2,0xda,0x63,0xcd,0x6d,0xfb,0xac,0xb6,0xdd,0x2f,0xf7,0x67,0x21,0xfd, +0xc2,0xdb,0xef,0x98,0xd5,0xd6,0xde,0x1c,0xbb,0x43,0xea,0xd5,0xdd,0x7c,0x6b,0xae, +0xb1,0xc7,0xb7,0x39,0xf6,0x2c,0x19,0xe8,0x1e,0x6f,0x8c,0x26,0x48,0x13,0xa5,0x49, +0xd2,0x64,0x69,0x8a,0xb4,0x96,0xb4,0xb6,0x34,0xd5,0x8a,0xc7,0x8e,0x33,0xde,0xb2, +0x27,0x58,0xf6,0x44,0xcb,0x9e,0x64,0xd9,0x93,0x2d,0x7b,0x8a,0x65,0xaf,0x65,0xd9, +0x6b,0x5b,0xf6,0x54,0x2b,0xdf,0x71,0x96,0xdd,0x2e,0x4f,0x82,0x65,0x4f,0xb4,0xec, +0x5e,0xba,0xbd,0x74,0x7d,0x37,0x5b,0xd7,0x6b,0xb3,0x75,0xad,0xb8,0xbd,0xae,0xe3, +0x66,0xeb,0xb8,0x3b,0x40,0xc7,0xdc,0x81,0x21,0xf7,0xe3,0x3c,0x4d,0xb0,0xec,0x89, +0xba,0x9e,0x6c,0xe2,0x18,0xc2,0x5a,0xb6,0x28,0x11,0xc5,0xf4,0x70,0x8f,0x71,0xe6, +0xba,0xa6,0x59,0xef,0x9c,0x89,0xfb,0xa5,0xbe,0xee,0x1a,0xaa,0xc8,0x95,0x9c,0xe7, +0xb7,0x76,0xd7,0x51,0x03,0x95,0x7e,0x7f,0xe9,0x52,0x3d,0xf3,0xdc,0x4f,0xee,0x3e, +0xd2,0x16,0xba,0x9e,0xdd,0x52,0x9a,0x21,0xf5,0xee,0x77,0xf7,0x55,0x58,0xdb,0x3d, +0x50,0xd7,0xbc,0xfb,0x4b,0x97,0x86,0x1d,0xd7,0x9e,0x4a,0xc3,0x7b,0x87,0xc9,0xbb, +0xef,0x3d,0x5a,0x6e,0xcf,0xde,0xd2,0xb2,0x67,0x58,0xf6,0x76,0x96,0x7d,0x69,0xd8, +0xf1,0x6b,0xdb,0x7d,0x55,0x2f,0x7d,0xad,0x6b,0xde,0x3d,0xac,0xeb,0xde,0xfd,0x14, +0xbe,0x9f,0x73,0x9c,0x6e,0xd2,0x3e,0xce,0x89,0xfe,0x09,0xd6,0xb6,0x04,0x4b,0xfb, +0x84,0xf8,0x79,0x6d,0xd0,0xcd,0xb2,0x7b,0xda,0x27,0xc4,0xaf,0x64,0x45,0xf7,0x5a, +0xbb,0x6d,0x4f,0xb0,0xfa,0x44,0x1f,0xcb,0xde,0xd2,0xb2,0x67,0x58,0xf6,0xc1,0x56, +0xff,0xb1,0xed,0x5e,0x7c,0x27,0xf3,0x4b,0xb0,0x9e,0x61,0xe8,0x2f,0x5d,0x1a,0x76, +0x3c,0x2f,0x43,0xb4,0xbd,0x83,0xb6,0x77,0xd0,0xf6,0x0e,0xda,0xde,0x41,0x79,0xeb, +0xa0,0x7c,0x79,0x7d,0xb3,0xa3,0xc2,0x77,0x54,0xf8,0x8e,0x0a,0xdf,0x51,0xe1,0x3b, +0x2a,0xbc,0xe7,0x9e,0xad,0x77,0x6d,0x66,0xeb,0x79,0xfa,0x58,0x85,0x8f,0x55,0x7f, +0x1a,0xa4,0x7a,0xec,0x66,0xf5,0xfb,0xc6,0x2a,0x87,0xd7,0x4f,0x1a,0x6b,0x7c,0xc4, +0x6a,0xbb,0xd7,0x1f,0x47,0xe9,0x9e,0x47,0xb6,0xfa,0x46,0x96,0xee,0x7f,0xf4,0x57, +0xff,0xf5,0x68,0xa9,0xbc,0x0c,0x75,0x4e,0xec,0x37,0xfd,0xa5,0x03,0x94,0x4e,0x5f, +0xdd,0x03,0xe9,0xa7,0xb1,0xd9,0xcf,0xba,0x47,0xde,0x4f,0xe1,0xfa,0x2a,0x9d,0x66, +0xaa,0x0f,0xbb,0x3c,0x59,0xc2,0x6b,0x47,0xef,0x59,0x91,0xc1,0xba,0xaf,0x33,0x5c, +0xf5,0xd2,0x55,0xf5,0x69,0xca,0xe8,0x8d,0x3b,0xcf,0x1e,0xaf,0xf3,0xf1,0x04,0x69, +0xa2,0x34,0x49,0x9a,0x2c,0x4d,0x91,0xd6,0x92,0xd6,0x96,0xa6,0x4a,0xbd,0xb9,0xd2, +0xb3,0xc7,0x5b,0xf6,0x04,0xcb,0x9e,0x68,0xd9,0x93,0x2c,0x7b,0xb2,0x65,0x4f,0xb1, +0xec,0xb5,0x2c,0x7b,0x6d,0xcb,0x9e,0x6a,0xe5,0x3b,0xce,0xb2,0xdb,0xe5,0x49,0xb0, +0xec,0x89,0x96,0x3d,0xc9,0xb2,0x27,0x5b,0xf6,0x14,0xcb,0x5e,0xcb,0xb2,0xd7,0xb6, +0xec,0xa9,0x56,0x3d,0xc5,0x59,0x76,0x2f,0xdd,0x9e,0xd6,0xfc,0xd4,0x3c,0x9c,0x73, +0x1a,0x18,0xf0,0xa4,0xdb,0x1e,0x8d,0x35,0x4f,0x99,0x5b,0x4b,0x95,0x7d,0xf8,0x41, +0x15,0xb6,0xd5,0x9a,0x43,0x7f,0xf1,0xd3,0x7e,0xe8,0x6d,0x68,0x33,0xce,0x09,0xbf, +0xea,0xe1,0xde,0x4b,0x58,0x87,0xfd,0x2d,0x3a,0x4e,0x02,0xe7,0x14,0x9f,0xb4,0x75, +0xaf,0xc3,0x1b,0xda,0x74,0x72,0xcf,0x5d,0x27,0x31,0x29,0x37,0xc3,0xfe,0x2f,0x12, +0xed,0x4d,0x83,0x4f,0xbc,0xde,0x71,0x1a,0xde,0xe8,0x38,0x2f,0x4e,0x72,0x9c,0x6f, +0x26,0x3b,0xce,0x14,0xce,0x53,0xfd,0x57,0x3b,0x4e,0x69,0x1a,0xfb,0x7d,0x3a,0xd0, +0x47,0x74,0x90,0xfa,0x37,0x38,0xce,0xd5,0xec,0x7b,0x78,0xba,0xe3,0x8c,0x27,0xde, +0x61,0xc4,0x1b,0x4e,0x87,0x2d,0x4d,0xc7,0x89,0x61,0xdf,0xb2,0x0f,0xd1,0x9f,0x38, +0x67,0xdd,0x4f,0x07,0xdc,0x38,0x91,0x31,0x70,0x93,0xe3,0xbc,0x46,0x27,0xda,0x3a, +0x8e,0x73,0x65,0xe2,0x5c,0xcf,0x31,0xe0,0x1c,0x0a,0x7a,0x35,0x71,0x1e,0x63,0x9f, +0x37,0x48,0xe3,0x46,0xe6,0xfb,0xc5,0x14,0xec,0x23,0x3a,0xe1,0x2b,0x0c,0x9a,0x2d, +0xa4,0x59,0x94,0x6d,0x9f,0x0e,0x77,0xef,0xcd,0x44,0x10,0xef,0x65,0x70,0xf0,0x36, +0xca,0x72,0x0f,0x75,0x72,0xbf,0xe3,0x7c,0xfb,0x20,0xc7,0x10,0x06,0xc0,0xf5,0x0c, +0xac,0x19,0xd7,0x92,0xc6,0x04,0xf2,0x71,0xa7,0x7b,0x9f,0xe2,0xdd,0x9b,0x59,0xa7, +0x5c,0x82,0x9b,0x63,0x49,0x97,0x31,0x8e,0x73,0x1d,0x71,0x74,0x25,0xbe,0xf5,0x84, +0x5f,0x4d,0x9d,0xfc,0xfb,0x6e,0xf2,0xc3,0xf6,0xae,0x97,0x39,0x4e,0x71,0xd2,0xfa, +0x80,0xbc,0x14,0x21,0xbf,0x35,0x89,0xa7,0xd6,0x75,0x8c,0x43,0xb6,0x6f,0x26,0x2f, +0xb7,0xb0,0x5f,0x2e,0xf9,0x7a,0x1d,0xce,0x67,0x32,0x5f,0xce,0xf6,0xc3,0xa4,0x33, +0x8c,0xed,0x63,0x6f,0x61,0x0d,0xd4,0xd5,0xad,0x9f,0x1f,0x48,0x2f,0x95,0xba,0xf8, +0x94,0x73,0xf3,0xb3,0xba,0x50,0xaf,0xd4,0xd3,0x40,0xce,0xf5,0xcf,0xa1,0x6e,0xbe, +0x23,0xcd,0x15,0x94,0x6f,0x36,0x79,0x39,0x83,0x30,0xaf,0xd3,0xb8,0x23,0x69,0xeb, +0x8a,0xc4,0xf5,0x32,0xdb,0xaf,0x20,0x1f,0xbe,0x11,0x1c,0x23,0xa9,0xd7,0xa7,0x88, +0xe7,0xc5,0x3e,0xee,0xfd,0x9f,0xc9,0x84,0xfb,0x81,0xf8,0x3f,0x19,0x4f,0xf9,0x98, +0x6c,0xba,0x13,0xdf,0xb3,0xec,0xdf,0x9b,0xbc,0xbc,0x06,0xe3,0x98,0x4c,0x3e,0xa5, +0x6c,0x03,0xd8,0xbe,0x99,0xfd,0xde,0xa4,0x4d,0xbe,0x26,0xcf,0xe9,0xed,0xdc,0x6b, +0x0c,0x9f,0x53,0xcf,0xaf,0x92,0xce,0x0f,0x94,0xab,0x1a,0x75,0xf4,0xcc,0x34,0xea, +0xfc,0x3e,0xc7,0xb9,0x87,0xfa,0x79,0xe3,0x21,0xf7,0xde,0xe4,0x1a,0xfa,0xc9,0x08, +0x73,0xff,0x8e,0xf4,0x86,0x12,0x3e,0x47,0x37,0x6c,0xef,0xa3,0x0d,0xa2,0xd9,0x2f, +0x93,0x09,0xef,0x26,0x26,0xa2,0xf5,0xec,0xff,0x15,0xf9,0x1d,0x40,0x7d,0x54,0x26, +0xec,0x17,0xe4,0x35,0x9a,0x76,0x6b,0x4e,0x7d,0x9f,0x43,0x3c,0x8f,0xc2,0x32,0xd2, +0x5d,0x47,0x1f,0x59,0x3d,0xd9,0x2d,0xc7,0x6b,0xc4,0xf7,0x35,0x65,0xbe,0x86,0xbc, +0x3f,0x4b,0x1a,0x0d,0xc8,0xeb,0xb0,0x21,0xee,0xf9,0xed,0xd1,0x0e,0x6e,0x5d,0xbd, +0x48,0x3f,0x39,0x9f,0xfa,0x5a,0x80,0x7f,0x6f,0xd2,0xb9,0x8f,0xfe,0xd7,0x94,0x34, +0x92,0xee,0xa0,0x4f,0x52,0xc7,0xcd,0x68,0xeb,0x73,0xef,0xa5,0x1d,0xa8,0xbf,0x67, +0xcd,0x75,0x14,0xca,0xf8,0x02,0xfe,0x1f,0xb3,0xcf,0x8d,0xc4,0xf3,0x01,0x13,0xd7, +0x17,0xc4,0xd3,0x90,0x76,0x9c,0xde,0xdd,0x6d,0x8b,0x37,0xc8,0x73,0x3a,0xfd,0xe6, +0x18,0x79,0x1c,0x93,0xe3,0xde,0x7f,0x9a,0x4c,0x39,0x63,0xd9,0xef,0x26,0xf2,0x79, +0x0d,0x7d,0xef,0x08,0x34,0xa2,0xcd,0x1f,0x60,0x6c,0x44,0x91,0x6e,0x27,0xea,0xb6, +0x0f,0xed,0x54,0x94,0x32,0x5e,0x71,0xaf,0x7b,0xed,0x27,0x96,0x7a,0x18,0xc9,0x3e, +0xd5,0x49,0xa3,0x14,0xf9,0xdc,0x47,0xf8,0x6a,0x94,0xfd,0x16,0xca,0xd4,0x84,0x7a, +0x3a,0xa7,0x97,0xdb,0xce,0x37,0x12,0xe6,0x42,0xe2,0x2d,0x42,0xf9,0xbb,0x9b,0xfe, +0x44,0x5a,0xad,0x88,0x7f,0x16,0xdb,0x3f,0xa1,0x0d,0x23,0x88,0x7f,0x27,0xf1,0x8f, +0xa2,0x6c,0x6f,0x52,0x37,0x1f,0x4f,0x76,0xef,0xe5,0xed,0x64,0xbf,0x86,0xb4,0xff, +0x8b,0xe4,0xa1,0x0c,0xfb,0x6e,0x22,0xdf,0xf7,0x12,0xf6,0x5b,0xc6,0xcc,0xa3,0x6c, +0xeb,0xf8,0x80,0xe3,0x3c,0x4c,0x3b,0xdd,0x43,0x5c,0x1b,0x48,0x7b,0xef,0x38,0xf7, +0x3e,0x66,0xf9,0x6b,0x1c,0xe7,0x0e,0xea,0x72,0x25,0xfd,0x79,0x3a,0xf5,0x7d,0x09, +0xfd,0x70,0xa5,0xb9,0x57,0x4d,0xbf,0xac,0x43,0x3e,0x22,0xe1,0x09,0xea,0x7e,0x0b, +0xf9,0x7f,0x97,0x70,0x13,0xa9,0x9f,0xb2,0xec,0xff,0x1c,0xf9,0xaa,0x3b,0xc5,0xbd, +0x3f,0xd9,0xf2,0x6e,0xf7,0xde,0xe4,0x16,0xc2,0xa5,0x51,0xd6,0x95,0xcc,0x03,0x97, +0xd2,0x0f,0x87,0x12,0xe6,0x23,0xdc,0xd5,0x28,0xd7,0x7a,0xea,0xb0,0x1e,0x75,0x7e, +0x05,0x74,0x87,0x29,0xd0,0x81,0xf6,0x58,0x3e,0xc6,0xbd,0x67,0x7a,0x16,0xe3,0xf1, +0x1b,0xda,0xb9,0x36,0x75,0xfc,0x3d,0x1c,0xa4,0xde,0x8e,0x41,0x55,0xe6,0x85,0xe7, +0x18,0x9b,0x1f,0xe1,0xb7,0x98,0x74,0x9e,0xa5,0xed,0x3e,0xa5,0x0e,0x5b,0x9a,0x7e, +0x4b,0xde,0x76,0x43,0x1b,0xca,0xfd,0x20,0x69,0x46,0xd0,0x0f,0x7a,0x41,0x1a,0x69, +0xcf,0x82,0xab,0x74,0x2f,0xfb,0x2e,0xda,0xb7,0x17,0x75,0x7c,0x3b,0x7c,0x09,0xad, +0x69,0xdb,0x9d,0x30,0x95,0xfc,0x4d,0xa4,0x5e,0x47,0x50,0x9e,0xf3,0xa8,0xb7,0x8a, +0xf4,0xd1,0xfe,0xd4,0x5b,0x75,0xea,0xa2,0x22,0x75,0x37,0x75,0xa4,0xbb,0x6e,0xcc, +0x84,0x66,0x90,0x65,0xf2,0x3c,0xca,0xbd,0x06,0x77,0x1b,0xdc,0x0e,0x69,0xd4,0xe1, +0x38,0x58,0x79,0x8d,0xdb,0xa7,0xa3,0x18,0xef,0x8d,0x60,0x30,0x65,0x0a,0xd0,0xf7, +0x0e,0x50,0xcf,0xa3,0xc6,0xbb,0x74,0xa4,0x0f,0x15,0xa5,0x9e,0xee,0x06,0x1f,0xf5, +0x9c,0x0a,0x5b,0x98,0x3f,0x0a,0x30,0x0f,0x3d,0x3f,0xc5,0x2d,0xfb,0x2e,0xca,0xf8, +0x23,0xf5,0x52,0x97,0xb2,0x0f,0x23,0xdf,0x5f,0xa4,0xfb,0x9d,0x73,0xd9,0xb7,0x32, +0x6d,0xb2,0x88,0x32,0xf7,0x82,0xb1,0xd4,0x41,0xd0,0x28,0xac,0xa5,0xfc,0xdf,0x5e, +0xec,0x96,0xbf,0x3d,0x4c,0x87,0x9d,0xaa,0xff,0x85,0xd0,0x84,0xb1,0xdb,0x0e,0xba, +0x5e,0x4a,0x5d,0xd2,0x76,0x9b,0x69,0xa3,0xf7,0xa1,0x37,0xfd,0xee,0x19,0xd8,0x4a, +0x1a,0xad,0xa8,0x93,0x02,0xaa,0x9f,0x2e,0xaa,0xa3,0x24,0xda,0xfb,0x15,0xc6,0xda, +0xf9,0x8c,0xdd,0x8b,0xa1,0x43,0x77,0xb7,0x3d,0xcd,0x5c,0x5b,0x1a,0x3a,0xf4,0x74, +0xef,0xd1,0x9b,0xf9,0xc5,0xf4,0xfd,0x6d,0xd4,0xdf,0x06,0xd5,0x61,0xd9,0x81,0x6e, +0x3d,0x3e,0xc9,0x3c,0x94,0x4c,0x5d,0xce,0x1d,0xec,0xf6,0x81,0x41,0xd4,0x69,0x04, +0x7d,0xb7,0x2e,0x94,0xa1,0x3f,0x94,0x1b,0xee,0xf6,0x8b,0x6d,0xf0,0x15,0x34,0x27, +0x7c,0x1a,0xbc,0x4e,0xbd,0xcf,0x57,0x9d,0x5e,0x43,0xff,0xe8,0x7c,0xad,0x5b,0xb7, +0x0d,0x54,0xa7,0x17,0xd3,0x37,0x0f,0xc2,0x28,0x8e,0x2b,0x8d,0xa8,0xcb,0x1b,0x55, +0xa7,0x2b,0x6e,0x76,0xfb,0xd0,0x86,0x9b,0xdd,0xfa,0x35,0xf3,0xe8,0x81,0x9b,0xdd, +0x7a,0xbe,0xf9,0x16,0xb7,0x9e,0x6b,0x53,0xcf,0x83,0xa9,0xe7,0xe9,0x8c,0x99,0xe1, +0xcc,0x0b,0x63,0xee,0x76,0xeb,0xdc,0xf4,0xc5,0x6d,0xf7,0xb8,0x75,0x5f,0xe8,0x5e, +0xb7,0xfe,0xcf,0xba,0xdf,0x3d,0xbe,0x35,0xaf,0xea,0x77,0x9a,0xc0,0x3b,0x89,0x7e, +0xe7,0xc1,0xba,0xcc,0x21,0x69,0xc4,0x09,0x99,0x17,0xfb,0x9d,0x4d,0x97,0xf9,0x9d, +0x2d,0xd7,0xf9,0x9d,0xc6,0x84,0xbb,0xfd,0x61,0x77,0xfd,0xed,0xd1,0x5b,0xda,0xf7, +0x24,0x7e,0x9e,0xbf,0xf7,0x2c,0x8a,0xa7,0x43,0x03,0xe4,0x2b,0xe0,0x6a,0x77,0xa9, +0xf9,0xde,0xc8,0x75,0x96,0x7f,0x3f,0x78,0x1f,0x9e,0x83,0x2f,0x61,0x31,0xec,0x0c, +0xb8,0xcf,0xad,0x9a,0xe7,0x55,0xdf,0x86,0x6d,0x90,0x0b,0x1f,0xc2,0x5e,0xd8,0x17, +0x70,0x9f,0x09,0xfe,0x0c,0x5d,0x15,0x70,0x75,0xb5,0x74,0xa9,0xe5,0xb7,0x54,0xfe, +0x9b,0x14,0xaf,0xd1,0x17,0xa4,0x4b,0xf5,0x5c,0xec,0x52,0x3d,0x1b,0xbb,0x54,0xe9, +0x2d,0x55,0x9a,0x46,0xdf,0x91,0xbe,0x2b,0xdd,0x2a,0x7d,0x5f,0xfa,0x81,0x74,0x9b, +0x34,0x57,0xfa,0x91,0x74,0x87,0xf4,0x63,0xe9,0x2e,0xe9,0x6e,0xe9,0x1e,0xe9,0xa7, +0xd2,0xbd,0x52,0x2f,0xef,0xfb,0xac,0x7c,0x2c,0x51,0x7e,0x57,0x28,0xbd,0x15,0x8a, +0x67,0x85,0xca,0x63,0xd2,0x1e,0x14,0xe1,0x72,0x4d,0x08,0xd7,0x85,0x30,0x36,0x84, +0xd1,0x21,0x5c,0x1f,0xc2,0xa8,0x10,0x1e,0x0b,0xe1,0x89,0x10,0x6e,0x08,0x61,0x42, +0x08,0x37,0x86,0x30,0x29,0x84,0xdb,0xc4,0xad,0xe2,0x76,0x31,0x59,0xdc,0x2b,0xa6, +0x8a,0xd9,0x21,0xcc,0x0d,0x61,0x61,0x08,0xf3,0x43,0x78,0x51,0xbc,0x14,0x82,0xf7, +0x2d,0x1b,0xfb,0x9b,0x36,0x36,0xcb,0x43,0xd8,0x6c,0x61,0x7f,0xfb,0xe6,0x99,0x10, +0xd6,0x8a,0x35,0x62,0x9d,0xf0,0xbe,0xa5,0xb3,0x41,0xbc,0x2a,0x5e,0x13,0x9b,0x42, +0xc8,0x14,0xf6,0xb7,0x79,0x4e,0x66,0x7f,0xe7,0x14,0xf6,0x66,0xa7,0xb0,0xaf,0x3d, +0x85,0x7d,0xcd,0x29,0xec,0xeb,0x4e,0x61,0xdf,0x74,0x1a,0xf6,0xcc,0xff,0x60,0x7f, +0x3d,0x04,0x6f,0x5b,0x0d,0xcb,0x1e,0x63,0xd9,0x83,0xa7,0x88,0xcb,0x68,0x55,0xed, +0x57,0x55,0xfb,0x18,0x8d,0x95,0x06,0xa5,0x99,0x52,0x13,0xbe,0x9a,0xc2,0x57,0x53, +0xf8,0x6a,0x0a,0x5f,0x4d,0xe1,0xab,0x29,0x7c,0x35,0x85,0xaf,0xae,0xf0,0xd5,0xb5, +0xbd,0xba,0xb6,0x57,0xd7,0xf6,0x1a,0x8a,0xa7,0x86,0xb6,0xc7,0x58,0x7e,0x41,0xc5, +0x5d,0x43,0x1a,0x23,0x35,0xfe,0x89,0xf2,0x4f,0x94,0x7f,0xa2,0xb6,0x25,0x6a,0x7b, +0xb2,0xfc,0x93,0xe5,0x4e,0x51,0xf8,0x14,0xf9,0xa7,0x28,0x7c,0x8a,0xb6,0xd7,0x92, +0x7f,0x2d,0xb9,0x6b,0x4b,0x53,0xb5,0x5f,0xaa,0xdc,0x75,0xe4,0xae,0x23,0x77,0x23, +0xb9,0x1b,0x69,0xff,0x46,0x8a,0xb7,0x91,0xb5,0x3d,0x53,0x6a,0xca,0x9b,0xae,0x70, +0xe9,0xda,0x9e,0xae,0xed,0xe9,0xda,0xde,0x58,0x7d,0xb4,0xb1,0xe2,0x6d,0xac,0xf0, +0x8d,0x15,0xaf,0xd1,0x26,0xd2,0xa0,0x34,0x53,0xda,0x5c,0xdb,0x6a,0x48,0x63,0xa4, +0xb1,0xd2,0xa0,0x34,0x53,0xda,0x5c,0x7e,0x76,0xdd,0x07,0xad,0x3a,0xf6,0xc8,0xb4, +0xfa,0x50,0x53,0x85,0x6f,0xaa,0xf0,0x4d,0x15,0xbe,0xa9,0xc2,0x34,0x55,0xf8,0xa6, +0x0a,0x9f,0xa1,0xf0,0x19,0xda,0x9e,0xa1,0xed,0x19,0xda,0xde,0xdc,0xea,0xb7,0x5e, +0x9f,0x8d,0xb5,0xf2,0xd6,0xdc,0xea,0xb3,0x86,0x38,0x18,0x08,0xf1,0xd2,0x4c,0xa9, +0x79,0x76,0xea,0x22,0xb4,0x8d,0xec,0x2d,0x2d,0x7b,0x2b,0xcb,0xde,0xda,0xb2,0x67, +0x59,0xf6,0x36,0x8a,0xc7,0x1b,0x1b,0xf1,0x96,0x3d,0xe1,0x14,0x63,0xa9,0xe9,0xcf, +0x8c,0xab,0x78,0x69,0x42,0xc8,0x78,0x6a,0x7a,0x8a,0x71,0x15,0x2f,0x4d,0x08,0x19, +0x4f,0x4d,0x4f,0x31,0xae,0xe2,0xa5,0x09,0x21,0xe3,0xab,0xe9,0x49,0xc6,0xd9,0xc9, +0xfa,0xe1,0xa9,0xfa,0xdd,0xcf,0xf5,0xaf,0x53,0xf5,0xa3,0x2a,0x56,0x9f,0x69,0xaa, +0xfc,0x35,0x55,0xfe,0xec,0xfe,0xd1,0xf4,0x24,0xfd,0x24,0xd3,0xaa,0x7f,0xaf,0xee, +0x13,0x42,0xfa,0x41,0xd3,0x93,0xf4,0x87,0x9f,0x9b,0xfb,0x62,0x4f,0xd1,0x76,0x19, +0xa7,0x39,0xf7,0x65,0x9c,0xe6,0x9c,0x97,0x61,0xb5,0xc1,0x2f,0x99,0xd3,0x7e,0xe9, +0x5c,0x16,0xfb,0x5f,0xcc,0x69,0xbf,0xd5,0x5c,0x16,0x3a,0x77,0x9d,0xee,0x1c,0x75, +0x3a,0x73,0x52,0xc6,0x69,0xcc,0x45,0xa7,0x33,0xf7,0x64,0x9c,0x62,0xce,0x19,0x78, +0x9a,0x73,0x4d,0xc6,0xcf,0xf4,0x97,0xd0,0x7e,0x71,0xb2,0xf6,0xaf,0x2e,0x77,0xa2, +0xd5,0xbe,0xc6,0x9d,0x24,0x77,0x92,0xdc,0x27,0xab,0xa7,0xe0,0x49,0xca,0x13,0x9a, +0xbf,0xb4,0x88,0xe3,0x73,0x9a,0xb1,0xb7,0xb6,0xec,0xde,0x9c,0x56,0x4b,0xe3,0xa4, +0x96,0xf6,0x4b,0x95,0x3b,0x55,0xee,0x3a,0x72,0xd7,0x91,0x3b,0x51,0xee,0x44,0xb9, +0x93,0xe4,0x4e,0xb2,0xea,0x2b,0xd3,0xaa,0xb7,0x1a,0x72,0xd7,0xb0,0xea,0x31,0xd3, +0xaa,0xcf,0x64,0xb9,0x93,0xe5,0x4e,0x91,0x3b,0xc5,0x8a,0xbf,0x86,0x34,0x46,0x1a, +0x1b,0x52,0x47,0xf1,0xca,0x4f,0xbc,0xe2,0x89,0xd7,0xfe,0xf1,0xff,0x80,0xf2,0xfd, +0xdc,0xfe,0x76,0x9f,0xca,0xb0,0xd6,0x2d,0xa7,0x9a,0x4b,0x4e,0x15,0x5f,0xe8,0x7a, +0xc7,0xcc,0xe1,0x2d,0x2c,0xad,0x66,0x8d,0xc9,0x6a,0xd6,0x5c,0x76,0x32,0x7b,0xd0, +0x9a,0x1b,0x83,0xd6,0xf8,0xa8,0x61,0xd9,0x63,0x2c,0x7b,0xec,0x49,0xe6,0x48,0xcf, +0x1e,0x63,0xf5,0xf9,0x18,0x6b,0x1d,0x92,0x68,0x85,0x4d,0xb4,0xe6,0xd5,0x44,0xab, +0xcd,0x12,0xad,0x78,0x4e,0x66,0xaf,0x61,0xd9,0x83,0x21,0xf6,0x64,0x2b,0xfd,0x50, +0x7b,0xd0,0x6a,0xbb,0x98,0x53,0xd8,0x6b,0x58,0xed,0x1f,0x0c,0x69,0x33,0xdb,0x1e, +0x0c,0xb1,0xa7,0x58,0x7d,0x30,0xc5,0xaa,0x43,0xdb,0x5e,0xcb,0x2a,0xcb,0xc9,0xec, +0x76,0x98,0xe6,0xd6,0x7c,0x1f,0xb4,0xe6,0xfc,0x53,0xd9,0x33,0xad,0xe3,0x40,0xd0, +0xb2,0x37,0xb7,0xec,0x99,0xd6,0x31,0x21,0x18,0x62,0x4f,0xb7,0xf2,0x93,0x6e,0xc5, +0xd3,0xc4,0xaa,0x9f,0x26,0xd6,0xf8,0x6a,0x62,0x95,0xd7,0x3b,0x3e,0xd4,0x38,0x89, +0x3d,0xd6,0xda,0x37,0x36,0x64,0x9e,0x8c,0x09,0xb1,0x9f,0xac,0x1f,0x05,0x2d,0x7b, +0xf3,0x90,0xe3,0xb3,0x7d,0xbc,0x09,0xed,0x8f,0xf6,0x71,0xc7,0x3b,0x56,0xdb,0xc7, +0xa8,0x8c,0x90,0xe3,0x52,0x4c,0x88,0x3d,0xd3,0x3a,0x5e,0x05,0x4f,0x61,0xcf,0xb4, +0xe6,0xfa,0xe6,0x96,0x3d,0xd3,0xca,0x6b,0x30,0xc4,0x5e,0xd5,0x9a,0x83,0xaa,0x59, +0xfd,0xad,0x9a,0x15,0x67,0xb5,0x90,0x30,0xb1,0x96,0x7f,0xd0,0xf2,0x0f,0x5a,0x73, +0x5c,0x30,0xe4,0x7c,0xcc,0xf6,0xcf,0xb4,0xe6,0x91,0x4c,0x6b,0x5c,0x34,0xb7,0xfa, +0x7f,0x73,0xab,0x0f,0xdb,0xe7,0x21,0xf6,0x9a,0xb1,0x79,0xc8,0xb1,0xd7,0x3e,0x1e, +0x37,0x3f,0x49,0x59,0x9b,0x5b,0x7d,0xa9,0xb9,0x55,0xb7,0xcd,0x43,0xfa,0x9b,0xdd, +0xc7,0x52,0xad,0xf0,0x8d,0x4f,0x72,0xde,0x62,0xaf,0x2b,0xec,0x7c,0x06,0xad,0xf0, +0xc1,0x10,0xff,0xa6,0x21,0x6b,0xba,0x18,0xab,0x1c,0x35,0x42,0xfa,0x55,0x73,0x6b, +0xbd,0xd4,0xdc,0x5a,0x5b,0x36,0x0f,0x89,0xdf,0x1e,0x9b,0xc9,0x21,0x73,0x51,0x6c, +0x48,0x9e,0xbd,0xe3,0x4d,0x13,0x5d,0x3b,0x49,0xb7,0xec,0x55,0x64,0xf7,0xd6,0x50, +0xde,0x1a,0xde,0x3b,0xff,0xb0,0xc7,0x41,0x4d,0x2b,0x1e,0xaf,0x9e,0xbc,0x63,0x50, +0x33,0xcb,0xbf,0x89,0xb5,0xd6,0x68,0xa6,0xed,0x4d,0xac,0xbc,0x36,0xb1,0xfa,0x81, +0x67,0xcf,0xfb,0x1b,0x2b,0x21,0x79,0x31,0x7e,0xa1,0xf1,0x19,0xbf,0xd0,0x38,0xbd, +0xb1,0x6e,0xb6,0x79,0xf6,0x2a,0x56,0x3c,0xf1,0xba,0xce,0xe1,0xf9,0xd5,0x30,0xcf, +0x4d,0xc7,0x39,0x8e,0x3f,0xce,0x7d,0x5f,0xaf,0xae,0xf5,0x1d,0x86,0xb3,0xf1,0x3b, +0x27,0xee,0xe4,0xdf,0x7d,0x28,0x41,0x02,0xc5,0xe1,0x4a,0xc7,0xc5,0xfb,0x66,0xc2, +0x35,0x70,0xad,0xd9,0xce,0x7e,0x25,0xa1,0x28,0x14,0x83,0x82,0x50,0x28,0xee,0xf8, +0xfb,0xc9,0x85,0xe1,0x0c,0x38,0x13,0x8a,0x98,0xf7,0x88,0xcc,0x73,0xe0,0xd6,0xb7, +0x21,0x4e,0xa5,0x5e,0x7a,0x06,0x2f,0xef,0xb1,0xca,0x77,0x1d,0xeb,0x5b,0x12,0x26, +0x7f,0xa7,0xca,0x53,0xb4,0xb9,0x87,0x6b,0x9e,0x5f,0xd7,0x77,0x1f,0x62,0x1c,0xf7, +0x3d,0xf0,0x06,0x7a,0x37,0xf1,0x32,0xf3,0x9d,0x48,0xf3,0xad,0x58,0x48,0x53,0x9e, +0x5a,0x68,0x4d,0xd8,0xc2,0x3a,0x3f,0xf6,0xce,0x8d,0xbd,0xf3,0x62,0x6f,0x2d,0xe9, +0x9d,0x1b,0x7b,0xeb,0x49,0xef,0xfc,0xd8,0x5b,0x53,0x7a,0xe7,0xc8,0x69,0xd6,0x39, +0xf3,0xc5,0x72,0x1b,0xad,0x10,0x71,0xe2,0xb7,0xb2,0xed,0x6f,0x66,0x87,0x7e,0x3b, +0x3b,0xf4,0x1b,0xda,0xa1,0xdf,0xd2,0x3e,0x95,0x56,0x11,0x55,0x43,0xb8,0x50,0x54, +0x0b,0xa1,0x7a,0x08,0x35,0x42,0x88,0x09,0x21,0x36,0x84,0x9a,0x22,0x4e,0xc4,0x8b, +0x04,0x91,0x18,0x42,0x52,0x08,0xc9,0x21,0xa4,0x84,0x50,0x2b,0x84,0xda,0x21,0xa4, +0x86,0x50,0x27,0x84,0x46,0x21,0xa4,0x87,0xd0,0x38,0x84,0x26,0x21,0x04,0x43,0x68, +0x1a,0x42,0x46,0x08,0xcd,0x44,0xe6,0x49,0xce,0xc1,0x9b,0x5b,0xe3,0xb6,0xed,0x29, +0xec,0xed,0x4e,0x61,0x6f,0x7f,0x0a,0xbb,0xa7,0x66,0x6c,0x54,0x74,0xdc,0x31,0xe0, +0xf5,0x71,0x33,0x16,0xaa,0x58,0x63,0xd8,0x1b,0x17,0x35,0x34,0x36,0x62,0xf5,0x3d, +0x92,0xd3,0xfd,0x96,0x8a,0x37,0x8f,0xd4,0xd3,0x78,0x6a,0xa0,0x71,0x99,0xf6,0x3b, +0xbe,0xfb,0xdc,0x59,0xe3,0xd8,0xcc,0x29,0x57,0x68,0xbe,0xe8,0xf2,0x3b,0xbe,0x13, +0x6d,0xe6,0x9c,0x31,0x9a,0x77,0xae,0x83,0x89,0x54,0xec,0x8d,0x17,0xba,0xf3,0xac, +0x37,0xf7,0x99,0xb9,0xeb,0x3b,0x3d,0x77,0x3e,0x53,0xcf,0xcc,0x3e,0xae,0xe7,0x63, +0xcd,0x73,0xe1,0xbb,0xf4,0x9c,0xf5,0xa7,0x7a,0x4e,0xf2,0x58,0xdc,0x5f,0xef,0xd9, +0xfa,0x23,0x7a,0xde,0xd3,0x3c,0x27,0xda,0xa5,0xd8,0xdf,0xeb,0xfd,0xc3,0x47,0x28, +0xce,0xa3,0xf0,0xb4,0xf5,0x37,0xd3,0x9e,0x40,0x1f,0x37,0xcf,0xb0,0xe1,0xe1,0xaf, +0xe4,0x7e,0x17,0x65,0x6a,0x05,0xf7,0xbb,0x28,0x77,0xc2,0x0c,0xfc,0x36,0x54,0x32, +0xf7,0x03,0x7d,0x79,0xdf,0xce,0xfd,0x40,0xba,0xc9,0xef,0x38,0x6f,0xf9,0xdd,0xbf, +0xf5,0x32,0x1d,0x6d,0x0b,0x8f,0x9a,0x6f,0xa7,0xcf,0x21,0x3e,0xf4,0x31,0xe8,0x00, +0x1d,0xcd,0xb7,0xcd,0xcb,0xd0,0xd7,0xd1,0x2b,0x60,0x36,0x5c,0x05,0x5d,0xa1,0x0b, +0xdc,0xef,0x77,0xbf,0x09,0xf4,0x80,0xf9,0x06,0x3c,0xdc,0x00,0x4f,0x99,0xef,0xa5, +0x9b,0xbf,0x2f,0x02,0xe1,0xdb,0x7d,0xce,0xed,0x4f,0x52,0x36,0xec,0x01,0x63,0x47, +0x23,0x50,0xf3,0x37,0x65,0x86,0x9b,0xbf,0x5f,0xe2,0x77,0xfb,0xf8,0x68,0xb4,0x00, +0xfe,0xd7,0xa2,0xd7,0xc1,0x58,0x98,0x05,0x4f,0x98,0x78,0xc9,0xd3,0x93,0xe8,0x64, +0x13,0x96,0x49,0x62,0x0a,0x3a,0x13,0x1e,0x81,0x7b,0x61,0x25,0xe9,0xaf,0x82,0xd5, +0x50,0x90,0x38,0xca,0xc2,0x24,0xfc,0xef,0x86,0x7b,0xe0,0x21,0x28,0x84,0xdf,0xf4, +0xa2,0x3e,0xe7,0x45,0xb8,0x5f,0xfa,0xb8,0x34,0xbe,0x98,0xcf,0xa9,0x02,0x09,0xd2, +0x8c,0xe2,0x3e,0xa7,0x41,0x71,0x57,0x3b,0xc2,0x78,0x78,0x0d,0x6e,0x80,0x97,0xe0, +0x16,0x58,0x0d,0x39,0xf2,0x5f,0x6d,0xf1,0x82,0xd4,0xf8,0x2f,0x29,0x41,0xfc,0x25, +0x5c,0x9d,0x27,0x5d,0x06,0x2f,0x94,0xf4,0x39,0x73,0x61,0x89,0x34,0xb9,0x94,0xcf, +0x89,0x83,0xb2,0xd9,0xc7,0xb9,0x50,0x5a,0x4e,0xf6,0x72,0x72,0x97,0xb7,0xc2,0x94, +0xb3,0xc2,0x96,0xb3,0xfc,0x4d,0x98,0x9e,0xfd,0x5c,0xba,0x85,0xa8,0xa1,0xad,0xde, +0x8b,0x5e,0xa7,0x71,0xbc,0x4e,0xe3,0x73,0xaf,0xc6,0xd4,0xef,0x35,0x67,0x9e,0xee, +0xfc,0xde,0xf1,0x2d,0x9f,0xd3,0x1d,0x2e,0x09,0xd1,0xfe,0x96,0x7d,0x80,0x65,0x1f, +0x68,0xd9,0x07,0x59,0xf6,0xc1,0xb0,0x44,0xf6,0x17,0xa5,0x4b,0xac,0xb8,0x5e,0xb4, +0xec,0x4b,0xac,0x78,0x5f,0xb4,0xec,0x7f,0xb7,0x6f,0x69,0xfc,0x19,0xca,0xf3,0x77, +0x2a,0xcb,0x6f,0xdd,0x36,0x5e,0x59,0x32,0xac,0xbc,0x87,0xe6,0xf9,0x97,0xe6,0xb7, +0xc7,0xcf,0xe4,0xf3,0x9f,0x5e,0xe7,0xe9,0x27,0x29,0xcb,0xcf,0x95,0xe1,0x3f,0xe5, +0xff,0x8f,0xce,0xfb,0xc9,0xda,0xa0,0xf5,0x9f,0x2c,0xcf,0xf9,0xf3,0x69,0x7e,0x79, +0xf2,0xcb,0x93,0x5f,0x9e,0xbf,0x5b,0x79,0xe2,0x39,0x27,0xa9,0xc5,0xf9,0xc7,0x76, +0xc7,0xfd,0x1e,0xf2,0x1d,0xfa,0x2e,0xe9,0x5d,0xfa,0x6e,0xf1,0xdd,0xfa,0x4e,0xf1, +0xbd,0xfa,0x76,0xf0,0x7d,0x70,0x3f,0x3c,0x00,0x0f,0xc2,0x43,0xfa,0xde,0xee,0x0c, +0x7d,0xcf,0xf7,0x5e,0xfd,0x3d,0xc2,0xc7,0xf4,0x9d,0xdf,0x27,0xe0,0x49,0xf3,0x7d, +0x47,0x7d,0x7f,0x37,0xb2,0xa2,0xfb,0x8d,0x66,0xfb,0x6f,0x6a,0x99,0x6f,0xa2,0x3f, +0xaf,0x6f,0x27,0xbf,0xa0,0xef,0x18,0x9b,0xbf,0x73,0xf8,0x92,0xfe,0xc6,0xf6,0x32, +0x58,0xae,0x6f,0xa1,0xaf,0xb4,0xfe,0xfe,0xe1,0xcb,0xf0,0x8a,0xbe,0x39,0xec,0xfd, +0xcd,0xad,0x75,0xfa,0x26,0xb0,0xbf,0xa2,0x1b,0xef,0x0b,0x8a,0x6b,0x8d,0xf6,0x5b, +0x19,0x96,0x5f,0xce,0xfc,0x72,0xe6,0x97,0xf3,0xcf,0x5c,0xce,0x5c,0xf8,0x30,0xec, +0xf4,0xcf,0xbf,0xff,0xec,0xe1,0xcc,0xdc,0xda,0x71,0x3b,0xe7,0xf9,0xd0,0x09,0xcc, +0xdf,0xb6,0x3d,0xb7,0x8c,0xe3,0x8c,0x65,0xee,0x2d,0x06,0x9f,0x40,0x3a,0xdc,0x07, +0x59,0x6c,0x6f,0x00,0x99,0xe6,0xef,0x49,0x11,0xa6,0x21,0xf6,0x87,0xf0,0x1f,0x83, +0xbb,0x36,0xa4,0x42,0x75,0xfc,0x4a,0xc1,0x8d,0xe6,0xfa,0x12,0x61,0x6a,0x60,0x3f, +0x1f,0xee,0xc4,0x7d,0x1f,0xee,0x40,0x19,0xf3,0x47,0x0c,0x69,0x4b,0xb8,0xde,0xfc, +0x1d,0x41,0x78,0x16,0xe6,0x42,0x05,0x48,0x82,0x64,0x48,0xf1,0x1f,0x6f,0x8f,0x71, +0x84,0x9d,0xf6,0xa4,0xe3,0x4c,0x42,0x6f,0x86,0xdb,0x61,0x32,0xe9,0x4e,0x87,0xc7, +0x61,0x06,0x61,0x9f,0x41,0xa3,0x48,0xc7,0xfc,0xcd,0xd6,0x78,0x48,0x08,0x77,0xff, +0x3e,0x6c,0x52,0xb8,0xfb,0x77,0x5b,0xcd,0xdf,0x66,0x35,0x7f,0x8f,0xd5,0xfc,0xcd, +0x55,0xf3,0x77,0x62,0xeb,0x42,0xbd,0x70,0xf7,0x6f,0xae,0x36,0x84,0x34,0x68,0x04, +0xe9,0xe1,0xee,0xdf,0x4d,0x6d,0x02,0x41,0x68,0x1a,0xee,0xfe,0xdd,0xd4,0x66,0xe1, +0xee,0xdf,0x4b,0x35,0x7f,0x83,0xb5,0x15,0xdc,0xf4,0x84,0xfb,0xf7,0x5f,0xcd,0xdf, +0x9e,0xbd,0x24,0xdc,0xfd,0x5b,0xad,0x73,0xe1,0xcd,0x70,0xe7,0x17,0xe5,0xc1,0x4b, +0xbf,0xd1,0x7f,0x48,0xb7,0xb9,0xd2,0x9e,0xaa,0xf4,0xda,0xc3,0x95,0x30,0x07,0xda, +0x90,0x8f,0xf9,0xe1,0xc7,0xef,0x0f,0xd5,0xd0,0xbd,0x9b,0x66,0xba,0x57,0x13,0x63, +0x3d,0x2b,0xd4,0x38,0xe4,0x59,0xab,0x44,0xdd,0x5f,0x69,0xa4,0xfb,0x34,0xe9,0xd6, +0x33,0x38,0xde,0x7d,0xa4,0x58,0xdd,0x03,0x4a,0xd1,0xbd,0x19,0x73,0xff,0xa5,0xbf, +0x9e,0x8f,0x9f,0x09,0x03,0xac,0x74,0x33,0x42,0xee,0xf9,0xfe,0x5c,0x5a,0xa1,0xe9, +0xa4,0x58,0xcf,0xe6,0xd9,0xf7,0xd3,0xed,0xfd,0xed,0x7d,0xed,0x7d,0x5e,0x3c,0x45, +0x5e,0x6a,0x85,0xdc,0x83,0xfe,0x25,0x79,0xb1,0xcb,0x3b,0x33,0xe2,0xff,0xd7,0x71, +0xc6,0x29,0xea,0xf9,0xb7,0xa8,0xe3,0x9f,0x6b,0xcb,0xdf,0x22,0x0d,0xef,0xdb,0xc0, +0x71,0xba,0x7f,0x14,0x2f,0x4d,0x90,0x26,0x4a,0x93,0xa4,0xc9,0xd2,0x14,0x69,0x2d, +0x69,0x6d,0x69,0xaa,0xb4,0xaa,0xd6,0xa2,0xde,0x37,0xba,0xd2,0x2d,0x7b,0x63,0xcb, +0xde,0xc4,0xb2,0x07,0x2d,0x7b,0x53,0xcb,0x9e,0x61,0xd9,0x9b,0x59,0xf6,0x4c,0xcb, +0xde,0xdc,0xb2,0xb7,0xb0,0xec,0x17,0x59,0xf6,0x96,0x96,0xbd,0x95,0x65,0x6f,0x6d, +0xd9,0xb3,0x2c,0x7b,0x1b,0xcb,0x7e,0xb1,0x65,0x6f,0x6b,0xd9,0xdb,0x59,0xf6,0xf6, +0x96,0xbd,0x83,0x65,0xef,0x68,0xd9,0x2f,0xb1,0xec,0x9d,0x2c,0xfb,0xa5,0xb2,0x9b, +0x7b,0xde,0x26,0x7e,0x73,0xdf,0xbb,0xb1,0xd2,0xf5,0xd6,0xf2,0x1d,0x15,0xee,0xf7, +0x5a,0xe3,0x37,0x0b,0xf9,0x46,0x40,0x5b,0xa5,0xd7,0x56,0x78,0xef,0xc4,0x7b,0xfb, +0x36,0x56,0x58,0x4f,0xbd,0xef,0xdd,0x5f,0x2c,0xbb,0xc9,0x93,0xf9,0xfe,0x67,0x0b, +0xdd,0xf3,0xf2,0xee,0x7b,0x99,0x6f,0xe8,0x76,0xec,0xec,0x38,0xaf,0xb7,0x3d,0xfe, +0x7d,0x1d,0xf3,0x7d,0xb1,0xf3,0xc8,0xc8,0xae,0x9b,0xdc,0xef,0x2b,0x3e,0x86,0xbb, +0x3c,0x27,0x18,0x15,0x06,0xb9,0xef,0xae,0xb6,0x24,0xd2,0x5b,0xaf,0x74,0x9c,0xdb, +0x28,0xcc,0x3c,0xdc,0x65,0xcc,0xbb,0xbc,0xd7,0xba,0xdf,0xbf,0x9d,0x7d,0xab,0xe3, +0x1c,0xa2,0x20,0xa9,0x14,0xae,0x04,0x27,0x1c,0xd3,0x88,0xbf,0x7d,0x37,0xb7,0x12, +0xcc,0x37,0xcb,0x9a,0xe7,0xb8,0xdf,0x09,0x33,0xdf,0x0c,0x33,0xdf,0x0a,0x8b,0xec, +0xe6,0x7e,0x57,0xb6,0x2d,0xe1,0xc6,0x71,0xe2,0x31,0x9a,0x13,0x8f,0x02,0xec,0x3b, +0xb6,0xbf,0xfb,0x8d,0xb2,0xbc,0xef,0x74,0x11,0xef,0x60,0xd2,0x78,0x9e,0xca,0x6a, +0x39,0xd5,0x6d,0xa7,0x1a,0x3d,0xdd,0x76,0x32,0x76,0x13,0xaf,0x67,0xbf,0xd5,0xb2, +0xdf,0xd4,0xf9,0xb8,0xdd,0x7c,0x33,0xc4,0xb3,0x9b,0xb4,0x3c,0xfb,0x7b,0xc3,0x8f, +0xdb,0x3f,0xbc,0xf8,0xb8,0xbd,0x63,0x77,0xd7,0x7e,0x0f,0xe5,0x3c,0xd8,0xf6,0xf4, +0x8f,0xe7,0xf5,0x49,0xbf,0xb6,0xf9,0x06,0x1b,0x54,0xf4,0xf9,0x9d,0x2e,0xad,0xdd, +0xf7,0x4a,0x5f,0x02,0x3f,0x0d,0x36,0x1a,0xa6,0x67,0xb9,0xef,0x99,0xbe,0x09,0x0f, +0x25,0x99,0xb9,0xc0,0x9f,0xf7,0xce,0x69,0x3b,0xb8,0x0a,0x46,0x98,0x77,0xb8,0x03, +0x7e,0x67,0x09,0xdb,0x7a,0xb6,0x71,0xeb,0xb9,0x05,0xee,0x7b,0xd0,0xc7,0xcc,0x3b, +0xde,0xc4,0xfd,0x74,0x1b,0xf7,0x9d,0xcd,0xed,0x53,0xfd,0x79,0xdf,0x70,0x0e,0x23, +0xef,0xdb,0x09,0x5f,0x17,0x6d,0x7a,0xb1,0x5b,0x5f,0x23,0x4c,0x79,0x92,0xdd,0xf7, +0x38,0xbd,0xf7,0x59,0xcd,0xfb,0x9c,0x01,0xca,0x13,0xd1,0xd6,0x7d,0xe7,0x3b,0xb3, +0xad,0xfb,0x8e,0xeb,0xa5,0x30,0x04,0xae,0x85,0xeb,0x2d,0x6a,0x14,0xf4,0x3b,0x03, +0xa9,0xbb,0xf5,0xd8,0xb7,0x43,0xb7,0x42,0x7e,0x67,0x3f,0x7a,0xd8,0xc4,0x41,0x3b, +0x3d,0x04,0xb5,0xa1,0x19,0xf4,0x32,0xdf,0x02,0x83,0x7f,0x41,0x51,0xda,0xaa,0x2d, +0x74,0x83,0x1b,0x84,0x79,0x7f,0x74,0x0e,0x2c,0x84,0xd5,0x70,0x76,0x47,0xf7,0xbd, +0xda,0x73,0xd0,0x36,0xe8,0xd0,0x0e,0xee,0x3b,0xc1,0x5f,0xd0,0x7f,0xde,0xc0,0xef, +0x2b,0x38,0x03,0xfb,0x2d,0x68,0x02,0x1a,0x0f,0x4f,0xc3,0xee,0x12,0x7e,0xe7,0x4b, +0xf4,0xdf,0x10,0xd1,0xc9,0xed,0xab,0x15,0xcd,0x7b,0xa8,0x30,0xeb,0x6c,0xbf,0xb3, +0x0f,0x3e,0xc7,0x5e,0x9a,0x81,0x54,0x05,0xb6,0x62,0xef,0x81,0x7e,0x41,0x63,0x1d, +0x83,0x02,0xf4,0x8b,0x06,0x62,0x5d,0x29,0xbf,0xf3,0x32,0xba,0xb5,0xb3,0xfb,0x9e, +0xf7,0x11,0x38,0xb7,0xb4,0xdf,0xf9,0x11,0x8d,0xb8,0x8c,0x32,0x5c,0xe9,0x7e,0xbb, +0x7a,0x1c,0x8d,0xdc,0x45,0xef,0xfc,0xae,0x84,0xdb,0x60,0x77,0x19,0xbf,0xd3,0x98, +0xbe,0xbc,0x07,0xed,0x8f,0xf6,0x81,0x31,0xf0,0x31,0xec,0x84,0x9a,0x74,0x8a,0xef, +0xd1,0xaa,0x57,0xd0,0x2f,0xcc,0x7b,0xb1,0xd0,0x15,0xbf,0x09,0x2c,0xb4,0xc6,0xa0, +0xf3,0x70,0x2f,0x84,0xe7,0xaf,0x70,0xbf,0x35,0x70,0xc7,0xa3,0xfe,0xbc,0xef,0x5e, +0xc7,0x47,0xfb,0xf3,0xf0,0x8d,0x27,0xed,0x2b,0x5d,0xd6,0x12,0xfe,0x85,0x04,0xbf, +0xf3,0x41,0xb6,0xdf,0xe9,0x8a,0xbb,0x0f,0xec,0xc2,0xef,0x3e,0x74,0x23,0xbc,0x07, +0x47,0x61,0x5c,0x17,0xfa,0x13,0x1d,0xf1,0xfc,0x54,0xf7,0xdd,0xe4,0xb7,0x2b,0xfb, +0x9d,0xb5,0x68,0xb3,0x6c,0xe6,0xa3,0x6c,0xf7,0x7d,0x5c,0xa3,0xa3,0xf5,0x4e,0xee, +0x02,0x78,0x0c,0xe6,0xc2,0x47,0x7a,0x3f,0xd7,0x7c,0x63,0xc1,0x7c,0xfb,0xa6,0x34, +0x5c,0x0e,0xf3,0xe1,0x6d,0xc8,0x62,0xac,0x16,0xae,0xee,0x77,0xea,0xa3,0xc7,0x70, +0xf7,0x42,0x27,0xc0,0x6e,0x38,0x8c,0x7f,0xc5,0xab,0x58,0xcf,0x63,0x9f,0x0d,0xb1, +0x75,0x28,0x2f,0xee,0xeb,0xe0,0x41,0x18,0x01,0x7d,0xeb,0xb8,0xef,0x47,0xf7,0xed, +0x6e,0x9e,0x71,0xf2,0x3b,0xbb,0xd0,0x6f,0x98,0x57,0x32,0xa1,0x54,0x5d,0xf7,0x9d, +0xe9,0x02,0xe8,0x6e,0xc2,0xdd,0x41,0x9f,0x9e,0xd6,0xc6,0xbd,0xa8,0xf1,0x00,0xfe, +0xcf,0x8c,0x65,0xbd,0xd7,0xf8,0xf8,0x3b,0xc2,0x15,0xe0,0x0a,0x68,0x0b,0x2f,0x27, +0xfa,0x9d,0x4c,0xf6,0xfb,0x16,0xfb,0x44,0xb8,0xb8,0x97,0xfb,0xee,0x75,0x3f,0x16, +0xb3,0xb7,0xa3,0xe5,0xa0,0x44,0x6f,0x27,0xef,0xfd,0xda,0x74,0xf4,0x51,0xd8,0x07, +0xb3,0xae,0xc6,0xce,0x42,0x77,0x1b,0x7a,0x6e,0x3d,0xe2,0xec,0xc3,0xf9,0x0e,0x0b, +0xe9,0x76,0x68,0x2b,0xdc,0x83,0xcd,0x37,0xd6,0xf5,0x1e,0xf2,0x4b,0x70,0x5b,0x1d, +0xbf,0x53,0x88,0xb6,0xfe,0x16,0x6d,0xd5,0x97,0xf3,0x9b,0x7a,0x7e,0x67,0x05,0xba, +0x11,0x7a,0xc2,0xd9,0xfd,0xe8,0x53,0xfd,0xdc,0x77,0xbe,0xcd,0x7b,0xcb,0xbd,0x61, +0x24,0x4c,0x84,0xb2,0xf5,0xfd,0x4e,0x12,0x5a,0x93,0x79,0xad,0x3f,0x24,0xd6,0x77, +0xdf,0x69,0x5e,0x0b,0x6f,0x35,0xf0,0x3b,0x47,0xd9,0xd6,0x9f,0xf9,0xf2,0x8a,0x86, +0xe4,0x19,0xd6,0x60,0x4f,0x1d,0xe8,0xbe,0xef,0x5c,0x1a,0xee,0x26,0x7c,0x73,0xf4, +0x5a,0x18,0x01,0xcf,0x40,0x25,0xe6,0x84,0x20,0x73,0x72,0xb7,0x74,0xbf,0xf3,0x00, +0x3a,0xa7,0xb1,0xdf,0xa9,0x3a,0xd8,0x7d,0x2f,0x3a,0x0b,0x0a,0x34,0xf5,0x3b,0x63, +0xd1,0x69,0xc6,0x2f,0xc3,0xef,0x94,0x68,0xe6,0x77,0x46,0x0f,0x61,0x3c,0xc1,0xd3, +0x0d,0x58,0xbb,0xa3,0x2f,0x34,0x70,0xc9,0x18,0xea,0x38,0x97,0x0d,0x75,0xdf,0xa3, +0x9e,0x68,0xbe,0xa3,0x00,0xa5,0x1b,0x3a,0xce,0x05,0xcc,0xbd,0x29,0x17,0xf9,0x9d, +0x06,0xe6,0x7b,0xe6,0xa8,0xf9,0x56,0xc4,0xc3,0xf4,0xdf,0xa2,0xcc,0x9b,0x33,0x5b, +0xfb,0x9d,0x17,0xa0,0x49,0x96,0xdf,0x39,0x46,0xd8,0x02,0x69,0xee,0xbb,0xd6,0x47, +0x70,0x7f,0x09,0xa5,0xda,0xf8,0x9d,0x44,0x28,0x3b,0x82,0x36,0x10,0xe6,0x3d,0x6c, +0xf3,0x7e,0xf3,0x2d,0x68,0x53,0xf4,0xee,0x34,0xf3,0x4d,0x01,0xea,0x73,0xa4,0xfb, +0x8d,0x0c,0xf3,0x7e,0xf6,0x2e,0xfc,0x2a,0x77,0xf0,0xe7,0xbd,0x0f,0x7f,0x1f,0xfa, +0x2a,0x98,0x77,0xfa,0xf7,0x43,0xcd,0x46,0xee,0x7b,0xf1,0xcd,0xa1,0x35,0x8c,0xe9, +0xe4,0x77,0x9e,0xbc,0xd4,0xe5,0x0b,0xdc,0x7e,0x0e,0xce,0x73,0x3a,0x53,0x7f,0xd7, +0x30,0xe7,0x41,0x15,0xdc,0x63,0x2f,0xf3,0x3b,0x9b,0xc7,0x70,0x9e,0x82,0x7d,0x2f, +0xba,0x4b,0x0f,0x9b,0xdc,0x78,0xa5,0xdf,0xe9,0x86,0xfa,0xe8,0x57,0x6b,0x51,0xff, +0x75,0x1c,0xcf,0x21,0x09,0x77,0xd5,0xae,0x7e,0x27,0x03,0x3a,0x61,0x7f,0x1f,0x1d, +0x7d,0x3d,0x6d,0xcb,0xc9,0xd9,0x34,0xf4,0x5b,0xbd,0x2b,0xfe,0xc1,0x55,0x7e,0x27, +0xba,0x3b,0x73,0x3c,0xf6,0x59,0xe8,0x40,0xf4,0x4a,0xfa,0xe2,0x3b,0xec,0xb3,0x00, +0x7b,0xd8,0x38,0xc7,0x29,0xc4,0xc1,0xb7,0x01,0xba,0x88,0xf9,0xe7,0xc9,0x9e,0x7e, +0x67,0x11,0xdc,0x49,0x98,0x07,0x12,0xdd,0xf1,0x1d,0x0e,0x0f,0x4d,0x61,0x3c,0x13, +0x6e,0x2a,0xf6,0x5b,0xe0,0x41,0x58,0xc8,0x3c,0x38,0xdf,0x28,0x2c,0x83,0x3d,0x50, +0xaf,0x8f,0x3f,0xef,0x1b,0x1b,0x65,0x26,0xd0,0xe6,0xf0,0x0c,0x44,0xc3,0x32,0xf8, +0x74,0x82,0xfb,0x0d,0x80,0xb6,0xe8,0x7a,0x78,0x1d,0x72,0x21,0xa5,0xaf,0xdf,0xe9, +0xd3,0x8f,0x3c,0xa1,0xd5,0x59,0xac,0x1c,0x26,0xcc,0x11,0x38,0x7b,0x22,0xe1,0x86, +0xf8,0x9d,0xab,0xd0,0x1a,0x03,0xfc,0xce,0xe5,0x6c,0xcb,0x86,0xf9,0xd8,0x37,0x0f, +0x64,0x1f,0xec,0x59,0xfa,0x96,0x49,0x4f,0xe8,0x0d,0xb3,0x61,0x32,0x9c,0x39,0x89, +0xf9,0xed,0x46,0xf7,0x1d,0xf9,0xaa,0xd0,0x07,0x6e,0x84,0xf7,0xd8,0xe7,0x63,0xd4, +0x37,0x99,0xb9,0x08,0x7b,0x17,0x7d,0x5f,0xbe,0xe7,0x70,0xbf,0xf3,0x1e,0xfa,0x11, +0x24,0xb3,0x58,0xfa,0x16,0x7d,0x89,0x63,0xd5,0xb3,0x23,0xfd,0x4e,0x8f,0x51,0x7e, +0x67,0x39,0x7e,0x6b,0x61,0x86,0xde,0xa9,0x37,0xef,0xd3,0x9b,0x6f,0xcf,0xcf,0xe2, +0xc4,0x76,0x0e,0xba,0x0a,0x4a,0xb3,0x46,0x18,0x01,0x35,0x39,0x69,0x0d,0x2f,0xe0, +0x77,0x36,0x60,0x5f,0x0a,0x87,0xe0,0x23,0xdc,0x6f,0xdf,0xee,0xbe,0x7f,0xbf,0x99, +0x13,0xda,0x03,0x70,0x17,0xeb,0x8c,0xc3,0x50,0x8c,0xf5,0x42,0xec,0x24,0xbf,0x53, +0x1a,0xad,0x7d,0x07,0x79,0x84,0xad,0xe6,0xdd,0x7c,0x38,0x7a,0x27,0xc7,0xc7,0xbb, +0xc8,0xcf,0x2d,0x7e,0xe7,0x96,0x69,0x8c,0x13,0x16,0x6f,0x8b,0xa7,0x99,0x74,0xfc, +0xce,0x1e,0xec,0x2f,0xdf,0x4d,0x3b,0x32,0x7f,0x47,0xdf,0x43,0xbf,0xe0,0x38,0x7b, +0xde,0x1d,0xcc,0xf3,0x2c,0xa4,0x86,0xc3,0x0e,0xfc,0x0a,0xde,0xe5,0x77,0x16,0x60, +0xbf,0x1b,0x35,0xef,0xf5,0x1b,0x2e,0x84,0xe7,0xa7,0xf9,0x9d,0x9d,0x68,0x22,0x8b, +0xc0,0x0b,0xa7,0xd3,0xee,0xb0,0x1a,0x7e,0x80,0x37,0xf0,0x8b,0xbb,0xdf,0x9f,0xf7, +0xfe,0x7f,0xda,0x03,0x1c,0x1f,0xe0,0x0d,0x16,0x8a,0x07,0xa0,0xe7,0x83,0xd8,0x39, +0x99,0xfe,0x06,0x7b,0x60,0xa6,0xdf,0x39,0xf3,0x11,0xbf,0x33,0x15,0xcc,0x77,0xec, +0x3b,0xb4,0x74,0xbf,0x5f,0xff,0x03,0x04,0x1e,0x76,0x9c,0x22,0x70,0xb6,0xbe,0x5f, +0x9f,0xf7,0xa0,0x09,0xd5,0xee,0x0f,0x0b,0x0f,0x44,0x44,0x16,0x88,0x2a,0x58,0xa8, +0xf0,0x19,0x67,0x12,0x24,0xef,0xb3,0xcd,0x67,0x15,0x2f,0x51,0xf2,0x6c,0xe6,0x4d, +0xe7,0xf8,0xef,0xdc,0x52,0x1c,0x33,0x9d,0x3f,0xe2,0x57,0xda,0x39,0xbf,0x4c,0xd9, +0x72,0xbf,0x71,0xa4,0xee,0x5f,0x4b,0xab,0x18,0x7d,0x81,0xeb,0xac,0xc4,0xe4,0x51, +0xa5,0xea,0x85,0xd5,0xaa,0xd7,0x88,0x89,0xad,0x19,0x17,0x9f,0x90,0xe8,0x24,0x25, +0xe7,0x2d,0xd3,0x7e,0xdd,0xaf,0x96,0x67,0xa9,0xed,0x3d,0xb6,0xf7,0x9b,0xfd,0xea, +0x9e,0xcc,0xb3,0x5e,0xfd,0x13,0x9c,0x0d,0x52,0x1b,0x3a,0x69,0x8d,0xd2,0x9d,0xc6, +0x4d,0x9c,0xfc,0x5f,0xfe,0x2f,0xff,0x97,0xff,0xcb,0xff,0xe5,0xff,0xf2,0x7f,0xf9, +0xbf,0xfc,0x5f,0xfe,0x2f,0xff,0x97,0xff,0xcb,0xff,0xe5,0xff,0xf2,0x7f,0xff,0xd0, +0xdf,0x9e,0x93,0xfd,0xf6,0xe6,0xf2,0xdb,0xbb,0xd5,0xfc,0x9f,0xbb,0x7e,0xfd,0xf1, +0xff,0xf5,0xf3,0x99,0x9f,0xb1,0x78,0xe1,0x0f,0xed,0x71,0x1d,0xb9,0xb9,0x4e,0xde, +0xff,0x38,0x88,0x62,0xcf,0x67,0xfb,0xf6,0x99,0x7f,0x27,0x44,0x9d,0x5f,0xe3,0x27, +0x6f,0x82,0xfc,0x6a,0xd0,0x2f,0xaf,0x53,0x99,0xff,0x3e,0x52,0xf7,0x72,0xfb,0x5c, +0x9e,0xdf,0x47,0xbb,0xf7,0xe4,0x5d,0xa3,0x2c,0x62,0x2e,0x4f,0xe6,0x5d,0x9f,0x3c, +0xc7,0x5c,0x94,0xdc,0x93,0xeb,0x9c,0x55,0xb0,0xe4,0x6f,0x3b,0x1e,0xca,0x96,0x2b, +0xff,0x4b,0x77,0x2d,0x6d,0xae,0x51,0x96,0xaf,0x50,0xd1,0x64,0x79,0x8f,0x4a,0x91, +0x1b,0x1a,0x28,0xfa,0xf7,0x1c,0xd5,0xae,0x25,0x37,0x4f,0x9d,0x93,0xe5,0xe6,0x24, +0xbf,0x0b,0x7e,0x26,0x66,0xb7,0x25,0x4c,0x8b,0x98,0x7f,0x79,0xd1,0xbb,0x66,0xcf, +0x5f,0x64,0xaa,0xcb,0x3d,0x9e,0xd1,0xdc,0xff,0x14,0xf4,0xf8,0xd4,0xe8,0xfc,0xe4, +0xfa,0x25,0xfd,0x38,0x37,0xf7,0x57,0xe5,0x55,0xd3,0xeb,0x2f,0x2c,0x5e,0xae,0x3d, +0x2d,0x2b,0xf7,0x6a,0x31,0x77,0x2b,0x9d,0x54,0x3d,0x33,0xf7,0x57,0xcf,0x3b,0x91, +0xa1,0x1e,0x51,0xea,0x20,0xbf,0x53,0x83,0x9e,0x34,0xfd,0x5f,0x56,0xcd,0x7f,0x70, +0xfa,0x4e,0x7e,0xfa,0xbf,0xe5,0xef,0xcf,0x52,0xfe,0x76,0x9d,0xff,0x09,0xf5,0x1f, +0x15,0xf5,0xa7,0x6a,0xff,0xdf,0x37,0xf1,0x9e,0x3d,0x4f,0x4c,0xaf,0x0f,0xbf,0xdf, +0x33,0xfd,0xe1,0xc3,0x4f,0x4c,0x7f,0xf4,0x68,0xf3,0x04,0xdc,0x6f,0xb8,0x0c,0xfb, +0x4f,0x47,0xaf,0x5c,0xcc,0xd6,0xff,0x32,0xe2,0x71,0xe3,0x9d,0x1b,0xf2,0x2c,0xe3, +0xf9,0xf1,0x3f,0xc7,0xad,0x28,0xe7,0xd7,0x1e,0x32,0x72,0x7f,0xef,0xce,0x16,0x79, +0x92,0xde,0xff,0x1b,0x54,0xfa,0xdf,0xef,0xcc,0xe6,0xaf,0x98,0xed,0x9f,0x6b,0xda, +0xa8,0x3f,0x77,0xee,0x7f,0xab,0xe5,0xcd,0x9f,0xeb,0xb7,0xfb,0x4f,0x96,0x9f,0x8f, +0xf6,0xfc,0xdd,0x46,0xeb,0x89,0xa7,0x79,0xff,0xcb,0xa3,0xf2,0xf1,0x8b,0x41,0xbf, +0x38,0x99,0x13,0x2f,0x09,0x38,0xb9,0xb9,0xf6,0xd9,0x76,0xe8,0x2f,0xf7,0x04,0xcb, +0xbe,0xbc,0xa0,0xff,0x83,0x75,0x57,0xd4,0xe9,0xd6,0xe9,0xaf,0xba,0x06,0xf6,0x6b, +0x0e,0x38,0x91,0xbf,0x51,0x3c,0xa7,0x5e,0x7a,0xfe,0x99,0x0e,0x39,0x3e,0xaf,0x7b, +0x98,0xff,0x1d,0x9f,0xfb,0xb3,0x8e,0xaf,0x7b,0xf2,0xc2,0xfd,0x5d,0x0e,0xb1,0xb9, +0xc7,0xfb,0xf8,0xbe,0x77,0x73,0xd7,0xef,0x39,0x9d,0xdf,0xde,0xdd,0xbb,0x73,0x3f, +0xd8,0xf3,0x59,0xee,0xdf,0x6f,0x0e,0xdb,0xb3,0xc7,0xe7,0x33,0x25,0xf4,0x19,0xf1, +0x1a,0x1b,0x7b,0xee,0x1e,0x5d,0xb2,0x76,0xfe,0xd1,0xbf,0x3f,0xdb,0x8a,0x2c,0xea, +0x77,0x28,0xf0,0x7f,0xfc,0x9d,0x7e,0x4c,0x1f,0xec,0xde,0xfb,0xd1,0x8e,0x1d,0xbf, +0x5b,0xcd,0x14,0x28,0xf0,0xb7,0xec,0x7f,0x27,0xb6,0xc9,0xcf,0xb7,0xde,0x6f,0xdf, +0x1f,0xfe,0xfb,0x6e,0xf8,0x67,0x5d,0xf7,0x47,0xfd,0xa2,0xfe,0xff,0x2b,0x2e,0x09, +0xe4,0xfe,0x29,0xaa,0x29,0xf2,0xaf,0x73,0x2e,0xf6,0xbf,0x18,0x40,0x79,0xb7,0x71, +0xd4,0x8c,0xe6,0xbe,0xc4,0x9f,0x72,0xda,0xfd,0xeb,0x0d,0x94,0x93,0xfe,0xce,0x73, +0xfe,0xe9,0xbf,0x3d,0xf6,0x4d,0xd8,0xdc,0xfc,0xfb,0xd4,0x7f,0xab,0x5f,0x6e,0x7e, +0x11,0xff,0xc0,0x51,0xf5,0x67,0xac,0xac,0xd3,0xce,0xd4,0x1e,0x5f,0xee,0x5f,0xe7, +0x40,0xf2,0x2b,0x4f,0x73,0x7f,0x93,0xc6,0xca,0x7f,0xca,0xe7,0x7f,0xb3,0x74,0xb7, +0x5b,0xf9,0x34,0x8e,0x4f,0x79,0x0f,0xae,0xe8,0x61,0x88,0x5f,0xf9,0x8c,0xc6,0x09, +0xb1,0xba,0x0f,0xc2,0xfc,0x37,0x11,0xee,0xf9,0x1b,0x5c,0x85,0x89,0xfa,0x6f,0x43, +0xfe,0xf7,0xf3,0x47,0x54,0xe4,0x6f,0xd4,0xa9,0x7e,0xf1,0xa0,0xfc,0xb5,0x17,0x50, +0x23,0xff,0x37,0x35,0xff,0x3b,0x5e,0x92,0x8d,0x8a,0xfc,0xeb,0x75,0xd1,0xc8,0xdf, +0xfc,0x50,0x15,0x79,0xfa,0xcf,0x5f,0x1c,0x3f,0xf5,0xfe,0xdf,0x1e,0x06,0xa2,0xa2, +0xa2,0xfe,0x90,0xb1,0x1f,0x79,0xca,0xb3,0xd5,0xfc,0xce,0xf8,0xb7,0x2e,0x7c,0xd4, +0x3f,0xa8,0xd8,0x51,0x4e,0xfe,0x2f,0x7f,0xd8,0xfd,0xff,0x95,0xc0,0x9f,0xba,0x22, +0xa2,0x7e,0x9f,0x38,0xa3,0xfe,0xa1,0xa3,0x2d,0x7f,0x4e,0xf8,0xdf,0x3c,0x0a,0x17, +0xf5,0x17,0x9b,0x03,0xfe,0x31,0x33,0x5e,0x7e,0x7f,0xff,0x6b,0xff,0x7e,0x7a,0x16, +0xe6,0xbf,0x3f,0x5f,0xce,0xbf,0x90,0xf5,0x17,0xfe,0x45,0x44,0xfc,0xa5,0x7a,0xeb, +0x9f,0x25,0x23,0xbf,0xee,0x42,0xe1,0xd6,0xad,0xee,0xa0,0xdb,0xb9,0xd5,0xfc,0x8e, +0xc7,0xe9,0xfe,0x7e,0x7a,0xa8,0xf1,0xe7,0x47,0xde,0x9f,0xb1,0x8d,0x4e,0xcc,0x96, +0x55,0x3e,0x53,0xe4,0xad,0x3f,0x5f,0x35,0x7f,0x78,0xee,0x4f,0x7c,0xd9,0x6f,0xcf, +0x09,0xef,0x4e,0xba,0x9b,0x7e,0xbf,0x8b,0xf7,0xf9,0x13,0xeb,0xff,0xb0,0x7a,0xfe, +0xe9,0x07,0xae,0xbd,0x7b,0xff,0xf1,0x8f,0x3f,0xe6,0xfe,0x33,0x07,0xcd,0x9e,0x9f, +0x46,0xc0,0xdf,0x7d,0x96,0xf9,0xe9,0x98,0xfa,0xbb,0x1f,0x43,0xfe,0xa2,0xd7,0xc3, +0xdc,0xaf,0xbf,0x06,0x02,0x91,0x81,0x02,0x51,0x05,0x03,0x81,0x42,0x81,0x9f,0x7e, +0x85,0x03,0x81,0x33,0xce,0x0c,0x14,0x29,0x1a,0xb0,0x7f,0xc5,0x02,0x7f,0xc3,0xdf, +0x59,0xc7,0xad,0xc5,0x4b,0x04,0x4a,0x9e,0x7d,0x0e,0x96,0x73,0x7f,0xa3,0xb8,0x4b, +0x59,0xf6,0xf3,0x02,0xf9,0xbf,0xfc,0x5f,0xfe,0x2f,0xff,0x97,0xff,0xcb,0xff,0xe5, +0xff,0xf2,0x7f,0xf9,0xbf,0xfc,0x5f,0xfe,0x2f,0xff,0x97,0xff,0xcb,0xff,0xe5,0xff, +0xfe,0x80,0x9f,0xcf,0xf9,0xa3,0x4c,0x98,0x13,0x70,0x22,0xf3,0x4c,0x15,0x27,0xc6, +0xa9,0xe5,0x34,0x76,0xba,0x3b,0x3d,0x9d,0x61,0xce,0x04,0x67,0xa6,0xf3,0xa8,0xf3, +0x8c,0xb3,0xc4,0x59,0xe1,0xbc,0xe5,0x1c,0x76,0xbe,0xc6,0x04,0x7c,0xc5,0x7d,0x15, +0x7c,0x19,0xbe,0x16,0xbe,0x8e,0xbe,0xce,0xbe,0x7e,0xbe,0x51,0x27,0x98,0xe9,0xbe, +0x87,0x7d,0xb3,0x7d,0x8b,0x7c,0xef,0xf9,0xde,0xf7,0x7d,0xea,0xfb,0xb7,0xaf,0xb8, +0xff,0x1c,0x7f,0x05,0x7f,0x8c,0x3f,0xd1,0x1f,0xf4,0x77,0xf7,0xf7,0xc6,0x8c,0xf2, +0x4f,0xf2,0xdf,0xe3,0x5f,0xe6,0x5f,0xe5,0x7f,0xd3,0xbf,0xc5,0xff,0xa9,0xff,0xc8, +0xff,0xd0,0x1c,0xfd,0x2f,0x8c,0x2f,0xcc,0x17,0x16,0x16,0x16,0x08,0x8b,0x0a,0x2b, +0x94,0x67,0x8a,0xff,0x64,0x4a,0xfe,0x64,0xca,0x84,0x45,0x87,0x55,0xc2,0x54,0x91, +0xa9,0x69,0x99,0x5a,0x98,0xd4,0xb0,0xba,0x61,0x0d,0xc3,0x1a,0xe5,0x99,0xcc,0x9f, +0x4c,0x8b,0x9f,0x4c,0xdb,0xb0,0x4e,0x61,0x9d,0x31,0x97,0xcb,0x74,0x3f,0xc1,0xf4, +0x0b,0x1b,0xf6,0x1f,0xcd,0xa8,0xb0,0x6b,0x7f,0x77,0x33,0x2e,0x6c,0xe2,0x29,0xcd, +0xa4,0xb0,0x9b,0x7e,0x32,0xb7,0x84,0xdd,0x76,0x82,0x99,0x12,0x36,0x35,0xec,0xce, +0xb0,0x69,0xa7,0x69,0xee,0xf9,0xd5,0x66,0x66,0xd8,0x9c,0xff,0x60,0x16,0x85,0xad, +0x38,0xc1,0xac,0xfa,0x5d,0xcc,0xcb,0x61,0xaf,0xfe,0x41,0x66,0x6d,0xd8,0x6b,0x61, +0x1b,0xc2,0x36,0xfe,0x64,0xde,0x0c,0x7b,0xeb,0x6f,0x61,0xb6,0xe4,0x9b,0x7f,0xb4, +0xf9,0x58,0xe6,0x33,0xcc,0x11,0x8c,0x2f,0xfc,0xb8,0x89,0xc2,0x14,0x92,0x39,0x47, +0xa6,0x42,0x9e,0x89,0xc6,0x54,0xca,0x33,0xc9,0x32,0xf5,0x31,0x99,0x98,0x4e,0x96, +0xc9,0xc6,0x74,0x97,0x19,0x26,0x33,0x2e,0x7c,0x52,0xf8,0x6d,0x79,0x66,0x8a,0xcc, +0x9d,0xbf,0x9b,0x99,0x76,0x12,0x33,0x3d,0xcf,0xdc,0x8f,0x99,0x19,0xfe,0x78,0xf8, +0x93,0xe1,0x73,0x31,0xf3,0x65,0x16,0xfe,0x64,0x5e,0x92,0x59,0x26,0xb3,0x02,0xb3, +0x2a,0xcf,0xbc,0x9a,0x67,0xd6,0x62,0x36,0x86,0xbf,0x15,0xbe,0x25,0x7c,0x1b,0xe6, +0x43,0x99,0xed,0x3f,0x99,0x4f,0x65,0x3e,0x93,0xd9,0x8f,0x39,0xf0,0xff,0xcc,0xc1, +0x5f,0x61,0x0e,0x87,0x1f,0xf9,0x5b,0x98,0xaf,0xc3,0xff,0xfd,0x1f,0xcd,0xd1,0xf0, +0xef,0x7e,0x91,0xc9,0x7f,0xba,0xe2,0x9f,0xfe,0xfb,0x2e,0xfc,0xb7,0x35,0xbe,0xc0, +0xaf,0x35,0x2c,0x89,0xff,0x61,0xe7,0x63,0x91,0x3f,0x6b,0xa2,0xf2,0x4c,0xa1,0xbf, +0x88,0x39,0x23,0xc4,0x14,0xc9,0x33,0xc5,0xf2,0xcd,0x69,0x99,0x92,0xff,0x78,0x53, +0xfa,0x4f,0x69,0xca,0xfc,0x4e,0xa6,0x42,0x20,0xfa,0x1f,0x6e,0x2a,0xfd,0xe3,0x4c, +0x95,0x13,0x4c,0x8c,0x4c,0xcd,0x7f,0xac,0x49,0x0c,0x24,0xe7,0x9b,0x9f,0x35,0x75, +0xf3,0x4c,0xfd,0x3f,0xa1,0x69,0x98,0x6f,0xfe,0xe2,0xa6,0x11,0xa6,0x31,0x26,0x88, +0xc9,0xc0,0x64,0xca,0xb4,0xf8,0xcd,0x4d,0x4b,0x4c,0x6b,0x4c,0x9b,0x40,0xdb,0x3c, +0xd3,0x3e,0xdf,0xfc,0x43,0x4c,0xc7,0x40,0xa7,0xdf,0xc4,0x74,0x0e,0x5c,0x7e,0x82, +0xb9,0x32,0x90,0xfd,0x87,0x99,0xee,0x81,0xde,0xbf,0xc8,0xf4,0x09,0xf4,0x3b,0x2d, +0x33,0x20,0x30,0xe8,0x77,0x32,0xa3,0x02,0xe3,0x02,0x13,0x02,0x13,0x03,0x93,0x02, +0x37,0x05,0x6e,0x09,0xdc,0x16,0x98,0x16,0x78,0x30,0xf0,0x70,0x60,0x66,0xe0,0xd1, +0xc0,0xe3,0x81,0x27,0x03,0xb3,0x03,0xcf,0x04,0xe6,0x9f,0x60,0x16,0x05,0x96,0x9c, +0x60,0x56,0x05,0x5e,0x0b,0x6c,0x08,0x6c,0x0c,0xbc,0x19,0x78,0x2b,0xb0,0x25,0xf0, +0x4e,0xe0,0xc3,0xc0,0x27,0x81,0x4f,0x03,0x9f,0x05,0xf6,0x07,0x0e,0x04,0x0e,0x06, +0x0e,0x07,0xfe,0x1d,0xf8,0xfe,0x04,0x13,0x16,0x11,0x75,0x82,0x39,0x23,0xa2,0xd8, +0x09,0xa6,0x64,0x44,0xa9,0x13,0x4c,0xb9,0x88,0x4a,0x21,0xa6,0xfa,0x09,0x26,0x31, +0xa2,0x6e,0x44,0xfd,0x88,0x86,0x11,0x8d,0x22,0x1a,0x47,0x04,0x23,0x32,0x22,0x5a, +0x47,0x74,0x8c,0xe8,0x14,0xd1,0x39,0xe2,0xf2,0x88,0x2b,0x23,0xb2,0x23,0xba,0x45, +0x74,0x97,0xe9,0x19,0x62,0x7a,0xff,0x01,0xa6,0xcf,0xff,0x33,0x83,0x4e,0x30,0x43, +0xfe,0xc7,0x66,0x58,0x88,0xb9,0x26,0xdf,0x9c,0x86,0xb9,0x16,0x73,0x3d,0x66,0xdc, +0x1f,0x64,0x26,0x60,0x26,0x62,0x26,0xfd,0x8f,0xcd,0x4d,0x3f,0x99,0x5b,0xf2,0xcc, +0x6d,0xbf,0xd0,0x4c,0xc1,0x4c,0xfd,0x45,0xe6,0xce,0x13,0xcc,0x34,0xcc,0x3d,0x79, +0x66,0xfa,0x4f,0xe6,0xfe,0xd3,0x34,0x0f,0xe6,0x99,0x87,0x23,0x66,0x9e,0xd2,0x3c, +0x1a,0xf1,0x78,0x9e,0x79,0x32,0x62,0x76,0x9e,0x99,0x13,0xf1,0x4c,0xc4,0xdc,0x88, +0xf9,0x3f,0x99,0x85,0x11,0x8b,0xf2,0xcc,0xe2,0x88,0x25,0x27,0x31,0x2f,0x45,0x2c, +0xfb,0x19,0xb3,0xc2,0x32,0xab,0x22,0x5e,0xc6,0xbc,0x7a,0x82,0x59,0x1b,0xf1,0x5a, +0xc4,0x86,0x88,0x8d,0xf9,0xe6,0x67,0xcd,0x9b,0x3f,0x99,0xb7,0x30,0x5b,0x30,0xef, +0x60,0xde,0xc3,0xbc,0x8f,0xd9,0x86,0xf9,0x10,0xb3,0x1d,0xf3,0x31,0x66,0x17,0xe6, +0x13,0xcc,0xa7,0x79,0xe6,0x33,0xcc,0x7e,0xcc,0x81,0x13,0xcc,0xe1,0x3c,0xf3,0x75, +0x9e,0x39,0x9a,0x67,0xbe,0xcf,0x33,0xbe,0xc8,0x5f,0x6f,0xc2,0xfe,0x9f,0x39,0x7e, +0x21,0xd7,0xfc,0xa2,0x30,0x85,0x30,0x67,0x60,0x8a,0x60,0x8a,0x61,0x8a,0x63,0x4a, +0x62,0xce,0xc1,0x94,0xc2,0x94,0xc6,0x94,0xc9,0x33,0xe5,0x30,0x15,0x30,0xd1,0x27, +0x98,0x2a,0x79,0xa6,0x7a,0x9e,0xa9,0x99,0x67,0x12,0xf3,0x4c,0xad,0xd3,0x34,0xa9, +0x91,0x75,0x23,0xeb,0x47,0x36,0x3c,0xa9,0x69,0x94,0x6f,0xfe,0x32,0xa6,0x71,0x88, +0x09,0xe6,0x9b,0x3f,0xd4,0x64,0x60,0x32,0x4f,0x62,0x5a,0xe4,0x9b,0x53,0x98,0x96, +0x91,0xad,0xf3,0x4d,0xbe,0x39,0x4d,0xd3,0xf6,0x0f,0x31,0xed,0x31,0x1d,0x4f,0x30, +0x9d,0x7e,0x32,0x9d,0x7f,0x07,0x93,0x9d,0x6f,0xfe,0x51,0xa6,0x67,0xbe,0xf9,0x47, +0x9b,0xde,0x91,0x7d,0xfe,0xb1,0xa6,0x5f,0xbe,0xf9,0xdb,0x99,0x61,0x79,0x66,0x54, +0xe4,0x35,0x27,0x98,0x6b,0xf3,0x4d,0xbe,0xf9,0xdd,0xcd,0xf5,0x32,0xe3,0x30,0x13, +0xf2,0xcd,0x2f,0x30,0xee,0xf3,0xa2,0xb5,0xc3,0x1c,0xa7,0x7f,0x45,0x57,0xbb,0x48, +0x07,0xa0,0x0e,0xba,0xd2,0x7c,0x5a,0x07,0x5d,0x85,0xfa,0xd1,0xd5,0xc6,0x1b,0x7d, +0x19,0x0d,0x0f,0x73,0x3f,0x6d,0x18,0x81,0xfa,0xd1,0x48,0xb4,0xb2,0xdf,0x71,0x0a, +0xa0,0xaf,0x98,0x8f,0xac,0xa2,0x8f,0x94,0x75,0x9c,0x82,0xe8,0xab,0xb8,0x0b,0xa3, +0x1b,0x09,0x57,0xc4,0xec,0x47,0xb8,0x62,0x66,0x3f,0x34,0x1a,0x9d,0x41,0xb8,0x4a, +0xc6,0x1f,0xad,0x8a,0x86,0x2b,0x3e,0x7f,0x59,0x77,0x7b,0x38,0x1a,0x8f,0x46,0x94, +0x75,0xf3,0x13,0xe1,0x73,0xf3,0x53,0x40,0xe1,0x0a,0xfa,0xdc,0xf8,0x0b,0xa3,0x55, +0xd0,0xb5,0x8e,0xfc,0xcb,0xba,0xfe,0x67,0xfa,0xdc,0x78,0x0a,0x97,0x75,0xb7,0x17, +0x45,0x63,0xd0,0xb3,0x14,0xef,0x99,0x65,0xdd,0xf2,0xae,0x53,0x79,0x5f,0x53,0x79, +0xd7,0xab,0xbc,0x4b,0xcb,0xba,0xe5,0x3d,0x4b,0xe5,0x2d,0xa1,0x74,0xcf,0xf6,0xb9, +0xe5,0xdd,0xa0,0xf2,0xbe,0xa8,0xf4,0xce,0x53,0x39,0xc3,0x55,0xce,0x08,0x95,0xf3, +0x05,0xa5,0x5f,0xd5,0xef,0x96,0xf3,0x5c,0x9f,0x9b,0x8f,0x73,0xf1,0x8f,0x33,0xfb, +0x95,0x75,0xe3,0x2d,0xab,0x72,0x7e,0xa5,0x72,0x9e,0xef,0x73,0xd3,0x2f,0x5f,0xd6, +0x4d,0xbf,0xac,0xd2,0x2f,0xaf,0x72,0xef,0x51,0xb9,0x2b,0x2a,0xfc,0x05,0xda,0x5e, +0xb1,0xac,0x9b,0xbf,0xca,0xca,0x57,0x59,0xe5,0xe3,0x02,0x2f,0x1f,0x68,0x2c,0x5a, +0x4d,0xe5,0x7f,0x5d,0xe5,0xdf,0xa8,0xf2,0xbf,0xa1,0xf2,0x57,0x55,0xfa,0xd5,0x54, +0xfe,0x1a,0x8a,0x3f,0x4e,0xe5,0x7f,0x53,0xe5,0x5f,0xa7,0x74,0xde,0x54,0xf9,0x0b, +0xa8,0xfc,0x05,0x95,0xee,0x7a,0xb5,0x6f,0xac,0xcf,0x2d,0x6f,0x8d,0xb2,0x6e,0x3a, +0x49,0x3e,0x37,0xdd,0x38,0xed,0xbf,0x57,0xed,0x95,0xa0,0x7c,0xa6,0xf8,0xdc,0x76, +0x4a,0x52,0xbd,0xa4,0xaa,0xdc,0xf5,0x15,0x2e,0x45,0xe1,0xea,0xaa,0x3e,0xeb,0xa9, +0x5d,0xeb,0x28,0x7c,0x03,0xd5,0x6b,0x9a,0xfa,0x53,0xba,0xca,0xfb,0x8d,0xd2,0x6d, +0xec,0x73,0xcb,0xf9,0x96,0xfa,0x4d,0x13,0xe5,0x23,0x43,0xf1,0x37,0x55,0xfc,0x41, +0xc5,0xdf,0x5c,0xf1,0x37,0x53,0x3c,0x9b,0x55,0x6f,0x5b,0x54,0x6f,0x6f,0xab,0xde, +0xde,0xd1,0x38,0xb9,0x48,0xf5,0xd6,0x4a,0xf5,0x16,0xab,0x71,0xf2,0xae,0xea,0xed, +0x0d,0xe2,0x29,0x84,0x66,0xa9,0x5c,0x6f,0xa9,0xfe,0x0a,0xab,0xfe,0xce,0x44,0x4b, +0x9b,0x71,0xa2,0xfc,0xbc,0xae,0x7a,0xdc,0xa7,0xfc,0xb7,0x53,0xf9,0x3a,0xa8,0xbc, +0xed,0x94,0xce,0x25,0x2a,0xc7,0x25,0x8a,0xaf,0xa8,0xe2,0x3b,0x4b,0xed,0x71,0xa9, +0xca,0xd5,0x41,0xf5,0x7b,0x85,0xf6,0xbf,0x54,0xfd,0xe8,0x32,0xc5,0xd3,0x45,0xf1, +0x74,0x51,0xfa,0x5d,0x71,0x57,0x36,0xfd,0xd6,0xef,0xee,0x7f,0x85,0xc2,0x5d,0xad, +0x70,0x57,0x29,0x5c,0x5f,0x85,0x3b,0x4f,0xe1,0xba,0xaa,0xfe,0x06,0xaa,0xfe,0xfa, +0xab,0xfe,0xde,0x57,0xfd,0x7d,0xa0,0xfa,0xdb,0xa6,0xfa,0xeb,0xa5,0x7e,0x77,0xb5, +0xea,0xaf,0xaf,0xfa,0x5b,0xae,0xea,0x6d,0x8f,0xe6,0x97,0xfe,0x3e,0xb7,0xfe,0x06, +0xaa,0xfe,0xb6,0xa8,0xbc,0x25,0x54,0xde,0xb3,0x55,0x7f,0x73,0x95,0xaf,0xdd,0xec, +0x77,0x01,0x3a,0x58,0xf5,0x38,0x58,0xf9,0x1a,0xae,0x71,0x38,0xb4,0xac,0x9b,0xfe, +0x18,0xf5,0x97,0xeb,0x94,0xcf,0xb1,0xaa,0x9f,0xf1,0xea,0xb7,0x43,0x55,0xee,0x1b, +0x35,0xce,0x6e,0x50,0xf8,0xc9,0x6a,0x8f,0x9b,0xe5,0x7f,0xab,0xf6,0xff,0x52,0xfb, +0x7f,0xa8,0x72,0x0e,0x57,0xbf,0xfb,0x46,0xf3,0x4b,0x82,0xdf,0xdd,0xef,0x76,0xed, +0x37,0xd2,0xe7,0x96,0xf3,0x5f,0x8a,0xf7,0x2b,0xed,0x3f,0x4a,0xed,0x93,0xa3,0x74, +0xae,0x51,0xb9,0xaf,0x55,0xf9,0xee,0x50,0xfd,0xde,0xa5,0x74,0x77,0xa8,0x7e,0x3f, +0x56,0xba,0x3b,0x55,0xbf,0xbb,0xd4,0x3f,0x7d,0xaa,0xdf,0x30,0x95,0xa7,0x8a,0xfa, +0xe7,0x6e,0xd5,0xf3,0xa3,0xaa,0xe7,0x4f,0x34,0x8f,0xbf,0xa1,0xfa,0xf5,0xa9,0x7e, +0xc3,0xd4,0x9f,0x66,0x6a,0x1e,0xf7,0xa9,0x5e,0x03,0x8a,0x2f,0x4c,0xf9,0x0f,0x28, +0x5f,0x91,0x2a,0x47,0xa4,0xca,0x11,0xa5,0x70,0x85,0x54,0x8e,0x33,0x34,0x9f,0x7d, +0xaa,0xf1,0x58,0x48,0xfd,0xaa,0x88,0xca,0x77,0x86,0xfa,0x6d,0x31,0xcd,0xe3,0xc5, +0x15,0x6f,0x11,0x95,0x77,0xaf,0xca,0xfb,0x99,0xca,0xbb,0x4f,0xe5,0x5d,0xa6,0x7a, +0x2e,0xae,0xf2,0x96,0x54,0xba,0xe7,0xa8,0x5f,0xed,0x57,0x79,0x5f,0x52,0x7a,0xa5, +0x55,0xce,0x80,0xca,0x19,0xa9,0x72,0x2e,0x51,0xfa,0x17,0x6a,0x1e,0x2f,0xa5,0xfe, +0x53,0x4a,0xfd,0xa7,0xb4,0xda,0xa5,0x9c,0xca,0xf9,0xb5,0xca,0x59,0x46,0xfd,0xb9, +0x82,0xe6,0xf1,0x72,0x4a,0xbf,0x82,0xca,0xfd,0xa9,0xca,0x1d,0xad,0xf0,0x95,0xb4, +0x3d,0x5a,0xfd,0xa1,0x8a,0xf2,0x55,0x4e,0xf9,0xa8,0xe4,0xe5,0x43,0xf3,0x78,0x75, +0xd5,0xc3,0xdd,0xaa,0x87,0xcf,0x55,0x0f,0x07,0x54,0x0f,0x5f,0xa8,0x1e,0x2e,0x54, +0x3e,0xaa,0xab,0x1e,0x62,0x54,0xfe,0x83,0x2a,0xff,0x6b,0x4a,0x67,0x93,0xca,0x1f, +0xa5,0xf2,0x17,0x52,0xba,0x1b,0xd4,0xbe,0x35,0x35,0x8f,0xc7,0x68,0x3c,0x24,0xab, +0x1c,0x87,0x34,0x2f,0xc5,0x2b,0x9e,0xcf,0xd4,0x6e,0x89,0xca,0x6f,0x2d,0xcd,0x37, +0xc9,0xaa,0x9f,0x3a,0xda,0xaf,0x81,0xc2,0xd5,0x52,0xb8,0x7a,0xaa,0xd7,0xfa,0x2a, +0x57,0x5d,0x85,0x6f,0xa8,0xfa,0x6d,0xa4,0x7e,0xd5,0x58,0xe5,0x3d,0xaa,0x74,0x9b, +0x68,0x5c,0x1d,0x56,0xff,0x09,0x2a,0x1f,0xcd,0x14,0x7f,0x86,0xe2,0x6f,0xaa,0xf8, +0x5b,0x28,0xfe,0x4c,0x6f,0x9c,0xaa,0xde,0x8e,0xa8,0xde,0xbe,0x52,0xbd,0x7d,0xad, +0xf1,0xd2,0x52,0xf5,0xd6,0x5a,0xed,0x53,0x53,0xe3,0xe5,0x5f,0xaa,0xbf,0x37,0x35, +0x9f,0xb7,0x51,0xb9,0x36,0xab,0x1e,0xcf,0x50,0x3d,0x16,0xd1,0x7c,0x34,0x53,0xf9, +0xd9,0xa8,0xfa,0xdc,0xaf,0xfc,0xb7,0x57,0xf9,0x3a,0xaa,0xbc,0xed,0x95,0x4e,0x27, +0x95,0xa3,0x93,0xe2,0x2b,0xa6,0xf8,0x8a,0xab,0x5d,0x3a,0xab,0x5c,0x1d,0x55,0xbf, +0x57,0x6a,0xff,0xce,0xea,0x4f,0x97,0x2b,0x9e,0x6c,0xc5,0x93,0xad,0xf4,0xbb,0x69, +0x9e,0x2e,0xa5,0x79,0xfa,0x4a,0x85,0xeb,0xa3,0x7e,0x77,0x8f,0xc2,0x77,0x57,0xf8, +0x7e,0x0a,0x5f,0x5a,0xe1,0xbb,0xa9,0x1e,0x07,0xa9,0x1e,0x07,0x78,0xed,0xa1,0x7a, +0xfc,0x56,0xf5,0xf8,0x9d,0xea,0xb1,0xb7,0xfa,0x5f,0x1f,0xd5,0x63,0x3f,0xf5,0xbf, +0x63,0xaa,0xbf,0x4f,0x35,0xdf,0x0c,0xd0,0xbc,0x3e,0x48,0xf5,0xf8,0xb6,0xca,0x5d, +0x52,0xe5,0x3e,0x47,0xf5,0x38,0x4f,0xf9,0xfa,0x44,0xf3,0xfa,0x10,0xd5,0xe7,0x10, +0xe5,0x6b,0x84,0xc6,0xe5,0x30,0xcd,0xeb,0xd7,0xaa,0xdf,0x5c,0xaf,0x7c,0x8e,0x53, +0x3d,0x4d,0x50,0x3f,0x1e,0xa6,0xf2,0x4f,0x52,0xf9,0x27,0x2a,0x3f,0xf7,0x6a,0xbf, +0x9b,0xd4,0x3e,0xb7,0x68,0xfb,0x6d,0x8a,0xe7,0x88,0xe2,0xf9,0x5e,0xe5,0x1d,0xa1, +0x7e,0x78,0x54,0xf3,0x4e,0xa2,0xe6,0xf7,0x29,0xda,0xef,0x47,0x95,0xf7,0xdf,0x8a, +0x7f,0xba,0xe2,0xff,0x5a,0xf1,0x8c,0x56,0xbb,0x4d,0x55,0x7a,0x63,0x54,0x0f,0xd7, +0xa9,0xbc,0x77,0xaa,0xbe,0xa7,0x29,0xfd,0x03,0xe5,0xdc,0xfd,0x26,0x9a,0x35,0x8e, +0x59,0xb7,0x97,0x73,0xfd,0x9f,0x50,0x7c,0x8f,0xa9,0xfc,0x4f,0x95,0x75,0xd3,0x9d, +0xa5,0x7c,0x7d,0xa4,0x7e,0xf7,0xad,0xf4,0x98,0xda,0x67,0xa7,0xdc,0x05,0x14,0xff, +0x4a,0xc5,0xb3,0x5c,0xf1,0xbc,0xa2,0x78,0x56,0xcb,0x3f,0xd6,0x5b,0x0f,0xc9,0xbd, +0x49,0xe1,0xde,0x55,0xb8,0xb7,0xe5,0x7f,0x91,0xd2,0xad,0xa1,0x71,0xd3,0x4a,0xee, +0x6a,0x7e,0x77,0xfb,0x0f,0x3e,0x37,0x9e,0x6d,0x4a,0xff,0x3d,0xe5,0xe7,0x1d,0x95, +0xff,0x7d,0x6d,0x7f,0x52,0xf1,0x3d,0xae,0x74,0xe6,0x28,0x9d,0xd9,0x8a,0x6f,0xbb, +0xf6,0xff,0x4e,0xfa,0xbd,0xe2,0xd9,0x25,0x77,0x94,0xf2,0xbb,0x4a,0xf1,0xac,0x50, +0x3c,0xaf,0x2a,0x9e,0x97,0xe5,0x5f,0x53,0xe1,0xb6,0xc8,0xfd,0x96,0xc2,0xbd,0xa7, +0x70,0xef,0xc8,0xbf,0xa5,0xd2,0x8d,0x51,0xb9,0x5a,0xcb,0x5d,0x5d,0xe5,0xfa,0x51, +0xf9,0xce,0x55,0xfa,0x5b,0x95,0x9f,0x77,0x55,0xae,0x0f,0xb4,0x7d,0x9e,0xe2,0x7b, +0x56,0xe9,0x3c,0xa7,0x74,0x16,0x28,0x1f,0xf3,0xb5,0x7d,0xae,0xb6,0x2f,0xd2,0xf6, +0x85,0xda,0x5e,0x42,0xdb,0xcf,0x96,0xbb,0xa4,0xdc,0xe7,0xc8,0x9d,0x25,0xf7,0xc5, +0x72,0xb7,0x91,0xbb,0xad,0xfa,0xd9,0x55,0xd2,0xee,0xd2,0x1e,0xd2,0x9e,0x0a,0x37, +0xd2,0x5b,0x87,0xa8,0x1f,0x8f,0x96,0x5e,0xa3,0x70,0xf7,0x2b,0xde,0x5c,0x85,0xfb, +0x40,0xf9,0xdc,0xa1,0x7c,0x7e,0xa4,0x7e,0xbe,0x53,0xe1,0x3e,0x54,0xb8,0x6d,0x0a, +0xf7,0xb1,0xc2,0x6d,0x57,0xb8,0x5d,0x0a,0xb7,0x4f,0xe1,0xf6,0x2a,0xdc,0x17,0x0a, +0xf7,0xb9,0xc2,0x1d,0x52,0xb8,0xfd,0x0a,0xf7,0x99,0xc2,0x1d,0x54,0xb8,0x03,0x0a, +0x77,0x58,0xf3,0xd9,0x17,0xaa,0xff,0xcf,0xa5,0x07,0xa4,0x3b,0xa4,0x1f,0x6b,0x7e, +0x3a,0x5f,0xc7,0xeb,0x32,0x6a,0xcf,0x38,0xbf,0xab,0xf1,0x7e,0x37,0x9e,0x83,0x6a, +0xb7,0x17,0x35,0xfe,0x6e,0x0c,0x73,0xb7,0x2f,0x29,0xe7,0xee,0xf7,0x02,0x5a,0xdc, +0x8c,0x23,0xb4,0x84,0xe9,0x77,0x68,0xd0,0x9c,0x57,0x6a,0x7c,0xae,0xd3,0x7e,0x93, +0xc3,0xdc,0x70,0xe7,0x2a,0x5c,0x29,0x6d,0x5f,0xaf,0xed,0x37,0x69,0x7b,0x55,0x6d, +0xbf,0x50,0xf1,0xbc,0xae,0x70,0x1f,0x28,0xdc,0xcd,0x4a,0xff,0x7d,0xa5,0xbf,0xb5, +0x9c,0xdb,0x3e,0x4f,0x69,0xff,0xda,0xda,0x3f,0x55,0xfb,0x7d,0xa3,0xfd,0x6e,0xd5, +0xf6,0x66,0xda,0x9e,0x29,0xfd,0x5c,0xe1,0xf6,0x29,0xdc,0xed,0x8a,0xff,0x33,0xc5, +0xbf,0x57,0xf1,0xcf,0x09,0x73,0xc3,0x77,0x52,0xf8,0x6f,0x15,0x7e,0x8a,0xe2,0xed, +0xa5,0xf8,0x7a,0x2b,0xdf,0xc7,0xa4,0xcf,0x49,0x5f,0xd1,0x7e,0x03,0xb5,0xdf,0xd3, +0x4a,0x67,0xbe,0xd2,0x99,0xa7,0x7a,0x74,0x14,0x8f,0xaf,0x9c,0x3b,0xcf,0x3d,0xaf, +0xfd,0x17,0x6a,0xff,0xc1,0xda,0xff,0x19,0xa5,0x5b,0x54,0xe1,0x8b,0x69,0xfb,0x50, +0x6d,0x7f,0x56,0xdb,0xcb,0x6b,0x7b,0x05,0xc5,0xb7,0x46,0xf1,0xbd,0xac,0xf0,0xc3, +0x15,0x7e,0xae,0xf2,0xf3,0x96,0xf2,0xb3,0x49,0xe5,0x5e,0xaf,0x78,0xe2,0x14,0x4f, +0xbc,0xe2,0x79,0x57,0xfb,0x8f,0xd4,0xfe,0xaf,0x2b,0x5c,0x9a,0xc2,0x35,0x52,0x79, +0x76,0xcb,0xfd,0x89,0xc2,0x8f,0x56,0xf8,0x8d,0x4a,0xef,0x63,0xa5,0xb7,0x43,0xe9, +0x6d,0x50,0x3c,0x59,0xda,0xaf,0x8d,0xd2,0xdb,0xa3,0xfd,0xc7,0x68,0xff,0x37,0x14, +0xae,0x8b,0xc2,0x65,0x2b,0xdc,0xbf,0x54,0xbe,0x23,0x0a,0xbf,0x59,0xe1,0x73,0x74, +0xdc,0x78,0x4f,0xfe,0x3b,0xe5,0x3f,0x4f,0xfe,0x9f,0x6a,0xbf,0xaf,0xe4,0xbf,0x25, +0xcc,0xcd,0xcf,0xdb,0xd2,0xc8,0x70,0xd5,0x4b,0xb8,0xeb,0xde,0x1c,0xee,0x86,0x0b, +0x0b,0x77,0xe3,0x73,0xb4,0xfd,0x5d,0x6d,0xf7,0xc9,0xbd,0x4a,0xee,0x5c,0xe9,0x47, +0x0a,0x7f,0x46,0xb8,0x8e,0x43,0x0a,0x57,0x4a,0xdb,0x77,0x2b,0xde,0xc2,0x72,0xef, +0x51,0xb8,0x2f,0x14,0xee,0x4c,0xf9,0x1f,0x0a,0x77,0xd7,0x0f,0x5f,0xca,0xfd,0x95, +0xf4,0x1b,0xe9,0xe7,0x0a,0xff,0x96,0xdc,0x5b,0x14,0x6f,0x5b,0xa5,0x9f,0xa5,0xed, +0xef,0x69,0x7b,0x1b,0xb9,0x57,0xcb,0xfd,0xa1,0x74,0xbb,0xc2,0x5f,0xae,0x7c,0xec, +0x52,0xb8,0x54,0x6d,0xff,0x44,0xf1,0x5e,0x26,0xf7,0xa7,0x0a,0x77,0x50,0xe1,0xae, +0x90,0xff,0x61,0xe5,0xf7,0x88,0xdc,0x5f,0x4b,0x8f,0x4a,0x0f,0x48,0x3b,0x86,0xbb, +0xeb,0xa0,0xe1,0xd2,0x11,0xf2,0xff,0x40,0xba,0x4d,0xba,0x4f,0xba,0x1f,0x6d,0x1b, +0xe1,0x38,0x15,0xa1,0x1d,0x44,0x43,0x7b,0xa8,0x24,0xf7,0x05,0xd2,0xca,0xd2,0xd5, +0xd2,0x2d,0xd2,0x95,0x50,0x2f,0x8a,0xf9,0x26,0xca,0xd5,0x78,0x69,0x12,0x2c,0x87, +0x0d,0xf0,0x1e,0xbc,0x0e,0x0d,0x0a,0xb1,0x9e,0x86,0x0e,0xd0,0x0c,0x3a,0xc2,0x45, +0xf0,0x1e,0xdc,0x05,0xcb,0x61,0xbd,0xdc,0xaf,0xcb,0xbd,0xc1,0x84,0x2f,0x4c,0x78, +0x78,0x07,0x56,0xc2,0x6a,0x58,0x2f,0xf7,0x5a,0x78,0x17,0xd6,0xc9,0xbd,0x01,0x1a, +0x9c,0xe1,0x38,0xcd,0xa1,0x23,0x5c,0x74,0x86,0xeb,0x6e,0x01,0xeb,0xe1,0x03,0x78, +0x13,0x72,0x61,0x3b,0x7c,0x24,0xff,0x0f,0x21,0xb6,0x28,0xe5,0x84,0xe4,0xd2,0xd4, +0x7d,0x69,0x57,0x0b,0x48,0x0b,0x4a,0x0b,0x4b,0xcf,0x94,0x9e,0x25,0xad,0x2b,0xad, +0x2f,0x4d,0x93,0x36,0x92,0x36,0x2e,0xed,0xb6,0x6b,0x6d,0x1d,0x27,0x52,0xa5,0x97, +0x49,0x2f,0xd7,0xf1,0xb1,0x97,0xb4,0xb7,0xd6,0x9b,0x4f,0xeb,0xf8,0xf2,0xbc,0xdc, +0xcf,0xc8,0xbd,0x58,0xee,0x35,0xd2,0xb5,0xd2,0xad,0xd2,0xf7,0x75,0xbc,0xf3,0x6b, +0x3c,0x86,0x6b,0x7c,0x47,0x68,0x9c,0x8e,0xd5,0x38,0x0e,0xd3,0xf6,0x80,0xb6,0x47, +0x6a,0xfb,0x38,0xe9,0x78,0xe9,0x04,0xe9,0x0d,0xd2,0x89,0xd2,0x1b,0xa5,0x93,0x14, +0x5f,0x41,0xc5,0x57,0x58,0xf1,0x9d,0xa9,0xed,0x93,0xb5,0xbd,0x90,0xb6,0x9f,0xa1, +0xed,0x45,0xb4,0xfd,0x26,0xe9,0xcd,0xd2,0x5b,0xa4,0xb7,0x4a,0x6f,0x93,0xde,0x2e, +0x9d,0xa2,0xf8,0xce,0x52,0x7c,0x25,0xe4,0x2e,0x2e,0x77,0x49,0xb9,0xcf,0x93,0xfb, +0x7c,0xb9,0x4b,0xcb,0x5d,0x46,0xee,0x8a,0x72,0x5f,0xa0,0xfc,0x54,0x56,0xfc,0x39, +0xda,0x1e,0xad,0xed,0x95,0xb4,0xbd,0x8a,0xb6,0x4f,0x95,0xde,0x21,0xbd,0x53,0x7a, +0x97,0x74,0x9a,0xf4,0x6e,0xe9,0x3d,0x8a,0xaf,0x9a,0xe2,0xab,0xa1,0xf8,0x62,0xb5, +0xfd,0x5e,0x6d,0xaf,0xae,0xed,0x31,0xda,0x5e,0x53,0xdb,0xa7,0x4b,0xef,0x93,0xde, +0x2f,0x7d,0x40,0xfa,0xa0,0xf4,0x21,0xe9,0xc3,0x8a,0x2f,0x41,0xf1,0x25,0x29,0xbe, +0x14,0xf9,0x27,0xca,0x3f,0x59,0xfe,0xb5,0xe4,0x5f,0x47,0xfe,0xf5,0xe4,0xdf,0x40, +0xfe,0x75,0xe5,0x5f,0x5f,0xfe,0x0d,0xe5,0x9f,0x2e,0xff,0x26,0x72,0x37,0x96,0x3b, +0x28,0x77,0x73,0xb9,0x2f,0x92,0xbb,0x85,0xdc,0x2d,0xe5,0xbe,0x58,0xee,0x76,0x8a, +0xb7,0x83,0xfc,0xdb,0xca,0xbf,0xbd,0xfc,0x3b,0xca,0xbf,0xb3,0xfc,0x2f,0x97,0xff, +0x95,0xf2,0xef,0x2a,0xff,0xab,0xe4,0xdf,0x43,0xf5,0x30,0x43,0xdb,0xbb,0x69,0x7b, +0x77,0x6d,0xef,0xa9,0xed,0x33,0xa5,0x8f,0x48,0x1f,0x95,0x3e,0x26,0x7d,0x5c,0xfa, +0x84,0xf4,0x49,0xc5,0x77,0xb5,0xe2,0xeb,0xab,0xf8,0xfa,0x6b,0xfb,0x2c,0x6d,0xef, +0xa3,0xed,0xfd,0xb4,0x7d,0x80,0xb6,0xcf,0x96,0x3e,0x25,0x9d,0x23,0x7d,0x5a,0xfa, +0x8c,0xf4,0x59,0xe9,0x5c,0xe9,0x02,0xe9,0x6a,0xe9,0x97,0xd2,0xc5,0x4a,0x6f,0xa3, +0x77,0x5c,0x57,0x7a,0x6f,0x6a,0xfb,0x5a,0xe9,0xbf,0x15,0xee,0x43,0x85,0xfb,0x48, +0xe1,0xb6,0x97,0x73,0xef,0xeb,0xdc,0x57,0xc1,0xd5,0xfb,0xa5,0xcf,0x4a,0x37,0x4a, +0xdf,0x94,0xbe,0x21,0x0d,0xd7,0xfd,0xa0,0x28,0x69,0x61,0xe9,0x05,0xd2,0xca,0xd2, +0x46,0xd2,0x26,0xd2,0x0c,0x69,0xa6,0xb4,0x9f,0xb4,0xab,0x74,0xa0,0x74,0x90,0x74, +0xa8,0x74,0x98,0x74,0xa4,0x74,0x94,0x74,0xac,0x74,0x9c,0x74,0x87,0xf4,0x63,0xe9, +0x0d,0xd2,0x89,0xd2,0xc9,0xd2,0x9b,0xa4,0x3b,0xa5,0xbb,0xa4,0x4f,0x4b,0x9f,0x91, +0x3e,0x2b,0x9d,0x2b,0xdd,0x27,0xdd,0x2f,0xfd,0x5c,0x7a,0x00,0x9d,0x1e,0xc7,0xf8, +0x8f,0x73,0xf5,0x22,0x69,0x2b,0x69,0x96,0xf4,0x62,0x69,0x3b,0x69,0x07,0xe9,0x25, +0xd2,0x4b,0xa5,0x97,0x49,0xaf,0x90,0x76,0x91,0x76,0x95,0x76,0x97,0xf6,0x94,0xf6, +0x96,0x0e,0x84,0xfb,0x60,0x90,0xdc,0x43,0xe4,0x1e,0x2a,0xf7,0x70,0xb9,0x47,0xc8, +0x3d,0x4a,0xee,0xd1,0x72,0x8f,0x91,0xfb,0x5a,0xb9,0x1f,0x92,0x7e,0x25,0x7d,0x5a, +0xfa,0xac,0x74,0x9e,0x74,0x81,0xf4,0x39,0xe9,0xf3,0xd2,0x17,0xa4,0x2f,0x4a,0x97, +0x4a,0x97,0x4b,0x57,0x4a,0x57,0x4b,0x5f,0x95,0xae,0x95,0xbe,0x26,0xdd,0xa4,0x7c, +0xbd,0x25,0xf7,0x16,0xb9,0xdf,0x96,0xfb,0x5d,0xb9,0xdf,0x93,0xfb,0x7d,0xb9,0x3f, +0x90,0x3b,0x57,0xee,0x0f,0xe5,0xfe,0xb7,0xf4,0x1b,0xe9,0x51,0xe9,0xb7,0xd2,0x1f, +0xe2,0xdc,0xe3,0xf0,0x6b,0x01,0x5f,0x9e,0xee,0x46,0x5f,0x2c,0xea,0x73,0xee,0x2b, +0xea,0xea,0x03,0xd2,0x39,0x50,0xa5,0x98,0xcf,0x89,0x2d,0xe6,0x6a,0x4d,0x68,0x50, +0xdc,0xe7,0xb4,0x80,0x8e,0x70,0x11,0xbc,0x06,0x13,0xe0,0x25,0x98,0x08,0xab,0xe1, +0x76,0xf9,0x4f,0x85,0x17,0x60,0xad,0xfc,0x5f,0x95,0xff,0x3a,0x98,0x57,0xc2,0xe7, +0x2c,0x85,0x17,0xe1,0x25,0x58,0x06,0xcb,0x61,0x6e,0x49,0xfc,0x4a,0xba,0xfa,0x12, +0xc4,0x95,0xf2,0x39,0xb5,0xa1,0x6c,0xb6,0xcf,0xa9,0x00,0xe5,0x20,0x1a,0xca,0x43, +0x25,0xb8,0x10,0x2a,0xca,0xbf,0xb2,0xfc,0xab,0xca,0x5d,0x45,0x7a,0x01,0xf4,0xec, +0xe7,0x73,0x7a,0xf7,0x73,0xb5,0x97,0xf4,0x6a,0xa0,0x2a,0x9c,0x54,0x68,0x04,0x97, +0xc2,0x95,0x22,0x1b,0x46,0xc3,0x53,0x62,0x91,0x58,0x2c,0x5e,0x14,0xe6,0x5e,0xb1, +0xb9,0x9f,0x65,0xfe,0x14,0x9a,0xb9,0x0e,0xfa,0x8d,0xf1,0xe7,0xbc,0xf8,0x25,0xb1, +0x14,0x56,0xc0,0x4a,0x78,0x19,0x5e,0x81,0x3b,0x39,0x7f,0xbe,0x0b,0xa6,0xc1,0xdd, +0x30,0x17,0xe6,0xc1,0x2a,0x58,0x03,0x6f,0xc1,0x0e,0xd8,0x0d,0x9f,0x8b,0x2f,0x84, +0x99,0xe7,0x06,0x98,0xb9,0xc4,0x5c,0xe7,0x33,0x73,0x88,0x18,0x6e,0xd6,0xc3,0xe6, +0x1c,0x4a,0x5c,0x63,0xae,0xf7,0x99,0x6b,0x7d,0xe2,0x46,0x31,0x49,0x4c,0xd6,0xf9, +0xf2,0xad,0xc2,0x9c,0xdb,0xce,0x34,0xc7,0x08,0xb3,0xfe,0x36,0x73,0xaa,0x99,0x77, +0x58,0x3f,0x4f,0x80,0x49,0x70,0x33,0xd4,0x0c,0xb0,0x06,0x86,0x0e,0x70,0x09,0x74, +0x82,0x2e,0x30,0x19,0x6e,0x81,0x5b,0x61,0x2a,0x2c,0x83,0x15,0x62,0x15,0xac,0x86, +0x57,0xe0,0x55,0x58,0x1b,0x30,0xfd,0x8e,0x3e,0x0f,0xfb,0xe0,0x20,0x7c,0x09,0x45, +0x59,0x6b,0x9f,0x07,0xe5,0xa1,0x21,0xa4,0x89,0x46,0xd0,0x1c,0x5a,0xc0,0x95,0xd0, +0x05,0x7a,0x43,0x7f,0x18,0x00,0x03,0xc5,0x20,0xad,0xdb,0xdf,0x11,0xef,0x42,0x2e, +0x6c,0x87,0xdd,0xf0,0x09,0xec,0x81,0x4f,0x61,0x2f,0xec,0x83,0x03,0xf0,0x05,0x1c, +0x84,0x43,0x70,0x14,0xbe,0x85,0x63,0xf0,0xa3,0x28,0x1a,0xe9,0x52,0x4c,0x9c,0x05, +0x35,0x21,0x0e,0x9a,0x43,0x4b,0x78,0x1c,0x9e,0x80,0x79,0x30,0x5f,0xac,0x84,0xd7, +0x60,0x3d,0xec,0x83,0xfd,0x70,0x04,0xbe,0x82,0xaf,0xe1,0x5b,0xf1,0xbd,0x70,0x0a, +0xb0,0xae,0x83,0xb3,0xa1,0x14,0x9c,0x27,0x4a,0x43,0x34,0x5c,0x20,0x2a,0x41,0x15, +0xa8,0x2a,0x2e,0x84,0x18,0x48,0x83,0x4b,0xa0,0x13,0x74,0x86,0x2e,0x70,0x35,0x0c, +0x84,0x49,0x70,0x13,0x4c,0x81,0x7b,0xe0,0x61,0x98,0x01,0xeb,0xe0,0x35,0xb1,0x1e, +0x3e,0x86,0x5d,0xe0,0xe7,0x7c,0x26,0x4c,0x84,0x43,0x2a,0xd4,0x11,0x75,0x45,0x3d, +0x51,0x5f,0x34,0x80,0x34,0x68,0x04,0xcd,0x20,0x13,0x2e,0x82,0x96,0xa2,0x15,0xb4, +0x86,0x2c,0xd1,0x06,0x3a,0xc2,0x25,0x90,0x0d,0x5d,0xa1,0x1b,0xf4,0x80,0x01,0x30, +0x48,0x0c,0x86,0xb1,0x30,0x4e,0x8c,0x87,0x09,0x30,0x11,0x6e,0x85,0x29,0x90,0x03, +0x77,0xc2,0x2c,0x78,0x0a,0xe6,0xc1,0x02,0xf1,0x3c,0x2c,0x81,0xa5,0x62,0x99,0x30, +0xe7,0x6f,0x2b,0x61,0x15,0xbc,0x02,0x6b,0x61,0x9d,0xce,0xe9,0xcc,0xf9,0xdc,0x46, +0xf1,0x86,0x78,0x4f,0xe4,0xc2,0x87,0xb0,0x1d,0x3e,0x86,0x9d,0xb0,0x0b,0xf6,0xc0, +0x41,0x38,0x04,0x87,0xe1,0x98,0xf8,0x41,0xf8,0x0a,0x52,0xaf,0x10,0x26,0x02,0x50, +0x10,0x8a,0x40,0x51,0x28,0x0e,0x55,0xa1,0x1a,0xc4,0x41,0x02,0x24,0x42,0x32,0xa4, +0x40,0x6d,0x48,0x85,0x7a,0xa2,0x01,0xa4,0x41,0x23,0x48,0x87,0x0c,0x68,0x06,0x2d, +0xa0,0x25,0xb4,0x11,0x9d,0xe0,0x32,0xb8,0x42,0xf4,0x80,0x01,0x30,0x10,0x06,0xc1, +0x60,0x18,0x0a,0xc3,0xc4,0x38,0x18,0x0f,0x13,0xc4,0x44,0xb8,0x0d,0xa6,0xc0,0x54, +0xb8,0x13,0x66,0xc1,0x53,0x30,0x0f,0x16,0xc0,0x42,0x58,0x04,0x4b,0x60,0xa9,0x58, +0x26,0x96,0xc3,0x4a,0x58,0x05,0xaf,0xc2,0x5a,0x58,0x07,0xaf,0x89,0x0d,0xf0,0x3a, +0x6c,0x14,0x9b,0xc4,0x0e,0xf8,0x18,0x76,0xc2,0x2e,0xd8,0x03,0x07,0xe1,0xa8,0xf8, +0x16,0x7e,0x04,0x5f,0x21,0x17,0x3f,0x84,0x41,0x00,0x0a,0x43,0x11,0x28,0x0a,0xc5, +0xa1,0x2a,0x54,0x83,0x38,0x48,0x80,0x44,0x48,0x86,0x54,0xa8,0x27,0xea,0x8b,0x06, +0xa2,0xa1,0x48,0x13,0x8d,0xa0,0x09,0x64,0xe8,0xfc,0xbe,0x85,0xce,0xef,0x5b,0x8a, +0xb6,0x3a,0xf7,0xef,0x28,0x2e,0x83,0xcb,0xe1,0x4a,0xc8,0x86,0xae,0xd0,0x0d,0x7a, +0xc0,0x00,0x18,0x24,0xc6,0x8b,0x09,0x62,0x22,0xdc,0x0c,0xb7,0x43,0x0e,0xdc,0x01, +0xd3,0x60,0x3a,0xdc,0x07,0x0f,0x88,0x87,0xe0,0x61,0x78,0x14,0x1e,0x83,0x59,0xf0, +0x14,0x3c,0x0b,0x4b,0x74,0x7d,0x61,0x05,0xac,0x14,0xab,0x60,0x35,0xac,0x81,0x75, +0xba,0x16,0x61,0xae,0x43,0x6c,0x14,0x9b,0xc4,0x7b,0x62,0x0f,0x1c,0x2c,0x64,0x6e, +0x7c,0xbb,0xf8,0x20,0x0c,0xc2,0x45,0x00,0x0a,0xc3,0x99,0x50,0x14,0xce,0x82,0xaa, +0x50,0x0d,0x52,0xa1,0x9e,0xa8,0x2f,0x1a,0x40,0x1a,0x34,0x82,0x26,0xd0,0x54,0xd7, +0x3d,0x9a,0x43,0x4b,0x68,0x5f,0xd8,0xbd,0x16,0x72,0x09,0x5c,0x0a,0x97,0xc1,0xe5, +0xd0,0x05,0xb2,0xa1,0x2b,0x74,0x83,0x1e,0x30,0x00,0xc6,0x8a,0x71,0x62,0x3c,0x4c, +0x80,0x89,0x70,0x2b,0xdc,0x0e,0x39,0x70,0x07,0xcc,0x82,0xa7,0x60,0x21,0x2c,0x82, +0x25,0xb0,0x54,0x2c,0x13,0xcb,0xc5,0x0a,0x61,0xae,0xc5,0xbc,0x02,0x6b,0xc4,0x5a, +0x5d,0x87,0x59,0xaf,0xeb,0x30,0xaf,0xc3,0x46,0x5d,0x97,0x31,0xd7,0x68,0x72,0xe1, +0x23,0xd8,0x01,0x1f,0xc3,0x4e,0xd8,0x05,0x7b,0xe0,0x20,0x1c,0x86,0x2f,0xe1,0x88, +0x70,0xce,0xa0,0x4e,0xc1,0x0f,0x61,0x10,0x0e,0x85,0xe1,0x4c,0x28,0x0a,0x67,0x41, +0x1d,0xa8,0x0b,0xf5,0xa0,0xbe,0x30,0xd7,0x7b,0xd2,0xa0,0x11,0x34,0x81,0xa6,0xd0, +0x4c,0xd7,0x84,0xcc,0xf5,0xa0,0x96,0xa2,0x95,0x68,0x07,0x1d,0x74,0xbd,0xc8,0x70, +0x25,0x64,0x43,0x57,0xe8,0x06,0x3d,0x60,0x00,0x8c,0x86,0xeb,0x61,0x9c,0x18,0x0f, +0x13,0x60,0x22,0xdc,0x0d,0xf7,0xc1,0x7c,0x58,0x08,0x2f,0xc1,0x32,0xb1,0x12,0xd6, +0xe8,0x3a,0xd3,0x7a,0x5d,0x7f,0x7a,0x0b,0x36,0xc3,0xdb,0xf0,0xae,0xd8,0xaa,0x6b, +0x52,0x7b,0xe0,0x20,0x7c,0x09,0x47,0x4c,0x1d,0x9c,0xc9,0xb8,0x84,0x78,0x91,0x00, +0x89,0x90,0x04,0x75,0x20,0x0d,0x82,0xd0,0x54,0x64,0x40,0x2b,0xc8,0x82,0x4e,0x30, +0x0e,0xc6,0xc3,0x0d,0xe2,0x46,0xb8,0x19,0x6e,0x85,0x47,0xe1,0x71,0xf1,0x24,0xcc, +0x83,0xf9,0x62,0x01,0x2c,0x84,0xe7,0x60,0x29,0x2c,0x13,0x2b,0xe1,0x15,0x58,0x23, +0xd6,0xc1,0x1b,0xb0,0x09,0xde,0x87,0x5c,0xd8,0x0e,0x4e,0x11,0x97,0x73,0xa1,0x14, +0x94,0x87,0x0b,0x21,0x59,0xd4,0x12,0xa9,0xa2,0x01,0x34,0x84,0x34,0xc8,0x80,0x4c, +0xe8,0x0b,0x83,0xe0,0x3a,0xb8,0x5e,0x8c,0x85,0x1b,0xe0,0x46,0x98,0x04,0x93,0xe1, +0x56,0xb8,0x0d,0xee,0x81,0xe9,0xb0,0x14,0xd6,0x08,0xa7,0x28,0x63,0x0e,0xaa,0x43, +0x0d,0x88,0x81,0x38,0x88,0x17,0x09,0x50,0x0b,0x6a,0x8b,0x54,0xa8,0x03,0x75,0xa1, +0x1e,0xd4,0x87,0x06,0xd0,0x50,0xa4,0x41,0x26,0x64,0x41,0x7b,0xe8,0x00,0x1d,0xe1, +0x12,0xe8,0x04,0x97,0xc2,0xe5,0x70,0x05,0x74,0x81,0x6c,0xd1,0x15,0xae,0x82,0xee, +0xd0,0x03,0x7a,0x42,0x3f,0xe8,0x0f,0x03,0x61,0x10,0x0c,0x85,0x61,0x30,0x0e,0xc6, +0x8b,0x09,0x70,0x03,0x4c,0x84,0x1b,0x61,0x12,0xdc,0x0a,0xb7,0x89,0xdb,0xc5,0x14, +0x91,0x03,0xd3,0xe1,0x3e,0x78,0x00,0x1e,0x14,0x33,0xe0,0x55,0x58,0x2b,0x36,0x8a, +0x4d,0xf0,0x2d,0x1c,0x13,0xdf,0xc3,0x8f,0xe0,0x14,0x63,0xdc,0x9c,0xc5,0xb8,0x81, +0x96,0x90,0x05,0x1d,0xe0,0x12,0x71,0x29,0x5c,0x0e,0x5d,0x60,0x32,0xdc,0x0c,0xb7, +0x41,0x0e,0xcc,0x83,0x05,0xb0,0x08,0x5e,0x80,0xe5,0xb0,0x52,0xac,0x86,0x57,0x61, +0x1d,0xbc,0x0b,0x5b,0xa1,0x68,0x71,0xc6,0x33,0x94,0x84,0x73,0xe1,0x52,0xb8,0x1c, +0xae,0x84,0xde,0x30,0x08,0xc6,0xc2,0x14,0x98,0x01,0x5f,0xc3,0x37,0xf0,0x3d,0xf8, +0x4a,0xd0,0x4f,0xce,0x66,0x8c,0xc2,0xf5,0x30,0x0e,0xee,0x83,0x19,0xb0,0x0f,0xbe, +0x80,0x43,0x70,0x18,0xbe,0x01,0xe7,0x1c,0x8a,0x06,0x67,0x41,0x09,0x28,0x29,0xca, +0x41,0x3c,0x24,0x40,0x22,0x24,0x89,0x34,0x68,0x03,0x17,0x43,0x5b,0xe8,0x02,0x7d, +0xa1,0x3f,0x0c,0x84,0xc1,0x30,0x04,0xc6,0xc2,0x42,0x78,0x0e,0x16,0xc1,0xf3,0x62, +0x31,0x2c,0x83,0xe5,0xf0,0x2a,0xac,0x11,0x6b,0x61,0x1d,0xbc,0x06,0x5b,0xe0,0x3d, +0x91,0x2b,0x3e,0x14,0x3b,0xe0,0x33,0x28,0x74,0x2e,0x53,0x22,0x14,0x11,0x45,0xa1, +0x14,0x94,0x87,0x74,0x68,0x2c,0x9a,0xc0,0x48,0x18,0x0b,0x37,0xc0,0x44,0xb8,0x11, +0x26,0xc1,0x2c,0x98,0x2d,0x9e,0x12,0xf3,0xe0,0x6b,0x70,0x4a,0x39,0x4e,0x59,0x28, +0x0f,0x15,0x21,0x1a,0x2a,0x43,0x15,0xa8,0x0a,0x17,0x42,0x75,0x88,0x83,0x78,0x48, +0x10,0x89,0x50,0x1b,0x52,0xa1,0x2e,0x34,0x85,0xd6,0x90,0x05,0xfd,0x60,0x20,0x0c, +0x85,0xb1,0x30,0x07,0xe6,0xc1,0x6b,0xb0,0x09,0xde,0x87,0x0f,0x84,0x73,0x1e,0x6b, +0x7b,0x38,0x07,0xce,0x85,0x52,0x70,0x1e,0x94,0x16,0xe5,0xa1,0x1d,0xb4,0x17,0x1d, +0x44,0x47,0x71,0x09,0x5c,0x01,0x5d,0x44,0xb6,0xe8,0x2a,0xba,0xc1,0x55,0xd0,0x1d, +0xfa,0x42,0x3f,0x18,0x0c,0x43,0x60,0x0c,0x5c,0x2f,0xc6,0xc2,0x4d,0x90,0x03,0xd3, +0xe1,0x49,0x31,0x0f,0x96,0xc1,0x0a,0x38,0x04,0x4e,0x69,0x8e,0x4b,0xe6,0xba,0xbe, +0x08,0x40,0x22,0x24,0x89,0x64,0x91,0x02,0x75,0x74,0x8f,0xc0,0x50,0x4f,0xd4,0xd7, +0xfd,0x81,0x74,0x61,0xee,0x11,0x34,0x81,0x20,0x5c,0x04,0x59,0xd0,0x09,0xfa,0xc0, +0x10,0x18,0x0b,0xe3,0x60,0xbc,0x98,0x00,0x33,0x60,0xa6,0x78,0x04,0x1e,0x87,0x27, +0xe0,0x49,0x98,0x05,0xb3,0xe1,0x29,0x31,0x07,0x9e,0x81,0x67,0x61,0x2e,0xcc,0x83, +0x25,0xf0,0x22,0x7c,0x02,0x7b,0xc4,0xa7,0x62,0x2f,0x7c,0x06,0xfb,0xe0,0x73,0x38, +0x20,0xbe,0x10,0x07,0xe1,0x30,0x7c,0x09,0x47,0xc0,0x39,0x9f,0x3e,0x03,0x17,0x40, +0x75,0xa8,0x01,0x89,0x90,0x04,0xc9,0x90,0x02,0xb5,0x20,0x0d,0x32,0xa1,0x25,0xb4, +0x86,0x2c,0xe8,0x04,0x97,0xc2,0x08,0x18,0x09,0xd7,0xc2,0x58,0xb8,0x19,0x72,0xe0, +0x45,0x58,0x06,0x2b,0x60,0x13,0x6c,0x86,0xb7,0x61,0x07,0x7c,0x2c,0x76,0xc2,0x5e, +0xf8,0x0c,0x3e,0x87,0x03,0xe2,0x0b,0x38,0x02,0x5f,0x89,0xaf,0xe1,0x5f,0xf0,0x6f, +0xf1,0x0d,0x1c,0x85,0x6f,0x85,0x53,0x86,0xfc,0x43,0x0d,0xb8,0x1a,0xfa,0xc0,0x08, +0x18,0x29,0x46,0xc1,0x7d,0x70,0x3f,0xac,0x80,0x95,0xf0,0x63,0x19,0xf7,0x19,0x75, +0x73,0xdf,0xc1,0xdc,0xa3,0x37,0xf7,0x17,0xcc,0xbd,0x63,0x73,0x1d,0xdc,0xdc,0x33, +0x37,0xd7,0xbb,0xcd,0x3d,0x59,0x73,0x1d,0xbb,0x93,0xe8,0x2c,0x2e,0x17,0xe6,0x5a, +0xf6,0xb5,0xe5,0xdc,0x7b,0x33,0xe6,0xbe,0xb7,0xb9,0x77,0x6d,0x9e,0x03,0x58,0x2e, +0xcc,0xb5,0x5f,0x73,0x1f,0xdc,0xdc,0x83,0x36,0xf7,0xf5,0xcd,0x3d,0xe6,0x2d,0xe5, +0xdc,0x7b,0xc9,0xdb,0xca,0xb9,0xf7,0x80,0xcd,0xfd,0x78,0x73,0x6d,0xd8,0xdc,0x87, +0x35,0xf7,0x72,0xcd,0x7d,0xf4,0xc2,0xe5,0x99,0x37,0xa0,0x21,0xa4,0x41,0x3b,0x31, +0x48,0x5c,0x2f,0xa6,0xc0,0xc3,0xb0,0x09,0x72,0xe1,0x63,0xf1,0x09,0x1c,0x02,0x7f, +0x05,0x97,0x48,0x51,0x10,0x8a,0x43,0x49,0x71,0xae,0x28,0x05,0x65,0xe0,0x02,0x51, +0x59,0x54,0x15,0xd5,0x20,0x06,0x62,0x45,0x4d,0x48,0x82,0x64,0x73,0x6d,0x19,0x52, +0x45,0x3d,0x68,0x08,0x41,0xc8,0x84,0x56,0xa2,0x0b,0x8c,0x87,0x09,0x70,0x03,0x4c, +0x84,0xc9,0xe0,0xd4,0x70,0x9c,0x6b,0x60,0x0c,0x5c,0x0b,0xd7,0xc1,0x6e,0xd8,0x0f, +0x5f,0xc0,0x41,0x38,0x0c,0x5f,0xc2,0x11,0x70,0x62,0x1c,0xa7,0x12,0x54,0x11,0x31, +0x22,0x0e,0x7a,0xc2,0x00,0x71,0xbd,0x18,0x0b,0x77,0xc3,0x0c,0x78,0x02,0x66,0xc1, +0xb3,0x30,0x0f,0x9e,0x87,0x17,0x60,0x39,0xac,0x84,0x35,0xb0,0x0e,0xde,0x80,0x4d, +0xf0,0x2e,0x6c,0x85,0x8f,0x60,0x07,0xfc,0x08,0x81,0x38,0x97,0x08,0x11,0x29,0x2a, +0xc0,0x85,0x50,0x0d,0x62,0x20,0x16,0x6a,0x42,0x3c,0x24,0x43,0x6d,0xa8,0x03,0x75, +0x45,0x3d,0xd1,0x08,0xee,0xd6,0xf5,0x4b,0x73,0xad,0xf3,0x7e,0x78,0x00,0x1e,0xd4, +0x75,0xdc,0x87,0xc5,0x4c,0x5d,0xe7,0xfc,0x4e,0x1c,0xd3,0xf5,0xce,0x1f,0x45,0x20, +0x9e,0xf4,0x20,0x1e,0x6e,0x87,0x19,0xb0,0x02,0x0e,0xc1,0x8f,0xe0,0x24,0xe1,0x6e, +0x89,0xb6,0xe2,0xf8,0x39,0x83,0xb6,0x17,0x67,0xc3,0xad,0x8f,0x51,0x5e,0xf8,0x37, +0x7c,0x03,0xdf,0x83,0xf3,0x38,0xc7,0xae,0x27,0xe8,0x87,0xa2,0x28,0x94,0x83,0xf2, +0x70,0x21,0x54,0x83,0xea,0x90,0x06,0xfd,0xa0,0xbf,0x18,0x20,0x86,0xc2,0xb5,0x70, +0xbd,0x18,0x0b,0xf7,0xc3,0x03,0xf0,0x20,0x3c,0x04,0x0f,0xc3,0x0c,0xf8,0x04,0xf6, +0xc0,0x41,0x38,0x04,0x87,0xe1,0x9c,0x27,0x49,0x0f,0x2a,0xc2,0x00,0x18,0x28,0x06, +0xc1,0x24,0x98,0x2c,0x6e,0x81,0xdb,0x61,0x8a,0xc8,0x81,0x0f,0x61,0xa7,0x38,0x0c, +0x5f,0xc1,0xd7,0xf0,0x2f,0xf8,0xb7,0xf8,0x06,0x8e,0xc2,0xb7,0xe2,0x3b,0xf0,0xcd, +0x62,0xac,0x88,0x30,0x08,0x40,0x84,0x88,0x84,0x82,0x50,0x48,0x14,0x86,0x8a,0x10, +0x0d,0x17,0x40,0x25,0xa8,0x0c,0x55,0x44,0x0d,0x91,0x06,0x43,0x60,0x2c,0x8c,0x83, +0xf1,0xb0,0x10,0x9e,0x83,0x97,0xe1,0x15,0x78,0x15,0x36,0xc1,0xfb,0xb0,0x03,0x0e, +0xc3,0x97,0xf0,0x6f,0xf8,0x4e,0x7c,0x0f,0x3f,0xc0,0x8f,0xc2,0x99,0xed,0x38,0x51, +0x50,0x10,0x2a,0x41,0x65,0x88,0x81,0x38,0x68,0x0a,0x19,0xd0,0x06,0x2e,0x86,0xb6, +0xd0,0x05,0xc6,0xc0,0x58,0x18,0x0f,0x13,0xc4,0x0d,0xb0,0x00,0x16,0x8a,0xe7,0x60, +0x11,0x3c,0x0f,0x4b,0xe0,0x45,0x78,0x09,0x96,0xc2,0x32,0x58,0x0e,0x2b,0xe1,0x4d, +0xb1,0x09,0xde,0x87,0x1d,0xb0,0x1b,0x3e,0x11,0x7b,0xc4,0xa7,0x70,0x10,0x0e,0xc1, +0x51,0xf8,0x16,0x7e,0x98,0xed,0x5e,0x7c,0xae,0x0a,0x17,0x42,0x2c,0xd4,0x84,0x38, +0x88,0x87,0x04,0x48,0x84,0x24,0x48,0x86,0x14,0x48,0x83,0x74,0x68,0x2c,0x9a,0x40, +0x0b,0xb8,0x48,0xb4,0x14,0x59,0xd0,0x09,0xba,0xc0,0x00,0x18,0x28,0x06,0xc1,0x70, +0x18,0x2d,0xae,0x11,0x63,0xc4,0xb5,0xe2,0x3a,0x98,0x0b,0xf3,0xc4,0x7c,0xb1,0x00, +0x9e,0x83,0x45,0xf0,0x3c,0x2c,0x86,0x17,0x60,0x09,0x2c,0x83,0xe5,0xb0,0x02,0x56, +0x8a,0x55,0x62,0xb5,0xd8,0x06,0xb9,0xf0,0xa1,0xd8,0x01,0xfb,0x60,0xbf,0xf8,0x1c, +0x0e,0xc0,0x17,0x70,0x10,0xbe,0x14,0x47,0xe0,0x2b,0xf8,0x5a,0xfc,0x4b,0xf8,0xe6, +0xd0,0x2f,0x21,0x0a,0xce,0x84,0x62,0x70,0x36,0x94,0x87,0xca,0x50,0x15,0x62,0x21, +0x0e,0x2e,0x85,0xcb,0xe0,0x4a,0xe8,0x02,0xbd,0xa0,0xb7,0xe8,0x0b,0xfd,0x60,0x20, +0xac,0x80,0x95,0xb0,0x13,0x76,0xc1,0x6e,0xf8,0x44,0xec,0x81,0x4f,0x61,0xaf,0xf8, +0x0c,0xf6,0xc1,0xe7,0xe2,0x80,0x38,0x04,0x47,0xc1,0x79,0x9a,0xf3,0xd4,0xf7,0xa8, +0x43,0x58,0x03,0x1b,0xe0,0x3b,0x30,0x0f,0x11,0xf7,0xfb,0x96,0xf4,0xe0,0x7d,0xf3, +0x20,0xf1,0x77,0x94,0x03,0x8a,0xc3,0x39,0x50,0x46,0x94,0x15,0xe5,0xa0,0x2a,0x54, +0x83,0x14,0xa8,0x0d,0xf5,0xa0,0x81,0x48,0x83,0x46,0xd0,0x18,0x9a,0x40,0x53,0x98, +0x0f,0x5b,0xa0,0xfe,0xf7,0xf4,0x07,0x98,0x02,0x77,0xc0,0x5a,0x38,0x04,0xdf,0x99, +0x07,0x7a,0x7f,0x60,0x3d,0x0e,0xe5,0xa1,0x26,0x24,0x42,0x12,0xb4,0x84,0xd6,0x30, +0x10,0x86,0xc2,0x70,0x38,0x06,0x45,0x7f,0xe4,0x18,0x09,0x15,0xa0,0x0e,0x34,0x14, +0x8d,0xe0,0x52,0xe8,0x2e,0x7a,0xc0,0x00,0x18,0x28,0x06,0xc1,0x83,0xf0,0x10,0x3c, +0x0c,0x33,0x60,0x39,0xac,0x86,0xb5,0xb0,0x1e,0xde,0x84,0xcd,0xf0,0x1e,0x7c,0x00, +0xb9,0xe6,0x41,0x62,0xc7,0xe7,0x14,0x82,0x33,0xa0,0x32,0x54,0x85,0x3a,0x50,0x0f, +0xea,0x43,0x43,0x68,0x09,0x59,0x70,0x39,0x8c,0x85,0x6f,0x21,0xcd,0xe7,0x73,0x86, +0xc2,0xf7,0x62,0xac,0xdf,0xe7,0x3c,0x00,0x33,0x60,0x13,0xec,0x10,0xe6,0xe5,0x90, +0x72,0x10,0x03,0x69,0xd0,0x48,0xa4,0x43,0x26,0x34,0x17,0x59,0x30,0x0c,0x86,0xc3, +0x68,0x18,0x0b,0x0f,0xc2,0x0c,0x78,0x19,0xd6,0xc1,0x9b,0xf0,0x16,0xbc,0x63,0x5e, +0x38,0x09,0xf7,0x39,0xad,0x21,0x0b,0x1e,0x84,0x19,0x30,0x1b,0xe6,0xc1,0x16,0xd8, +0x0a,0xdf,0x99,0x17,0x02,0x03,0x3e,0xa7,0x0a,0xc4,0x41,0x37,0x18,0x08,0xa3,0x61, +0x0c,0xdc,0x0c,0xb7,0xc2,0x1d,0x70,0x17,0x4c,0x83,0x7b,0x60,0x26,0x3c,0x0a,0xf3, +0x61,0x21,0x2c,0x81,0x97,0x60,0x29,0xac,0x84,0x23,0xe6,0x05,0x95,0x08,0x9f,0x93, +0x12,0x49,0x99,0xa0,0x3d,0x74,0x81,0x9e,0x30,0x16,0x26,0xc2,0x24,0x98,0x07,0x0b, +0x60,0x85,0x79,0x61,0xa5,0x80,0xcf,0x09,0x40,0x01,0x51,0x10,0x92,0xa1,0x16,0xd4, +0x86,0x7a,0xa2,0x21,0xb4,0x87,0x2e,0x30,0x1c,0xc6,0xc2,0x43,0xb0,0x03,0xbe,0x84, +0xaf,0xe0,0x6b,0xf3,0x02,0x63,0x94,0xcf,0x29,0x09,0xe5,0x21,0x15,0xd2,0xa0,0x13, +0x8c,0x85,0xc5,0xb0,0x1c,0x56,0x98,0x17,0x64,0x0a,0xba,0xf8,0x20,0x0c,0x02,0x10, +0x01,0x85,0xa1,0x08,0x14,0x85,0xe2,0x50,0x12,0xce,0x81,0x52,0x90,0x0c,0xb5,0xa1, +0x0e,0x34,0x14,0x5d,0x60,0x0c,0x8c,0x85,0x07,0x60,0x25,0xac,0x85,0xd7,0x60,0x37, +0x7c,0x02,0x7b,0x4c,0x5a,0x85,0xd8,0x1f,0xd2,0xa0,0x3d,0x74,0x81,0xc1,0x30,0x16, +0xa6,0xe6,0xbd,0xa8,0xe3,0x73,0x9a,0xc1,0x58,0x58,0x00,0x2b,0xe1,0x4b,0xf3,0x02, +0xe6,0x19,0x3e,0x27,0x1a,0x2e,0x80,0x2a,0x10,0x07,0xa9,0x90,0x06,0x99,0xd0,0x1c, +0x5a,0x42,0x2b,0xd1,0x5a,0x64,0x41,0x77,0xe8,0x0d,0xfd,0x60,0x80,0x18,0x08,0x13, +0x61,0xec,0x99,0xf4,0x0b,0x98,0x03,0x4f,0xc3,0x3c,0x98,0x0f,0xab,0xe1,0x15,0x78, +0x55,0xac,0x81,0xb5,0xb0,0x01,0xde,0x84,0xf7,0xe1,0x0b,0x38,0x04,0x3f,0x9a,0x17, +0x41,0x8b,0xf8,0x9c,0xf3,0xa1,0x8a,0x88,0x83,0x20,0x34,0x85,0x2c,0x18,0x08,0xe3, +0x60,0x3c,0x4c,0x84,0x79,0xf0,0x0a,0xec,0x80,0x7f,0x99,0x17,0x90,0x8a,0xba,0xf8, +0x84,0x5f,0x84,0x41,0x2d,0xa8,0x0d,0x4d,0xa1,0x07,0x0c,0x80,0x81,0x62,0x10,0x0c, +0x86,0x21,0x30,0x14,0x86,0x89,0xeb,0x61,0x1c,0x8c,0x17,0x13,0x60,0x2e,0xcc,0x83, +0x05,0xb0,0x10,0x9e,0x87,0xc5,0xf0,0x02,0x2c,0xd1,0x3d,0xe9,0xd5,0x62,0x13,0xec, +0x85,0x43,0x70,0xd4,0xe4,0xad,0x18,0xf9,0x81,0x30,0xa8,0xac,0xfb,0xd5,0xd5,0xa1, +0x86,0x88,0x81,0x24,0x48,0x81,0x86,0xd0,0x44,0x04,0xa1,0x29,0x64,0x88,0x2c,0x18, +0x0c,0x43,0xc4,0x70,0x31,0x16,0xc6,0xc1,0x78,0x31,0x01,0x16,0xc0,0x42,0x58,0x04, +0xcf,0xc3,0x72,0x58,0x01,0x2b,0x61,0x15,0xbc,0x02,0xaf,0xc1,0xeb,0xf0,0x86,0x78, +0x53,0x6c,0x82,0xf7,0xe1,0x03,0x91,0x2b,0xcc,0xcb,0xb6,0xc5,0xa0,0x38,0x54,0x87, +0x1a,0x10,0x0b,0x35,0x21,0x1e,0x12,0x20,0x11,0x92,0x44,0xb2,0x48,0x81,0x5a,0xd0, +0x40,0x34,0x84,0x34,0x68,0x24,0xc6,0xc2,0x8d,0x30,0x59,0xdc,0x0c,0xb7,0xc1,0x14, +0x78,0x10,0x1e,0x86,0x59,0x30,0x0f,0x3e,0x82,0xed,0x62,0x07,0xec,0x84,0x5d,0xb0, +0x0f,0x0e,0xc1,0x51,0xf3,0x42,0x70,0x71,0xfa,0x01,0xf8,0x21,0x0c,0x02,0x50,0x18, +0x8a,0x40,0x51,0x28,0x0e,0x55,0xa1,0x1a,0xc4,0x41,0x02,0x24,0x42,0x32,0xa4,0x42, +0x5d,0xa8,0x07,0xf5,0x85,0x79,0xae,0xa0,0x21,0xa4,0x89,0x46,0xd0,0x04,0x32,0xa0, +0x99,0x9e,0x39,0x68,0x09,0x59,0xa2,0xa3,0xb8,0x1c,0xb2,0xa1,0x2b,0x74,0x83,0x1e, +0xd0,0x17,0x06,0xc2,0x50,0x18,0x0b,0x37,0xc1,0x2d,0xe2,0x76,0x91,0x03,0x8b,0x60, +0xb1,0x30,0xcf,0x29,0xbc,0xa8,0xe7,0x18,0x56,0xea,0x79,0x05,0xef,0x99,0x85,0x57, +0xf5,0x0c,0xc3,0x7a,0x78,0x1d,0x36,0xc2,0x1b,0xe2,0x4d,0xb1,0x49,0xbc,0x25,0x36, +0x8b,0x2d,0xe2,0x63,0xd8,0x69,0x5e,0xc0,0x2b,0x41,0xbb,0x41,0x32,0xd4,0x82,0xda, +0xd0,0x10,0xd2,0xa0,0x11,0xa4,0x43,0x13,0x08,0x8a,0xa6,0x22,0x03,0x9a,0x43,0x16, +0x74,0x82,0x2b,0xc4,0x95,0x90,0x0d,0x63,0xcd,0xb3,0x13,0x25,0xdc,0xe7,0x2a,0x16, +0xc0,0x42,0x78,0x01,0x96,0x88,0x17,0xad,0x67,0x2d,0xcc,0x73,0x16,0x2b,0x60,0x25, +0xac,0x12,0xab,0xe1,0x65,0x78,0x05,0x5e,0x85,0xb5,0x62,0x13,0xbc,0x6f,0xe2,0x2f, +0xe9,0x73,0x9e,0xd5,0x73,0x19,0xf3,0x61,0x01,0x2c,0x82,0x17,0xf4,0x9c,0xc6,0x52, +0x58,0x06,0xcb,0xc5,0x0a,0x58,0x09,0x5b,0x61,0x1b,0xe4,0xc2,0x87,0xe6,0xc5,0xc3, +0xb3,0xe9,0xcb,0x10,0x07,0x09,0x90,0x08,0x75,0xa0,0x2e,0xd4,0x83,0xfa,0xa2,0x81, +0x68,0x08,0x69,0xd0,0x44,0x64,0x41,0x27,0x18,0x0b,0x4f,0xc1,0x1c,0xf1,0xb4,0x78, +0x46,0x3c,0x0b,0x73,0x61,0x1e,0x2c,0x82,0xe7,0xc5,0x62,0xf1,0x82,0x58,0x09,0xaf, +0xc1,0x26,0xd8,0x65,0x5e,0x6c,0x3f,0xc7,0xe7,0x9c,0x07,0x65,0x44,0x59,0x51,0x4e, +0x94,0x87,0x0a,0x50,0x11,0x2a,0x41,0x65,0x51,0x05,0xaa,0x43,0x1c,0xa4,0x42,0x1a, +0x34,0x35,0x2f,0x58,0x9e,0x8b,0x3f,0xd4,0x80,0x58,0xa8,0x09,0xb5,0xa0,0xb6,0x48, +0x85,0x3a,0x30,0x03,0xb6,0xc3,0x0e,0xf8,0x0c,0x7e,0x84,0x88,0x52,0x3e,0x27,0x4a, +0x14,0x86,0xe2,0x50,0x12,0xce,0x86,0x73,0xa1,0x66,0x29,0xf7,0xf9,0x98,0x64,0xa8, +0xa5,0xe7,0x64,0xea,0x42,0x3d,0xa8,0x2f,0x1a,0x88,0x86,0x22,0x4d,0x34,0x12,0xe9, +0xa2,0xb1,0xc8,0x82,0x4e,0x30,0x03,0x9e,0x84,0xa7,0x60,0x13,0xbc,0x05,0x5b,0xe0, +0x6d,0x78,0x0f,0x3e,0x80,0x6d,0x90,0x0b,0xdb,0x61,0x87,0xf8,0x58,0xec,0x12,0xbb, +0x45,0xde,0xc7,0x01,0xc0,0x07,0x05,0xa1,0x10,0x24,0x40,0x22,0xd4,0x86,0x54,0x51, +0x47,0xd4,0x85,0x06,0x90,0x21,0xb2,0x44,0x1b,0xe8,0x00,0x1d,0xe1,0x12,0xe8,0x04, +0x9d,0xe1,0x32,0xb8,0x09,0x6e,0x86,0xbb,0xe1,0x1e,0x71,0x2f,0x4c,0x87,0x07,0xc5, +0x3c,0xf8,0xc6,0xe4,0xa1,0xb4,0x4b,0x17,0x91,0x2d,0xba,0xc2,0x55,0xd0,0x5d,0xf4, +0x10,0x3d,0xc5,0x4a,0xd8,0x01,0x87,0xe0,0xa8,0x79,0x51,0xf6,0x7c,0xd6,0x43,0x50, +0x10,0x62,0xa1,0xa6,0x88,0x83,0x14,0xa8,0x0d,0xf5,0xa1,0x81,0x68,0x28,0xd2,0x44, +0x16,0x74,0x82,0xc1,0x30,0x05,0xee,0x80,0x27,0x61,0xb6,0x78,0x0a,0xe6,0xc1,0x7c, +0xb1,0x00,0x16,0xc2,0x73,0x62,0x11,0x3c,0x6f,0x3e,0x94,0x50,0x86,0xfe,0x02,0x05, +0x20,0x0a,0x0a,0x41,0x1c,0xc4,0x43,0x0a,0xd4,0x11,0xf5,0xa0,0x3e,0x34,0x84,0x20, +0x34,0x15,0x19,0x22,0x0b,0x3a,0x41,0x17,0xe8,0x0e,0x3d,0xa1,0x17,0x5c,0x0d,0x37, +0xc1,0xcd,0x70,0x3b,0xe4,0xc0,0x54,0xb8,0x13,0xee,0x82,0x69,0xe2,0x6e,0x71,0x8f, +0xb8,0x57,0xcc,0x80,0xd9,0x30,0x0f,0xb6,0xc2,0xfb,0xe2,0x03,0xd8,0x06,0x3b,0xe0, +0x33,0x38,0x24,0x0e,0x8b,0x1d,0x65,0x59,0x5f,0xc1,0x11,0xf8,0x0a,0xbe,0x86,0x7f, +0x99,0x0f,0x41,0x94,0xa3,0x2f,0x81,0x5f,0x84,0x89,0x70,0x28,0x0a,0x67,0x41,0x22, +0x24,0x41,0x32,0xa4,0x40,0x1d,0x68,0x00,0x0d,0x21,0x4d,0x34,0x12,0xe9,0x22,0x0b, +0x3a,0xc1,0xa5,0x62,0x9e,0x30,0x1f,0x9d,0x98,0x6e,0x5e,0x50,0xbe,0x80,0xf5,0x0d, +0x0c,0x83,0xeb,0x61,0x2c,0x34,0xae,0xc4,0x7e,0x70,0x63,0x65,0xea,0xa5,0x26,0xf9, +0xcf,0x7b,0x41,0x98,0x7e,0x90,0x44,0x1a,0xa2,0x11,0x34,0x85,0x0c,0x68,0x0f,0x5d, +0xe0,0x5b,0xf3,0x01,0x86,0x26,0xf8,0x9b,0x17,0x72,0xb3,0x99,0x6f,0xb2,0xdd,0xe7, +0xdc,0xcc,0x33,0x6d,0xd5,0xa0,0x06,0xc4,0x40,0x4d,0x88,0x83,0x54,0xf3,0xe2,0x6a, +0x2f,0xfa,0xd4,0xd5,0xc4,0x09,0x57,0x40,0x17,0xe8,0x0d,0x03,0x61,0x39,0xac,0x84, +0xd7,0x60,0x13,0x1c,0x80,0x43,0xf0,0x95,0xf9,0x90,0x40,0x1f,0xe2,0x81,0x38,0x48, +0x81,0x34,0x68,0x0c,0x59,0xd0,0x09,0xba,0xc1,0x08,0xb8,0x16,0xa6,0x98,0xed,0xfd, +0xa8,0x0f,0x68,0xac,0xe7,0xe4,0xfa,0x40,0x5f,0x18,0x08,0xa3,0x20,0xad,0x3f,0xe5, +0x87,0x19,0xf0,0x02,0xbc,0x04,0x5b,0xcc,0x07,0x09,0x06,0x70,0x9c,0x82,0xd6,0x22, +0x4b,0xb4,0x81,0x49,0x30,0x05,0xee,0x80,0x3b,0xe1,0x61,0xd8,0x01,0x1f,0xc3,0x2e, +0xb1,0x5b,0x1c,0x82,0xc3,0xf0,0x25,0x1c,0x81,0xaf,0xe0,0x5f,0xe6,0xc5,0xd8,0x81, +0xf4,0x99,0x5b,0x99,0x1f,0xa1,0xfc,0x6d,0xd4,0x3f,0x7c,0x09,0xce,0xed,0xf4,0xc7, +0xa9,0xe4,0x07,0x36,0xc3,0xa1,0xb9,0xec,0x07,0x5f,0xc3,0x77,0xf0,0x3d,0xfc,0x60, +0x3e,0x84,0x30,0x8f,0x75,0xc9,0x7c,0xe6,0x1e,0x91,0x05,0x17,0x43,0x7b,0x71,0x15, +0xf4,0x82,0x81,0xf0,0xdd,0x02,0xf7,0x01,0xbe,0xab,0x61,0x20,0x8c,0x81,0xb1,0x30, +0x19,0x72,0x60,0x3a,0x3c,0x08,0x0f,0xc1,0xa1,0xd7,0x99,0x0f,0xc0,0x7c,0x04,0x24, +0x06,0xe2,0xa0,0x29,0x54,0x79,0x8b,0xf4,0xa0,0x3b,0xf4,0x80,0x9e,0xd0,0x1b,0xfa, +0xc1,0x60,0xb8,0x06,0xc6,0xc3,0x44,0xb8,0x05,0x9e,0x82,0x67,0x20,0x7d,0x33,0xc7, +0x3b,0xc8,0x82,0x8b,0xa1,0x33,0x5c,0x06,0x57,0x8a,0xb1,0x30,0xce,0xbc,0x60,0xfd, +0xb6,0xcf,0x69,0x07,0x1d,0xe0,0x01,0x78,0x08,0x1e,0x86,0x47,0xc4,0xe3,0xf0,0x04, +0xcc,0x86,0xa7,0xe1,0x59,0x58,0x02,0x2f,0x89,0x65,0xf0,0x32,0xbc,0x0a,0x81,0x77, +0x7c,0x4e,0x24,0x14,0x84,0x33,0xa0,0x04,0x9c,0x0d,0xe7,0x43,0x59,0x48,0x85,0xba, +0xd0,0x00,0xd2,0xa0,0x09,0x34,0x15,0xcd,0x21,0x0b,0x2e,0x86,0x27,0xde,0x65,0x2d, +0x09,0x2b,0x61,0x35,0x7c,0x00,0xb9,0xf0,0x2d,0x1c,0x83,0x12,0xef,0x11,0x2f,0x24, +0x41,0x0a,0xb4,0x82,0x2c,0xe8,0x0f,0x03,0x61,0x32,0xdc,0x0c,0xb3,0xe0,0x29,0x58, +0x0d,0xaf,0xc0,0x06,0x78,0x03,0x7e,0x34,0x2f,0xc6,0x7e,0xc0,0xbe,0x50,0x17,0xfa, +0xc2,0x30,0x71,0x83,0xb8,0x1f,0x1e,0x86,0x99,0x30,0xd7,0xbc,0x60,0xba,0x9d,0x79, +0x11,0x0a,0x8a,0x42,0x70,0x3d,0x8c,0x85,0x71,0x90,0x03,0x77,0xc3,0x46,0xf8,0xd1, +0xbc,0x40,0xbb,0x83,0xf9,0x14,0x0a,0xc0,0xb9,0x50,0x1a,0x2a,0x40,0x34,0x5c,0x00, +0x95,0xa1,0x1a,0xc4,0x41,0x3f,0x98,0x22,0xcc,0xcb,0x93,0x35,0x20,0x0e,0x52,0xa0, +0x16,0xd4,0x87,0x34,0xc8,0x84,0x56,0x22,0x67,0x27,0xed,0x0c,0xcf,0x8a,0x95,0xb0, +0x1f,0x3e,0x87,0x83,0x70,0x08,0x8e,0xc2,0xa6,0xdd,0xac,0xbb,0x61,0xbf,0xf8,0x1c, +0x0e,0xc2,0x21,0x38,0x0a,0x9b,0x3e,0x61,0x9c,0xc3,0x17,0x70,0x10,0x0e,0x89,0xc3, +0xf0,0x2d,0xac,0xdc,0xc3,0x7a,0x1e,0x76,0xc0,0x4e,0xd8,0x25,0x76,0xc3,0x27,0xb0, +0x47,0x7c,0x0a,0x07,0xe0,0x0b,0x38,0x08,0x87,0xe0,0x2b,0xf8,0x5a,0xfc,0x20,0x7e, +0x14,0x3b,0x3e,0x65,0x3f,0xd8,0x0b,0xfb,0xe1,0x00,0x7c,0x01,0x87,0xe0,0x07,0xf3, +0x41,0x87,0xbd,0xb4,0x19,0x6c,0x82,0x77,0xcd,0x87,0x6d,0x3e,0x63,0x2e,0x81,0x26, +0xd0,0x1c,0x5a,0x88,0x2c,0xe8,0x64,0x3e,0x94,0xf0,0x05,0xf3,0xf7,0xff,0xb5,0x77, +0x1e,0xf0,0x55,0x97,0x67,0x1b,0x3e,0xe7,0xe4,0xe4,0x70,0x92,0x20,0xe0,0xc0,0x2d, +0x6e,0xd9,0x10,0x99,0x0a,0x08,0x41,0x51,0x1c,0x1f,0x05,0xdc,0x48,0x15,0xc4,0x8d, +0x03,0x04,0xdc,0x16,0x11,0x44,0xc5,0x89,0x6d,0xb5,0x9f,0xa3,0x8a,0xf5,0x73,0xa0, +0x82,0x51,0xd0,0x82,0x20,0x04,0x71,0xcb,0x12,0x5c,0x75,0x31,0xac,0x7e,0x28,0x22, +0xcb,0x09,0x6a,0xbe,0xfb,0x3d,0xff,0xeb,0x21,0x0f,0x7f,0x73,0x04,0xac,0xfd,0xd5, +0xfe,0xbe,0x26,0xbd,0x01,0x43,0x20,0x83,0x24,0x7d,0xf2,0x5e,0xcf,0x75,0xbf,0x4a, +0xa1,0xb2,0xab,0xb2,0xbb,0xb2,0x87,0xb2,0x17,0xa9,0x4f,0x1a,0x2a,0x2d,0x94,0x56, +0x4a,0x5b,0x65,0x7f,0xd2,0x9e,0x1c,0x48,0xba,0x92,0xc3,0xc8,0x11,0xa4,0x9b,0xd2, +0x5d,0xe9,0xa9,0x1c,0xa9,0x1c,0x4d,0x8e,0x23,0xbd,0x48,0x6f,0x72,0x22,0xe9,0x43, +0x4e,0x56,0xfa,0x29,0xa7,0x92,0x33,0x94,0xfe,0xca,0x39,0xca,0x20,0x65,0x88,0x72, +0x91,0x72,0x89,0x72,0xb9,0x32,0x94,0x0c,0x53,0x46,0x29,0xd7,0x2b,0x77,0x2a,0xf7, +0x2a,0xf7,0x29,0xf7,0x2b,0x63,0x95,0x47,0x94,0x29,0xca,0xca,0x75,0xfa,0x77,0x0d, +0xe2,0x76,0x22,0x95,0x58,0xf8,0x40,0x2a,0x91,0x78,0x30,0x95,0xa8,0x37,0x29,0x95, +0xd8,0x4d,0x19,0x37,0x27,0x95,0x28,0x57,0x16,0x2d,0x4b,0x25,0x56,0x2a,0x27,0x86, +0x85,0xe0,0x6f,0x52,0x89,0x5d,0xd6,0x46,0x8b,0xc1,0x87,0x6f,0x5d,0xa0,0xef,0x8d, +0x0a,0x12,0x97,0xb4,0x0a,0x32,0x62,0x41,0xa2,0xd3,0x77,0x05,0xb9,0x05,0x9b,0x15, +0x8a,0xed,0x37,0xe7,0xdb,0x6b,0xfe,0x57,0xed,0x33,0xff,0xdc,0x3d,0xe6,0x4d,0xdd, +0x5f,0xde,0xd4,0xbd,0xe5,0xf8,0x3e,0x72,0xbe,0x3d,0x64,0xdb,0x3b,0x8e,0xef,0x1b, +0xdb,0x7e,0xb1,0xed,0x13,0xe7,0xdb,0x23,0xb6,0xfd,0x61,0xdb,0x1b,0xb6,0x7d,0x61, +0xdb,0x13,0x8e,0xef,0x07,0xdb,0x5e,0xb0,0xed,0x03,0xdb,0x1e,0xb0,0xed,0xff,0xda, +0xde,0x6f,0xbe,0x7d,0xdf,0xf8,0x9e,0xaf,0xed,0xf3,0xda,0xde,0xae,0xed,0xe3,0xda, +0x1e,0x6e,0x7c,0xef,0x76,0x73,0xf7,0x6c,0x6d,0xbf,0xd6,0xf6,0x66,0xe3,0xfb,0xb2, +0xf1,0xfd,0xd8,0x9f,0xbb,0x07,0x1b,0xdf,0x6b,0xb5,0x3d,0xd6,0xcd,0xdd,0x57,0xb5, +0x3d,0xd5,0xf8,0xde,0xa9,0xed,0x99,0x6e,0xee,0x3e,0xa9,0xed,0x91,0xc6,0xf7,0x3f, +0x6d,0xdf,0xf3,0x97,0xde,0xf3,0xb4,0xbd,0xcd,0x8d,0xed,0x63,0xda,0x1e,0x66,0xbe, +0xfd,0x4a,0xdb,0xa7,0xdc,0xd4,0xfd,0x49,0xdb,0x9b,0x8c,0xef,0x3d,0xda,0x9e,0x63, +0xbe,0x7d,0x46,0xdb,0x63,0x8c,0xef,0x27,0xda,0x5e,0xa2,0xed,0x21,0x6e,0xea,0xde, +0xa1,0xed,0x0f,0xda,0xde,0x60,0x7c,0x5f,0x70,0x73,0xf7,0x03,0x6d,0x2f,0x30,0xdf, +0x3e,0x60,0x7c,0xff,0x2f,0xbe,0xcf,0x67,0xfb,0x7a,0xb6,0x97,0x67,0x7b,0x75,0xb6, +0x4f,0x67,0xfb,0x73,0xb6,0x37,0x67,0xfb,0x72,0xb6,0x27,0x67,0xfb,0x71,0xb6,0xf7, +0xf6,0xef,0xb6,0xd7,0xf6,0x4b,0xef,0xb1,0xd9,0xde,0x9a,0xed,0xa9,0xc5,0xf7,0xd3, +0x6c,0x2f,0x2d,0xbe,0x5f,0xb6,0xb9,0x7b,0x63,0xf9,0xf6,0xc5,0x36,0xb6,0xe7,0x65, +0x7b,0x5d,0xb6,0xbf,0x65,0xfb,0x54,0xb6,0x2f,0x65,0xfb,0x4e,0xb6,0xcf,0x64,0xfb, +0x49,0xb6,0x97,0x64,0x7b,0x45,0xb6,0x2f,0xb4,0xa9,0x7b,0x42,0xb6,0x07,0x64,0xfb, +0x3f,0xb6,0xf7,0xf3,0x73,0xf7,0x7c,0x7e,0xad,0xfb,0x3d,0xf9,0xf6,0x78,0xfe,0xdd, +0xf7,0x75,0x36,0x77,0x4f,0xe7,0x97,0xda,0xcf,0xd9,0xd8,0x5e,0xce,0xa6,0xee,0xe1, +0x6c,0x6c,0xff,0xe6,0x5f,0xb5,0x77,0x93,0x6f,0xdf,0x26,0xdf,0x7e,0x4d,0x7c,0xaf, +0xe6,0x5f,0xb5,0x4f,0x63,0x7b,0x34,0xb6,0x3f,0x63,0x7b,0x33,0xb6,0x17,0x63,0xfb, +0x30,0xf9,0xf6,0x5d,0x6c,0xbf,0xc5,0xf6,0x5a,0x6c,0x8f,0xc5,0xf6,0x56,0x6c,0x0f, +0xc5,0xf6,0x4f,0xe2,0x7b,0x27,0xf1,0x7d,0x13,0xdb,0x23,0xb1,0xfd,0x91,0x8d,0xed, +0x89,0xd8,0x3e,0x88,0xed,0x81,0xd8,0xfe,0x87,0xed,0x7d,0xd8,0xbe,0xc7,0xc6,0xf6, +0x3c,0xe2,0xfb,0x1c,0xff,0xec,0xfd,0x8d,0x7f,0x74,0xff,0xe2,0x9f,0xb5,0x77,0x11, +0xdf,0xab,0xb0,0x7d,0x0a,0xdb,0xa3,0xf8,0xb5,0xec,0x4f,0xc4,0xf7,0x26,0x36,0x77, +0x5f,0x62,0x73,0xf7,0x24,0xfe,0xb3,0x1f,0x51,0xfd,0x7e,0x44,0xbe,0x3d,0x88,0x8d, +0xed,0x3d,0xfc,0xa3,0xfb,0x0e,0x1b,0xdb,0x6b,0xc8,0xb7,0xcf,0xb0,0xb1,0x3d,0x06, +0xdb,0x5f,0xc8,0xb7,0xb7,0x60,0xfb,0x0a,0xf1,0x3d,0x05,0xdb,0x47,0xb0,0xbd,0x03, +0xdb,0x37,0xb0,0xfd,0x02,0xdb,0x1b,0xb0,0x3d,0x01,0xdb,0x03,0x88,0xf3,0x7f,0xe3, +0xfe,0xc6,0xf9,0x8d,0xe7,0x6f,0x8c,0xd7,0x1b,0x77,0xdf,0x5c,0xde,0xbe,0xb9,0xfc, +0xdc,0xb8,0xb9,0xf1,0x70,0xe3,0xe0,0x9b,0xca,0xbb,0x8d,0x53,0x1b,0x9f,0x36,0x2e, +0x6d,0x9c,0x39,0xce,0x95,0xe3,0x5c,0xd8,0x78,0xb0,0xf1,0x5d,0xe3,0xba,0xc6,0x69, +0x8d,0xcf,0x1a,0x67,0x35,0xae,0x1a,0xe7,0xa2,0xc6,0x3d,0x37,0x95,0x77,0x1a,0xc7, +0x34,0x7e,0x19,0xe7,0x94,0x71,0xfe,0x68,0xdc,0xd1,0x78,0xa3,0xf1,0x45,0xe3,0x89, +0xc6,0x0d,0xf3,0xf1,0x41,0xe3,0x7d,0x71,0xce,0x67,0xfc,0xce,0xb8,0x5d,0x3e,0xfe, +0x66,0x7c,0x2d,0x1f,0x4f,0x33,0x3e,0x96,0x8f,0x8b,0xc5,0x39,0x98,0xf1,0xae,0x38, +0xe7,0xfa,0x47,0x39,0x95,0xf1,0xa9,0x7c,0x5c,0x2a,0xce,0x9d,0x8c,0x37,0x19,0x67, +0x32,0xbe,0x64,0x5c,0x69,0x53,0x79,0xd2,0xc6,0x38,0x92,0xf1,0xa3,0x7c,0xbc,0xe8, +0xd7,0xce,0x87,0xfe,0xbf,0xf1,0x99,0xcd,0xe5,0x2c,0xc6,0x4f,0x8c,0x9b,0x18,0x2f, +0x89,0x73,0x12,0xe3,0x23,0x71,0x1e,0x62,0xfc,0xc3,0xb8,0x47,0x9c,0x77,0x18,0xe7, +0x30,0xbe,0x61,0x5c,0xe3,0xe7,0xf2,0x0c,0xe3,0x18,0xc6,0x2f,0xfe,0xc3,0x2d,0x22, +0x6e,0xf1,0x8b,0xf1,0x8a,0xd0,0x0d,0xac,0x14,0x2b,0xa6,0x9f,0x6f,0xa1,0xd4,0x8a, +0x8e,0x4a,0x42,0x05,0x66,0x42,0xdf,0xfe,0x27,0xc2,0xb7,0xd8,0x7b,0x2a,0xfb,0x28, +0x8d,0xa3,0x6f,0xb7,0xc3,0xb7,0xd2,0x89,0x66,0x4a,0xe8,0x74,0x69,0xa7,0xb4,0xa7, +0xd7,0xa5,0x37,0xdc,0xe3,0x32,0xe5,0x0a,0x65,0xa4,0x72,0xb5,0xa2,0x6f,0x2d,0x13, +0xf7,0x2a,0x7f,0x51,0x1e,0x80,0x87,0x84,0x6f,0x09,0xc6,0x29,0xe3,0x95,0x72,0xe5, +0x09,0x65,0x22,0x8c,0xe4,0x29,0x65,0x32,0x9c,0x64,0x0a,0xac,0xe4,0x2d,0x58,0xc9, +0xd7,0xb0,0x92,0xc9,0x7a,0xd3,0xa6,0x28,0xcf,0x2a,0xf3,0x94,0xf9,0xb0,0x8f,0x8f, +0xe0,0x1d,0x2b,0xe8,0x70,0x19,0xe8,0x78,0x47,0xe0,0x1c,0x43,0xe1,0x1b,0x57,0xb9, +0x9e,0x96,0x6b,0x1d,0xdb,0x08,0x5c,0xe3,0x2b,0xb8,0xc6,0x08,0xb8,0xc6,0xbe,0xf0, +0x8c,0xeb,0xe0,0x18,0x37,0x2a,0x37,0xd3,0xc1,0x32,0x8d,0xfe,0x95,0x0a,0x3a,0x58, +0x66,0xd2,0xc1,0xf2,0x02,0x1d,0x2c,0xf3,0x60,0x1d,0x89,0x8c,0xfe,0xa7,0x64,0x95, +0x22,0xa5,0x44,0xa9,0xa9,0x6c,0xa1,0xd4,0xca,0x44,0xbd,0x2c,0x3b,0xd1,0xbf,0x12, +0xba,0x57,0xfa,0x2b,0x67,0x2b,0xe7,0xba,0xde,0x95,0xd0,0xb5,0xf2,0xbe,0xf2,0x01, +0x7d,0x2b,0x1f,0xd1,0xb3,0xf2,0x09,0x3d,0x2b,0x9f,0xd3,0xaf,0x12,0x98,0x48,0x6d, +0xd7,0xa3,0x52,0x0a,0x07,0x79,0xc0,0x75,0xa6,0x2c,0x83,0x81,0x7c,0xe5,0xfa,0x51, +0x7e,0xa8,0x11,0xf5,0xa2,0x58,0x1f,0x8a,0xf5,0xa0,0x58,0xff,0x49,0x29,0x1c,0x24, +0x74,0x9f,0x9c,0x04,0x0b,0x09,0x1c,0x64,0x34,0x7d,0x27,0x63,0xe8,0x37,0x59,0x42, +0xbf,0x49,0x81,0xeb,0x32,0xb1,0x0e,0x93,0xce,0x74,0x96,0x58,0x57,0x49,0x4f,0x98, +0x48,0xe8,0x25,0x39,0xd5,0x75,0x8f,0x8c,0x84,0x85,0xfc,0x01,0x06,0x62,0xec,0xc3, +0xba,0x45,0x66,0xd0,0x25,0xf2,0xaa,0xeb,0x0f,0xb1,0xde,0x90,0x85,0xf4,0x85,0x84, +0xae,0x90,0xd5,0xca,0x17,0xca,0x3a,0xd7,0x13,0x92,0x74,0xdd,0x20,0xb5,0x61,0x21, +0x8d,0x60,0x20,0xad,0x61,0x1f,0xd6,0xfd,0xd1,0x99,0xce,0x8f,0x23,0x5c,0xcf,0x87, +0xf5,0x7b,0x0c,0x84,0x87,0x84,0x3e,0x8f,0x0b,0xe9,0xf4,0xb0,0x2e,0x8f,0x9b,0x61, +0x22,0x0f,0xc3,0x42,0x9e,0x74,0x7d,0x1d,0x33,0xe8,0xe7,0xb0,0x5e,0x8e,0xd9,0x8e, +0x89,0x2c,0xa1,0x83,0x63,0x95,0xeb,0xdf,0xb0,0xde,0x8d,0x42,0xf8,0xc8,0xd6,0x70, +0x91,0x16,0xf0,0x10,0xeb,0xd5,0xe8,0xe4,0x3a,0x34,0xba,0xd2,0x9d,0x61,0x9d,0x19, +0xd6,0x95,0xd1,0x87,0x8e,0x8c,0xd3,0x5d,0x1f,0xc6,0x48,0xf8,0xc8,0xef,0xe1,0x22, +0xc6,0x43,0xee,0x83,0x83,0x8c,0xa7,0xe7,0xc2,0xfa,0x2d,0x5e,0xa0,0xd7,0x62,0xb6, +0xeb,0xb2,0x08,0x3d,0x16,0x6b,0x94,0x6f,0x95,0xb5,0x25,0x55,0x5d,0x16,0xd6,0x61, +0x51,0x0b,0x56,0xd2,0xc8,0xf5,0x55,0x74,0xa4,0xa7,0xe2,0x10,0xfa,0x29,0x8e,0x81, +0x9b,0xfc,0x16,0x5e,0xd2,0x8f,0x1e,0x8a,0x8b,0x94,0x8b,0x95,0x2b,0x5c,0x07,0xc5, +0x4d,0x30,0x93,0x87,0x61,0x25,0xd6,0x31,0xf1,0x02,0xdd,0x11,0xb3,0xe8,0x8c,0x78, +0x0f,0x66,0xb2,0x84,0x8e,0x88,0x55,0x7c,0xa1,0x4b,0xc1,0x4c,0xb6,0xa2,0xfb,0xe1, +0x00,0xba,0x1e,0x0e,0xa1,0xe3,0xa1,0x9b,0xe3,0x26,0xfd,0xe8,0x6f,0xb0,0xbe,0x86, +0x91,0xf0,0x92,0x09,0x8e,0x91,0x58,0x27,0xc3,0x7c,0xd7,0xc3,0xf0,0x31,0xfd,0x0b, +0x49,0xd7,0xb9,0x10,0xfa,0x16,0x3a,0xc1,0x4f,0x42,0xc7,0x42,0x77,0xd8,0x89,0x31, +0x93,0x1b,0x1c,0x27,0xb1,0xfe,0x84,0x89,0x8e,0x91,0x58,0x57,0xc2,0x3c,0x18,0x89, +0x75,0x23,0xec,0x48,0x1f,0x42,0x1b,0xfa,0x10,0xf6,0xa3,0x0f,0xa1,0x1d,0x9d,0x08, +0x87,0xd1,0x81,0x60,0xdd,0x07,0x23,0xe9,0x3e,0xb8,0x96,0xce,0x83,0xd0,0x77,0x30, +0x8d,0xae,0x83,0x17,0x95,0x39,0xb0,0x95,0xa6,0xae,0xdf,0xc0,0x7a,0x0d,0xda,0xd3, +0x67,0xd0,0x89,0xbe,0x82,0x13,0xe8,0x29,0x38,0x99,0xfe,0x81,0x0b,0x5c,0xe7,0xc0, +0x48,0xba,0x06,0xac,0x63,0x20,0x74,0x08,0xdc,0xed,0x18,0x4b,0xe0,0x2b,0x87,0xc3, +0x4f,0x8c,0x9b,0xf4,0x85,0x97,0x8c,0x86,0x93,0x4c,0x72,0x6c,0xe4,0x25,0x98,0xc8, +0x56,0xb0,0x90,0xe0,0xf7,0xf7,0x85,0x87,0x8c,0x86,0x87,0x04,0x16,0x92,0xd8,0x26, +0x62,0x21,0xc3,0x60,0x20,0x77,0xc2,0x40,0x12,0x38,0xfb,0xe6,0xea,0xb7,0x70,0x7e, +0xfe,0x91,0x70,0x8f,0xf3,0xf0,0xf1,0x87,0xe1,0xe1,0x9b,0x7f,0x3f,0xcd,0x39,0xf7, +0xc1,0xb7,0x7f,0x5d,0x79,0xd7,0x79,0xf6,0xc1,0xb1,0x5f,0xa9,0x24,0xb6,0x8f,0x3c, +0xfb,0x5a,0xce,0xb1,0xdf,0x0d,0x26,0x32,0x12,0x16,0x32,0xd6,0x71,0x90,0x04,0xbe, +0xfc,0x9e,0x78,0xf2,0x0d,0xf1,0xe3,0xcd,0x8b,0x0f,0x4e,0x7c,0x99,0xd2,0x05,0x2f, +0x7e,0x20,0x7c,0xa4,0x1c,0xff,0xfd,0x03,0xf8,0xc8,0x76,0xf8,0xee,0xc1,0x73,0xaf, +0xe7,0xbc,0xf6,0xe3,0x9d,0xcb,0x6e,0x0e,0xfb,0x69,0xb8,0xeb,0x83,0x9d,0xaf,0x1e, +0x5c,0xf5,0x31,0x38,0xea,0x09,0x7c,0xf4,0x56,0x31,0xff,0xfc,0x37,0xb8,0xe4,0x43, +0x70,0xc9,0x87,0xe3,0x8c,0x3f,0x80,0x2b,0x6e,0x8e,0xf8,0x78,0xe7,0x81,0x2f,0xc5, +0xff,0x5e,0xee,0x9c,0xef,0xe0,0x7b,0x7f,0xb7,0x53,0xe4,0x77,0xb7,0xc2,0xeb,0x6e, +0x0f,0x9f,0x19,0x0d,0x7f,0x09,0x8e,0xf6,0x02,0x1c,0x6d,0x73,0xb3,0x3f,0x71,0x3e, +0xb6,0x79,0xd8,0xdf,0x38,0x16,0x53,0x01,0x63,0xd9,0x1e,0xb6,0x72,0x28,0x4c,0xa5, +0x97,0xe3,0x28,0x7d,0xe0,0x27,0x81,0x9d,0x3c,0x03,0x37,0x99,0x0e,0x3b,0x09,0xdc, +0x64,0x36,0xdc,0x24,0x30,0x93,0xf7,0x61,0x26,0xcb,0x61,0x26,0x81,0x97,0x7c,0xcf, +0x70,0x54,0xa2,0xd4,0x52,0x6a,0x2b,0x75,0x94,0x06,0x4a,0x43,0xa5,0x91,0xd2,0x58, +0x69,0xa2,0x34,0x55,0x9a,0x29,0xcd,0x95,0x52,0xa5,0xb5,0xd2,0x45,0x39,0x58,0xe9, +0xa3,0xf4,0x55,0x4e,0x57,0xce,0x50,0xce,0x54,0xce,0x52,0xfa,0x2b,0x03,0xe1,0x31, +0x43,0x94,0x4b,0x95,0xcb,0xe1,0x32,0xc3,0x94,0xeb,0x94,0x1b,0x94,0xd1,0xca,0x18, +0x5c,0xeb,0x04,0x9c,0xa6,0x00,0x4e,0x93,0x85,0xd5,0x6c,0x03,0xa7,0xd9,0x16,0x46, +0x53,0x0f,0x3e,0xb3,0x37,0x7c,0xa6,0x3e,0x7c,0xa6,0x21,0x8c,0xc6,0xd8,0x4c,0x3b, +0x58,0x4c,0x19,0x2c,0xe6,0x70,0x38,0x4c,0x0f,0x58,0xcc,0x28,0x65,0xb4,0xb2,0xd5, +0x1e,0xfa,0xff,0x23,0x65,0x1b,0xa5,0x8d,0x06,0xc5,0xcb,0x94,0x5b,0x95,0xdb,0x94, +0xb2,0xbd,0xf4,0xbc,0xca,0xb5,0xca,0x5d,0xca,0xa7,0xca,0xa3,0x1a,0x24,0xc7,0x85, +0x61,0xb2,0x81,0xd2,0x50,0xff,0xbf,0xc9,0x50,0xf9,0x11,0xcc,0x66,0x05,0xcc,0xe6, +0x5b,0x06,0xcd,0xfa,0x8e,0xd3,0x0c,0x70,0x0e,0xf5,0x18,0xd8,0x4c,0x39,0x4c,0xa6, +0x02,0x16,0x33,0x0f,0x06,0xb3,0x88,0x21,0xb5,0xaf,0x32,0x4c,0xb9,0x33,0x0c,0xac, +0xcd,0xf5,0xf9,0xd9,0x3c,0x1a,0x5c,0x93,0xf0,0x99,0x2c,0x4c,0xa6,0x11,0x8e,0x74, +0x29,0x6c,0xa6,0x0d,0x6c,0xe6,0x00,0x58,0xcc,0xed,0xb0,0x98,0xc0,0x61,0xc6,0xc0, +0x5f,0xcc,0x7b,0x2e,0x84,0xb7,0x8c,0x56,0x2a,0x94,0x15,0xf0,0x96,0x5d,0x5a,0xe8, +0xc3,0x44,0xe9,0xa1,0xf4,0x55,0x2e,0x57,0xae,0x50,0x1e,0x57,0x2a,0x94,0x59,0xca, +0x3c,0xe5,0xa2,0x96,0x7a,0xbf,0x29,0x1f,0x28,0x8b,0x94,0xca,0x96,0x11,0xa7,0xa9, +0x80,0xd3,0x8c,0x86,0xcb,0x6c,0x01,0x7f,0x29,0xc3,0x69,0x1e,0x8c,0xd7,0x3c,0x14, +0xde,0x72,0x37,0x9c,0x25,0x38,0xcb,0xab,0xc3,0xa0,0x0d,0x5f,0x09,0x1c,0x65,0x94, +0xe3,0x25,0xe6,0x13,0x9b,0x47,0x6c,0xfe,0xf0,0xde,0xb8,0xc2,0x0d,0x70,0x85,0x4b, +0x95,0xfd,0x60,0x23,0x43,0x70,0x86,0x83,0x1f,0x3c,0x07,0x2f,0x78,0xb5,0x73,0x7f, +0x83,0xef,0xdb,0x0c,0xcf,0x37,0x38,0xbe,0x7d,0x70,0x7b,0x47,0x38,0x8f,0xf7,0x29, +0xfc,0xdd,0xa9,0x78,0xbb,0x81,0x93,0x7c,0xe0,0xfc,0xdc,0x04,0xfe,0x6d,0x73,0xbc, +0xdb,0x96,0xf8,0xb6,0x65,0xce,0xb1,0xfd,0x2f,0xe7,0xd5,0xfe,0xd6,0xb9,0xb2,0xe5, +0xce,0x8b,0x7d,0x12,0x1f,0x76,0x32,0x1e,0x6c,0x85,0x73,0x5f,0xdf,0xc5,0x6d,0xfd, +0xdc,0x79,0xab,0x45,0xf0,0x8e,0xdd,0xe0,0x1c,0x81,0x71,0xf4,0x87,0x65,0x0c,0x74, +0xbe,0xa9,0x79,0xa6,0xe6,0x95,0x06,0xa6,0x51,0x0e,0xcb,0x08,0xdf,0x9c,0x0c,0x84, +0x5f,0x6c,0xed,0x9c,0xd1,0xc0,0x2d,0x1a,0xc2,0x2d,0xf6,0x73,0xac,0xe2,0x20,0x18, +0x45,0x0f,0x65,0x26,0x9c,0xa2,0x23,0x9c,0x62,0x34,0x9c,0xe2,0x25,0x38,0xc5,0xf7, +0xf8,0xa1,0x75,0xf0,0x43,0x4b,0x95,0x1e,0x4a,0x4f,0xe5,0x48,0xe5,0x68,0xe5,0x18, +0xe5,0x58,0xa5,0x8f,0xd2,0x57,0xe9,0xa7,0x9c,0xaa,0x9c,0xa9,0x9c,0xa5,0x9c,0x8d, +0x43,0x1a,0x38,0x47,0xa5,0x92,0xac,0xd4,0xc7,0x80,0x92,0x51,0x4a,0x94,0x9a,0xca, +0x16,0x4a,0xad,0xca,0xc8,0x2d,0xdd,0x51,0xd9,0x09,0xbf,0xb4,0x3d,0x3c,0xa4,0x37, +0x3c,0xe4,0x59,0x38,0xc7,0x7c,0xf8,0xc6,0x22,0x65,0x89,0xf2,0x91,0xb2,0x54,0xf9, +0x16,0xde,0xb1,0x05,0x9c,0xa3,0x03,0x7c,0xa3,0x07,0x5c,0x23,0x5c,0x08,0x96,0x54, +0x52,0x4a,0x0d,0xa5,0x6d,0x32,0xe2,0x1c,0x37,0x2a,0xa3,0x95,0x31,0xca,0x3c,0xe7, +0x8b,0x8e,0xc1,0x11,0x5d,0x0c,0xf7,0x68,0x0a,0xd7,0xb8,0x10,0xae,0x71,0x0f,0x3c, +0x23,0x81,0xdf,0x59,0x0e,0xb7,0x48,0xc0,0x2b,0x06,0xc0,0x29,0x6e,0x80,0x4f,0xfc, +0x09,0x2e,0x31,0x01,0x1e,0x51,0x01,0x87,0x28,0x83,0x3f,0x0c,0x83,0x3b,0x3c,0x01, +0x6f,0x30,0xce,0xd0,0xd6,0xb1,0x85,0xe3,0x94,0x07,0xe1,0x09,0x81,0x25,0xac,0x53, +0x76,0x85,0x23,0x74,0x82,0x1f,0x4c,0x55,0xe6,0x17,0x45,0x4e,0x65,0x21,0x2e,0x65, +0x1d,0xd8,0xc1,0x0e,0xb8,0x93,0xc1,0x99,0x2c,0x53,0x7a,0xc0,0x10,0x2a,0x70,0x24, +0x97,0xc1,0x0c,0xf6,0x87,0x19,0x1c,0xaf,0x5c,0xac,0xdc,0xae,0x8c,0x85,0x17,0x0c, +0x83,0x13,0xac,0x85,0x13,0xec,0x85,0x0f,0x59,0x06,0x2f,0x08,0xae,0xe3,0x79,0x70, +0x81,0x9b,0x94,0xbe,0xb5,0x22,0x2e,0x10,0x1c,0xc7,0x71,0xb0,0x81,0xc0,0x05,0x5e, +0xc6,0x67,0x9c,0x07,0x0f,0x58,0x09,0x0f,0x28,0xc5,0x5b,0xec,0x09,0x07,0x08,0xce, +0xe2,0xd5,0xb0,0x80,0x45,0xb5,0xab,0x3c,0xc5,0x14,0x5e,0x62,0x57,0xe5,0x48,0xdc, +0x44,0x73,0x12,0x07,0x3b,0x0f,0x71,0x38,0xbe,0xe1,0x5f,0xf1,0x0c,0xa7,0xe0,0x18, +0xce,0x86,0x17,0xac,0xc4,0x2f,0x2c,0xc0,0x2b,0x34,0x9f,0xb0,0x0d,0xbc,0x20,0x78, +0x82,0x43,0x70,0x04,0x87,0xe3,0x02,0x4e,0xc7,0xfd,0x9b,0xed,0x7c,0xbf,0xc5,0xf0, +0x82,0xad,0xf1,0xf9,0x5a,0x38,0x87,0x2f,0xf8,0x7b,0xfb,0x39,0x77,0xcf,0x9c,0x3d, +0x63,0x07,0x37,0xc3,0x0c,0xca,0x9d,0x97,0xf7,0x21,0x3e,0x5e,0x02,0x0f,0xaf,0x10, +0x7e,0xb0,0x35,0xdc,0xa0,0x05,0xbc,0xa0,0x3d,0xac,0xc0,0xbc,0xba,0xae,0xf8,0x74, +0x3d,0x9c,0x43,0x77,0x3a,0xce,0xdc,0x30,0xc7,0x0d,0x46,0xc3,0x0a,0xa6,0x38,0x17, +0xee,0x45,0x1c,0xb8,0x39,0xce,0x7b,0x7b,0xcd,0xb9,0x6e,0x6f,0xe1,0xba,0x25,0x70, +0xdb,0xca,0x70,0xda,0x0e,0x76,0x1e,0xdb,0x89,0xce,0x5d,0x1b,0x86,0xab,0x36,0xd9, +0xf9,0x69,0xd3,0x9d,0x93,0xf6,0x1c,0x0e,0xda,0x30,0x9c,0xb3,0x49,0xb8,0x66,0xe6, +0x98,0xcd,0xc0,0x2d,0x4b,0xe0,0x92,0xb5,0x77,0xfe,0x58,0x70,0xc7,0x3a,0xe3,0x8c, +0xf5,0x85,0x49,0x3c,0xe2,0x3c,0xb1,0xf1,0xf8,0x61,0x4f,0x39,0x27,0xac,0x02,0x17, +0x2c,0xe1,0xfc,0x2f,0xf3,0xbe,0xf6,0x70,0xae,0x57,0x29,0x0c,0xa3,0xb9,0xf3,0xb8, +0xda,0xc3,0x33,0x02,0xcb,0x30,0x86,0x51,0x17,0x76,0xd1,0x16,0x37,0xeb,0x00,0xe7, +0x63,0x05,0xdf,0xaa,0x0b,0xce,0xd5,0x18,0x18,0xc6,0xeb,0xb8,0x55,0xef,0x39,0x9f, +0xca,0xbc,0xa9,0x1a,0x4a,0x11,0x2c,0xa3,0x25,0xbe,0x54,0xf0,0xa4,0x3a,0x39,0x47, +0xaa,0x27,0x6e,0x54,0x2f,0xd8,0xc6,0x75,0xce,0x83,0xba,0x03,0xbe,0x91,0x70,0xce, +0x53,0x3f,0xe7,0x39,0x99,0xdf,0xb4,0x12,0xde,0x51,0x8c,0xc7,0xb4,0x1f,0xee,0x52, +0x70,0x95,0x06,0xe2,0x28,0x99,0x9b,0x64,0x4e,0x92,0xb9,0x48,0x09,0x18,0x48,0x09, +0xee,0x91,0x39,0x47,0x9d,0x9c,0x67,0xd4,0x03,0x1e,0x72,0x06,0x1c,0x64,0x34,0x1e, +0xd1,0xad,0xce,0x1d,0x32,0x67,0xa8,0x1c,0x37,0x68,0xa5,0xe3,0x20,0x6b,0xf0,0x80, +0x12,0xb0,0x90,0xad,0xf0,0x7b,0x3a,0x3a,0xa7,0x27,0xb8,0x3c,0x07,0x39,0x87,0xa7, +0x42,0x79,0x43,0x79,0x5f,0x59,0xac,0x54,0xee,0x1a,0x31,0x92,0xc0,0x43,0x46,0xc3, +0x41,0xcc,0xd3,0xe9,0x0a,0x07,0xc9,0x5d,0xa8,0x87,0x93,0xd3,0x08,0x17,0xa7,0x14, +0x16,0x52,0x86,0x7b,0x73,0x1e,0xce,0xcd,0x3c,0x5c,0x9b,0x2f,0x61,0x21,0xc1,0xb3, +0x69,0x8b,0x5f,0xd3,0x1b,0x1e,0xf2,0x3b,0x38,0x48,0x19,0xbc,0x63,0x0a,0x9c,0xc3, +0x3c,0x99,0x9b,0xe1,0x1c,0x81,0x71,0x2c,0x71,0x3e,0xcc,0x4a,0xb8,0x46,0x60,0x1a, +0xc3,0x60,0x19,0x63,0x60,0x18,0x5f,0xc2,0x2e,0x02,0xb7,0x30,0x5e,0x61,0x9c,0x22, +0x30,0x8a,0x04,0x6c,0x62,0x18,0x4c,0xe2,0x2e,0x9c,0x95,0x7b,0x94,0x31,0x81,0x4f, +0xcc,0x4a,0x26,0xde,0x9c,0x15,0xf9,0x2b,0x6b,0x83,0xbf,0x32,0x5b,0x9f,0x87,0x73, +0xf4,0xf9,0xac,0xbc,0x3f,0x27,0xf2,0x59,0x82,0xcb,0xd2,0x23,0x5c,0x6e,0x1b,0x2e, +0x46,0x7c,0x2d,0x72,0x5a,0x1a,0xe2,0xb2,0xf4,0x57,0x06,0xe3,0xb1,0x8c,0xc0,0x63, +0xb9,0x01,0x8f,0x65,0xbc,0xf2,0x89,0xb2,0x2c,0x5c,0xec,0x3a,0x3f,0x72,0x5a,0x0e, +0xc6,0x69,0x09,0x3e,0xcb,0x89,0x4a,0x85,0xb2,0x28,0x78,0x2c,0x0b,0xf4,0xfe,0x5c, +0x10,0xf1,0x92,0x63,0xe1,0x24,0xc6,0x47,0xc6,0xc2,0x45,0x8c,0x87,0x04,0x16,0x52, +0x03,0x06,0xb2,0x2d,0xec,0xa3,0x3d,0xcc,0xc3,0x58,0x47,0xe0,0x1c,0x81,0x71,0xcc, +0x80,0x71,0xbc,0x0b,0xe3,0x58,0x07,0xe3,0xa8,0x0b,0xe3,0x68,0x0d,0xe3,0xe8,0x0e, +0xe3,0x18,0x00,0xe3,0x18,0x05,0xe3,0x18,0x0b,0xe3,0x98,0x09,0xe3,0x08,0xfe,0x49, +0xee,0x02,0xb3,0x77,0xf4,0xef,0x8b,0x7f,0x72,0x2e,0xee,0xc9,0x85,0xb8,0x27,0x23, +0xf1,0x4f,0x82,0x7b,0x92,0xbb,0xcc,0x0d,0xee,0x31,0x1b,0xaf,0x24,0x8b,0x4f,0xb2, +0x27,0x1e,0x49,0xa9,0x73,0x47,0x4a,0x61,0x20,0x65,0x8e,0x7f,0x98,0x1f,0xf2,0x19, +0x5e,0x48,0x25,0x1c,0xe4,0x33,0x3c,0x90,0x79,0xf8,0x1f,0x81,0x7f,0x54,0xc2,0x40, +0x16,0x39,0xcf,0xc3,0xfc,0x8e,0xcf,0xe1,0x1f,0xe6,0x73,0x2c,0x82,0x77,0x2c,0x87, +0x73,0x04,0xc6,0xf1,0x22,0xce,0x46,0x02,0x57,0xc3,0x1c,0x8d,0x93,0x94,0xf3,0x3f, +0xd3,0xd7,0xa1,0xe5,0x11,0xf3,0x28,0x84,0x75,0xec,0xe5,0xf8,0x46,0x2b,0xc7,0x34, +0x0e,0x74,0x1c,0xc3,0xf8,0x45,0x4f,0xc7,0x2c,0x7a,0x39,0x4e,0x61,0x7c,0xc2,0xb8, +0xc4,0x39,0xf0,0x88,0x4b,0x1c,0x83,0xb8,0x1e,0xf6,0x70,0x3f,0xcc,0x61,0x65,0x60, +0x0e,0x2b,0xf5,0xfe,0x52,0xc6,0x28,0x8f,0x2b,0x33,0x94,0xd7,0xc2,0x25,0x9c,0xab, +0xf4,0xf5,0x47,0xa9,0xa3,0x34,0x57,0x4a,0x95,0xfe,0xca,0x40,0x65,0x9c,0x32,0x5e, +0xf9,0x38,0xfc,0xfe,0x6a,0xbd,0x9f,0x95,0x1e,0x4a,0x5f,0x25,0xb1,0x46,0x1f,0x23, +0x5f,0xe9,0xef,0x56,0x12,0x5f,0xeb,0xeb,0xb0,0xf2,0xae,0xb2,0x48,0x59,0xa9,0xd4, +0xf9,0x46,0xcf,0xab,0xf4,0x55,0x46,0x2b,0xe5,0x4a,0x85,0x32,0x2f,0x5c,0xa8,0xfc, +0xad,0x9e,0xbe,0x56,0x2f,0x43,0x19,0xa6,0xbc,0xa4,0xcc,0x52,0x16,0x2a,0x2b,0xc2, +0x05,0x83,0xeb,0x34,0xe3,0xad,0x8b,0xfc,0x8e,0xb5,0xf8,0x1d,0x81,0x95,0x04,0x4e, +0x12,0x18,0x49,0xe0,0x23,0x81,0x8d,0x04,0x38,0x10,0x98,0x48,0xe0,0x21,0xc9,0x44, +0x2d,0x7d,0x3b,0x5f,0x2b,0x3a,0xa8,0x4b,0x44,0x07,0x5f,0xd9,0x3c,0x7c,0x64,0xa7, +0xe8,0x78,0x61,0x3d,0x1f,0x09,0x57,0x99,0xef,0xad,0x34,0x8a,0xf1,0x91,0xe6,0xf4, +0xdd,0x07,0x3e,0x52,0x86,0x13,0xd2,0x17,0x27,0x64,0xa8,0x72,0x15,0x7c,0xe4,0x1e, +0xc7,0x47,0xee,0x8f,0xbe,0x95,0xca,0xf1,0x91,0x47,0xe1,0x23,0x8f,0x29,0x8f,0x2b, +0x13,0x1c,0x1f,0x99,0xe4,0xf8,0xc8,0x74,0x3c,0x92,0xb7,0xf0,0x48,0x02,0x1f,0xd1, +0x9b,0x9a,0x78,0x1a,0x2f,0x64,0x2e,0x5e,0xc8,0x42,0xbc,0x90,0xe5,0xf0,0x91,0xca, +0x54,0xd4,0x6f,0x1f,0x9c,0x90,0x0b,0x70,0x41,0x7e,0xe7,0xf8,0xc8,0x48,0xc7,0x47, +0xcc,0xff,0xb8,0x17,0xe7,0x23,0xf0,0x91,0xe1,0x69,0x7d,0x4f,0x89,0xf3,0x11,0x7c, +0x8f,0x51,0xf0,0x91,0xe0,0x78,0xdc,0x04,0x1f,0x79,0x26,0xc6,0x47,0x9e,0x85,0x8f, +0x3c,0x0f,0x1f,0x79,0x19,0x17,0xe4,0x0b,0xa5,0x30,0xa3,0xef,0x45,0xe1,0x23,0xc5, +0x31,0x3e,0x52,0x9b,0xce,0xfa,0xc3,0xe9,0xa6,0x3f,0x0b,0x3e,0x72,0x8e,0xeb,0xa6, +0x7f,0x83,0x1e,0x7a,0xe3,0x23,0x7f,0xc7,0x13,0x59,0x0a,0x1f,0x59,0x8e,0x2f,0x12, +0xba,0xe7,0xb7,0x70,0x5d,0xf3,0xcd,0xe9,0x97,0xbf,0xdf,0xf5,0xca,0x7f,0x4a,0x87, +0x7c,0xf0,0x43,0xbe,0x75,0x7c,0xa4,0xae,0xeb,0x8c,0xb7,0xae,0x78,0xeb,0x88,0x0f, +0xdd,0xf0,0x1d,0x71,0x44,0x7a,0xc3,0x47,0xfa,0xe3,0x86,0xdc,0x42,0x17,0xfc,0xcb, +0x74,0xbf,0x2f,0xa1,0xfb,0x7d,0xff,0x18,0x1f,0x29,0xa3,0xd3,0xdd,0xfa,0xdc,0x7b, +0xd0,0xdd,0x7e,0x32,0x9d,0xed,0xd6,0xcf,0x3e,0x02,0x57,0x64,0x34,0x8e,0x88,0xf9, +0x21,0xd6,0xbf,0x5e,0x41,0xd7,0xfa,0x4b,0xae,0x63,0xdd,0xf8,0xc8,0xfb,0xf8,0x21, +0x1f,0xe2,0x87,0xac,0x51,0xd6,0xc2,0x47,0xbe,0x87,0x8f,0x58,0x7f,0x7a,0x31,0xae, +0x48,0x03,0x1c,0x91,0x96,0xb8,0x21,0xd6,0x8f,0x5e,0x46,0x27,0xfa,0xa1,0xae,0x0b, +0xdd,0x5c,0x91,0x01,0xf4,0x9e,0x0f,0x71,0x7c,0xc4,0xfa,0xce,0x6f,0xc4,0x19,0x79, +0x08,0x57,0x64,0x82,0xeb,0x34,0xaf,0xa0,0xbf,0xdc,0xba,0xcb,0x67,0x39,0x3e,0xb2, +0x98,0x8e,0xf2,0x95,0x8e,0x8f,0x58,0x37,0x79,0x01,0xfe,0x48,0x1d,0xbc,0x91,0x52, +0x7c,0x11,0xeb,0x1e,0xef,0xe8,0xf8,0x48,0x17,0xba,0xc5,0xad,0x57,0xdc,0xfa,0xc4, +0x4f,0xc4,0x21,0x09,0xfd,0xe1,0x17,0x39,0x3e,0x72,0x1d,0xee,0xc8,0xad,0xce,0x19, +0xb9,0x07,0x4f,0xe4,0x61,0xfc,0x10,0xeb,0x00,0x7f,0x96,0xde,0xef,0x59,0x31,0x3e, +0xb2,0x5a,0xf9,0x26,0xc6,0x47,0xac,0xe7,0xbb,0x26,0x2e,0x49,0x03,0xd7,0xe9,0x7d, +0x00,0x3d,0xde,0x5d,0xe8,0xef,0xee,0x46,0x6f,0xf7,0x09,0xf8,0x24,0x27,0xd3,0xd3, +0x3d,0x00,0x3e,0x32,0xd4,0xf5,0x74,0xdf,0x80,0x53,0xf2,0x10,0x2e,0x89,0xf5,0x70, +0x3f,0x47,0xb7,0xf6,0xab,0x74,0x6a,0xbf,0x89,0x53,0xb2,0x98,0x0e,0xed,0x15,0x74, +0x66,0x27,0x71,0x4a,0xea,0xe0,0x92,0x74,0xa0,0x0b,0xbb,0x0b,0x1d,0xd8,0xd6,0x7f, +0xdd,0x1d,0x97,0xe4,0x14,0xd7,0x69,0x3d,0x02,0x9f,0xe4,0x71,0xe7,0x91,0x58,0x6f, +0xf5,0x6b,0xae,0xab,0x7a,0x21,0xfd,0xd4,0x5f,0x6c,0x51,0xd5,0x4b,0xdd,0x92,0x2e, +0xea,0x4e,0x38,0x25,0xa1,0x7f,0xba,0xb7,0xf3,0x4a,0xae,0x73,0x2e,0x89,0x75,0x4c, +0x4f,0x70,0xbd,0xd2,0xe6,0x8f,0xcc,0xa1,0x43,0x3a,0xf8,0x23,0xdb,0xd1,0x1b,0xdd, +0x2a,0x0f,0x1f,0x39,0x00,0xaf,0xe4,0x1c,0xd7,0x0f,0x7d,0x15,0x7c,0xe4,0x1a,0x1c, +0x93,0x3f,0xd1,0x05,0xfd,0x3c,0x7c,0x64,0x96,0xf2,0x4e,0xed,0xa8,0x07,0xda,0x3a, +0xa0,0xad,0xfb,0xb9,0x1d,0x7d,0xcf,0x1d,0xe9,0x73,0xee,0x85,0x87,0xd2,0x17,0xef, +0x64,0x88,0xeb,0x65,0xbe,0x8a,0x2e,0x66,0xeb,0x61,0xb6,0x9e,0xe5,0xe7,0x1d,0x1f, +0x39,0x14,0xbf,0xc4,0xdc,0x92,0x13,0xf1,0x49,0x6e,0xc4,0x23,0x79,0xd2,0xf9,0x23, +0xcf,0xe3,0x8c,0xd4,0xc1,0x15,0x39,0x81,0xee,0xe3,0xcb,0x71,0x45,0x6e,0xc7,0x15, +0xf9,0x1e,0x3e,0x12,0xfc,0x90,0x61,0xf8,0x21,0x77,0xe1,0x83,0x6c,0xe9,0xfa,0x8c, +0xf7,0xa5,0xc3,0xb8,0x0d,0x4e,0xc8,0x51,0x38,0x21,0x03,0xe9,0x2a,0x9e,0xe0,0x3a, +0x8a,0x9f,0x71,0xbd,0xc4,0x2f,0xd1,0x45,0xfc,0x4e,0x8c,0x8f,0x84,0xfe,0xe1,0x6f, +0x95,0x62,0x3a,0x88,0x8d,0x8f,0xec,0x80,0x33,0x72,0x15,0xae,0xc8,0x43,0x8e,0x8f, +0x04,0x47,0xa4,0x1e,0x5d,0xc2,0xfb,0xd0,0x21,0xdc,0xd8,0x75,0x07,0xef,0x47,0x5f, +0x70,0xe0,0x23,0x07,0xe3,0x90,0x0c,0xc1,0x1d,0x79,0x99,0x4e,0xe0,0xca,0x1d,0x22, +0x77,0x64,0x7b,0xd7,0x05,0x7c,0x8c,0xe3,0x23,0x27,0xc5,0xf8,0xc8,0xa9,0x74,0xfb, +0x0e,0x72,0x9d,0xbe,0xa3,0xe8,0xf1,0x1d,0x47,0x6f,0x6f,0x81,0xeb,0xe9,0x0d,0x7c, +0x64,0x7f,0xfc,0x93,0xfe,0xf4,0xec,0x5e,0x41,0xcf,0xee,0xbd,0xf4,0xe9,0x3e,0xe8, +0x7a,0x74,0xc7,0xb9,0xae,0xdc,0xff,0xa5,0x1f,0xf7,0x33,0xc7,0x47,0x56,0xd1,0x85, +0xdb,0x98,0xee,0xdb,0xd6,0x74,0xde,0x1e,0x86,0xa3,0x12,0xfc,0x94,0x17,0xe9,0xaf, +0x5d,0xe0,0xfa,0x6b,0x97,0xba,0xce,0x5a,0xeb,0xaa,0xfd,0xda,0xf5,0xd2,0x4e,0xa7, +0x63,0xb6,0x2e,0xee,0xc9,0xc1,0x38,0x27,0xc7,0xc5,0xf8,0xc8,0xef,0x70,0x4b,0xa6, +0x3a,0x3e,0x32,0x03,0xaf,0x24,0x38,0x25,0x73,0x71,0x4a,0x82,0x4f,0xb2,0x10,0x9f, +0x64,0x05,0x3e,0x49,0x70,0x49,0x7e,0x50,0x8a,0xe9,0x8b,0x35,0x3e,0x52,0x7f,0x13, +0xf8,0x48,0x2b,0xe5,0x20,0xf8,0xc8,0x49,0xf0,0x91,0x53,0xab,0xe1,0x23,0x03,0x1c, +0x1f,0xb9,0x44,0xb9,0x4c,0x19,0x0a,0x1f,0x19,0xa5,0x5c,0xef,0xfc,0x95,0xe7,0xe8, +0x9d,0x4d,0xc2,0x47,0x32,0xf0,0x91,0x22,0x3c,0x96,0x6d,0x9c,0xc7,0x12,0xfc,0x95, +0x3d,0x7f,0x82,0x8f,0x98,0xbf,0x12,0x3c,0x95,0xf6,0x78,0x2a,0x5d,0xf0,0x54,0xba, +0x29,0xdd,0x95,0x3e,0x78,0x29,0xd7,0x2b,0x5b,0xee,0x51,0xc5,0x47,0x5a,0xef,0xa9, +0xd9,0x4f,0xf9,0x23,0x7c,0xa4,0xe1,0x5e,0x9a,0x3b,0x94,0x6b,0x94,0x3b,0x95,0x4f, +0x94,0x47,0xf6,0x89,0xf8,0x48,0x65,0x7d,0xa5,0x81,0x3e,0x8e,0x34,0x50,0x56,0x36, +0x8e,0x7c,0x96,0x4f,0xf1,0x59,0x56,0xe1,0xb3,0x54,0x36,0xa9,0xf2,0x59,0x9a,0xe2, +0xb0,0x0c,0x84,0x8f,0xdc,0x86,0xbb,0x32,0x1e,0x67,0x65,0x1a,0xae,0xca,0x1c,0x1c, +0x95,0x0f,0xe8,0x8e,0x3d,0xb1,0x99,0xbe,0x76,0x2b,0xb7,0x2b,0x6b,0x94,0x37,0x34, +0xb4,0x56,0xc2,0x47,0xd2,0xf8,0x2a,0xbb,0xe1,0xab,0x34,0xa5,0x3f,0xb6,0x14,0x6f, +0xa5,0x2d,0x9e,0x4a,0x27,0x3c,0x95,0x3b,0xf0,0x54,0xee,0x81,0x8f,0x58,0x37,0x6c, +0x70,0x52,0x9a,0xe3,0xa2,0x04,0x0f,0xe5,0x23,0xf8,0xc8,0xce,0x2d,0xf4,0x79,0xad, +0x74,0x57,0xfa,0x28,0x97,0x29,0x43,0x95,0x72,0x65,0xba,0xf2,0xaa,0x32,0x57,0xb9, +0xb0,0xa5,0xde,0x6f,0xca,0xfb,0xca,0x42,0xe5,0x07,0xf8,0x48,0x70,0x58,0x2a,0xbb, +0x45,0xce,0xca,0x0b,0xff,0x13,0xb9,0x29,0xb5,0x71,0x52,0x82,0x87,0x32,0x08,0x3e, +0x62,0x9d,0xaf,0x7f,0xa6,0xdf,0x75,0x05,0x7d,0xae,0x5f,0x2b,0xbb,0x3b,0xd7,0xc4, +0x9c,0x12,0xeb,0x5c,0xb5,0xae,0x55,0xeb,0x58,0xdd,0xcb,0xf5,0xa9,0x36,0x86,0x8f, +0xb4,0x55,0xf6,0xc7,0x1b,0xb9,0x88,0xfe,0xd4,0xe7,0xe9,0x4d,0x5d,0xe5,0xfa,0x51, +0xf7,0xa6,0x0b,0xf5,0x10,0x3a,0x50,0x8f,0xc2,0x19,0x19,0xee,0xba,0x4e,0x9f,0xa4, +0xdf,0x74,0x0a,0xbd,0xa6,0xb3,0xe9,0x31,0xb5,0x0e,0xd3,0xe0,0x8c,0x34,0xa0,0x9b, +0xb4,0x94,0x4e,0xd2,0x56,0x74,0x91,0x5a,0x0f,0xe9,0x11,0x8e,0x8f,0xf4,0x72,0x7d, +0xa2,0x8f,0x39,0x3e,0x32,0x11,0x5f,0x64,0x12,0xbe,0xc8,0xf4,0x18,0x1f,0x59,0x46, +0xef,0xa7,0x75,0x7b,0x66,0xf0,0x41,0xb6,0xc5,0x03,0x69,0x86,0xe7,0x71,0x36,0x9e, +0x87,0x75,0x72,0x5a,0x17,0xa7,0x75,0x6f,0x86,0xce,0xcd,0xfb,0x70,0x3d,0x82,0xe7, +0x71,0x2e,0x7e,0x47,0xc6,0x79,0x1d,0xf5,0x70,0x3a,0x1a,0xe2,0x74,0x98,0xcf,0xd1, +0x19,0x87,0xa3,0xbb,0xf2,0xac,0x32,0x1f,0x87,0xa3,0x3b,0x0e,0xc7,0x2d,0x38,0x1c, +0x73,0x95,0xef,0x94,0xca,0xef,0xa3,0xee,0xcc,0x1d,0xe8,0xce,0xec,0x9e,0x87,0x8f, +0x9c,0x04,0x1f,0x39,0x59,0x39,0x45,0x39,0x1d,0x3e,0xd2,0x1f,0x3e,0x32,0x04,0x07, +0x24,0xf0,0x91,0x54,0xa5,0x3e,0x06,0x94,0xe2,0x18,0x1f,0xa9,0x4d,0xef,0x66,0xe0, +0x23,0xbb,0xe1,0x8a,0x94,0xb9,0xce,0xcd,0x69,0x78,0x20,0x73,0xf1,0x3f,0x82,0xfb, +0xb1,0x58,0xf9,0xbb,0xf2,0xb1,0xf2,0xb9,0xf2,0x7d,0xf8,0x3b,0xf1,0x40,0xda,0xe1, +0x7f,0x74,0xc3,0xfb,0x58,0x1b,0xe3,0x23,0x2d,0x95,0x4e,0xca,0x0d,0xca,0x4d,0xca, +0x5d,0xf0,0x91,0xef,0xe0,0x23,0x77,0xb9,0x1e,0xcd,0x75,0xca,0x9e,0x78,0x1f,0x17, +0xd0,0x8f,0xf9,0x67,0x7c,0x8f,0xe0,0x78,0xfc,0x99,0xee,0xcb,0x05,0x38,0x1d,0xf5, +0x71,0x39,0x2e,0xc5,0xe1,0xf8,0x3d,0xee,0xc6,0xbd,0x38,0x1b,0x93,0x71,0x35,0x82, +0xa7,0xd1,0x06,0x3f,0xe3,0x0c,0xbc,0x8c,0x72,0x7c,0x0c,0x73,0x31,0x5a,0x3b,0xff, +0xe2,0x18,0x5c,0x8b,0xc7,0x70,0x2d,0x82,0x67,0xb1,0x53,0x51,0xc4,0x47,0xf6,0xc7, +0xaf,0x08,0x6e,0xc5,0x5c,0xbc,0x8a,0x02,0xba,0x26,0x6b,0xe3,0x56,0x6c,0x87,0x53, +0x61,0xbd,0x92,0x87,0x2a,0xc7,0x2b,0xf7,0xe0,0x52,0x84,0xfe,0xc8,0xaf,0x8a,0x23, +0x9f,0xa2,0x13,0x3e,0xc5,0x20,0x3c,0x8a,0xbb,0x94,0xc7,0x4a,0x22,0x97,0xe2,0x09, +0x1c,0x8a,0xca,0x9a,0x91,0x43,0x51,0x9f,0xae,0xc8,0xc3,0x70,0x26,0xce,0x85,0x8f, +0x04,0x5f,0xe2,0x66,0x65,0x28,0xce,0xc4,0xa3,0xf0,0x91,0xc7,0x71,0x24,0x5e,0xa1, +0xeb,0xf1,0x6d,0x5c,0x89,0xd0,0xf3,0x58,0x1f,0x3f,0x22,0x74,0x3a,0xf6,0xc2,0x91, +0x08,0x7d,0x8e,0xa3,0x94,0x57,0x5d,0x97,0x63,0x12,0x4f,0x22,0x74,0x36,0x76,0x53, +0x4e,0x73,0xbd,0x8d,0x83,0x5c,0x57,0xe3,0x95,0xf4,0x31,0x3e,0x45,0x0f,0x63,0xe8, +0x60,0x9c,0xe1,0xf8,0xc8,0x52,0xfa,0x17,0x53,0xf8,0x14,0xd6,0xb9,0xd8,0x0a,0x9f, +0x62,0x90,0xeb,0x51,0xbc,0x92,0xae,0xc4,0xd0,0x93,0xf8,0x92,0xeb,0x45,0x0c,0x7c, +0x64,0xa1,0xf2,0xc5,0x96,0x91,0x4b,0xd1,0x8c,0xae,0xc3,0x96,0x8e,0x8f,0x84,0x6e, +0xc3,0x03,0xe0,0x23,0xd6,0x6b,0x68,0x7e,0xc5,0x8d,0x38,0x15,0x63,0x5d,0x77,0xe1, +0x12,0xfa,0x0a,0x43,0x57,0x61,0x92,0x8e,0xc2,0x9a,0xb8,0x15,0x0d,0x70,0x2a,0x5a, +0xe2,0x52,0x74,0x70,0xdd,0x83,0x5d,0xe8,0x1b,0xec,0xe6,0xf8,0xc8,0x29,0x74,0x0a, +0x0e,0x71,0x6e,0xc5,0x4d,0xf8,0x14,0x4f,0xbb,0xbe,0xc0,0xe7,0xe9,0x08,0x9c,0x9d, +0x87,0x8f,0xbc,0xa1,0xbc,0x4d,0x0f,0x60,0x5b,0x7a,0xff,0x3a,0xbb,0xbe,0xbf,0xc0, +0x47,0x7a,0x3b,0x3e,0x72,0x32,0x5d,0x7e,0x93,0x1c,0x1f,0x99,0xe6,0x7a,0xfb,0x66, +0xe2,0x62,0x84,0x7e,0xbe,0xc7,0xe9,0xe3,0x9b,0xe2,0x7a,0xf8,0x2a,0x70,0x33,0x42, +0xef,0x5e,0x0b,0x7a,0xf6,0x3a,0x38,0x3e,0x62,0xbd,0x7a,0xa1,0x4f,0xef,0x1c,0xd7, +0xa7,0x67,0x7c,0xe4,0x31,0xd7,0x9d,0x17,0xf8,0xc8,0x64,0xba,0xf2,0x42,0x4f,0xde, +0x8e,0x31,0x3e,0xb2,0xbb,0xeb,0xc3,0x6b,0x8c,0xe3,0xd1,0xcc,0x75,0xdd,0xb5,0x83, +0x8f,0xac,0x76,0x9e,0xc7,0xd6,0xb8,0x1d,0xad,0xe9,0xae,0xeb,0xe0,0xf8,0x88,0x75, +0xd2,0x1d,0x42,0x1f,0xdd,0x83,0xf4,0xcf,0xbd,0x45,0xef,0x9c,0x75,0xce,0x59,0xb7, +0x5c,0x46,0xc9,0xd2,0x2d,0xd7,0x82,0x4e,0xb9,0x76,0x74,0xc8,0x1d,0xe2,0xf8,0xc8, +0xb1,0xf4,0xc6,0xf5,0xc6,0xfb,0xb0,0xae,0xb8,0xd0,0x11,0xf7,0x17,0xe7,0x7e,0x18, +0x1f,0x39,0x35,0xc6,0x47,0x16,0xd3,0xfb,0x96,0xa5,0xe7,0xad,0x0d,0xfd,0x6e,0x07, +0x2b,0xe7,0xe0,0x82,0x58,0x7f,0x9b,0xf5,0xb6,0x59,0x5f,0x5b,0xe8,0x69,0xcb,0xe0, +0x87,0x94,0xba,0x5e,0xb6,0x03,0x5c,0x17,0x5b,0x57,0xfa,0xd7,0x4e,0xc3,0x13,0xb9, +0x89,0x9e,0xb5,0x3f,0x56,0xc3,0x47,0xc6,0xe2,0x88,0x7c,0xe2,0xf8,0xc8,0x6a,0x7a, +0xd2,0xbe,0xa9,0x17,0xf5,0xa3,0xd5,0xa1,0xff,0xac,0x9d,0xeb,0x3d,0x33,0x3e,0xd2, +0xcb,0xf1,0x91,0xd7,0x95,0xf7,0x94,0x45,0xca,0xaa,0x5d,0x23,0x87,0xe4,0x20,0x5c, +0x91,0xd5,0xcd,0xf5,0x67,0xe9,0x31,0x3b,0x84,0xfe,0xb2,0xe0,0x88,0x04,0x3f,0x64, +0x17,0xfa,0xca,0x9a,0xd0,0x53,0x16,0x3a,0xca,0xf6,0xc3,0x11,0x39,0x0b,0x47,0xe4, +0x65,0x1c,0x91,0x2f,0xe0,0x23,0xcd,0xe9,0x20,0x3b,0x98,0xee,0xb1,0x93,0x71,0x45, +0x82,0x27,0x12,0xba,0xc5,0xee,0xc0,0x05,0x09,0x1e,0x88,0x75,0x89,0x5d,0x43,0x6f, +0xd8,0x3d,0xf8,0x1f,0x9e,0x8f,0x04,0xef,0xe3,0x1d,0x7c,0x8f,0xe0,0x7a,0xdc,0x82, +0xe3,0xb1,0x06,0xb7,0x23,0x78,0x1d,0xe6,0x74,0x98,0xcb,0x71,0x26,0xfe,0x46,0x7f, +0xbc,0x8d,0x6b,0xf1,0x35,0xee,0xa2,0xcf,0x2b,0xf0,0x91,0xfb,0x94,0x37,0x66,0x25, +0x13,0x2b,0xe8,0xf6,0xfa,0x4e,0x99,0x30,0x47,0x9f,0xd3,0xca,0xeb,0xca,0xf7,0x73, +0xa2,0xae,0xaf,0xd0,0xf3,0x35,0x53,0xf9,0x72,0x9e,0x3e,0xfe,0xe9,0xfb,0x3a,0x9d, +0x9e,0xaf,0xd0,0xf1,0x75,0x29,0x1d,0x5f,0x57,0xd1,0xf1,0x35,0x96,0x8e,0xaf,0xa5, +0xca,0xa7,0x4a,0xa5,0xd2,0x99,0xbe,0xaf,0xc0,0x47,0x4e,0xa0,0xeb,0x2b,0xf4,0x7b, +0x2d,0x50,0xd6,0x28,0xc7,0x2e,0x48,0x26,0x2e,0x5e,0x10,0xb9,0x24,0x77,0x39,0x87, +0xe4,0x01,0xbc,0x11,0x73,0x46,0x66,0xe2,0x89,0x14,0xe3,0x87,0xec,0x8c,0x17,0xd2, +0xd1,0xf9,0x20,0x3d,0x70,0x40,0x2a,0xe0,0x23,0xef,0xc0,0x47,0xd6,0xc2,0x47,0x82, +0xff,0x51,0x17,0xff,0xa3,0x35,0xfe,0x47,0x77,0xfc,0x8f,0x01,0xf8,0x1f,0xa3,0xf0, +0x3f,0xc6,0xe2,0x7f,0xcc,0xc4,0xff,0x08,0xdd,0x5c,0x95,0x7f,0x8b,0xba,0xb9,0xda, +0xd1,0xcd,0x35,0x04,0x3e,0x32,0x02,0x3e,0x72,0x3d,0xdd,0x5c,0xa1,0x97,0x6b,0xe7, +0x77,0x23,0x2f,0xe4,0x36,0x7c,0x90,0x0c,0x7d,0x5b,0xbb,0xd3,0xb3,0xd5,0xc8,0xf5, +0x6b,0x35,0xa1,0x53,0xeb,0x00,0xba,0xb4,0xba,0x2f,0xae,0xea,0xd0,0x5a,0x46,0x6f, +0xd6,0xb7,0xf0,0x91,0x65,0xf4,0x64,0x85,0x8e,0xac,0xe5,0x74,0x63,0xad,0x85,0x8f, +0x7c,0xe0,0xba,0xb0,0xac,0x03,0x6b,0x39,0xbd,0x57,0xd6,0x79,0x15,0x9c,0x90,0x8f, +0x71,0x41,0x3e,0xc7,0x01,0x09,0xfe,0xc7,0x5c,0xfa,0xac,0x0e,0x72,0x3d,0x56,0xa1, +0xbf,0xaa,0x8f,0x32,0xf1,0x33,0xbd,0x6e,0xcb,0x23,0x1f,0x64,0x57,0xe7,0x81,0xd4, +0xc7,0xfd,0x68,0xfb,0x13,0x7c,0xa4,0xbb,0xf3,0x3a,0xaa,0xe3,0x23,0xe6,0x6e,0xf4, +0xc7,0xd7,0xb8,0xc8,0x79,0x1a,0xa3,0x70,0x33,0xee,0xc3,0xc9,0x08,0x3e,0xc6,0x2a, +0xa5,0xf1,0xca,0x64,0xe2,0x0f,0xca,0x78,0x65,0xba,0x32,0x57,0xf9,0x52,0x29,0x5e, +0xa5,0x99,0x46,0x69,0x06,0x1f,0x39,0x4b,0x19,0xa0,0x3c,0xea,0xf8,0x48,0x6a,0xb5, +0x5e,0x4f,0xe5,0x50,0xa5,0xa7,0x72,0x9a,0xf2,0xb7,0xaf,0x92,0x89,0xcf,0x94,0xef, +0x94,0xbf,0x39,0x3e,0xb2,0x4c,0x29,0xf9,0x46,0x6f,0x8f,0xd2,0x4b,0xb9,0x46,0x19, +0xa7,0x4c,0x51,0x66,0x28,0x6f,0x2b,0xc7,0xad,0xd5,0xbf,0xa3,0x72,0xb9,0xf2,0x02, +0x7c,0xe4,0x7d,0x65,0x99,0xb2,0x56,0xf9,0xfd,0x3a,0xbd,0xff,0xe9,0xbe,0x0a,0x7c, +0x24,0xb8,0x24,0xf5,0x70,0x48,0x16,0xe1,0x8e,0x04,0x6f,0xe4,0x70,0x7c,0x91,0xe0, +0x8a,0x04,0x3e,0x72,0x45,0x22,0xea,0xb7,0xfa,0xbe,0xb2,0xb6,0x52,0x27,0x91,0xdc, +0xb6,0xee,0xb6,0x35,0xeb,0x26,0xf5,0x43,0xba,0x24,0x5d,0x90,0x2a,0x48,0x15,0xa6, +0xd2,0x19,0x3d,0x26,0xeb,0x26,0x53,0x7a,0x8a,0x7e,0x91,0x2e,0x29,0xd4,0x4f,0x85, +0x99,0xf4,0x86,0x8f,0x59,0xfd,0xc0,0xaf,0x33,0xe1,0x17,0xd9,0xdc,0x8f,0xe9,0x92, +0x6c,0x0d,0x7b,0xac,0x51,0x9c,0x2e,0x2a,0x29,0x4a,0x15,0xa5,0xb3,0x45,0xd9,0xe2, +0x92,0xe2,0xa2,0xf0,0x53,0xf8,0xb5,0x52,0x58,0x14,0xfe,0x4b,0x8f,0x7a,0xb6,0x74, +0x0d,0xf7,0x47,0xb2,0x35,0x8a,0x8a,0x8a,0xc3,0x33,0x66,0x33,0x1b,0x3e,0x46,0x0f, +0xb9,0x5f,0x65,0xa3,0x5f,0x95,0xe8,0x31,0x6b,0xbf,0x11,0x7e,0x27,0x9b,0xfb,0xaf, +0xd8,0xb3,0x47,0xcf,0x9f,0xf5,0xcf,0xcb,0x73,0xac,0x7f,0xee,0xaa,0x87,0x2c,0xd1, +0x1b,0x9e,0xb5,0x17,0x93,0xfb,0x8b,0xa3,0xa7,0xa7,0x79,0xe6,0x6c,0x55,0xb2,0xee, +0x95,0x5a,0xff,0x77,0x65,0x79,0x59,0xfa,0xb9,0x64,0xc3,0x57,0x3d,0x53,0xf5,0x1a, +0x66,0xd3,0xeb,0x7f,0x95,0xf5,0x4f,0xae,0xf6,0xed,0xce,0x6c,0xf8,0x4a,0xe6,0xde, +0xf3,0x35,0x33,0xe9,0xcc,0xfa,0x97,0xec,0xfe,0x44,0x78,0x91,0xe9,0x74,0x36,0x99, +0x75,0x2f,0x34,0x7a,0x86,0x74,0xee,0x9f,0x2a,0xf7,0x66,0xac,0x7f,0xb9,0xbc,0xae, +0xd9,0xec,0xfa,0xe7,0x8a,0xbf,0x02,0xfe,0x3d,0x51,0xf5,0xb4,0xaa,0x87,0x74,0xf4, +0xea,0xf0,0x73,0xcd,0x64,0xa6,0x46,0xba,0x66,0xdd,0xed,0xea,0xd4,0xae,0xb5,0x45, +0xaa,0x24,0x9d,0xd2,0x13,0xb6,0xd9,0x72,0xab,0xad,0x93,0x85,0x99,0xc2,0x82,0x74, +0x2e,0x25,0xd9,0x74,0xfc,0x63,0x49,0xaf,0xf3,0xfa,0x5f,0xa7,0x0b,0x4a,0xa2,0x9f, +0xed,0x43,0x2e,0x9d,0x7b,0x85,0xd3,0xeb,0xdf,0xf3,0xbc,0x17,0xd2,0xb9,0x87,0x9a, +0xf6,0xbb,0xb9,0x9f,0xab,0x3e,0x1c,0x7f,0xfc,0x22,0xf8,0x3d,0x7d,0xf4,0x45,0x6f, +0x7f,0xf4,0x9c,0xf6,0x16,0xa5,0xb3,0xb9,0xd7,0x21,0xf6,0x66,0x67,0xab,0xfe,0x99, +0xfd,0x7f,0xfe,0xf8,0x9d,0x93,0xc9,0xa4,0x37,0xfc,0xc8,0xcb,0xe8,0x23,0xb9,0xa0, +0x46,0xee,0xa1,0x28,0x6d,0x8f,0xe1,0x65,0xa7,0x72,0x8f,0xfa,0x54,0x4b,0xeb,0x87, +0xa2,0xa2,0xe4,0x86,0x9f,0x75,0xb9,0x3f,0x5a,0xa2,0xa7,0xa5,0xab,0xde,0xbb,0x99, +0xe8,0x9d,0x10,0x5e,0x58,0x61,0x26,0x53,0xed,0x87,0x44,0xf4,0x12,0xab,0x1e,0xd2, +0xb9,0x1f,0xf5,0x71,0x9b,0xfb,0x31,0xf7,0x6b,0x7b,0x62,0xee,0x35,0xca,0x16,0x17, +0xd7,0xc8,0xea,0xbf,0x8b,0xc3,0xd3,0xf5,0xa9,0x98,0x2e,0xd2,0xe7,0x5d,0xee,0x93, +0xb1,0x46,0x0d,0xde,0x39,0xd9,0x6a,0xde,0xe6,0x0d,0x3f,0x2c,0x63,0x1f,0xa3,0x3f, +0xfa,0x34,0xcd,0x64,0x32,0xf6,0x39,0x97,0xcd,0xfc,0xf8,0xef,0x88,0xbf,0x8f,0x37, +0x78,0x81,0xe9,0xea,0x5e,0x90,0x7f,0xf7,0x56,0xfd,0x66,0xbe,0x0f,0x5b,0xf7,0x0a, +0x65,0xfd,0x4b,0xc8,0x44,0x5f,0x28,0xb2,0x1b,0xfe,0x2d,0x99,0xd8,0x2b,0x17,0xbe, +0xf4,0x65,0x36,0xfc,0x04,0xca,0x64,0xaa,0x3e,0xe5,0xfd,0xdb,0x99,0xae,0xfe,0x9f, +0x24,0x9b,0x49,0xea,0xe3,0x3d,0xf7,0x41,0xba,0xfe,0xe5,0x27,0xb3,0xf6,0xa1,0x97, +0xb5,0x2f,0x98,0xd5,0x3d,0x54,0xf7,0x81,0x5b,0x58,0xf5,0xb6,0x65,0xd3,0xbc,0x11, +0x1b,0xbc,0x87,0x4a,0xdc,0x97,0xc6,0xaa,0x37,0xbd,0x46,0xf4,0x65,0x55,0xff,0xc8, +0x1b,0x7d,0x88,0x3e,0xa1,0xd2,0x85,0xe9,0xaa,0xaf,0xea,0x99,0xdc,0x53,0x32,0xe9, +0x6a,0x1e,0x0a,0xab,0x5e,0xf5,0x64,0xf8,0x52,0x63,0xf7,0xac,0x8f,0x80,0x27,0x6f, +0xea,0xbd,0xe6,0x76,0x8f,0xb9,0xdd,0x57,0x6e,0xf7,0x93,0xc7,0xef,0x23,0x8f,0xdf, +0x43,0x6e,0xf7,0x8b,0xdb,0xbd,0xe2,0x76,0x9f,0xb8,0xdd,0x1b,0x6e,0xf7,0x84,0xdb, +0xfd,0xe0,0x76,0x2f,0xb8,0xdd,0x07,0x6e,0xf7,0x80,0xdb,0xfd,0xdf,0x76,0xcf,0xb7, +0xbf,0xd7,0xdb,0xbc,0xb7,0x0e,0xdc,0xd7,0xdd,0xdd,0xdd,0xc3,0x6d,0xf7,0x6f,0x1b, +0xc7,0xb5,0xfb,0xb2,0xa7,0x55,0x73,0x3f,0xf6,0x6c,0x77,0x1f,0xb6,0xdd,0x7f,0xfd, +0x43,0xcc,0x61,0xf3,0xf7,0x54,0xff,0xd4,0xfd,0xd4,0x76,0x0f,0xb5,0xbf,0x7f,0x7a, +0x84,0xbb,0x47,0x7a,0x9a,0xbb,0x37,0xda,0x7b,0x69,0x76,0x2f,0xf4,0xda,0x18,0x6b, +0xed,0xe0,0xb8,0x6a,0xfc,0xbe,0x66,0xef,0x9c,0xd9,0x7d,0xcc,0x76,0xff,0xf2,0xb4, +0x6a,0xee,0x47,0x9e,0xed,0xee,0x43,0x4e,0xc0,0x44,0xed,0x5e,0xe3,0x8e,0x1b,0xb9, +0xc7,0xd8,0xee,0x2b,0xbe,0x92,0x7b,0x89,0xed,0xbe,0xe1,0x69,0xee,0x5e,0x61,0xbb, +0x4f,0xd8,0xdf,0x23,0x6c,0xf7,0x06,0xfb,0x7b,0x82,0x0b,0xdc,0x3d,0xc0,0x1d,0xab, +0xb9,0xf7,0xb7,0x9b,0xbb,0xdf,0xd7,0xee,0xf5,0x35,0xe6,0xe9,0xef,0xe5,0xad,0xee, +0x3e,0x5e,0xbb,0x87,0xd7,0xee,0xdf,0xb5,0x7b,0x77,0xed,0x9e,0x5d,0xbb,0x2f,0xd7, +0xee,0xc9,0xb5,0xfb,0x70,0xed,0xde,0xdb,0x8d,0xdd,0x77,0x7b,0x7e,0xec,0x3e,0xdb, +0x7c,0xf7,0xd8,0x36,0x86,0x4d,0x1e,0x0b,0x9b,0xb4,0xfb,0x65,0xed,0x5e,0x59,0xbb, +0x4f,0xd6,0xee,0x91,0x1d,0x0e,0x9b,0xb4,0x7b,0x61,0xef,0x80,0x51,0xda,0xbd,0xaa, +0xe6,0x52,0x99,0x47,0x65,0xf7,0x9b,0xda,0x7d,0xa6,0x13,0x61,0x81,0x76,0x0f,0x69, +0xfc,0xfe,0x51,0xeb,0x87,0xb3,0xfb,0x44,0x77,0x73,0xf7,0x83,0x06,0xae,0xb7,0x9d, +0xe3,0x75,0xc6,0xe9,0xfc,0x3d,0x9b,0xe5,0xee,0x1e,0x4d,0xf3,0x95,0xba,0xc4,0xee, +0xbb,0x1c,0x0e,0x87,0x1b,0x07,0x73,0x0b,0x6c,0x6d,0x2f,0x98,0x9a,0xbf,0x07,0x72, +0xa9,0xbb,0xef,0xf1,0x8b,0x18,0x3f,0xb3,0xfb,0x19,0xe7,0xc1,0x93,0xec,0x1e,0x40, +0xbb,0xd7,0xcf,0xee,0xe3,0x6b,0x04,0x27,0xb1,0xfb,0xf3,0x06,0xc0,0x22,0xec,0xfe, +0x39,0xbb,0x67,0xce,0xee,0x95,0xb3,0xfb,0xdd,0xec,0x5e,0x37,0xbb,0xcf,0x6d,0xcf, +0xd8,0xbd,0x6d,0x76,0x5f,0xdb,0x44,0x18,0x83,0xdd,0xcb,0x66,0xf7,0xaf,0xd9,0x7d, +0x6b,0x5d,0xe1,0x0b,0xde,0xbd,0xa8,0x70,0xf7,0xa0,0x35,0x84,0x19,0xd8,0xbd,0x65, +0xc6,0x0b,0x2e,0x73,0x1e,0x45,0xb9,0xbb,0x5f,0xcc,0xee,0x15,0xb3,0xfb,0xc4,0xec, +0x1e,0xb1,0x65,0xdc,0x0b,0x66,0x9c,0xe0,0x43,0x77,0xff,0x56,0x38,0xff,0xb7,0xfb, +0xb2,0xe2,0xf7,0x5a,0xd9,0x3d,0x50,0x76,0xef,0x93,0xdd,0xe3,0x94,0xef,0xde,0xa1, +0xf8,0xfd,0x42,0x76,0x7f,0x90,0xdd,0xff,0x63,0xf7,0xf9,0xd8,0xbd,0x3d,0x76,0x2f, +0x8f,0xdd,0xc7,0x63,0xf7,0xee,0xd8,0x7d,0x3b,0x09,0xb7,0xaf,0x7e,0x88,0xbb,0x3f, +0xc7,0xee,0xcd,0xb1,0x3d,0xf5,0xf2,0xd8,0x3d,0x38,0x76,0xef,0x4d,0x7d,0xce,0x5c, +0xed,0x3e,0x1b,0xbb,0xbf,0xc6,0x76,0xd2,0x27,0x70,0x2f,0xcd,0xcb,0xb1,0x73,0xd7, +0x26,0xb1,0x7b,0x63,0xec,0xbe,0x98,0x85,0x9c,0x9f,0x26,0x38,0x3b,0xb5,0xfb,0x5a, +0x3a,0xe6,0xb9,0x97,0xc5,0xee,0x63,0xc9,0x77,0x0f,0xcb,0xa4,0x4d,0xb8,0x57,0x65, +0x9e,0xbb,0x37,0xc5,0xee,0x4b,0x69,0xcd,0xb9,0xa8,0xdd,0x77,0x52,0xce,0xb9,0xe7, +0x63,0xee,0xfe,0x91,0x0a,0x77,0xbf,0x48,0x29,0xe7,0x9a,0x8f,0x70,0x66,0xb9,0x0b, +0xe7,0x91,0x4d,0x38,0x83,0xac,0xee,0xbe,0x8c,0x8e,0xee,0x5e,0x0c,0x3b,0x77,0x7c, +0xcd,0xdd,0x73,0xb1,0xc8,0xdd,0x63,0x61,0xf7,0x57,0xf8,0xfd,0x6b,0x7f,0x4f,0x45, +0x4f,0xce,0x16,0xaf,0xe3,0x4c,0xb1,0x2f,0xe7,0x86,0xcd,0xdd,0x7d,0x10,0x9d,0x62, +0xf7,0x3c,0x84,0x73,0xc1,0x8d,0xdd,0xd3,0x60,0xf7,0x33,0x54,0x77,0xff,0xc2,0x9f, +0xdc,0xbd,0x09,0x6b,0x62,0xf7,0x23,0xd8,0xbd,0x08,0xad,0xdc,0xfd,0x07,0x07,0xba, +0xfb,0x0d,0xec,0x7e,0x02,0xbb,0x97,0xa0,0x1e,0xe7,0x78,0x76,0x6f,0x80,0xdd,0x17, +0x60,0x7d,0xfe,0xf1,0x1e,0xff,0x78,0x5f,0xbf,0xf5,0xe1,0xff,0x54,0x0f,0xfe,0x2f, +0xda,0x7f,0xbf,0xb9,0x3d,0xf0,0x9b,0xd8,0xeb,0x6e,0x7d,0xee,0xd6,0xe3,0x6e,0x3d, +0xed,0xd6,0xcf,0x6e,0x3d,0xec,0xd6,0xbb,0x6e,0xbd,0xea,0xd6,0xa7,0x6e,0x3d,0xea, +0xd6,0x9f,0x6e,0x3d,0xe8,0xd6,0x7f,0x6e,0xbd,0xdc,0x61,0x97,0x32,0xc1,0x9c,0x79, +0x8b,0x9b,0x2d,0x9f,0x63,0xa6,0x0c,0xf3,0xe4,0xce,0x99,0xa8,0x8f,0x7a,0x0f,0x65, +0x1f,0xa5,0xbe,0xd2,0x40,0x69,0xa8,0x34,0x52,0x9a,0x2b,0x2d,0x5d,0x4f,0xf5,0xa1, +0xca,0x61,0xcc,0xa0,0xe7,0xb9,0x9e,0x86,0x0b,0x94,0x8b,0x95,0x6b,0x95,0x3b,0x94, +0x0a,0x65,0x86,0x32,0x53,0x99,0xa5,0xcc,0x56,0xe6,0x28,0x73,0x95,0x79,0xca,0x7c, +0xf6,0x17,0xdf,0x64,0x6e,0xfd,0x5f,0xd7,0xe7,0xb0,0x96,0x5e,0xeb,0xda,0x6e,0x67, +0x31,0x74,0x3a,0xd4,0x55,0x76,0x54,0xea,0x29,0xbb,0x2a,0x0d,0x94,0x86,0x4a,0x23, +0xa5,0xb1,0xd2,0x44,0x69,0xca,0x7e,0xa3,0xf5,0x3f,0xfc,0x46,0xe9,0xa5,0xfc,0x56, +0x39,0x5b,0x39,0x57,0x39,0x5f,0x19,0xa4,0x0c,0x56,0x2e,0x50,0x2e,0x56,0x2e,0x65, +0x2e,0x7e,0x85,0xb9,0x78,0xad,0x9b,0x89,0x77,0x62,0x16,0x6e,0x48,0x17,0x44,0x67, +0xe5,0x10,0xe5,0x50,0xe5,0x30,0xe5,0x70,0xe5,0x68,0xe5,0x18,0xe5,0x58,0xe6,0xe4, +0xd0,0x13,0xd1,0x4f,0x39,0x43,0x39,0x53,0x39,0x8b,0xde,0x88,0x11,0xca,0xd5,0x74, +0x68,0xdf,0xc4,0xae,0xa4,0xf5,0x48,0x3c,0xac,0x8c,0x57,0x1e,0x53,0x1e,0x57,0x26, +0x28,0x93,0x95,0xa7,0x99,0xb5,0xc3,0x9c,0x6d,0x33,0x76,0x67,0xf6,0x25,0x7b,0x32, +0x5f,0x5f,0xc9,0x4c,0x3d,0x83,0x19,0x7a,0x89,0x9b,0x99,0x3b,0x54,0xd3,0xe9,0x30, +0xd0,0xcd,0xc4,0x53,0x5d,0x3f,0x83,0xcd,0xbf,0xd6,0xc1,0xd0,0x81,0x1d,0xc2,0xce, +0x6e,0xc6,0xed,0xc7,0x5c,0x5b,0xc1,0x1c,0xeb,0xe7,0xd7,0x8e,0xb1,0x6e,0x83,0x7e, +0xcc,0xa9,0x61,0x3e,0x9d,0xce,0x6c,0x3a,0x8b,0x59,0x34,0xc1,0xec,0xd9,0x99,0x39, +0xb3,0x1f,0xb3,0xe5,0x2b,0xae,0x53,0xc0,0xe6,0xc6,0xae,0x6e,0x56,0x7c,0x89,0x19, +0xb1,0xb5,0x9b,0x0b,0xcf,0xc7,0xf1,0xbf,0xda,0xb9,0xfd,0x61,0xf6,0x6b,0x8a,0xc7, +0xbf,0x3f,0xfe,0xfe,0xf1,0xcc,0x7f,0xe7,0x33,0xe7,0x8d,0x64,0xd6,0xb3,0xf9,0x6e, +0x2b,0xe6,0xba,0x23,0x99,0xe7,0x26,0xe2,0xc1,0xbf,0x80,0xff,0x1e,0xe6,0xb9,0x1a, +0xdb,0x47,0xfb,0x5c,0x25,0xcc,0x73,0xbb,0x55,0xe3,0xb8,0xef,0x86,0xd7,0xde,0x02, +0x97,0xdd,0x66,0xba,0x63,0x9d,0x9b,0xde,0x0f,0x27,0x7d,0xb0,0x9b,0xeb,0x12,0xcc, +0x73,0x6d,0xb8,0xeb,0xfc,0x40,0xe6,0xba,0x61,0x38,0xe7,0x0f,0xe1,0x9a,0x7f,0x8c, +0x63,0xbe,0x1c,0xb7,0xbc,0x09,0x3e,0xf9,0x3c,0xe6,0xba,0x25,0x6e,0xa6,0xfb,0x86, +0x59,0xae,0xc4,0xed,0x27,0x35,0xc2,0xc3,0xee,0x8f,0x4b,0xbd,0xa2,0x49,0xd5,0x4c, +0xd7,0x88,0x59,0xce,0xee,0x10,0xbe,0x9b,0xd9,0x2d,0xe5,0xe6,0xb5,0xbd,0xdd,0xdd, +0xba,0x83,0x70,0x64,0x17,0xb9,0xb9,0xac,0x2b,0xf3,0xd8,0x04,0x1c,0xd8,0xa9,0x6e, +0x16,0xdb,0x17,0xc7,0xd5,0x66,0xb1,0xcb,0xdd,0xfc,0xf5,0x57,0xe6,0xae,0x19,0x38, +0xab,0x61,0xce,0xfa,0x88,0x3d,0x0b,0x9b,0xb1,0x12,0xcc,0x56,0x61,0x67,0x21,0x78, +0x97,0x36,0x5b,0x5d,0x58,0xb0,0xa1,0x77,0x68,0xae,0x61,0xf0,0x0b,0x9f,0x77,0xdd, +0x84,0xb3,0x95,0x39,0xca,0x02,0xe5,0x2d,0xe5,0x6d,0xe5,0x7d,0xe5,0x03,0x65,0xb1, +0xbb,0xb3,0x31,0xf8,0x88,0x2b,0x8a,0xa3,0xbe,0xc2,0x2b,0x95,0xe1,0xca,0x08,0xe5, +0x6a,0x65,0x94,0x72,0x9d,0x72,0x83,0x72,0xa3,0x72,0x93,0x32,0x1a,0x1e,0x1f,0x5c, +0xc5,0x71,0x25,0x91,0x9f,0x98,0x54,0xf6,0x70,0xf7,0x37,0x9e,0xc5,0xdc,0x16,0x1c, +0xc4,0x99,0x74,0x12,0xbe,0xea,0x1c,0xc4,0xe0,0x1f,0xb6,0x54,0x5a,0x39,0x0f,0xf1, +0x68,0x5c,0xc4,0x21,0xca,0x85,0xcc,0x75,0xc1,0x47,0x7c,0x42,0x99,0xa8,0x4c,0x52, +0x26,0x2b,0x53,0x94,0x67,0x94,0x69,0xca,0x0c,0xe5,0x59,0xfa,0x0b,0x5f,0x56,0x5e, +0x81,0xd1,0x27,0x99,0x03,0x6d,0xfe,0xbb,0x02,0x3f,0x71,0xb2,0x9b,0xf9,0xea,0xe3, +0x20,0xda,0x8c,0xf7,0x14,0xb3,0x5d,0x98,0xe9,0x9a,0xc3,0xcd,0xdb,0xb8,0x99,0x6e, +0x21,0xbe,0x60,0x82,0x59,0xae,0xcc,0x39,0x7f,0x53,0xe0,0xd5,0xf3,0xdc,0xec,0xb5, +0x1f,0xde,0x9e,0xcd,0x5e,0x13,0xe0,0xcf,0xd3,0xf1,0xf2,0x9e,0xc0,0xc3,0x9b,0xce, +0xec,0xd5,0x12,0xae,0xdc,0x89,0xd9,0x6b,0x1c,0x6e,0x9d,0xcd,0x60,0xbb,0xe2,0xcf, +0x05,0x77,0xae,0xb9,0xf9,0x72,0xcc,0x5e,0x07,0x39,0xef,0x6d,0x11,0x33,0x56,0x4b, +0x66,0x2b,0x9b,0xa9,0x7a,0x31,0x53,0xfd,0x37,0x33,0x55,0x3f,0x98,0x6c,0x69,0x6c, +0xa6,0x7a,0x18,0x1f,0xed,0xc9,0x9d,0x7f,0xec,0x9f,0x75,0x65,0x6e,0xba,0xd5,0xcd, +0x4c,0x6b,0x98,0x95,0xda,0xc0,0x46,0x6d,0x36,0x2a,0x65,0x26,0xaa,0x87,0xf7,0xb5, +0x92,0x59,0xa8,0x3b,0xb3,0xcf,0xdf,0x99,0x75,0xc6,0x4c,0xad,0x72,0xa4,0xea,0xe3, +0x44,0x0d,0x66,0x9e,0x79,0x98,0x39,0xa6,0x37,0x73,0x4a,0x7b,0x37,0x9b,0xac,0xf7, +0x83,0xaa,0xf1,0x81,0x6c,0xee,0xb0,0x79,0xe3,0x33,0xe6,0x8c,0x0f,0xdd,0x6c,0x61, +0x33,0x85,0x79,0x3a,0xde,0x15,0x09,0x33,0x45,0x38,0xbb,0x0a,0xe7,0x56,0x76,0x66, +0xf5,0x2c,0xe7,0x54,0xe1,0x8c,0x6a,0x47,0x37,0x53,0xec,0x5d,0xcd,0x4c,0xd1,0x4c, +0x69,0xe1,0xee,0xbf,0xe8,0xca,0x4c,0x61,0x9e,0x83,0xb9,0x0d,0x83,0x95,0x8b,0x94, +0x6b,0x94,0xdb,0x95,0xe9,0xcc,0x14,0xcf,0x2a,0xaf,0x56,0x33,0x53,0xbc,0xe6,0xee, +0xcc,0x78,0x8f,0x73,0xb0,0xa5,0xce,0x81,0xf8,0xae,0x9a,0x99,0x62,0x1b,0x65,0x07, +0x65,0x17,0x66,0x8a,0xfa,0x79,0x66,0x8a,0x66,0xce,0x99,0x08,0x33,0xc5,0xf1,0x4a, +0x6f,0xa5,0xbf,0x72,0x8e,0x32,0xd0,0xcd,0x14,0x43,0x94,0x8b,0x94,0x4b,0x94,0x2b, +0x38,0x67,0x33,0xb7,0xc2,0x66,0x8a,0x1d,0x38,0x5f,0xab,0xcf,0xb9,0x5a,0x98,0x29, +0x0e,0x56,0xba,0xba,0x99,0xe2,0x28,0x37,0x53,0x98,0x5f,0x11,0x66,0x8a,0xd3,0xdc, +0x4c,0x11,0x5c,0x8b,0xe1,0xca,0x48,0x66,0x8a,0x1b,0xdd,0x4c,0x11,0xce,0xe7,0xc6, +0x2a,0x8f,0x32,0x53,0x94,0x2b,0x4f,0x28,0x93,0x98,0x29,0x5e,0xe2,0xec,0x2e,0xe5, +0xce,0xed,0x0e,0x65,0xa6,0x38,0xce,0x9d,0xd7,0x4d,0xe5,0x8c,0x6e,0xb6,0x3b,0x8b, +0x4b,0x31,0x53,0xc4,0x3d,0x08,0x3b,0x6b,0x1b,0xce,0x4c,0x61,0x4e,0xc3,0x6c,0xce, +0xd3,0x2a,0x63,0x33,0x45,0x17,0xe7,0x22,0x9c,0xf2,0x13,0x33,0x45,0x59,0xcc,0x07, +0x38,0xa5,0x9a,0x99,0x62,0x36,0x67,0x5b,0x49,0xce,0xb2,0xba,0x30,0x53,0x9c,0xe2, +0x66,0x8a,0xd7,0xdd,0x4c,0xd1,0xce,0x9d,0x41,0x4d,0xe5,0xdc,0x69,0x87,0xd8,0x4c, +0x31,0x94,0xf3,0xa5,0x6b,0xdc,0x3e,0x7c,0x98,0x29,0x4a,0xd9,0x7d,0x6f,0xc7,0xb9, +0x52,0x2f,0xce,0x93,0xec,0xec,0xe8,0x6a,0x37,0x53,0x84,0xf3,0xa2,0x6d,0xd8,0x29, +0x3f,0x8a,0xf3,0xa1,0x27,0xd9,0x1d,0x7f,0xc1,0x9d,0x13,0xd9,0x4c,0x61,0xe7,0x44, +0x17,0x57,0xb3,0x17,0xbe,0x07,0xbb,0xe0,0x2d,0x38,0x27,0xda,0xde,0xcd,0x14,0x27, +0xb9,0x99,0xe2,0x1c,0x77,0x5e,0x64,0x7b,0xdb,0xad,0xe8,0xb2,0xb1,0x99,0x62,0x30, +0xbb,0xda,0xf7,0xb3,0xa3,0x6d,0xe7,0x44,0x9f,0x30,0x53,0x84,0x7d,0xec,0x96,0x9c, +0x17,0xcd,0x67,0xdf,0x7a,0xa9,0x9b,0x29,0xc2,0xf9,0x50,0xa5,0x9b,0x29,0x6a,0xb3, +0xd3,0x7c,0x2a,0xbb,0xca,0xe1,0xbc,0xc8,0xce,0x8a,0xc2,0x19,0x51,0x53,0xce,0x86, +0x06,0x71,0x26,0x74,0x8f,0x3b,0x0b,0xb2,0x99,0x62,0x1f,0x66,0x8a,0xf3,0x99,0x29, +0x9e,0x77,0xe7,0x3d,0x4d,0xd9,0x23,0x1d,0xce,0x4c,0x31,0x99,0x9d,0xd1,0x30,0x53, +0x34,0x63,0x37,0xb4,0x4d,0x35,0x33,0xc5,0x44,0xce,0x72,0xec,0x1c,0x67,0x79,0x9e, +0x99,0xa2,0x36,0x67,0x35,0x61,0xa6,0x58,0xe7,0x66,0x8a,0x70,0x4e,0xe3,0x77,0xf5, +0xec,0x5c,0xe6,0x39,0x37,0x53,0xbc,0xc2,0x4c,0x31,0x5f,0x79,0x93,0x99,0xe2,0x3d, +0x66,0x8a,0x45,0x6e,0xa6,0x08,0x67,0x38,0x9f,0x57,0x33,0x53,0x8c,0x54,0xae,0x65, +0xa6,0xb8,0xde,0xcd,0x14,0x37,0xbb,0x99,0xe2,0x51,0x65,0x3c,0x33,0xc5,0xee,0x6e, +0xa6,0xa8,0xcf,0x59,0xd0,0xa3,0xae,0xef,0xf8,0x45,0xce,0x83,0x6c,0x6f,0xaf,0x05, +0x33,0x45,0x17,0xce,0x85,0x8e,0x62,0xa6,0x18,0xac,0x5c,0xe0,0xf6,0xf8,0xc2,0x4c, +0x31,0x41,0x79,0x8a,0x99,0xe2,0x69,0x65,0x2a,0x33,0xc5,0x74,0x66,0x8a,0x99,0x79, +0x66,0x0a,0x3b,0x57,0x1a,0xc2,0x5e,0xdf,0x53,0xee,0x2c,0x29,0xc5,0xee,0x5e,0x2b, +0x66,0x8a,0x2b,0xd9,0xd3,0x9b,0xc5,0x4c,0xb1,0x2f,0x33,0x45,0xdb,0xd8,0x4c,0xf1, +0x29,0xfb,0x75,0x1d,0x98,0x29,0x6c,0x4f,0xae,0x22,0x36,0x53,0x84,0xb3,0x9c,0x4e, +0xec,0xba,0xd9,0x4c,0x31,0x89,0x99,0xa2,0x82,0x33,0x9d,0x27,0xd9,0x5d,0xab,0xe0, +0x2c,0xa7,0x1d,0x33,0x45,0x99,0x9b,0x29,0x9e,0x8c,0xcd,0x14,0x7b,0x73,0xbe,0xd3, +0x96,0xf3,0x9d,0x0e,0x6e,0xa6,0xb0,0x5d,0xb1,0x30,0x53,0x14,0xb3,0x13,0x66,0x67, +0x35,0xc7,0x72,0x4e,0x73,0x9b,0x3b,0xa7,0x39,0x95,0x99,0xc2,0x76,0xba,0x3a,0x71, +0x46,0x53,0xce,0x0e,0x57,0x38,0xa7,0x89,0xef,0x6c,0x75,0xe5,0x1c,0xc6,0xcf,0x14, +0x5f,0xb0,0x7b,0xd5,0x2e,0x36,0x53,0x94,0x71,0xc6,0xd2,0x90,0x33,0x96,0x70,0xbe, +0x62,0x67,0x2b,0x76,0x96,0x72,0x37,0x7b,0x47,0xb6,0x57,0xd4,0x80,0xf3,0x92,0xe1, +0x9c,0x8f,0x84,0xb3,0x91,0x2e,0x9c,0x85,0xb4,0x71,0x67,0x1e,0x57,0xb9,0x9d,0x9a, +0xea,0x76,0x68,0xc2,0x4c,0x61,0xe7,0x18,0xe1,0xfc,0x22,0x9c,0x5d,0xac,0x70,0x33, +0x85,0x9d,0x55,0xd8,0x6e,0xcb,0x11,0xcc,0x14,0xb6,0x5f,0x51,0xb8,0xfe,0x21,0x05, +0xf3,0x4d,0x25,0x95,0xc2,0x54,0x61,0x3a,0x9d,0x72,0x8f,0xe9,0xf0,0x2c,0xe9,0x94, +0x9e,0x5c,0xe8,0x9f,0x5c,0xe8,0x9f,0x49,0x7f,0x28,0x59,0x18,0x3d,0x9f,0xfd,0x76, +0x2a,0xf7,0x67,0x93,0xa9,0xdc,0xef,0xf2,0x37,0x16,0xfe,0xf3,0x1f,0x52,0x7a,0x3d, +0x52,0xb9,0xc7,0x4d,0x7a,0x48,0x56,0xf7,0x57,0x14,0x6c,0xea,0xcb,0x4a,0xa7,0xd3, +0x05,0xe9,0x54,0x41,0xf4,0x5e,0x4a,0x6d,0xf8,0x5e,0xcb,0x3d,0x99,0xf7,0x5c,0x41, +0x61,0xf4,0x5e,0xc8,0xfd,0xc8,0x73,0xe4,0x7e,0x28,0x28,0xfc,0xf5,0x3c,0xe4,0xde, +0x63,0xff,0x07, }; } // namespace ada::idna::table_blob #endif @@ -4716,6 +4899,8 @@ inline void convert_table_blob_to_host_endian(uint8_t* buffer) noexcept { u32(table_blob::off_dir_start, table_blob::count_dir_start); u32(table_blob::off_dir_final, table_blob::count_dir_final); u32(table_blob::off_combining_flat, table_blob::count_combining_flat); + u32(table_blob::off_joining_start, table_blob::count_joining_start); + u32(table_blob::off_joining_final, table_blob::count_joining_final); } } // namespace detail @@ -4735,6 +4920,10 @@ static_assert(table_blob::count_composition_block == static_assert(table_blob::count_dir_start == table_blob::dir_table_count && table_blob::count_dir_final == table_blob::dir_table_count && table_blob::count_dir_value == table_blob::dir_table_count); +static_assert( + table_blob::count_joining_start == table_blob::joining_table_count && + table_blob::count_joining_final == table_blob::joining_table_count && + table_blob::count_joining_value == table_blob::joining_table_count); static_assert(table_blob::count_id_continue_flat == table_blob::id_continue_count * 2); static_assert(table_blob::count_id_start_flat == @@ -4753,6 +4942,8 @@ static_assert(table_blob::off_id_start_flat % alignof(uint32_t) == 0); static_assert(table_blob::off_dir_start % alignof(uint32_t) == 0); static_assert(table_blob::off_dir_final % alignof(uint32_t) == 0); static_assert(table_blob::off_combining_flat % alignof(uint32_t) == 0); +static_assert(table_blob::off_joining_start % alignof(uint32_t) == 0); +static_assert(table_blob::off_joining_final % alignof(uint32_t) == 0); static_assert(table_blob::compressed_size == sizeof(table_blob::compressed)); // Every section must lie entirely inside the uncompressed buffer. @@ -4795,6 +4986,12 @@ ADA_IDNA_SECTION_IN_BOUNDS(table_blob::off_dir_value, table_blob::count_dir_value, 1); ADA_IDNA_SECTION_IN_BOUNDS(table_blob::off_combining_flat, table_blob::count_combining_flat, 4); +ADA_IDNA_SECTION_IN_BOUNDS(table_blob::off_joining_start, + table_blob::count_joining_start, 4); +ADA_IDNA_SECTION_IN_BOUNDS(table_blob::off_joining_final, + table_blob::count_joining_final, 4); +ADA_IDNA_SECTION_IN_BOUNDS(table_blob::off_joining_value, + table_blob::count_joining_value, 1); #undef ADA_IDNA_SECTION_IN_BOUNDS // --- Mapping ----------------------------------------------------------------- @@ -4826,10 +5023,14 @@ inline const uint32_t* dir_start = nullptr; inline const uint32_t* dir_final = nullptr; inline const uint8_t* dir_value = nullptr; inline range_pair_ptr combining_ranges = nullptr; +inline const uint32_t* joining_start = nullptr; +inline const uint32_t* joining_final = nullptr; +inline const uint8_t* joining_value = nullptr; inline constexpr size_t id_continue_count = table_blob::id_continue_count; inline constexpr size_t id_start_count = table_blob::id_start_count; inline constexpr size_t dir_table_count = table_blob::dir_table_count; +inline constexpr size_t joining_table_count = table_blob::joining_table_count; inline constexpr size_t combining_range_count = table_blob::combining_range_count; inline constexpr size_t idna_utf8_mappings_size = @@ -4897,8 +5098,12 @@ inline constexpr uint64_t kTablesSpinLimit = 1'000'000'000ull; std::memory_order_acquire)) { uint8_t* buffer = new (std::nothrow) uint8_t[table_blob::uncompressed_size]; if (buffer == nullptr) { - tables_init_state.store(kTablesFailed, std::memory_order_release); + // Leave the state uninitialized so a later call can retry. A corrupt + // blob (below) is permanent; running out of memory may not be. + // LCOV_EXCL_START + tables_init_state.store(kTablesUninit, std::memory_order_release); return false; + // LCOV_EXCL_STOP } const size_t n = deflate::inflate_raw(table_blob::compressed, @@ -4953,6 +5158,11 @@ inline constexpr uint64_t kTablesSpinLimit = 1'000'000'000ull; dir_value = at(table_blob::off_dir_value); combining_ranges = reinterpret_cast<range_pair_ptr>(at(table_blob::off_combining_flat)); + joining_start = + reinterpret_cast<const uint32_t*>(at(table_blob::off_joining_start)); + joining_final = + reinterpret_cast<const uint32_t*>(at(table_blob::off_joining_final)); + joining_value = at(table_blob::off_joining_value); tables_buffer = buffer; tables_init_state.store(kTablesReady, std::memory_order_release); @@ -4965,9 +5175,15 @@ inline constexpr uint64_t kTablesSpinLimit = 1'000'000'000ull; if (state == kTablesReady) { return true; } - if (state == kTablesFailed) { + // Failed is permanent. Uninit means the peer gave up after a failed + // allocation: do not spin, the next call can take the init slot. One + // comparison, same shape as the old Failed check, so this wait loop does + // not grow the unity translation unit. + // LCOV_EXCL_START + if (state != kTablesInProgress) { return false; } + // LCOV_EXCL_STOP #if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \ defined(_M_IX86) #if defined(__GNUC__) || defined(__clang__) @@ -5010,14 +5226,16 @@ inline const uint16_t* composition_block_row(uint8_t bi) noexcept { } // namespace ada::idna /* end file src/table_store.hpp */ /* begin file src/mapping_tables.cpp */ -// IDNA 17.0.0 -// Two-level compressed mapping table. -// All constants are derived from the table data; no hardcoded boundaries. -// Total binary size: 48659 bytes (47.5 KB) -// stage1: 6564 bytes (3282 uint16_t entries) -// stage2: 22912 bytes (179 mixed blocks x 64) +// IDNA 18.0.0 +// Two-level compressed mapping table (constants only). +// Array payloads are stored in the DEFLATE blob (see table_store.hpp / +// scripts/pack_tables.py). +// Regenerate with: python3 scripts/idna_table.py --write +// Logical table size: 51037 bytes (49.8 KB) +// stage1: 8162 bytes (4081 uint16_t entries) +// stage2: 23424 bytes (183 mixed blocks x 64) // bool_blocks: 1800 bytes (225 uint64_t words) -// utf8 maps: 17383 bytes +// utf8 maps: 17651 bytes // clang-format off #ifndef ADA_IDNA_MAPPING_TABLE_H @@ -5042,7 +5260,7 @@ constexpr uint16_t IDNA_BOOL_FLAG = 0x8000; // Two-level table covers code points [0, IDNA_LOW_RANGE_END). // Derived from the highest non-disallowed code point below the high-ignored range, // rounded up to the next 64-code-point block boundary. -constexpr uint32_t IDNA_LOW_RANGE_END = 0x00033480; +constexpr uint32_t IDNA_LOW_RANGE_END = 0x0003FC40; // Variation selectors supplement: U+E0100..U+E01EF are all ignored. // These are handled with a simple range check; everything else above @@ -5050,9 +5268,7 @@ constexpr uint32_t IDNA_LOW_RANGE_END = 0x00033480; constexpr uint32_t IDNA_HIGH_IGNORED_START = 0x000E0100; constexpr uint32_t IDNA_HIGH_IGNORED_END = 0x000E01F0; // exclusive -// idna_stage1[cp >> 6]: one entry per 64-code-point block. -// Bit 15 set -> lower 15 bits = index into idna_bool_blocks[]. -// Bit 15 clear -> value = base offset into idna_stage2[] for this block. +// Large arrays (idna_stage1/stage2/bool_blocks/utf8_mappings) live in table_blob. } // namespace ada::idna #endif // ADA_IDNA_MAPPING_TABLE_H @@ -5235,6 +5451,7 @@ namespace ada::idna { /* begin file src/normalization_tables.cpp */ // Normalization table helpers. // Array payloads live in the DEFLATE blob (table_store.hpp). +// Regenerate with: python3 scripts/unicode_data_table.py --write // clang-format off #ifndef ADA_IDNA_NORMALIZATION_TABLES_H #define ADA_IDNA_NORMALIZATION_TABLES_H @@ -5400,6 +5617,28 @@ void decompose_nfc(std::u32string& input) { sort_marks(input); } +// Returns true if the composition row of a starter has a pair with `second`. +static bool has_composition(const uint16_t* composition, + char32_t second) noexcept { + int left = composition[0]; + int right = composition[1]; + if (left < 0 || right <= left || + static_cast<size_t>(right) > composition_data_size) { + return false; + } + while (left + 2 < right) { + int middle = left + (((right - left) >> 1) & ~1); + if (composition_data[static_cast<size_t>(middle)] <= second) { + left = middle; + } + if (composition_data[static_cast<size_t>(middle)] >= second) { + right = middle; + } + } + return static_cast<size_t>(left + 1) < composition_data_size && + composition_data[static_cast<size_t>(left)] == second; +} + // Returns true if a composition step would change the string. static bool would_compose(std::u32string_view input) noexcept { for (size_t input_count = 0; input_count < input.size();) { @@ -5414,7 +5653,7 @@ static bool would_compose(std::u32string_view input) noexcept { continue; } if (current >= hangul_sbase && current < hangul_sbase + hangul_scount) { - if ((current - hangul_sbase) % hangul_tcount && + if ((current - hangul_sbase) % hangul_tcount == 0 && input_count + 1 < input.size() && input[input_count + 1] > hangul_tbase && input[input_count + 1] < hangul_tbase + hangul_tcount) { @@ -5431,26 +5670,9 @@ static bool would_compose(std::u32string_view input) noexcept { size_t j = input_count; for (; j + 1 < input.size(); ++j) { uint8_t ccc = get_ccc(input[j + 1]); - if (composition[1] != composition[0] && previous_ccc < ccc) { - int left = composition[0]; - int right = composition[1]; - if (left < 0 || right < left || - static_cast<size_t>(right) > composition_data_size) { - break; - } - while (left + 2 < right) { - int middle = left + (((right - left) >> 1) & ~1); - if (composition_data[static_cast<size_t>(middle)] <= input[j + 1]) { - left = middle; - } - if (composition_data[static_cast<size_t>(middle)] >= input[j + 1]) { - right = middle; - } - } - if (static_cast<size_t>(left + 1) < composition_data_size && - composition_data[static_cast<size_t>(left)] == input[j + 1]) { - return true; - } + if (composition[1] != composition[0] && previous_ccc < ccc && + has_composition(composition, input[j + 1])) { + return true; } if (ccc == 0) { break; @@ -5465,6 +5687,69 @@ static bool would_compose(std::u32string_view input) noexcept { return false; } +// Trailing canonical combining class of a character: the combining class of the +// last code point of its canonical decomposition, or the character's own class +// when it has none. A precomposed starter such as U+00E1 (a + U+0301, class +// 230) has class 0 but a nonzero trailing class, so a following mark of lower +// class reorders past the hidden mark during normalization. +static uint8_t trailing_ccc(char32_t c) noexcept { + const size_t length = canonical_decomp_length(c); + if (length == 0) { + return get_ccc(c); + } + const uint16_t* const decomposition = + decomposition_block_row(decomposition_index[c >> 8]) + (c % 256); + const size_t base = decomposition[0] >> 2; + return get_ccc(decomposition_data[base + length - 1]); +} + +void compose(std::u32string& input); + +// A character that has a canonical decomposition is in NFC form only if that +// decomposition composes back to exactly it. Singletons never do (e.g. U+212B +// ANGSTROM SIGN). Composition exclusions do not either: their decomposition +// composes to a different primary composite (e.g. U+1F71 -> U+03B1 U+0301 -> +// U+03AC) or does not compose at all (e.g. U+0958 DEVANAGARI LETTER QA -> +// U+0915 U+093C), and non-starter decompositions such as U+0344 -> U+0308 +// U+0301 stay decomposed. All are NFC_Quick_Check=No and must be normalized. +// Since Unicode 16 the first code point of a decomposition can also compose +// with the preceding character: U+16121 is U+1611E U+1611E, so U+1611E U+16121 +// normalizes to U+16121 U+1611E. +static bool decomposition_is_not_nfc(char32_t previous, char32_t c) noexcept { + if (c >= hangul_sbase && c < hangul_sbase + hangul_scount) { + return false; + } + if (c >= 0x110000) { + return false; + } + const uint16_t* const decomposition = + decomposition_block_row(decomposition_index[c >> 8]) + (c % 256); + const size_t length = (decomposition[1] >> 2) - (decomposition[0] >> 2); + if (length == 0 || (decomposition[0] & 1)) { + return false; // no canonical decomposition (or compatibility-only) + } + if (length == 1) { + return true; // singleton + } + const size_t base = decomposition[0] >> 2; + if (base + length > decomposition_data_size) { + return false; + } + // Recompose the canonical decomposition; if it does not collapse back to c, + // then c is an exclusion / non-starter decomposition and is not NFC. + std::u32string decomposed(decomposition_data + base, + decomposition_data + base + length); + compose(decomposed); + if (!(decomposed.size() == 1 && decomposed[0] == c)) { + return true; + } + return previous < 0x110000 && + has_composition( + composition_block_row(composition_index[previous >> 8]) + + (previous % 256), + decomposition_data[base]); +} + bool is_already_nfc(std::u32string_view input) noexcept { if (input.empty()) { return true; @@ -5472,21 +5757,28 @@ bool is_already_nfc(std::u32string_view input) noexcept { if (!tables_are_ready() && !ensure_tables()) { return false; } - // 1) Singleton decompositions are never NFC (e.g. U+212B ANGSTROM SIGN). - // Multi-code-point decomps are primary composites that are NFC as-is. + // 1) A character whose canonical decomposition does not compose back to it is + // not NFC: singletons (e.g. U+212B), composition exclusions (e.g. U+0958) + // and non-starter decompositions (e.g. U+0344), or one whose + // decomposition starts with a code point that composes with the previous + // character (e.g. U+1611E U+16121). + char32_t previous = 0x110000; // none for (char32_t c : input) { - if (canonical_decomp_length(c) == 1) { + if (decomposition_is_not_nfc(previous, c)) { return false; } + previous = c; } - // 2) Combining marks already in canonical order. + // 2) Combining marks already in canonical order. prev_ccc carries the + // trailing class of the previous character's canonical decomposition so a + // composite starter followed by a lower-class mark is caught. uint8_t prev_ccc = 0; for (char32_t c : input) { uint8_t ccc = get_ccc(c); if (ccc != 0 && prev_ccc > ccc) { return false; } - prev_ccc = ccc; + prev_ccc = trailing_ccc(c); } // 3) No pairwise composition would apply (including Hangul L+V / LV+T). return !would_compose(input); @@ -5520,7 +5812,7 @@ void compose(std::u32string& input) { } } else if (input[input_count] >= hangul_sbase && input[input_count] < hangul_sbase + hangul_scount) { - if ((input[input_count] - hangul_sbase) % hangul_tcount && + if ((input[input_count] - hangul_sbase) % hangul_tcount == 0 && input_count + 1 < input.size() && input[input_count + 1] > hangul_tbase && input[input_count + 1] < hangul_tbase + hangul_tcount) { @@ -5661,8 +5953,13 @@ bool punycode_to_utf32(std::string_view input, std::u32string &out) { int32_t i = 0; int32_t bias = initial_bias; // grab ascii content + // RFC 3492 section 6.2: copy the code points before the last delimiter, + // then consume the delimiter only "if more than zero code points were + // consumed". With a leading delimiter, b == 0, decoding starts at the + // delimiter itself, which is not a digit, and fails. This matches the + // reference implementation in appendix C (`in = b > 0 ? b + 1 : 0`). size_t end_of_ascii = input.find_last_of('-'); - if (end_of_ascii != std::string_view::npos) { + if (end_of_ascii != std::string_view::npos && end_of_ascii > 0) { for (uint8_t c : input.substr(0, end_of_ascii)) { if (c >= 0x80) { return false; @@ -5869,6 +6166,8 @@ bool utf32_to_punycode(std::u32string_view input, std::string &out) { namespace ada::idna { +// Values stored in dir_value; keep in sync with BIDI_CLASSES in +// scripts/unicode_data_table.py. enum direction : uint8_t { NONE, BN, @@ -5896,28 +6195,88 @@ enum direction : uint8_t { LRE }; -// Bidi direction ranges live in the compressed blob as const SoA arrays -// (dir_start / dir_final / dir_value). See table_store.hpp layout asserts. +// Values stored in joining_value; keep in sync with JOINING_TYPES in +// scripts/unicode_data_table.py. Code points without a range are U. +enum class joining_type : uint8_t { U, C, D, L, R, T }; + +// Bidi direction and Joining_Type ranges live in the compressed blob as const +// SoA arrays (dir_* and joining_*). See table_store.hpp layout asserts. +// Regenerate with: python3 scripts/unicode_data_table.py --write + +// Defined in normalization.cpp. +uint8_t get_ccc(char32_t c) noexcept; // CheckJoiners and CheckBidi are true for URL specification. -// Assumes ensure_tables() has already been called by is_label_valid(). -inline static direction find_direction(uint32_t code_point) noexcept { - // Binary search on dir_final (sorted upper bounds). - size_t lo = 0, hi = dir_table_count; +// Returns the index of the range [start[i], last[i]] that contains code_point, +// or count if there is none. `last` must be sorted. +inline static size_t find_range(const uint32_t* start, const uint32_t* last, + size_t count, uint32_t code_point) noexcept { + size_t lo = 0, hi = count; while (lo < hi) { size_t mid = lo + (hi - lo) / 2; - if (dir_final[mid] < code_point) { + if (last[mid] < code_point) { lo = mid + 1; } else { hi = mid; } } - if (lo == dir_table_count) { - return direction::NONE; + return lo < count && code_point >= start[lo] ? lo : count; +} + +// Assumes ensure_tables() has already been called by is_label_valid(). +inline static direction find_direction(uint32_t code_point) noexcept { + size_t i = find_range(dir_start, dir_final, dir_table_count, code_point); + return i == dir_table_count ? direction::NONE + : static_cast<direction>(dir_value[i]); +} + +// Assumes ensure_tables() has already been called by is_label_valid(). +inline static joining_type find_joining_type(uint32_t code_point) noexcept { + size_t i = + find_range(joining_start, joining_final, joining_table_count, code_point); + return i == joining_table_count ? joining_type::U + : static_cast<joining_type>(joining_value[i]); +} + +// The ContextJ rules for U+200C and U+200D from RFC 5892 Appendix A. +inline static bool is_contextj_valid(std::u32string_view label) noexcept { + constexpr uint8_t virama_ccc = 9; + for (size_t i = 0; i < label.size(); i++) { + if (label[i] != 0x200C && label[i] != 0x200D) { + continue; + } + // If Canonical_Combining_Class(Before(cp)) .eq. Virama Then True; + if (i > 0 && get_ccc(label[i - 1]) == virama_ccc) { + continue; + } + if (label[i] == 0x200D) { + return false; + } + // If RegExpMatch((Joining_Type:{L,D})(Joining_Type:T)*\u200C + // (Joining_Type:T)*(Joining_Type:{R,D})) Then True; + joining_type before = joining_type::U; + for (size_t j = i; j > 0;) { + before = find_joining_type(label[--j]); + if (before != joining_type::T) { + break; + } + } + if (before != joining_type::L && before != joining_type::D) { + return false; + } + joining_type after = joining_type::U; + for (size_t j = i + 1; j < label.size(); j++) { + after = find_joining_type(label[j]); + if (after != joining_type::T) { + break; + } + } + if (after != joining_type::R && after != joining_type::D) { + return false; + } } - return code_point >= dir_start[lo] ? static_cast<direction>(dir_value[lo]) - : direction::NONE; + return true; } inline static size_t find_last_not_of_nsm( @@ -5929,7 +6288,9 @@ inline static size_t find_last_not_of_nsm( } // An RTL label is a label that contains at least one character of type R, AL, -// or AN. https://www.rfc-editor.org/rfc/rfc5893#section-2 +// or AN. A domain containing one is a Bidi domain name: RFC 5893 then applies +// to every label, including labels that are themselves all LTR. +// https://www.rfc-editor.org/rfc/rfc5893#section-2 inline static bool is_rtl_label(const std::u32string_view label) noexcept { const size_t mask = (1u << direction::R) | (1u << direction::AL) | (1u << direction::AN); @@ -5941,12 +6302,28 @@ inline static bool is_rtl_label(const std::u32string_view label) noexcept { return (directions & mask) != 0; } -bool is_label_valid(const std::u32string_view label) { +// Same as is_rtl_label, but loads the Bidi tables first. Visible to to_ascii +// and to_unicode, which are part of this translation unit. +inline static bool label_contains_rtl(std::u32string_view label) noexcept { + if (label.empty() || !ensure_tables() || dir_start == nullptr || + dir_final == nullptr || dir_value == nullptr) { + return false; + } + return is_rtl_label(label); +} + +// `bidi_domain` is true when the domain name contains at least one RTL label. +// CheckBidi then applies to this label even if the label itself has no R, AL, +// or AN character (RFC 5893). The one-argument is_label_valid() passes false, +// which preserves the per-label check for callers that do not know yet. +static bool check_label(const std::u32string_view label, bool bidi_domain) { if (label.empty()) { return true; } if (!ensure_tables() || combining_ranges == nullptr || dir_start == nullptr || - dir_final == nullptr || dir_value == nullptr) { + dir_final == nullptr || dir_value == nullptr || + joining_start == nullptr || joining_final == nullptr || + joining_value == nullptr) { return false; } @@ -5989,98 +6366,8 @@ bool is_label_valid(const std::u32string_view label) { // If CheckJoiners, the label must satisfy the ContextJ rules from Appendix // A, in The Unicode Code Points and Internationalized Domain Names for // Applications (IDNA) [IDNA2008]. - constexpr static uint32_t virama[] = { - 0x094D, 0x09CD, 0x0A4D, 0x0ACD, 0x0B4D, 0x0BCD, 0x0C4D, 0x0CCD, - 0x0D3B, 0x0D3C, 0x0D4D, 0x0DCA, 0x0E3A, 0x0EBA, 0x0F84, 0x1039, - 0x103A, 0x1714, 0x1734, 0x17D2, 0x1A60, 0x1B44, 0x1BAA, 0x1BAB, - 0x1BF2, 0x1BF3, 0x2D7F, 0xA806, 0xA82C, 0xA8C4, 0xA953, 0xA9C0, - 0xAAF6, 0xABED, 0x10A3F, 0x11046, 0x1107F, 0x110B9, 0x11133, 0x11134, - 0x111C0, 0x11235, 0x112EA, 0x1134D, 0x11442, 0x114C2, 0x115BF, 0x1163F, - 0x116B6, 0x1172B, 0x11839, 0x1193D, 0x1193E, 0x119E0, 0x11A34, 0x11A47, - 0x11A99, 0x11C3F, 0x11D44, 0x11D45, 0x11D97}; - constexpr static uint32_t R[] = { - 0x622, 0x623, 0x624, 0x625, 0x627, 0x629, 0x62f, 0x630, 0x631, - 0x632, 0x648, 0x671, 0x672, 0x673, 0x675, 0x676, 0x677, 0x688, - 0x689, 0x68a, 0x68b, 0x68c, 0x68d, 0x68e, 0x68f, 0x690, 0x691, - 0x692, 0x693, 0x694, 0x695, 0x696, 0x697, 0x698, 0x699, 0x6c0, - 0x6c3, 0x6c4, 0x6c5, 0x6c6, 0x6c7, 0x6c8, 0x6c9, 0x6ca, 0x6cb, - 0x6cd, 0x6cf, 0x6d2, 0x6d3, 0x6d5, 0x6ee, 0x6ef, 0x710, 0x715, - 0x716, 0x717, 0x718, 0x719, 0x71e, 0x728, 0x72a, 0x72c, 0x72f, - 0x74d, 0x759, 0x75a, 0x75b, 0x854, 0x8aa, 0x8ab, 0x8ac}; - constexpr static uint32_t L[] = {0xa872}; - constexpr static uint32_t D[] = { - 0x620, 0x626, 0x628, 0x62a, 0x62b, 0x62c, 0x62d, 0x62e, 0x633, - 0x634, 0x635, 0x636, 0x637, 0x638, 0x639, 0x63a, 0x63b, 0x63c, - 0x63d, 0x63e, 0x63f, 0x641, 0x642, 0x643, 0x644, 0x645, 0x646, - 0x647, 0x649, 0x64a, 0x66e, 0x66f, 0x678, 0x679, 0x67a, 0x67b, - 0x67c, 0x67d, 0x67e, 0x67f, 0x680, 0x681, 0x682, 0x683, 0x684, - 0x685, 0x686, 0x687, 0x69a, 0x69b, 0x69c, 0x69d, 0x69e, 0x69f, - 0x6a0, 0x6a1, 0x6a2, 0x6a3, 0x6a4, 0x6a5, 0x6a6, 0x6a7, 0x6a8, - 0x6a9, 0x6aa, 0x6ab, 0x6ac, 0x6ad, 0x6ae, 0x6af, 0x6b0, 0x6b1, - 0x6b2, 0x6b3, 0x6b4, 0x6b5, 0x6b6, 0x6b7, 0x6b8, 0x6b9, 0x6ba, - 0x6bb, 0x6bc, 0x6bd, 0x6be, 0x6bf, 0x6c1, 0x6c2, 0x6cc, 0x6ce, - 0x6d0, 0x6d1, 0x6fa, 0x6fb, 0x6fc, 0x6ff, 0x712, 0x713, 0x714, - 0x71a, 0x71b, 0x71c, 0x71d, 0x71f, 0x720, 0x721, 0x722, 0x723, - 0x724, 0x725, 0x726, 0x727, 0x729, 0x72b, 0x72d, 0x72e, 0x74e, - 0x74f, 0x750, 0x751, 0x752, 0x753, 0x754, 0x755, 0x756, 0x757, - 0x758, 0x75c, 0x75d, 0x75e, 0x75f, 0x760, 0x761, 0x762, 0x763, - 0x764, 0x765, 0x766, 0x850, 0x851, 0x852, 0x853, 0x855, 0x8a0, - 0x8a2, 0x8a3, 0x8a4, 0x8a5, 0x8a6, 0x8a7, 0x8a8, 0x8a9, 0x1807, - 0x1820, 0x1821, 0x1822, 0x1823, 0x1824, 0x1825, 0x1826, 0x1827, 0x1828, - 0x1829, 0x182a, 0x182b, 0x182c, 0x182d, 0x182e, 0x182f, 0x1830, 0x1831, - 0x1832, 0x1833, 0x1834, 0x1835, 0x1836, 0x1837, 0x1838, 0x1839, 0x183a, - 0x183b, 0x183c, 0x183d, 0x183e, 0x183f, 0x1840, 0x1841, 0x1842, 0x1843, - 0x1844, 0x1845, 0x1846, 0x1847, 0x1848, 0x1849, 0x184a, 0x184b, 0x184c, - 0x184d, 0x184e, 0x184f, 0x1850, 0x1851, 0x1852, 0x1853, 0x1854, 0x1855, - 0x1856, 0x1857, 0x1858, 0x1859, 0x185a, 0x185b, 0x185c, 0x185d, 0x185e, - 0x185f, 0x1860, 0x1861, 0x1862, 0x1863, 0x1864, 0x1865, 0x1866, 0x1867, - 0x1868, 0x1869, 0x186a, 0x186b, 0x186c, 0x186d, 0x186e, 0x186f, 0x1870, - 0x1871, 0x1872, 0x1873, 0x1874, 0x1875, 0x1876, 0x1877, 0x1887, 0x1888, - 0x1889, 0x188a, 0x188b, 0x188c, 0x188d, 0x188e, 0x188f, 0x1890, 0x1891, - 0x1892, 0x1893, 0x1894, 0x1895, 0x1896, 0x1897, 0x1898, 0x1899, 0x189a, - 0x189b, 0x189c, 0x189d, 0x189e, 0x189f, 0x18a0, 0x18a1, 0x18a2, 0x18a3, - 0x18a4, 0x18a5, 0x18a6, 0x18a7, 0x18a8, 0x18aa, 0xa840, 0xa841, 0xa842, - 0xa843, 0xa844, 0xa845, 0xa846, 0xa847, 0xa848, 0xa849, 0xa84a, 0xa84b, - 0xa84c, 0xa84d, 0xa84e, 0xa84f, 0xa850, 0xa851, 0xa852, 0xa853, 0xa854, - 0xa855, 0xa856, 0xa857, 0xa858, 0xa859, 0xa85a, 0xa85b, 0xa85c, 0xa85d, - 0xa85e, 0xa85f, 0xa860, 0xa861, 0xa862, 0xa863, 0xa864, 0xa865, 0xa866, - 0xa867, 0xa868, 0xa869, 0xa86a, 0xa86b, 0xa86c, 0xa86d, 0xa86e, 0xa86f, - 0xa870, 0xa871}; - - for (size_t i = 0; i < label.size(); i++) { - uint32_t c = label[i]; - if (c == 0x200c) { - if (i > 0) { - if (std::ranges::binary_search(virama, label[i - 1])) { - return true; - } - } - if ((i == 0) || (i + 1 >= label.size())) { - return false; - } - // we go backward looking for L or D - auto is_l_or_d = [](uint32_t code) { - return std::ranges::binary_search(L, code) || - std::ranges::binary_search(D, code); - }; - auto is_r_or_d = [](uint32_t code) { - return std::ranges::binary_search(R, code) || - std::ranges::binary_search(D, code); - }; - std::u32string_view before = label.substr(0, i); - std::u32string_view after = label.substr(i + 1); - return (std::find_if(before.begin(), before.end(), is_l_or_d) != - before.end()) && - (std::find_if(after.begin(), after.end(), is_r_or_d) != - after.end()); - } else if (c == 0x200d) { - if (i > 0) { - if (std::ranges::binary_search(virama, label[i - 1])) { - return true; - } - } - return false; - } + if (!is_contextj_valid(label)) { + return false; } // If CheckBidi, and if the domain name is a Bidi domain name, then the label @@ -6120,8 +6407,8 @@ bool is_label_valid(const std::u32string_view label) { // A "Bidi domain name" is a domain name that contains at least one RTL label. // The following rule, consisting of six conditions, applies to labels in Bidi - // domain names. - if (is_rtl_label(label)) { + // domain names: every label, not only the RTL ones. + if (bidi_domain || is_rtl_label(label)) { // The first character must be a character with Bidi property L, R, // or AL. If it has the R or AL property, it is an RTL label; if it // has the L property, it is an LTR label. @@ -6190,6 +6477,10 @@ bool is_label_valid(const std::u32string_view label) { return true; } +bool is_label_valid(const std::u32string_view label) { + return check_label(label, false); +} + } // namespace ada::idna /* end file src/validity.cpp */ /* begin file src/to_ascii.cpp */ @@ -6208,7 +6499,8 @@ bool is_label_valid(const std::u32string_view label) { namespace ada::idna { -// Maximum accepted UTF-8 domain length for to_ascii / to_unicode. +// Maximum accepted UTF-8 domain length for non-ASCII to_ascii input and for +// to_unicode input. // Bounds heap growth under untrusted input (DoS resistance). DNS wire limits // are smaller; this allows long Unicode labels used in URL tests/fixtures. inline constexpr size_t max_domain_input_bytes = 16384; @@ -6225,8 +6517,9 @@ namespace ada::idna { // decoding: percent decoding should be done prior to calling this function. We // do not remove tabs and spaces, they should have been removed prior to calling // this function. We also do not trim control characters. We also assume that -// the input is not empty. We return "" on error. Inputs longer than -// max_domain_input_bytes are rejected. +// the input is not empty. We return "" on error. Non-ASCII inputs longer than +// max_domain_input_bytes are rejected; ASCII inputs of any length are accepted +// (they are only lowercased). // // This function may accept or even produce invalid domains (WHATWG carve-outs). std::string to_ascii(std::string_view ut8_string); @@ -6345,15 +6638,65 @@ static bool is_ace_prefix(std::u32string_view label) noexcept { label[2] == U'-' && label[3] == U'-'; } +// RFC 5893: a Bidi domain name contains at least one RTL label. CheckBidi then +// applies to every label in the domain, so this must be known before the first +// label is validated. ACE labels are decoded; a decode failure is left for the +// conversion pass, which rejects the domain. +static bool mapped_domain_is_bidi(std::u32string_view mapped) { + const char32_t* p = mapped.data(); + const char32_t* const end = p + mapped.size(); + std::string puny; + std::u32string decoded; + while (p < end) { + const char32_t* begin = p; + while (p < end && *p != U'.') { + ++p; + } + const std::u32string_view label(begin, static_cast<size_t>(p - begin)); + if (p < end) { + ++p; + } + if (label.empty()) { + continue; + } + if (is_ace_prefix(label)) { + bool ace_ascii = true; + for (char32_t c : label) { + if (c >= 0x80) { + ace_ascii = false; + break; + } + } + if (!ace_ascii) { + continue; + } + puny.resize(label.size() - 4); + for (size_t i = 0; i < puny.size(); i++) { + puny[i] = static_cast<char>(label[i + 4]); + } + decoded.clear(); + if (punycode_to_utf32(puny, decoded) && label_contains_rtl(decoded)) { + return true; + } + } else if (label_contains_rtl(label)) { + return true; + } + } + return false; +} + [[nodiscard]] bool to_ascii(std::string_view ut8_string, std::string& out) { out.clear(); - if (ut8_string.size() > max_domain_input_bytes) { - return false; - } + // The ASCII path is a single same-size copy, so it needs no length bound. + // Checking first would reject the (longer) ASCII output of a non-ASCII input + // that was accepted, breaking to_ascii(to_ascii(x)) == to_ascii(x). if (is_ascii(ut8_string)) { from_ascii_to_ascii(ut8_string, out); return true; } + if (ut8_string.size() > max_domain_input_bytes) { + return false; + } #ifdef ADA_USE_SIMDUTF size_t utf32_length = @@ -6394,6 +6737,9 @@ static bool is_ace_prefix(std::u32string_view label) noexcept { } } + // CheckBidi applies to every label once any label is RTL (RFC 5893). + const bool bidi_domain = mapped_domain_is_bidi(mapped); + // Estimate ASCII output size (punycode may expand non-ASCII labels). out.reserve(mapped.size() + 8); @@ -6446,14 +6792,20 @@ static bool is_ace_prefix(std::u32string_view label) noexcept { return false; } } - if (post_map.empty() || !is_label_valid(post_map)) { + if (post_map.empty() || !check_label(post_map, bidi_domain)) { out.clear(); return false; } } else if (is_ascii(label_view)) { + // All-ASCII domains never reach here (they return above). An ASCII label + // in a Bidi domain must still satisfy RFC 5893 rules 1, 5, and 6. + if (bidi_domain && !check_label(label_view, true)) { + out.clear(); + return false; + } append_ascii_label(out, label_view); } else { - if (!is_label_valid(label_view)) { + if (!check_label(label_view, bidi_domain)) { out.clear(); return false; } @@ -6544,11 +6896,79 @@ bool valid_name_code_point(char32_t code_point, bool first); namespace ada::idna { +// True when an all-ASCII label is valid on its own but violates RFC 5893 +// because the domain contains an RTL label (for example a label starting +// with a digit). ToUnicode then returns the original input (UTS #46). +static bool ascii_label_fails_bidi_domain(std::string_view label) { + std::u32string utf32(label.size(), 0); + for (size_t i = 0; i < label.size(); i++) { + utf32[i] = static_cast<unsigned char>(label[i]); + } + return check_label(utf32, false) && !check_label(utf32, true); +} + +static bool utf8_domain_is_bidi(std::string_view input) { + std::u32string decoded; + size_t label_start = 0; + while (label_start < input.size()) { + const size_t loc_dot = input.find('.', label_start); + const bool is_last_label = (loc_dot == std::string_view::npos); + const size_t label_size = + is_last_label ? input.size() - label_start : loc_dot - label_start; + const std::string_view label = input.substr(label_start, label_size); + if (label.starts_with("xn--") && is_ascii(label)) { + decoded.clear(); + if (label.size() > 4 && punycode_to_utf32(label.substr(4), decoded) && + label_contains_rtl(decoded)) { + return true; + } + } else if (!is_ascii(label)) { + const size_t utf32_length = + utf32_length_from_utf8(label.data(), label.size()); + if (utf32_length != 0) { + decoded.assign(utf32_length, 0); + const size_t written = + utf8_to_utf32(label.data(), label.size(), decoded.data()); + if (written == utf32_length && label_contains_rtl(decoded)) { + return true; + } + } + } + if (is_last_label) { + break; + } + label_start += label_size + 1; + } + return false; +} + [[nodiscard]] bool to_unicode(std::string_view input, std::string& output) { output.clear(); if (input.size() > max_domain_input_bytes) { return false; } + // An ASCII label that is only illegal because the domain is a Bidi domain + // fails ToUnicode for the whole input (UTS #46), not just that label. + const bool bidi_domain = utf8_domain_is_bidi(input); + if (bidi_domain) { + size_t label_start = 0; + while (label_start < input.size()) { + const size_t loc_dot = input.find('.', label_start); + const bool is_last_label = (loc_dot == std::string_view::npos); + const size_t label_size = + is_last_label ? input.size() - label_start : loc_dot - label_start; + const std::string_view label = input.substr(label_start, label_size); + if (!label.empty() && is_ascii(label) && !label.starts_with("xn--") && + ascii_label_fails_bidi_domain(label)) { + output.assign(input); + return true; + } + if (is_last_label) { + break; + } + label_start += label_size + 1; + } + } output.reserve(input.size()); size_t label_start = 0; @@ -6577,7 +6997,7 @@ namespace ada::idna { accept_decoded = false; } else if (!ada::idna::normalize(post_map) || post_map != tmp_buffer || post_map.empty() || - !ada::idna::is_label_valid(post_map)) { + !check_label(post_map, bidi_domain)) { accept_decoded = false; } } @@ -6650,8 +7070,11 @@ std::string to_unicode(std::string_view input) { #include <string> /* begin file src/id_tables.cpp */ -// IDNA 17.0.0 +// IDNA 18.0.0 // Identifier range tables are stored in the compressed blob (table_store.hpp). +// Regenerate with: python3 scripts/derived_table.py --write +// id_continue: 1437 ranges +// id_start: 789 ranges // clang-format off #ifndef ADA_IDNA_IDENTIFIER_TABLES_H @@ -6722,7 +7145,13 @@ ADA_POP_DISABLE_WARNINGS #include <algorithm> #include <array> +#include <cstdint> #include <cstring> +#include <iterator> +#include <optional> +#include <string> +#include <string_view> +#include <utility> #if ADA_SSSE3 #include <tmmintrin.h> #elif ADA_NEON @@ -6840,7 +7269,16 @@ ada_really_inline bool has_tabs_or_newline( vld1q_u8((const uint8_t*)user_input.data() + user_input.length() - 16); running = vorrq_u8(running, vceqq_u8(vqtbl1q_u8(rnt, word), word)); } - return vmaxvq_u32(vreinterpretq_u32_u8(running)) != 0; + // `running` accumulates comparison results, so every lane is 0x00 or 0xFF: + // narrowing to four bits per lane and testing against zero is cheaper than a + // horizontal maximum. The double compare (ADA_NEON_SAFE_ZERO_CHECK set to 0) + // avoids a GPR transfer but is incorrect if flush-to-zero is enabled. + uint8x8_t narrowed = vshrn_n_u16(vreinterpretq_u16_u8(running), 4); +#if ADA_NEON_SAFE_ZERO_CHECK + return vget_lane_u64(vreinterpret_u64_u8(narrowed), 0) != 0; +#else + return vdupd_lane_f64(vreinterpret_f64_u8(narrowed), 0) != 0.0; +#endif } #elif ADA_SSE2 ada_really_inline bool has_tabs_or_newline( @@ -7168,31 +7606,51 @@ std::string percent_decode(const std::string_view input, size_t first_percent) { if (first_percent == std::string_view::npos) { return std::string(input); } - std::string dest; - dest.reserve(input.length()); - dest.append(input.substr(0, first_percent)); - const char* pointer = input.data() + first_percent; - const char* end = input.data() + input.size(); - // Optimization opportunity: if the following code gets - // called often, it can be optimized quite a bit. - while (pointer < end) { - const char ch = pointer[0]; - size_t remaining = end - pointer - 1; - if (ch != '%' || remaining < 2 || - ( // ch == '%' && // It is unnecessary to check that ch == '%'. - (!is_ascii_hex_digit(pointer[1]) || - !is_ascii_hex_digit(pointer[2])))) { - dest += ch; - pointer++; + + // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage) + const char* const src = input.data(); + const char* const end = src + input.size(); + + // Decoding never grows the string, so a single pre-sized buffer written via + // bulk memcpy of the plain runs (then shrunk to the final length) avoids the + // byte-at-a-time appends of the naive version. + std::string out(input.size(), '\0'); + char* d = out.data(); + char* const d0 = d; + + std::memcpy(d, src, first_percent); + d += first_percent; + + const char* p = src + first_percent; + while (p < end) { + if (*p == '%') { + // Decode runs of valid %XX tightly (common for nested/encoded URLs). + while (p + 2 < end && *p == '%') { + if (!is_ascii_hex_digit(p[1]) || !is_ascii_hex_digit(p[2])) { + break; + } + *d++ = static_cast<char>(convert_hex_to_binary(p[1]) * 16 + + convert_hex_to_binary(p[2])); + p += 3; + } + if (p < end && *p == '%') { + // Not a valid escape (too few chars left or bad hex): copy '%' + // literally and keep scanning after it. + *d++ = *p++; + } } else { - unsigned a = convert_hex_to_binary(pointer[1]); - unsigned b = convert_hex_to_binary(pointer[2]); - char c = static_cast<char>(a * 16 + b); - dest += c; - pointer += 3; + const char* q = static_cast<const char*>( + std::memchr(p, '%', static_cast<size_t>(end - p))); + const char* run_end = q ? q : end; + const size_t n = static_cast<size_t>(run_end - p); + std::memcpy(d, p, n); + d += n; + p = run_end; } } - return dest; + + out.resize(static_cast<size_t>(d - d0)); + return out; } // 0..15 for hex digits, 0xFF otherwise - validate and decode with two loads. @@ -7277,6 +7735,9 @@ std::string form_urlencoded_decode(const std::string_view input) { return out; } +void percent_encode_suffix(const char* p, const char* end, + const uint8_t character_set[], std::string& out); + std::string percent_encode(const std::string_view input, const uint8_t character_set[]) { auto pointer = std::ranges::find_if(input, [character_set](const char c) { @@ -7291,15 +7752,18 @@ std::string percent_encode(const std::string_view input, result.reserve(input.length()); // in the worst case, percent encoding might // produce 3 characters. result.append(input.substr(0, std::distance(input.begin(), pointer))); - - for (; pointer != input.end(); pointer++) { - if (character_sets::bit_at(character_set, *pointer)) { - result.append(character_sets::hex + uint8_t(*pointer) * 4, 3); - } else { - result += *pointer; + if (static_cast<size_t>(input.end() - pointer) >= 48) { + percent_encode_suffix(&*pointer, input.data() + input.size(), character_set, + result); + } else { + for (; pointer != input.end(); pointer++) { + if (character_sets::bit_at(character_set, *pointer)) { + result.append(character_sets::hex + uint8_t(*pointer) * 4, 3); + } else { + result += *pointer; + } } } - return result; } @@ -7338,6 +7802,13 @@ bool percent_encode(const std::string_view input, const uint8_t character_set[], return true; } +template bool percent_encode<true>(std::string_view input, + const uint8_t character_set[], + std::string& out); +template bool percent_encode<false>(std::string_view input, + const uint8_t character_set[], + std::string& out); + bool to_ascii(std::optional<std::string>& out, const std::string_view plain, size_t first_percent) { std::string percent_decoded_buffer; @@ -7362,11 +7833,16 @@ std::string percent_encode(const std::string_view input, // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage) out.append(input.data(), index); auto pointer = input.begin() + index; - for (; pointer != input.end(); pointer++) { - if (character_sets::bit_at(character_set, *pointer)) { - out.append(character_sets::hex + uint8_t(*pointer) * 4, 3); - } else { - out += *pointer; + if (static_cast<size_t>(input.end() - pointer) >= 48) { + percent_encode_suffix(&*pointer, input.data() + input.size(), character_set, + out); + } else { + for (; pointer != input.end(); pointer++) { + if (character_sets::bit_at(character_set, *pointer)) { + out.append(character_sets::hex + uint8_t(*pointer) * 4, 3); + } else { + out += *pointer; + } } } return out; @@ -7374,29 +7850,342 @@ std::string percent_encode(const std::string_view input, } // namespace ada::unicode /* end file src/unicode.cpp */ -/* begin file src/serializers.cpp */ - -#include <array> +#if !defined(ADA_PERCENT_ENCODE_SIMD_SEPARATE_TU) +/* begin file src/unicode_percent_encode.cpp */ #include <cstdint> + + + #include <cstring> #include <string> +#if ADA_SSSE3 +#include <tmmintrin.h> +#define ADA_UNICODE_SSSE3 1 +#elif ADA_NEON +#include <arm_neon.h> +#elif ADA_RVV +#include <riscv_vector.h> +#endif -namespace ada::serializers { +// gcc/clang honor target("ssse3") on an SSE2 translation unit. clang-cl and +// MSVC do not: they still compile the function as SSE2, then reject +// always_inline _mm_shuffle_epi8. Same approach as parser.cpp. +#if !ADA_UNICODE_SSSE3 && (defined(__x86_64__) || defined(__amd64__)) && \ + defined(__GNUC__) && !defined(_MSC_VER) +#include <tmmintrin.h> +#define ADA_UNICODE_SSSE3 1 +#define ADA_UNICODE_NEED_SSSE3_TARGET 1 +#endif +#ifndef ADA_UNICODE_SSSE3 +#define ADA_UNICODE_SSSE3 0 +#endif +#ifdef ADA_UNICODE_NEED_SSSE3_TARGET +// noinline: these functions must not be inlined into a caller that also +// contains the CPU check. A target("ssse3") function can use SSSE3 in its +// prologue, before any check inside it would run. +#define ADA_UNICODE_SIMD __attribute__((target("ssse3"), noinline)) +#else +#define ADA_UNICODE_SIMD ada_really_inline +#endif + +#ifdef ADA_REGULAR_VISUAL_STUDIO +#include <intrin.h> +#endif + +namespace ada::unicode { namespace { -// Digit pair LUT for fast decimal write: index 0..99 -> two chars. -constexpr std::array<char, 200> make_digit_pairs() noexcept { - std::array<char, 200> t{}; - for (size_t i = 0; i < 100; ++i) { - t[i * 2] = static_cast<char>('0' + i / 10); - t[i * 2 + 1] = static_cast<char>('0' + i % 10); - } - return t; +#if ADA_UNICODE_SSSE3 || ADA_NEON +ada_really_inline int trailing_zeroes32(uint32_t input_num) noexcept { +#ifdef ADA_REGULAR_VISUAL_STUDIO + unsigned long ret; + _BitScanForward(&ret, input_num); + return static_cast<int>(ret); +#else + return __builtin_ctz(input_num); +#endif } -constexpr auto digit_pairs = make_digit_pairs(); +// Append one window whose set bits mark bytes that need encoding. +ada_really_inline void encode_mask_window(const char* p, uint32_t mask, + size_t width, std::string& out) { + uint64_t bits = mask; + size_t off = 0; + while (bits != 0) { + const int zero_run = trailing_zeroes32(static_cast<uint32_t>(bits)); + if (zero_run != 0) { + out.append(p + off, static_cast<size_t>(zero_run)); + } + off += static_cast<size_t>(zero_run); + out.append(character_sets::hex + uint8_t(p[off]) * 4, 3); + ++off; + bits >>= static_cast<unsigned>(zero_run + 1); + } + if (off < width) { + out.append(p + off, width - off); + } +} +#endif // ADA_UNICODE_SSSE3 || ADA_NEON -ada_really_inline char* write_u8(char* p, uint8_t v) noexcept { +ada_really_inline void percent_encode_to_scalar(const char* p, const char* end, + const uint8_t character_set[], + std::string& out) { + for (; p != end; ++p) { + if (character_sets::bit_at(character_set, *p)) { + out.append(character_sets::hex + uint8_t(*p) * 4, 3); + } else { + out += *p; + } + } +} + +#if ADA_UNICODE_SSSE3 +// Classify 16 input bytes against the 32-byte character_set bitmap: +// bit_at(cs, b) == cs[b >> 3] & (1 << (b & 7)). pshufb looks up the two +// 16-byte halves of that bitmap; no per-call nibble table is built. +struct ssse3_percent_tables { + __m128i cs_lo; + __m128i cs_hi; + __m128i pow2; + __m128i mask_0f; + __m128i mask_07; + __m128i zero; +}; + +ADA_UNICODE_SIMD ssse3_percent_tables +load_ssse3_percent_tables(const uint8_t character_set[]) noexcept { + ssse3_percent_tables t{}; + t.cs_lo = _mm_loadu_si128(reinterpret_cast<const __m128i*>(character_set)); + t.cs_hi = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(character_set + 16)); + // 1 << (0..7), duplicated so pshufb(index & 7) works for every lane. + t.pow2 = + _mm_setr_epi8(1, 2, 4, 8, 16, 32, 64, -128, 1, 2, 4, 8, 16, 32, 64, -128); + t.mask_0f = _mm_set1_epi8(0x0F); + t.mask_07 = _mm_set1_epi8(0x07); + t.zero = _mm_setzero_si128(); + return t; +} + +ADA_UNICODE_SIMD int ssse3_percent_mask( + __m128i word, const ssse3_percent_tables& tables) noexcept { + const __m128i idx = _mm_and_si128(_mm_srli_epi16(word, 3), tables.mask_0f); + const __m128i lo = _mm_shuffle_epi8(tables.cs_lo, idx); + const __m128i hi = _mm_shuffle_epi8(tables.cs_hi, idx); + // Bytes 0x80-0xFF are signed-negative; select the high half of the bitmap. + const __m128i high_byte = _mm_cmpgt_epi8(tables.zero, word); + const __m128i cs_byte = _mm_or_si128(_mm_and_si128(hi, high_byte), + _mm_andnot_si128(high_byte, lo)); + const __m128i bits = + _mm_shuffle_epi8(tables.pow2, _mm_and_si128(word, tables.mask_07)); + const __m128i hits = _mm_and_si128(cs_byte, bits); + return _mm_movemask_epi8(_mm_cmpeq_epi8(hits, tables.zero)) ^ 0xFFFF; +} + +ADA_UNICODE_SIMD void percent_encode_to_ssse3( + const char* p, const char* end, const uint8_t character_set[], + const ssse3_percent_tables& tables, std::string& out) { + // Pair 16-byte windows so a fully clean 32-byte run is one append. + while (p + 32 <= end) { + const __m128i word0 = _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); + const __m128i word1 = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(p + 16)); + const int mask0 = ssse3_percent_mask(word0, tables); + const int mask1 = ssse3_percent_mask(word1, tables); + if ((mask0 | mask1) == 0) { + out.append(p, 32); + } else { + if (mask0 == 0) { + out.append(p, 16); + } else { + encode_mask_window(p, static_cast<uint32_t>(mask0), 16, out); + } + if (mask1 == 0) { + out.append(p + 16, 16); + } else { + encode_mask_window(p + 16, static_cast<uint32_t>(mask1), 16, out); + } + } + p += 32; + } + if (p + 16 <= end) { + const __m128i word = _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); + const int mask = ssse3_percent_mask(word, tables); + if (mask == 0) { + out.append(p, 16); + } else { + encode_mask_window(p, static_cast<uint32_t>(mask), 16, out); + } + p += 16; + } + percent_encode_to_scalar(p, end, character_set, out); +} +#endif // ADA_UNICODE_SSSE3 + +#if ADA_NEON +ada_really_inline uint8x16x2_t +load_neon_percent_table(const uint8_t character_set[]) noexcept { + uint8x16x2_t table{}; + table.val[0] = vld1q_u8(character_set); + table.val[1] = vld1q_u8(character_set + 16); + return table; +} + +ada_really_inline uint8x16_t neon_percent_hits(uint8x16_t word, + uint8x16x2_t table) noexcept { + const uint8x16_t cs_bytes = vqtbl2q_u8(table, vshrq_n_u8(word, 3)); + const uint8x16_t bit_mask = vshlq_u8( + vdupq_n_u8(1), vreinterpretq_s8_u8(vandq_u8(word, vdupq_n_u8(7)))); + return vandq_u8(cs_bytes, bit_mask); +} + +ada_really_inline uint32_t neon_percent_mask(uint8x16_t hits) noexcept { + const uint8x16_t cmp = vcgtq_u8(hits, vdupq_n_u8(0)); + const uint8x16_t bit = {1, 2, 4, 8, 16, 32, 64, 128, + 1, 2, 4, 8, 16, 32, 64, 128}; + const uint8x16_t masked = vandq_u8(cmp, bit); + return static_cast<uint32_t>(vaddv_u8(vget_low_u8(masked))) | + (static_cast<uint32_t>(vaddv_u8(vget_high_u8(masked))) << 8); +} + +ada_really_inline void percent_encode_to_neon(const char* p, const char* end, + const uint8_t character_set[], + uint8x16x2_t table, + std::string& out) { + while (p + 32 <= end) { + const uint8x16_t hits0 = + neon_percent_hits(vld1q_u8(reinterpret_cast<const uint8_t*>(p)), table); + const uint8x16_t hits1 = neon_percent_hits( + vld1q_u8(reinterpret_cast<const uint8_t*>(p + 16)), table); + const bool clean0 = vmaxvq_u32(vreinterpretq_u32_u8(hits0)) == 0; + const bool clean1 = vmaxvq_u32(vreinterpretq_u32_u8(hits1)) == 0; + if (clean0 && clean1) { + out.append(p, 32); + } else { + if (clean0) { + out.append(p, 16); + } else { + encode_mask_window(p, neon_percent_mask(hits0), 16, out); + } + if (clean1) { + out.append(p + 16, 16); + } else { + encode_mask_window(p + 16, neon_percent_mask(hits1), 16, out); + } + } + p += 32; + } + if (p + 16 <= end) { + const uint8x16_t hits = + neon_percent_hits(vld1q_u8(reinterpret_cast<const uint8_t*>(p)), table); + if (vmaxvq_u32(vreinterpretq_u32_u8(hits)) == 0) { + out.append(p, 16); + } else { + encode_mask_window(p, neon_percent_mask(hits), 16, out); + } + p += 16; + } + percent_encode_to_scalar(p, end, character_set, out); +} +#endif // ADA_NEON + +#if ADA_RVV +ada_really_inline void percent_encode_to_rvv(const char* p, const char* end, + const uint8_t character_set[], + std::string& out) { + while (p < end) { + const size_t remaining = static_cast<size_t>(end - p); + const size_t vl = __riscv_vsetvl_e8m1(remaining); + const vuint8m1_t word = + __riscv_vle8_v_u8m1(reinterpret_cast<const uint8_t*>(p), vl); + const vuint8m1_t cs_bytes = + __riscv_vluxei8(character_set, __riscv_vsrl(word, 3, vl), vl); + const vuint8m1_t bit_mask = __riscv_vsll(__riscv_vmv_v_x_u8m1(1, vl), + __riscv_vand(word, 7, vl), vl); + const long idx = __riscv_vfirst( + __riscv_vmsne(__riscv_vand(cs_bytes, bit_mask, vl), 0, vl), vl); + if (idx < 0) { + out.append(p, vl); + p += vl; + continue; + } + if (idx > 0) { + out.append(p, static_cast<size_t>(idx)); + p += idx; + } + out.append(character_sets::hex + uint8_t(*p) * 4, 3); + ++p; + } +} +#endif // ADA_RVV + +#if ADA_UNICODE_SSSE3 || ADA_NEON || ADA_RVV +// Setter and existing percent_encode benches are 2-44 bytes. Table setup +// plus mask walking costs more instructions than bit_at on those inputs +// (especially dense USERINFO). SIMD pays off on the remaining suffix. +static constexpr size_t kPercentEncodeSimdMin = 48; + +void percent_encode_to_wide(const char* p, const char* end, + const uint8_t character_set[], std::string& out) { + // Worst case every byte becomes %XX. Avoids realloc while walking windows. + out.reserve(out.size() + static_cast<size_t>(end - p) * 3); +#if ADA_UNICODE_SSSE3 + const ssse3_percent_tables tables = load_ssse3_percent_tables(character_set); + percent_encode_to_ssse3(p, end, character_set, tables, out); +#elif ADA_NEON + percent_encode_to_neon(p, end, character_set, + load_neon_percent_table(character_set), out); +#elif ADA_RVV + percent_encode_to_rvv(p, end, character_set, out); +#endif +} +#endif + +} // namespace + +void percent_encode_suffix(const char* p, const char* end, + const uint8_t character_set[], std::string& out) { +#if ADA_UNICODE_SSSE3 || ADA_NEON || ADA_RVV +#ifdef ADA_UNICODE_NEED_SSSE3_TARGET + static const bool ssse3_supported = __builtin_cpu_supports("ssse3") != 0; + const bool use_wide = ssse3_supported; +#else + const bool use_wide = true; +#endif + if (use_wide && static_cast<size_t>(end - p) >= kPercentEncodeSimdMin) { + percent_encode_to_wide(p, end, character_set, out); + return; + } +#endif + percent_encode_to_scalar(p, end, character_set, out); +} + +} // namespace ada::unicode +/* end file src/unicode_percent_encode.cpp */ +#endif +/* begin file src/serializers.cpp */ + +#include <array> +#include <cstdint> +#include <cstring> +#include <string> + +namespace ada::serializers { +namespace { + +// Digit pair LUT for fast decimal write: index 0..99 -> two chars. +constexpr std::array<char, 200> make_digit_pairs() noexcept { + std::array<char, 200> t{}; + for (size_t i = 0; i < 100; ++i) { + t[i * 2] = static_cast<char>('0' + i / 10); + t[i * 2 + 1] = static_cast<char>('0' + i % 10); + } + return t; +} + +constexpr auto digit_pairs = make_digit_pairs(); + +ada_really_inline char* write_u8(char* p, uint8_t v) noexcept { if (v < 10) { *p++ = static_cast<char>('0' + v); } else if (v < 100) { @@ -7467,8 +8256,8 @@ std::string ipv6(const std::array<uint16_t, 8>& address) { } // Max: '[' + 8*4 hex + 7 ':' + ']' = 41 - std::string output(4 * 8 + 7 + 2, '\0'); - char* point = output.data(); + char output[4 * 8 + 7 + 2]; + char* point = output; *point++ = '['; size_t piece_index = 0; while (true) { @@ -7491,8 +8280,7 @@ std::string ipv6(const std::array<uint16_t, 8>& address) { *point++ = ':'; } *point++ = ']'; - output.resize(static_cast<size_t>(point - output.data())); - return output; + return std::string(output, static_cast<size_t>(point - output)); } std::string ipv4(const uint64_t address) { @@ -7513,9 +8301,13 @@ std::string ipv4(const uint64_t address) { /* end file src/serializers.cpp */ /* begin file src/implementation.cpp */ +#include <array> #include <atomic> +#include <cstdint> +#include <cstring> #include <limits> #include <optional> +#include <string> #include <string_view> @@ -7534,6 +8326,146 @@ uint32_t get_max_input_length() { namespace { +constexpr std::array<uint8_t, 256> clean_http_host_byte = []() consteval { + std::array<uint8_t, 256> result{}; + for (size_t i = 0; i < result.size(); ++i) { + const auto c = static_cast<uint8_t>(i); + result[i] = + static_cast<uint8_t>((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '-' || c == '.' || c == '_' || c == '~'); + } + return result; +}(); + +// SWAR: eight ASCII host bytes in [a-z0-9-._~] without 8 table lookups. +// High bits must be clear first so the range subtracts cannot borrow +// across bytes. +// High-bit-cleared ASCII only. Subtracts cannot borrow across bytes because +// each (hi|0x80) byte is >= 0x80 and each data byte is <= 0x7F. Do not use +// has-zero (x-ones)&~x: a match followed by match^1 (e.g. "./" or "_^") +// produces a false positive via borrow. +ada_really_inline uint64_t swar_in_range(uint64_t w, uint8_t lo, + uint8_t hi) noexcept { + constexpr uint64_t k_ones = 0x0101010101010101ull; + constexpr uint64_t k_high = 0x8080808080808080ull; + const uint64_t ge_lo = (w | k_high) - (k_ones * lo); + const uint64_t le_hi = ((k_ones * hi) | k_high) - w; + return ge_lo & le_hi & k_high; +} + +ada_really_inline bool eight_clean_http_host_bytes( + const uint8_t* input) noexcept { + uint64_t w = 0; + std::memcpy(&w, input, 8); + constexpr uint64_t k_high = 0x8080808080808080ull; + if ((w & k_high) != 0) { + return false; + } + const uint64_t ok = swar_in_range(w, 'a', 'z') | swar_in_range(w, '0', '9') | + swar_in_range(w, '-', '-') | swar_in_range(w, '.', '.') | + swar_in_range(w, '_', '_') | swar_in_range(w, '~', '~'); + return ok == k_high; +} + +// Minimal front end for the overwhelmingly common already-canonical HTTP(S) +// case. It deliberately handles fewer inputs than +// try_can_parse_absolute_fast: anything requiring normalization or detailed +// host parsing falls through to that broader validator. +#if defined(_MSC_VER) || \ + (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) +constexpr bool k_can_parse_little_endian = true; +#else +constexpr bool k_can_parse_little_endian = false; +#endif + +std::optional<bool> try_can_parse_clean_http(std::string_view input) noexcept { + const auto* bytes = reinterpret_cast<const uint8_t*>(input.data()); + const size_t length = input.size(); + if (length < 7) { + return std::nullopt; + } + + size_t authority_start; + if constexpr (k_can_parse_little_endian) { + if (length >= 8) { + uint64_t first8 = 0; + std::memcpy(&first8, bytes, 8); + if (first8 == 0x2f2f3a7370747468ull) { // "https://" + authority_start = 8; + } else if ((first8 & 0x00ffffffffffffffull) == + 0x002f2f3a70747468ull) { // "http://" + authority_start = 7; + } else { + return std::nullopt; + } + } else if (bytes[0] == 'h' && bytes[1] == 't' && bytes[2] == 't' && + bytes[3] == 'p' && bytes[4] == ':' && bytes[5] == '/' && + bytes[6] == '/') { + authority_start = 7; + } else { + return std::nullopt; + } + } else { + uint32_t first4{}; + std::memcpy(&first4, bytes, 4); + if (first4 != 0x68747470u) { // "http" + return std::nullopt; + } + if (length >= 8 && bytes[4] == 's' && bytes[5] == ':' && bytes[6] == '/' && + bytes[7] == '/') { + authority_start = 8; + } else if (bytes[4] == ':' && bytes[5] == '/' && bytes[6] == '/') { + authority_start = 7; + } else { + return std::nullopt; + } + } + + if (authority_start >= length) { + return false; + } + + size_t cursor = authority_start; + while (cursor + 8 <= length && eight_clean_http_host_bytes(bytes + cursor)) { + cursor += 8; + } + while (cursor < length) { + const uint8_t c = bytes[cursor]; + if (c == '/' || c == '?' || c == '#') { + break; + } + if (!clean_http_host_byte[c]) { + return std::nullopt; + } + ++cursor; + } + + const size_t host_length = cursor - authority_start; + if (host_length == 0) { + // Extra special-scheme slashes are normalization, not an empty host. + if (bytes[authority_start] == '/' || bytes[authority_start] == '\\') { + return std::nullopt; + } + return false; + } + if (host_length > 253 || bytes[cursor - 1] == '.') { + return std::nullopt; + } + + const std::string_view host(input.data() + authority_start, host_length); + if (checkers::last_label_may_be_a_number(host)) { + return std::nullopt; + } + if (host.find('x') != std::string_view::npos && + host.find("xn-") != std::string_view::npos) { + return std::nullopt; + } + + // Once a special URL has a valid host, path/query/fragment bytes cannot make + // it structurally invalid: the full parser percent-encodes them as needed. + return true; +} + // @private // Fast-path validator for can_parse. // @@ -7655,7 +8587,6 @@ std::optional<bool> try_can_parse_absolute_fast( size_t auth_end = pos; size_t port_colon = SIZE_MAX; bool all_dec_dots = true; - uint8_t last_non_dot = 0; for (; auth_end < len; ++auth_end) { const uint8_t c = b[auth_end]; @@ -7700,9 +8631,6 @@ std::optional<bool> try_can_parse_absolute_fast( // Track whether host is all decimal digits and dots (potential IPv4). if (c != '.' && (c < '0' || c > '9')) all_dec_dots = false; - // Track last non-dot character for the IPv4 hex/octal heuristic. - if (c != '.') last_non_dot = c; - // Detect xn-- prefix inline (IDNA punycode -> needs full parser). // Checking at every position mirrors the original behavior: any // occurrence of "xn--" in the host (not just at label boundaries) @@ -7736,16 +8664,8 @@ std::optional<bool> try_can_parse_absolute_fast( return std::nullopt; } - // Last-significant-character heuristic for non-decimal IPv4 (hex/octal): - // if the last non-dot char is a digit, 'a'-'f', or 'x' the host might be - // an IPv4 address that the fast path can't validate -- fall through. - // last_non_dot was tracked during the authority scan above. - { - const uint8_t lc = last_non_dot | 0x20; - if ((last_non_dot >= '0' && last_non_dot <= '9') || - (lc >= 'a' && lc <= 'f') || lc == 'x') { - return std::nullopt; - } + if (checkers::last_label_may_be_a_number({host_ptr, host_len})) { + return std::nullopt; } // -- Port validation ------------------------------------------------------- @@ -7838,7 +8758,11 @@ bool can_parse(std::string_view input, const std::string_view* base_input) { // Hot path first: absolute special URLs, no base. Avoid loading max_length // until we need it (common absolute-fast true/false cases). if (base_input == nullptr) { - if (const auto r = try_can_parse_absolute_fast(input)) { + auto r = try_can_parse_clean_http(input); + if (!r.has_value()) { + r = try_can_parse_absolute_fast(input); + } + if (r.has_value()) { if (!*r) { return false; } @@ -7921,9 +8845,14 @@ ada_warn_unused std::string_view to_string(ada::encoding_type type) { } // namespace ada /* end file src/implementation.cpp */ /* begin file src/helpers.cpp */ +#include <array> #include <cstdint> #include <cstring> +#include <optional> #include <sstream> +#include <string> +#include <string_view> +#include <utility> #if ADA_SSSE3 @@ -8066,8 +8995,13 @@ ada_really_inline bool shorten_path(std::string_view& path, } ada_really_inline void remove_ascii_tab_or_newline(std::string& input) { - // if this ever becomes a performance issue, we could use an approach similar - // to has_tabs_or_newline + // Fast path: inputs with no tab/newline (the common case) avoid the + // per-character erase_if scan. has_tabs_or_newline uses SIMD for inputs + // >= 16 bytes, making this check much cheaper than erase_if's scalar + // predicate walk when there is nothing to remove. + if (!ada::unicode::has_tabs_or_newline(input)) { + return; + } std::erase_if(input, ada::unicode::is_ascii_tab_or_newline); } @@ -8098,6 +9032,50 @@ ada_really_inline int trailing_zeroes(uint32_t input_num) noexcept { #endif // ADA_REGULAR_VISUAL_STUDIO } +#if ADA_NEON +// computes the number of trailing zeroes of a 64-bit word +// this is a private inline function only defined in this source file. +ada_really_inline int trailing_zeroes64(uint64_t input_num) noexcept { +#ifdef ADA_REGULAR_VISUAL_STUDIO + unsigned long ret; + _BitScanForward64(&ret, input_num); + return (int)ret; +#else // ADA_REGULAR_VISUAL_STUDIO + return __builtin_ctzll(input_num); +#endif // ADA_REGULAR_VISUAL_STUDIO +} + +// Given a NEON register whose lanes are all either 0x00 or 0xFF (i.e., the +// result of a comparison), produce a 64-bit value with four bits set per +// matching input byte, and zero bits elsewhere. Narrowing by four bits per +// 16-bit lane is cheaper than materializing a 16-bit bitmask. +// +// With ADA_NEON_SAFE_ZERO_CHECK set to 0, the "any match?" test instead +// treats the nibble mask as an IEEE 754 double and compares it against zero, +// avoiding a transfer to a general-purpose register on the common no-match +// path. Negative zero cannot occur (each byte is 0x00, 0x0F, 0xF0 or 0xFF), +// but a mask with only low bits set is a denormal: if flush-to-zero is +// enabled, those compare equal to 0.0. Do not use this on arbitrary vectors. +ada_really_inline uint8x8_t to_nibble_mask(uint8x16_t comparison) noexcept { + return vshrn_n_u16(vreinterpretq_u16_u8(comparison), 4); +} + +ada_really_inline bool any_set(uint8x8_t nibble_mask) noexcept { +#if ADA_NEON_SAFE_ZERO_CHECK + return vget_lane_u64(vreinterpret_u64_u8(nibble_mask), 0) != 0; +#else + return vdupd_lane_f64(vreinterpret_f64_u8(nibble_mask), 0) != 0.0; +#endif +} + +// index of the first matching byte; only meaningful when any_set is true. +ada_really_inline size_t first_set(uint8x8_t nibble_mask) noexcept { + return size_t(trailing_zeroes64( + vget_lane_u64(vreinterpret_u64_u8(nibble_mask), 0))) >> + 2; +} +#endif // ADA_NEON + // starting at index location, this finds the next location of a character // :, /, \\, ? or [. If none is found, view.size() is returned. // For use within get_host_delimiter_location. @@ -8184,17 +9162,6 @@ ada_really_inline size_t find_next_host_delimiter_special( } return size_t(view.size()); } - auto to_bitmask = [](uint8x16_t input) -> uint16_t { - uint8x16_t bit_mask = - ada_make_uint8x16_t(0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x01, - 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80); - uint8x16_t minput = vandq_u8(input, bit_mask); - uint8x16_t tmp = vpaddq_u8(minput, minput); - tmp = vpaddq_u8(tmp, tmp); - tmp = vpaddq_u8(tmp, tmp); - return vgetq_lane_u16(vreinterpretq_u16_u8(tmp), 0); - }; - // fast path for long strings (expected to be common) size_t i = location; uint8x16_t low_mask = @@ -8204,16 +9171,16 @@ ada_really_inline size_t find_next_host_delimiter_special( ada_make_uint8x16_t(0x00, 0x00, 0x02, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); uint8x16_t fmask = vmovq_n_u8(0xf); - uint8x16_t zero{0}; for (; i + 15 < view.size(); i += 16) { uint8x16_t word = vld1q_u8((const uint8_t*)view.data() + i); uint8x16_t lowpart = vqtbl1q_u8(low_mask, vandq_u8(word, fmask)); uint8x16_t highpart = vqtbl1q_u8(high_mask, vshrq_n_u8(word, 4)); - uint8x16_t classify = vandq_u8(lowpart, highpart); - if (vmaxvq_u32(vreinterpretq_u32_u8(classify)) != 0) { - uint8x16_t is_zero = vceqq_u8(classify, zero); - uint16_t is_non_zero = static_cast<uint16_t>(~to_bitmask(is_zero)); - return i + trailing_zeroes(is_non_zero); + // vtstq_u8 gives us 0xFF where (lowpart & highpart) is non-zero and 0x00 + // elsewhere: unlike the plain AND, that is a proper comparison mask, which + // is what to_nibble_mask requires. + uint8x8_t matches = to_nibble_mask(vtstq_u8(lowpart, highpart)); + if (any_set(matches)) { + return i + first_set(matches); } } @@ -8222,11 +9189,9 @@ ada_really_inline size_t find_next_host_delimiter_special( vld1q_u8((const uint8_t*)view.data() + view.length() - 16); uint8x16_t lowpart = vqtbl1q_u8(low_mask, vandq_u8(word, fmask)); uint8x16_t highpart = vqtbl1q_u8(high_mask, vshrq_n_u8(word, 4)); - uint8x16_t classify = vandq_u8(lowpart, highpart); - if (vmaxvq_u32(vreinterpretq_u32_u8(classify)) != 0) { - uint8x16_t is_zero = vceqq_u8(classify, zero); - uint16_t is_non_zero = static_cast<uint16_t>(~to_bitmask(is_zero)); - return view.length() - 16 + trailing_zeroes(is_non_zero); + uint8x8_t matches = to_nibble_mask(vtstq_u8(lowpart, highpart)); + if (any_set(matches)) { + return view.length() - 16 + first_set(matches); } } return size_t(view.size()); @@ -8473,17 +9438,6 @@ ada_really_inline size_t find_next_host_delimiter(std::string_view view, } return size_t(view.size()); } - auto to_bitmask = [](uint8x16_t input) -> uint16_t { - uint8x16_t bit_mask = - ada_make_uint8x16_t(0x01, 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x01, - 0x02, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80); - uint8x16_t minput = vandq_u8(input, bit_mask); - uint8x16_t tmp = vpaddq_u8(minput, minput); - tmp = vpaddq_u8(tmp, tmp); - tmp = vpaddq_u8(tmp, tmp); - return vgetq_lane_u16(vreinterpretq_u16_u8(tmp), 0); - }; - // fast path for long strings (expected to be common) size_t i = location; uint8x16_t low_mask = @@ -8493,16 +9447,16 @@ ada_really_inline size_t find_next_host_delimiter(std::string_view view, ada_make_uint8x16_t(0x00, 0x00, 0x02, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00); uint8x16_t fmask = vmovq_n_u8(0xf); - uint8x16_t zero{0}; for (; i + 15 < view.size(); i += 16) { uint8x16_t word = vld1q_u8((const uint8_t*)view.data() + i); uint8x16_t lowpart = vqtbl1q_u8(low_mask, vandq_u8(word, fmask)); uint8x16_t highpart = vqtbl1q_u8(high_mask, vshrq_n_u8(word, 4)); - uint8x16_t classify = vandq_u8(lowpart, highpart); - if (vmaxvq_u32(vreinterpretq_u32_u8(classify)) != 0) { - uint8x16_t is_zero = vceqq_u8(classify, zero); - uint16_t is_non_zero = static_cast<uint16_t>(~to_bitmask(is_zero)); - return i + trailing_zeroes(is_non_zero); + // vtstq_u8 gives us 0xFF where (lowpart & highpart) is non-zero and 0x00 + // elsewhere: unlike the plain AND, that is a proper comparison mask, which + // is what to_nibble_mask requires. + uint8x8_t matches = to_nibble_mask(vtstq_u8(lowpart, highpart)); + if (any_set(matches)) { + return i + first_set(matches); } } @@ -8511,11 +9465,9 @@ ada_really_inline size_t find_next_host_delimiter(std::string_view view, vld1q_u8((const uint8_t*)view.data() + view.length() - 16); uint8x16_t lowpart = vqtbl1q_u8(low_mask, vandq_u8(word, fmask)); uint8x16_t highpart = vqtbl1q_u8(high_mask, vshrq_n_u8(word, 4)); - uint8x16_t classify = vandq_u8(lowpart, highpart); - if (vmaxvq_u32(vreinterpretq_u32_u8(classify)) != 0) { - uint8x16_t is_zero = vceqq_u8(classify, zero); - uint16_t is_non_zero = static_cast<uint16_t>(~to_bitmask(is_zero)); - return view.length() - 16 + trailing_zeroes(is_non_zero); + uint8x8_t matches = to_nibble_mask(vtstq_u8(lowpart, highpart)); + if (any_set(matches)) { + return view.length() - 16 + first_set(matches); } } return size_t(view.size()); @@ -8858,7 +9810,6 @@ ada_really_inline void parse_prepared_path(std::string_view input, ada_log("parse_path slow"); // we have reached the general case bool needs_percent_encoding = (accumulator & 1); - std::string path_buffer_tmp; do { size_t location = (special && (accumulator & 2)) ? input.find_first_of("/\\") @@ -8868,39 +9819,37 @@ ada_really_inline void parse_prepared_path(std::string_view input, path_view.remove_suffix(path_view.size() - location); input.remove_prefix(location + 1); } - // path_buffer is either path_view or it might point at a percent encoded - // temporary file. - std::string_view path_buffer = - (needs_percent_encoding && - ada::unicode::percent_encode<false>( - path_view, character_sets::PATH_PERCENT_ENCODE, path_buffer_tmp)) - ? path_buffer_tmp - : path_view; - if (unicode::is_double_dot_path_segment(path_buffer)) { + // Path encoding preserves dots and percent signs, so normalize first. + if (unicode::is_double_dot_path_segment(path_view)) { helpers::shorten_path(path, type); if (location == std::string_view::npos) { path += '/'; } - } else if (unicode::is_single_dot_path_segment(path_buffer) && + } else if (unicode::is_single_dot_path_segment(path_view) && (location == std::string_view::npos)) { path += '/'; } - // Otherwise, if path_buffer is not a single-dot path segment, then: - else if (!unicode::is_single_dot_path_segment(path_buffer)) { - // If url's scheme is "file", url's path is empty, and path_buffer is a + // Otherwise, if path_view is not a single-dot path segment, then: + else if (!unicode::is_single_dot_path_segment(path_view)) { + // If url's scheme is "file", url's path is empty, and path_view is a // Windows drive letter, then replace the second code point in - // path_buffer with U+003A (:). + // path_view with U+003A (:). if (type == ada::scheme::type::FILE && path.empty() && - checkers::is_windows_drive_letter(path_buffer)) { + path_view.size() == 2 && + checkers::is_windows_drive_letter(path_view)) { path += '/'; - path += path_buffer[0]; + path += path_view[0]; path += ':'; - path_buffer.remove_prefix(2); - path.append(path_buffer); + path_view.remove_prefix(2); + path.append(path_view); } else { - // Append path_buffer to url's path. + // Append encoded bytes directly to the pathname. path += '/'; - path.append(path_buffer); + if (!needs_percent_encoding || + !ada::unicode::percent_encode<true>( + path_view, character_sets::PATH_PERCENT_ENCODE, path)) { + path.append(path_view); + } } } if (location == std::string_view::npos) { @@ -8998,8 +9947,15 @@ ada_warn_unused std::string to_string(ada::state state) { #include <array> +#include <cstddef> #include <cstdint> +// The IPv6 kernel needs vpermi2b/vpermb (VBMI) and vpcompressb/vpexpandb +// (VBMI2) on top of ADA_AVX512's BW+VL. +#if defined(ADA_AVX512) && defined(__AVX512VBMI__) && defined(__AVX512VBMI2__) +#define ADA_AVX512_IPV6 1 +#endif + #if defined(ADA_AVX512) #include <immintrin.h> #endif @@ -9138,41 +10094,136 @@ inline int parse_hex_piece(const char*& pointer, const char* end, return length; } -#if defined(ADA_AVX512) -// Classify an IPv6 host (no brackets) with one masked 512-bit load. -// Returns false if the colon/dot shape is impossible (e.g. two "::", >8 -// colons, full form without 7 colons). Used as a cheap prefilter before the -// full WHATWG piece parser. -ada_really_inline bool ipv6_structure_plausible(const char* data, - size_t len) noexcept { - if (len < 2 || len > 45) { +#if defined(ADA_AVX512_IPV6) +// Gather each group's up-to-four nibbles and fold them into eight hextets. +// `prev` is the byte before each group, so an index that runs off the front of +// a short group clamps onto a colon, which translates to zero: no write mask. +ada_really_inline void ipv6_gather(__m128i ends, __m128i prev, __m512i nib, + std::array<uint16_t, 8>& address) noexcept { + const __m256i grp = + _mm256_setr_epi8(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, + 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7); + const __m256i off = _mm256_setr_epi8( + -4, -3, -2, -1, -4, -3, -2, -1, -4, -3, -2, -1, -4, -3, -2, -1, -4, -3, + -2, -1, -4, -3, -2, -1, -4, -3, -2, -1, -4, -3, -2, -1); + const __m256i idx = _mm256_max_epi8( + _mm256_add_epi8( + _mm256_permutexvar_epi8(grp, _mm256_castsi128_si256(ends)), off), + _mm256_permutexvar_epi8(grp, _mm256_castsi128_si256(prev))); + const __m256i gathered = _mm512_castsi512_si256( + _mm512_permutexvar_epi8(_mm512_castsi256_si512(idx), nib)); + // (a,b) -> 16a+b are the sixteen address bytes; 256*hi+lo pairs them. + const __m256i hextets = _mm256_madd_epi16( + _mm256_maddubs_epi16(gathered, _mm256_set1_epi16(0x0110)), + _mm256_set1_epi32(0x00010100)); + _mm_storeu_si128(reinterpret_cast<__m128i*>(address.data()), + _mm256_cvtepi32_epi16(hextets)); +} + +// Parse an IPv6 host with one masked 512-bit load. Derived from +// vtlmks/ipv6-avx512 (Peter Fors, MIT). +// +// Returns false when the input is outside this kernel's grammar and the caller +// must run the scalar parser. Otherwise `valid` receives the verdict, and +// `address` the eight hextets when valid. +ada_really_inline bool try_parse_ipv6_avx512(const char* data, size_t len, + std::array<uint16_t, 8>& address, + bool& valid) noexcept { + if (len < 2 || len > 45) [[unlikely]] { return false; } - const __mmask64 live = static_cast<__mmask64>((1ULL << len) - 1ULL); - const __m512i input = - _mm512_maskz_loadu_epi8(live, reinterpret_cast<const void*>(data)); - const __mmask64 is_colon = - _mm512_mask_cmpeq_epi8_mask(live, input, _mm512_set1_epi8(':')); - const __mmask64 is_dot = - _mm512_mask_cmpeq_epi8_mask(live, input, _mm512_set1_epi8('.')); - const int colons = - static_cast<int>(_mm_popcnt_u64(static_cast<uint64_t>(is_colon))); - if (colons > 8) { + // ':' rather than 0x80 for the colon, so a clamped index reads a zero nibble. + alignas(64) static constexpr uint8_t hex_lo[64] = { + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, + 0x07, 0x08, 0x09, 0x00, 0x80, 0x80, 0x80, 0x80, 0x80}; + alignas(64) static constexpr uint8_t hex_hi[64] = { + 0x80, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, + 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80}; + alignas(64) static constexpr uint8_t iota[64] = { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, + 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, + 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}; + + const __mmask64 active = + static_cast<__mmask64>(_bzhi_u64(~0ULL, static_cast<uint32_t>(len))); + const __m512i colon = _mm512_set1_epi8(':'); + // Merging ':' into the tail makes the terminator at `len` a real colon, so + // the compress mask below never has to be rebuilt in a general register. + const __m512i v = _mm512_mask_loadu_epi8(colon, active, data); + const __mmask64 mcolon = _mm512_cmpeq_epi8_mask(v, colon); + + // An embedded dotted quad is the one valid form this kernel does not cover. + // Because that is the only gap, every other input it does not accept is + // invalid, which is what makes `valid = false` below safe. + if (_mm512_cmpeq_epi8_mask(v, _mm512_set1_epi8('.'))) [[unlikely]] { return false; } - const uint64_t doubles = - static_cast<uint64_t>(is_colon) & (static_cast<uint64_t>(is_colon) << 1); - if (doubles != 0 && (doubles & (doubles - 1)) != 0) { - return false; // more than one "::" (or ":::...") - } - const bool has_double = doubles != 0; - const bool has_dot = is_dot != 0; - if (!has_double && !has_dot && colons != 7) { - return false; + + const __m512i nib = _mm512_permutex2var_epi8(_mm512_load_si512(hex_lo), v, + _mm512_load_si512(hex_hi)); + const __m128i comp = _mm512_castsi512_si128( + _mm512_maskz_compress_epi8(mcolon, _mm512_load_si512(iota))); + const __m128i lane0 = + _mm_setr_epi8(-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i prev = _mm_or_si128(_mm_bslli_si128(comp, 1), lane0); + const __m128i width = _mm_sub_epi8(comp, prev); // one too large + + const uint64_t mc = static_cast<uint64_t>(mcolon); + const uint64_t act = static_cast<uint64_t>(active); + const uint64_t dc = mc & (mc >> 1) & (act >> 1); // a "::" inside [0, len) + + if (!dc) { + ipv6_gather(comp, prev, nib, address); + // nib | (v & 0x80): one scan for non-hex bytes and for bytes whose high + // bit made vpermi2b alias a legal one. + const __m512i fused = _mm512_ternarylogic_epi32( + nib, v, _mm512_set1_epi8(static_cast<char>(0x80)), 0xf8); + // Lanes 8..15 bound against 255, which an unsigned byte cannot exceed. + const __m128i wmax = + _mm_setr_epi8(3, 3, 3, 3, 3, 3, 3, 3, -1, -1, -1, -1, -1, -1, -1, -1); + __mmask64 err = _kandn_mask64(mcolon, _mm512_movepi8_mask(fused)); + err = _kor_mask64( + err, static_cast<__mmask64>(static_cast<uint16_t>(_mm_cmpgt_epu8_mask( + _mm_sub_epi8(width, _mm_set1_epi8(2)), wmax)))); + valid = (_mm_popcnt_u64(mc & act) == 7) && !err; + return true; } + + // Drop the zero-width gap field(s), then expand the surviving head and tail + // fields into eight slots with all-zero groups inserted at the gap. + const uint32_t head = static_cast<uint32_t>(_mm_popcnt_u64(mc & (dc - 1))) + + static_cast<uint32_t>(dc > 1); + const __mmask16 keep = _mm_cmpgt_epi8_mask(width, _mm_set1_epi8(1)); + const uint32_t kept = static_cast<uint32_t>(_mm_popcnt_u32(keep)); + const __mmask16 slots = static_cast<__mmask16>( + ~(_bzhi_u32(0xFFFFFFFFu, 8 - kept) << head) & 0xFFu); + // Inserted groups take prev = -1, so their indices clamp to byte 63, a tail + // colon, and read zero. + ipv6_gather(_mm_maskz_expand_epi8(slots, _mm_maskz_compress_epi8(keep, comp)), + _mm_mask_expand_epi8(_mm_set1_epi8(-1), slots, + _mm_maskz_compress_epi8(keep, prev)), + nib, address); + + uint64_t err = _mm512_movepi8_mask(v); // high-bit bytes + err |= _mm512_movepi8_mask(nib) & ~mc; // non-hex + err |= _blsr_u64(dc); // a second "::" + err |= static_cast<uint64_t>(kept >= 8); // "::" elides nothing + err |= _mm_cmpgt_epu8_mask(width, _mm_set1_epi8(5)) & keep; // group > 4 + err |= (mc & 1ULL) & ~dc; // leading lone ':' + err |= ((mc >> (len - 1)) & 1ULL) & ~(dc >> (len - 2)); // trailing lone ':' + valid = !err; return true; } -#endif // ADA_AVX512 +#endif // ADA_AVX512_IPV6 } // namespace ada::detail @@ -9181,12 +10232,15 @@ ada_really_inline bool ipv6_structure_plausible(const char* data, #include <algorithm> #include <array> +#include <cstddef> #include <cstdint> #include <iterator> #include <numeric> +#include <optional> #include <ranges> #include <string> #include <string_view> +#include <utility> namespace ada { @@ -9272,16 +10326,19 @@ bool url::parse_ipv6(std::string_view input) { if (input.empty() || input.size() > 45) [[unlikely]] { return is_valid = false; } -#if defined(ADA_AVX512) - // One masked load classifies colon/dot shape; rejects impossible inputs - // before the piece parser (free on AVX-512BW+VL builds). - if (!detail::ipv6_structure_plausible(input.data(), input.size())) - [[unlikely]] { - return is_valid = false; + std::array<uint16_t, 8> address{}; +#if defined(ADA_AVX512_IPV6) + if (bool simd_valid; detail::try_parse_ipv6_avx512(input.data(), input.size(), + address, simd_valid)) { + if (!simd_valid) [[unlikely]] { + return is_valid = false; + } + host = ada::serializers::ipv6(address); + host_type = IPV6; + return true; } + address = {}; #endif - - std::array<uint16_t, 8> address{}; const char* pointer = input.data(); const char* const end = pointer + input.size(); int piece_index = 0; @@ -9527,10 +10584,9 @@ ada_really_inline bool url::parse_host(std::string_view input) { return parse_opaque_host(input); } - // Fast path: try to parse as pure decimal IPv4(a.b.c.d) first. + // Fast path: try to parse as pure decimal IPv4 first. const uint64_t fast_result = checkers::try_parse_ipv4_fast(input); if (fast_result < checkers::ipv4_fast_fail) { - // Fast path succeeded - input is pure decimal IPv4 if (!input.empty() && input.back() == '.') { host = input.substr(0, input.size() - 1); } else { @@ -9546,26 +10602,45 @@ ada_really_inline bool url::parse_host(std::string_view input) { // to ASCII with domain and false. The most common case is an ASCII input, in // which case we do not need to call the expensive 'to_ascii' if a few // conditions are met: no '%' and no 'xn-' subsequence. - std::string buffer = std::string(input); - // This next function checks that the result is ascii, but we are going to - // to check anyhow with is_forbidden. - // bool is_ascii = - unicode::to_lower_ascii(buffer.data(), buffer.size()); - bool is_forbidden = unicode::contains_forbidden_domain_code_point( - buffer.data(), buffer.size()); + const uint8_t forbidden_or_upper = + unicode::contains_forbidden_domain_code_point_or_upper(input.data(), + input.size()); static constexpr std::string_view xn_dash{"xn-", 3}; - if (is_forbidden == 0 && buffer.find(xn_dash) == std::string_view::npos) { - // fast path - host = std::move(buffer); - - // Check for other IPv4 formats (hex, octal, etc.) - if (checkers::is_ipv4(host.value())) { - ada_log("parse_host fast path ipv4"); - return parse_ipv4(host.value()); + if ((forbidden_or_upper & 1) == 0) { + host = std::string(input); + if ((forbidden_or_upper & 2) != 0) { + unicode::to_lower_ascii(host->data(), host->size()); + } + if (host->find('-') == std::string_view::npos || + host->find(xn_dash) == std::string_view::npos) { + if (checkers::is_ipv4(*host)) { + ada_log("parse_host fast path ipv4"); + return parse_ipv4(*host); + } + ada_log("parse_host fast path ", *host); + is_valid = true; + return true; + } + } else if (const size_t first_percent = input.find('%'); + first_percent != std::string_view::npos) { + std::string decoded = unicode::percent_decode(input, first_percent); + const uint8_t decoded_flags = + unicode::contains_forbidden_domain_code_point_or_upper(decoded.data(), + decoded.size()); + if ((decoded_flags & 1) == 0) { + if ((decoded_flags & 2) != 0) { + unicode::to_lower_ascii(decoded.data(), decoded.size()); + } + if (decoded.find('-') == std::string_view::npos || + decoded.find(xn_dash) == std::string_view::npos) { + host = std::move(decoded); + if (checkers::is_ipv4(*host)) { + return parse_ipv4(*host); + } + is_valid = true; + return true; + } } - ada_log("parse_host fast path ", *host); - is_valid = true; - return true; } ada_log("parse_host calling to_ascii"); is_valid = ada::unicode::to_ascii(host, input, input.find('%')); @@ -9761,6 +10836,10 @@ ada_really_inline void url::parse_path(std::string_view input) { return (!hash.has_value() || (hash->empty())) ? "" : "#" + hash.value(); } +bool url::needs_rollback_snapshot(size_t input_len) const noexcept { + return get_href_size() + input_len + 16 > ada::get_max_input_length(); +} + template <bool override_hostname> bool url::set_host_or_hostname(const std::string_view input) { if (has_opaque_path) { @@ -9817,9 +10896,13 @@ bool url::set_host_or_hostname(const std::string_view input) { // Set url's host to host, buffer to the empty string, and state to port // state. + // Not set_port(): its size check and rollback cover only the port. std::string_view port_buffer = new_host.substr(location + 1); - if (!port_buffer.empty()) { - set_port(port_buffer); + std::string_view digits = + port_buffer.substr(0, port_buffer.find_first_not_of("0123456789")); + if (!digits.empty() && !cannot_have_credentials_or_port()) { + parse_port(digits); + is_valid = true; // an out-of-range port is ignored } return check_url_size(); } @@ -9888,6 +10971,9 @@ bool url::set_hostname(const std::string_view input) { } bool url::set_username(const std::string_view input) { + if (helpers::overlaps(input, username)) { + return set_username(std::string(input)); + } if (cannot_have_credentials_or_port()) { return false; } @@ -9902,6 +10988,9 @@ bool url::set_username(const std::string_view input) { } bool url::set_password(const std::string_view input) { + if (helpers::overlaps(input, password)) { + return set_password(std::string(input)); + } if (cannot_have_credentials_or_port()) { return false; } @@ -9999,6 +11088,9 @@ void url::set_search(const std::string_view input) { } bool url::set_pathname(const std::string_view input) { + if (helpers::overlaps(input, path)) { + return set_pathname(std::string(input)); + } if (has_opaque_path) { return false; } @@ -10030,11 +11122,14 @@ bool url::set_protocol(const std::string_view input) { std::ranges::find_if_not(view, unicode::is_alnum_plus); if (pointer != view.end() && *pointer == ':') { - url saved_url(*this); + std::optional<url> saved_url; + if (needs_rollback_snapshot(view.size())) { + saved_url = *this; + } bool result = parse_scheme<true>( std::string_view(view.data(), pointer - view.begin())); - if (result && get_href_size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + if (result && saved_url && get_href_size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return false; } return result; @@ -10051,7 +11146,7 @@ bool url::set_href(const std::string_view input) { if (out->get_href_size() > ada::get_max_input_length()) { return false; } - *this = *out; + *this = std::move(*out); } return out.has_value(); @@ -10062,16 +11157,62 @@ bool url::set_href(const std::string_view input) { /* begin file src/parser.cpp */ #include <array> +#include <bit> +#include <charconv> +#include <cstdint> #include <cstring> #include <limits> +#include <optional> #include <ranges> +#include <string> +#include <string_view> +#include <utility> +#if ADA_NEON +#include <arm_neon.h> +#elif defined(__SSSE3__) +#include <tmmintrin.h> +#define ADA_PARSER_SSSE3 1 +#elif (defined(__x86_64__) || defined(__amd64__)) && defined(__GNUC__) && \ + !defined(_MSC_VER) +// gcc/clang honor target("ssse3"). clang-cl and MSVC do not: they still +// compile the function as SSE2, then reject always_inline _mm_shuffle_epi8. +#include <tmmintrin.h> +#define ADA_PARSER_SSSE3 1 +#define ADA_PARSER_NEED_SSSE3_TARGET 1 +#elif ADA_SSE2 +#include <emmintrin.h> +#endif +#ifndef ADA_PARSER_SSSE3 +#define ADA_PARSER_SSSE3 0 +#endif + +#ifdef ADA_PARSER_NEED_SSSE3_TARGET +// Scan loops stay on the default ISA (SSE2 for generic x86-64). pshufb lives +// in a noinline SSSE3 function so the CPU check is not inside a function the +// compiler is free to compile entirely with SSSE3 instructions. +#define ADA_PARSER_SIMD ada_really_inline +#define ADA_PARSER_SSSE3_FN __attribute__((target("ssse3"), noinline)) +#else +#define ADA_PARSER_SIMD ada_really_inline +#define ADA_PARSER_SSSE3_FN ada_really_inline +#endif + +#ifdef ADA_REGULAR_VISUAL_STUDIO +#include <intrin.h> +#endif + namespace ada::parser { -// 0 = host byte, 1 = host delimiter (/ ? #), 2 = reject +// Classification tables and 16-byte run scanners for the absolute-URL fast +// path. Inspired by oven-sh/WebKit#452 and #454: scan 16 bytes at a time +// (nibble-table pshufb/tbl when SSSE3 or NEON is available), and when the +// path/query/fragment is not already canonical, keep the parsed host and +// finish with the existing path helpers instead of re-parsing from scratch. namespace { +// 0 = host byte, 1 = host delimiter (/ ? # :), 2 = reject constexpr std::array<uint8_t, 256> k_host_class = []() consteval { std::array<uint8_t, 256> t{}; for (size_t i = 0; i < 256; ++i) { @@ -10087,11 +11228,12 @@ constexpr std::array<uint8_t, 256> k_host_class = []() consteval { t[static_cast<uint8_t>('/')] = 1; t[static_cast<uint8_t>('?')] = 1; t[static_cast<uint8_t>('#')] = 1; + t[static_cast<uint8_t>(':')] = 1; return t; }(); -// 0 = ok, 1 = ?/#, 2 = reject. Path rejects '%' so "%2e" falls through. -constexpr std::array<uint8_t, 256> k_rest = []() consteval { +// Path: 0 = copy, 1 = ?/#, 2 = needs work. Apostrophe is copyable in a path. +constexpr std::array<uint8_t, 256> k_path = []() consteval { std::array<uint8_t, 256> t{}; for (size_t i = 0; i < 256; ++i) { t[i] = 2; @@ -10103,7 +11245,7 @@ constexpr std::array<uint8_t, 256> k_rest = []() consteval { static_cast<uint8_t>('>'), static_cast<uint8_t>('`'), static_cast<uint8_t>('{'), static_cast<uint8_t>('}'), static_cast<uint8_t>('^'), static_cast<uint8_t>('\\'), - static_cast<uint8_t>('%'), static_cast<uint8_t>('\'')}) { + static_cast<uint8_t>('%')}) { t[c] = 2; } t[static_cast<uint8_t>('?')] = 1; @@ -10111,114 +11253,956 @@ constexpr std::array<uint8_t, 256> k_rest = []() consteval { return t; }(); -} // namespace - -// Fast path for already-normalized absolute http(s) URLs. noinline keeps -// the fallthrough path small (IPv4 microbenches). -template <class result_type> -ada_never_inline bool try_parse_simple_absolute(std::string_view input, - result_type& out) { - constexpr bool is_ada_url = std::is_same_v<result_type, ada::url>; - constexpr bool is_aggregator = - std::is_same_v<result_type, ada::url_aggregator>; - static_assert(is_ada_url || is_aggregator); - - const size_t len = input.size(); - if (len < 8) [[unlikely]] { - return false; +// Special-query: 0 = copy, 1 = #, 2 = needs work. Apostrophe must be encoded. +constexpr std::array<uint8_t, 256> k_query = []() consteval { + std::array<uint8_t, 256> t{}; + for (size_t i = 0; i < 256; ++i) { + t[i] = 2; } - const auto* b = reinterpret_cast<const uint8_t*>(input.data()); - - size_t pos; - ada::scheme::type scheme_type; - uint32_t protocol_end; - if (b[0] == 'h' && b[1] == 't' && b[2] == 't' && b[3] == 'p') { - if (b[4] == ':' && b[5] == '/' && b[6] == '/') { - pos = 7; - scheme_type = ada::scheme::type::HTTP; - protocol_end = 5; - } else if (len >= 8 && b[4] == 's' && b[5] == ':' && b[6] == '/' && - b[7] == '/') { - pos = 8; - scheme_type = ada::scheme::type::HTTPS; - protocol_end = 6; - } else { - return false; + for (uint8_t c = 0x21; c <= 0x7E; ++c) { + t[c] = 0; + } + for (uint8_t c : {static_cast<uint8_t>('"'), static_cast<uint8_t>('<'), + static_cast<uint8_t>('>'), static_cast<uint8_t>('\'')}) { + t[c] = 2; + } + t[static_cast<uint8_t>('#')] = 1; + return t; +}(); + +// Fragment: 0 = copy, 2 = needs work. '?' '#' '%' are copyable. +constexpr std::array<uint8_t, 256> k_hash = []() consteval { + std::array<uint8_t, 256> t{}; + for (size_t i = 0; i < 256; ++i) { + t[i] = 2; + } + for (uint8_t c = 0x21; c <= 0x7E; ++c) { + t[c] = 0; + } + for (uint8_t c : {static_cast<uint8_t>('"'), static_cast<uint8_t>('<'), + static_cast<uint8_t>('>'), static_cast<uint8_t>('`')}) { + t[c] = 2; + } + return t; +}(); + +// Nibble tables for pshufb / tbl classification (oven-sh/WebKit#454). +// A byte is a stop when low[b & 0xF] & high[b >> 4] != 0. High nibbles whose +// sixteen bytes share a stop pattern share a bit, so any set with at most +// eight distinct patterns fits. Tables are built from the scalar class +// arrays, so the vector and scalar paths cannot disagree. +struct nibble_tables { + alignas(16) uint8_t low[16]{}; + alignas(16) uint8_t high[16]{}; + bool fits{true}; +}; + +consteval nibble_tables make_stop_nibble_tables( + const std::array<uint8_t, 256>& cls) { + nibble_tables t{}; + uint16_t patterns[16]{}; + for (int hi = 0; hi < 16; ++hi) { + for (int lo = 0; lo < 16; ++lo) { + if (cls[static_cast<size_t>((hi << 4) | lo)] != 0) { + patterns[hi] = static_cast<uint16_t>(patterns[hi] | (1u << lo)); + } } - } else { - return false; } - if (pos < len && (b[pos] == '/' || b[pos] == '\\')) [[unlikely]] { - return false; + int bits_used = 0; + for (int hi = 0; hi < 16; ++hi) { + if (patterns[hi] == 0 || t.high[hi] != 0) { + continue; + } + if (bits_used == 8) { + t.fits = false; + return t; + } + const uint8_t bit = static_cast<uint8_t>(1u << bits_used++); + for (int other = hi; other < 16; ++other) { + if (patterns[other] == patterns[hi]) { + t.high[other] = static_cast<uint8_t>(t.high[other] | bit); + } + } + for (int lo = 0; lo < 16; ++lo) { + if ((patterns[hi] & (1u << lo)) != 0) { + t.low[lo] = static_cast<uint8_t>(t.low[lo] | bit); + } + } + } + return t; +} + +constexpr nibble_tables k_host_nibbles = make_stop_nibble_tables(k_host_class); +constexpr nibble_tables k_path_nibbles = make_stop_nibble_tables(k_path); +constexpr nibble_tables k_query_nibbles = make_stop_nibble_tables(k_query); +constexpr nibble_tables k_hash_nibbles = make_stop_nibble_tables(k_hash); +static_assert(k_host_nibbles.fits); +static_assert(k_path_nibbles.fits); +static_assert(k_query_nibbles.fits); +static_assert(k_hash_nibbles.fits); + +// WHATWG serializes a port as its decimal value with no leading zeros. +ada_really_inline uint32_t port_decimal_digit_count(uint32_t port) noexcept { + uint32_t digits = 1; + while (port >= 10) { + port /= 10; + ++digits; } + return digits; +} + +ada_really_inline void append_canonical_port(std::string& buffer, + uint32_t port) { + buffer += ':'; + char port_buf[5]; + auto [ptr, ec] = std::to_chars(port_buf, port_buf + 5, port); + (void)ec; + buffer.append(port_buf, static_cast<size_t>(ptr - port_buf)); +} + +ada_really_inline int trailing_zeroes32(uint32_t input_num) noexcept { +#ifdef ADA_REGULAR_VISUAL_STUDIO + unsigned long ret; + _BitScanForward(&ret, input_num); + return static_cast<int>(ret); +#else + return __builtin_ctz(input_num); +#endif +} + +ada_really_inline int trailing_zeroes64(uint64_t input_num) noexcept { +#ifdef ADA_REGULAR_VISUAL_STUDIO + unsigned long ret; + _BitScanForward64(&ret, input_num); + return static_cast<int>(ret); +#else + return __builtin_ctzll(input_num); +#endif +} - // Digit-led hosts are IPv4/numeric; skip before scanning. - if (pos < len && b[pos] >= '0' && b[pos] <= '9') { +#if ADA_PARSER_SSSE3 +ADA_PARSER_SIMD __m128i nibble_load(const uint8_t* t) noexcept { + return _mm_load_si128(reinterpret_cast<const __m128i*>(t)); +} + +// Non-zero lanes are stops. Tables are passed in so the scan loops can hoist +// the loads out of the 16-byte iteration. +ADA_PARSER_SSSE3_FN int ssse3_nibble_mask(__m128i w, __m128i lo_tbl, + __m128i hi_tbl) noexcept { + const __m128i nibble = _mm_set1_epi8(0x0F); + const __m128i lo = _mm_and_si128(w, nibble); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(w, 4), nibble); + const __m128i hit = + _mm_and_si128(_mm_shuffle_epi8(lo_tbl, lo), _mm_shuffle_epi8(hi_tbl, hi)); + return _mm_movemask_epi8(_mm_cmpeq_epi8(hit, _mm_setzero_si128())) ^ 0xFFFF; +} +#endif // ADA_PARSER_SSSE3 + +#if ADA_SSE2 +#if !ADA_PARSER_SSSE3 +// Signed < 0x21 matches 0x00-0x20 and 0x80-0xFF; 0x7F is checked separately. +ada_really_inline __m128i sse2_ctrl_or_nonascii(__m128i w) noexcept { + return _mm_or_si128(_mm_cmplt_epi8(w, _mm_set1_epi8(0x21)), + _mm_cmpeq_epi8(w, _mm_set1_epi8(0x7F))); +} + +ada_really_inline int sse2_host_stop(__m128i w) noexcept { + const __m128i ctrl = sse2_ctrl_or_nonascii(w); + const __m128i is_upper = _mm_and_si128( + _mm_cmpgt_epi8(w, _mm_set1_epi8(static_cast<char>('A' - 1))), + _mm_cmplt_epi8(w, _mm_set1_epi8(static_cast<char>('Z' + 1)))); + const __m128i at = _mm_sub_epi8(w, _mm_set1_epi8('@')); + const __m128i at_through_caret = + _mm_cmpeq_epi8(_mm_min_epu8(at, _mm_set1_epi8('^' - '@')), at); + const __m128i at_not_upper = _mm_andnot_si128(is_upper, at_through_caret); + const __m128i spec = _mm_or_si128( + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('#')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('%'))), + _mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('/')), + _mm_cmpeq_epi8(w, _mm_set1_epi8(':')))), + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('<')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('>'))), + _mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('?')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('|'))))); + return _mm_movemask_epi8( + _mm_or_si128(_mm_or_si128(ctrl, at_not_upper), spec)); +} + +ada_really_inline int sse2_path_stop(__m128i w) noexcept { + const __m128i ctrl = sse2_ctrl_or_nonascii(w); + const __m128i spec = _mm_or_si128( + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('"')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('#'))), + _mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('%')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('<')))), + _mm_or_si128( + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('>')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('?'))), + _mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('\\')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('^')))), + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('`')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('{'))), + _mm_cmpeq_epi8(w, _mm_set1_epi8('}'))))); + return _mm_movemask_epi8(_mm_or_si128(ctrl, spec)); +} + +ada_really_inline int sse2_query_stop(__m128i w) noexcept { + const __m128i ctrl = sse2_ctrl_or_nonascii(w); + const __m128i spec = _mm_or_si128( + _mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('"')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('#'))), + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('<')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('>'))), + _mm_cmpeq_epi8(w, _mm_set1_epi8('\'')))); + return _mm_movemask_epi8(_mm_or_si128(ctrl, spec)); +} + +ada_really_inline int sse2_hash_stop(__m128i w) noexcept { + const __m128i ctrl = sse2_ctrl_or_nonascii(w); + const __m128i spec = + _mm_or_si128(_mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('"')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('<'))), + _mm_or_si128(_mm_cmpeq_epi8(w, _mm_set1_epi8('>')), + _mm_cmpeq_epi8(w, _mm_set1_epi8('`')))); + return _mm_movemask_epi8(_mm_or_si128(ctrl, spec)); +} +#endif // !ADA_PARSER_SSSE3 + +ada_really_inline int sse2_uppercase(__m128i w) noexcept { + return _mm_movemask_epi8(_mm_and_si128( + _mm_cmpgt_epi8(w, _mm_set1_epi8(static_cast<char>('A' - 1))), + _mm_cmplt_epi8(w, _mm_set1_epi8(static_cast<char>('Z' + 1))))); +} +#endif // ADA_SSE2 + +#if ADA_NEON +ada_really_inline uint64_t neon_nibble_bits(uint8x16_t matches) noexcept { + const uint8x8_t nib = vshrn_n_u16(vreinterpretq_u16_u8(matches), 4); + return vget_lane_u64(vreinterpret_u64_u8(nib), 0); +} + +ada_really_inline uint64_t neon_table_stop(uint8x16_t w, uint8x16_t lo_tbl, + uint8x16_t hi_tbl) noexcept { + const uint8x16_t hit = + vandq_u8(vqtbl1q_u8(lo_tbl, vandq_u8(w, vdupq_n_u8(0x0F))), + vqtbl1q_u8(hi_tbl, vshrq_n_u8(w, 4))); + return neon_nibble_bits(vtstq_u8(hit, hit)); +} + +ada_really_inline uint64_t neon_uppercase(uint8x16_t w) noexcept { + return neon_nibble_bits( + vandq_u8(vcgeq_u8(w, vdupq_n_u8('A')), vcleq_u8(w, vdupq_n_u8('Z')))); +} +#endif // ADA_NEON + +// True when '@' appears in the authority before '/', '?', or '#'. +// One 16-byte window covers typical userinfo (SetHref's "user:pass@"). +// Longer userinfo still misses inside the never_inline fast path. No +// '@' is a single load + compare so the parse hot path stays cheap. +ada_really_inline bool authority_has_at(const uint8_t* p, size_t host_start, + size_t n) noexcept { + const size_t rem = n - host_start; + if (rem == 0) { return false; } +#if ADA_NEON + if (rem >= 16) { + const uint8x16_t w = vld1q_u8(p + host_start); + const uint64_t at = neon_nibble_bits(vceqq_u8(w, vdupq_n_u8('@'))); + if (at == 0) { + return false; + } + const uint64_t delim = neon_nibble_bits(vceqq_u8(w, vdupq_n_u8('/'))) | + neon_nibble_bits(vceqq_u8(w, vdupq_n_u8('?'))) | + neon_nibble_bits(vceqq_u8(w, vdupq_n_u8('#'))); + return delim == 0 || std::countr_zero(at) < std::countr_zero(delim); + } +#elif ADA_SSE2 + if (rem >= 16) { + const __m128i w = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(p + host_start)); + const uint16_t at = static_cast<uint16_t>( + _mm_movemask_epi8(_mm_cmpeq_epi8(w, _mm_set1_epi8('@')))); + if (at == 0) { + return false; + } + const uint16_t delim = static_cast<uint16_t>( + _mm_movemask_epi8(_mm_cmpeq_epi8(w, _mm_set1_epi8('/'))) | + _mm_movemask_epi8(_mm_cmpeq_epi8(w, _mm_set1_epi8('?'))) | + _mm_movemask_epi8(_mm_cmpeq_epi8(w, _mm_set1_epi8('#')))); + return delim == 0 || std::countr_zero(at) < std::countr_zero(delim); + } +#endif + const size_t lim = host_start + rem; + for (size_t i = host_start; i < lim; ++i) { + const uint8_t c = p[i]; + if (c == '@') { + return true; + } + if (c == '/' || c == '?' || c == '#') { + return false; + } + } + return false; +} - const size_t host_start = pos; - bool has_upper = false; - size_t i = pos; +#if ADA_PARSER_SSSE3 +// True when this process can execute the SSSE3 scanners. When the binary was +// built for SSSE3, the check is a constant. Otherwise it is cached from the +// CPU and the scanners fall back to the scalar loops below. +ada_really_inline bool parser_use_ssse3() noexcept { +#ifdef ADA_PARSER_NEED_SSSE3_TARGET + static const bool supported = __builtin_cpu_supports("ssse3") != 0; + return supported; +#else + return true; +#endif +} +#endif + +// Returns false if a forbidden host code point is found. On success, *end is +// the first / ? # or len. has_upper / has_x only count host bytes, not the +// path/query bytes that may sit in the same SIMD window after the delimiter. +ADA_PARSER_SIMD bool scan_plain_host(const uint8_t* b, size_t start, size_t len, + size_t& end, bool& has_upper, + bool& has_x) noexcept { + has_upper = false; + has_x = false; + size_t i = start; +#if ADA_PARSER_SSSE3 + if (parser_use_ssse3() && (len - start >= 16)) { + const __m128i lo_tbl = nibble_load(k_host_nibbles.low); + const __m128i hi_tbl = nibble_load(k_host_nibbles.high); + const __m128i x_splat = _mm_set1_epi8('x'); + auto visit = [&](size_t at) noexcept -> bool { + const __m128i w = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + at)); + const int up = sse2_uppercase(w); + const int xs = _mm_movemask_epi8(_mm_cmpeq_epi8(w, x_splat)); + const int mask = ssse3_nibble_mask(w, lo_tbl, hi_tbl); + if (mask == 0) { + if (up != 0) { + has_upper = true; + } + if (xs != 0) { + has_x = true; + } + return false; + } + const int hit = trailing_zeroes32(static_cast<uint32_t>(mask)); + const int valid = (1 << hit) - 1; + if ((up & valid) != 0) { + has_upper = true; + } + if ((xs & valid) != 0) { + has_x = true; + } + end = at + static_cast<size_t>(hit); + return true; + }; + for (; i + 32 <= len; i += 32) { + if (visit(i) || visit(i + 16)) { + return k_host_class[b[end]] == 1; + } + } + for (; i + 16 <= len; i += 16) { + if (visit(i)) { + return k_host_class[b[end]] == 1; + } + } + // Overlapping tail only after a full 16-byte step so the window cannot + // start before `start` (a prior '/' would otherwise look like a host stop). + if (i > start && i < len) { + if (visit(len - 16) && end >= i) { + return k_host_class[b[end]] == 1; + } + end = len; + return true; + } + } +#elif ADA_SSE2 + const __m128i x_splat = _mm_set1_epi8('x'); + for (; i + 32 <= len; i += 32) { + for (size_t off = 0; off < 32; off += 16) { + const __m128i w = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i + off)); + const int up = sse2_uppercase(w); + const int xs = _mm_movemask_epi8(_mm_cmpeq_epi8(w, x_splat)); + const int mask = sse2_host_stop(w); + if (mask != 0) { + const int hit = trailing_zeroes32(static_cast<uint32_t>(mask)); + const int valid = (1 << hit) - 1; + if ((up & valid) != 0) { + has_upper = true; + } + if ((xs & valid) != 0) { + has_x = true; + } + end = i + off + static_cast<size_t>(hit); + return k_host_class[b[end]] == 1; + } + if (up != 0) { + has_upper = true; + } + if (xs != 0) { + has_x = true; + } + } + } + for (; i + 16 <= len; i += 16) { + const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); + const int up = sse2_uppercase(w); + const int xs = _mm_movemask_epi8(_mm_cmpeq_epi8(w, x_splat)); + const int mask = sse2_host_stop(w); + if (mask != 0) { + const int hit = trailing_zeroes32(static_cast<uint32_t>(mask)); + const int valid = (1 << hit) - 1; + if ((up & valid) != 0) { + has_upper = true; + } + if ((xs & valid) != 0) { + has_x = true; + } + end = i + static_cast<size_t>(hit); + return k_host_class[b[end]] == 1; + } + if (up != 0) { + has_upper = true; + } + if (xs != 0) { + has_x = true; + } + } +#elif ADA_NEON + if (len - start >= 16) { + const uint8x16_t lo_tbl = vld1q_u8(k_host_nibbles.low); + const uint8x16_t hi_tbl = vld1q_u8(k_host_nibbles.high); + const uint8x16_t x_splat = vdupq_n_u8('x'); + auto visit = [&](size_t at) noexcept -> bool { + const uint8x16_t w = vld1q_u8(b + at); + const uint64_t up = neon_uppercase(w); + const uint64_t xs = neon_nibble_bits(vceqq_u8(w, x_splat)); + const uint64_t bits = neon_table_stop(w, lo_tbl, hi_tbl); + if (bits == 0) { + if (up != 0) { + has_upper = true; + } + if (xs != 0) { + has_x = true; + } + return false; + } + const size_t hit = static_cast<size_t>(trailing_zeroes64(bits)) >> 2; + const uint64_t valid = (hit == 0) ? 0 : (uint64_t{1} << (hit * 4)) - 1; + if ((up & valid) != 0) { + has_upper = true; + } + if ((xs & valid) != 0) { + has_x = true; + } + end = at + hit; + return true; + }; + for (; i + 32 <= len; i += 32) { + if (visit(i) || visit(i + 16)) { + return k_host_class[b[end]] == 1; + } + } + for (; i + 16 <= len; i += 16) { + if (visit(i)) { + return k_host_class[b[end]] == 1; + } + } + if (i > start && i < len) { + if (visit(len - 16) && end >= i) { + return k_host_class[b[end]] == 1; + } + end = len; + return true; + } + } +#endif for (; i < len; ++i) { const uint8_t c = b[i]; const uint8_t cls = k_host_class[c]; if (cls == 1) { - break; + end = i; + return true; } - if (cls == 2) [[unlikely]] { + if (cls == 2) { return false; } if (c >= 'A' && c <= 'Z') { has_upper = true; + } else if (c == 'x') { + has_x = true; } } - const size_t host_end = i; - if (host_start == host_end) [[unlikely]] { - return false; + end = len; + return true; +} + +ada_really_inline void note_possible_dot_segment( + const uint8_t* b, size_t pos, size_t run_start, + bool& maybe_dot_segment) noexcept { + if (pos == run_start || b[pos - 1] == '/') { + maybe_dot_segment = true; } - const size_t host_len = host_end - host_start; - if (host_len > 253) [[unlikely]] { +} + +#if ADA_PARSER_SSSE3 || ADA_SSE2 +// valid_mask selects bytes in this 16-byte window that belong to the path +// (bits after a stop are cleared). A '.' starts a possible dot-segment when +// it is the first path byte or immediately follows '/'. +ada_really_inline void note_dots_in_window(const uint8_t* b, size_t i, + size_t run_start, __m128i w, + int valid_mask, + bool& maybe_dot_segment) noexcept { + if (maybe_dot_segment || valid_mask == 0) { + return; + } + const int dots = + _mm_movemask_epi8(_mm_cmpeq_epi8(w, _mm_set1_epi8('.'))) & valid_mask; + if (dots == 0) { + return; + } + const int slashes = + _mm_movemask_epi8(_mm_cmpeq_epi8(w, _mm_set1_epi8('/'))) & valid_mask; + if (((dots & 1) != 0 && (i == run_start || b[i - 1] == '/')) || + (dots & (slashes << 1)) != 0) { + maybe_dot_segment = true; + } +} +#endif + +#if ADA_NEON +// Each NEON match nibble occupies 4 bits, so a '.' immediately after '/' is +// (slashes << 4) rather than (slashes << 1). +ada_really_inline void note_dots_in_window_neon( + const uint8_t* b, size_t i, size_t run_start, uint8x16_t w, + uint64_t valid_bits, bool& maybe_dot_segment) noexcept { + if (maybe_dot_segment || valid_bits == 0) { + return; + } + const uint64_t dots = + neon_nibble_bits(vceqq_u8(w, vdupq_n_u8('.'))) & valid_bits; + if (dots == 0) { + return; + } + const uint64_t slashes = + neon_nibble_bits(vceqq_u8(w, vdupq_n_u8('/'))) & valid_bits; + if (((dots & 0xF) != 0 && (i == run_start || b[i - 1] == '/')) || + (dots & (slashes << 4)) != 0) { + maybe_dot_segment = true; + } +} +#endif + +// Advance i to the first path-class 1 or 2 character (or len). +ADA_PARSER_SIMD void scan_path_run(const uint8_t* b, size_t& i, size_t len, + bool& maybe_dot_segment) noexcept { + const size_t run_start = i; +#if ADA_PARSER_SSSE3 + if (parser_use_ssse3() && (i + 16 <= len)) { + const __m128i lo_tbl = nibble_load(k_path_nibbles.low); + const __m128i hi_tbl = nibble_load(k_path_nibbles.high); + for (; i + 32 <= len; i += 32) { + const __m128i w0 = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); + const int m0 = ssse3_nibble_mask(w0, lo_tbl, hi_tbl); + if (m0 != 0) { + const int hit_bit = trailing_zeroes32(static_cast<uint32_t>(m0)); + note_dots_in_window(b, i, run_start, w0, (1 << hit_bit) - 1, + maybe_dot_segment); + i += static_cast<size_t>(hit_bit); + return; + } + note_dots_in_window(b, i, run_start, w0, 0xFFFF, maybe_dot_segment); + const __m128i w1 = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i + 16)); + const int m1 = ssse3_nibble_mask(w1, lo_tbl, hi_tbl); + if (m1 != 0) { + const int hit_bit = trailing_zeroes32(static_cast<uint32_t>(m1)); + note_dots_in_window(b, i + 16, run_start, w1, (1 << hit_bit) - 1, + maybe_dot_segment); + i += 16 + static_cast<size_t>(hit_bit); + return; + } + note_dots_in_window(b, i + 16, run_start, w1, 0xFFFF, maybe_dot_segment); + } + for (; i + 16 <= len; i += 16) { + const __m128i w = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); + const int mask = ssse3_nibble_mask(w, lo_tbl, hi_tbl); + if (mask != 0) { + const int hit_bit = trailing_zeroes32(static_cast<uint32_t>(mask)); + note_dots_in_window(b, i, run_start, w, (1 << hit_bit) - 1, + maybe_dot_segment); + i += static_cast<size_t>(hit_bit); + return; + } + note_dots_in_window(b, i, run_start, w, 0xFFFF, maybe_dot_segment); + } + if (i > run_start && i < len) { + const __m128i w = + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + len - 16)); + const int mask = ssse3_nibble_mask(w, lo_tbl, hi_tbl); + if (mask != 0) { + const size_t hit = + len - 16 + + static_cast<size_t>(trailing_zeroes32(static_cast<uint32_t>(mask))); + if (hit >= i) { + for (size_t j = i; j < hit; ++j) { + if (b[j] == '.') { + note_possible_dot_segment(b, j, run_start, maybe_dot_segment); + } + } + i = hit; + return; + } + } + for (size_t j = i; j < len; ++j) { + if (b[j] == '.') { + note_possible_dot_segment(b, j, run_start, maybe_dot_segment); + } + } + i = len; + return; + } + } +#elif ADA_SSE2 + for (; i + 16 <= len; i += 16) { + const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); + const int mask = sse2_path_stop(w); + if (mask != 0) { + const int hit_bit = trailing_zeroes32(static_cast<uint32_t>(mask)); + note_dots_in_window(b, i, run_start, w, (1 << hit_bit) - 1, + maybe_dot_segment); + i += static_cast<size_t>(hit_bit); + return; + } + note_dots_in_window(b, i, run_start, w, 0xFFFF, maybe_dot_segment); + } +#elif ADA_NEON + if (i + 16 <= len) { + const uint8x16_t lo_tbl = vld1q_u8(k_path_nibbles.low); + const uint8x16_t hi_tbl = vld1q_u8(k_path_nibbles.high); + for (; i + 32 <= len; i += 32) { + const uint8x16_t w0 = vld1q_u8(b + i); + const uint64_t bits0 = neon_table_stop(w0, lo_tbl, hi_tbl); + if (bits0 != 0) { + const size_t hit_off = + static_cast<size_t>(trailing_zeroes64(bits0)) >> 2; + const uint64_t valid = + (hit_off == 0) ? 0 : (uint64_t{1} << (hit_off * 4)) - 1; + note_dots_in_window_neon(b, i, run_start, w0, valid, maybe_dot_segment); + i += hit_off; + return; + } + note_dots_in_window_neon(b, i, run_start, w0, ~uint64_t{0}, + maybe_dot_segment); + const uint8x16_t w1 = vld1q_u8(b + i + 16); + const uint64_t bits1 = neon_table_stop(w1, lo_tbl, hi_tbl); + if (bits1 != 0) { + const size_t hit_off = + static_cast<size_t>(trailing_zeroes64(bits1)) >> 2; + const uint64_t valid = + (hit_off == 0) ? 0 : (uint64_t{1} << (hit_off * 4)) - 1; + note_dots_in_window_neon(b, i + 16, run_start, w1, valid, + maybe_dot_segment); + i += 16 + hit_off; + return; + } + note_dots_in_window_neon(b, i + 16, run_start, w1, ~uint64_t{0}, + maybe_dot_segment); + } + for (; i + 16 <= len; i += 16) { + const uint8x16_t w = vld1q_u8(b + i); + const uint64_t bits = neon_table_stop(w, lo_tbl, hi_tbl); + if (bits != 0) { + const size_t hit_off = + static_cast<size_t>(trailing_zeroes64(bits)) >> 2; + const uint64_t valid = + (hit_off == 0) ? 0 : (uint64_t{1} << (hit_off * 4)) - 1; + note_dots_in_window_neon(b, i, run_start, w, valid, maybe_dot_segment); + i += hit_off; + return; + } + note_dots_in_window_neon(b, i, run_start, w, ~uint64_t{0}, + maybe_dot_segment); + } + if (i > run_start && i < len) { + const uint8x16_t w = vld1q_u8(b + len - 16); + const uint64_t bits = neon_table_stop(w, lo_tbl, hi_tbl); + if (bits != 0) { + const size_t hit = + len - 16 + (static_cast<size_t>(trailing_zeroes64(bits)) >> 2); + if (hit >= i) { + for (size_t j = i; j < hit; ++j) { + if (b[j] == '.') { + note_possible_dot_segment(b, j, run_start, maybe_dot_segment); + } + } + i = hit; + return; + } + } + for (size_t j = i; j < len; ++j) { + if (b[j] == '.') { + note_possible_dot_segment(b, j, run_start, maybe_dot_segment); + } + } + i = len; + return; + } + } +#endif + for (; i < len; ++i) { + const uint8_t c = b[i]; + const uint8_t cls = k_path[c]; + if (cls != 0) { + return; + } + if (c == '.') { + note_possible_dot_segment(b, i, run_start, maybe_dot_segment); + } + } +} + +// Advance i to the first class-table stop (or len). Query and hash share +// this loop; path keeps its own copy because it also tracks '.' segments. +#if ADA_PARSER_SSSE3 +#define ADA_SCAN_STOP_RUN(nibbles, cls, unused_sse2_stop) \ + do { \ + const size_t scan_start = i; \ + if (parser_use_ssse3() && (i + 16 <= len)) { \ + const __m128i lo_tbl = nibble_load((nibbles).low); \ + const __m128i hi_tbl = nibble_load((nibbles).high); \ + for (; i + 32 <= len; i += 32) { \ + const __m128i w0 = \ + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); \ + const int m0 = ssse3_nibble_mask(w0, lo_tbl, hi_tbl); \ + if (m0 != 0) { \ + i += static_cast<size_t>( \ + trailing_zeroes32(static_cast<uint32_t>(m0))); \ + return; \ + } \ + const __m128i w1 = \ + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i + 16)); \ + const int m1 = ssse3_nibble_mask(w1, lo_tbl, hi_tbl); \ + if (m1 != 0) { \ + i += 16 + static_cast<size_t>( \ + trailing_zeroes32(static_cast<uint32_t>(m1))); \ + return; \ + } \ + } \ + for (; i + 16 <= len; i += 16) { \ + const __m128i w = \ + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); \ + const int mask = ssse3_nibble_mask(w, lo_tbl, hi_tbl); \ + if (mask != 0) { \ + i += static_cast<size_t>( \ + trailing_zeroes32(static_cast<uint32_t>(mask))); \ + return; \ + } \ + } \ + if (i > scan_start && i < len) { \ + const __m128i w = \ + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + len - 16)); \ + const int mask = ssse3_nibble_mask(w, lo_tbl, hi_tbl); \ + if (mask != 0) { \ + const size_t hit = len - 16 + \ + static_cast<size_t>(trailing_zeroes32( \ + static_cast<uint32_t>(mask))); \ + if (hit >= i) { \ + i = hit; \ + return; \ + } \ + } \ + i = len; \ + return; \ + } \ + } \ + for (; i < len; ++i) { \ + if ((cls)[b[i]] != 0) { \ + return; \ + } \ + } \ + } while (0) +#elif ADA_NEON +#define ADA_SCAN_STOP_RUN(nibbles, cls, unused_sse2_stop) \ + do { \ + const size_t scan_start = i; \ + if (i + 16 <= len) { \ + const uint8x16_t lo_tbl = vld1q_u8((nibbles).low); \ + const uint8x16_t hi_tbl = vld1q_u8((nibbles).high); \ + for (; i + 32 <= len; i += 32) { \ + const uint64_t bits0 = \ + neon_table_stop(vld1q_u8(b + i), lo_tbl, hi_tbl); \ + if (bits0 != 0) { \ + i += static_cast<size_t>(trailing_zeroes64(bits0)) >> 2; \ + return; \ + } \ + const uint64_t bits1 = \ + neon_table_stop(vld1q_u8(b + i + 16), lo_tbl, hi_tbl); \ + if (bits1 != 0) { \ + i += 16 + (static_cast<size_t>(trailing_zeroes64(bits1)) >> 2); \ + return; \ + } \ + } \ + for (; i + 16 <= len; i += 16) { \ + const uint8x16_t w = vld1q_u8(b + i); \ + const uint64_t bits = neon_table_stop(w, lo_tbl, hi_tbl); \ + if (bits != 0) { \ + i += static_cast<size_t>(trailing_zeroes64(bits)) >> 2; \ + return; \ + } \ + } \ + if (i > scan_start && i < len) { \ + const uint8x16_t w = vld1q_u8(b + len - 16); \ + const uint64_t bits = neon_table_stop(w, lo_tbl, hi_tbl); \ + if (bits != 0) { \ + const size_t hit = \ + len - 16 + (static_cast<size_t>(trailing_zeroes64(bits)) >> 2); \ + if (hit >= i) { \ + i = hit; \ + return; \ + } \ + } \ + i = len; \ + return; \ + } \ + } \ + for (; i < len; ++i) { \ + if ((cls)[b[i]] != 0) { \ + return; \ + } \ + } \ + } while (0) +#elif ADA_SSE2 +#define ADA_SCAN_STOP_RUN(nibbles, cls, sse2_stop) \ + do { \ + for (; i + 16 <= len; i += 16) { \ + const __m128i w = \ + _mm_loadu_si128(reinterpret_cast<const __m128i*>(b + i)); \ + const int mask = sse2_stop(w); \ + if (mask != 0) { \ + i += static_cast<size_t>( \ + trailing_zeroes32(static_cast<uint32_t>(mask))); \ + return; \ + } \ + } \ + for (; i < len; ++i) { \ + if ((cls)[b[i]] != 0) { \ + return; \ + } \ + } \ + } while (0) +#else +#define ADA_SCAN_STOP_RUN(nibbles, cls, unused_sse2_stop) \ + do { \ + for (; i < len; ++i) { \ + if ((cls)[b[i]] != 0) { \ + return; \ + } \ + } \ + } while (0) +#endif + +ADA_PARSER_SIMD void scan_query_run(const uint8_t* b, size_t& i, + size_t len) noexcept { + ADA_SCAN_STOP_RUN(k_query_nibbles, k_query, sse2_query_stop); +} + +ADA_PARSER_SIMD void scan_hash_run(const uint8_t* b, size_t& i, + size_t len) noexcept { + ADA_SCAN_STOP_RUN(k_hash_nibbles, k_hash, sse2_hash_stop); +} + +#undef ADA_SCAN_STOP_RUN + +bool path_has_dot_segment(std::string_view path) noexcept { + if (path.empty()) { return false; } - { - std::string_view hv(input.data() + host_start, host_len); - char host_buf[256]; - if (has_upper) [[unlikely]] { - std::memcpy(host_buf, input.data() + host_start, host_len); - unicode::to_lower_ascii(host_buf, host_len); - hv = std::string_view(host_buf, host_len); + // "." / ".." at the start, with or without a leading '/'. + const size_t i = (path[0] == '/') ? 1 : 0; + if (i < path.size() && path[i] == '.') { + const size_t after = i + 1; + if (after == path.size() || path[after] == '/' || + (after < path.size() && path[after] == '.' && + (after + 1 == path.size() || path[after + 1] == '/'))) { + return true; } - if (checkers::is_ipv4(hv)) [[unlikely]] { - return false; + } + static constexpr std::string_view slash_dot{"/.", 2}; + size_t p = i; + while ((p = path.find(slash_dot, p)) != std::string_view::npos) { + const size_t after = p + 2; + if (after == path.size() || path[after] == '/' || + (after < path.size() && path[after] == '.' && + (after + 1 == path.size() || path[after + 1] == '/'))) { + return true; } - static constexpr std::string_view xn{"xn-", 3}; - if (hv.find(xn) != std::string_view::npos) [[unlikely]] { + p = after; + } + return false; +} + +} // namespace + +template <class result_type> +ada_never_inline bool finish_simple_absolute_with_port( + std::string_view input, result_type& out, ada::scheme::type scheme_type, + uint32_t protocol_end, size_t host_start, size_t host_end, size_t host_len, + bool has_upper) { + constexpr bool is_ada_url = std::is_same_v<result_type, ada::url>; + constexpr bool is_aggregator = + std::is_same_v<result_type, ada::url_aggregator>; + static_assert(is_ada_url || is_aggregator); + + const size_t len = input.size(); + const auto* b = reinterpret_cast<const uint8_t*>(input.data()); + size_t p = host_end + 1; + uint32_t port_value = 0; + bool any_digit = false; + while (p < len && b[p] >= '0' && b[p] <= '9') { + any_digit = true; + port_value = port_value * 10 + static_cast<uint32_t>(b[p] - '0'); + if (port_value > 65535) [[unlikely]] { return false; } + ++p; + } + if (p < len && b[p] != '/' && b[p] != '?' && b[p] != '#') [[unlikely]] { + return false; + } + uint32_t parsed_port = url_components::omitted; + const uint16_t default_port = ada::scheme::get_special_port(scheme_type); + if (any_digit && port_value != default_port) { + parsed_port = port_value; } + const size_t authority_end = p; + size_t i = authority_end; size_t path_start = host_end; size_t path_end = host_end; size_t query_start = std::string_view::npos; size_t hash_start = std::string_view::npos; bool has_path = false; - bool path_has_dot = false; + bool maybe_dot_segment = false; + bool rest_simple = true; if (i < len && b[i] == '/') { has_path = true; path_start = i; ++i; - for (; i < len; ++i) { - const uint8_t c = b[i]; - const uint8_t cls = k_rest[c]; - if (cls == 0) { - path_has_dot |= (c == '.'); - continue; - } + scan_path_run(b, i, len, maybe_dot_segment); + if (i < len) { + const uint8_t cls = k_path[b[i]]; if (cls == 1) { path_end = i; - if (c == '?') { + if (b[i] == '?') { query_start = i; ++i; goto scan_query; @@ -10227,7 +12211,23 @@ ada_never_inline bool try_parse_simple_absolute(std::string_view input, ++i; goto scan_hash; } - return false; + rest_simple = false; + for (; i < len; ++i) { + if (b[i] == '?') { + path_end = i; + query_start = i; + ++i; + goto scan_query_boundary; + } + if (b[i] == '#') { + path_end = i; + hash_start = i; + ++i; + goto after_rest; + } + } + path_end = i; + goto after_rest; } path_end = i; } else if (i < len && b[i] == '?') { @@ -10242,71 +12242,500 @@ ada_never_inline bool try_parse_simple_absolute(std::string_view input, goto after_rest; scan_query: - for (; i < len; ++i) { - const uint8_t c = b[i]; - if (c == '#') { + scan_query_run(b, i, len); + if (i < len) { + if (b[i] == '#') { hash_start = i; ++i; goto scan_hash; } - if (c == '?' || c == '%') { - continue; - } - if (k_rest[c] == 2) [[unlikely]] { - return false; - } + rest_simple = false; + goto scan_query_boundary; } goto after_rest; -scan_hash: +scan_query_boundary: for (; i < len; ++i) { - const uint8_t c = b[i]; - if (c == '?' || c == '#' || c == '%') { - continue; - } - if (k_rest[c] == 2) [[unlikely]] { - return false; + if (b[i] == '#') { + hash_start = i; + ++i; + goto after_rest; } } + goto after_rest; + +scan_hash: + scan_hash_run(b, i, len); + if (i < len) { + rest_simple = false; + } after_rest: - if (path_has_dot) [[unlikely]] { + if (rest_simple && maybe_dot_segment) { const std::string_view path_body(input.data() + path_start, path_end - path_start); - if (path_body.size() >= 2 && path_body[1] == '.') { - if (path_body.size() == 2 || path_body[2] == '/' || - (path_body.size() >= 3 && path_body[2] == '.' && - (path_body.size() == 3 || path_body[3] == '/'))) { - return false; + if (path_has_dot_segment(path_body)) { + rest_simple = false; + } + } + + // The slow path removes ASCII tab/newline anywhere in the input and trims a + // trailing C0 control or space; this fast path does neither. A query or + // fragment reaching the helpers below would keep those bytes percent-encoded + // ("?a\nb" -> "?a%0Ab", "#f " -> "#f%20") instead of stripped, so hand such + // inputs back to the slow path. + if (!rest_simple && (unicode::is_c0_control_or_space(input.back()) || + unicode::has_tabs_or_newline(input))) { + return false; + } + + out.type = scheme_type; + out.is_valid = true; + out.has_opaque_path = false; + out.host_type = DEFAULT; + + const uint32_t port_bytes = (parsed_port != url_components::omitted) + ? (1 + port_decimal_digit_count(parsed_port)) + : 0; + + if (!rest_simple) { + const std::string_view path_view = + has_path + ? std::string_view(input.data() + path_start, path_end - path_start) + : std::string_view{}; + auto apply_query_and_hash = [&]() { + if (query_start != std::string_view::npos) { + const size_t q_end = + (hash_start != std::string_view::npos) ? hash_start : len; + out.update_base_search(std::string_view(input.data() + query_start + 1, + q_end - query_start - 1), + character_sets::SPECIAL_QUERY_PERCENT_ENCODE); + } + if (hash_start != std::string_view::npos) { + out.update_unencoded_base_hash(std::string_view( + input.data() + hash_start + 1, len - hash_start - 1)); + } + }; + if constexpr (is_aggregator) { + out.buffer.assign(input.substr(0, host_end)); + if (parsed_port != url_components::omitted) { + append_canonical_port(out.buffer, parsed_port); + } + if (has_upper) { + unicode::to_lower_ascii(out.buffer.data() + host_start, host_len); + } + out.components.protocol_end = protocol_end; + out.components.username_end = protocol_end + 2; + out.components.host_start = protocol_end + 2; + out.components.host_end = static_cast<uint32_t>(host_end); + out.components.port = parsed_port; + out.components.pathname_start = static_cast<uint32_t>(out.buffer.size()); + out.components.search_start = url_components::omitted; + out.components.hash_start = url_components::omitted; + out.parse_path(path_view); + apply_query_and_hash(); + } else { + std::string host_str(input.substr(host_start, host_len)); + if (has_upper) { + unicode::to_lower_ascii(host_str.data(), host_str.size()); } + out.host = std::move(host_str); + if (parsed_port != url_components::omitted) { + out.port = static_cast<uint16_t>(parsed_port); + } + out.parse_path(path_view); + apply_query_and_hash(); } - static constexpr std::string_view slash_dot{"/.", 2}; - size_t p = 1; - while ((p = path_body.find(slash_dot, p)) != std::string_view::npos) { - const size_t after = p + 2; - if (after == path_body.size() || path_body[after] == '/' || - (after + 1 <= path_body.size() && path_body[after] == '.' && - (after + 1 == path_body.size() || path_body[after + 1] == '/'))) { - return false; + return true; + } + + const bool insert_slash = !has_path; + if constexpr (is_aggregator) { + const size_t out_len = + host_end + port_bytes + (insert_slash ? 1 : 0) + (len - authority_end); + const bool omit_port_bytes = parsed_port == url_components::omitted; + if (out_len == len && !insert_slash && !omit_port_bytes) { + out.buffer.assign(input); + } else { + out.buffer.clear(); + out.buffer.reserve(out_len); + out.buffer.append(input.substr(0, host_end)); + if (parsed_port != url_components::omitted) { + append_canonical_port(out.buffer, parsed_port); + } + if (insert_slash) { + out.buffer.push_back('/'); } - p = after; + if (authority_end < len) { + out.buffer.append(input.substr(authority_end)); + } + } + if (has_upper) { + unicode::to_lower_ascii(out.buffer.data() + host_start, host_len); + } + const uint32_t pathname_start = + static_cast<uint32_t>(host_end) + port_bytes; + const int32_t tail_delta = static_cast<int32_t>(pathname_start) + + (insert_slash ? 1 : 0) - + static_cast<int32_t>(authority_end); + out.components.protocol_end = protocol_end; + out.components.username_end = protocol_end + 2; + out.components.host_start = protocol_end + 2; + out.components.host_end = static_cast<uint32_t>(host_end); + out.components.port = parsed_port; + out.components.pathname_start = pathname_start; + out.components.search_start = + (query_start != std::string_view::npos) + ? static_cast<uint32_t>(static_cast<int32_t>(query_start) + + tail_delta) + : url_components::omitted; + out.components.hash_start = + (hash_start != std::string_view::npos) + ? static_cast<uint32_t>(static_cast<int32_t>(hash_start) + + tail_delta) + : url_components::omitted; + } else { + std::string host_str(input.substr(host_start, host_len)); + if (has_upper) { + unicode::to_lower_ascii(host_str.data(), host_str.size()); + } + out.host = std::move(host_str); + if (parsed_port != url_components::omitted) { + out.port = static_cast<uint16_t>(parsed_port); + } + if (insert_slash) { + out.path = "/"; + } else { + out.path.assign(input.data() + path_start, path_end - path_start); + } + if (query_start != std::string_view::npos) { + const size_t q_end = + (hash_start != std::string_view::npos) ? hash_start : len; + out.query.emplace(input.data() + query_start + 1, + q_end - query_start - 1); + } + if (hash_start != std::string_view::npos) { + out.hash.emplace(input.data() + hash_start + 1, len - hash_start - 1); } } + return true; +} + +// Fast path for already-canonical special-scheme URLs of the shape +// scheme://host[/path][?query][#fragment]. When the host is a plain domain +// but the rest needs encoding or dot-segment normalization, the host is +// kept and the path/query/hash helpers finish the URL. +template <class result_type> +ada_never_inline bool try_parse_simple_absolute(std::string_view input, + result_type& out) { + constexpr bool is_ada_url = std::is_same_v<result_type, ada::url>; + constexpr bool is_aggregator = + std::is_same_v<result_type, ada::url_aggregator>; + static_assert(is_ada_url || is_aggregator); + + const size_t len = input.size(); + // Shortest accepted form is "ws://x" (6). + if (len < 6) [[unlikely]] { + return false; + } + const auto* b = reinterpret_cast<const uint8_t*>(input.data()); + + size_t pos = 0; + ada::scheme::type scheme_type = ada::scheme::type::NOT_SPECIAL; + uint32_t protocol_end = 0; +#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || \ + defined(_M_X64) || defined(_M_IX86) || defined(_M_AMD64) + // One 8-byte load + integer compare is a single cmp/jcc on x86-64. + // Masked compares cover the shorter special schemes without extra loads. + if (len >= 8) { + uint64_t first8 = 0; + std::memcpy(&first8, b, 8); + if (first8 == 0x2f2f3a7370747468ull) { // "https://" + pos = 8; + scheme_type = ada::scheme::type::HTTPS; + protocol_end = 6; + } else if ((first8 & 0x00ffffffffffffffull) == + 0x002f2f3a70747468ull) { // "http://" + pos = 7; + scheme_type = ada::scheme::type::HTTP; + protocol_end = 5; + } else if ((first8 & 0x0000ffffffffffffull) == + 0x00002f2f3a737377ull) { // "wss://" + pos = 6; + scheme_type = ada::scheme::type::WSS; + protocol_end = 4; + } else if ((first8 & 0x0000ffffffffffffull) == + 0x00002f2f3a707466ull) { // "ftp://" + pos = 6; + scheme_type = ada::scheme::type::FTP; + protocol_end = 4; + } else if ((first8 & 0x000000ffffffffffull) == + 0x0000002f2f3a7377ull) { // "ws://" + pos = 5; + scheme_type = ada::scheme::type::WS; + protocol_end = 3; + } else { + return false; + } + } else if (b[0] == 'w' && b[1] == 's') { + if (b[2] == ':' && b[3] == '/' && b[4] == '/') { + pos = 5; + scheme_type = ada::scheme::type::WS; + protocol_end = 3; + } else if (b[2] == 's' && b[3] == ':' && b[4] == '/' && b[5] == '/') { + pos = 6; + scheme_type = ada::scheme::type::WSS; + protocol_end = 4; + } else { + return false; + } + } else if (b[0] == 'f' && b[1] == 't' && b[2] == 'p' && b[3] == ':' && + b[4] == '/' && b[5] == '/') { + pos = 6; + scheme_type = ada::scheme::type::FTP; + protocol_end = 4; + } else if (len >= 7 && b[0] == 'h' && b[1] == 't' && b[2] == 't' && + b[3] == 'p' && b[4] == ':' && b[5] == '/' && b[6] == '/') { + pos = 7; + scheme_type = ada::scheme::type::HTTP; + protocol_end = 5; + } else { + return false; + } +#else + // Big-endian / uncommon arches: byte-wise special-scheme match. + if (len >= 8 && b[0] == 'h' && b[1] == 't' && b[2] == 't' && b[3] == 'p' && + b[4] == 's' && b[5] == ':' && b[6] == '/' && b[7] == '/') { + pos = 8; + scheme_type = ada::scheme::type::HTTPS; + protocol_end = 6; + } else if (len >= 7 && b[0] == 'h' && b[1] == 't' && b[2] == 't' && + b[3] == 'p' && b[4] == ':' && b[5] == '/' && b[6] == '/') { + pos = 7; + scheme_type = ada::scheme::type::HTTP; + protocol_end = 5; + } else if (b[0] == 'w' && b[1] == 's') { + if (b[2] == ':' && b[3] == '/' && b[4] == '/') { + pos = 5; + scheme_type = ada::scheme::type::WS; + protocol_end = 3; + } else if (len >= 6 && b[2] == 's' && b[3] == ':' && b[4] == '/' && + b[5] == '/') { + pos = 6; + scheme_type = ada::scheme::type::WSS; + protocol_end = 4; + } else { + return false; + } + } else if (b[0] == 'f' && b[1] == 't' && b[2] == 'p' && b[3] == ':' && + b[4] == '/' && b[5] == '/') { + pos = 6; + scheme_type = ada::scheme::type::FTP; + protocol_end = 4; + } else { + return false; + } +#endif + if (pos < len && (b[pos] == '/' || b[pos] == '\\')) [[unlikely]] { + return false; + } + + // Digit-led hosts are IPv4/numeric; '[' is IPv6. Skip before scanning. + if (pos < len && ((b[pos] >= '0' && b[pos] <= '9') || b[pos] == '[')) { + return false; + } + + const size_t host_start = pos; + bool has_upper = false; + bool has_x = false; + size_t host_end = pos; + if (!scan_plain_host(b, pos, len, host_end, has_upper, has_x)) { + return false; + } + if (host_start == host_end) [[unlikely]] { + return false; + } + const size_t host_len = host_end - host_start; + if (host_len > 253) [[unlikely]] { + return false; + } + { + std::string_view hv(input.data() + host_start, host_len); + char host_buf[256]; + if (has_upper) [[unlikely]] { + std::memcpy(host_buf, input.data() + host_start, host_len); + unicode::to_lower_ascii(host_buf, host_len); + hv = std::string_view(host_buf, host_len); + } + if (ada::checkers::last_label_may_be_a_number(hv)) [[unlikely]] { + return false; + } + // Punycode is "xn--...". The host scan already notes a lowercase 'x'; + // uppercase 'X' is covered by has_upper after the in-place lower. + static constexpr std::string_view xn{"xn-", 3}; + if ((has_x || has_upper) && hv.find(xn) != std::string_view::npos) + [[unlikely]] { + return false; + } + } + + if (host_end < len && b[host_end] == ':') [[unlikely]] { + return finish_simple_absolute_with_port(input, out, scheme_type, + protocol_end, host_start, host_end, + host_len, has_upper); + } + + size_t i = host_end; + size_t path_start = host_end; + size_t path_end = host_end; + size_t query_start = std::string_view::npos; + size_t hash_start = std::string_view::npos; + bool has_path = false; + bool maybe_dot_segment = false; + bool rest_simple = true; + + if (i < len && b[i] == '/') { + has_path = true; + path_start = i; + ++i; + scan_path_run(b, i, len, maybe_dot_segment); + if (i < len) { + const uint8_t cls = k_path[b[i]]; + if (cls == 1) { + path_end = i; + if (b[i] == '?') { + query_start = i; + ++i; + goto scan_query; + } + hash_start = i; + ++i; + goto scan_hash; + } + rest_simple = false; + hash_start = input.find('#', i); + query_start = input.substr(0, hash_start).find('?', i); + if (query_start != std::string_view::npos) { + path_end = query_start; + } else { + path_end = hash_start != std::string_view::npos ? hash_start : len; + } + goto after_rest; + } + path_end = i; + } else if (i < len && b[i] == '?') { + query_start = i; + ++i; + goto scan_query; + } else if (i < len && b[i] == '#') { + hash_start = i; + ++i; + goto scan_hash; + } + goto after_rest; + +scan_query: + scan_query_run(b, i, len); + if (i < len) { + if (b[i] == '#') { + hash_start = i; + ++i; + goto scan_hash; + } + rest_simple = false; + goto scan_query_boundary; + } + goto after_rest; + +scan_query_boundary: + hash_start = input.find('#', i); + goto after_rest; + +scan_hash: + scan_hash_run(b, i, len); + if (i < len) { + rest_simple = false; + } + +after_rest: + if (rest_simple && maybe_dot_segment) { + const std::string_view path_body(input.data() + path_start, + path_end - path_start); + if (path_has_dot_segment(path_body)) { + rest_simple = false; + } + } + + // The slow path removes ASCII tab/newline anywhere in the input and trims a + // trailing C0 control or space; this fast path does neither. A query or + // fragment reaching the helpers below would keep those bytes percent-encoded + // ("?a\nb" -> "?a%0Ab", "#f " -> "#f%20") instead of stripped, so hand such + // inputs back to the slow path. + if (!rest_simple && (unicode::is_c0_control_or_space(input.back()) || + unicode::has_tabs_or_newline(input))) { + return false; + } - const bool need_slash = !has_path; out.type = scheme_type; out.is_valid = true; out.has_opaque_path = false; out.host_type = DEFAULT; + if (!rest_simple) { + // Host is a plain domain. Finish path/query/hash with + // the regular helpers + // so percent-encoding and dot segments do not re-parse the authority. + const std::string_view path_view = + has_path + ? std::string_view(input.data() + path_start, path_end - path_start) + : std::string_view{}; + auto apply_query_and_hash = [&]() { + if (query_start != std::string_view::npos) { + const size_t q_end = + (hash_start != std::string_view::npos) ? hash_start : len; + out.update_base_search(std::string_view(input.data() + query_start + 1, + q_end - query_start - 1), + character_sets::SPECIAL_QUERY_PERCENT_ENCODE); + } + if (hash_start != std::string_view::npos) { + out.update_unencoded_base_hash(std::string_view( + input.data() + hash_start + 1, len - hash_start - 1)); + } + }; + if constexpr (is_aggregator) { + out.buffer.assign(input.substr(0, host_end)); + if (has_upper) { + unicode::to_lower_ascii(out.buffer.data() + host_start, host_len); + } + out.components.protocol_end = protocol_end; + out.components.username_end = protocol_end + 2; + out.components.host_start = protocol_end + 2; + out.components.host_end = static_cast<uint32_t>(host_end); + out.components.port = url_components::omitted; + out.components.pathname_start = static_cast<uint32_t>(host_end); + out.components.search_start = url_components::omitted; + out.components.hash_start = url_components::omitted; + out.parse_path(path_view); + apply_query_and_hash(); + } else { + std::string host_str(input.substr(host_start, host_len)); + if (has_upper) { + unicode::to_lower_ascii(host_str.data(), host_str.size()); + } + out.host = std::move(host_str); + out.parse_path(path_view); + apply_query_and_hash(); + } + return true; + } + + const bool need_slash = !has_path; if constexpr (is_aggregator) { if (!need_slash) { - out.buffer.resize(len); - // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage) - std::memcpy(out.buffer.data(), input.data(), len); + // assign copies once. resize()+memcpy would value-init then overwrite. + out.buffer.assign(input); if (has_upper) { - unicode::to_lower_ascii(out.buffer.data() + host_start, - host_end - host_start); + unicode::to_lower_ascii(out.buffer.data() + host_start, host_len); } out.components.protocol_end = protocol_end; out.components.username_end = protocol_end + 2; @@ -10321,17 +12750,15 @@ ada_never_inline bool try_parse_simple_absolute(std::string_view input, ? static_cast<uint32_t>(hash_start) : url_components::omitted; } else { - out.buffer.resize(len + 1); - // NOLINTNEXTLINE(bugprone-suspicious-stringview-data-usage) - std::memcpy(out.buffer.data(), input.data(), host_end); - out.buffer[host_end] = '/'; + out.buffer.clear(); + out.buffer.reserve(len + 1); + out.buffer.append(input.substr(0, host_end)); + out.buffer.push_back('/'); if (host_end < len) { - std::memcpy(out.buffer.data() + host_end + 1, input.data() + host_end, - len - host_end); + out.buffer.append(input.substr(host_end)); } if (has_upper) { - unicode::to_lower_ascii(out.buffer.data() + host_start, - host_end - host_start); + unicode::to_lower_ascii(out.buffer.data() + host_start, host_len); } out.components.protocol_end = protocol_end; out.components.username_end = protocol_end + 2; @@ -10347,7 +12774,7 @@ ada_never_inline bool try_parse_simple_absolute(std::string_view input, : url_components::omitted; } } else { - std::string host_str(input.substr(host_start, host_end - host_start)); + std::string host_str(input.substr(host_start, host_len)); if (has_upper) { unicode::to_lower_ascii(host_str.data(), host_str.size()); } @@ -10370,37 +12797,244 @@ ada_never_inline bool try_parse_simple_absolute(std::string_view input, return true; } -template <class result_type, bool store_values> -result_type parse_url_impl(std::string_view user_input, - const result_type* base_url) { - // We can specialize the implementation per type. - // Important: result_type_is_ada_url is evaluated at *compile time*. This - // means that doing if constexpr(result_type_is_ada_url) { something } else { - // something else } is free (at runtime). This means that ada::url_aggregator - // and ada::url **do not have to support the exact same API**. - constexpr bool result_type_is_ada_url = std::is_same_v<url, result_type>; - constexpr bool result_type_is_ada_url_aggregator = - std::is_same_v<url_aggregator, result_type>; - static_assert(result_type_is_ada_url || - result_type_is_ada_url_aggregator); // We don't support - // anything else for now. - - ada_log("ada::parser::parse_url('", user_input, "' [", user_input.size(), - " bytes],", (base_url != nullptr ? base_url->to_string() : "null"), - ")"); - - state state = state::SCHEME_START; - result_type url{}; - - const uint32_t max_input_length = ada::get_max_input_length(); +// Fast path for `/path`, path-relative (`foo`, `c/d?q`), `?query`, and +// `#fragment` against a special-scheme base. Scheme-relative (`//`) and +// scheme-like first segments (`foo:bar`) stay on the state machine. +template <class result_type> +ada_never_inline bool try_parse_simple_relative(std::string_view input, + const result_type& base, + result_type& out) { + constexpr bool is_ada_url = std::is_same_v<result_type, ada::url>; + constexpr bool is_aggregator = + std::is_same_v<result_type, ada::url_aggregator>; + static_assert(is_ada_url || is_aggregator); - // We refuse to parse URL strings that exceed the maximum input length. - // By default, this is 4GB but can be configured via - // ada::set_max_input_length(). - if (user_input.size() > max_input_length) [[unlikely]] { - url.is_valid = false; + if (!base.is_special() || base.type == ada::scheme::type::FILE || + base.has_opaque_path || input.empty()) { + return false; } - // Going forward, user_input.size() is in [0, + const auto* b = reinterpret_cast<const uint8_t*>(input.data()); + const size_t len = input.size(); + const uint8_t first = b[0]; + const bool path_relative = first != '/' && first != '?' && first != '#'; + if (first == '/' && len > 1 && (b[1] == '/' || b[1] == '\\')) { + return false; + } + // A ':' before the first / ? # is a scheme, not a path segment. + if (path_relative) { + const size_t delim = input.find_first_of("/?#:"); + if (delim != std::string_view::npos && input[delim] == ':') { + return false; + } + } + + size_t i = 0; + size_t path_start = 0; + size_t path_end = 0; + size_t query_start = std::string_view::npos; + size_t hash_start = std::string_view::npos; + bool has_path = false; + bool maybe_dot_segment = false; + + if (first == '/' || path_relative) { + has_path = true; + path_start = 0; + if (first == '/') { + i = 1; + } + scan_path_run(b, i, len, maybe_dot_segment); + if (i < len) { + const uint8_t cls = k_path[b[i]]; + if (cls == 2) { + return false; + } + } + path_end = i; + if (i < len && b[i] == '?') { + query_start = i; + ++i; + scan_query_run(b, i, len); + if (i < len) { + if (b[i] != '#') { + return false; + } + hash_start = i; + ++i; + scan_hash_run(b, i, len); + if (i < len) { + return false; + } + } + } else if (i < len && b[i] == '#') { + hash_start = i; + ++i; + scan_hash_run(b, i, len); + if (i < len) { + return false; + } + } else if (i < len) { + return false; + } + } else if (first == '?') { + query_start = 0; + i = 1; + scan_query_run(b, i, len); + if (i < len) { + if (b[i] != '#') { + return false; + } + hash_start = i; + ++i; + scan_hash_run(b, i, len); + if (i < len) { + return false; + } + } + } else { + hash_start = 0; + i = 1; + scan_hash_run(b, i, len); + if (i < len) { + return false; + } + } + + if (has_path && maybe_dot_segment) { + const std::string_view path_body(input.data() + path_start, + path_end - path_start); + if (path_has_dot_segment(path_body)) { + return false; + } + } + + out = base; + out.is_valid = true; + out.has_opaque_path = false; + + const size_t q_end = + (hash_start != std::string_view::npos) ? hash_start : len; + const bool has_query = query_start != std::string_view::npos; + const bool has_hash = hash_start != std::string_view::npos; + const std::string_view query = + has_query ? std::string_view(input.data() + query_start + 1, + q_end - query_start - 1) + : std::string_view{}; + const std::string_view hash = + has_hash ? std::string_view(input.data() + hash_start + 1, + len - hash_start - 1) + : std::string_view{}; + + if constexpr (is_aggregator) { + if (first == '/' || first == '?' || path_relative) { + out.clear_hash(); + out.clear_search(); + } + if (first == '/') { + out.update_base_pathname(input.substr(path_start, path_end - path_start)); + } else if (path_relative) { + const std::string_view base_path = out.get_pathname(); + const size_t slash = base_path.rfind('/'); + const std::string_view prefix = (slash == std::string_view::npos) + ? std::string_view("/") + : base_path.substr(0, slash + 1); + const std::string_view rel(input.data() + path_start, + path_end - path_start); + std::string new_path; + new_path.reserve(prefix.size() + rel.size()); + new_path.assign(prefix); + new_path.append(rel); + out.update_base_pathname(new_path); + } + if (has_query) { + // Do not use update_base_search: it strips a leading '?' and would + // collapse '??a=b' into '?a=b'. + out.components.search_start = static_cast<uint32_t>(out.buffer.size()); + out.buffer += '?'; + out.buffer.append(query); + } + if (has_hash) { + out.update_unencoded_base_hash(hash); + } + } else { + if (first == '/' || first == '?' || path_relative) { + out.hash.reset(); + } + if (first == '/') { + out.query.reset(); + out.path.assign(input.substr(path_start, path_end - path_start)); + } else if (path_relative) { + out.query.reset(); + const size_t slash = out.path.rfind('/'); + if (slash == std::string::npos) { + out.path = '/'; + } else { + out.path.resize(slash + 1); + } + out.path.append(input.substr(path_start, path_end - path_start)); + } + if (has_query) { + out.query.emplace(query); + } + if (has_hash) { + out.hash.emplace(hash); + } + } + return true; +} + +template <class result_type, bool store_values> +result_type parse_url_impl(std::string_view user_input, + const result_type* base_url) { + // We can specialize the implementation per type. + // Important: result_type_is_ada_url is evaluated at *compile time*. This + // means that doing if constexpr(result_type_is_ada_url) { something } else { + // something else } is free (at runtime). This means that ada::url_aggregator + // and ada::url **do not have to support the exact same API**. + constexpr bool result_type_is_ada_url = std::is_same_v<url, result_type>; + constexpr bool result_type_is_ada_url_aggregator = + std::is_same_v<url_aggregator, result_type>; + static_assert(result_type_is_ada_url || + result_type_is_ada_url_aggregator); // We don't support + // anything else for now. + + ada_log("ada::parser::parse_url('", user_input, "' [", user_input.size(), + " bytes],", (base_url != nullptr ? base_url->to_string() : "null"), + ")"); + + result_type url{}; + + const uint32_t max_input_length = ada::get_max_input_length(); + + // Normalization (percent-encoding, IDNA) can push the serialized URL past + // max_input_length even when the input fit under it. The check at the end of + // the state machine covers URLs that run to completion, but several states + // return early after appending a query or fragment, so run the same check on + // those exits too. Without this, a query- or fragment-terminated URL such as + // file://x/?<...> or https://user@x/?<...> is accepted while the equivalent + // https://x/?<...> that takes the absolute fast path is rejected. + const auto enforce_max_input_length = [&]() { + if constexpr (store_values) { + if (url.is_valid) { + if constexpr (result_type_is_ada_url_aggregator) { + if (url.buffer.size() > max_input_length) [[unlikely]] { + url.is_valid = false; + } + } else { + if (url.get_href_size() > max_input_length) [[unlikely]] { + url.is_valid = false; + } + } + } + } + }; + + // We refuse to parse URL strings that exceed the maximum input length. + // By default, this is 4GB but can be configured via + // ada::set_max_input_length(). + if (user_input.size() > max_input_length) [[unlikely]] { + url.is_valid = false; + } + // Going forward, user_input.size() is in [0, // std::numeric_limits<uint32_t>::max). If we are provided with an invalid // base, or the optional_url was invalid, we must return. if (base_url != nullptr) { @@ -10410,31 +13044,54 @@ result_type parse_url_impl(std::string_view user_input, return url; } - // Simple absolute http(s) fast path (before tabs/newline scan). - // Skip digit-led hosts (IPv4) with a cheap peek. + // Simple absolute / relative fast paths (before tabs/newline scan). if constexpr (store_values) { + bool hit_fast_path = false; if (base_url == nullptr) { + // IPv4/IPv6 and userinfo miss the fast path. Skip the never_inline + // call so those URLs (including SetHref) do not pay for a miss. const auto* p = reinterpret_cast<const uint8_t*>(user_input.data()); const size_t n = user_input.size(); - const bool digit_led_host = (n >= 8 && p[4] == ':' && p[5] == '/' && - p[6] == '/' && p[7] >= '0' && p[7] <= '9') || - (n >= 9 && p[5] == ':' && p[6] == '/' && - p[7] == '/' && p[8] >= '0' && p[8] <= '9'); - if (!digit_led_host && try_parse_simple_absolute(user_input, url)) { - if constexpr (result_type_is_ada_url_aggregator) { - if (url.buffer.size() > max_input_length) [[unlikely]] { - url.is_valid = false; - } - } else { - if (url.get_href_size() > max_input_length) [[unlikely]] { - url.is_valid = false; - } + size_t host_start = 0; + if (n >= 8 && p[4] == ':' && p[5] == '/' && p[6] == '/') { + host_start = 7; + } else if (n >= 9 && p[5] == ':' && p[6] == '/' && p[7] == '/') { + host_start = 8; + } + const uint8_t host_first = host_start != 0 ? p[host_start] : 0; + const bool skip_ip = + host_first == '[' || (host_first >= '0' && host_first <= '9'); + // Only scan for userinfo when the host is not an IP literal, so + // IPv4/IPv6 inputs skip the SIMD '@' check entirely. + hit_fast_path = + !skip_ip && + !(host_start != 0 && authority_has_at(p, host_start, n)) && + try_parse_simple_absolute(user_input, url); + } else { + hit_fast_path = try_parse_simple_relative(user_input, *base_url, url); + } + if (hit_fast_path) { + if constexpr (result_type_is_ada_url_aggregator) { + if (url.buffer.size() > max_input_length) [[unlikely]] { + url.is_valid = false; + } + } else { + // For a small absolute input, even worst-case normalization cannot + // exceed the limit: percent encoding expands at most 3x and IDNA at + // most 4.5x. Avoid traversing every stored component on the common + // default-limit path. + if ((base_url != nullptr || + user_input.size() > static_cast<size_t>(max_input_length) / 5) && + url.get_href_size() > max_input_length) [[unlikely]] { + url.is_valid = false; } - return url; } + return url; } } + state state = state::SCHEME_START; + std::string tmp_buffer; std::string_view url_data; if (unicode::has_tabs_or_newline(user_input)) [[unlikely]] { @@ -10610,6 +13267,7 @@ result_type parse_url_impl(std::string_view user_input, } } url.update_unencoded_base_hash(*fragment); + enforce_max_input_length(); return url; } // Otherwise, if base's scheme is not "file", set state to relative @@ -10745,6 +13403,7 @@ result_type parse_url_impl(std::string_view user_input, url.update_unencoded_base_hash(*fragment); } } + enforce_max_input_length(); return url; } input_position = end_of_authority + 1; @@ -10958,6 +13617,7 @@ result_type parse_url_impl(std::string_view user_input, url.update_unencoded_base_hash(*fragment); } } + enforce_max_input_length(); return url; } case state::HOST: { @@ -11088,6 +13748,7 @@ result_type parse_url_impl(std::string_view user_input, url.update_unencoded_base_hash(*fragment); } } + enforce_max_input_length(); return url; } // If c is neither U+002F (/) nor U+005C (\), then decrease pointer @@ -11316,7 +13977,6 @@ result_type parse_url_impl(std::string_view user_input, else { // Set url's path to an empty list. url.clear_pathname(); - url.has_opaque_path = true; } // Set state to path state and decrease pointer by 1. @@ -11343,25 +14003,26 @@ result_type parse_url_impl(std::string_view user_input, url.update_unencoded_base_hash(*fragment); } } - // Check the resulting (normalized) URL size against the maximum input length. - // Normalization (percent-encoding, IDNA, etc.) can expand the URL beyond the - // original input size. - if constexpr (store_values) { - if (url.is_valid) { - if constexpr (result_type_is_ada_url_aggregator) { - if (url.buffer.size() > max_input_length) { - url.is_valid = false; - } - } else { - if (url.get_href_size() > max_input_length) { - url.is_valid = false; - } - } - } - } + enforce_max_input_length(); return url; } +template bool try_parse_simple_absolute<url>(std::string_view, url&); +template bool try_parse_simple_absolute<url_aggregator>(std::string_view, + url_aggregator&); +template bool finish_simple_absolute_with_port<url>(std::string_view, url&, + ada::scheme::type, uint32_t, + size_t, size_t, size_t, + bool); +template bool finish_simple_absolute_with_port<url_aggregator>( + std::string_view, url_aggregator&, ada::scheme::type, uint32_t, size_t, + size_t, size_t, bool); +template bool try_parse_simple_relative<url>(std::string_view, const url&, + url&); +template bool try_parse_simple_relative<url_aggregator>(std::string_view, + const url_aggregator&, + url_aggregator&); + template url parse_url_impl<url, true>(std::string_view user_input, const url* base_url = nullptr); template url_aggregator parse_url_impl<url_aggregator, true>( @@ -11433,13 +14094,16 @@ namespace ada { /* end file src/url_components.cpp */ /* begin file src/url_aggregator.cpp */ +#include <algorithm> #include <array> #include <cstdint> #include <cstring> #include <iterator> +#include <optional> #include <ranges> #include <string> #include <string_view> +#include <utility> namespace { @@ -11633,6 +14297,13 @@ inline void url_aggregator::set_scheme(std::string_view new_scheme) { ADA_ASSERT_TRUE(validate()); } +bool url_aggregator::needs_rollback_snapshot(size_t input_len) const noexcept { + // 3x should cover worst-case percent-encoding of every input byte; the + // constant covers the handful of delimiter bytes a setter may add ("/.", "?", + // "#" and so on) + return buffer.size() + input_len * 3 + 16 > ada::get_max_input_length(); +} + bool url_aggregator::set_protocol(const std::string_view input) { ada_log("url_aggregator::set_protocol ", input); ADA_ASSERT_TRUE(validate()); @@ -11654,11 +14325,14 @@ bool url_aggregator::set_protocol(const std::string_view input) { std::ranges::find_if_not(view, unicode::is_alnum_plus); if (pointer != view.end() && *pointer == ':') { - url_aggregator saved_url(*this); + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(view.size())) { + saved_url = *this; + } bool result = parse_scheme_with_colon<true>( view.substr(0, pointer - view.begin() + 1)); - if (result && buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + if (result && saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return false; } return result; @@ -11667,13 +14341,19 @@ bool url_aggregator::set_protocol(const std::string_view input) { } bool url_aggregator::set_username(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + return set_username(std::string(input)); + } ada_log("url_aggregator::set_username '", input, "' "); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); if (cannot_have_credentials_or_port()) { return false; } - url_aggregator saved_url(*this); + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(input.size())) { + saved_url = *this; + } size_t idx = ada::unicode::percent_encode_index( input, character_sets::USERINFO_PERCENT_ENCODE); if (idx == input.size()) { @@ -11683,8 +14363,8 @@ bool url_aggregator::set_username(const std::string_view input) { update_base_username(ada::unicode::percent_encode( input, character_sets::USERINFO_PERCENT_ENCODE, idx)); } - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return false; } ADA_ASSERT_TRUE(validate()); @@ -11692,13 +14372,19 @@ bool url_aggregator::set_username(const std::string_view input) { } bool url_aggregator::set_password(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + return set_password(std::string(input)); + } ada_log("url_aggregator::set_password '", input, "'"); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); if (cannot_have_credentials_or_port()) { return false; } - url_aggregator saved_url(*this); + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(input.size())) { + saved_url = *this; + } size_t idx = ada::unicode::percent_encode_index( input, character_sets::USERINFO_PERCENT_ENCODE); if (idx == input.size()) { @@ -11708,8 +14394,8 @@ bool url_aggregator::set_password(const std::string_view input) { update_base_password(ada::unicode::percent_encode( input, character_sets::USERINFO_PERCENT_ENCODE, idx)); } - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return false; } ADA_ASSERT_TRUE(validate()); @@ -11747,30 +14433,40 @@ bool url_aggregator::set_port(const std::string_view input) { std::string_view digits_to_parse = std::string_view(trimmed.data(), first_non_digit - trimmed.begin()); - // Revert changes if parse_port fails. - url_aggregator saved_url(*this); + // parse_port only touches the buffer once the digits are already known to + // be in range, so an invalid port never mutates anything and needs no + // rollback; a valid one can only grow the buffer by a few bytes. + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(digits_to_parse.size())) { + saved_url = *this; + } parse_port(digits_to_parse); - if (is_valid) { - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); - return false; - } - return true; + if (!is_valid) { + is_valid = true; + ADA_ASSERT_TRUE(validate()); + return false; } - *this = std::move(saved_url); - is_valid = true; - ADA_ASSERT_TRUE(validate()); - return false; + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); + return false; + } + return true; } bool url_aggregator::set_pathname(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + return set_pathname(std::string(input)); + } ada_log("url_aggregator::set_pathname ", input); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); if (has_opaque_path) { return false; } - url_aggregator saved_url(*this); + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(input.size())) { + saved_url = *this; + } clear_pathname(); parse_path(input); if (get_pathname().starts_with("//") && !has_authority() && !has_dash_dot()) { @@ -11783,8 +14479,8 @@ bool url_aggregator::set_pathname(const std::string_view input) { components.hash_start += 2; } } - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return false; } ADA_ASSERT_TRUE(validate()); @@ -11833,6 +14529,10 @@ ada_really_inline void url_aggregator::parse_path(std::string_view input) { } void url_aggregator::set_search(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + set_search(std::string(input)); + return; + } ada_log("url_aggregator::set_search ", input); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); @@ -11842,24 +14542,38 @@ void url_aggregator::set_search(const std::string_view input) { return; } - std::string new_value; - new_value = input[0] == '?' ? input.substr(1) : input; - helpers::remove_ascii_tab_or_newline(new_value); + std::string_view stripped = input[0] == '?' ? input.substr(1) : input; + // Fast path: no tabs/newlines (the common case) avoids the std::string + // allocation entirely by passing the view straight to update_base_search. + std::string cleaned; + std::string_view effective = stripped; + if (unicode::has_tabs_or_newline(stripped)) { + cleaned = stripped; + helpers::remove_ascii_tab_or_newline(cleaned); + effective = cleaned; + } auto query_percent_encode_set = is_special() ? ada::character_sets::SPECIAL_QUERY_PERCENT_ENCODE : ada::character_sets::QUERY_PERCENT_ENCODE; - url_aggregator saved_url(*this); - update_base_search(new_value, query_percent_encode_set); - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(effective.size())) { + saved_url = *this; + } + update_base_search(effective, query_percent_encode_set); + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return; } ADA_ASSERT_TRUE(validate()); } void url_aggregator::set_hash(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + set_hash(std::string(input)); + return; + } ada_log("url_aggregator::set_hash ", input); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); @@ -11872,13 +14586,23 @@ void url_aggregator::set_hash(const std::string_view input) { return; } - std::string new_value; - new_value = input[0] == '#' ? input.substr(1) : input; - helpers::remove_ascii_tab_or_newline(new_value); - url_aggregator saved_url(*this); - update_unencoded_base_hash(new_value); - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + std::string_view stripped = input[0] == '#' ? input.substr(1) : input; + // Fast path: no tabs/newlines (the common case) avoids the std::string + // allocation entirely by passing the view straight through. + std::string cleaned; + std::string_view effective = stripped; + if (unicode::has_tabs_or_newline(stripped)) { + cleaned = stripped; + helpers::remove_ascii_tab_or_newline(cleaned); + effective = cleaned; + } + std::optional<url_aggregator> saved_url; + if (needs_rollback_snapshot(effective.size())) { + saved_url = *this; + } + update_unencoded_base_hash(effective); + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return; } ADA_ASSERT_TRUE(validate()); @@ -11898,7 +14622,7 @@ bool url_aggregator::set_href(const std::string_view input) { } ada_log("url_aggregator::set_href, parsed ", out->to_string()); // TODO: Figure out why the following line puts test to never finish. - *this = *out; + *this = std::move(*out); } return out.has_value(); @@ -11942,10 +14666,9 @@ ada_really_inline bool url_aggregator::parse_host(std::string_view input) { // case ASCII letter, then we can just copy it to the buffer. We want to // optimize for such a common case. - // Fast path: try to parse as pure decimal IPv4(a.b.c.d) first. + // Fast path: try to parse as pure decimal IPv4 first. const uint64_t fast_result = checkers::try_parse_ipv4_fast(input); if (fast_result < checkers::ipv4_fast_fail) { - // Fast path succeeded - input is pure decimal IPv4 if (!input.empty() && input.back() == '.') { update_base_hostname(input.substr(0, input.size() - 1)); } else { @@ -11960,26 +14683,57 @@ ada_really_inline bool url_aggregator::parse_host(std::string_view input) { uint8_t is_forbidden_or_upper = unicode::contains_forbidden_domain_code_point_or_upper(input.data(), input.size()); - // Minor optimization opportunity: - // contains_forbidden_domain_code_point_or_upper could be extend to check for - // the presence of characters that cannot appear in the ipv4 address and we - // could also check whether x and n and - are present, and so we could skip - // some of the checks below. However, the gains are likely to be small, and - // the code would be more complex. static constexpr std::string_view xn_dash{"xn-", 3}; - if (is_forbidden_or_upper == 0 && - input.find(xn_dash) == std::string_view::npos) { - // fast path - update_base_hostname(input); - - // Check for other IPv4 formats (hex, octal, etc.) - if (checkers::is_ipv4(get_hostname())) { - ada_log("parse_host fast path ipv4"); - return parse_ipv4(get_hostname(), true); + if ((is_forbidden_or_upper & 1) == 0) { + if ((is_forbidden_or_upper & 2) != 0) { + std::string lowered(input); + unicode::to_lower_ascii(lowered.data(), lowered.size()); + if (lowered.find('-') == std::string_view::npos || + lowered.find(xn_dash) == std::string_view::npos) { + // Check IPv4 before mutating so failures leave the buffer untouched. + // This also avoids a double buffer rewrite for hex/octal IPv4. + if (checkers::is_ipv4(lowered)) { + ada_log("parse_host fast path ipv4"); + return parse_ipv4(lowered, false); + } + update_base_hostname(lowered); + ada_log("parse_host fast path ", get_hostname()); + is_valid = true; + return true; + } + } else if (input.find('-') == std::string_view::npos || + input.find(xn_dash) == std::string_view::npos) { + // Check IPv4 before mutating so failures leave the buffer untouched. + if (checkers::is_ipv4(input)) { + ada_log("parse_host fast path ipv4"); + return parse_ipv4(input, false); + } + update_base_hostname(input); + ada_log("parse_host fast path ", get_hostname()); + is_valid = true; + return true; + } + } else if (const size_t first_percent = input.find('%'); + first_percent != std::string_view::npos) { + std::string decoded = unicode::percent_decode(input, first_percent); + const uint8_t decoded_flags = + unicode::contains_forbidden_domain_code_point_or_upper(decoded.data(), + decoded.size()); + if ((decoded_flags & 1) == 0) { + if ((decoded_flags & 2) != 0) { + unicode::to_lower_ascii(decoded.data(), decoded.size()); + } + if (decoded.find('-') == std::string_view::npos || + decoded.find(xn_dash) == std::string_view::npos) { + // Check IPv4 before mutating so failures leave the buffer untouched. + if (checkers::is_ipv4(decoded)) { + return parse_ipv4(decoded, false); + } + update_base_hostname(decoded); + is_valid = true; + return true; + } } - ada_log("parse_host fast path ", get_hostname()); - is_valid = true; - return true; } // We have encountered at least one forbidden code point or the input contains // 'xn-' (case insensitive), so we need to call 'to_ascii' to perform the full @@ -12021,18 +14775,64 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { return false; } - url_aggregator saved_url(*this); + // parse_host no longer mutates the buffer on failure (IPv4 is checked + // before update_base_hostname), so the only rollback needed is for the + // length limit. Snapshot only when the bound can be reached, like the + // other setters do via needs_rollback_snapshot. That bound assumes + // percent-encoding (3x) is the worst growth, but domain to ASCII can grow + // a non-ASCII host further (U+337F, 3 bytes, becomes the 17-byte label + // "xn--6oqv20b1zgzxr"), so a non-ASCII host always takes the snapshot. + const bool was_valid = is_valid; + std::optional<url_aggregator> saved_url; + // The 3x bound covers percent-encoding. Domain-to-ASCII can grow a + // non-ASCII host further, so those inputs always snapshot. The byte + // scan runs only when the 3x bound did not already require a snapshot + // (the common ASCII setter path stays a size compare). + bool take_snapshot = needs_rollback_snapshot(input.size()); + if (!take_snapshot) { + const size_t host_end = input.find('#'); + const size_t n = + host_end == std::string_view::npos ? input.size() : host_end; + for (size_t i = 0; i < n; ++i) { + if (static_cast<unsigned char>(input[i]) >= 0x80) { + take_snapshot = true; + break; + } + } + } + if (take_snapshot) { + saved_url = *this; + } + + auto restore_on_failure = [&]() { + if (saved_url) { + *this = std::move(*saved_url); + } else { + // Buffer is untouched on parse failure; just restore the is_valid flag + // that parse_host may have cleared. + is_valid = was_valid; + } + }; size_t host_end_pos = input.find('#'); - std::string _host(input.data(), host_end_pos != std::string_view::npos - ? host_end_pos - : input.size()); - helpers::remove_ascii_tab_or_newline(_host); - std::string_view new_host(_host); + std::string_view host_input( + input.data(), + host_end_pos != std::string_view::npos ? host_end_pos : input.size()); + // Fast path: no tabs/newlines (the common case) avoids the std::string + // allocation by viewing the input prefix directly. + std::string _host_buf; + std::string_view new_host; + if (unicode::has_tabs_or_newline(host_input)) { + _host_buf = host_input; + helpers::remove_ascii_tab_or_newline(_host_buf); + new_host = _host_buf; + } else { + new_host = host_input; + } auto check_url_size = [&]() -> bool { - if (buffer.size() > ada::get_max_input_length()) { - *this = std::move(saved_url); + if (saved_url && buffer.size() > ada::get_max_input_length()) { + *this = std::move(*saved_url); return false; } return true; @@ -12041,7 +14841,7 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { // If url's scheme is "file", then set state to file host state, instead of // host state. if (type != ada::scheme::type::FILE) { - std::string_view host_view(_host.data(), _host.length()); + std::string_view host_view = new_host; auto [location, found_colon] = helpers::get_host_delimiter_location(is_special(), host_view); @@ -12065,7 +14865,7 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { // Let host be the result of host parsing buffer with url is not special. bool succeeded = parse_host(host_buffer); if (!succeeded) { - *this = std::move(saved_url); + restore_on_failure(); return false; } else if (has_dash_dot()) { // The url now has a non-null host, so the "/." that guarded a @@ -12076,9 +14876,13 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { // Set url's host to host, buffer to the empty string, and state to port // state. + // Not set_port(): its size check and rollback cover only the port. std::string_view port_buffer = new_host.substr(location + 1); - if (!port_buffer.empty()) { - set_port(port_buffer); + std::string_view digits = + port_buffer.substr(0, port_buffer.find_first_not_of("0123456789")); + if (!digits.empty() && !cannot_have_credentials_or_port()) { + parse_port(digits); + is_valid = true; // an out-of-range port is ignored } return check_url_size(); } @@ -12117,7 +14921,7 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { bool succeeded = parse_host(host_view); if (!succeeded) { - *this = std::move(saved_url); + restore_on_failure(); return false; } else if (has_dash_dot()) { // Should remove dash_dot from pathname @@ -12138,7 +14942,7 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { } else { // Let host be the result of host parsing buffer with url is not special. if (!parse_host(new_host)) { - *this = std::move(saved_url); + restore_on_failure(); return false; } @@ -12153,6 +14957,9 @@ bool url_aggregator::set_host_or_hostname(const std::string_view input) { } bool url_aggregator::set_host(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + return set_host(std::string(input)); + } ada_log("url_aggregator::set_host '", input, "'"); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); @@ -12160,6 +14967,9 @@ bool url_aggregator::set_host(const std::string_view input) { } bool url_aggregator::set_hostname(const std::string_view input) { + if (helpers::overlaps(input, buffer)) { + return set_hostname(std::string(input)); + } ada_log("url_aggregator::set_hostname '", input, "'"); ADA_ASSERT_TRUE(validate()); ADA_ASSERT_TRUE(!helpers::overlaps(input, buffer)); @@ -12423,7 +15233,11 @@ bool url_aggregator::parse_ipv4(std::string_view input, bool in_place) { // Pure decimal: keep the buffer when it already holds the address. // Otherwise write the (trailing-dot-stripped) input. if (!(in_place && !trailing_dot)) { - update_base_hostname(input); + if (helpers::overlaps(input, buffer)) { + update_base_hostname(std::string(input)); + } else { + update_base_hostname(input); + } } host_type = IPV4; ADA_ASSERT_TRUE(validate()); @@ -12484,14 +15298,22 @@ bool url_aggregator::parse_ipv6(std::string_view input) { if (input.empty() || input.size() > 45) [[unlikely]] { return is_valid = false; } -#if defined(ADA_AVX512) - if (!detail::ipv6_structure_plausible(input.data(), input.size())) - [[unlikely]] { - return is_valid = false; + std::array<uint16_t, 8> address{}; +#if defined(ADA_AVX512_IPV6) + if (bool simd_valid; detail::try_parse_ipv6_avx512(input.data(), input.size(), + address, simd_valid)) { + if (!simd_valid) [[unlikely]] { + return is_valid = false; + } + const std::string serialized = ada::serializers::ipv6(address); + if (get_hostname() != serialized) { + update_base_hostname(serialized); + } + host_type = IPV6; + return true; } + address = {}; #endif - - std::array<uint16_t, 8> address{}; const char* pointer = input.data(); const char* const end = pointer + input.size(); int piece_index = 0; @@ -12942,7 +15764,6 @@ inline void url_aggregator::consume_prepared_path(std::string_view input) { ada_log("parse_path slow"); // we have reached the general case bool needs_percent_encoding = (accumulator & 1); - std::string path_buffer_tmp; do { size_t location = (special && (accumulator & 2)) ? input.find_first_of("/\\") @@ -12952,39 +15773,37 @@ inline void url_aggregator::consume_prepared_path(std::string_view input) { path_view.remove_suffix(path_view.size() - location); input.remove_prefix(location + 1); } - // path_buffer is either path_view or it might point at a percent encoded - // temporary string. - std::string_view path_buffer = - (needs_percent_encoding && - ada::unicode::percent_encode<false>( - path_view, character_sets::PATH_PERCENT_ENCODE, path_buffer_tmp)) - ? path_buffer_tmp - : path_view; - if (unicode::is_double_dot_path_segment(path_buffer)) { + // Path encoding preserves dots and percent signs, so normalize first. + if (unicode::is_double_dot_path_segment(path_view)) { helpers::shorten_path(path, type); if (location == std::string_view::npos) { path += '/'; } - } else if (unicode::is_single_dot_path_segment(path_buffer) && + } else if (unicode::is_single_dot_path_segment(path_view) && (location == std::string_view::npos)) { path += '/'; } - // Otherwise, if path_buffer is not a single-dot path segment, then: - else if (!unicode::is_single_dot_path_segment(path_buffer)) { - // If url's scheme is "file", url's path is empty, and path_buffer is a + // Otherwise, if path_view is not a single-dot path segment, then: + else if (!unicode::is_single_dot_path_segment(path_view)) { + // If url's scheme is "file", url's path is empty, and path_view is a // Windows drive letter, then replace the second code point in - // path_buffer with U+003A (:). + // path_view with U+003A (:). if (type == ada::scheme::type::FILE && path.empty() && - checkers::is_windows_drive_letter(path_buffer)) { + path_view.size() == 2 && + checkers::is_windows_drive_letter(path_view)) { path += '/'; - path += path_buffer[0]; + path += path_view[0]; path += ':'; - path_buffer.remove_prefix(2); - path.append(path_buffer); + path_view.remove_prefix(2); + path.append(path_view); } else { - // Append path_buffer to url's path. + // Append encoded bytes directly to the pathname. path += '/'; - path.append(path_buffer); + if (!needs_percent_encoding || + !ada::unicode::percent_encode<true>( + path_view, character_sets::PATH_PERCENT_ENCODE, path)) { + path.append(path_view); + } } } if (location == std::string_view::npos) { @@ -13005,6 +15824,8 @@ inline void url_aggregator::consume_prepared_path(std::string_view input) { #include <algorithm> #include <optional> #include <string> +#include <string_view> +#include <utility> namespace ada { @@ -13386,9 +16207,16 @@ tl::expected<std::string, errors> url_pattern_init::process_hash( #include <algorithm> #include <array> #include <charconv> +#include <cstddef> +#include <cstdint> #include <optional> #include <ranges> #include <string> +#include <string_view> +#include <system_error> +#include <tuple> +#include <utility> +#include <vector> namespace ada::url_pattern_helpers { @@ -13616,6 +16444,9 @@ tl::expected<std::string, errors> canonicalize_protocol( if (input.ends_with(":")) { input.remove_suffix(1); + if (input.empty()) [[unlikely]] { + return tl::unexpected(errors::type_error); + } } // Fast path: special schemes are already canonical @@ -13888,7 +16719,11 @@ tl::expected<std::string, errors> canonicalize_pathname( // query/fragment, so the pathname was silently truncated at the first literal // '?' or '#'. set_pathname runs the parser in path state override, matching // how canonicalize_hostname uses set_hostname. - auto url = ada::parse<url_aggregator>("fake://fake-url", nullptr); + // The spec's "create a dummy URL" is "https://dummy.invalid/": a special + // URL, so the path parser turns "\\" into "/" as it does in a special URL. + // A non-special dummy kept a literal backslash, so a pattern such as + // "/a\\b" never matched "https://h/a/b". + auto url = ada::parse<url_aggregator>("https://dummy.invalid/", nullptr); ADA_ASSERT_TRUE(url); if (!url->set_pathname(modified_value)) { // If parseResult is failure, then throw a TypeError. @@ -13914,17 +16749,11 @@ tl::expected<std::string, errors> canonicalize_opaque_pathname( if (input.empty()) [[unlikely]] { return ""; } - // Let dummyURL be a new URL record. - // Set dummyURL's path to the empty string. - // Let parseResult be the result of running URL parsing given value with - // dummyURL as url and opaque path state as state override. - if (auto url = - ada::parse<url_aggregator>("fake:" + std::string(input), nullptr)) { - // Return the result of URL path serializing dummyURL. - return std::string(url->get_pathname()); - } - // If parseResult is failure, then throw a TypeError. - return tl::unexpected(errors::type_error); + // Opaque-path state: no authority and no dot-segment normalization. + std::string value(input); + helpers::remove_ascii_tab_or_newline(value); + return ada::unicode::percent_encode( + value, character_sets::C0_CONTROL_PERCENT_ENCODE); } tl::expected<std::string, errors> canonicalize_search(std::string_view input) { @@ -13943,18 +16772,16 @@ tl::expected<std::string, errors> canonicalize_search(std::string_view input) { return ""; } - // Percent-encode using QUERY_PERCENT_ENCODE (for non-special URLs) - // Note: "fake://dummy.test" is not a special URL, so we use - // QUERY_PERCENT_ENCODE + // The spec's dummy URL is special, so use the special-query set. size_t idx = ada::unicode::percent_encode_index( - new_value, character_sets::QUERY_PERCENT_ENCODE); + new_value, character_sets::SPECIAL_QUERY_PERCENT_ENCODE); if (idx == new_value.size()) { // No encoding needed return new_value; } // Percent-encode from the first character that needs encoding return ada::unicode::percent_encode( - new_value, character_sets::QUERY_PERCENT_ENCODE, idx); + new_value, character_sets::SPECIAL_QUERY_PERCENT_ENCODE, idx); } tl::expected<std::string, errors> canonicalize_hash(std::string_view input) { @@ -14494,10 +17321,11 @@ std::string generate_pattern_string( // - part's suffix is not the empty string. // - part's prefix is not the empty string and is not options's prefix code // point. + // This compares the whole prefix: a prefix such as "/9" starts with the + // prefix code point but is not it, and still needs grouping. bool needs_grouping = !part.suffix.empty() || - (!part.prefix.empty() && (options.get_prefix().empty() || - part.prefix[0] != options.get_prefix()[0])); + (!part.prefix.empty() && part.prefix != options.get_prefix()); // If all of the following are true: // - needs grouping is false; and @@ -14540,175 +17368,1478 @@ std::string generate_pattern_string( needs_grouping = true; } - // Assert: part's name is not the empty string or null. - ADA_ASSERT_TRUE(!part.name.empty()); + // Assert: part's name is not the empty string or null. + ADA_ASSERT_TRUE(!part.name.empty()); + + // If needs grouping is true, then append "{" to the end of result. + if (needs_grouping) { + result.append("{"); + } + + // Append the result of running escape a pattern string given part's prefix + // to the end of result. + result.append(escape_pattern_string(part.prefix)); + + // If custom name is true: + if (custom_name) { + // Append ":" to the end of result. + result.append(":"); + // Append part's name to the end of result. + result.append(part.name); + } + + // If part's type is "regexp" then: + if (part.type == url_pattern_part_type::REGEXP) { + // Append "(" to the end of result. + result.append("("); + // Append part's value to the end of result. + result.append(part.value); + // Append ")" to the end of result. + result.append(")"); + } else if (part.type == url_pattern_part_type::SEGMENT_WILDCARD && + !custom_name) { + // Otherwise if part's type is "segment-wildcard" and custom name is + // false: Append "(" to the end of result. + result.append("("); + // Append the result of running generate a segment wildcard regexp given + // options to the end of result. + result.append(generate_segment_wildcard_regexp(options)); + // Append ")" to the end of result. + result.append(")"); + } else if (part.type == url_pattern_part_type::FULL_WILDCARD) { + // Otherwise if part's type is "full-wildcard": + // If custom name is false and one of the following is true: + // - previous part is null; or + // - previous part's type is "fixed-text"; or + // - previous part's modifier is not "none"; or + // - needs grouping is true; or + // - part's prefix is not the empty string + // - then append "*" to the end of result. + if (!custom_name && + (!previous_part || + previous_part->type == url_pattern_part_type::FIXED_TEXT || + previous_part->modifier != url_pattern_part_modifier::none || + needs_grouping || !part.prefix.empty())) { + result.append("*"); + } else { + // Append "(" to the end of result. + // Append full wildcard regexp value to the end of result. + // Append ")" to the end of result. + result.append("(.*)"); + } + } + + // If all of the following are true: + // - part's type is "segment-wildcard"; and + // - custom name is true; and + // - part's suffix is not the empty string; and + // - The result of running is a valid name code point given part's suffix's + // first code point and the boolean false is true then append U+005C (\) to + // the end of result. + if (part.type == url_pattern_part_type::SEGMENT_WILDCARD && custom_name && + !part.suffix.empty() && + idna::valid_name_code_point(part.suffix[0], false)) { + result.append("\\"); + } + + // Append the result of running escape a pattern string given part's suffix + // to the end of result. + result.append(escape_pattern_string(part.suffix)); + // If needs grouping is true, then append "}" to the end of result. + if (needs_grouping) result.append("}"); + // Append the result of running convert a modifier to a string given part's + // modifier to the end of result. + result.append(convert_modifier_to_string(part.modifier)); + } + // Return result. + return result; +} +} // namespace ada::url_pattern_helpers + +#endif // ADA_INCLUDE_URL_PATTERN +/* end file src/url_pattern_helpers.cpp */ +/* begin file src/url_pattern_regex.cpp */ +#if ADA_INCLUDE_URL_PATTERN + + +#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER +#include <cstddef> +#include <optional> +#include <regex> +#include <string> +#include <string_view> +#include <vector> +#endif // ADA_USE_UNSAFE_STD_REGEX_PROVIDER + +namespace ada::url_pattern_regex { + +#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER +std::optional<std::regex> std_regex_provider::create_instance( + std::string_view pattern, bool ignore_case) { + // Let flags be an empty string. + // If options's ignore case is true then set flags to "vi". + // Otherwise set flags to "v" + auto flags = ignore_case + ? std::regex::icase | std::regex_constants::ECMAScript + : std::regex_constants::ECMAScript; + try { + return std::regex(pattern.data(), pattern.size(), flags); + } catch (const std::regex_error& e) { + (void)e; + ada_log("std_regex_provider::create_instance failed:", e.what()); + return std::nullopt; + } +} + +std::optional<std::vector<std::optional<std::string>>> +std_regex_provider::regex_search(std::string_view input, + const std::regex& pattern) { + // Use iterator-based regex_search to avoid string allocation + std::match_results<std::string_view::const_iterator> match_result; + try { + if (!std::regex_search(input.begin(), input.end(), match_result, pattern, + std::regex_constants::match_any)) { + return std::nullopt; + } + } catch (const std::regex_error& e) { + (void)e; + ada_log("std_regex_provider::regex_search failed:", e.what()); + return std::nullopt; + } + std::vector<std::optional<std::string>> matches; + // An empty input can still match with capture groups (e.g. "(x*)" or an + // optional ":a?" against ""), so the group values must be extracted here + // just like for a non-empty input. A successful regex_search always leaves + // the full match at index 0, so match_result is never empty at this point. + if (match_result.empty()) { + return matches; + } + matches.reserve(match_result.size()); + for (size_t i = 1; i < match_result.size(); ++i) { + if (auto entry = match_result[i]; entry.matched) { + matches.emplace_back(entry.str()); + } else { + // A capture group that did not participate in the match is undefined, + // not absent. Emitting nullopt keeps the result aligned by position with + // the component's group name list; dropping it shifts every later group + // onto the wrong name. + matches.emplace_back(std::nullopt); + } + } + return matches; +} + +bool std_regex_provider::regex_match(std::string_view input, + const std::regex& pattern) { + try { + return std::regex_match(input.begin(), input.end(), pattern); + } catch (const std::regex_error& e) { + (void)e; + ada_log("std_regex_provider::regex_match failed:", e.what()); + return false; + } +} + +#endif // ADA_USE_UNSAFE_STD_REGEX_PROVIDER + +} // namespace ada::url_pattern_regex + +#endif // ADA_INCLUDE_URL_PATTERN +/* end file src/url_pattern_regex.cpp */ +#if !defined(ADA_URL_PATTERN_LIST_SEPARATE_TU) +/* begin file src/url_pattern_list.cpp */ +/** + * @file url_pattern_list.cpp + * @brief Route-set compiler backing ada::url_pattern_list. + * + * The provider-independent build side: classification of URLPattern part + * lists into pattern segments, the compiler (segment trie, per-node dispatch, + * auxiliary-route pruning), the arena packing, and the sequential reference + * matcher used beyond the fast-path limits. The matcher itself is inline in + * url_pattern_list-inl.h. + * + * Every dispatch decision is made at build time so that the per-request + * residual is a segment scan and a trie walk with bounded backtracking. + * Offline searches (witness plans, perfect multipliers) that fail demote the + * affected node to a linear scan: slower, never incorrect. + */ +/* begin file src/url_pattern_list_compiler.h */ +/** + * @file url_pattern_list_compiler.h + * @brief The url_pattern_list route-set compiler: pattern classification and + * the build-time table construction behind ada::parse_url_pattern_list. + * + * This header is NOT part of the public API and is not included from ada.h: + * only src/url_pattern_list.cpp (and, through the amalgamated ada.cpp, the + * url_pattern_list fuzzer) include it. The matcher-visible table layout it + * produces is declared in include/ada/url_pattern_list.h. + */ +#ifndef ADA_URL_PATTERN_LIST_COMPILER_H +#define ADA_URL_PATTERN_LIST_COMPILER_H + + +#include <cstddef> +#include <cstdint> +#include <string> +#include <vector> + +#if ADA_INCLUDE_URL_PATTERN +namespace ada::url_pattern_list_compiler { + +/** + * Maximum number of entries a perfect-hash dispatch table may index (slot + * ordinals are 8-bit, with 0xFF reserved for "empty"). Nodes with a larger + * static fanout are demoted to a linear scan: slower, never incorrect. + */ +inline constexpr uint32_t max_dispatch_table_entries = 254; + +/** + * Static fanout up to which a node compares its children directly, in + * turn; wider nodes dispatch through a projection table. Measured on a + * synthetic node hit uniformly: direct compares beat the projection by + * about 1 ns for keys of varied length up to about 12 children, while for + * keys of one length (which the length gate cannot reject) the projection + * wins by 4-5 ns at every fanout and by more on misses, because the direct + * loop's exit is unpredictable. Eight keeps the first case and bounds the + * second. + */ +inline constexpr uint32_t max_direct_children = 8; + +/** + * The kind of one compiled pattern segment. The numeric values define match + * priority: at the first differing segment, a literal beats a ":param" and a + * ":param" beats a "*" (find-my-way / Express-compatible specificity order). + */ +enum class segment_kind : uint8_t { + literal = 0, + param = 1, + wildcard = 2, +}; + +/** + * One '/'-separated segment of a compiled pattern: a literal text (already + * canonicalized by the URLPattern pattern parser), a ":param" (text = group + * name), or a trailing "*" wildcard. + */ +struct route_segment { + segment_kind kind = segment_kind::literal; + std::string text{}; +}; + +/** + * Everything the compiler knows about one route. `kind_sequence` packs the + * per-segment kinds two bits per segment, most significant first, so that + * comparing (kind_sequence, kind_length, route index) as a tuple is exactly + * the documented specificity order. For regexp-mode routes, `segments` + * holds only the anchored literal prefix (the leading segments that are + * whole fixed text, closed by a '/'), which the auxiliary-route pruning + * uses to rule out routes that can never match the same input. + */ +struct route_info { + std::vector<route_segment> segments{}; + // Capture group names, in capture order (params left to right, then the + // wildcard group). Regexp-mode routes: filled from the compiled component. + std::vector<std::string> group_names{}; + uint64_t kind_sequence = 0; + uint8_t kind_length = 0; + url_pattern_list_detail::route_mode mode = + url_pattern_list_detail::route_mode::sequential; + bool has_wildcard = false; + bool all_literal = false; +}; + +/** + * Classifies a URLPattern part list into '/'-separated pattern segments. + * Returns true when the pattern is expressible in the static/":param"/"*" + * subset (every segment wholly a literal, a param, or a final wildcard); + * `segments` and `group_names` are only valid on success. + */ +bool classify_parts(const std::vector<url_pattern_part>& parts, + std::vector<route_segment>& segments, + std::vector<std::string>& group_names); + +/** + * Computes kind sequence and flags from route.segments and decides the + * route's mode: trie when every fast-path build limit is met, sequential + * otherwise (the empty pattern, more than max_trie_pattern_segments + * segments, or more than max_captures_per_route capture groups). + */ +void finalize_route(route_info& route) noexcept; + +/** + * Best-effort kind sequence for a route that needs regexp matching, so it can + * participate in the specificity order: custom "(...)" groups count as params, + * full wildcards and modified ("?", "+", "*") groups terminate the sequence as + * a wildcard tail. This mapping is an approximation and is called out as an + * open question in the class documentation. Also records the route's + * anchored literal prefix in route.segments and sets mode = regexp. + */ +void approximate_kind_sequence(const std::vector<url_pattern_part>& parts, + route_info& route); + +/** + * True when route `a` (at insertion index `a_index`) outranks route `b`. + */ +constexpr bool route_outranks(const route_info& a, size_t a_index, + const route_info& b, size_t b_index) noexcept { + return url_pattern_list_detail::outranks(a.kind_sequence, a.kind_length, + a_index, b.kind_sequence, + b.kind_length, b_index); +} + +/** + * Compiles the route set: builds the trie and its dispatch plans over the + * trie-mode routes, the segment table, the auxiliary-route table with its + * per-route challenger ranges, and packs everything into one arena. A node + * whose offline search fails is demoted to a slower but correct plan. Fails + * only when a table exceeds its limit or integer encoding. + * Literal texts are used as given (the caller has already case-folded them + * when ignore_case is set). + */ +tl::expected<url_pattern_list_detail::compiled_routes, errors> +compile_route_set(std::vector<route_info>& routes); + +} // namespace ada::url_pattern_list_compiler +#endif // ADA_INCLUDE_URL_PATTERN +#endif // ADA_URL_PATTERN_LIST_COMPILER_H +/* end file src/url_pattern_list_compiler.h */ + +#include <algorithm> +#include <array> +#include <bit> +#include <cstdint> +#include <cstring> +#include <limits> +#include <span> +#include <string_view> +#include <utility> +#include <vector> + +#if ADA_INCLUDE_URL_PATTERN + +namespace ada::url_pattern_list_compiler { + +namespace { + +using url_pattern_list_detail::compiled_routes; +using url_pattern_list_detail::edge_record; +using url_pattern_list_detail::hash_record; +using url_pattern_list_detail::node_record; +using url_pattern_list_detail::route_mode; +using url_pattern_list_detail::route_record; +using url_pattern_list_detail::segment_record; +using url_pattern_list_limits::max_captures_per_route; +using url_pattern_list_limits::max_trie_pattern_segments; + +// The tables under construction, one vector per section; packed into the +// single arena of compiled_routes at the end of the build. +struct builder_tables { + std::vector<node_record> nodes{}; + std::vector<hash_record> hashes{}; + std::vector<edge_record> edges{}; + std::vector<uint8_t> slots{}; + std::vector<char> blob{}; + std::vector<route_record> routes{}; + std::vector<segment_record> segments{}; + std::vector<uint32_t> aux{}; + std::vector<uint16_t> root_index{}; + uint32_t n_aux_all = 0; +}; + +// Witness plan for single-string tables: nibbles 0..2 hold witness ids +// (distinct ids first, remaining slots duplicating id 0 so the runtime +// gather is fixed-shape and branch-free); bits 12..14 are metadata. +constexpr uint16_t pack_witness_plan(const uint8_t* ids, uint32_t n_ids, + bool use_len) noexcept { + uint16_t w = 0; + for (uint32_t j = 0; j < 3; j++) { + w = static_cast<uint16_t>( + w | static_cast<uint16_t>((j < n_ids ? ids[j] : ids[0]) & 15u) + << (4 * j)); + } + w = static_cast<uint16_t>(w | static_cast<uint16_t>(n_ids << 12)); + if (use_len) { + w = static_cast<uint16_t>(w | static_cast<uint16_t>(1) << 14); + } + return w; +} + +// Bytes [from, min(from + 8, len)) of a key, packed little-endian and +// zero-padded; the build-time twin of the matcher's window load. +constexpr uint64_t pack_window_le(const char* p, uint32_t len, + uint32_t from) noexcept { + uint64_t x = 0; + for (uint32_t j = 0; j < 8 && from + j < len; j++) { + x |= static_cast<uint64_t>(static_cast<uint8_t>(p[from + j])) << (8 * j); + } + return x; +} + +// Deterministic RNG for the multiplier search (splitmix64). +struct splitmix64 { + uint64_t state; + constexpr explicit splitmix64(uint64_t seed) noexcept : state(seed) {} + constexpr uint64_t next() noexcept { + uint64_t z = (state += 0x9E3779B97F4A7C15ull); + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return z ^ (z >> 31); + } +}; + +struct transient_node { // build-time trie (views into route segment storage) + std::vector<std::pair<std::string_view, int32_t>> kids{}; + int32_t param = -1; + int32_t wild_route = -1; + int32_t terminal = -1; +}; + +constexpr unsigned ceil_log2(size_t n) noexcept { + unsigned b = 0; + while ((size_t{1} << b) < n) { + b++; + } + return b; +} + +// Starting table size for n keys: load factor <= ~1/4, loosened as n grows +// so the multiplier search still lands inside the budget. +constexpr unsigned initial_slot_bits(size_t n) noexcept { + unsigned headroom = 1; + if (n > 64) { + headroom = 3; + } else if (n > 8) { + headroom = 2; + } + return ceil_log2(n) + headroom; +} + +bool find_multiplier(const std::vector<uint64_t>& proj, unsigned b0, + uint64_t& multiplier_out, uint8_t& bits_out) { + const size_t n = proj.size(); + for (unsigned b = b0; b <= 12; b++) { + std::vector<uint32_t> stamp(size_t{1} << b, 0); + splitmix64 rng(0x14C0FFEEull + b); + for (uint32_t t = 1; t <= 4000; t++) { + const uint64_t m = rng.next() | 1; + bool ok = true; + for (size_t i = 0; i < n; i++) { + const uint64_t s = (proj[i] * m) >> (64 - b); + if (stamp[s] == t) { + ok = false; + break; + } + stamp[s] = t; + } + if (ok) { + multiplier_out = m; + bits_out = static_cast<uint8_t>(b); + return true; + } + } + } + return false; +} + +// Emits a perfect-hash slot table for `proj` at the end of `slots`. Returns +// false if the search failed, in which case nothing was appended and the +// caller demotes that table to a linear scan. +bool emit_slot_table(const std::vector<uint64_t>& proj, + std::vector<uint8_t>& slots, uint64_t& multiplier_out, + uint8_t& bits_out, uint32_t& base_out) { + if (!find_multiplier(proj, initial_slot_bits(proj.size()), multiplier_out, + bits_out)) { + return false; + } + base_out = static_cast<uint32_t>(slots.size()); + slots.resize(slots.size() + (size_t{1} << bits_out), 0xFF); + for (size_t i = 0; i < proj.size(); i++) { + slots[base_out + + url_pattern_list_detail::slot_of(proj[i], multiplier_out, bits_out)] = + static_cast<uint8_t>(i); + } + return true; +} + +// Advances `c` to the next k-combination of {0..n-1} in lexicographic +// order; false once the last one has been visited. +template <size_t N> +constexpr bool next_combination(std::array<uint32_t, N>& c, uint32_t k, + uint32_t n) noexcept { + int32_t j = static_cast<int32_t>(k) - 1; + while (j >= 0 && + c[static_cast<uint32_t>(j)] == n - k + static_cast<uint32_t>(j)) { + j--; + } + if (j < 0) { + return false; + } + c[static_cast<uint32_t>(j)]++; + for (uint32_t t = static_cast<uint32_t>(j) + 1; t < k; t++) { + c[t] = c[t - 1] + 1; + } + return true; +} + +// Witness-subset search over the given id alphabet, cost-ordered: fewest +// distinct witness ids first (the length is always packed -- it is free). +// The first injective subset wins. +bool find_witness_plan( + const std::vector<std::pair<std::string_view, int32_t>>& kids, + const uint8_t* alphabet, uint32_t n_alpha, uint32_t max_reads, + uint16_t& plan_out) { + const size_t n = kids.size(); + auto injective = [&](uint16_t wp) { // sort + adjacent compare + std::vector<uint64_t> proj(n); + for (size_t i = 0; i < n; i++) { + proj[i] = url_pattern_list_detail::project( + kids[i].first.data(), static_cast<uint32_t>(kids[i].first.size()), + wp); + } + std::sort(proj.begin(), proj.end()); + for (size_t i = 1; i < n; i++) { + if (proj[i] == proj[i - 1]) { + return false; + } + } + return true; + }; + for (uint32_t k = 1; k <= max_reads && k <= n_alpha; k++) { + std::array<uint32_t, 3> c{0, 1, 2}; + do { + uint8_t ids[3] = {0, 0, 0}; + for (uint32_t j = 0; j < k; j++) { + ids[j] = alphabet[c[j]]; + } + const uint16_t wp = pack_witness_plan(ids, k, true); + if (injective(wp)) { + plan_out = wp; + return true; + } + } while (next_combination(c, k, n_alpha)); + } + return false; +} + +// ---- build stages ---------------------------------------------------------- + +// Segment trie over the trie-mode routes. Priority is resolved here, at +// build, into each node's fixed decision order (static children -> param -> +// wildcard); a DFS in that order returns the match with the +// lexicographically minimal kind sequence. Duplicate patterns collapse onto +// one slot: an occupied slot is never overwritten, so the smallest route +// index survives. +std::vector<transient_node> build_trie(const std::vector<route_info>& routes) { + std::vector<transient_node> t(1); + for (size_t i = 0; i < routes.size(); i++) { + const route_info& rt = routes[i]; + if (rt.mode != route_mode::trie) { + continue; + } + int32_t cur = 0; + for (const route_segment& ps : rt.segments) { + if (ps.kind == segment_kind::literal) { + int32_t nxt = -1; + for (auto& kv : t[static_cast<size_t>(cur)].kids) { + if (kv.first == ps.text) { + nxt = kv.second; + break; + } + } + if (nxt < 0) { + nxt = static_cast<int32_t>(t.size()); + t[static_cast<size_t>(cur)].kids.emplace_back(ps.text, nxt); + t.emplace_back(); + } + cur = nxt; + } else if (ps.kind == segment_kind::param) { + if (t[static_cast<size_t>(cur)].param < 0) { + t[static_cast<size_t>(cur)].param = static_cast<int32_t>(t.size()); + t.emplace_back(); + } + cur = t[static_cast<size_t>(cur)].param; + } else { // wildcard (classification guarantees final) + if (t[static_cast<size_t>(cur)].wild_route < 0) { + t[static_cast<size_t>(cur)].wild_route = static_cast<int32_t>(i); + } + cur = -1; + break; + } + } + if (cur >= 0 && t[static_cast<size_t>(cur)].terminal < 0) { + t[static_cast<size_t>(cur)].terminal = static_cast<int32_t>(i); + } + } + // The root's children are sorted by first byte so that the first-byte + // index can address each run of same-byte children as one contiguous + // block of edges. + std::stable_sort( + t[0].kids.begin(), t[0].kids.end(), [](const auto& a, const auto& b) { + const int ka = a.first.empty() ? -1 : static_cast<uint8_t>(a.first[0]); + const int kb = b.first.empty() ? -1 : static_cast<uint8_t>(b.first[0]); + return ka < kb; + }); + return t; +} + +// Per-route records: priority data, capture positions (so extracting params +// at match time is a fixed walk over param_positions), regexp ordinals. +void compile_route_records(builder_tables& r, + const std::vector<route_info>& routes) { + r.routes.resize(routes.size()); + int32_t n_regexp = 0; + for (size_t i = 0; i < routes.size(); i++) { + const route_info& rt = routes[i]; + route_record& rm = r.routes[i]; + rm.kind_sequence = rt.kind_sequence; + rm.kind_length = rt.kind_length; + rm.mode = rt.mode; + rm.wild = rt.has_wildcard ? 1 : 0; + if (rt.mode == route_mode::regexp) { + rm.regexp_component = n_regexp++; + continue; + } + if (rt.mode != route_mode::trie) { + continue; // capture positions are only read for trie-answered routes + } + for (size_t s = 0; s < rt.segments.size(); s++) { + if (rt.segments[s].kind == segment_kind::param) { + // Classification guarantees n_params <= max_captures_per_route for + // trie-mode routes. + rm.param_positions[rm.n_params++] = static_cast<uint8_t>(s); + } + } + } +} + +// BFS layout: assign final node ids breadth-first so each node's static +// children occupy a contiguous block of edges[]. Returns the transient-node +// id per final id. +std::vector<int32_t> layout_nodes(builder_tables& r, + const std::vector<transient_node>& t) { + std::vector<int32_t> order; // transient id per final id + order.push_back(0); + r.nodes.resize(1); + for (size_t head = 0; head < order.size(); head++) { + const transient_node& tn = t[static_cast<size_t>(order[head])]; + node_record nd{}; + nd.wild_route = tn.wild_route; + nd.terminal_route = tn.terminal; + nd.first_child = static_cast<int32_t>(r.edges.size()); + nd.n_static = static_cast<uint16_t>(tn.kids.size()); + const size_t id_base = order.size(); // children take the next BFS ids + for (size_t ci = 0; ci < tn.kids.size(); ci++) { + const std::string_view k = tn.kids[ci].first; + edge_record e{}; + e.key_length = static_cast<uint16_t>(k.size()); + e.key_offset = static_cast<uint32_t>(r.blob.size()); + r.blob.insert(r.blob.end(), k.begin(), k.end()); + e.prefix = pack_window_le(k.data(), static_cast<uint32_t>(k.size()), 0); + e.suffix = pack_window_le( + k.data(), static_cast<uint32_t>(k.size()), + k.size() >= 8 ? static_cast<uint32_t>(k.size()) - 8 : 0); + e.node = static_cast<int32_t>(id_base + ci); + r.edges.push_back(e); + } + for (size_t ci = 0; ci < tn.kids.size(); ci++) { + order.push_back(tn.kids[ci].second); + } + if (tn.param >= 0) { + nd.param_child = static_cast<int32_t>(order.size()); + order.push_back(tn.param); + } + nd.has_alternative = (nd.param_child >= 0 || nd.wild_route >= 0) ? 1 : 0; + r.nodes.resize(order.size()); + r.nodes[head] = nd; + } + return order; +} + +// Root first-byte index: a 256-entry table from the first byte of the +// input's first segment to the first root child starting with it (the +// children are sorted by first byte). Built for a root with at least three +// children; a run of same-byte children longer than max_direct_children, or +// an empty key, falls back to the regular ladder. Returns true when the +// index was emitted. +bool build_root_index(builder_tables& r, const transient_node& root) { + const size_t nk = root.kids.size(); + if (nk < 3) { + return false; + } + std::array<uint16_t, 256> index{}; + index.fill(0xFFFF); + std::array<uint32_t, 256> run{}; + for (size_t ci = 0; ci < nk; ci++) { + if (root.kids[ci].first.empty()) { + return false; // an empty key has no first byte: regular ladder + } + const uint8_t b = static_cast<uint8_t>(root.kids[ci].first[0]); + if (index[b] == 0xFFFF) { + index[b] = static_cast<uint16_t>(ci); + } + if (++run[b] > max_direct_children) { + return false; + } + } + r.root_index.assign(index.begin(), index.end()); + return true; +} + +// Per-node dispatch ladder, chosen by static child count: 0 none, up to +// max_direct_children direct compares, then projection over a restricted +// alphabet (escalating to the full alphabet); linear demotion when a search +// fails or when the fanout exceeds max_dispatch_table_entries. The root +// gets the first-byte index when its fanout allows. Never incorrect, only +// slower. +void compile_dispatch(builder_tables& r, const std::vector<transient_node>& t, + const std::vector<int32_t>& order) { + for (size_t ni = 0; ni < r.nodes.size(); ni++) { + node_record& nd = r.nodes[ni]; + const transient_node& tn = t[static_cast<size_t>(order[ni])]; + const size_t nk = tn.kids.size(); + if (nk == 0) { + nd.dispatch = 0; + continue; + } + if (ni == 0 && build_root_index(r, tn)) { + nd.dispatch = 4; + continue; + } + if (nk <= max_direct_children) { + nd.dispatch = 1; + continue; + } + if (nk > max_dispatch_table_entries) { + nd.dispatch = 3; // slot ordinals are 8-bit; linear scan stays correct + continue; + } + uint16_t wp = 0; + bool found = false; + if (nk <= 16) { + constexpr uint8_t alpha_small[2] = {0, 8}; // s[0], s[len - 1] + found = find_witness_plan(tn.kids, alpha_small, 2, 2, wp); + } + if (!found) { // full alphabet (also the escalation path for <= 16) + uint8_t alpha_full[16] = {0, 1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15}; + found = find_witness_plan(tn.kids, alpha_full, 16, 3, wp); + } + hash_record h{}; + if (found) { + std::vector<uint64_t> proj(nk); + for (size_t i = 0; i < nk; i++) { + proj[i] = url_pattern_list_detail::project( + tn.kids[i].first.data(), + static_cast<uint32_t>(tn.kids[i].first.size()), wp); + } + found = emit_slot_table(proj, r.slots, h.multiplier, h.slot_bits, + h.slot_base); + } + if (!found) { + nd.dispatch = 3; // demoted: correct, slower + continue; + } + nd.dispatch = 2; + h.witness_plan = wp; + nd.hash_index = static_cast<uint32_t>(r.hashes.size()); + r.hashes.push_back(h); + } +} + +// Pure-leaf edge encoding, last: a child that is a pure leaf (terminal +// route only) is encoded as -2 - route directly in the edge, so the walk +// finishes or dead-ends there without loading the leaf node. -1 keeps +// meaning "absent" for param_child. +void encode_leaf_shortcuts(builder_tables& r) { + auto pure_leaf = [&](int32_t ni) { + const node_record& nd = r.nodes[static_cast<size_t>(ni)]; + return nd.n_static == 0 && nd.param_child < 0 && nd.wild_route < 0 && + nd.terminal_route >= 0; + }; + for (auto& e : r.edges) { + if (pure_leaf(e.node)) { + e.node = -2 - r.nodes[static_cast<size_t>(e.node)].terminal_route; + } + } + for (auto& nd : r.nodes) { + if (nd.param_child >= 0 && pure_leaf(nd.param_child)) { + nd.param_child = + -2 - r.nodes[static_cast<size_t>(nd.param_child)].terminal_route; + } + } +} + +// Segment table: every non-regexp route's segments (kind plus literal text +// in the blob), so the sequential fallback beyond the fast-path limits can +// match any route without the compiler's types; for regexp routes, the +// anchored literal prefix the matcher checks before running the provider. +void build_segment_table(builder_tables& r, + const std::vector<route_info>& routes) { + for (size_t i = 0; i < routes.size(); i++) { + const route_info& rt = routes[i]; + route_record& rm = r.routes[i]; + rm.segment_first = static_cast<uint32_t>(r.segments.size()); + rm.segment_count = static_cast<uint32_t>(rt.segments.size()); + for (const route_segment& s : rt.segments) { + segment_record sr{}; + sr.kind = static_cast<uint8_t>(s.kind); + if (s.kind == segment_kind::literal) { + sr.text_offset = static_cast<uint32_t>(r.blob.size()); + sr.text_length = static_cast<uint32_t>(s.text.size()); + r.blob.insert(r.blob.end(), s.text.begin(), s.text.end()); + } + r.segments.push_back(sr); + } + } +} + +// Could some pathname match both a fast-path route `w` (full segment +// information) and route `c`? Conservative: true unless a literal conflict +// or a segment-count conflict proves otherwise. For a regexp-mode `c`, +// segments are what approximate_kind_sequence could certify (see there); +// has_wildcard means the input needs at least segments.size() segments +// rather than exactly that many. +bool co_matchable(const route_info& w, const route_info& c) noexcept { + const bool c_regexp = c.mode == route_mode::regexp; + const size_t wn = w.segments.size(); + const size_t cn = c.segments.size(); + constexpr size_t unbounded = ~size_t{0}; + // Segment counts each route accepts: [min, max]. + const size_t w_max = w.has_wildcard ? unbounded : wn; + const size_t c_max = c.has_wildcard ? unbounded : cn; + if ((wn > cn ? wn : cn) > (w_max < c_max ? w_max : c_max)) { + return false; + } + // Positions both routes constrain (a safe wildcard segment constrains + // nothing; a regexp route's segments are all constraining). + const size_t w_fixed = w.has_wildcard ? wn - 1 : wn; + const size_t c_fixed = (!c_regexp && c.has_wildcard) ? cn - 1 : cn; + const size_t upto = w_fixed < c_fixed ? w_fixed : c_fixed; + for (size_t j = 0; j < upto; j++) { + const route_segment& ws = w.segments[j]; + const route_segment& cs = c.segments[j]; + if (ws.kind == segment_kind::literal && cs.kind == segment_kind::literal) { + if (ws.text != cs.text) { + return false; + } + } else if (ws.kind == segment_kind::literal && + cs.kind == segment_kind::param) { + if (ws.text.empty()) { + return false; // params never bind an empty segment + } + } else if (ws.kind == segment_kind::param && + cs.kind == segment_kind::literal) { + if (cs.text.empty()) { + return false; + } + } + } + return true; +} + +// Auxiliary routes: those the trie cannot answer for (regexp mode and +// sequential mode), in insertion order, followed by one challenger range per +// trie route: the auxiliary routes that outrank it AND could match the same +// input. After a fast-path hit only the winner's challengers are tested +// (usually none). Fails past url_pattern_list_limits::max_aux_entries. +bool build_aux_table(builder_tables& r, const std::vector<route_info>& routes) { + std::vector<uint32_t> aux_all; + for (size_t i = 0; i < routes.size(); i++) { + if (routes[i].mode != route_mode::trie) { + aux_all.push_back(static_cast<uint32_t>(i)); + } + } + r.aux = aux_all; + r.n_aux_all = static_cast<uint32_t>(aux_all.size()); + for (size_t w = 0; w < routes.size(); w++) { + const route_info& winner = routes[w]; + if (winner.mode != route_mode::trie) { + continue; // never a fast-path winner + } + route_record& rm = r.routes[w]; + rm.challenger_first = static_cast<uint32_t>(r.aux.size()); + for (const uint32_t c : aux_all) { + if (route_outranks(routes[c], c, winner, w) && + co_matchable(winner, routes[c])) { + if (r.aux.size() >= url_pattern_list_limits::max_aux_entries) { + return false; + } + r.aux.push_back(c); + } + } + rm.challenger_count = + static_cast<uint32_t>(r.aux.size()) - rm.challenger_first; + } + return true; +} - // If needs grouping is true, then append "{" to the end of result. - if (needs_grouping) { - result.append("{"); +// Packs every table into one arena, each section 8-byte aligned, and +// records the section offsets. The blob gets 8 bytes of zero padding so +// short key windows can always be loaded whole. Fails when the arena does not +// fit the uint32_t offsets, which also bounds every offset and count stored +// in the tables. +tl::expected<compiled_routes, errors> pack_arena(builder_tables& r) { + compiled_routes out{}; + r.blob.insert(r.blob.end(), 8, '\0'); + uint64_t total = 0; + const auto reserve = [&](size_t bytes) { + const uint64_t offset = total; + total += (bytes + 7) & ~size_t{7}; + return static_cast<uint32_t>(offset); + }; + const auto bytes_of = [](const auto& v) { return v.size() * sizeof(v[0]); }; + out.nodes_offset = reserve(bytes_of(r.nodes)); + out.hashes_offset = reserve(bytes_of(r.hashes)); + out.edges_offset = reserve(bytes_of(r.edges)); + out.slots_offset = reserve(bytes_of(r.slots)); + out.blob_offset = reserve(bytes_of(r.blob)); + out.routes_offset = reserve(bytes_of(r.routes)); + out.segments_offset = reserve(bytes_of(r.segments)); + out.aux_offset = reserve(bytes_of(r.aux)); + out.root_index_offset = reserve(bytes_of(r.root_index)); + // LCOV_EXCL_START + if (total > UINT32_MAX) { + return tl::unexpected(errors::type_error); + } + // LCOV_EXCL_STOP + out.arena.assign(static_cast<size_t>(total), 0); + const auto place = [&](uint32_t offset, const auto& v) { + if (!v.empty()) { + std::memcpy(out.arena.data() + offset, v.data(), v.size() * sizeof(v[0])); } + }; + place(out.nodes_offset, r.nodes); + place(out.hashes_offset, r.hashes); + place(out.edges_offset, r.edges); + place(out.slots_offset, r.slots); + place(out.blob_offset, r.blob); + place(out.routes_offset, r.routes); + place(out.segments_offset, r.segments); + place(out.aux_offset, r.aux); + place(out.root_index_offset, r.root_index); + out.n_routes = static_cast<uint32_t>(r.routes.size()); + out.n_aux_all = r.n_aux_all; + return out; +} - // Append the result of running escape a pattern string given part's prefix - // to the end of result. - result.append(escape_pattern_string(part.prefix)); +// Fills route.kind_sequence / kind_length from route.segments. +void compute_kind_sequence(route_info& route) noexcept { + uint64_t seq = 0; + const size_t n = route.segments.size(); + for (size_t j = 0; j < n && j < 32; j++) { + seq |= static_cast<uint64_t>(route.segments[j].kind) << (62 - 2 * j); + } + route.kind_sequence = seq; + route.kind_length = static_cast<uint8_t>(n < 255 ? n : 255); +} - // If custom name is true: - if (custom_name) { - // Append ":" to the end of result. - result.append(":"); - // Append part's name to the end of result. - result.append(part.name); - } +} // namespace - // If part's type is "regexp" then: - if (part.type == url_pattern_part_type::REGEXP) { - // Append "(" to the end of result. - result.append("("); - // Append part's value to the end of result. - result.append(part.value); - // Append ")" to the end of result. - result.append(")"); - } else if (part.type == url_pattern_part_type::SEGMENT_WILDCARD && - !custom_name) { - // Otherwise if part's type is "segment-wildcard" and custom name is - // false: Append "(" to the end of result. - result.append("("); - // Append the result of running generate a segment wildcard regexp given - // options to the end of result. - result.append(generate_segment_wildcard_regexp(options)); - // Append ")" to the end of result. - result.append(")"); - } else if (part.type == url_pattern_part_type::FULL_WILDCARD) { - // Otherwise if part's type is "full-wildcard": - // If custom name is false and one of the following is true: - // - previous part is null; or - // - previous part's type is "fixed-text"; or - // - previous part's modifier is not "none"; or - // - needs grouping is true; or - // - part's prefix is not the empty string - // - then append "*" to the end of result. - if (!custom_name && - (!previous_part || - previous_part->type == url_pattern_part_type::FIXED_TEXT || - previous_part->modifier != url_pattern_part_modifier::none || - needs_grouping || !part.prefix.empty())) { - result.append("*"); +// ---- compiler entry points ------------------------------------------------- + +bool classify_parts(const std::vector<url_pattern_part>& parts, + std::vector<route_segment>& segments, + std::vector<std::string>& group_names) { + segments.clear(); + group_names.clear(); + bool started = false; // leading '/' consumed + bool group_open = false; // the open segment slot is a group + bool wildcard_seen = false; // a "*" segment was consumed (must stay last) + std::string literal; + const auto close_segment = [&]() { + if (!group_open) { + segments.push_back(route_segment{segment_kind::literal, literal}); + } + literal.clear(); + group_open = false; + }; + const auto process_text = [&](std::string_view text) { + for (const char c : text) { + if (wildcard_seen) { + return false; // nothing may follow a "*" segment + } + if (c == '/') { + if (!started) { + started = true; + } else { + close_segment(); + } } else { - // Append "(" to the end of result. - // Append full wildcard regexp value to the end of result. - // Append ")" to the end of result. - result.append("(.*)"); + if (!started || group_open) { + return false; // text before '/', or suffix text after a group + } + literal += c; } } - - // If all of the following are true: - // - part's type is "segment-wildcard"; and - // - custom name is true; and - // - part's suffix is not the empty string; and - // - The result of running is a valid name code point given part's suffix's - // first code point and the boolean false is true then append U+005C (\) to - // the end of result. - if (part.type == url_pattern_part_type::SEGMENT_WILDCARD && custom_name && - !part.suffix.empty() && - idna::valid_name_code_point(part.suffix[0], false)) { - result.append("\\"); + return true; + }; + for (const url_pattern_part& part : parts) { + if (part.type == url_pattern_part_type::FIXED_TEXT && + part.modifier == url_pattern_part_modifier::none) { + if (!process_text(part.prefix) || !process_text(part.value) || + !process_text(part.suffix)) { + return false; + } + } else if ((part.type == url_pattern_part_type::SEGMENT_WILDCARD || + part.type == url_pattern_part_type::FULL_WILDCARD) && + part.modifier == url_pattern_part_modifier::none && + part.suffix.empty()) { + if (wildcard_seen) { + return false; + } + if (part.prefix == "/") { + if (!started) { + started = true; + } else { + close_segment(); + } + } else if (part.prefix.empty()) { + // The group must occupy a whole, freshly opened segment slot. + if (!started || group_open || !literal.empty()) { + return false; + } + } else { + return false; // group not aligned on a '/' boundary + } + const bool is_wildcard = + part.type == url_pattern_part_type::FULL_WILDCARD; + segments.push_back(route_segment{ + is_wildcard ? segment_kind::wildcard : segment_kind::param, + part.name}); + group_names.push_back(part.name); + group_open = true; + wildcard_seen = is_wildcard; + } else { + return false; // regexp group or a "?" / "+" / "*" modifier } + } + if (!started) { + // Only the empty pattern (zero parts) is representable without a leading + // '/': it matches exactly the empty pathname. + return parts.empty(); + } + close_segment(); + return true; +} - // Append the result of running escape a pattern string given part's suffix - // to the end of result. - result.append(escape_pattern_string(part.suffix)); - // If needs grouping is true, then append "}" to the end of result. - if (needs_grouping) result.append("}"); - // Append the result of running convert a modifier to a string given part's - // modifier to the end of result. - result.append(convert_modifier_to_string(part.modifier)); +void finalize_route(route_info& route) noexcept { + compute_kind_sequence(route); + route.all_literal = true; + route.has_wildcard = false; + size_t n_params = 0; + // A trie edge keeps its literal segment length in edge_record::key_length, a + // uint16_t. A literal longer than that wraps around, so the trie would match + // a shorter, truncated length (e.g. a 65536-byte segment becomes length 0 and + // matches an empty segment). Keep such a route out of the trie and let the + // sequential matcher, which compares the whole segment, answer it. + bool literal_fits_edge = true; + for (const route_segment& s : route.segments) { + if (s.kind != segment_kind::literal) { + route.all_literal = false; + if (s.kind == segment_kind::param) { + n_params++; + } else { + route.has_wildcard = true; + } + } else if (s.text.size() > std::numeric_limits<uint16_t>::max()) { + literal_fits_edge = false; + } + } + const size_t n_captures = n_params + (route.has_wildcard ? 1 : 0); + const bool trie_safe = !route.segments.empty() && + route.segments.size() <= max_trie_pattern_segments && + n_captures <= max_captures_per_route && + literal_fits_edge; + route.mode = trie_safe ? route_mode::trie : route_mode::sequential; +} + +void approximate_kind_sequence(const std::vector<url_pattern_part>& parts, + route_info& route) { + std::vector<uint8_t> kinds; + // The route's segment shape, as far as it is known: literal segments carry + // their text, opaque ones (a ":name" group, alone or mixed with text) are + // params. Exact while every group is a ":name" segment wildcard, which + // cannot match '/': then the segment count and every literal position are + // certain. A custom "(...)" group, a "*" or a modifier can span segments, + // so from there on nothing is known and only the anchored literal prefix + // before it is kept. + std::vector<route_segment> shape; + std::string literal; + bool started = false; + bool open = false; + bool leading_slash = false; // the pattern is anchored at a '/' + bool exact = true; // no part can span a segment boundary + bool tail_known = true; // segments after the last closed one are known + uint8_t current = 0; + // Closes the open segment; `complete` is true only when a '/' of fixed + // text closed it, i.e. the segment is exactly what was accumulated. + const auto close = [&](bool complete) { + if (open) { + kinds.push_back(current); + if (complete || exact) { + shape.push_back(current == 0 + ? route_segment{segment_kind::literal, literal} + : route_segment{segment_kind::param, {}}); + } else { + tail_known = false; + } + open = false; + current = 0; + } + literal.clear(); + }; + const auto process_text = [&](std::string_view text) { + for (const char c : text) { + if (c == '/') { + if (started) { + close(true); + } else { + leading_slash = true; + } + started = true; + open = true; + current = 0; + } else { + if (!started) { + started = true; + } + if (!open) { + open = true; + current = 0; + } + literal += c; + } + } + }; + const auto add_group = [&](uint8_t kind) { + if (!open) { + started = true; + open = true; + current = 0; + } + current = current < kind ? kind : current; + }; + for (const url_pattern_part& part : parts) { + if (part.type == url_pattern_part_type::FULL_WILDCARD || + part.modifier != url_pattern_part_modifier::none) { + // A greedy or modified group can span segments: treat the rest of the + // route as a wildcard tail and stop. A "/" prefix closes the previous + // segment only when this part must occur. An optional ("?") or + // zero-or-more ("*") part, prefix included, may be absent, so the text + // after it stays in the same segment ("/reports{/:id}?.json" matches + // "/reports.json"). Treating that "/" as a definite boundary certified + // a segment the input does not have, and the shape check rejected the + // match before the provider ran. + exact = false; + const bool must_occur = + part.modifier != url_pattern_part_modifier::optional && + part.modifier != url_pattern_part_modifier::zero_or_more; + close(must_occur && part.prefix == "/"); + tail_known = false; + kinds.push_back(2); + break; + } + if (part.type == url_pattern_part_type::FIXED_TEXT) { + process_text(part.value); + } else { // SEGMENT_WILDCARD or REGEXP, modifier none + if (part.type == url_pattern_part_type::REGEXP) { + exact = false; // a custom group may match '/' + } + process_text(part.prefix); + add_group(1); + process_text(part.suffix); + } + } + close(exact); + uint64_t seq = 0; + for (size_t j = 0; j < kinds.size() && j < 32; j++) { + seq |= static_cast<uint64_t>(kinds[j]) << (62 - 2 * j); + } + route.kind_sequence = seq; + route.kind_length = + static_cast<uint8_t>(kinds.size() < 255 ? kinds.size() : 255); + route.mode = route_mode::regexp; + route.all_literal = false; + route.segments.clear(); + if (!leading_slash) { + // Not anchored at '/': nothing about the segments is known. + route.has_wildcard = true; + return; } - // Return result. - return result; + // has_wildcard here means "the tail is unconstrained": the input needs at + // least segments.size() segments; otherwise exactly that many. + route.has_wildcard = !(exact && tail_known); + if (route.has_wildcard) { + // Keep only the anchored literal prefix. + size_t n_prefix = 0; + while (n_prefix < shape.size() && + shape[n_prefix].kind == segment_kind::literal) { + n_prefix++; + } + shape.resize(n_prefix); + } + route.segments = std::move(shape); +} + +tl::expected<compiled_routes, errors> compile_route_set( + std::vector<route_info>& routes) { + builder_tables r{}; + const std::vector<transient_node> t = build_trie(routes); + compile_route_records(r, routes); + const std::vector<int32_t> order = layout_nodes(r, t); + compile_dispatch(r, t, order); + encode_leaf_shortcuts(r); // last: must not confuse the stages above + build_segment_table(r, routes); + if (!build_aux_table(r, routes)) { + return tl::unexpected(errors::type_error); + } + auto out = pack_arena(r); + if (!out) { + return out; + } + out->group_names.resize(routes.size()); + for (size_t i = 0; i < routes.size(); i++) { + if (routes[i].mode != route_mode::regexp) { + out->group_names[i] = routes[i].group_names; + } + } + return out; } -} // namespace ada::url_pattern_helpers -#endif // ADA_INCLUDE_URL_PATTERN -/* end file src/url_pattern_helpers.cpp */ -/* begin file src/url_pattern_regex.cpp */ -#if ADA_INCLUDE_URL_PATTERN +} // namespace ada::url_pattern_list_compiler +namespace ada::url_pattern_list_detail { -namespace ada::url_pattern_regex { +tl::expected<compiled_routes, errors> compile_pathname_patterns( + std::span<const std::string> patterns, bool ignore_case) { + if (patterns.size() > url_pattern_list_limits::max_routes) { + return tl::unexpected(errors::type_error); + } + namespace compiler = url_pattern_list_compiler; + std::vector<compiler::route_info> routes; + routes.reserve(patterns.size()); + for (const std::string& pattern : patterns) { + // The pattern side goes through ada's own URLPattern machinery: the + // pattern parser tokenizes and canonicalizes exactly as a URLPattern + // pathname component would. + auto options = url_pattern_compile_component_options::PATHNAME; + auto part_list = url_pattern_helpers::parse_pattern_string( + pattern, options, url_pattern_helpers::canonicalize_pathname); + if (!part_list) { + return tl::unexpected(part_list.error()); + } + compiler::route_info route{}; + if (compiler::classify_parts(*part_list, route.segments, + route.group_names)) { + compiler::finalize_route(route); + } else { + // The pattern needs URLPattern regexp semantics: the caller compiles + // it as a pathname component through the provider; it participates + // in the priority order via its approximated kind sequence. + compiler::approximate_kind_sequence(*part_list, route); + } + if (ignore_case) { + // The compiled literals are ASCII-folded; the matcher folds the input + // the same way. + for (compiler::route_segment& s : route.segments) { + if (s.kind == compiler::segment_kind::literal) { + ascii_fold(s.text.data(), static_cast<uint32_t>(s.text.size()), + s.text.data()); + } + } + } + routes.push_back(std::move(route)); + } + auto compiled = compiler::compile_route_set(routes); + if (compiled) { + compiled->ignore_case = ignore_case ? 1 : 0; + } + return compiled; +} -#ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER -std::optional<std::regex> std_regex_provider::create_instance( - std::string_view pattern, bool ignore_case) { - // Let flags be an empty string. - // If options's ignore case is true then set flags to "vi". - // Otherwise set flags to "v" - auto flags = ignore_case - ? std::regex::icase | std::regex_constants::ECMAScript - : std::regex_constants::ECMAScript; - try { - return std::regex(pattern.data(), pattern.size(), flags); - } catch (const std::regex_error& e) { - (void)e; - ada_log("std_regex_provider::create_instance failed:", e.what()); - return std::nullopt; +namespace { + +// Literal-segment compare against the blob, folding the input on request +// (the blob text is already folded). +bool literal_equals(std::string_view s, const char* text, uint32_t length, + bool fold_input) noexcept { + if (s.size() != length) { + return false; + } + if (!fold_input) { + return s.size() == 0 || std::memcmp(s.data(), text, s.size()) == 0; + } + for (size_t i = 0; i < s.size(); i++) { + const uint8_t c = static_cast<uint8_t>(s[i]); + const char folded = + static_cast<char>(c | ((c >= 'A' && c <= 'Z') ? 0x20u : 0u)); + if (folded != text[i]) { + return false; + } } + return true; } -std::optional<std::vector<std::optional<std::string>>> -std_regex_provider::regex_search(std::string_view input, - const std::regex& pattern) { - // Use iterator-based regex_search to avoid string allocation - std::match_results<std::string_view::const_iterator> match_result; - try { - if (!std::regex_search(input.begin(), input.end(), match_result, pattern, - std::regex_constants::match_any)) { - return std::nullopt; +} // namespace + +// Kept out of line on purpose: inlined into the walk, this loop cost the +// static and ":param" paths, which never run it, about 5 ns through register +// allocation; as a call it costs only wildcard hits. It lives in this +// translation unit rather than the header because MSVC's ada_never_inline +// expands to __declspec(noinline) with no inline linkage, so a definition in +// the header is emitted in every translation unit and the link fails. +// +// On AArch64 whole 16-byte blocks go through NEON (a running byte minimum); +// the rest is SWAR, 8 bytes per step: "some byte is below 0x20" ("hasless" +// of Bit Twiddling Hacks) is exact as a yes/no answer, because a borrow can +// only leave a lane that itself qualifies. Only a tail holding a control +// byte gets the exact byte check. +bool wildcard_tail_ok(const char* p, uint32_t n) noexcept { + constexpr uint64_t spaces = 0x2020202020202020ull; + constexpr uint64_t highs = 0x8080808080808080ull; + const auto below_space = [](uint64_t x) noexcept { + return (x - spaces) & ~x & highs; + }; + uint64_t control = 0; + uint32_t i = 0; +#if ADA_NEON + if (n >= 16) { + uint8x16_t lowest = vdupq_n_u8(0xFF); + for (; i + 16 <= n; i += 16) { + lowest = + vminq_u8(lowest, vld1q_u8(reinterpret_cast<const uint8_t*>(p + i))); } - } catch (const std::regex_error& e) { - (void)e; - ada_log("std_regex_provider::regex_search failed:", e.what()); - return std::nullopt; + control = vminvq_u8(lowest) < 0x20 ? 1 : 0; } - std::vector<std::optional<std::string>> matches; - // An empty input can still match with capture groups (e.g. "(x*)" or an - // optional ":a?" against ""), so the group values must be extracted here - // just like for a non-empty input. A successful regex_search always leaves - // the full match at index 0, so match_result is never empty at this point. - if (match_result.empty()) { - return matches; +#endif + for (; i + 8 <= n; i += 8) { + control |= below_space(load8_le(p + i)); } - matches.reserve(match_result.size()); - for (size_t i = 1; i < match_result.size(); ++i) { - if (auto entry = match_result[i]; entry.matched) { - matches.emplace_back(entry.str()); - } else { - // A capture group that did not participate in the match is undefined, - // not absent. Emitting nullopt keeps the result aligned by position with - // the component's group name list; dropping it shifts every later group - // onto the wrong name. - matches.emplace_back(std::nullopt); + if (i < n) { // 1..7 bytes, padded with spaces + control |= below_space(gather_le(p + i, n - i) | + (spaces & ~low_bytes_mask(n - i))); + } + if (control == 0) { + return true; + } + for (uint32_t j = 0; j < n; j++) { + if (p[j] == '\n' || p[j] == '\r') { + return false; } } - return matches; + return true; } -bool std_regex_provider::regex_match(std::string_view input, - const std::regex& pattern) { - try { - return std::regex_match(input.begin(), input.end(), pattern); - } catch (const std::regex_error& e) { - (void)e; - ada_log("std_regex_provider::regex_match failed:", e.what()); +bool match_regexp_shape(const compiled_routes& r, uint32_t route, + std::string_view pathname, bool fold_input) noexcept { + const route_record& rt = r.section<route_record>(r.routes_offset)[route]; + const segment_record* segs = + r.section<segment_record>(r.segments_offset) + rt.segment_first; + const char* blob = r.section<char>(r.blob_offset); + if (rt.segment_count == 0 && rt.wild != 0) { + return true; // nothing is known about the route's shape + } + if (pathname.empty() || pathname[0] != '/') { + return false; // a known shape always starts with '/' + } + size_t seg_start = 1; + for (uint32_t si = 0; si < rt.segment_count; si++) { + if (seg_start > pathname.size()) { + return false; // fewer segments than the shape + } + const size_t slash = pathname.find('/', seg_start); + const size_t seg_end = + slash == std::string_view::npos ? pathname.size() : slash; + const std::string_view s(pathname.data() + seg_start, seg_end - seg_start); + if (segs[si].kind == 0) { // literal + if (!literal_equals(s, blob + segs[si].text_offset, segs[si].text_length, + fold_input)) { + return false; + } + } else if (s.empty()) { + return false; // a ":name" group, mixed or not, never binds "" + } + seg_start = seg_end + 1; + } + // An exact shape admits no further segments. + return rt.wild != 0 || seg_start == pathname.size() + 1; +} + +bool match_route_sequential(const compiled_routes& r, uint32_t route, + std::string_view pathname, bool fold_input, + engine_result& result) noexcept { + using url_pattern_list_limits::max_captures_per_route; + result.capture_count = 0; + result.captures_truncated = false; + const route_record& rt = r.section<route_record>(r.routes_offset)[route]; + const segment_record* segs = + r.section<segment_record>(r.segments_offset) + rt.segment_first; + const char* blob = r.section<char>(r.blob_offset); + const size_t n_pattern = rt.segment_count; + if (n_pattern == 0) { + return pathname.empty(); // the empty pattern matches only "" + } + if (pathname.empty() || pathname[0] != '/') { return false; } + const bool wild = rt.wild != 0; // wildcard is always the last segment + const size_t n_fixed = wild ? n_pattern - 1 : n_pattern; + uint32_t total_captures = 0; + const auto add_capture = [&](size_t offset, size_t length) { + if (total_captures < max_captures_per_route) { + result.captures[total_captures] = {static_cast<uint32_t>(offset), + static_cast<uint32_t>(length)}; + } else { + result.captures_truncated = true; + } + total_captures++; + }; + size_t seg_start = 1; + for (size_t si = 0; si < n_fixed; si++) { + if (seg_start > pathname.size()) { + return false; // the input has fewer segments than the pattern + } + const size_t slash = pathname.find('/', seg_start); + const size_t seg_end = + slash == std::string_view::npos ? pathname.size() : slash; + // seg_start <= pathname.size() was checked above, so this is in range + // (spelled without substr to keep the function provably non-throwing). + const std::string_view s(pathname.data() + seg_start, seg_end - seg_start); + if (segs[si].kind == 0) { // literal + if (!literal_equals(s, blob + segs[si].text_offset, segs[si].text_length, + fold_input)) { + return false; + } + } else { // param: binds one non-empty segment + if (s.empty()) { + return false; + } + add_capture(seg_start, s.size()); + } + seg_start = seg_end + 1; + } + if (wild) { + if (seg_start > pathname.size()) { + return false; // the wildcard still needs its (possibly empty) segment + } + // "(.*)" does not match a line terminator (see wildcard_tail_ok). + if (pathname.find_first_of("\n\r", seg_start) != std::string_view::npos) { + return false; + } + add_capture(seg_start, pathname.size() - seg_start); + } else if (seg_start != pathname.size() + 1) { + return false; // the input has more segments than the pattern + } + result.capture_count = total_captures < max_captures_per_route + ? total_captures + : max_captures_per_route; + return true; } -#endif // ADA_USE_UNSAFE_STD_REGEX_PROVIDER - -} // namespace ada::url_pattern_regex - +} // namespace ada::url_pattern_list_detail #endif // ADA_INCLUDE_URL_PATTERN -/* end file src/url_pattern_regex.cpp */ +/* end file src/url_pattern_list.cpp */ +#endif #endif // ADA_INCLUDE_URL_PATTERN /* begin file src/ada_c.cpp */ @@ -14833,8 +18964,10 @@ ada_owned_string ada_get_origin(ada_url result) noexcept { } std::string out = r->get_origin(); owned.length = out.size(); - owned.data = new char[owned.length]; + // +1 for a trailing NUL. length does not include it. (#1307) + owned.data = new char[owned.length + 1]; memcpy((void*)owned.data, out.data(), owned.length); + const_cast<char*>(owned.data)[owned.length] = '\0'; return owned; } @@ -15164,8 +19297,9 @@ ada_owned_string ada_idna_to_unicode(const char* input, size_t length) { std::string out = ada::idna::to_unicode(std::string_view(input, length)); ada_owned_string owned{}; owned.length = out.length(); - owned.data = new char[owned.length]; + owned.data = new char[owned.length + 1]; memcpy((void*)owned.data, out.data(), owned.length); + const_cast<char*>(owned.data)[owned.length] = '\0'; return owned; } @@ -15173,8 +19307,9 @@ ada_owned_string ada_idna_to_ascii(const char* input, size_t length) { std::string out = ada::idna::to_ascii(std::string_view(input, length)); ada_owned_string owned{}; owned.length = out.size(); - owned.data = new char[owned.length]; + owned.data = new char[owned.length + 1]; memcpy((void*)owned.data, out.data(), owned.length); + const_cast<char*>(owned.data)[owned.length] = '\0'; return owned; } @@ -15196,8 +19331,9 @@ ada_owned_string ada_search_params_to_string(ada_url_search_params result) { std::string out = r->to_string(); ada_owned_string owned{}; owned.length = out.size(); - owned.data = new char[owned.length]; + owned.data = new char[owned.length + 1]; memcpy((void*)owned.data, out.data(), owned.length); + const_cast<char*>(owned.data)[owned.length] = '\0'; return owned; } @@ -15317,15 +19453,31 @@ ada_strings ada_search_params_get_all(ada_url_search_params result, r->get_all(std::string_view(key, key_length))); } +// next() returns views into the iterator's params, so each C iterator owns a +// copy that outlives ada_free_search_params and later mutations. +struct ada_c_search_params_keys_iter { + ada::url_search_params params{}; + ada::url_search_params_keys_iter iter = params.get_keys(); +}; + +struct ada_c_search_params_values_iter { + ada::url_search_params params{}; + ada::url_search_params_values_iter iter = params.get_values(); +}; + +struct ada_c_search_params_entries_iter { + ada::url_search_params params{}; + ada::url_search_params_entries_iter iter = params.get_entries(); +}; + ada_url_search_params_keys_iter ada_search_params_get_keys( ada_url_search_params result) { ada::result<ada::url_search_params>& r = *(ada::result<ada::url_search_params>*)result; if (!r) { - return new ada::result<ada::url_search_params_keys_iter>( - ada::url_search_params_keys_iter()); + return new ada_c_search_params_keys_iter{}; } - return new ada::result<ada::url_search_params_keys_iter>(r->get_keys()); + return new ada_c_search_params_keys_iter{*r}; } ada_url_search_params_values_iter ada_search_params_get_values( @@ -15333,10 +19485,9 @@ ada_url_search_params_values_iter ada_search_params_get_values( ada::result<ada::url_search_params>& r = *(ada::result<ada::url_search_params>*)result; if (!r) { - return new ada::result<ada::url_search_params_values_iter>( - ada::url_search_params_values_iter()); + return new ada_c_search_params_values_iter{}; } - return new ada::result<ada::url_search_params_values_iter>(r->get_values()); + return new ada_c_search_params_values_iter{*r}; } ada_url_search_params_entries_iter ada_search_params_get_entries( @@ -15344,10 +19495,9 @@ ada_url_search_params_entries_iter ada_search_params_get_entries( ada::result<ada::url_search_params>& r = *(ada::result<ada::url_search_params>*)result; if (!r) { - return new ada::result<ada::url_search_params_entries_iter>( - ada::url_search_params_entries_iter()); + return new ada_c_search_params_entries_iter{}; } - return new ada::result<ada::url_search_params_entries_iter>(r->get_entries()); + return new ada_c_search_params_entries_iter{*r}; } void ada_free_strings(ada_strings result) { @@ -15365,7 +19515,7 @@ size_t ada_strings_size(ada_strings result) { ada_string ada_strings_get(ada_strings result, size_t index) { auto* r = (ada::result<std::vector<std::string>>*)result; - if (!r) { + if (!r || index >= (*r)->size()) { return ada_string_create(nullptr, 0); } std::string_view view = (*r)->at(index); @@ -15373,17 +19523,17 @@ ada_string ada_strings_get(ada_strings result, size_t index) { } void ada_free_search_params_keys_iter(ada_url_search_params_keys_iter result) { - auto* r = (ada::result<ada::url_search_params_keys_iter>*)result; + auto* r = (ada_c_search_params_keys_iter*)result; delete r; } ada_string ada_search_params_keys_iter_next( ada_url_search_params_keys_iter result) { - auto* r = (ada::result<ada::url_search_params_keys_iter>*)result; + auto* r = (ada_c_search_params_keys_iter*)result; if (!r) { return ada_string_create(nullptr, 0); } - auto next = (*r)->next(); + auto next = r->iter.next(); if (!next.has_value()) { return ada_string_create(nullptr, 0); } @@ -15392,26 +19542,26 @@ ada_string ada_search_params_keys_iter_next( bool ada_search_params_keys_iter_has_next( ada_url_search_params_keys_iter result) { - auto* r = (ada::result<ada::url_search_params_keys_iter>*)result; + auto* r = (ada_c_search_params_keys_iter*)result; if (!r) { return false; } - return (*r)->has_next(); + return r->iter.has_next(); } void ada_free_search_params_values_iter( ada_url_search_params_values_iter result) { - auto* r = (ada::result<ada::url_search_params_values_iter>*)result; + auto* r = (ada_c_search_params_values_iter*)result; delete r; } ada_string ada_search_params_values_iter_next( ada_url_search_params_values_iter result) { - auto* r = (ada::result<ada::url_search_params_values_iter>*)result; + auto* r = (ada_c_search_params_values_iter*)result; if (!r) { return ada_string_create(nullptr, 0); } - auto next = (*r)->next(); + auto next = r->iter.next(); if (!next.has_value()) { return ada_string_create(nullptr, 0); } @@ -15420,24 +19570,24 @@ ada_string ada_search_params_values_iter_next( bool ada_search_params_values_iter_has_next( ada_url_search_params_values_iter result) { - auto* r = (ada::result<ada::url_search_params_values_iter>*)result; + auto* r = (ada_c_search_params_values_iter*)result; if (!r) { return false; } - return (*r)->has_next(); + return r->iter.has_next(); } void ada_free_search_params_entries_iter( ada_url_search_params_entries_iter result) { - auto* r = (ada::result<ada::url_search_params_entries_iter>*)result; + auto* r = (ada_c_search_params_entries_iter*)result; delete r; } ada_string_pair ada_search_params_entries_iter_next( ada_url_search_params_entries_iter result) { - auto* r = (ada::result<ada::url_search_params_entries_iter>*)result; + auto* r = (ada_c_search_params_entries_iter*)result; if (!r) return {ada_string_create(nullptr, 0), ada_string_create(nullptr, 0)}; - auto next = (*r)->next(); + auto next = r->iter.next(); if (!next.has_value()) { return {ada_string_create(nullptr, 0), ada_string_create(nullptr, 0)}; } @@ -15448,11 +19598,11 @@ ada_string_pair ada_search_params_entries_iter_next( bool ada_search_params_entries_iter_has_next( ada_url_search_params_entries_iter result) { - auto* r = (ada::result<ada::url_search_params_entries_iter>*)result; + auto* r = (ada_c_search_params_entries_iter*)result; if (!r) { return false; } - return (*r)->has_next(); + return r->iter.has_next(); } void ada_set_max_input_length(uint32_t length) noexcept { diff --git a/deps/ada/ada.h b/deps/ada/ada.h index dc96fe834308..df3014e2a61a 100644 --- a/deps/ada/ada.h +++ b/deps/ada/ada.h @@ -1,4 +1,4 @@ -/* auto-generated on 2026-07-27 16:10:09 -0400. Do not edit! */ +/* auto-generated on 2026-11-19 15:19:30 -0500. Do not edit! */ /* begin file include/ada.h */ /** * @file ada.h @@ -30,7 +30,7 @@ #define ADA_H /* begin file include/ada/ada_idna.h */ -/* auto-generated on 2026-07-12 20:34:08 -0400. Do not edit! */ +/* auto-generated on 2026-11-19 15:08:48 -0500. Do not edit! */ /* begin file include/idna.h */ #ifndef ADA_IDNA_H #define ADA_IDNA_H @@ -150,7 +150,8 @@ bool is_label_valid(std::u32string_view label); namespace ada::idna { -// Maximum accepted UTF-8 domain length for to_ascii / to_unicode. +// Maximum accepted UTF-8 domain length for non-ASCII to_ascii input and for +// to_unicode input. // Bounds heap growth under untrusted input (DoS resistance). DNS wire limits // are smaller; this allows long Unicode labels used in URL tests/fixtures. inline constexpr size_t max_domain_input_bytes = 16384; @@ -167,8 +168,9 @@ namespace ada::idna { // decoding: percent decoding should be done prior to calling this function. We // do not remove tabs and spaces, they should have been removed prior to calling // this function. We also do not trim control characters. We also assume that -// the input is not empty. We return "" on error. Inputs longer than -// max_domain_input_bytes are rejected. +// the input is not empty. We return "" on error. Non-ASCII inputs longer than +// max_domain_input_bytes are rejected; ASCII inputs of any length are accepted +// (they are only lowercased). // // This function may accept or even produce invalid domains (WHATWG carve-outs). std::string to_ascii(std::string_view ut8_string); @@ -540,6 +542,14 @@ namespace ada { #define ADA_INCLUDE_URL_PATTERN 1 #endif // ADA_INCLUDE_URL_PATTERN +// When set (the default), NEON all-zero tests use an integer compare. Define +// it to 0 to reinterpret the bits as a double and compare against 0.0: that +// avoids a GPR transfer but is incorrect if flush-to-zero is enabled (e.g., +// when the application is built with -ffast-math). +#ifndef ADA_NEON_SAFE_ZERO_CHECK +#define ADA_NEON_SAFE_ZERO_CHECK 1 +#endif // ADA_NEON_SAFE_ZERO_CHECK + #endif // ADA_COMMON_DEFS_H /* end file include/ada/common_defs.h */ #include <cstdint> @@ -568,6 +578,8 @@ ada_really_inline constexpr bool bit_at(const uint8_t a[], uint8_t i); #define ADA_CHARACTER_SETS_INL_H +#include <cstdint> + /** * These functions are not part of our public API and may * change at any time. @@ -1088,8 +1100,8 @@ ada_really_inline constexpr bool bit_at(const uint8_t a[], const uint8_t i) { #define ADA_CHECKERS_INL_H #include <bit> +#include <cstddef> #include <cstdint> -#include <cstring> #include <string_view> /* begin file include/ada/checkers.h */ /** @@ -1100,6 +1112,7 @@ ada_really_inline constexpr bool bit_at(const uint8_t a[], const uint8_t i) { #define ADA_CHECKERS_H +#include <cstdint> #include <cstring> #include <string_view> @@ -1129,20 +1142,6 @@ constexpr char to_lower(char x) noexcept; */ constexpr bool is_alpha(char x) noexcept; -/** - * @private - * Check whether a string starts with 0x or 0X. The function is only - * safe if input.size() >=2. - * - * @see has_hex_prefix - */ -constexpr bool has_hex_prefix_unsafe(std::string_view input); -/** - * @private - * Check whether a string starts with 0x or 0X. - */ -constexpr bool has_hex_prefix(std::string_view input); - /** * @private * Check whether x is an ASCII digit. More likely to be inlined than @@ -1180,6 +1179,19 @@ inline constexpr bool is_normalized_windows_drive_letter( */ ada_really_inline constexpr bool is_ipv4(std::string_view view) noexcept; +/** + * @private + * Cheap pre-check for the WHATWG "ends in a number" / IPv4-host cases. + * False means the host cannot be IPv4: the last label is empty, does not + * start with an ASCII digit, or contains a character other than a hex + * digit or x/X. True means the slower IPv4 parsers should run. + * + * Safe on mixed-case input (unlike is_ipv4, which expects a lowercased + * host). + */ +ada_really_inline constexpr bool last_label_may_be_a_number( + std::string_view view) noexcept; + /** * @private * Returns a bitset. If the first bit is set, then at least one character needs @@ -1225,32 +1237,44 @@ constexpr uint64_t ipv4_fast_fail = uint64_t(1) << 32; #endif // ADA_CHECKERS_H /* end file include/ada/checkers.h */ -#if defined(ADA_AVX512) +#if defined(ADA_AVX512) && defined(__AVX512VBMI2__) #include <immintrin.h> #endif namespace ada::checkers { -constexpr bool has_hex_prefix_unsafe(std::string_view input) { - // This is actually efficient code, see has_hex_prefix for the assembly. - constexpr bool is_little_endian = std::endian::native == std::endian::little; - constexpr uint16_t word0x = 0x7830; - uint16_t two_first_bytes = - static_cast<uint16_t>(input[0]) | - static_cast<uint16_t>((static_cast<uint16_t>(input[1]) << 8)); - if constexpr (is_little_endian) { - two_first_bytes |= 0x2000; - } else { - two_first_bytes |= 0x020; - } - return two_first_bytes == word0x; -} +constexpr bool is_digit(char x) noexcept { return (x >= '0') & (x <= '9'); } -constexpr bool has_hex_prefix(std::string_view input) { - return input.size() >= 2 && has_hex_prefix_unsafe(input); +constexpr bool is_ipv4_number_char(char x) noexcept { + const unsigned char c = static_cast<unsigned char>(x); + return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || + (c >= 'A' && c <= 'F') || c == 'x' || c == 'X'; } -constexpr bool is_digit(char x) noexcept { return (x >= '0') & (x <= '9'); } +constexpr bool last_label_may_be_a_number(std::string_view view) noexcept { + if (view.empty()) { + return false; + } + const char* start = view.data(); + const char* end = start + view.size(); + if (end[-1] == '.') { + --end; + if (end == start) { + return false; + } + } + if (!is_ipv4_number_char(end[-1])) { + return false; + } + const char* label = end; + while (label != start && is_ipv4_number_char(label[-1])) { + --label; + } + if (label != start && label[-1] != '.') { + return false; + } + return label != end && is_digit(*label); +} constexpr char to_lower(char x) noexcept { return (x | 0x20); } @@ -1325,68 +1349,101 @@ parse_ipv4_decimal_scalar(const char* p, const char* pend) noexcept { return ipv4; } -#if defined(ADA_AVX512) -// After SIMD validation: fewer rejection branches on convert. -ada_really_inline uint64_t -parse_ipv4_decimal_trusted(const char* p, const char* pend) noexcept { - uint32_t ipv4 = 0; - for (int i = 0; i < 4; ++i) { - uint32_t val = static_cast<uint32_t>(*p - '0'); - ++p; - if (p < pend && static_cast<unsigned char>(*p - '0') <= 9) { - if (val == 0) [[unlikely]] { - return ipv4_fast_fail; - } - val = val * 10u + static_cast<uint32_t>(*p - '0'); - ++p; - if (p < pend && static_cast<unsigned char>(*p - '0') <= 9) { - val = val * 10u + static_cast<uint32_t>(*p - '0'); - ++p; - if (val > 255u) [[unlikely]] { - return ipv4_fast_fail; - } - } - } - ipv4 = (ipv4 << 8) | val; - if (i < 3) { - ++p; // trusted '.' - } - } - return ipv4; // trailing-dot already accounted for by caller via pend -} - -// AVX-512 pure-decimal IPv4 (Lemire/Mula-style masked load + parallel checks). -// No over-read of the source string. Wins when the binary is built with -// -mavx512bw -mavx512vl (or -march that enables them). +#if defined(ADA_AVX512) && defined(__AVX512VBMI2__) +// Table-free AVX-512VL IPv4 parse (simdip parse_ipv4_avx512vl_notab5). +// Needs VBMI2 for vpcompressb; ADA_AVX512 stays BW+VL (IPv6 does not use +// VBMI2). Masked load of exactly `len` bytes (no over-read). Digit +// placement is computed from compressed delimiter positions; octet > 255 +// is a dword compare on the zero-padded reversed digit group, in parallel +// with the convert. Unusual-but-valid forms (octal, hex, leading zeros, +// fewer than four parts) return ipv4_fast_fail so the general parser runs. ada_really_inline uint64_t try_parse_ipv4_avx512(const char* data, size_t len) noexcept { - const __mmask16 live = static_cast<__mmask16>((1u << len) - 1u); - const __m128i input = - _mm_maskz_loadu_epi8(live, reinterpret_cast<const void*>(data)); - const __mmask16 is_dot = - _mm_mask_cmpeq_epi8_mask(live, input, _mm_set1_epi8('.')); - const __m128i shifted = _mm_sub_epi8(input, _mm_set1_epi8('0')); - const __mmask16 is_digit = - _mm_mask_cmplt_epu8_mask(live, shifted, _mm_set1_epi8(10)); - if ((is_digit | is_dot) != live) { - return ipv4_fast_fail; + // One trailing dot is WHATWG-legal ("1.2.3.4."); the SIMD kernel is + // strict four-group dotted-decimal. + if (data[len - 1] == '.') { + --len; } - const unsigned dot_count = - static_cast<unsigned>(_mm_popcnt_u32(static_cast<unsigned>(is_dot))); - size_t effective_len = len; - if (dot_count == 3) { - // ok - } else if (dot_count == 4 && data[len - 1] == '.') { - effective_len = len - 1; // strip trailing dot for convert - } else { + if (len > 15) [[unlikely]] { return ipv4_fast_fail; } - // Convert from a tiny stack copy so trusted peeks stay in-bounds. - alignas(16) char buf[16]{}; - std::memcpy(buf, data, effective_len); - return parse_ipv4_decimal_trusted(buf, buf + effective_len); + +#if defined(__BMI2__) + const uint32_t len_mask = _bzhi_u32(0xFFFFFFFFu, static_cast<unsigned>(len)); +#else + const uint32_t len_mask = (1u << static_cast<unsigned>(len)) - 1u; +#endif + const __mmask16 len_k = static_cast<__mmask16>(len_mask); + const __m128i dot = _mm_set1_epi8('.'); + const __m128i v = + _mm_mask_loadu_epi8(dot, len_k, reinterpret_cast<const void*>(data)); + + const __mmask16 delim = _mm_cmpeq_epi8_mask(v, dot); + const uint32_t dots = static_cast<uint32_t>(delim) & len_mask; + const uint32_t keep = len_mask & ~dots; + + const __m128i zero = _mm_set1_epi8('0'); + const __m128i digits = _mm_sub_epi8(v, zero); + const __mmask16 is_digit = _mm_cmple_epu8_mask(digits, _mm_set1_epi8(9)); + // Junk in a digit slot: inside [0, len) yet neither a digit nor a dot. + const __mmask16 hole = _kandn_mask16(_kor_mask16(delim, is_digit), len_k); + const __m128i v0 = _mm_maskz_mov_epi8(is_digit, digits); + + const __m128i iota = + _mm_setr_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15); + const __m128i c = _mm_maskz_compress_epi8(delim, iota); + const __m128i k_rep = + _mm_setr_epi8(0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3); + const __m128i qi = _mm_shuffle_epi8(c, k_rep); + const __m128i prev = + _mm_shuffle_epi8(_mm_alignr_epi8(c, _mm_set1_epi8(-1), 15), k_rep); + // Reversed group order: lane 4i+j fetches q_i-(j+1), so the dword is + // ones | tens<<8 | hundreds<<16, monotone in the decimal value. + const __m128i offr = _mm_setr_epi8(-1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, + -4, -1, -2, -3, -4); + const __m128i idx = _mm_max_epi8(_mm_add_epi8(qi, offr), prev); + const __m128i padded = _mm_shuffle_epi8(v0, idx); + + const __m128i lim = + _mm_setr_epi8(5, 5, 2, 0, 5, 5, 2, 0, 5, 5, 2, 0, 5, 5, 2, 0); + const __mmask8 over = _mm_cmpgt_epu32_mask(padded, lim); + const __m128i wtsr = + _mm_setr_epi8(1, 10, 100, 0, 1, 10, 100, 0, 1, 10, 100, 0, 1, 10, 100, 0); +#if defined(__AVX512VNNI__) + const __m128i res = _mm_dpbusd_epi32(_mm_setzero_si128(), padded, wtsr); +#else + const __m128i res = + _mm_madd_epi16(_mm_maddubs_epi16(padded, wtsr), _mm_set1_epi16(1)); +#endif + + const __m128i gmin = + _mm_setr_epi8(1, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + const __m128i gmax = + _mm_setr_epi8(2, 2, 2, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i gap = _mm_sub_epi8(c, _mm_slli_si128(c, 1)); + const __mmask16 bad_gap = _mm_cmpgt_epu8_mask(_mm_sub_epi8(gap, gmin), gmax); + + const uint32_t zero_bits = + static_cast<uint32_t>(_mm_cmpeq_epi8_mask(v, zero)); + const uint32_t start_bits = (dots << 1) | 1u; + + const __mmask16 kerr = + _kor_mask16(_kor_mask16(hole, static_cast<__mmask16>(over)), bad_gap); + const uint32_t gerr = static_cast<uint32_t>(_mm_popcnt_u32(dots) ^ 3u) | + (zero_bits & start_bits & (keep >> 1)); + + if ((gerr | static_cast<uint32_t>(kerr)) == 0) [[likely]] { + const uint32_t packed = + static_cast<uint32_t>(_mm_cvtsi128_si32(_mm_cvtepi32_epi8(res))); +#if defined(__GNUC__) || defined(__clang__) + return static_cast<uint64_t>(__builtin_bswap32(packed)); +#else + return static_cast<uint64_t>(_byteswap_ulong(packed)); +#endif + } + return ipv4_fast_fail; } -#endif // ADA_AVX512 +#endif // ADA_AVX512 && __AVX512VBMI2__ } // namespace detail @@ -1394,9 +1451,10 @@ ada_really_inline uint64_t try_parse_ipv4_avx512(const char* data, * Fast pure-decimal IPv4 parse. Returns packed address or ipv4_fast_fail. * Accepts an optional single trailing dot. * - * On AVX-512BW+VL targets, uses a masked-load SIMD kernel (no source - * over-read) inspired by Lemire/Mula. Otherwise uses an unrolled scalar path - * (typically faster than SSE2/NEON pre-validation for these 7-16 byte hosts). + * On AVX-512BW+VL+VBMI2 targets, uses a table-free SIMD parse (masked + * load, no source over-read) based on parse_ipv4_avx512vl_notab5. + * Otherwise uses an unrolled scalar path (typically faster than SSE2/NEON + * pre-validation for these 7-16 byte hosts). */ ada_really_inline uint64_t try_parse_ipv4_fast(std::string_view input) noexcept { @@ -1407,7 +1465,7 @@ try_parse_ipv4_fast(std::string_view input) noexcept { } const char* data = input.data(); -#if defined(ADA_AVX512) +#if defined(ADA_AVX512) && defined(__AVX512VBMI2__) return detail::try_parse_ipv4_avx512(data, len); #else return detail::parse_ipv4_decimal_scalar(data, data + len); @@ -1477,6 +1535,7 @@ constexpr ada_really_inline void log([[maybe_unused]] Args... args) { #define ADA_ENCODING_TYPE_H #include <string> +#include <string_view> namespace ada { @@ -1540,7 +1599,9 @@ ada_warn_unused std::string_view to_string(encoding_type type); #define ADA_SCHEME_H +#include <cstdint> #include <string> +#include <string_view> /** * @namespace ada::scheme @@ -1611,6 +1672,8 @@ constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept; #endif // ADA_SCHEME_H /* end file include/ada/scheme.h */ +#include <cstddef> +#include <cstdint> #include <string> #include <string_view> @@ -1745,11 +1808,15 @@ struct url_base { #endif /* end file include/ada/url_base.h */ +#include <cstddef> +#include <cstdint> +#include <optional> #include <string> #include <string_view> -#include <optional> +#include <utility> #if ADA_DEVELOPMENT_CHECKS +#include <cstdlib> #include <iostream> #endif // ADA_DEVELOPMENT_CHECKS @@ -1983,6 +2050,8 @@ inline int fast_digit_count(uint32_t x) noexcept { #ifndef ADA_PARSER_H #define ADA_PARSER_H +#include <cstddef> +#include <cstdint> #include <string_view> #include <variant> @@ -2014,8 +2083,10 @@ inline int fast_digit_count(uint32_t x) noexcept { #define TL_EXPECTED_VERSION_MINOR 1 #define TL_EXPECTED_VERSION_PATCH 0 +#include <cstddef> #include <exception> #include <functional> +#include <initializer_list> #include <type_traits> #include <utility> @@ -4506,8 +4577,11 @@ void swap(expected<T, E>& lhs, #ifndef ADA_URL_PATTERN_REGEX_H #define ADA_URL_PATTERN_REGEX_H +#include <concepts> +#include <optional> #include <string> #include <string_view> +#include <vector> #ifdef ADA_USE_UNSAFE_STD_REGEX_PROVIDER #include <regex> @@ -4516,6 +4590,31 @@ void swap(expected<T, E>& lhs, #if ADA_INCLUDE_URL_PATTERN namespace ada::url_pattern_regex { +/** + * @brief Concept defining the interface for regex engine providers used by + * URLPattern. + * + * A regex provider supplies the regular expression engine used for + * pattern compilation and matching. + * + * Requirements: + * - typename T::regex_type: The compiled regex object type. + * - T::create_instance(pattern, ignore_case): Compiles the regex pattern + * string. Returns std::nullopt if the pattern is invalid or cannot be compiled. + * - T::regex_search(input, pattern): Executes a regex search against the input, + * returning a vector of capture group values (with std::nullopt for + * unmatched optional groups) or std::nullopt if the input does not match. + * - T::regex_match(input, pattern): Returns true if the input matches the + * pattern, or false otherwise. + * + * Exception contract: + * Provider methods may throw exceptions (for example, on allocation failure, + * input length limits, complexity limits, or internal engine errors). In + * environments where C++ exceptions are enabled, exceptions thrown by the + * provider will propagate out of URLPattern functions (such as fast_test, + * fast_match, test, exec, match, etc.). Providers that prefer non-throwing + * operation should handle internal errors and return false or std::nullopt. + */ template <typename T> concept regex_concept = requires(T t, std::string_view pattern, bool ignore_case, std::string_view input) { @@ -4593,10 +4692,12 @@ enum class errors : uint8_t { #endif // ADA_ERRORS_H /* end file include/ada/errors.h */ -#include <string_view> -#include <string> -#include <optional> +#include <concepts> +#include <cstdint> #include <iostream> +#include <optional> +#include <string> +#include <string_view> #if ADA_TESTING #include <iostream> @@ -4778,6 +4879,19 @@ extern template url parse_url_impl<url, true>(std::string_view user_input, template <class result_type> bool try_parse_simple_absolute(std::string_view input, result_type& out); +/** @private */ +template <class result_type> +bool finish_simple_absolute_with_port(std::string_view input, result_type& out, + ada::scheme::type scheme_type, + uint32_t protocol_end, size_t host_start, + size_t host_end, size_t host_len, + bool has_upper); + +/** @private */ +template <class result_type> +bool try_parse_simple_relative(std::string_view input, const result_type& base, + result_type& out); + #if ADA_INCLUDE_URL_PATTERN template <url_pattern_regex::regex_concept regex_provider> tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( @@ -4825,9 +4939,12 @@ tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( #ifndef ADA_IMPLEMENTATION_H #define ADA_IMPLEMENTATION_H +#include <cstdint> +#include <optional> +#include <span> #include <string> #include <string_view> -#include <optional> +#include <variant> /* begin file include/ada/url.h */ /** @@ -4844,6 +4961,8 @@ tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( #define ADA_URL_H #include <algorithm> +#include <cstddef> +#include <cstdint> #include <optional> #include <ostream> #include <string> @@ -4861,6 +4980,9 @@ tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( #ifndef ADA_URL_COMPONENTS_H #define ADA_URL_COMPONENTS_H +#include <cstdint> +#include <string> + namespace ada { /** @@ -5306,6 +5428,14 @@ struct url : url_base { template <class result_type> friend bool ada::parser::try_parse_simple_absolute(std::string_view, result_type&); + template <class result_type> + friend bool ada::parser::finish_simple_absolute_with_port( + std::string_view, result_type&, ada::scheme::type, uint32_t, size_t, + size_t, size_t, bool); + template <class result_type> + friend bool ada::parser::try_parse_simple_relative(std::string_view, + const result_type&, + result_type&); inline void update_unencoded_base_hash(std::string_view input); inline void update_base_hostname(std::string_view input); @@ -5317,6 +5447,12 @@ struct url : url_base { inline void update_base_password(std::string_view input); inline void update_base_port(std::optional<uint16_t> input); + /** + * Returns true if growing href by input_len (worst case) could exceed + * get_max_input_length(), meaning a rollback snapshot is actually needed. + */ + [[nodiscard]] bool needs_rollback_snapshot(size_t input_len) const noexcept; + /** * Sets the host or hostname according to override condition. * Return true on success. @@ -5544,6 +5680,52 @@ ada_warn_unused tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern(std::variant<std::string_view, url_pattern_init>&& input, const std::string_view* base_url = nullptr, const url_pattern_options* options = nullptr); + +template <url_pattern_regex::regex_concept regex_provider> +class url_pattern_list; + +/** + * Compiles a set of URLPattern pathname patterns into an ada::url_pattern_list + * (experimental): one structure that answers "which route matches this + * pathname, and what are its group values?" without a loop over the + * patterns and without executing regular expressions for routes written in + * the static / ":param" / "*" subset. + * + * @tparam regex_provider The regex implementation, as for parse_url_pattern; + * it is used only for routes that need URLPattern regexp semantics. + * + * @param pathname_patterns URLPattern pathname patterns (valid UTF-8), for + * example "/users/:id". The index of a pattern is the route index + * reported by url_pattern_list::match; duplicates are allowed. + * @param base_url Optional pointer to a base URL string (valid UTF-8): each + * pattern is then processed as the pathname of a URLPatternInit with + * that base URL (relative patterns resolve against its path). + * @param options Optional pointer to configuration options (ignore_case), + * applied to every route as parse_url_pattern applies them. + * + * @return A `tl::expected` containing either the compiled list on success, + * or an error code when a pattern is not a valid URLPattern pathname + * pattern (errors::type_error, as the URLPattern constructor). + * + * @see https://github.com/whatwg/urlpattern/issues/166 + */ +template <url_pattern_regex::regex_concept regex_provider> +ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors> +parse_url_pattern_list(std::span<const std::string_view> pathname_patterns, + const std::string_view* base_url = nullptr, + const url_pattern_options* options = nullptr); + +/** + * Compiles the pathname components of existing url_pattern objects into an + * ada::url_pattern_list (experimental). Only the pathname component of each + * pattern is used; routes that need the regex provider reuse the pattern's + * already compiled pathname component. All patterns must share the same + * ignore_case setting (errors::type_error otherwise); the pathname is + * compiled as for a special-scheme URL. + */ +template <url_pattern_regex::regex_concept regex_provider> +ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors> +parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns); #endif // ADA_INCLUDE_URL_PATTERN /** @@ -5588,10 +5770,13 @@ uint32_t get_max_input_length(); #endif // ADA_IMPLEMENTATION_H /* end file include/ada/implementation.h */ +#include <cstdint> +#include <optional> #include <ostream> #include <string> #include <string_view> #include <unordered_map> +#include <utility> #include <variant> #include <vector> @@ -5771,7 +5956,8 @@ class url_pattern_component { // Fast path test that returns true/false without constructing result groups. // Uses cached pattern type to skip regex evaluation for simple patterns. - bool fast_test(std::string_view input) const noexcept; + // Note: Not marked noexcept because the regex provider may throw. + bool fast_test(std::string_view input) const; // Fast path match that returns capture groups without regex for simple // patterns. Returns nullopt if pattern doesn't match, otherwise returns @@ -5808,6 +5994,10 @@ using url_pattern_input = std::variant<std::string_view, url_pattern_init>; // A struct providing the URLPattern matching results for all // components of a URL. The URLPatternResult API is defined as // part of the URLPattern specification. +// +// string_view entries in `inputs` that were filled by exec/match +// point at storage owned by this object and stay valid for its +// lifetime, including after copy and move. struct url_pattern_result { std::vector<url_pattern_input> inputs; url_pattern_component_result protocol; @@ -5818,6 +6008,32 @@ struct url_pattern_result { url_pattern_component_result pathname; url_pattern_component_result search; url_pattern_component_result hash; + + url_pattern_result() = default; + url_pattern_result(const url_pattern_result& other); + url_pattern_result(url_pattern_result&& other) noexcept; + url_pattern_result& operator=(const url_pattern_result& other); + url_pattern_result& operator=(url_pattern_result&& other) noexcept; + ~url_pattern_result() = default; + + private: + // At most two strings: the input URL and the optional base URL. + // Filled only by store_inputs. + std::vector<std::string> owned_strings_{}; + + // Point each inputs[] view that aliases `from[i]` at the same + // offset inside owned_strings_[i]. + void rebind_owned_input_views(const std::pair<const char*, size_t>* from, + size_t from_size); + // Move inputs + owned_strings_ from other and rebind. other is + // left with empty inputs / owned_strings_. Component results are + // not touched. + void take_inputs(url_pattern_result& other) noexcept; + void store_inputs(const url_pattern_input& input, + const std::string_view* base_url = nullptr); + + template <url_pattern_regex::regex_concept regex_provider> + friend class url_pattern; }; struct url_pattern_options { @@ -5997,8 +6213,14 @@ class url_pattern { #define ADA_URL_PATTERN_HELPERS_H +#include <cstddef> +#include <cstdint> +#include <optional> #include <string> +#include <string_view> #include <tuple> +#include <unordered_set> +#include <utility> #include <vector> #if ADA_INCLUDE_URL_PATTERN @@ -6089,6 +6311,10 @@ class url_pattern_parser { std::string pending_fixed_value{}; size_t index = 0; size_t next_numeric_name = 0; + // Names already taken by a part, for the "is a duplicate name" check in + // add_part. A linear scan of the part list there is O(n^2) over a pattern + // with n named parts (e.g. "/*" repeated); this set keeps it amortized O(1). + std::unordered_set<std::string> seen_names{}; }; // @see https://urlpattern.spec.whatwg.org/#tokenizer @@ -6342,8 +6568,10 @@ std::string generate_segment_wildcard_regexp( #endif /* end file include/ada/url_pattern_helpers.h */ +#include <cstdint> #include <string> #include <string_view> +#include <utility> #include <variant> namespace ada::parser { @@ -6426,9 +6654,12 @@ tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( // using ASCII digits then set processedInit["port"] to the empty string. // TODO: Optimization opportunity. if (scheme::is_special(*processed_init->protocol)) { - std::string_view port = processed_init->port.value(); - if (std::to_string(scheme::get_special_port(*processed_init->protocol)) == - port) { + // file is the only special scheme with no default port; get_special_port + // returns 0 as its sentinel, so a literal "0" port must not be mistaken for + // a default and dropped. + uint16_t default_port = scheme::get_special_port(*processed_init->protocol); + if (default_port != 0 && + std::to_string(default_port) == processed_init->port.value()) { processed_init->port->clear(); } } @@ -6532,6 +6763,9 @@ tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( auto compile_options = url_pattern_compile_component_options::DEFAULT; if (options) { compile_options.ignore_case = options->ignore_case; + // Recorded on the pattern so that url_pattern::ignore_case() reports the + // option it was created with. + url_pattern_.ignore_case_ = options->ignore_case; } // TODO: Optimization opportunity: Simplify this if statement. @@ -6615,6 +6849,10 @@ tl::expected<url_pattern<regex_provider>, errors> parse_url_pattern_impl( #define ADA_SCHEME_INL_H +#include <cstddef> +#include <cstdint> +#include <string_view> + namespace ada::scheme { /** @@ -6744,6 +6982,8 @@ constexpr ada::scheme::type get_scheme_type(std::string_view scheme) noexcept { #include <array> +#include <cstddef> +#include <cstdint> #include <string> /** @@ -6936,9 +7176,11 @@ ada_warn_unused std::string to_string(ada::state s); #define ADA_UNICODE_H +#include <cstddef> +#include <cstdint> +#include <optional> #include <string> #include <string_view> -#include <optional> /** * Unicode operations. These functions are not part of our public API and may @@ -7187,6 +7429,7 @@ constexpr bool to_lower_ascii(char* input, size_t length) noexcept; #define ADA_URL_BASE_INL_H +#include <cstdint> #include <string> #if ADA_REGULAR_VISUAL_STUDIO #include <intrin.h> @@ -7222,9 +7465,14 @@ url_base::scheme_default_port() const noexcept { #include <charconv> +#include <cstdint> #include <cstring> #include <optional> +#include <ostream> #include <string> +#include <string_view> +#include <system_error> +#include <utility> #if ADA_REGULAR_VISUAL_STUDIO #include <intrin.h> #endif // ADA_REGULAR_VISUAL_STUDIO @@ -7284,15 +7532,18 @@ inline std::ostream& operator<<(std::ostream& out, const ada::url& u) { out.host_start += uint32_t(password.size() + 1); } - out.host_end = uint32_t(out.host_start + host->size()); + // host_start is the '@' when there are credentials, exactly as + // url_aggregator reports it, so the host itself begins one byte later. + out.host_end = uint32_t(out.host_start + 1 + host->size()); } else { out.username_end = out.host_start; // Host does not start with "@" if it does not include credentials. - out.host_end = uint32_t(out.host_start + host->size()) - 1; + out.host_end = uint32_t(out.host_start + host->size()); } - running_index = out.host_end + 1; + // host_end is one past the host, so it is already the next index. + running_index = out.host_end; } else { // Update host start and end date to the same index, since it does not // exist. @@ -7572,6 +7823,8 @@ ada_really_inline size_t url::parse_port(std::string_view view, #define ADA_URL_COMPONENTS_INL_H +#include <cstdint> + namespace ada { [[nodiscard]] constexpr bool url_components::check_offset_consistency() @@ -7662,6 +7915,8 @@ namespace ada { #ifndef ADA_URL_AGGREGATOR_H #define ADA_URL_AGGREGATOR_H +#include <cstddef> +#include <cstdint> #include <ostream> #include <string> #include <string_view> @@ -7972,6 +8227,16 @@ struct url_aggregator : url_base { std::string_view, const url_aggregator*); template <class result_type> friend bool parser::try_parse_simple_absolute(std::string_view, result_type&); + template <class result_type> + friend bool parser::finish_simple_absolute_with_port(std::string_view, + result_type&, + ada::scheme::type, + uint32_t, size_t, size_t, + size_t, bool); + template <class result_type> + friend bool parser::try_parse_simple_relative(std::string_view, + const result_type&, + result_type&); #if ADA_INCLUDE_URL_PATTERN // url_pattern methods @@ -8038,6 +8303,17 @@ struct url_aggregator : url_base { */ [[nodiscard]] constexpr bool cannot_have_credentials_or_port() const; + /** + * @private + * Several setters restore a saved copy of the URL when the mutation pushes + * the buffer past get_max_input_length(). A setter grows the buffer by at + * most input_len * 3 (worst-case percent-encoding) plus a small constant for + * delimiters, so this returns false when that upper bound stays within the + * limit. It does not account for parse-failure rollbacks, which are + * unrelated to the length limit. + */ + [[nodiscard]] bool needs_rollback_snapshot(size_t input_len) const noexcept; + template <bool override_hostname = false> bool set_host_or_hostname(std::string_view input); @@ -8105,6 +8381,11 @@ inline std::ostream& operator<<(std::ostream& out, const url& u); #ifndef ADA_UNICODE_INL_H #define ADA_UNICODE_INL_H +#include <cstddef> +#include <cstdint> +#include <cstring> +#include <string_view> + /** * Unicode operations. These functions are not part of our public API and may * change at any time. @@ -8149,8 +8430,12 @@ ada_really_inline size_t percent_encode_index(const std::string_view input, /* end file include/ada/unicode-inl.h */ #include <charconv> +#include <cstdint> +#include <cstring> #include <ostream> +#include <string> #include <string_view> +#include <system_error> namespace ada { @@ -8245,7 +8530,9 @@ ada_really_inline uint32_t url_aggregator::replace_and_resize( if (current_length == 0) { buffer.insert(start, input); } else if (input_size == current_length) { - buffer.replace(start, input_size, input); + if (input_size != 0) { + std::memmove(buffer.data() + start, input.data(), input_size); + } } else if (input_size < current_length) { buffer.erase(start, current_length - input_size); buffer.replace(start, input_size, input); @@ -8324,17 +8611,17 @@ inline void url_aggregator::update_base_search(std::string_view input) { } buffer.append(input); + } else if (components.search_start != url_components::omitted) { + const uint32_t difference = replace_and_resize( + components.search_start + 1, components.hash_start, input); + components.hash_start += difference; } else { - if (components.search_start == url_components::omitted) { - components.search_start = components.hash_start; - } else { - buffer.erase(components.search_start, - components.hash_start - components.search_start); - components.hash_start = components.search_start; + components.search_start = components.hash_start; + buffer.insert(components.search_start, input.size() + 1, '?'); + if (!input.empty()) { + std::memmove(buffer.data() + components.search_start + 1, input.data(), + input.size()); } - - buffer.insert(components.search_start, "?"); - buffer.insert(components.search_start + 1, input); components.hash_start += uint32_t(input.size() + 1); // Do not forget `?` } @@ -8364,30 +8651,29 @@ inline void url_aggregator::update_base_search( buffer.append(input); } } else { - if (components.search_start == url_components::omitted) { - components.search_start = components.hash_start; - } else { - buffer.erase(components.search_start, - components.hash_start - components.search_start); - components.hash_start = components.search_start; + const size_t idx = + ada::unicode::percent_encode_index(input, query_percent_encode_set); + std::string encoded; + std::string_view replacement = input; + if (idx != input.size()) { + encoded = + ada::unicode::percent_encode(input, query_percent_encode_set, idx); + replacement = encoded; } - buffer.insert(components.search_start, "?"); - size_t idx = - ada::unicode::percent_encode_index(input, query_percent_encode_set); - if (idx == input.size()) { - buffer.insert(components.search_start + 1, input); - components.hash_start += uint32_t(input.size() + 1); // Do not forget `?` + if (components.search_start != url_components::omitted) { + const uint32_t difference = replace_and_resize( + components.search_start + 1, components.hash_start, replacement); + components.hash_start += difference; } else { - buffer.insert(components.search_start + 1, input, 0, idx); - input.remove_prefix(idx); - // We only create a temporary string if we need percent encoding and - // we attempt to create as small a temporary string as we can. - std::string encoded = - ada::unicode::percent_encode(input, query_percent_encode_set); - buffer.insert(components.search_start + idx + 1, encoded); + components.search_start = components.hash_start; + buffer.insert(components.search_start, replacement.size() + 1, '?'); + if (!replacement.empty()) { + std::memmove(buffer.data() + components.search_start + 1, + replacement.data(), replacement.size()); + } components.hash_start += - uint32_t(encoded.size() + idx + 1); // Do not forget `?` + uint32_t(replacement.size() + 1); // Do not forget `?` } } @@ -8591,16 +8877,14 @@ inline void url_aggregator::update_base_password(const std::string_view input) { uint32_t difference = uint32_t(input.size()); if (password_exists) { - uint32_t current_length = - components.host_start - components.username_end - 1; - buffer.erase(components.username_end + 1, current_length); - difference -= current_length; + difference = replace_and_resize(components.username_end + 1, + components.host_start, input); } else { - buffer.insert(components.username_end, ":"); + buffer.insert(components.username_end, input.size() + 1, ':'); + std::memmove(buffer.data() + components.username_end + 1, input.data(), + input.size()); difference++; } - - buffer.insert(components.username_end + 1, input); components.host_start += difference; // The following line is required to add "@" to hostname. When updating @@ -9288,9 +9572,11 @@ void url_aggregator::update_host_to_base_host(const std::string_view input) { #ifndef ADA_URL_SEARCH_PARAMS_H #define ADA_URL_SEARCH_PARAMS_H +#include <cstddef> #include <optional> #include <string> #include <string_view> +#include <utility> #include <vector> namespace ada { @@ -9547,7 +9833,9 @@ struct url_search_params_iter { #include <algorithm> +#include <cstddef> #include <cstdint> +#include <iterator> #include <optional> #include <ranges> #include <string> @@ -9565,8 +9853,10 @@ template <typename T, ada::url_search_params_iter_type Type> url_search_params url_search_params_iter<T, Type>::EMPTY; inline void url_search_params::reset(std::string_view input) { + // input may point into params. + const std::string copy(input); params.clear(); - initialize(input); + initialize(copy); } inline void url_search_params::initialize(std::string_view input) { @@ -9581,7 +9871,15 @@ inline void url_search_params::initialize(std::string_view input) { return; } - params.reserve(size_t(std::count(input.begin(), input.end(), '&')) + 1); + // count('&')+1 is an upper bound on the pairs the loop below keeps + // (empty segments are skipped). It is one character count, which is + // the reserve the parse path already paid for. An input of only '&' + // would reserve N+1 pairs and store nothing; skip that. + const size_t ampersands = size_t(std::count(input.begin(), input.end(), '&')); + if (ampersands == input.size()) { + return; + } + params.reserve(ampersands + 1); auto process_key_value = [&](const std::string_view current) { const auto equal = current.find('='); @@ -9847,8 +10145,13 @@ url_search_params_entries_iter::next() { #include <algorithm> +#include <cstddef> +#include <optional> +#include <string> #include <string_view> #include <utility> +#include <variant> +#include <vector> #if ADA_INCLUDE_URL_PATTERN namespace ada { @@ -9865,6 +10168,127 @@ inline bool url_pattern_component_result::operator==( return input == other.input && groups == other.groups; } +inline void url_pattern_result::rebind_owned_input_views( + const std::pair<const char*, size_t>* from, size_t from_size) { + // A view the caller pushed into `inputs` does not alias `from` and + // is left unchanged. + for (auto& value : inputs) { + auto* sv = std::get_if<std::string_view>(&value); + if (sv == nullptr) { + continue; + } + for (size_t i = 0; i < from_size && i < owned_strings_.size(); ++i) { + const char* const begin = from[i].first; + const char* const end = begin + from[i].second; + if (sv->data() >= begin && sv->data() <= end && + static_cast<size_t>(end - sv->data()) >= sv->size()) { + const size_t off = static_cast<size_t>(sv->data() - begin); + value = std::string_view(owned_strings_[i].data() + off, sv->size()); + break; + } + } + } +} + +inline void url_pattern_result::take_inputs( + url_pattern_result& other) noexcept { + // SSO buffers change address when a std::string is moved, so the + // source addresses have to be captured first. store_inputs never + // owns more than two strings, which keeps this noexcept. + std::pair<const char*, size_t> from[2]; + const size_t n = + other.owned_strings_.size() < 2 ? other.owned_strings_.size() : 2; + for (size_t i = 0; i < n; ++i) { + from[i] = {other.owned_strings_[i].data(), other.owned_strings_[i].size()}; + } + inputs = std::move(other.inputs); + owned_strings_ = std::move(other.owned_strings_); + rebind_owned_input_views(from, n); + other.inputs.clear(); + other.owned_strings_.clear(); +} + +inline void url_pattern_result::store_inputs(const url_pattern_input& input, + const std::string_view* base_url) { + owned_strings_.clear(); + inputs.clear(); + // inputs[] holds views into owned_strings_, so it must not reallocate + // (and move SSO buffers) after the first view is taken. + owned_strings_.reserve(2); + if (std::holds_alternative<std::string_view>(input)) { + owned_strings_.emplace_back(std::get<std::string_view>(input)); + inputs.emplace_back(std::string_view(owned_strings_.back())); + } else { + inputs.emplace_back(std::get<url_pattern_init>(input)); + } + if (base_url != nullptr) { + owned_strings_.emplace_back(*base_url); + inputs.emplace_back(std::string_view(owned_strings_.back())); + } +} + +inline url_pattern_result::url_pattern_result(const url_pattern_result& other) + : inputs(other.inputs), + protocol(other.protocol), + username(other.username), + password(other.password), + hostname(other.hostname), + port(other.port), + pathname(other.pathname), + search(other.search), + hash(other.hash), + owned_strings_(other.owned_strings_) { + // `other` is unchanged, so its buffers are still the ones inputs + // may point at. + std::pair<const char*, size_t> from[2]; + const size_t n = + other.owned_strings_.size() < 2 ? other.owned_strings_.size() : 2; + for (size_t i = 0; i < n; ++i) { + from[i] = {other.owned_strings_[i].data(), other.owned_strings_[i].size()}; + } + rebind_owned_input_views(from, n); +} + +inline url_pattern_result::url_pattern_result( + url_pattern_result&& other) noexcept + : inputs(), + protocol(std::move(other.protocol)), + username(std::move(other.username)), + password(std::move(other.password)), + hostname(std::move(other.hostname)), + port(std::move(other.port)), + pathname(std::move(other.pathname)), + search(std::move(other.search)), + hash(std::move(other.hash)), + owned_strings_() { + take_inputs(other); +} + +inline url_pattern_result& url_pattern_result::operator=( + const url_pattern_result& other) { + if (this != &other) { + url_pattern_result tmp(other); + *this = std::move(tmp); + } + return *this; +} + +inline url_pattern_result& url_pattern_result::operator=( + url_pattern_result&& other) noexcept { + if (this != &other) { + protocol = std::move(other.protocol); + username = std::move(other.username); + password = std::move(other.password); + hostname = std::move(other.hostname); + port = std::move(other.port); + pathname = std::move(other.pathname); + search = std::move(other.search); + hash = std::move(other.hash); + take_inputs(other); + } + return *this; +} + template <url_pattern_regex::regex_concept regex_provider> url_pattern_component_result url_pattern_component<regex_provider>::create_component_match_result( @@ -10054,7 +10478,7 @@ url_pattern_component<regex_provider>::compile( template <url_pattern_regex::regex_concept regex_provider> bool url_pattern_component<regex_provider>::fast_test( - std::string_view input) const noexcept { + std::string_view input) const { // Fast path for simple patterns - avoid regex evaluation // Using if-else for better branch prediction on common cases if (type == url_pattern_component_type::FULL_WILDCARD) { @@ -10154,8 +10578,11 @@ result<bool> url_pattern<regex_provider>::test( search_view, *apply_result->hash); } - // URL string input path - result<url_aggregator> base_url; + // URL string input path. + // Let baseURL be null. A default-constructed result holds a value (an + // empty URL), and a relative input would then resolve against it. Start + // from an error so "no base given" means no value. + result<url_aggregator> base_url = tl::unexpected(errors::type_error); if (base_url_string) { base_url = ada::parse<url_aggregator>(*base_url_string, nullptr); if (!base_url) { @@ -10204,10 +10631,6 @@ result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match( std::string search{}; std::string hash{}; - // Let inputs be an empty list. - // Append input to inputs. - std::vector inputs{input}; - // If input is a URLPatternInit then: if (std::holds_alternative<url_pattern_init>(input)) { ada_log( @@ -10271,8 +10694,10 @@ result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match( } else { ADA_ASSERT_TRUE(std::holds_alternative<std::string_view>(input)); - // Let baseURL be null. - result<url_aggregator> base_url; + // Let baseURL be null. A default-constructed result holds a value (an + // empty URL), and a relative input would then resolve against it. Start + // from an error so "no base given" means no value. + result<url_aggregator> base_url = tl::unexpected(errors::type_error); // If baseURLString was given, then: if (base_url_string) { @@ -10285,9 +10710,6 @@ result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match( *base_url_string); return std::nullopt; } - - // Append baseURLString to inputs. - inputs.emplace_back(*base_url_string); } url_aggregator* base_url_value = @@ -10399,8 +10821,9 @@ result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match( // Let result be a new URLPatternResult. auto result = url_pattern_result{}; - // Set result["inputs"] to inputs. - result.inputs = std::move(inputs); + // Set result["inputs"] to inputs. Copy URL / base URL text into the + // result so inputs[] string_views outlive the caller's arguments. + result.store_inputs(input, base_url_string); // Set result["protocol"] to the result of creating a component match result // given urlPattern's protocol component, protocol, and protocolExecResult. result.protocol = protocol_component.create_component_match_result( @@ -10456,8 +10879,13 @@ result<std::optional<url_pattern_result>> url_pattern<regex_provider>::match( #ifndef ADA_URL_PATTERN_HELPERS_INL_H #define ADA_URL_PATTERN_HELPERS_INL_H +#include <cstddef> +#include <cstdint> #include <optional> +#include <string> #include <string_view> +#include <utility> +#include <vector> #if ADA_INCLUDE_URL_PATTERN @@ -11131,9 +11559,10 @@ std::optional<errors> url_pattern_parser<F>::add_part( next_numeric_name++; } // If the result of running is a duplicate name given parser and name is - // true, then throw a TypeError. - if (std::ranges::any_of( - parts, [&name](const auto& part) { return part.name == name; })) { + // true, then throw a TypeError. Tracked in a set so this stays O(1): a + // linear scan of the part list here is O(n^2) over a pattern string with n + // named parts (e.g. "/*" repeated), an algorithmic-complexity DoS. + if (!name.empty() && !seen_names.insert(name).second) { return errors::type_error; } // Let encoded prefix be the result of running parser's encoding callback @@ -11596,41 +12025,1191 @@ constructor_string_parser<regex_provider>::parse(std::string_view input) { #endif // ADA_INCLUDE_URL_PATTERN #endif /* end file include/ada/url_pattern_helpers-inl.h */ - -// Public API -/* begin file include/ada/ada_version.h */ -/** - * @file ada_version.h - * @brief Definitions for Ada's version number. +/* begin file include/ada/url_pattern_list.h */ +/** + * @file url_pattern_list.h + * @brief Compiled set-level matching over URLPattern pathname patterns. + * + * `ada::url_pattern_list` answers the question "which of my N routes matches + * this pathname, and what are the parameter values?" in a single walk + * instead of a loop of N `url_pattern::exec` calls. The whole route set is + * compiled once, by ada::parse_url_pattern_list, into a segment trie with + * per-node dispatch (direct compares for small fanouts, a first-byte index + * at the root, perfect-hash projection for wide nodes). Matching a pathname + * against the compiled set is allocation-free and does not execute any + * regular expression for routes written in the common static / ":param" / + * "*" subset; other routes are matched through the regex provider, exactly + * as ada::url_pattern does. + * + * This implements the route-set ("URLPatternList") use case discussed in + * https://github.com/whatwg/urlpattern/issues/166 for the pathname component. + * + * Correctness does not depend on the fast path: inputs or routes that exceed + * the fast-path limits (documented on the constants in + * `ada::url_pattern_list_limits`) are matched by a sequential fallback with + * identical priority semantics, never rejected and never answered wrongly. + * + * @see https://urlpattern.spec.whatwg.org/ */ -#ifndef ADA_ADA_VERSION_H -#define ADA_ADA_VERSION_H +#ifndef ADA_URL_PATTERN_LIST_H +#define ADA_URL_PATTERN_LIST_H -#define ADA_VERSION "4.0.0" -namespace ada { +#include <array> +#include <cstddef> +#include <cstdint> +#include <optional> +#include <span> +#include <string> +#include <string_view> +#include <vector> -enum { - ADA_VERSION_MAJOR = 4, - ADA_VERSION_MINOR = 0, - ADA_VERSION_REVISION = 0, -}; +#if ADA_INCLUDE_URL_PATTERN +namespace ada { -} // namespace ada +/** + * The limits of the url_pattern_list fast path. None of them changes what a + * list matches: routes and inputs beyond a limit are matched by a sequential + * fallback with identical semantics. + * @namespace ada::url_pattern_list_limits + */ +namespace url_pattern_list_limits { -#endif // ADA_ADA_VERSION_H -/* end file include/ada/ada_version.h */ -/* begin file include/ada/implementation-inl.h */ /** - * @file implementation-inl.h + * Maximum number of captures (":param" groups plus one trailing "*" group) + * a route may declare and still be compiled into the fast path. Routes with + * more groups are matched by the sequential fallback; their match is still + * correct, but only the first `max_captures_per_route` captures are reported + * (see url_pattern_list_match_result::captures_truncated). */ -#ifndef ADA_IMPLEMENTATION_INL_H -#define ADA_IMPLEMENTATION_INL_H +inline constexpr uint32_t max_captures_per_route = 8; +/** + * Maximum number of '/'-separated segments an input pathname may have and + * still be matched by the fast path. Longer inputs fall back to the + * sequential matcher and are still matched correctly. + */ +inline constexpr uint32_t max_fast_path_segments = 24; +/** + * Maximum input pathname length (bytes) accepted by the fast path; segment + * offsets are tracked in 16-bit integers internally. Longer inputs fall back + * to the sequential matcher and are still matched correctly. + */ +inline constexpr uint32_t max_fast_path_pathname_length = 4096; -#include <variant> +/** + * Maximum number of pattern segments a route may have and still be compiled + * into the trie fast path. Deeper routes are matched by the sequential + * fallback with identical semantics. + */ +inline constexpr uint32_t max_trie_pattern_segments = 16; + +/** + * Maximum number of routes in a url_pattern_list (a node's static child + * count is a uint16_t). + */ +inline constexpr size_t max_routes = 65535; + +/** + * Maximum number of challenger table entries. The table grows with the + * product of overlapping auxiliary and trie routes. + */ +inline constexpr size_t max_aux_entries = 1u << 20; + +} // namespace url_pattern_list_limits + +/** + * The result of url_pattern_list::match. A winning route reports its group + * values in one of two forms, mirroring url_pattern_list::group_names(): + * + * - Routes in the static / ":param" / "*" subset report zero-allocation + * captures: (offset, length) slices of the pathname passed to match, in + * capture order (":param" groups left to right, then the "*" group). + * `regexp_route` is false and `regexp_groups` is empty. + * - Routes matched through the regex provider (patterns with custom regexp + * groups or "?" / "+" / "*" modifiers) report the group values the + * provider's regex_search returned, exactly as url_pattern::exec would for + * the pathname component: `regexp_route` is true, `regexp_groups[i]` is the + * value of group_names(route_index)[i] (nullopt for a group that did not + * participate), and capture_count is 0. + * + * Routes with more than url_pattern_list_limits::max_captures_per_route + * groups report only the first max_captures_per_route slices and set + * captures_truncated. + */ +struct url_pattern_list_match_result { + /** One capture: an (offset, length) slice of the matched pathname. */ + struct capture { + uint32_t offset = 0; + uint32_t length = 0; + }; + /** Index of the winning route in the creation order, or -1 for no match. */ + int32_t route_index = -1; + /** Number of valid entries in captures. */ + uint32_t capture_count = 0; + /** True when the route has more groups than could be reported as slices. */ + bool captures_truncated = false; + /** True when the winning route was matched through the regex provider; its + * group values are in regexp_groups. */ + bool regexp_route = false; + std::array<capture, url_pattern_list_limits::max_captures_per_route> + captures{}; + /** Group values of a regexp route, as returned by the provider. */ + std::vector<std::optional<std::string>> regexp_groups{}; + + [[nodiscard]] bool has_match() const noexcept { return route_index >= 0; } +}; + +/** + * @private + * The compiled tables url_pattern_list::match walks, and the inline matcher + * over them (url_pattern_list-inl.h). Nothing here is part of the supported + * API. The route-set compiler that produces these tables is not part of the + * public headers at all (src/url_pattern_list_compiler.h). + * @namespace ada::url_pattern_list_detail + */ +namespace url_pattern_list_detail { + +/** @private One trie node. Nodes with a projection dispatch keep their hash + * payload in a separate hash_record, so the common 0/1/direct nodes stay at + * 24 bytes. */ +struct node_record { + // First static edge (edges are laid out per node, contiguously). + int32_t first_child = 0; + // Child node index, -2 - route (pure-leaf shortcut), or -1. + int32_t param_child = -1; + // Route index of a "*" ending at this prefix, or -1. + int32_t wild_route = -1; + // Route ending exactly here, or -1. + int32_t terminal_route = -1; + uint16_t n_static = 0; + // 0 none, 1 direct compares, 2 projection, 3 linear scan, 4 first-byte + // index (root only). + uint8_t dispatch = 0; + // 1 if the node still has a param/wildcard alternative to backtrack to. + uint8_t has_alternative = 0; + // Index of the node's hash_record (dispatch == 2 only). + uint32_t hash_index = 0; +}; + +/** @private Projection-dispatch payload of a hashed node. */ +struct hash_record { + uint64_t multiplier = 0; + uint32_t slot_base = 0; + // Witness plan: 3 nibble ids | count << 12 | use_len << 14. + uint16_t witness_plan = 0; + // Slot table size == 1 << slot_bits. + uint8_t slot_bits = 0; + uint8_t reserved = 0; +}; + +/** @private One static edge; keys <= 16 bytes verify from the packed + * windows alone. */ +struct edge_record { + // Key bytes [0, min(8, len)), little-endian, zero-padded. + uint64_t prefix = 0; + // Key bytes [max(0, len - 8), len), little-endian, zero-padded. + uint64_t suffix = 0; + // Child node index; negative values encode -2 - route pure-leaf shortcuts. + int32_t node = -1; + // Full key in the blob (read only when key_length > 16). + uint32_t key_offset = 0; + uint16_t key_length = 0; +}; + +/** @private How one route of the set is matched. */ +enum class route_mode : uint8_t { + // Compiled into the trie fast path. + trie = 0, + // Safe static/":param"/"*" syntax beyond a fast-path build limit: matched + // by the sequential segment matcher. + sequential = 1, + // Needs URLPattern regexp semantics: matched through the regex provider. + regexp = 2, +}; + +/** @private Everything the matcher knows about one route after a hit. */ +struct route_record { + // Packed per-segment kinds, two bits per segment, most significant first; + // (kind_sequence, kind_length, route index) compared as a tuple is the + // specificity order. + uint64_t kind_sequence = 0; + // Sequential-mode routes: their segments in the segment table. + uint32_t segment_first = 0; + uint32_t segment_count = 0; + // Auxiliary routes that can outrank this route when it wins the fast + // path: a range of the aux table (usually empty). + uint32_t challenger_first = 0; + uint32_t challenger_count = 0; + // Ordinal among the regexp-mode routes, or -1. + int32_t regexp_component = -1; + uint8_t kind_length = 0; + route_mode mode = route_mode::sequential; + // Trie-mode routes: capture positions. + uint8_t n_params = 0; + uint8_t wild = 0; + std::array<uint8_t, url_pattern_list_limits::max_captures_per_route> + param_positions{}; +}; + +/** @private One pattern segment of a sequential-mode route. */ +struct segment_record { + uint32_t text_offset = 0; + uint32_t text_length = 0; + // 0 literal, 1 ":param", 2 "*". + uint8_t kind = 0; +}; + +/** + * @private + * The compiled route set: one arena holding every table, addressed by + * section offsets, plus the per-route group names. Sections are 8-byte + * aligned; the blob is zero-padded by 8 bytes so short key windows can be + * loaded whole. + */ +struct compiled_routes { + std::vector<uint8_t> arena{}; + std::vector<std::vector<std::string>> group_names{}; + uint32_t nodes_offset = 0; + uint32_t hashes_offset = 0; + uint32_t edges_offset = 0; + uint32_t slots_offset = 0; + uint32_t blob_offset = 0; + uint32_t routes_offset = 0; + uint32_t segments_offset = 0; + uint32_t aux_offset = 0; + uint32_t root_index_offset = 0; + uint32_t n_routes = 0; + // All auxiliary routes (regexp mode and sequential mode) in insertion + // order: the aux table's first n_aux_all entries; challenger ranges + // follow. + uint32_t n_aux_all = 0; + uint8_t ignore_case = 0; + + template <typename T> + [[nodiscard]] const T* section(uint32_t offset) const noexcept { + return reinterpret_cast<const T*>(arena.data() + offset); + } +}; + +/** @private Result of the fast-path engine or of the sequential matcher. */ +struct engine_result { + using capture = url_pattern_list_match_result::capture; + int32_t route = -1; + uint32_t capture_count = 0; + // False when the input exceeded a fast-path limit and the caller must run + // the sequential fallback over the whole route set. + bool within_fast_path = true; + bool captures_truncated = false; + std::array<capture, url_pattern_list_limits::max_captures_per_route> + captures{}; +}; + +/** + * @private + * Parses and compiles a set of pathname patterns (already base-URL + * processed). Routes that need the regex provider come back with + * route_record::regexp_component set to their ordinal in insertion order; + * the caller compiles those components and fills their group names. + */ +tl::expected<compiled_routes, errors> compile_pathname_patterns( + std::span<const std::string> patterns, bool ignore_case); + +/** + * @private + * Sequential reference matcher for one non-regexp route of the compiled set; + * matches any input (no fast-path limits) with the same semantics as the + * compiled engine. With `fold_input`, input bytes are ASCII case-folded on + * the fly (the compiled literals are already folded). On a match, fills + * `result` (route index is NOT set) and returns true. + */ +bool match_route_sequential(const compiled_routes& tables, uint32_t route, + std::string_view pathname, bool fold_input, + engine_result& result) noexcept; + +/** + * @private + * True when the bytes [p, p + n) hold no line terminator. A "*" segment + * compiles to "(.*)" in the URLPattern regexp, and "." in an ECMAScript + * regular expression does not match LF or CR, so a wildcard may not capture + * past one. Deliberately not inlined into the walk (it costs the static and + * ":param" paths, which never run it), and deliberately defined in + * url_pattern_list.cpp rather than here: MSVC's ada_never_inline carries no + * inline linkage, so a definition in this header is emitted in every + * translation unit. + */ +bool wildcard_tail_ok(const char* p, uint32_t n) noexcept; + +/** + * @private + * Cheap pre-check for a regexp-mode route before running the provider: the + * part of the route's segment shape that is certain (see the compiler's + * approximate_kind_sequence) must fit the pathname -- its anchored literal + * segments, and its exact segment count when every group is a ":name" + * segment wildcard. False proves the regular expression cannot match. + */ +bool match_regexp_shape(const compiled_routes& tables, uint32_t route, + std::string_view pathname, bool fold_input) noexcept; + +/** + * @private + * True when route `a` (at insertion index `a_index`) outranks route `b` (at + * `b_index`): lexicographically smaller kind sequence, insertion order as the + * tiebreak. + */ +constexpr bool outranks(uint64_t a_sequence, uint32_t a_length, size_t a_index, + uint64_t b_sequence, uint32_t b_length, + size_t b_index) noexcept { + if (a_sequence != b_sequence) { + return a_sequence < b_sequence; + } + if (a_length != b_length) { + return a_length < b_length; + } + return a_index < b_index; +} + +} // namespace url_pattern_list_detail + +template <url_pattern_regex::regex_concept regex_provider> +class url_pattern_list; + +/** + * @private + * url_pattern_list befriends these two specializations, so they have to be + * declared before it: a friend declaration that redeclares the function + * template instead is not matched by every compiler we support (Apple clang + * 15 rejects the resulting member access). The documented declarations are + * in implementation.h, next to parse_url_pattern, and carry the default + * arguments: this header includes url_pattern.h, which includes + * implementation.h, so those declarations are always seen first, and a + * function template may not gain default arguments in a later declaration. + */ +template <url_pattern_regex::regex_concept regex_provider> +ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors> +parse_url_pattern_list(std::span<const std::string_view> pathname_patterns, + const std::string_view* base_url, + const url_pattern_options* options); + +/** @private See above. */ +template <url_pattern_regex::regex_concept regex_provider> +ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors> +parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns); + +/** + * @brief A compiled set of URLPattern pathname patterns with one-shot + * matching. + * + * Build once with ada::parse_url_pattern_list, then call match() per + * request. Matching within the fast-path limits is allocation-free and + * regex-free for routes written in the static / ":param" / "*" subset; other + * routes are matched through the regex provider (the same regex_search call + * url_pattern::exec makes) and still participate in the priority order. + * + * Match priority is specificity order, not registration order: routes are + * compared by their per-segment kind sequence (literal < ":param" < "*", + * lexicographically from the first segment), with insertion order breaking + * ties. This is the priority scheme of find-my-way (Fastify) and Express- + * style routers. Whether a standardized URLPatternList should instead use + * pure first-match-in-insertion-order semantics is an open question; the + * compiled representation supports either, and the priority rule is + * deliberately centralized in url_pattern_list_detail::outranks. + * + * Scope (v1): the pathname component only. Other URL components are treated + * as fully wildcarded; match() takes an already-extracted pathname (for + * example ada::url_aggregator::get_pathname()). Inputs are matched as given + * and are expected to be in canonical (percent-encoded) form; the pattern + * side is canonicalized by the URLPattern pattern parser at creation. The + * subset follows the URLPattern regexp it stands for: a ":param" segment + * ("[^/]+?") is one non-empty segment, and a "*" tail ("(.*)") matches any + * bytes except the line terminators LF and CR, which "." never matches. + * + * With url_pattern_options::ignore_case, regexp routes are compiled through + * the provider with the flag set (as url_pattern does), and the static / + * ":param" / "*" subset compares literal segments with ASCII case folding, + * which is what a case-insensitive regular expression does over the ASCII + * text of a canonical pathname. + * + * @tparam regex_provider The regex implementation used only for routes that + * need URLPattern regexp semantics. Must satisfy + * url_pattern_regex::regex_concept. + */ +template <url_pattern_regex::regex_concept regex_provider> +class url_pattern_list { + public: + url_pattern_list() = default; + + /** + * Matches a pathname against the set and returns the winning route with + * its captures (see url_pattern_list_match_result). The fast path is + * allocation-free; inputs beyond the fast-path limits are matched by the + * sequential fallback with identical semantics. + */ + [[nodiscard]] url_pattern_list_match_result match( + std::string_view pathname) const; + + /** Number of routes in the set. */ + [[nodiscard]] size_t size() const noexcept { return patterns_.size(); } + + /** The pathname pattern string the route at `route_index` was created + * from (after base URL processing, if a base URL was given). */ + [[nodiscard]] std::string_view pattern(size_t route_index) const + ada_lifetime_bound { + return patterns_[route_index]; + } + + /** + * Capture group names of the route at `route_index`, in the order of + * url_pattern_list_match_result::captures / regexp_groups ("*" groups have + * numeric names, per URLPattern). + */ + [[nodiscard]] const std::vector<std::string>& group_names( + size_t route_index) const ada_lifetime_bound { + return compiled_.group_names[route_index]; + } + + /** The ignore_case option the set was created with. */ + [[nodiscard]] bool ignore_case() const noexcept { + return compiled_.ignore_case != 0; + } + + friend tl::expected<url_pattern_list, errors> + parse_url_pattern_list<regex_provider>( + std::span<const std::string_view> pathname_patterns, + const std::string_view* base_url, const url_pattern_options* options); + + friend tl::expected<url_pattern_list, errors> parse_url_pattern_list< + regex_provider>(std::span<const url_pattern<regex_provider>> patterns); + + private: + /** @private Compiles the (already processed) pattern strings; the regexp + * components are then supplied by the caller in insertion order. */ + static tl::expected<url_pattern_list, errors> create( + std::vector<std::string>&& pathname_patterns, bool ignore_case); + + /** @private Tests one auxiliary route (sequential or regexp mode) and, + * when it matches and outranks `best`, replaces `best` with it. `probe` + * is the (possibly case-folded) pathname for the sequential matcher, + * `pathname` the original for the provider. */ + void consider_route( + uint32_t route_index, std::string_view pathname, std::string_view probe, + bool fold_input, url_pattern_list_detail::engine_result& best, + std::vector<std::optional<std::string>>& best_groups) const; + + /** @private The pattern strings, by route index. */ + std::vector<std::string> patterns_{}; + /** @private The compiled tables. */ + url_pattern_list_detail::compiled_routes compiled_{}; + /** @private Compiled pathname components of the regexp-mode routes, in + * insertion order. */ + std::vector<url_pattern_component<regex_provider>> regexp_components_{}; +}; + +} // namespace ada +#endif // ADA_INCLUDE_URL_PATTERN +#endif // ADA_URL_PATTERN_LIST_H +/* end file include/ada/url_pattern_list.h */ +/* begin file include/ada/url_pattern_list-inl.h */ +/** + * @file url_pattern_list-inl.h + * @brief The url_pattern_list matcher (inline) and the class template's + * member definitions. + * + * The walk over the compiled tables lives here, as ada_really_inline + * functions, so that it inlines into url_pattern_list::match; the route-set + * compiler that builds the tables is in its own translation unit + * (src/url_pattern_list.cpp) and is not part of the public headers. + */ +#ifndef ADA_URL_PATTERN_LIST_INL_H +#define ADA_URL_PATTERN_LIST_INL_H + + +#include <bit> +#include <cstdint> +#include <cstring> +#include <optional> +#include <string> #include <string_view> +#include <utility> +#include <vector> + +#if ADA_NEON +#include <arm_neon.h> +#endif + +#if ADA_INCLUDE_URL_PATTERN +namespace ada::url_pattern_list_detail { + +// ---- byte helpers ---------------------------------------------------------- + +// Unaligned 8-byte little-endian load; all 8 bytes must be readable. The +// byte-assembly fallback keeps big-endian targets correct (the compiler +// lowers it to a single load plus byte swap). +ada_really_inline uint64_t load8_le(const char* p) noexcept { + if constexpr (std::endian::native == std::endian::little) { + uint64_t x; + std::memcpy(&x, p, 8); + return x; + } else { + uint64_t x = 0; + for (uint32_t j = 0; j < 8; j++) { + x |= static_cast<uint64_t>(static_cast<uint8_t>(p[j])) << (8 * j); + } + return x; + } +} + +// Bytes [0, n) of p packed little-endian, zero-padded; reads exactly n +// bytes (n < 8). This is the byte-compare path for short tails. +ada_really_inline uint64_t gather_le(const char* p, uint32_t n) noexcept { + uint64_t x = 0; + for (uint32_t j = 0; j < n; j++) { + x |= static_cast<uint64_t>(static_cast<uint8_t>(p[j])) << (8 * j); + } + return x; +} + +// Mask selecting the low n bytes, 1 <= n <= 7. +constexpr uint64_t low_bytes_mask(uint32_t n) noexcept { + return ~0ull >> (64 - 8 * n); +} + +// ASCII case folding of n bytes from src into dst (the compiler vectorizes +// this loop). Only ASCII letters change: canonical pathnames are ASCII, and +// this is what a case-insensitive regular expression does over them. +inline void ascii_fold(const char* src, uint32_t n, char* dst) noexcept { + for (uint32_t i = 0; i < n; i++) { + const uint8_t c = static_cast<uint8_t>(src[i]); + dst[i] = static_cast<char>(c | ((c >= 'A' && c <= 'Z') ? 0x20u : 0u)); + } +} + +// ---- witness machinery ----------------------------------------------------- +// Projection dispatch for wide trie nodes. A witness id names a feature of a +// byte string: +// 0..7 the byte at absolute offset id (0 when out of range) +// 8..15 the byte at offset id-8 counted from the end +// A projection is three witness bytes plus the length packed into one +// uint64; a perfect multiplier turns it into a slot index. Builder and +// matcher call the same accessors and the same packing, so a slot table +// cannot disagree with the gather that reads it. + +constexpr uint8_t length_byte(uint32_t len) noexcept { + return len < 255u ? static_cast<uint8_t>(len) : static_cast<uint8_t>(255); +} + +constexpr uint8_t witness_byte(const char* p, uint32_t len, + uint8_t id) noexcept { // ids 0..15 + uint32_t o = id & 7u; + bool in = o < len; + uint32_t pos = (id & 8u) ? len - 1u - o : o; // wraps when !in; masked then + pos = in ? pos : 0u; + uint8_t v = len ? static_cast<uint8_t>(p[pos]) : static_cast<uint8_t>(0); + return in ? v : static_cast<uint8_t>(0); +} + +constexpr uint64_t pack_projection(uint8_t f0, uint8_t f1, uint8_t f2, + uint8_t f3) noexcept { + return (static_cast<uint64_t>(f0) << 24) | (static_cast<uint64_t>(f1) << 16) | + (static_cast<uint64_t>(f2) << 8) | static_cast<uint64_t>(f3); +} + +// Perfect-multiplier slot index; b <= 12 everywhere, so the shift is in +// range and the product needs no modulus. +constexpr uint64_t slot_of(uint64_t proj, uint64_t multiplier, + uint8_t b) noexcept { + return (proj * multiplier) >> (64 - b); +} + +// Fixed-shape projection of one string: always 3 witness bytes plus the +// length. Duplicated ids add no information but keep the gather uniform. +constexpr uint64_t project(const char* p, uint32_t len, + uint16_t plan) noexcept { + return pack_projection( + witness_byte(p, len, static_cast<uint8_t>(plan & 15u)), + witness_byte(p, len, static_cast<uint8_t>((plan >> 4) & 15u)), + witness_byte(p, len, static_cast<uint8_t>((plan >> 8) & 15u)), + length_byte(len)); +} + +// ---- segment scan ---------------------------------------------------------- + +// Splits the pathname into segments in one pass, in place: only segment +// starts are recorded, with a sentinel soff[nseg] = ulen + 1 so that +// seg_len(i) == soff[i + 1] - soff[i] - 1. Returns the segment count, or 0 +// when the input has more than max_fast_path_segments segments (the caller +// falls back to the sequential matcher). Requires ulen >= 1 and +// url[0] == '/'. +// +// Two implementations with the same contract: the portable SWAR scan (8 +// bytes per step, an exact zero-byte test on x ^ '/'-fill with no false +// positives, bytes >= 0x80 included, and a byte-exact partial load for the +// tail, so the input is never over-read), and on AArch64 a NEON scan for +// inputs of 16 bytes or more (16 bytes per step, the '/' compare narrowed +// to one nibble per byte, the last block overlapping the previous one so +// the input is never over-read). The 1k+ pathname benchmark in the PR +// discussion is what keeps the NEON scan: it is faster at every length and +// 3-4x faster past 1 KB. +struct segment_emitter { + uint16_t* soff; + uint32_t nseg = 0; + uint32_t start = 1; + // One segment start per set bit of `lanes`; a lane is 1 << shift bits + // wide (8 for the SWAR masks, 4 for the NEON nibble masks). + ada_really_inline bool emit(uint64_t lanes, uint32_t base, + unsigned shift) noexcept { + using url_pattern_list_limits::max_fast_path_segments; + while (lanes) { + const uint32_t pos = + base + (static_cast<uint32_t>(std::countr_zero(lanes)) >> shift); + if (nseg >= max_fast_path_segments) { + return false; + } + soff[nseg++] = static_cast<uint16_t>(start); + start = pos + 1; + lanes &= lanes - 1; + } + return true; + } + ada_really_inline uint32_t finish(uint32_t ulen) noexcept { + using url_pattern_list_limits::max_fast_path_segments; + if (nseg >= max_fast_path_segments) { + return 0; + } + soff[nseg++] = static_cast<uint16_t>(start); + soff[nseg] = static_cast<uint16_t>(ulen + 1); // sentinel + return nseg; + } +}; + +ada_really_inline uint32_t scan_segments_swar(const char* url, uint32_t ulen, + uint16_t* soff) noexcept { + constexpr uint64_t slashes = 0x2F2F2F2F2F2F2F2Full; + constexpr uint64_t low7 = 0x7F7F7F7F7F7F7F7Full; + // Bit 7 of every byte of x that is zero, exactly: (b & 0x7F) + 0x7F has + // bit 7 set iff the low bits are non-zero, b itself has it set iff b is + // >= 0x80, and no lane can carry into its neighbour. + const auto zero_lanes = [](uint64_t x) noexcept { + return ~(((x & low7) + low7) | x | low7); + }; + segment_emitter out{soff}; + uint32_t i = 1; + for (; i + 8 <= ulen; i += 8) { + const uint64_t lanes = zero_lanes(load8_le(url + i) ^ slashes); + if (lanes != 0 && !out.emit(lanes, i, 3)) { + return 0; + } + } + if (i < ulen) { // tail of 1..7 bytes: zero padding is never a '/' + const uint64_t lanes = zero_lanes(gather_le(url + i, ulen - i) ^ slashes); + if (lanes != 0 && !out.emit(lanes, i, 3)) { + return 0; + } + } + return out.finish(ulen); +} + +#if ADA_NEON +ada_really_inline uint32_t scan_segments_neon(const char* url, uint32_t ulen, + uint16_t* soff) noexcept { + // Requires ulen >= 16. + const uint8x16_t slash = vdupq_n_u8('/'); + // One bit per byte lane that holds a '/': compare, narrow each 16-bit + // pair to its high nibble, keep bit 0 of every nibble. + const auto slash_lanes = [&](const char* p) noexcept { + const uint8x16_t v = vld1q_u8(reinterpret_cast<const uint8_t*>(p)); + const uint64_t nibbles = + vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16( + vreinterpretq_u16_u8(vceqq_u8(v, slash)), 4)), + 0); + return nibbles & 0x1111111111111111ull; + }; + segment_emitter out{soff}; + uint32_t i = 0; + for (; i + 16 <= ulen; i += 16) { + uint64_t lanes = slash_lanes(url + i); + if (i == 0) { + lanes &= ~0xFull; // the leading '/' is not a separator + } + if (lanes != 0 && !out.emit(lanes, i, 2)) { + return 0; + } + } + if (i < ulen) { // overlapped last block: drop the lanes already scanned + const uint32_t off = ulen - 16; + const uint64_t lanes = slash_lanes(url + off) & (~0ull << ((i - off) * 4)); + if (lanes != 0 && !out.emit(lanes, off, 2)) { + return 0; + } + } + return out.finish(ulen); +} +#endif // ADA_NEON + +ada_really_inline uint32_t scan_segments(const char* url, uint32_t ulen, + uint16_t* soff) noexcept { +#if ADA_NEON + if (ulen >= 16) { + return scan_segments_neon(url, ulen, soff); + } +#endif + return scan_segments_swar(url, ulen, soff); +} + +// ---- verify / dispatch ----------------------------------------------------- + +// One input segment prepared for dispatch: its bytes, its length, and how +// many bytes are readable from p (to the end of the pathname). +struct segment_ref { + const char* p; + uint32_t len; + uint32_t avail; +}; + +// Segment-vs-edge compare. Keys of 8..16 bytes verify from two whole-word +// loads inside the segment; shorter keys from one masked load when the +// input has 8 readable bytes, else from a byte gather (short tails such as +// "42" or "me"); longer keys through memcmp against the blob. An empty key +// (a pattern such as "/users/") matches exactly the empty segment. +ada_really_inline bool verify_edge(const edge_record& e, const segment_ref& s, + const char* blob) noexcept { + const uint32_t len = s.len; + if (len != e.key_length) { + return false; + } + if (len == 0) { + return true; + } + if (len > 16) { + return std::memcmp(s.p, blob + e.key_offset, len) == 0; + } + if (len >= 8) { + return ((load8_le(s.p) ^ e.prefix) | + (load8_le(s.p + len - 8) ^ e.suffix)) == 0; + } + const uint64_t x = s.avail >= 8 ? (load8_le(s.p) & low_bytes_mask(len)) + : gather_le(s.p, len); + return x == e.prefix; +} + +// The typed view of the arena the walk reads; derived once per match. +struct table_view { + const node_record* nodes; + const hash_record* hashes; + const edge_record* edges; + const uint8_t* slots; + const char* blob; + const uint16_t* root_index; +}; + +ada_really_inline table_view view_of(const compiled_routes& r) noexcept { + return table_view{r.section<node_record>(r.nodes_offset), + r.section<hash_record>(r.hashes_offset), + r.section<edge_record>(r.edges_offset), + r.section<uint8_t>(r.slots_offset), + r.section<char>(r.blob_offset), + r.section<uint16_t>(r.root_index_offset)}; +} + +// Static-child dispatch: returns the child ordinal within the node or -1. +// Correctness never depends on the projection or the index: the candidate +// is always confirmed by a full segment compare, so a bad table can only +// cost time, never change an answer. +ada_really_inline int32_t dispatch_static(const table_view& t, + const node_record& nd, + const segment_ref& s) noexcept { + const edge_record* e = t.edges + nd.first_child; + switch (nd.dispatch) { + case 0: + return -1; + case 1: { // direct: up to 8 compares, each gated by the key length + for (uint32_t j = 0; j < nd.n_static; j++) { + if (verify_edge(e[j], s, t.blob)) { + return static_cast<int32_t>(j); + } + } + return -1; + } + case 2: { // projection: gather -> multiply -> slot -> verify + const hash_record& h = t.hashes[nd.hash_index]; + const uint64_t proj = project(s.p, s.len, h.witness_plan); + const uint8_t ord = + t.slots[h.slot_base + slot_of(proj, h.multiplier, h.slot_bits)]; + if (ord == 0xFF) { + return -1; + } + return verify_edge(e[ord], s, t.blob) ? static_cast<int32_t>(ord) : -1; + } + case 4: { // root first-byte index: jump to the run of children that + // share the segment's first byte (children are sorted by it) + if (s.len == 0) { + return -1; // no first byte; an indexed root has no empty key + } + const uint8_t b = static_cast<uint8_t>(s.p[0]); + uint32_t j = t.root_index[b]; + if (j == 0xFFFF) { + return -1; + } + for (; j < nd.n_static && static_cast<uint8_t>(e[j].prefix & 0xFFu) == b; + j++) { + if (verify_edge(e[j], s, t.blob)) { + return static_cast<int32_t>(j); + } + } + return -1; + } + default: { // linear demotion rung (also carries fanout > 254) + for (uint32_t j = 0; j < nd.n_static; j++) { + if (verify_edge(e[j], s, t.blob)) { + return static_cast<int32_t>(j); + } + } + return -1; + } + } +} + +// ---- the match residual ---------------------------------------------------- + +// Matches `pathname` against the compiled tables. When the input is out of +// the fast-path contract, returns with within_fast_path == false and no +// answer; the caller falls back to the sequential matcher. +ada_really_inline void match_compiled(const compiled_routes& r, const char* url, + uint32_t ulen, + engine_result& out) noexcept { + using url_pattern_list_limits::max_fast_path_pathname_length; + using url_pattern_list_limits::max_fast_path_segments; + out = engine_result{}; + if (ulen == 0 || url[0] != '/' || ulen > max_fast_path_pathname_length) { + out.within_fast_path = false; // the sequential fallback decides + return; + } + const table_view t = view_of(r); + const route_record* routes = r.section<route_record>(r.routes_offset); + + // Segment scan; overflow means the input is beyond the fast path. + uint16_t soff[max_fast_path_segments + 1]; + const uint32_t nseg = scan_segments(url, ulen, soff); + if (nseg == 0) { + out.within_fast_path = false; + return; + } + const auto seg_len = [&](uint32_t i) { + return static_cast<uint32_t>(soff[i + 1]) - soff[i] - 1u; + }; + const auto seg_ref = [&](uint32_t i) { + const uint32_t off = soff[i]; + return segment_ref{url + off, seg_len(i), ulen - off}; + }; + + // Trie walk with an explicit bounded backtrack stack. Every node offers + // the same three alternatives in the compiled priority order (static + // child, param child, wildcard); a backtrack record stores the resume + // point, and a record is pushed only when the node still has an untried + // alternative, so the stack never exceeds the walk depth. Edges encoded + // as -2 - route are pure-leaf shortcuts. + enum alternative : uint16_t { + alt_static = 0, + alt_param = 1, + alt_wild = 2, + alt_none = 3 + }; + struct backtrack { + int32_t node; + uint16_t i; + uint16_t resume; + }; + backtrack stack[max_fast_path_segments + 1]; + uint32_t sp = 0; + int32_t node = 0; + uint32_t i = 0; + uint32_t alt = alt_static; + int32_t route = -1; + uint32_t wild_from = 0; + bool wild = false; + for (;;) { + const node_record& nd = t.nodes[static_cast<size_t>(node)]; + if (alt == alt_static) { + if (i == nseg) { + if (nd.terminal_route >= 0) { + route = nd.terminal_route; + break; + } + alt = alt_none; + } else { + const int32_t ord = dispatch_static(t, nd, seg_ref(i)); + if (ord >= 0) { + const int32_t nxt = t.edges[static_cast<size_t>(nd.first_child) + + static_cast<size_t>(ord)] + .node; + if (nxt >= 0) { + if (nd.has_alternative) { + stack[sp++] = {node, static_cast<uint16_t>(i), alt_param}; + } + node = nxt; + i++; + continue; + } + // Pure-leaf shortcut. + if (i + 1 == nseg) { + route = -2 - nxt; + break; + } + alt = alt_param; // dead end: fall through to this node's fallbacks + } else { + alt = alt_param; + } + } + } + if (alt == alt_param) { + const int32_t pc = nd.param_child; + if (pc != -1 && seg_len(i) > 0) { + if (pc >= 0) { + if (nd.wild_route >= 0) { + stack[sp++] = {node, static_cast<uint16_t>(i), alt_wild}; + } + node = pc; + i++; + alt = alt_static; + continue; + } + // Pure-leaf param shortcut. + if (i + 1 == nseg) { + route = -2 - pc; + break; + } + alt = alt_wild; // only the wildcard remains here + } else { + alt = alt_wild; + } + } + if (alt == alt_wild) { + if (nd.wild_route >= 0 && + wildcard_tail_ok(url + soff[i], ulen - soff[i])) { + route = nd.wild_route; + wild_from = i; + wild = true; + break; + } + // No alternative left at this node: resume from the backtrack stack + // (alt is overwritten by the popped record). + } + if (sp == 0) { + break; // nothing to resume: miss + } + --sp; + node = stack[sp].node; + i = stack[sp].i; + alt = stack[sp].resume; + } + + out.route = route; + if (route >= 0) { // capture extraction: params first, wildcard tail last + const route_record& rm = routes[static_cast<size_t>(route)]; + uint32_t nc = 0; + for (uint32_t k = 0; k < rm.n_params; k++) { + const uint32_t p = rm.param_positions[k]; + out.captures[nc++] = {soff[p], seg_len(p)}; + } + if (wild) { + out.captures[nc++] = {soff[wild_from], ulen - soff[wild_from]}; + } + out.capture_count = nc; + } +} + +} // namespace ada::url_pattern_list_detail + +namespace ada { + +template <url_pattern_regex::regex_concept regex_provider> +tl::expected<url_pattern_list<regex_provider>, errors> +url_pattern_list<regex_provider>::create( + std::vector<std::string>&& pathname_patterns, bool ignore_case) { + url_pattern_list list{}; + list.patterns_ = std::move(pathname_patterns); + auto compiled = url_pattern_list_detail::compile_pathname_patterns( + list.patterns_, ignore_case); + if (!compiled) { + return tl::unexpected(compiled.error()); + } + list.compiled_ = std::move(*compiled); + return list; +} + +template <url_pattern_regex::regex_concept regex_provider> +void url_pattern_list<regex_provider>::consider_route( + uint32_t route_index, std::string_view pathname, std::string_view probe, + bool fold_input, url_pattern_list_detail::engine_result& best, + std::vector<std::optional<std::string>>& best_groups) const { + namespace detail = url_pattern_list_detail; + const detail::route_record* routes = + compiled_.section<detail::route_record>(compiled_.routes_offset); + const detail::route_record& candidate = routes[route_index]; + // Only test candidates that would outrank the current best. + if (best.route >= 0) { + const detail::route_record& current = + routes[static_cast<size_t>(best.route)]; + if (!detail::outranks(candidate.kind_sequence, candidate.kind_length, + route_index, current.kind_sequence, + current.kind_length, + static_cast<size_t>(best.route))) { + return; + } + } + if (candidate.mode == detail::route_mode::regexp) { + // A route whose certain segment shape does not fit the input cannot + // match at all: skip the provider. + if (!detail::match_regexp_shape(compiled_, route_index, probe, + fold_input)) { + return; + } + // URLPattern's own test/exec split: regex_match answers yes/no (this is + // what rejects a non-matching route cheaply; a regex_search miss can + // cost a scan over every start position), and regex_search then + // produces the group values exactly as url_pattern::exec does. + const url_pattern_component<regex_provider>& component = + regexp_components_[static_cast<size_t>(candidate.regexp_component)]; + if (!component.fast_test(pathname)) { + return; + } + auto groups = component.fast_match(pathname); + if (groups) { + best = detail::engine_result{}; + best.route = static_cast<int32_t>(route_index); + best_groups = std::move(*groups); + } + } else { + detail::engine_result scratch{}; + if (detail::match_route_sequential(compiled_, route_index, probe, + fold_input, scratch)) { + scratch.route = static_cast<int32_t>(route_index); + best = scratch; + best_groups.clear(); + } + } +} + +template <url_pattern_regex::regex_concept regex_provider> +url_pattern_list_match_result url_pattern_list<regex_provider>::match( + std::string_view pathname) const { + namespace detail = url_pattern_list_detail; + using url_pattern_list_limits::max_fast_path_pathname_length; + // A default-constructed list (or one compiled from no routes) has no + // tables. Walking them would dereference section pointers into an empty + // arena. + if (patterns_.empty() || compiled_.arena.empty()) { + return {}; + } + // With ignore_case the compiled literals are ASCII-folded, so the fast + // path probes a folded copy of the input (offsets are unchanged, so the + // captures still slice the original). Inputs beyond the fast-path length + // are folded on the fly by the sequential matcher instead. + char folded[max_fast_path_pathname_length]; + std::string_view probe = pathname; + bool fold_input = false; + if (compiled_.ignore_case) { + if (pathname.size() <= max_fast_path_pathname_length) { + detail::ascii_fold(pathname.data(), + static_cast<uint32_t>(pathname.size()), folded); + probe = std::string_view(folded, pathname.size()); + } else { + fold_input = true; + } + } + detail::engine_result best{}; + std::vector<std::optional<std::string>> best_groups{}; + detail::match_compiled(compiled_, probe.data(), + static_cast<uint32_t>(probe.size()), best); + const uint32_t* aux = compiled_.section<uint32_t>(compiled_.aux_offset); + if (!best.within_fast_path) { + // The input exceeds a fast-path limit (length, segment count, or no + // leading '/'): the sequential fallback matches every route with + // identical priority semantics. + best = detail::engine_result{}; + for (size_t i = 0; i < patterns_.size(); i++) { + consider_route(static_cast<uint32_t>(i), pathname, probe, fold_input, + best, best_groups); + } + } else if (best.route >= 0) { + // A fast-path winner is final except for the auxiliary routes recorded + // at creation as able to outrank it (usually none). + const detail::route_record& winner = + compiled_.section<detail::route_record>( + compiled_.routes_offset)[static_cast<size_t>(best.route)]; + for (uint32_t k = 0; k < winner.challenger_count; k++) { + consider_route(aux[winner.challenger_first + k], pathname, probe, + fold_input, best, best_groups); + } + } else { + // A fast-path miss: any auxiliary route may still match. + for (uint32_t k = 0; k < compiled_.n_aux_all; k++) { + consider_route(aux[k], pathname, probe, fold_input, best, best_groups); + } + } + url_pattern_list_match_result result{}; + result.route_index = best.route; + if (best.route >= 0) { + const detail::route_record& winner = + compiled_.section<detail::route_record>( + compiled_.routes_offset)[static_cast<size_t>(best.route)]; + if (winner.mode == detail::route_mode::regexp) { + result.regexp_route = true; + result.regexp_groups = std::move(best_groups); + } else { + result.capture_count = best.capture_count; + result.captures_truncated = best.captures_truncated; + result.captures = best.captures; + } + } + return result; +} + +} // namespace ada +#endif // ADA_INCLUDE_URL_PATTERN +#endif // ADA_URL_PATTERN_LIST_INL_H +/* end file include/ada/url_pattern_list-inl.h */ + +// Public API +/* begin file include/ada/ada_version.h */ +/** + * @file ada_version.h + * @brief Definitions for Ada's version number. + */ +#ifndef ADA_ADA_VERSION_H +#define ADA_ADA_VERSION_H + +#define ADA_VERSION "4.1.1" + +namespace ada { + +enum { + ADA_VERSION_MAJOR = 4, + ADA_VERSION_MINOR = 1, + ADA_VERSION_REVISION = 1, +}; + +} // namespace ada + +#endif // ADA_ADA_VERSION_H +/* end file include/ada/ada_version.h */ +/* begin file include/ada/implementation-inl.h */ +/** + * @file implementation-inl.h + */ +#ifndef ADA_IMPLEMENTATION_INL_H +#define ADA_IMPLEMENTATION_INL_H + + + +#include <cstddef> +#include <span> +#include <string> +#include <string_view> +#include <utility> +#include <variant> +#include <vector> namespace ada { @@ -11643,6 +13222,94 @@ parse_url_pattern(std::variant<std::string_view, url_pattern_init>&& input, return parser::parse_url_pattern_impl<regex_provider>(std::move(input), base_url, options); } + +template <url_pattern_regex::regex_concept regex_provider> +ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors> +parse_url_pattern_list(std::span<const std::string_view> pathname_patterns, + const std::string_view* base_url, + const url_pattern_options* options) { + std::vector<std::string> processed; + processed.reserve(pathname_patterns.size()); + for (const std::string_view pattern : pathname_patterns) { + if (base_url == nullptr) { + processed.emplace_back(pattern); + continue; + } + // With a base URL, each pattern is processed exactly as the pathname of + // a URLPatternInit would be: a relative pattern is resolved against the + // base URL's path (and an unparsable base URL is a type error). + url_pattern_init init{}; + init.pathname = std::string(pattern); + init.base_url = std::string(*base_url); + auto result = url_pattern_init::process( + init, url_pattern_init::process_type::pattern); + if (!result) { + return tl::unexpected(result.error()); + } + processed.push_back(std::move(result->pathname).value_or(std::string{})); + } + const bool ignore_case = options != nullptr && options->ignore_case; + auto list = url_pattern_list<regex_provider>::create(std::move(processed), + ignore_case); + if (!list) { + return list; + } + // Routes outside the static/":param"/"*" subset are compiled as a + // URLPattern pathname component through the provider, with the same + // options parse_url_pattern would use (ignore_case included). + auto compile_options = url_pattern_compile_component_options::PATHNAME; + compile_options.ignore_case = ignore_case; + const url_pattern_list_detail::route_record* routes = + list->compiled_.template section<url_pattern_list_detail::route_record>( + list->compiled_.routes_offset); + for (size_t i = 0; i < list->patterns_.size(); i++) { + if (routes[i].regexp_component < 0) { + continue; + } + auto component = url_pattern_component<regex_provider>::compile( + list->patterns_[i], url_pattern_helpers::canonicalize_pathname, + compile_options); + if (!component) { + return tl::unexpected(component.error()); + } + list->compiled_.group_names[i] = component->group_name_list; + list->regexp_components_.push_back(std::move(*component)); + } + return list; +} + +template <url_pattern_regex::regex_concept regex_provider> +ada_warn_unused tl::expected<url_pattern_list<regex_provider>, errors> +parse_url_pattern_list(std::span<const url_pattern<regex_provider>> patterns) { + std::vector<std::string> texts; + texts.reserve(patterns.size()); + const bool ignore_case = !patterns.empty() && patterns[0].ignore_case(); + for (const url_pattern<regex_provider>& pattern : patterns) { + if (pattern.ignore_case() != ignore_case) { + return tl::unexpected(errors::type_error); // one flag per list + } + texts.emplace_back(pattern.get_pathname()); + } + auto list = + url_pattern_list<regex_provider>::create(std::move(texts), ignore_case); + if (!list) { + return list; + } + // Routes outside the subset reuse the pattern's already compiled pathname + // component: no second create_instance through the provider. + const url_pattern_list_detail::route_record* routes = + list->compiled_.template section<url_pattern_list_detail::route_record>( + list->compiled_.routes_offset); + for (size_t i = 0; i < patterns.size(); i++) { + if (routes[i].regexp_component < 0) { + continue; + } + list->compiled_.group_names[i] = + patterns[i].pathname_component.group_name_list; + list->regexp_components_.push_back(patterns[i].pathname_component); + } + return list; +} #endif // ADA_INCLUDE_URL_PATTERN } // namespace ada diff --git a/deps/ada/ada_c.h b/deps/ada/ada_c.h index 98e4ce20ccd5..c3c7c1ad5fb2 100644 --- a/deps/ada/ada_c.h +++ b/deps/ada/ada_c.h @@ -24,7 +24,10 @@ typedef struct { size_t length; } ada_string; -// string that must be freed by the caller +// string that must be freed by the caller. +// data is NUL-terminated. length does not include the trailing NUL. +// data is null only when the call failed; an empty string is a non-null +// pointer to a single '\0' with length 0. typedef struct { const char* data; size_t length; diff --git a/deps/googletest/include/gtest/gtest.h b/deps/googletest/include/gtest/gtest.h index 7c003c5d60e3..28a7fa8fbc24 100644 --- a/deps/googletest/include/gtest/gtest.h +++ b/deps/googletest/include/gtest/gtest.h @@ -300,12 +300,12 @@ class GTEST_API_ [[nodiscard]] Test { // global context (before or after invocation of RUN_ALL_TESTS and from // SetUp/TearDown method of Environment objects registered with Google // Test) will be output as attributes of the <testsuites> element. - static void RecordProperty(const std::string& key, const std::string& value); + static void RecordProperty(std::string_view key, std::string_view value); // We do not define a custom serialization except for values that can be // converted to int64_t, but other values could be logged in this way. template <typename T, std::enable_if_t<std::is_convertible<T, int64_t>::value, bool> = true> - static void RecordProperty(const std::string& key, const T& value) { + static void RecordProperty(std::string_view key, const T& value) { RecordProperty(key, (Message() << value).GetString()); } @@ -376,7 +376,7 @@ class [[nodiscard]] TestProperty { // C'tor. TestProperty does NOT have a default constructor. // Always use this constructor (with parameters) to create a // TestProperty object. - TestProperty(const std::string& a_key, const std::string& a_value) + TestProperty(std::string_view a_key, std::string_view a_value) : key_(a_key), value_(a_value) {} // Gets the user supplied key. @@ -386,7 +386,7 @@ class [[nodiscard]] TestProperty { const char* value() const { return value_.c_str(); } // Sets a new value, overriding the one supplied in the constructor. - void SetValue(const std::string& new_value) { value_ = new_value; } + void SetValue(std::string_view new_value) { value_ = new_value; } private: // The key supplied by the user. @@ -1261,7 +1261,7 @@ class GTEST_API_ [[nodiscard]] UnitTest { // from SetUpTestSuite or TearDownTestSuite, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. - void RecordProperty(const std::string& key, const std::string& value); + void RecordProperty(std::string_view key, std::string_view value); // Gets the i-th test suite among all the test suites. i can range from 0 to // total_test_suite_count() - 1. If i is not in that range, returns NULL. diff --git a/deps/googletest/include/gtest/internal/gtest-port.h b/deps/googletest/include/gtest/internal/gtest-port.h index 3b2947b852e7..081b2facdaea 100644 --- a/deps/googletest/include/gtest/internal/gtest-port.h +++ b/deps/googletest/include/gtest/internal/gtest-port.h @@ -676,7 +676,7 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; #if defined(GTEST_OS_WINDOWS_MOBILE) || defined(GTEST_OS_WINDOWS_PHONE) || \ defined(GTEST_OS_WINDOWS_RT) || defined(GTEST_OS_WINDOWS_GAMES) || \ defined(GTEST_OS_ESP8266) || defined(GTEST_OS_XTENSA) || \ - defined(GTEST_OS_QURT) || !GTEST_HAS_FILE_SYSTEM + defined(GTEST_OS_QURT) || defined(__wasi__) || !GTEST_HAS_FILE_SYSTEM #define GTEST_HAS_STREAM_REDIRECTION 0 #else #define GTEST_HAS_STREAM_REDIRECTION 1 @@ -706,8 +706,9 @@ typedef struct _RTL_CRITICAL_SECTION GTEST_CRITICAL_SECTION; // Created by default when Death tests are supported, but other platforms can // use the Premature exit file without Death test support (e.g. for detecting // crashes). -#if GTEST_HAS_DEATH_TEST || \ - (defined(GTEST_OS_EMSCRIPTEN) && GTEST_HAS_FILE_SYSTEM) +#if GTEST_HAS_DEATH_TEST || \ + ((defined(GTEST_OS_EMSCRIPTEN) || defined(GTEST_OS_IOS)) && \ + GTEST_HAS_FILE_SYSTEM) #define GTEST_INTERNAL_HAS_PREMATURE_EXIT_FILE 1 #endif diff --git a/deps/googletest/src/gtest.cc b/deps/googletest/src/gtest.cc index d66756e88f54..88b478e80836 100644 --- a/deps/googletest/src/gtest.cc +++ b/deps/googletest/src/gtest.cc @@ -2565,7 +2565,7 @@ void Test::SetUp() {} void Test::TearDown() {} // Allows user supplied key value pairs to be recorded for later output. -void Test::RecordProperty(const std::string& key, const std::string& value) { +void Test::RecordProperty(std::string_view key, std::string_view value) { UnitTest::GetInstance()->RecordProperty(key, value); } @@ -5528,8 +5528,7 @@ void UnitTest::AddTestPartResult(TestPartResult::Type result_type, // from SetUpTestSuite or TearDownTestSuite, or to the global property set // when invoked elsewhere. If the result already contains a property with // the same key, the value will be updated. -void UnitTest::RecordProperty(const std::string& key, - const std::string& value) { +void UnitTest::RecordProperty(std::string_view key, std::string_view value) { impl_->RecordProperty(TestProperty(key, value)); } diff --git a/deps/histogram/include/hdr/hdr_histogram.h b/deps/histogram/include/hdr/hdr_histogram.h index 3dd76037ee67..2c35186a152e 100644 --- a/deps/histogram/include/hdr/hdr_histogram.h +++ b/deps/histogram/include/hdr/hdr_histogram.h @@ -265,8 +265,9 @@ int64_t hdr_add_while_correcting_for_coordinated_omission( struct hdr_histogram* h, struct hdr_histogram* from, int64_t expected_interval); /** - * Get minimum value from the histogram. Will return 2^63-1 if the histogram - * is empty. + * Get minimum value from the histogram. Will return 0 if the histogram is + * empty, like hdr_max; a recorded 0 also gives 0, so use hdr_total_count to + * tell the two apart. * * @param h "This" pointer */ @@ -292,7 +293,10 @@ int64_t hdr_total_count(const struct hdr_histogram* h); * Get the value at a specific percentile. * * @param h "This" pointer. - * @param percentile The percentile to get the value for + * @param percentile The percentile to get the value for. Above 100 gives the value at + * 100; below 0 and -inf give the first recorded value. Exactly 0 returns the lowest + * equivalent value of that bucket. + * @return the value at the percentile, or 0 if no values have been recorded. */ int64_t hdr_value_at_percentile(const struct hdr_histogram* h, double percentile); @@ -300,11 +304,14 @@ int64_t hdr_value_at_percentile(const struct hdr_histogram* h, double percentile * Get the values at the given percentiles. * * @param h "This" pointer. - * @param percentiles The ordered percentiles array to get the values for. + * @param percentiles The ordered percentiles array to get the values for, with the + * same out-of-range handling as hdr_value_at_percentile. * @param length Number of elements in the arrays. * @param values Destination array containing the values at the given percentiles. * The values array should be allocated by the caller. - * @return 0 on success, ENOMEM if the provided destination array is null. + * Percentiles that cannot be resolved get the same value hdr_value_at_percentile + * returns for them, so all are 0 on an empty histogram. + * @return 0 on success, EINVAL if percentiles or values is null. */ int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percentiles, int64_t *values, size_t length); @@ -312,7 +319,7 @@ int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percen * Gets the standard deviation for the values in the histogram. * * @param h "This" pointer - * @return The standard deviation + * @return The standard deviation, or 0.0 if the histogram is empty. */ double hdr_stddev(const struct hdr_histogram* h); @@ -320,7 +327,7 @@ double hdr_stddev(const struct hdr_histogram* h); * Gets the mean for the values in the histogram. * * @param h "This" pointer - * @return The mean + * @return The mean, or 0.0 if the histogram is empty. */ double hdr_mean(const struct hdr_histogram* h); diff --git a/deps/histogram/include/hdr/hdr_histogram_version.h b/deps/histogram/include/hdr/hdr_histogram_version.h index c009dce9f205..a03cb6215a74 100644 --- a/deps/histogram/include/hdr/hdr_histogram_version.h +++ b/deps/histogram/include/hdr/hdr_histogram_version.h @@ -7,6 +7,6 @@ #ifndef HDR_HISTOGRAM_VERSION_H #define HDR_HISTOGRAM_VERSION_H -#define HDR_HISTOGRAM_VERSION "0.12.0" +#define HDR_HISTOGRAM_VERSION "0.12.1" #endif // HDR_HISTOGRAM_VERSION_H diff --git a/deps/histogram/src/hdr_histogram.c b/deps/histogram/src/hdr_histogram.c index 3d10cf589692..71c26c9e8d82 100644 --- a/deps/histogram/src/hdr_histogram.c +++ b/deps/histogram/src/hdr_histogram.c @@ -780,7 +780,7 @@ int64_t hdr_total_count(const struct hdr_histogram* h) int64_t hdr_min(const struct hdr_histogram* h) { - if (0 < hdr_count_at_index(h, 0)) + if (0 == hdr_total_count(h) || 0 < hdr_count_at_index(h, 0)) { return 0; } @@ -914,12 +914,25 @@ static int64_t get_value_from_idx_up_to_count(const struct hdr_histogram* h, int } +/* Target cumulative count in [1, total_count]; NaN/+inf -> total_count, -inf/negative -> 1 */ +static int64_t count_at_percentile(int64_t total_count, double percentile) +{ + const double requested = percentile < 100.0 ? percentile : 100.0; + const double cc = ((requested / 100) * (double) total_count) + 0.5; + if (!(cc >= 1.0)) return 1; + if (cc >= (double) total_count) return total_count; + return (int64_t) cc; +} + int64_t hdr_value_at_percentile(const struct hdr_histogram* h, double percentile) { - double requested_percentile = percentile < 100.0 ? percentile : 100.0; - int64_t count_at_percentile = - (int64_t) (((requested_percentile / 100) * h->total_count) + 0.5); - int64_t value_from_idx = get_value_from_idx_up_to_count(h, count_at_percentile); + /* empty: the scan's not-found 0 must not be rounded up to highest_equivalent_value(0) */ + if (HDR_UNLIKELY(h->total_count == 0)) + { + return 0; + } + int64_t value_from_idx = + get_value_from_idx_up_to_count(h, count_at_percentile(h->total_count, percentile)); if (percentile == 0.0) { return lowest_equivalent_value(h, value_from_idx); @@ -927,12 +940,26 @@ int64_t hdr_value_at_percentile(const struct hdr_histogram* h, double percentile return highest_equivalent_value(h, value_from_idx); } +/* p0 is the bucket's lowest value, matching hdr_value_at_percentile */ +static int64_t percentile_bound(const struct hdr_histogram* h, double percentile, int64_t value) +{ + return percentile == 0.0 ? lowest_equivalent_value(h, value) : highest_equivalent_value(h, value); +} + int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percentiles, int64_t *values, size_t length) { if (NULL == percentiles || NULL == values) { return EINVAL; } + if (HDR_UNLIKELY(h->total_count == 0)) + { + for (size_t i = 0; i < length; i++) + { + values[i] = 0; + } + return 0; + } struct hdr_iter iter; const int64_t total_count = h->total_count; @@ -940,10 +967,7 @@ int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percen // i.e. to store the expected cumulative count at each percentile for (size_t i = 0; i < length; i++) { - const double requested_percentile = percentiles[i] < 100.0 ? percentiles[i] : 100.0; - const int64_t count_at_percentile = - (int64_t) (((requested_percentile / 100) * total_count) + 0.5); - values[i] = count_at_percentile > 1 ? count_at_percentile : 1; + values[i] = count_at_percentile(total_count, percentiles[i]); } uint64_t total = 0; /* unsigned: no signed-overflow UB when a hostile block sum is added at once */ @@ -974,7 +998,7 @@ int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percen total += (uint64_t)counts[j]; while (at_pos < length && (int64_t)total >= values[at_pos]) { - values[at_pos] = highest_equivalent_value(h, hdr_value_at_index(h, j)); + values[at_pos] = percentile_bound(h, percentiles[at_pos], hdr_value_at_index(h, j)); at_pos++; } } @@ -990,7 +1014,7 @@ int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percen total += (uint64_t)counts[idx]; while (at_pos < length && (int64_t)total >= values[at_pos]) { - values[at_pos] = highest_equivalent_value(h, hdr_value_at_index(h, idx)); + values[at_pos] = percentile_bound(h, percentiles[at_pos], hdr_value_at_index(h, idx)); at_pos++; } } @@ -1005,11 +1029,17 @@ int hdr_value_at_percentiles(const struct hdr_histogram *h, const double *percen total += (uint64_t)iter.count; while (at_pos < length && (int64_t)total >= values[at_pos]) { - values[at_pos] = highest_equivalent_value(h, iter.value); + values[at_pos] = percentile_bound(h, percentiles[at_pos], iter.value); at_pos++; } } } + /* unreached targets (counts below total_count) get the singular's not-found value */ + for (; at_pos < length; at_pos++) + { + values[at_pos] = percentiles[at_pos] == 0.0 ? + lowest_equivalent_value(h, 0) : highest_equivalent_value(h, 0); + } return 0; } @@ -1020,6 +1050,11 @@ double hdr_mean(const struct hdr_histogram* h) int64_t count = 0; int64_t total_count = h->total_count; + if (total_count == 0) + { + return 0.0; + } + hdr_iter_init(&iter, h); while (hdr_iter_next(&iter) && count < total_count) @@ -1037,6 +1072,11 @@ double hdr_mean(const struct hdr_histogram* h) double hdr_stddev(const struct hdr_histogram* h) { + if (h->total_count == 0) + { + return 0.0; + } + double mean = hdr_mean(h); double geometric_dev_total = 0.0; diff --git a/deps/inspector_protocol/README.node b/deps/inspector_protocol/README.node index 6216d7a8ea06..ca6864b05083 100644 --- a/deps/inspector_protocol/README.node +++ b/deps/inspector_protocol/README.node @@ -2,7 +2,7 @@ Name: inspector protocol Short Name: inspector_protocol URL: https://chromium.googlesource.com/deps/inspector_protocol/ Version: 0 -Revision: 1b1bcbbe060e8c8cd8704f00f78978c50991b307 +Revision: c0045057ce801744c5e88596a2f1bab1802e39f0 License: BSD License File: LICENSE Security Critical: no diff --git a/deps/inspector_protocol/code_generator.py b/deps/inspector_protocol/code_generator.py index b25ffc29b0a9..2ad9465a6b2f 100755 --- a/deps/inspector_protocol/code_generator.py +++ b/deps/inspector_protocol/code_generator.py @@ -101,35 +101,35 @@ def init_defaults(config_tuple, path, defaults): config_base) config_json_file.close() defaults = { - ".use_snake_file_names": False, - ".use_title_case_methods": False, - ".use_embedder_types": False, - ".imported": False, - ".imported.export_macro": "", - ".imported.export_header": False, - ".imported.header": False, - ".imported.package": False, - ".imported.options": False, - ".protocol.export_macro": "", - ".protocol.export_header": False, - ".protocol.options": False, - ".protocol.file_name_prefix": "", - ".exported": False, - ".exported.export_macro": "", - ".exported.export_header": False, - ".lib": False, - ".lib.export_macro": "", - ".lib.export_header": False, - ".crdtp": False, - ".crdtp.dir": os.path.join(inspector_protocol_dir, "crdtp"), - ".crdtp.namespace": "crdtp", + ".use_snake_file_names": False, + ".use_title_case_methods": False, + ".use_embedder_types": False, + ".imported": False, + ".imported.export_macro": "", + ".imported.export_header": False, + ".imported.header": False, + ".imported.package": False, + ".imported.options": False, + ".protocol.export_macro": "", + ".protocol.export_header": False, + ".protocol.options": False, + ".protocol.file_name_prefix": "", + ".exported": False, + ".exported.export_macro": "", + ".exported.export_header": False, + ".lib": False, + ".lib.export_macro": "", + ".lib.export_header": False, + ".crdtp": False, + ".crdtp.dir": os.path.join(inspector_protocol_dir, "crdtp"), + ".crdtp.namespace": "crdtp", } for key_value in config_values: parts = key_value.split("=") if len(parts) == 2: defaults["." + parts[0]] = parts[1] - return (jinja_dir, config_file, init_defaults(config_partial, "", defaults), - depfile, stamp) + return (jinja_dir, config_file, init_defaults(config_partial, "", + defaults), depfile, stamp) except Exception: # Work with python 2 and 3 http://docs.python.org/py3k/howto/pyporting.html exc = sys.exc_info()[1] @@ -286,32 +286,32 @@ def create_any_type_definition(): def create_string_type_definition(): # pylint: disable=W0622 return { - "return_type": "String", - "pass_type": "const String&", - "to_pass_type": "%s", - "to_raw_type": "%s", - "to_rvalue": "%s", - "type": "String", - "raw_type": "String", - "raw_pass_type": "const String&", - "raw_return_type": "String", - "is_primitive": True + "return_type": "String", + "pass_type": "const String&", + "to_pass_type": "%s", + "to_raw_type": "%s", + "to_rvalue": "%s", + "type": "String", + "raw_type": "String", + "raw_pass_type": "const String&", + "raw_return_type": "String", + "is_primitive": True } def create_binary_type_definition(): # pylint: disable=W0622 return { - "return_type": "Binary", - "pass_type": "const Binary&", - "to_pass_type": "%s", - "to_raw_type": "%s", - "to_rvalue": "%s", - "type": "Binary", - "raw_type": "Binary", - "raw_pass_type": "const Binary&", - "raw_return_type": "Binary", - "is_primitive": True + "return_type": "Binary", + "pass_type": "const Binary&", + "to_pass_type": "%s", + "to_raw_type": "%s", + "to_rvalue": "%s", + "type": "Binary", + "raw_type": "Binary", + "raw_pass_type": "const Binary&", + "raw_return_type": "Binary", + "is_primitive": True } @@ -333,17 +333,17 @@ def create_primitive_type_definition(type): "boolean": "TypeBoolean", } return { - "return_type": typedefs[type], - "pass_type": typedefs[type], - "to_pass_type": "%s", - "to_raw_type": "%s", - "to_rvalue": "%s", - "type": typedefs[type], - "raw_type": typedefs[type], - "raw_pass_type": typedefs[type], - "raw_return_type": typedefs[type], - "default_value": defaults[type], - "is_primitive": True + "return_type": typedefs[type], + "pass_type": typedefs[type], + "to_pass_type": "%s", + "to_raw_type": "%s", + "to_rvalue": "%s", + "type": typedefs[type], + "raw_type": typedefs[type], + "raw_pass_type": typedefs[type], + "raw_return_type": typedefs[type], + "default_value": defaults[type], + "is_primitive": True } def wrap_array_definition(type): @@ -444,10 +444,12 @@ def check_if_dependency_declared(self, domain, refs): domain_match = re.match(r'^(.*)[.]', ref) if domain_match: referenced_domain_name = domain_match.group(1) - if referenced_domain_name != domain['domain'] and not referenced_domain_name in dependencies: - sys.stderr.write(("Domains [%s] uses type [%s] from domain [%s], but did not declare the dependency\n\n" - ) % (domain["domain"], ref, referenced_domain_name)) - exit(1) + if referenced_domain_name != domain[ + 'domain'] and not referenced_domain_name in dependencies: + sys.stderr.write(( + "Domains [%s] uses type [%s] from domain [%s], but did not declare the dependency\n\n" + ) % (domain["domain"], ref, referenced_domain_name)) + exit(1) def generate_used_types(self): all_refs = set() @@ -552,10 +554,10 @@ def resolve_type(self, prop): return self.type_definitions[prop["type"]] def optional_type(self, prop): - type = self.resolve_type(prop) - template = ("std::optional<{}>" if type.get('is_primitive', False) - else "std::unique_ptr<{}>") - return template.format(type.get("raw_type")) + type = self.resolve_type(prop) + template = ("std::optional<{}>" + if type.get('is_primitive', False) else "std::unique_ptr<{}>") + return template.format(type.get("raw_type")) def generate_command(self, domain, command): if not self.config.protocol.options: @@ -572,6 +574,12 @@ def generate_event(self, domain, event): def generate_type(self, domain, typename): return domain + "." + typename in self.used_types + def should_pass_associated_data(self, domain, command): + if not self.config.protocol.options: + return False + return self.check_options(self.config.protocol.options, domain, command, + "pass_associated_data", None, False) + def is_async_command(self, domain, command): if not self.config.protocol.options: return False @@ -658,25 +666,23 @@ def main(): } if domain["domain"] in protocol.generate_domains: - output_h = os.path.join(config.protocol.output, to_file_name( - config, file_name + ".h")) + output_h = os.path.join(config.protocol.output, + to_file_name(config, file_name + ".h")) outputs[output_h] = h_template.render(template_context) source_set.add(h_template.filename) - output_cpp = os.path.join(config.protocol.output, to_file_name( - config, file_name + ".cpp")) + output_cpp = os.path.join(config.protocol.output, + to_file_name(config, file_name + ".cpp")) outputs[output_cpp] = cpp_template.render(template_context) source_set.add(cpp_template.filename) if domain["domain"] in protocol.exported_domains: - output_export_h = os.path.join(config.exported.output, to_file_name( - config, file_name + ".h")) - outputs[output_export_h] = exported_template.render( - template_context) + output_export_h = os.path.join(config.exported.output, + to_file_name(config, file_name + ".h")) + outputs[output_export_h] = exported_template.render(template_context) source_set.add(exported_template.filename) if domain["domain"] in protocol.imported_domains: - output_import_h = os.path.join(config.protocol.output, to_file_name( - config, file_name + ".h")) - outputs[output_import_h] = imported_template.render( - template_context) + output_import_h = os.path.join(config.protocol.output, + to_file_name(config, file_name + ".h")) + outputs[output_import_h] = imported_template.render(template_context) source_set.add(imported_template.filename) if config.lib: @@ -699,19 +705,19 @@ def main(): if not config.use_embedder_types: protocol_h_templates += [ - "Values_h.template", - "Object_h.template", - "ValueConversions_h.template", + "Values_h.template", + "Object_h.template", + "ValueConversions_h.template", ] protocol_cpp_templates += [ - "Protocol_cpp.template", - "Values_cpp.template", - "Object_cpp.template", - "ValueConversions_cpp.template", + "Protocol_cpp.template", + "Values_cpp.template", + "Object_cpp.template", + "ValueConversions_cpp.template", ] else: protocol_h_templates += [ - "Forward_h.template", + "Forward_h.template", ] def generate_lib_file(file_name, template_files): @@ -729,8 +735,9 @@ def generate_lib_file(file_name, template_files): config, "Protocol.h")), protocol_h_templates) if not config.use_embedder_types: - generate_lib_file(os.path.join(config.lib.output, to_file_name( - config, "Protocol.cpp")), protocol_cpp_templates) + generate_lib_file( + os.path.join(config.lib.output, to_file_name(config, "Protocol.cpp")), + protocol_cpp_templates) if stamp_filename: with open(stamp_filename, "w"): @@ -748,8 +755,8 @@ def generate_lib_file(file_name, template_files): if deps_filename: assert stamp_filename with open(deps_filename, "w") as deps_file: - deps_file.write("%s: %s\n" % ( - stamp_filename, " ".join(sorted(source_set)))) + deps_file.write("%s: %s\n" % + (stamp_filename, " ".join(sorted(source_set)))) if __name__ == "__main__": diff --git a/deps/inspector_protocol/concatenate_protocols.py b/deps/inspector_protocol/concatenate_protocols.py index 8ad4f6de712a..14bb366497c8 100755 --- a/deps/inspector_protocol/concatenate_protocols.py +++ b/deps/inspector_protocol/concatenate_protocols.py @@ -58,8 +58,8 @@ def main(argv): if deps_filename: assert stamp_filename with open(deps_filename, "w") as deps_file: - deps_file.write("%s: %s\n" % ( - stamp_filename, " ".join(sorted(source_set)))) + deps_file.write("%s: %s\n" % + (stamp_filename, " ".join(sorted(source_set)))) if __name__ == '__main__': diff --git a/deps/inspector_protocol/crdtp/cbor.cc b/deps/inspector_protocol/crdtp/cbor.cc index dc52549c55a6..7e62d765141c 100644 --- a/deps/inspector_protocol/crdtp/cbor.cc +++ b/deps/inspector_protocol/crdtp/cbor.cc @@ -1074,5 +1074,97 @@ Status AppendString8EntryToCBORMap(span<uint8_t> string8_key, *(out) = new_envelope_size & 0xff; return Status(); } + +span<uint8_t> GetString8ValueFromMap(span<uint8_t> message, + span<uint8_t> string8_key) { + CBORTokenizer tokenizer(message); + if (tokenizer.TokenTag() != CBORTokenTag::ENVELOPE) { + return {}; + } + tokenizer.EnterEnvelope(); + if (tokenizer.TokenTag() != CBORTokenTag::MAP_START) { + return {}; + } + tokenizer.Next(); + span<uint8_t> result; + bool found_key = false; + bool found_value = false; + bool is_key = true; + while (tokenizer.TokenTag() != CBORTokenTag::STOP && + tokenizer.TokenTag() != CBORTokenTag::DONE && + tokenizer.TokenTag() != CBORTokenTag::ERROR_VALUE) { + if (tokenizer.TokenTag() == CBORTokenTag::MAP_START || + tokenizer.TokenTag() == CBORTokenTag::ARRAY_START) { + return {}; + } + if (is_key) { + if (tokenizer.TokenTag() == CBORTokenTag::STRING8 && + SpanEquals(tokenizer.GetString8(), string8_key)) { + if (found_key) { + return {}; // Duplicate key + } + found_key = true; + } + } else if (found_key && !found_value) { + if (tokenizer.TokenTag() == CBORTokenTag::STRING8) { + result = tokenizer.GetString8(); + } + found_value = true; + } + tokenizer.Next(); + is_key = !is_key; + } + if (tokenizer.TokenTag() != CBORTokenTag::STOP) { + return {}; + } + return result; +} + +bool HasKeyInMap(span<uint8_t> message, span<uint8_t> key) { + CBORTokenizer tokenizer(message); + if (tokenizer.TokenTag() != CBORTokenTag::ENVELOPE) { + return false; + } + tokenizer.EnterEnvelope(); + if (tokenizer.TokenTag() != CBORTokenTag::MAP_START) { + return false; + } + tokenizer.Next(); + bool is_key = true; + size_t nested_depth = 0; + while (tokenizer.TokenTag() != CBORTokenTag::DONE && + tokenizer.TokenTag() != CBORTokenTag::ERROR_VALUE) { + if (tokenizer.TokenTag() == CBORTokenTag::STOP) { + if (nested_depth == 0) { + break; + } + nested_depth--; + if (nested_depth == 0) { + is_key = !is_key; + } + tokenizer.Next(); + continue; + } + if (tokenizer.TokenTag() == CBORTokenTag::MAP_START || + tokenizer.TokenTag() == CBORTokenTag::ARRAY_START) { + nested_depth++; + tokenizer.Next(); + continue; + } + if (nested_depth > 0) { + tokenizer.Next(); + continue; + } + if (is_key) { + if (tokenizer.TokenTag() == CBORTokenTag::STRING8 && + SpanEquals(tokenizer.GetString8(), key)) { + return true; + } + } + tokenizer.Next(); + is_key = !is_key; + } + return false; +} } // namespace cbor } // namespace crdtp diff --git a/deps/inspector_protocol/crdtp/cbor.h b/deps/inspector_protocol/crdtp/cbor.h index 2d925fad5cc3..d7bcfa2652fd 100644 --- a/deps/inspector_protocol/crdtp/cbor.h +++ b/deps/inspector_protocol/crdtp/cbor.h @@ -315,6 +315,18 @@ CRDTP_EXPORT Status AppendString8EntryToCBORMap(span<uint8_t> string8_key, span<uint8_t> string8_value, std::vector<uint8_t>* cbor); +// Safely extracts the value for |string8_key| from a CBOR encoded map wrapped +// in an envelope. This is a shallow parser that skips unknown keys and +// complex values. If the key is not found, or if it is found more than once, +// or if it contains nested maps/arrays, returns an empty span. +// Explicitly rejects duplicate keys and non-STRING8 values. +CRDTP_EXPORT span<uint8_t> GetString8ValueFromMap(span<uint8_t> message, + span<uint8_t> string8_key); +// Safely checks if |key| exists in the top-level of a CBOR encoded map wrapped +// in an envelope. Shallow parser that skips nested structures. +// Returns true as soon as the key is found at the top level. +CRDTP_EXPORT bool HasKeyInMap(span<uint8_t> message, span<uint8_t> key); + namespace internals { // Exposed only for writing tests. CRDTP_EXPORT size_t ReadTokenStart(span<uint8_t> bytes, cbor::MajorType* type, diff --git a/deps/inspector_protocol/crdtp/cbor_test.cc b/deps/inspector_protocol/crdtp/cbor_test.cc index 2d3689e73004..4b23d3629d8e 100644 --- a/deps/inspector_protocol/crdtp/cbor_test.cc +++ b/deps/inspector_protocol/crdtp/cbor_test.cc @@ -1445,5 +1445,362 @@ TEST(AppendString8EntryToMapTest, InvalidEnvelope_Error) { EXPECT_THAT(status, StatusIs(Error::CBOR_INVALID_ENVELOPE, 0)); } } + +// ============================================================================= +// cbor::GetString8ValueFromMap +// ============================================================================= + +TEST(GetString8ValueFromMapTest, HandlesEmptyStringKey) { + std::vector<uint8_t> encoded = { + 0xd8, 0x5a, 0, 0, 0, 2, EncodeIndefiniteLengthMapStart(), EncodeStop()}; + EXPECT_THAT(AppendString8EntryToCBORMap(SpanFrom(""), SpanFrom("value1"), + &encoded), + StatusIsOk()); + EXPECT_THAT(AppendString8EntryToCBORMap(SpanFrom("key2"), SpanFrom("value2"), + &encoded), + StatusIsOk()); + + span<uint8_t> result1 = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("")); + EXPECT_EQ("value1", std::string(result1.begin(), result1.end())); + + span<uint8_t> result2 = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key2")); + EXPECT_EQ("value2", std::string(result2.begin(), result2.end())); +} + +TEST(GetString8ValueFromMapTest, ExtractsValueSuccessfully) { + std::vector<uint8_t> encoded = { + 0xd8, 0x5a, 0, 0, 0, 2, EncodeIndefiniteLengthMapStart(), EncodeStop()}; + EXPECT_THAT(AppendString8EntryToCBORMap(SpanFrom("key1"), SpanFrom("value1"), + &encoded), + StatusIsOk()); + EXPECT_THAT(AppendString8EntryToCBORMap(SpanFrom("key2"), SpanFrom("value2"), + &encoded), + StatusIsOk()); + + span<uint8_t> result1 = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key1")); + EXPECT_EQ("value1", std::string(result1.begin(), result1.end())); + + span<uint8_t> result2 = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key2")); + EXPECT_EQ("value2", std::string(result2.begin(), result2.end())); +} + +TEST(GetString8ValueFromMapTest, HandlesMissingKey) { + std::vector<uint8_t> encoded = { + 0xd8, 0x5a, 0, 0, 0, 2, EncodeIndefiniteLengthMapStart(), EncodeStop()}; + EXPECT_THAT(AppendString8EntryToCBORMap(SpanFrom("key1"), SpanFrom("value1"), + &encoded), + StatusIsOk()); + + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("missing_key")); + EXPECT_TRUE(result.empty()); +} + +TEST(GetString8ValueFromMapTest, HandlesNonStringValuesGracefully) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("int_key"), &encoded); + EncodeInt32(42, &encoded); + + EncodeString8(SpanFrom("string_key"), &encoded); + EncodeString8(SpanFrom("string_value"), &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + span<uint8_t> result1 = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("int_key")); + EXPECT_TRUE(result1.empty()); + + span<uint8_t> result2 = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("string_key")); + EXPECT_EQ("string_value", std::string(result2.begin(), result2.end())); +} + +TEST(GetString8ValueFromMapTest, HandlesErrorValue) { + // Envelope with 2 bytes of content: + // [Map Start (0xbf), String Start length 1 (0x61)]. + // The string key is truncated (missing its data byte), which triggers + // CBORTokenTag::ERROR_VALUE. + std::vector<uint8_t> encoded = { + 0xd8, 0x5a, 0, 0, 0, 2, + EncodeIndefiniteLengthMapStart(), + 0x61 /* major type 3 (string), additional info 1 (length 1) */ + }; + + // Without the fix for the infinite loop, this call would never return. + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key")); + + EXPECT_TRUE(result.empty()); +} + +TEST(GetString8ValueFromMapTest, RejectsDuplicateKeys) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key"), &encoded); + EncodeString8(SpanFrom("value1"), &encoded); + + EncodeString8(SpanFrom("key"), &encoded); + EncodeString8(SpanFrom("value2"), &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key")); + EXPECT_TRUE(result.empty()); +} + +TEST(GetString8ValueFromMapTest, RejectsNestedStructures) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("fake"), &encoded); + // Nested map: {"key": "spoofed"} + encoded.push_back(EncodeIndefiniteLengthMapStart()); + EncodeString8(SpanFrom("key"), &encoded); + EncodeString8(SpanFrom("spoofed"), &encoded); + encoded.push_back(EncodeStop()); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key")); + EXPECT_TRUE(result.empty()); +} + +TEST(GetString8ValueFromMapTest, RejectsString16Values) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key"), &encoded); + // "value16" in UTF-16LE + std::vector<uint16_t> value16 = {'v', 'a', 'l', 'u', 'e', '1', '6'}; + EncodeString16(SpanFrom(value16), &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key")); + EXPECT_TRUE(result.empty()); +} + +TEST(GetString8ValueFromMapTest, HandlesEmptyValuesWithDuplicates) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key"), &encoded); + EncodeString8(SpanFrom(""), &encoded); + + EncodeString8(SpanFrom("key"), &encoded); + EncodeString8(SpanFrom("value2"), &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key")); + EXPECT_TRUE(result.empty()); +} + + +TEST(GetString8ValueFromMapTest, RejectsTruncatedMap) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key"), &encoded); + // Missing value here. + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(encoded), SpanFrom("key")); + EXPECT_TRUE(result.empty()); +} + +TEST(GetString8ValueFromMapTest, InvalidMessage) { + std::vector<uint8_t> msg = { + 0xd8, 0x5a, 0, 0, 0, 2, EncodeIndefiniteLengthMapStart(), 42}; + span<uint8_t> result = + GetString8ValueFromMap(SpanFrom(msg), SpanFrom("key")); + EXPECT_TRUE(result.empty()); +} + +TEST(HasKeyInMapTest, FindsKeySuccessfully) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key1"), &encoded); + EncodeString8(SpanFrom("value1"), &encoded); + + EncodeString8(SpanFrom("key2"), &encoded); + EncodeInt32(42, &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key1"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key2"))); +} + +TEST(HasKeyInMapTest, HandlesMissingKey) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key1"), &encoded); + EncodeString8(SpanFrom("value1"), &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + EXPECT_FALSE(HasKeyInMap(SpanFrom(encoded), SpanFrom("missing_key"))); +} + +TEST(HasKeyInMapTest, WorksWithVariousValueTypes) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("string_key"), &encoded); + EncodeString8(SpanFrom("value"), &encoded); + + EncodeString8(SpanFrom("int_key"), &encoded); + EncodeInt32(42, &encoded); + + EncodeString8(SpanFrom("double_key"), &encoded); + EncodeDouble(3.14, &encoded); + + EncodeString8(SpanFrom("bool_true_key"), &encoded); + encoded.push_back(EncodeTrue()); + + EncodeString8(SpanFrom("bool_false_key"), &encoded); + encoded.push_back(EncodeFalse()); + + EncodeString8(SpanFrom("null_key"), &encoded); + encoded.push_back(EncodeNull()); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("string_key"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("int_key"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("double_key"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("bool_true_key"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("bool_false_key"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("null_key"))); +} + +TEST(HasKeyInMapTest, HandlesErrorValue) { + // Envelope with 2 bytes of content: + // [Map Start (0xbf), String Start length 1 (0x61)]. + // The string key is truncated (missing its data byte), which triggers + // CBORTokenTag::ERROR_VALUE. + std::vector<uint8_t> encoded = { + 0xd8, 0x5a, 0, 0, 0, 2, EncodeIndefiniteLengthMapStart(), + 0x61 /* major type 3 (string), additional info 1 (length 1) */ + }; + + EXPECT_FALSE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key"))); +} + +TEST(HasKeyInMapTest, AllowsDuplicateKeys) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key"), &encoded); + EncodeInt32(42, &encoded); + + EncodeString8(SpanFrom("key"), &encoded); + EncodeInt32(24, &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key"))); +} + +TEST(HasKeyInMapTest, AllowsNestedStructures) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key1"), &encoded); + // Start a nested map as value. + encoded.push_back(EncodeIndefiniteLengthMapStart()); + EncodeString8(SpanFrom("inner_key"), &encoded); + EncodeInt32(42, &encoded); + encoded.push_back(EncodeStop()); + + EncodeString8(SpanFrom("key2"), &encoded); + EncodeInt32(24, &encoded); + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + // We should find top-level keys even with nested structures. + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key1"))); + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key2"))); + + // We should NOT find keys that are inside nested structures (they are not + // top-level). + EXPECT_FALSE(HasKeyInMap(SpanFrom(encoded), SpanFrom("inner_key"))); +} + +TEST(HasKeyInMapTest, HandlesTruncation) { + std::vector<uint8_t> encoded; + EnvelopeEncoder envelope; + envelope.EncodeStart(&encoded); + encoded.push_back(EncodeIndefiniteLengthMapStart()); + + EncodeString8(SpanFrom("key1"), &encoded); + // Missing value here. + // Truncated before we can write key2. + + encoded.push_back(EncodeStop()); + envelope.EncodeStop(&encoded); + + // "key1" is found because we return early on seeing the key. + EXPECT_TRUE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key1"))); + + // "key2" is not found because it is not in the map (and map is truncated). + EXPECT_FALSE(HasKeyInMap(SpanFrom(encoded), SpanFrom("key2"))); +} + +TEST(HasKeyInMapTest, InvalidMessage) { + std::vector<uint8_t> msg = { + 0xd8, 0x5a, 0, 0, 0, 2, EncodeIndefiniteLengthMapStart(), 42}; + EXPECT_FALSE(HasKeyInMap(SpanFrom(msg), SpanFrom("key"))); +} + } // namespace cbor } // namespace crdtp diff --git a/deps/inspector_protocol/crdtp/dispatch.cc b/deps/inspector_protocol/crdtp/dispatch.cc index b36b91ad0e37..9f94cf2793c9 100644 --- a/deps/inspector_protocol/crdtp/dispatch.cc +++ b/deps/inspector_protocol/crdtp/dispatch.cc @@ -30,6 +30,14 @@ DispatchResponse DispatchResponse::FallThrough() { return result; } +// static +DispatchResponse DispatchResponse::FallThrough(std::string associated_data) { + DispatchResponse result; + result.code_ = DispatchCode::FALL_THROUGH; + result.message_ = std::move(associated_data); + return result; +} + // static DispatchResponse DispatchResponse::ParseError(std::string message) { DispatchResponse result; @@ -89,7 +97,12 @@ DispatchResponse DispatchResponse::SessionNotFound(std::string message) { // ============================================================================= // Dispatchable - a shallow parser for CBOR encoded DevTools messages // ============================================================================= -Dispatchable::Dispatchable(span<uint8_t> serialized) : serialized_(serialized) { +Dispatchable::Dispatchable(span<uint8_t> serialized, + std::string_view associated_data, + FallthroughCallback fallthrough_callback) + : serialized_(serialized), + associated_data_(associated_data), + fallthrough_callback_(std::move(fallthrough_callback)) { Status s = cbor::CheckCBORMessage(serialized); if (!s.ok()) { status_ = {Error::MESSAGE_MUST_BE_AN_OBJECT, s.pos}; @@ -264,6 +277,17 @@ bool Dispatchable::MaybeParseSessionId(cbor::CBORTokenizer* tokenizer) { return true; } +FallthroughCallback Dispatchable::TakeFallthroughCallback() { + FallthroughCallback result; + std::swap(result, fallthrough_callback_); + return result; +} + +void Dispatchable::DispatchFallThrough(const std::string& associated_data) { + assert(fallthrough_callback_); + TakeFallthroughCallback()(call_id_, method_, serialized_, associated_data); +} + namespace { class ProtocolError : public Serializable { public: @@ -424,13 +448,13 @@ void DomainDispatcher::Callback::dispose() { DomainDispatcher::Callback::Callback( std::unique_ptr<DomainDispatcher::WeakPtr> backend_impl, - int call_id, - span<uint8_t> method, - span<uint8_t> message) + Dispatchable& dispatchable) : backend_impl_(std::move(backend_impl)), - call_id_(call_id), - method_(method), - message_(message.begin(), message.end()) {} + call_id_(dispatchable.CallId()), + method_(dispatchable.Method()), + message_(dispatchable.Serialized().begin(), + dispatchable.Serialized().end()), + fallthrough_callback_(dispatchable.TakeFallthroughCallback()) {} void DomainDispatcher::Callback::sendIfActive( std::unique_ptr<Serializable> partialMessage, @@ -445,8 +469,11 @@ void DomainDispatcher::Callback::sendIfActive( void DomainDispatcher::Callback::fallThroughIfActive() { if (!backend_impl_ || !backend_impl_->get()) return; - backend_impl_->get()->channel()->FallThrough(call_id_, method_, - SpanFrom(message_)); + // Fallthrough callback may be retaining session which outlives backend. + // TODO(caseq): handle fall-through associated data for async callbacks. + fallthrough_callback_(call_id_, method_, SpanFrom(message_), + std::string_view()); + fallthrough_callback_ = nullptr; backend_impl_ = nullptr; } @@ -499,17 +526,6 @@ std::unique_ptr<DomainDispatcher::WeakPtr> DomainDispatcher::weakPtr() { // ============================================================================= // UberDispatcher - dispatches between domains (backends). // ============================================================================= -UberDispatcher::DispatchResult::DispatchResult(bool method_found, - std::function<void()> runnable) - : method_found_(method_found), runnable_(runnable) {} - -void UberDispatcher::DispatchResult::Run() { - if (!runnable_) - return; - runnable_(); - runnable_ = nullptr; -} - UberDispatcher::UberDispatcher(FrontendChannel* frontend_channel) : frontend_channel_(frontend_channel) { assert(frontend_channel); @@ -526,36 +542,34 @@ size_t DotIdx(span<uint8_t> method) { } } // namespace -UberDispatcher::DispatchResult UberDispatcher::Dispatch( - const Dispatchable& dispatchable) const { +void UberDispatcher::Dispatch(Dispatchable& dispatchable) { span<uint8_t> method = FindByFirst(redirects_, dispatchable.Method(), /*default_value=*/dispatchable.Method()); size_t dot_idx = DotIdx(method); if (dot_idx != kNotFound) { span<uint8_t> domain = method.subspan(0, dot_idx); span<uint8_t> command = method.subspan(dot_idx + 1); - DomainDispatcher* dispatcher = FindByFirst(dispatchers_, domain); - if (dispatcher) { - std::function<void(const Dispatchable&)> dispatched = - dispatcher->Dispatch(command); - if (dispatched) { - return DispatchResult( - true, [dispatchable, dispatched = std::move(dispatched)]() { - dispatched(dispatchable); - }); + if (DomainDispatcher* dispatcher = FindByFirst(dispatchers_, domain)) { + if (dispatcher->Dispatch(command, dispatchable)) { + return; } } } - return DispatchResult(false, [this, dispatchable]() { - frontend_channel_->SendProtocolResponse( - dispatchable.CallId(), - CreateErrorResponse(dispatchable.CallId(), - DispatchResponse::MethodNotFound( - "'" + - std::string(dispatchable.Method().begin(), - dispatchable.Method().end()) + - "' wasn't found"))); - }); + if (auto fallthrough = dispatchable.TakeFallthroughCallback()) { + fallthrough(dispatchable.CallId(), dispatchable.Method(), + dispatchable.Serialized(), std::string_view()); + } else { + SendMethodNotFound(dispatchable.CallId(), method); + } +} + +void UberDispatcher::SendMethodNotFound(int call_id, span<uint8_t> method) { + frontend_channel_->SendProtocolResponse( + call_id, + CreateErrorResponse(call_id, + DispatchResponse::MethodNotFound( + "'" + std::string(method.begin(), method.end()) + + "' wasn't found"))); } template <typename T> diff --git a/deps/inspector_protocol/crdtp/dispatch.h b/deps/inspector_protocol/crdtp/dispatch.h index 8da8255c6fe8..4f5d33990cf8 100644 --- a/deps/inspector_protocol/crdtp/dispatch.h +++ b/deps/inspector_protocol/crdtp/dispatch.h @@ -9,7 +9,9 @@ #include <cstdint> #include <functional> #include <string> +#include <string_view> #include <unordered_set> + #include "export.h" #include "serializable.h" #include "span.h" @@ -55,6 +57,7 @@ class CRDTP_EXPORT DispatchResponse { static DispatchResponse Success(); static DispatchResponse FallThrough(); + static DispatchResponse FallThrough(std::string associated_data); // Indicates that a message could not be parsed. E.g., malformed JSON. static DispatchResponse ParseError(std::string message); @@ -84,9 +87,20 @@ class CRDTP_EXPORT DispatchResponse { private: DispatchResponse() = default; DispatchCode code_; + // For error responses, a message describing the error. + // For fall-through responses, fall-through associated message. std::string message_; }; +// This callback is invoked if the command was not dispatched due to handler +// not being found. The caller has an opportunity to dispatch the command +// to a different layer then. +using FallthroughCallback = + std::function<void(int call_id, + span<uint8_t> method, + span<uint8_t> serialized_message, + std::string_view associated_data)>; + // ============================================================================= // Dispatchable - a shallow parser for CBOR encoded DevTools messages // ============================================================================= @@ -100,7 +114,16 @@ class CRDTP_EXPORT Dispatchable { // |Params()| can be used to access, the extracted contents. Otherwise, // |ok()| will yield |false|, and |DispatchError()| can be // used to send a response or notification to the client. - explicit Dispatchable(span<uint8_t> serialized); + // |associated_data| would be passed as is to handler methods that were + // configured as those willing to receive it. + // |fallthrough_callback|, if non-empty, will be invoked by the dispatcher + // if no handler was found or if the handler chose to fall through, + // and can be used to pass command to be handled elsewhere. + // Note that in case of an async command, fallthrough_callback may be invoked + // asynchronously. + Dispatchable(span<uint8_t> serialized, + std::string_view associated_data, + FallthroughCallback fallthrough_callback); // The serialized message that we just parsed. span<uint8_t> Serialized() const { return serialized_; } @@ -127,6 +150,17 @@ class CRDTP_EXPORT Dispatchable { // not parse into this; it only provides access to its raw contents here. span<uint8_t> Params() const { return params_; } + std::string_view AssociatedData() const { return associated_data_; } + + // Takes the fallthrough callback, if any. + FallthroughCallback TakeFallthroughCallback(); + // Takes the fallthrough callback and dispatches it with stored + // call/method/message. The associated_data is passed through to + // the other handling layer (not to be confused with the member + // associated_data which is the one to be passed to handlers + // during current dispatch). + void DispatchFallThrough(const std::string& associated_data); + private: bool MaybeParseProperty(cbor::CBORTokenizer* tokenizer); bool MaybeParseCallId(cbor::CBORTokenizer* tokenizer); @@ -144,6 +178,8 @@ class CRDTP_EXPORT Dispatchable { bool params_seen_ = false; span<uint8_t> params_; span<uint8_t> session_id_; + std::string_view associated_data_; + FallthroughCallback fallthrough_callback_; }; // ============================================================================= @@ -197,10 +233,7 @@ class CRDTP_EXPORT DomainDispatcher { protected: // |method| must point at static storage (a C++ string literal in practice). - Callback(std::unique_ptr<WeakPtr> backend_impl, - int call_id, - span<uint8_t> method, - span<uint8_t> message); + Callback(std::unique_ptr<WeakPtr> backend_impl, Dispatchable& dispatchable); void sendIfActive(std::unique_ptr<Serializable> partialMessage, const DispatchResponse& response); @@ -214,20 +247,19 @@ class CRDTP_EXPORT DomainDispatcher { // storage for |method| is the binary of the running process. span<uint8_t> method_; std::vector<uint8_t> message_; + FallthroughCallback fallthrough_callback_; }; explicit DomainDispatcher(FrontendChannel*); virtual ~DomainDispatcher(); // Given a |command_name| without domain qualification, looks up the - // corresponding method. If the method is not found, returns nullptr. - // Otherwise, Returns a closure that will parse the provided - // Dispatchable.params() to a protocol object and execute the - // apprpropriate method. If the parsing fails it will issue an - // error response on the frontend channel, otherwise it will execute the - // command. - virtual std::function<void(const Dispatchable&)> Dispatch( - span<uint8_t> command_name) = 0; + // corresponding method and attempeds to parse and execute it. + // If the command is not found, returns false. Otherwise and possible + // result, whether a response or error, is send using underlying + // frontend_channel_. + virtual bool Dispatch(span<uint8_t> command_name, + Dispatchable& dispatchable) = 0; // Sends a response to the client via the channel. void sendResponse(int call_id, @@ -253,25 +285,6 @@ class CRDTP_EXPORT DomainDispatcher { // ============================================================================= class CRDTP_EXPORT UberDispatcher { public: - // Return type for ::Dispatch. - class CRDTP_EXPORT DispatchResult { - public: - DispatchResult(bool method_found, std::function<void()> runnable); - - // Indicates whether the method was found, that is, it could be dispatched - // to a backend registered with this dispatcher. - bool MethodFound() const { return method_found_; } - - // Runs the dispatched result. This will send the appropriate error - // responses if the method wasn't found or if something went wrong during - // parameter parsing. - void Run(); - - private: - bool method_found_; - std::function<void()> runnable_; - }; - // |frontend_hannel| can't be nullptr. explicit UberDispatcher(FrontendChannel* frontend_channel); virtual ~UberDispatcher(); @@ -280,7 +293,9 @@ class CRDTP_EXPORT UberDispatcher { // handlers registered with this uber dispatcher. Also see |DispatchResult|. // |dispatchable.ok()| must hold - callers must check this separately and // deal with errors. - DispatchResult Dispatch(const Dispatchable& dispatchable) const; + void Dispatch(Dispatchable& dispatchable); + + void SendMethodNotFound(int call_id, span<uint8_t> method); // Invoked from generated code for wiring domain backends; that is, // connecting domain handlers to an uber dispatcher. @@ -308,6 +323,7 @@ class CRDTP_EXPORT UberDispatcher { std::vector<std::pair<span<uint8_t>, std::unique_ptr<DomainDispatcher>>> dispatchers_; }; + } // namespace crdtp #endif // CRDTP_DISPATCH_H_ diff --git a/deps/inspector_protocol/crdtp/dispatch_test.cc b/deps/inspector_protocol/crdtp/dispatch_test.cc index c7290f929613..e21b9bb309df 100644 --- a/deps/inspector_protocol/crdtp/dispatch_test.cc +++ b/deps/inspector_protocol/crdtp/dispatch_test.cc @@ -55,13 +55,21 @@ TEST(DispatchResponseTest, FallThrough) { EXPECT_EQ(DispatchCode::FALL_THROUGH, error.Code()); } +TEST(DispatchResponseTest, FallThroughWithAssociatedData) { + DispatchResponse fall_through = DispatchResponse::FallThrough("some details"); + EXPECT_FALSE(fall_through.IsSuccess()); + EXPECT_TRUE(fall_through.IsFallThrough()); + EXPECT_EQ(DispatchCode::FALL_THROUGH, fall_through.Code()); + EXPECT_EQ("some details", fall_through.Message()); +} + // ============================================================================= // Dispatchable - a shallow parser for CBOR encoded DevTools messages // ============================================================================= TEST(DispatchableTest, MessageMustBeAnObject) { // Provide no input whatsoever. span<uint8_t> empty_span; - Dispatchable empty(empty_span); + Dispatchable empty(empty_span, std::string_view(), nullptr); EXPECT_FALSE(empty.ok()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, empty.DispatchError().Code()); EXPECT_EQ("Message must be an object", empty.DispatchError().Message()); @@ -71,7 +79,7 @@ TEST(DispatchableTest, MessageMustHaveIntegerIdProperty) { // Construct an empty map inside of an envelope. std::vector<uint8_t> cbor; ASSERT_TRUE(json::ConvertJSONToCBOR(SpanFrom("{}"), &cbor).ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_FALSE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -84,7 +92,7 @@ TEST(DispatchableTest, MessageMustHaveIntegerIdProperty_IncorrectType) { std::vector<uint8_t> cbor; ASSERT_TRUE( json::ConvertJSONToCBOR(SpanFrom("{\"id\":\"foo\"}"), &cbor).ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_FALSE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -96,7 +104,7 @@ TEST(DispatchableTest, MessageMustHaveStringMethodProperty) { // This time we set the id property, but not the method property. std::vector<uint8_t> cbor; ASSERT_TRUE(json::ConvertJSONToCBOR(SpanFrom("{\"id\":42}"), &cbor).ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -110,7 +118,7 @@ TEST(DispatchableTest, MessageMustHaveStringMethodProperty_IncorrectType) { ASSERT_TRUE( json::ConvertJSONToCBOR(SpanFrom("{\"id\":42,\"method\":42}"), &cbor) .ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -128,7 +136,7 @@ TEST(DispatchableTest, MessageMayHaveStringSessionIdProperty) { "}"), &cbor) .ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -145,7 +153,7 @@ TEST(DispatchableTest, MessageMayHaveObjectParamsProperty) { "}"), &cbor) .ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -159,7 +167,7 @@ TEST(DispatchableTest, MessageWithUnknownProperty) { ASSERT_TRUE( json::ConvertJSONToCBOR(SpanFrom("{\"id\":42,\"unknown\":42}"), &cbor) .ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(DispatchCode::INVALID_REQUEST, dispatchable.DispatchError().Code()); @@ -177,7 +185,7 @@ TEST(DispatchableTest, DuplicateMapKey) { SCOPED_TRACE("json = " + json); std::vector<uint8_t> cbor; ASSERT_TRUE(json::ConvertJSONToCBOR(SpanFrom(json), &cbor).ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_EQ(DispatchCode::PARSE_ERROR, dispatchable.DispatchError().Code()); EXPECT_THAT(dispatchable.DispatchError().Message(), @@ -195,7 +203,7 @@ TEST(DispatchableTest, ValidMessageParsesOK_NoParams) { SCOPED_TRACE("json = " + json); std::vector<uint8_t> cbor; ASSERT_TRUE(json::ConvertJSONToCBOR(SpanFrom(json), &cbor).ok()); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_TRUE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(42, dispatchable.CallId()); @@ -228,7 +236,7 @@ TEST(DispatchableTest, ValidMessageParsesOK_WithParams) { cbor::EncodeString8(SpanFrom("f421ssvaz4"), &cbor); cbor.push_back(cbor::EncodeStop()); envelope.EncodeStop(&cbor); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), "associated data", nullptr); EXPECT_TRUE(dispatchable.ok()); EXPECT_TRUE(dispatchable.HasCallId()); EXPECT_EQ(42, dispatchable.CallId()); @@ -242,6 +250,7 @@ TEST(DispatchableTest, ValidMessageParsesOK_WithParams) { ASSERT_EQ(cbor::CBORTokenTag::STRING8, params_tokenizer.TokenTag()); EXPECT_EQ("params payload", std::string(params_tokenizer.GetString8().begin(), params_tokenizer.GetString8().end())); + EXPECT_EQ(dispatchable.AssociatedData(), "associated data"); } TEST(DispatchableTest, FaultyCBORTrailingJunk) { @@ -266,7 +275,7 @@ TEST(DispatchableTest, FaultyCBORTrailingJunk) { cbor.push_back('a'); cbor.push_back('i'); cbor.push_back('l'); - Dispatchable dispatchable(SpanFrom(cbor)); + Dispatchable dispatchable(SpanFrom(cbor), std::string_view(), nullptr); EXPECT_FALSE(dispatchable.ok()); EXPECT_EQ(DispatchCode::PARSE_ERROR, dispatchable.DispatchError().Code()); EXPECT_EQ(57u, trailing_junk_pos); @@ -341,9 +350,7 @@ class TestChannel : public FrontendChannel { cbor_ = message->Serialize(); } - void FallThrough(int call_id, - span<uint8_t> method, - span<uint8_t> message) override {} + void FlushProtocolNotifications() override {} @@ -359,11 +366,9 @@ TEST(UberDispatcherTest, MethodNotFound) { std::vector<uint8_t> message; json::ConvertJSONToCBOR(SpanFrom("{\"id\":42,\"method\":\"Foo.bar\"}"), &message); - Dispatchable dispatchable(SpanFrom(message)); + Dispatchable dispatchable(SpanFrom(message), std::string_view(), nullptr); ASSERT_TRUE(dispatchable.ok()); - UberDispatcher::DispatchResult dispatched = dispatcher.Dispatch(dispatchable); - EXPECT_FALSE(dispatched.MethodFound()); - dispatched.Run(); + dispatcher.Dispatch(dispatchable); EXPECT_EQ( "{\"id\":42,\"error\":" "{\"code\":-32601,\"message\":\"'Foo.bar' wasn't found\"}}", @@ -376,13 +381,12 @@ class TestDomain : public DomainDispatcher { public: explicit TestDomain(FrontendChannel* channel) : DomainDispatcher(channel) {} - std::function<void(const Dispatchable&)> Dispatch( - span<uint8_t> command_name) override { + bool Dispatch(span<uint8_t> command_name, + Dispatchable& dispatchable) override { dispatched_commands_.push_back( std::string(command_name.begin(), command_name.end())); - return [this](const Dispatchable& dispatchable) { - executed_commands_.push_back(dispatchable.CallId()); - }; + executed_commands_.push_back(dispatchable.CallId()); + return true; } // Command names of the dispatched commands. @@ -418,23 +422,17 @@ TEST(UberDispatcherTest, DispatchingToDomainWithRedirects) { std::vector<uint8_t> message; json::ConvertJSONToCBOR(SpanFrom("{\"id\":42,\"method\":\"Foo.execute\"}"), &message); - Dispatchable dispatchable(SpanFrom(message)); + Dispatchable dispatchable(SpanFrom(message), std::string_view(), nullptr); ASSERT_TRUE(dispatchable.ok()); - UberDispatcher::DispatchResult dispatched = - dispatcher.Dispatch(dispatchable); - EXPECT_TRUE(dispatched.MethodFound()); - dispatched.Run(); + dispatcher.Dispatch(dispatchable); } { std::vector<uint8_t> message; json::ConvertJSONToCBOR(SpanFrom("{\"id\":43,\"method\":\"Foo.redirect\"}"), &message); - Dispatchable dispatchable(SpanFrom(message)); + Dispatchable dispatchable(SpanFrom(message), std::string_view(), nullptr); ASSERT_TRUE(dispatchable.ok()); - UberDispatcher::DispatchResult dispatched = - dispatcher.Dispatch(dispatchable); - EXPECT_TRUE(dispatched.MethodFound()); - dispatched.Run(); + dispatcher.Dispatch(dispatchable); } EXPECT_THAT(foo->DispatchedCommands(), testing::ElementsAre("execute")); EXPECT_THAT(foo->ExecutedCommands(), testing::ElementsAre(42)); diff --git a/deps/inspector_protocol/crdtp/frontend_channel.h b/deps/inspector_protocol/crdtp/frontend_channel.h index 652c65219d4d..fddb52e51e35 100644 --- a/deps/inspector_protocol/crdtp/frontend_channel.h +++ b/deps/inspector_protocol/crdtp/frontend_channel.h @@ -30,14 +30,6 @@ class CRDTP_EXPORT FrontendChannel { virtual void SendProtocolNotification( std::unique_ptr<Serializable> message) = 0; - // FallThrough indicates that |message| should be handled in another layer. - // Usually this means the layer responding to the message didn't handle it, - // but in some cases messages are handled by multiple layers (e.g. both - // the embedder and the content layer in Chromium). - virtual void FallThrough(int call_id, - span<uint8_t> method, - span<uint8_t> message) = 0; - // Session implementations may queue notifications for performance or // other considerations; this is a hook for domain handlers to manually flush. virtual void FlushProtocolNotifications() = 0; diff --git a/deps/inspector_protocol/inspector_protocol.gni b/deps/inspector_protocol/inspector_protocol.gni index 6b278c9fa8ef..b9948c08a047 100644 --- a/deps/inspector_protocol/inspector_protocol.gni +++ b/deps/inspector_protocol/inspector_protocol.gni @@ -144,8 +144,8 @@ template("inspector_protocol_concatenate") { inputs += invoker.inputs args += rebase_path(invoker.inputs, root_build_dir) - outputs += [invoker.output_file] - args += [rebase_path(invoker.output_file, root_build_dir)] + outputs += [ invoker.output_file ] + args += [ rebase_path(invoker.output_file, root_build_dir) ] forward_variables_from(invoker, [ diff --git a/deps/inspector_protocol/lib/Values_cpp.template b/deps/inspector_protocol/lib/Values_cpp.template index abeee79e5c3a..2d34fb3de4fd 100644 --- a/deps/inspector_protocol/lib/Values_cpp.template +++ b/deps/inspector_protocol/lib/Values_cpp.template @@ -461,7 +461,7 @@ double DictionaryValue::doubleProperty(const String& name, double defaultValue) void DictionaryValue::remove(const String& name) { m_data.erase(name); - m_order.erase(std::remove(m_order.begin(), m_order.end(), name), m_order.end()); + std::erase(m_order, name); } void DictionaryValue::AppendSerialized(std::vector<uint8_t>* bytes) const { diff --git a/deps/inspector_protocol/pdl.py b/deps/inspector_protocol/pdl.py index 5b53291fd5b3..eb8f24745315 100644 --- a/deps/inspector_protocol/pdl.py +++ b/deps/inspector_protocol/pdl.py @@ -89,15 +89,16 @@ def parse(data, file_name, map_binary_to_string, source_set): protocol['domains'].append(domain) continue - match = re.compile( - r'^include (.*)').match(line) + match = re.compile(r'^include (.*)').match(line) if match: included_filename = match.group(1) if os.path.isabs(included_filename): raise Exception("Only relative paths are supported in includes") - resolved_path = os.path.normpath(os.path.join(os.path.dirname(file_name), included_filename)) + resolved_path = os.path.normpath( + os.path.join(os.path.dirname(file_name), included_filename)) with open(resolved_path, 'r') as file: - included_data = parse(file.read(), resolved_path, map_binary_to_string, source_set) + included_data = parse(file.read(), resolved_path, map_binary_to_string, + source_set) protocol['domains'].extend(included_data['domains']) continue diff --git a/deps/inspector_protocol/templates/TypeBuilder_cpp.template b/deps/inspector_protocol/templates/TypeBuilder_cpp.template index a38182c311ae..2f70a9d12997 100644 --- a/deps/inspector_protocol/templates/TypeBuilder_cpp.template +++ b/deps/inspector_protocol/templates/TypeBuilder_cpp.template @@ -18,6 +18,7 @@ namespace {{namespace}} { namespace {{domain.domain}} { using {{config.crdtp.namespace}}::DeserializerState; +using {{config.crdtp.namespace}}::FallthroughCallback; using {{config.crdtp.namespace}}::ProtocolTypeTraits; // ------------- Enum values from types. @@ -155,14 +156,14 @@ public: , m_backend(backend) {} ~DomainDispatcherImpl() override { } - using CallHandler = void (DomainDispatcherImpl::*)(const {{config.crdtp.namespace}}::Dispatchable& dispatchable); + using CallHandler = void (DomainDispatcherImpl::*)({{config.crdtp.namespace}}::Dispatchable& dispatchable); - std::function<void(const {{config.crdtp.namespace}}::Dispatchable&)> Dispatch({{config.crdtp.namespace}}::span<uint8_t> command_name) override; + bool Dispatch({{config.crdtp.namespace}}::span<uint8_t> command_name, {{config.crdtp.namespace}}::Dispatchable& dispatchable) override; {% for command in domain.commands %} {% if "redirect" in command %}{% continue %}{% endif %} {% if not protocol.generate_command(domain.domain, command.name) %}{% continue %}{% endif %} - void {{command.name}}(const {{config.crdtp.namespace}}::Dispatchable& dispatchable); + void {{command.name}}({{config.crdtp.namespace}}::Dispatchable& dispatchable); {% endfor %} protected: Backend* m_backend; @@ -191,13 +192,12 @@ DomainDispatcherImpl::CallHandler CommandByName({{config.crdtp.namespace}}::span } } // namespace -std::function<void(const {{config.crdtp.namespace}}::Dispatchable&)> DomainDispatcherImpl::Dispatch({{config.crdtp.namespace}}::span<uint8_t> command_name) { +bool DomainDispatcherImpl::Dispatch({{config.crdtp.namespace}}::span<uint8_t> command_name, {{config.crdtp.namespace}}::Dispatchable& dispatchable) { CallHandler handler = CommandByName(command_name); - if (!handler) return nullptr; + if (!handler) return false; - return [this, handler](const {{config.crdtp.namespace}}::Dispatchable& dispatchable) { - (this->*handler)(dispatchable); - }; + (this->*handler)(dispatchable); + return true; } {% for command in domain.commands %} @@ -208,9 +208,8 @@ std::function<void(const {{config.crdtp.namespace}}::Dispatchable&)> DomainDispa class {{command_name_title}}CallbackImpl : public Backend::{{command_name_title}}Callback, public DomainDispatcher::Callback { public: - {{command_name_title}}CallbackImpl(std::unique_ptr<DomainDispatcher::WeakPtr> backendImpl, int callId, {{config.crdtp.namespace}}::span<uint8_t> message) - : DomainDispatcher::Callback(std::move(backendImpl), callId, -{{config.crdtp.namespace}}::SpanFrom("{{domain.domain}}.{{command.name}}"), message) { } + {{command_name_title}}CallbackImpl(std::unique_ptr<DomainDispatcher::WeakPtr> backendImpl, {{config.crdtp.namespace}}::Dispatchable& dispatchable) + : DomainDispatcher::Callback(std::move(backendImpl), dispatchable) { } void sendSuccess( {%- for parameter in command.returns -%} @@ -270,7 +269,7 @@ CRDTP_END_DESERIALIZER() } // namespace -void DomainDispatcherImpl::{{command.name}}(const {{config.crdtp.namespace}}::Dispatchable& dispatchable) +void DomainDispatcherImpl::{{command.name}}({{config.crdtp.namespace}}::Dispatchable& dispatchable) { // Prepare input parameters. {% if "parameters" in command %} @@ -304,6 +303,13 @@ void DomainDispatcherImpl::{{command.name}}(const {{config.crdtp.namespace}}::Di {{protocol.resolve_type(parameter).to_pass_type % ("params." + parameter.name)}} {%- endif -%} {%- endfor %} + + {%- if protocol.should_pass_associated_data(domain.domain, command.name) -%} + {%- if command.parameters -%}, {% endif -%} + {{config.crdtp.namespace}}::ConvertAssociatedData<std::remove_cvref_t<{{protocol.type_definition(domain.domain + ".string").pass_type}}>>( + dispatchable.AssociatedData()) + {%- endif -%} + {%- if "returns" in command %} {%- for parameter in command.returns -%} {%- if not loop.first or command.parameters -%}, {% endif -%} @@ -311,7 +317,7 @@ void DomainDispatcherImpl::{{command.name}}(const {{config.crdtp.namespace}}::Di {%- endfor %} {% endif %}); if (response.IsFallThrough()) { - channel()->FallThrough(dispatchable.CallId(), {{config.crdtp.namespace}}::SpanFrom("{{domain.domain}}.{{command.name}}"), dispatchable.Serialized()); + dispatchable.DispatchFallThrough(response.Message()); return; } {% if "returns" in command %} @@ -344,7 +350,7 @@ void DomainDispatcherImpl::{{command.name}}(const {{config.crdtp.namespace}}::Di {%- endif -%} {%- endfor -%} {%- if command.parameters -%}, {% endif -%} - std::make_unique<{{command_name_title}}CallbackImpl>(weakPtr(), dispatchable.CallId(), dispatchable.Serialized())); + std::make_unique<{{command_name_title}}CallbackImpl>(weakPtr(), dispatchable)); {% endif %} } {% endfor %} diff --git a/deps/inspector_protocol/templates/TypeBuilder_h.template b/deps/inspector_protocol/templates/TypeBuilder_h.template index 33c5d1af5353..38b1fcf6da22 100644 --- a/deps/inspector_protocol/templates/TypeBuilder_h.template +++ b/deps/inspector_protocol/templates/TypeBuilder_h.template @@ -256,8 +256,12 @@ public: {{protocol.resolve_type(parameter).pass_type}} in_{{parameter.name}} {%- endif -%} {%- endfor -%} - {%- if protocol.is_async_command(domain.domain, command.name) -%} + {%- if protocol.should_pass_associated_data(domain.domain, command.name) -%} {%- if command.parameters -%}, {% endif -%} + {{protocol.type_definition(domain.domain + ".string").pass_type}} associated_data + {%- endif -%} + {%- if protocol.is_async_command(domain.domain, command.name) -%} + {%- if command.parameters or protocol.should_pass_associated_data(domain.domain, command.name) -%}, {% endif -%} std::unique_ptr<{{command.name | to_title_case}}Callback> callback {%- else -%} {%- for parameter in command.returns -%} diff --git a/deps/libffi/ChangeLog b/deps/libffi/ChangeLog index f64d5d5c46ac..133b18134c57 100644 --- a/deps/libffi/ChangeLog +++ b/deps/libffi/ChangeLog @@ -1,3 +1,2049 @@ +commit de7afe7aa9e8ab7ac36429428a7222caae1e7988 +Merge: 63cfe02c 8d6f5bf5 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 08:15:07 2026 -0500 + + Merge pull request #1082 from libffi/release/3.8.1 + + Release 3.8.1 + +commit 8d6f5bf587f642c53b62bde916d7ec60da925cf3 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 08:10:58 2026 -0500 + + Release 3.8.1 + + Bump the version from 3.8.0 to 3.8.1 and finalize the changelog: + + * configure.ac: AC_INIT 3.8.0 -> 3.8.1 (propagates to FFI_VERSION, + libffi.pc, and the manual's @value{VERSION}). + * libtool-version: 13:0:5 -> 13:1:5. The source changed but no exported + interface was added, removed, or changed since 3.8.0, so only revision + is incremented. + * doc/version.texi, README.md: set the version and the release date. + + Also fix three latent release-tooling bugs that "make distcheck" exposes + (plain "make dist" hides them because it does not make the source tree + read-only or verify a clean distclean): + + * Makefile.am dist-hook rewrote $(distdir)/README.md, which automake had + already copied read-only, so the redirect failed with "Permission + denied". Remove it first. + * configure.ac: the X86_64 unwind-section test linked conftest without + -o, leaving an a.out that distcleancheck flagged. Link to a conftest + file and clean up. + * Makefile.am: add the generated libffi.map (and libffi.map-sun) to + DISTCLEANFILES so distclean removes them. + + make distcheck now passes end to end: builds from the tarball, runs the + full testsuite, installs, uninstalls, and distcleans with nothing left. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 63cfe02cc95a0ad97a38586bb5aaf87fcc7e69b4 +Merge: fd2cdac5 f3dd79a0 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 07:34:25 2026 -0500 + + Merge pull request #1081 from libffi/testsuite/dist-missing-tests + + testsuite: add new tests to EXTRA_DIST so they ship in the release + +commit f3dd79a0662142fca361835ebabea06727c634eb +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 07:22:22 2026 -0500 + + testsuite: add the new tests to EXTRA_DIST so they ship in the release + + The dejagnu .exp drivers glob *.c at run time, so these tests ran in-tree, + but testsuite/Makefile.am's EXTRA_DIST is a hand-maintained list and `make + dist` ships only what it names. The tests added this cycle were missing, so + a `make check` from the release tarball would silently skip them -- dropping + the regression coverage for several of the security fixes: + + libffi.call/closure_raw.c (GHSA-w6j9-w53f-2857) + libffi.closures/closure_int128.c (GHSA-wf8m-qr3x-cch4) + libffi.closures/closure_mmap_failure.c (#1055) + libffi.closures/closure_trampoline_table.c (GHSA-23hx-9rxv-9qfp) + libffi.vector/vector_unsupported_abi.c (GHSA-5pc3-hr6f-q3mm) + + Also add libffi.configure/libdir.sh (the --libdir test run from CI) so it + ships too. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit fd2cdac5e82b6c357775ff968ff58149f8f44245 +Merge: 297a80c4 852244d3 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 07:19:30 2026 -0500 + + Merge pull request #1080 from libffi/readme/tighten-tbd + + README: tighten the TBD changelog and fold in the security fixes + +commit 852244d378e908d846439a7a02d2b33c8b00a965 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 07:18:18 2026 -0500 + + README: tighten the TBD changelog and fold in the security fixes + + Group the pending changes by architecture and theme instead of a flat + list plus a separate "Security fixes" block, so related entries (including + the six advisories) sit together. Drop the CWE codes and the long + mechanism descriptions -- the referenced issues and advisories carry that + detail -- while keeping every #issue and GHSA reference. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 297a80c4b02ef00010e985675c4c34dbc7bb2181 +Merge: 21a49087 46203c53 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 07:12:43 2026 -0500 + + Merge pull request #1079 from libffi/ci/green-emscripten-pytest + + ci(emscripten): get the browser test job green (pytest 9.x + closure_mmap_failure) + +commit 46203c534e0a5d57729d838cc59d42103dd7cf62 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 06:21:33 2026 -0500 + + testsuite: guard closure_mmap_failure for non-glibc harnesses + + The Emscripten browser harness (testsuite/emscripten/build-tests.sh) compiles + every testcase and ignores the dg-do "target x86_64-*-linux-gnu*" directive. + closure_mmap_failure interposes mmap via dlsym(RTLD_NEXT, "mmap"), which aborts + on wasm: + + Aborted(Assertion failed: Tried to dlsym() from an unopened handle: -1) + + (188 passed, 1 failed in the browser run.) Guard the body on __GLIBC__ so it + is a no-op wherever the RTLD_NEXT mmap-interposition technique isn't available; + ffitest.h pulls in <stdlib.h>, so __GLIBC__ is defined on the x86_64-linux-gnu + dejagnu runs that actually exercise this test, leaving them unchanged. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 4abb340542b4a7f6af328bf5e8c16d2bd631b30e +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 06:08:19 2026 -0500 + + ci(emscripten): bump pytest-pyodide 0.59.2 -> 0.59.4 for pytest 9.x + + The browser `test` job crashed during pytest collection: + + INTERNALERROR> AttributeError: 'FixtureManager' object has no + attribute '_arg2fixturedefs' + + pytest-pyodide 0.59.2's set_runtime_fixture_params() reads the private + pytest internal `_fixturemanager._arg2fixturedefs`, which pytest removed. + The workflow installs an unpinned pytest (currently 9.2.0), so collection + aborted before any test ran. (It was masked until now because the build + job failed first; fixing closure_raw.c let the test job finally run.) + + 0.59.4 handles this with a version shim (uses getfixturedefs() on + pytest >= 9.2), so just bump the pin. Pinning pytest down instead is a + dead end: pytest-asyncio 1.5.0 (a pytest-pyodide dep) requires pytest>=8.4, + which already lacks _arg2fixturedefs. + + Verified locally that collection of testsuite/emscripten/test_libffi.py + succeeds with pytest 9.2.0 + pytest-pyodide 0.59.4 (the crash is gone); + the browser run itself is validated by CI. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 21a490876ea8046f544fbbf93a594ccf63685e9a +Merge: 997aee20 6aff44d2 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 05:41:38 2026 -0500 + + Merge pull request #1078 from libffi/ci/green-emscripten-raw + + testsuite: guard closure_raw on !FFI_NO_RAW_API (fix Emscripten CI) + +commit 6aff44d25cc7ba8ed4d3a1f64a7e931544545a41 +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 05:18:38 2026 -0500 + + testsuite: guard closure_raw on !FFI_NO_RAW_API (fix Emscripten CI) + + The Emscripten build configures libffi with --disable-raw-api, which sets + FFI_NO_RAW_API and compiles raw_api.c (and the native raw entries) to + nothing -- so ffi_prep_raw_closure_loc is absent from the wasm library. + closure_raw.c referenced it unconditionally under only #if FFI_CLOSURES, so + every wasm target failed to link: + + wasm-ld: error: undefined symbol: ffi_prep_raw_closure_loc + + Match raw_api.c's own guard: compile the raw-closure test only when + FFI_CLOSURES && !FFI_NO_RAW_API, falling back to the no-op main otherwise. + ffitest.h already includes fficonfig.h, so FFI_NO_RAW_API is visible to the + test. No change on targets where the raw API is enabled. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 997aee20b30d93c4526473d66fec6a37168f550a +Merge: 4098fd38 7632e27b +Author: Anthony Green <green@moxielogic.com> +Date: Sat Nov 14 00:41:50 2026 -0500 + + Merge pull request #1077 from libffi/ci/green-android-macos + + ci: xfail x86_64 Android ld-struct return; drop dead macos-14 runner + +commit 7632e27b5894c78b0511a4aef8ef0cf0c325880c +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 22:06:45 2026 -0500 + + ci: xfail x86_64 Android ld-struct return; drop dead macos-14 runner + + Two independent CI-green fixes: + + testsuite: cls_struct_ld_return.c fails only on x86_64-pc-linux-android + (NDK clang, static, run natively), while x86_64-pc-linux-gnu passes the + identical test. The generic x86-64 struct-return path is therefore sound; + the Android-specific divergence (possibly a binary128 vs 80-bit long double + difference feeding classify_argument) is unconfirmed and can't be reproduced + without the NDK. xfail it on x86_64-*-linux-android* and track the real fix + in libffi #1076 rather than guess at ffi64.c and risk the cases that pass. + + build.yml: the macos-14 runners (both compiler jobs and the Rosetta job that + pins macos-14) have been lost on every recent run -- scheduled, then killed + ~2 min in with no steps, conclusion "cancelled" -- while macos-15 runs fine. + Drop macos-14 from the matrix and move the Rosetta x86_64 job to macos-15, + which is also Apple Silicon and supports Rosetta 2, so x86_64 macOS coverage + is preserved. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 4098fd38a167f492e0f9c774298f6754c8ec20d1 +Merge: 89a976d5 24c817af +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 19:38:54 2026 -0500 + + Merge pull request #1075 from libffi/ci/green-android-win32 + + CI: make dist PDF best-effort (Android) and xfail closure_raw on i686 MSVC + +commit 24c817af9aac5e1fb286ce7219d2e08ffd38c113 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 19:38:36 2026 -0500 + + testsuite: xfail closure_raw on i686 MSVC (libffi #1074) + + The raw-API closure test passes everywhere except 32-bit MSVC + (i686-pc-cygwin), where it compiles but fails at execution in the i386 + native raw-closure path. It passes on Windows 64-bit gcc/clang and all + Linux/macOS targets, and the GHSA-w6j9 change there is static-trampoline + gated (off on Windows), so this is a pre-existing gap the new test + exposed. xfail it on i686-pc-cygwin, tracked by issue #1074. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 9967918609a581dad639b388e03b6d5679e7340b +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 19:38:36 2026 -0500 + + build: make the dist-hook PDF manual truly best-effort + + The previous guard checked for texi2pdf, but texi2pdf ships with texinfo + even when no TeX engine is installed (e.g. the Android CI container), so + 'make pdf' still ran texi2dvi --pdf and failed 'make dist'. Attempt the + PDF build and copy, and if any part fails, skip it with a message; the + .info manual is still shipped and release builds (with texlive) still get + the PDF. Verified: 'make dist' with the TeX engine forced to fail still + succeeds. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 89a976d5b37fb16fc7881d5a0b9d4138418bd221 +Merge: 48d7a47e d9208dee +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 19:06:30 2026 -0500 + + Merge pull request #1073 from libffi/ci/fix-ci-regressions + + CI: fix regressions from new tests + complete the dist-hook docs guard + +commit d9208dee3bd27888e23512327820c1e869413cb4 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 18:19:50 2026 -0500 + + testsuite: xfail more mips N64 complex/fp-return tests (libffi #1071) + + The full matrix surfaced two more failures in the same mips N64 ABI + cluster: complex_regs_double fails on little-endian (it passes on + big-endian hardware), and cls_struct_ld_return (long-double struct return) + fails at -O2. xfail both on mips64*-*-* alongside the others, tracked by + issue #1071. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit ecb977826207ce0ebf99272c2be2d34da8216dfd +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 18:19:50 2026 -0500 + + build: only build the PDF manual in dist-hook when texi2pdf is present + + The dist-hook BUILD_DOCS guard still ran 'make pdf' whenever makeinfo was + available, so environments with texinfo but no TeX (e.g. the Android CI + container) failed 'make dist' at the PDF step. Build and copy the PDF + only when texi2pdf exists; the .info manual is still shipped, and release + builds (which install texlive) still get the PDF. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit b81760d079fb5ba84c70965eaf6b82de2d8a4fe4 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 18:19:50 2026 -0500 + + testsuite: fix closure_raw user_data cast for LLP64 (Windows) + + closure_raw.c read its void* user_data back as (long), which truncates a + 64-bit pointer on LLP64 (Windows x64), tripping -Wall as an excess error + and failing the test's compile on the mingw/MSVC CI jobs. Use intptr_t. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 48d7a47ef94a9b229f7591b6aadd31542556b3f5 +Merge: 693dcbac e431830b +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 16:15:36 2026 -0500 + + Merge pull request #1072 from libffi/readme-changelog-consolidate + + README: complete and consolidate the TBD changelog + +commit 693dcbac9f1eb63c68e13fbdec767201b8ec1ff5 +Merge: af169894 1436c4a9 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 16:15:31 2026 -0500 + + Merge pull request #1070 from libffi/ci/dist-docs-and-test-portability + + CI: fix make dist doc build and closure_mmap_failure on Android + +commit e431830b996633d67f41dd43db448fa5f364e789 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 16:14:00 2026 -0500 + + README: complete and consolidate the TBD changelog for the release + + Add user-facing changes that had landed since 3.8.0 but were missing from + the notes: the x86-64 single-long-double struct return (#1058), the x86-64 + 16-byte vector call-plan upper-half fix, the RISC-V void-call return-buffer + fix, the wasm >=2 GiB heap and stack-switching-closure fixes (#1062), the + bounded executable-mmap retry (#1055), keeping bundled dlmalloc symbols + static, the mips N32/N64 CFI unwinding (#1063), and the build/packaging + fixes (--enable-docs, --libdir, CCASFLAGS; #1060). + + Consolidate the six security fixes under one Security fixes heading with a + concise entry each (keeping the GHSA/CWE ids), fold GHSA-vg77 into the + aarch64 entry it duplicates, and merge the NetBSD closure-allocation + fallback into the page-size-lookup entry. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 1436c4a967441a4fb10be43d98d0fb9dfce60743 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 16:09:31 2026 -0500 + + testsuite: xfail mips N64 complex/fp-return tests (libffi #1071) + + complex_regs_float, complex_regs_longdouble and cls_struct_fp_return fail + on mips64 N64 due to real, pre-existing ABI bugs in libffi's N64 + complex-float/longdouble argument passing and fp-struct returns (confirmed + on real mips64 hardware, not a QEMU artifact). Mark them xfail on + mips64*-*-* with a pointer to the tracking issue so CI reflects the known + limitation while the ABI fix is developed; they are not whitelisted in + rlgl-policy, since the sim is not at fault. + + See https://github.com/libffi/libffi/issues/1071. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit a5cf1f76582fc8d669c6e8ed5415571068099017 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 15:12:26 2026 -0500 + + testsuite: restrict closure_mmap_failure to glibc Linux + + The test interposes mmap with a defined symbol plus dlsym(RTLD_NEXT, + "mmap") and -Wl,--export-dynamic, which is a glibc technique. Its + target guard was x86_64-*-linux*, which also matches x86_64-linux-android, + so the Android x86_64 CI job tried to build it and failed to compile + ("test for excess errors"). Tighten the guard to x86_64-*-linux-gnu* so + it runs on glibc Linux (where it is designed to work and still passes) and + is skipped on Android and musl. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 591109062b61d5f8b8bc45253d288ab3445e4280 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 15:09:49 2026 -0500 + + build: only build docs in dist-hook when docs are enabled + + The dist-hook unconditionally ran "cd doc; make pdf", so "make dist" + tried to build the PDF (and the .info it depends on) even when configured + --disable-docs or when makeinfo/TeX is absent. That failed the dist step + on runners without texinfo/texlive (e.g. the macOS and Android CI jobs: + libffi.info Error 127, libffi.pdf Error 1). + + Guard the doc-building line of dist-hook with the BUILD_DOCS automake + conditional, leaving the ChangeLog and README generation unconditional. + Verified: with --disable-docs the generated rule comments out the pdf + build and "make dist" completes (produces the tarball); with + --enable-docs the pdf build still runs. + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit af169894df2091141cbf3c2c562f1802decd2b14 +Merge: c19aeb48 2cb14fc0 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:45:49 2026 -0500 + + Merge pull request #1060 from 7thplanetyt/codex/fix-890-ccasflags + + configure: keep assembler defaults in sync with final CFLAGS + +commit c19aeb480f8fe4c7f0bf1bfcf9d2d6b7bee4e4b9 +Merge: 113cdf63 1c7d90af +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:45:44 2026 -0500 + + Merge pull request #1063 from vhankala/mips-n32-cfi + + mips: Use CFI directives in N32/N64 assembly + +commit 113cdf6313bce9a1cdb8ed7e8c96e6c60cc169a2 +Merge: f64ed0fa 6a1bdb5d +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:45:40 2026 -0500 + + Merge pull request #1062 from agriyakhetarpal/wasm-unsigned-heap-index + + Fix WASM heap view indexing at 2 GiB and above + +commit f64ed0faee0fe947c8e47012ec088d3617da072a +Merge: 5b8dbbd8 a80fe939 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:45:35 2026 -0500 + + Merge pull request #1058 from shalseth/x86-64-struct-ld-return + + x86-64: return a struct with one long double member in %st0 + +commit 5b8dbbd85f5cdaf296ceb1226c9533f51a5e0a22 +Merge: 8da7a153 12e1b740 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:30:20 2026 -0500 + + Merge pull request #1069 from libffi/fix/ghsa-w6j9-raw-closure + + Fix raw-API closures under static trampolines (GHSA-w6j9-w53f-2857) + +commit 12e1b740ebe7861a9d0a7dc23003e3498645e8f2 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:28:11 2026 -0500 + + x86: support static trampolines in the i386 native raw closure path + + ffi_prep_raw_closure_loc for the i386 native raw API wrote a dynamic + trampoline straight into closure->tramp with no ffi_tramp_is_present() + guard, unlike ffi_prep_closure_loc. With FFI_EXEC_STATIC_TRAMP (the + default) that write lands on the ftramp pointer ffi_closure_alloc stored + at offset 0, so ffi_closure_free later calls ffi_tramp_free() on a + corrupted pointer; and the static trampoline returned in *code was never + given its parameters, so invoking the closure jumped through an unset + (NULL or stale) slot. The documented ffi_closure_alloc + + ffi_prep_raw_closure_loc pattern therefore crashed (GHSA-w6j9-w53f-2857 + part B). + + Mirror ffi_prep_closure_loc: when a static trampoline is present, set its + parameters (via the closure's ftramp, read through ffi_closure as + ffi_closure_alloc does) and point it at new _alt entry points instead of + writing the dynamic trampoline. Add ffi_closure_raw_SYSV_alt and + ffi_closure_raw_THISCALL_alt, which load the closure pointer the static + trampoline passes into %eax and fall through to the normal bodies, just + like ffi_closure_i386_alt. No struct layout changes. + + Verified on real i386 (GCC compile farm, cfarm26, native i686): the + raw-closure test crashed before and passes after, and the call and + closure suites pass (1472). This completes GHSA-w6j9-w53f-2857 together + with the generic-path fix; the closure_raw.c test now exercises both the + generic (x86-64) and native (i386) raw closure paths. + + Advisory: GHSA-w6j9-w53f-2857 + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 8f13de89965408bd1186c873ec87ad8f0a9170af +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:11:13 2026 -0500 + + raw API: pass the closure, not codeloc, as the translate-args user_data + + ffi_prep_raw_closure_loc and ffi_prep_java_raw_closure_loc installed their + generic trampoline handler (ffi_translate_args / ffi_java_translate_args) + with codeloc as both the user_data and the code location. The handler then + cast that user_data back to the ffi_raw_closure and read cl->fun and + cl->user_data from it. + + That worked only because, before static trampolines, codeloc aliased the + closure's own data. With FFI_EXEC_STATIC_TRAMP (the default on Linux) + codeloc points into the read-only trampoline code table instead, so the + handler read cl->fun from unrelated memory and made a wild indirect call. + The documented ffi_closure_alloc + ffi_prep_raw_closure_loc pattern + therefore crashed. + + Pass the closure itself as the user_data so the handler always reads the + real cl->fun/cl->user_data, regardless of where the code lives. + + Add testsuite/libffi.call/closure_raw.c, the first test to exercise + ffi_prep_raw_closure_loc; verified on x86-64 (static trampolines on) that + the documented pattern crashed before and returns the correct value after. + + This is part A of GHSA-w6j9-w53f-2857. Part B (the i386 native raw API not + checking ffi_tramp_is_present) is handled separately where it can be run on + a 32-bit target. + + Reported-by: karimabisaad (https://github.com/karimabisaad) + Advisory: GHSA-w6j9-w53f-2857 + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 8da7a153ff8e5a10b9c1e57b186fd31ae8c01c51 +Merge: 748934db d544f904 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:07:10 2026 -0500 + + Merge pull request #1068 from libffi/fix/ghsa-wf8m-s390x-int128 + + s390x: pass 128-bit integer arguments to closures by reference (GHSA-wf8m-qr3x-cch4) + +commit d544f90452eac771560e6c1032acd25f586e216a +Merge: cdc4a549 748934db +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:07:03 2026 -0500 + + Merge remote-tracking branch 'origin/master' into wf8m-merge + + # Conflicts: + # README.md + +commit 748934dbfa1c99da2f1d1839c97cf22f05ebafab +Merge: 39fd231e 6383099a +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:06:38 2026 -0500 + + Merge pull request #1067 from libffi/fix/ghsa-h52h-aarch64-abi + + aarch64: fix large-struct pointer offset and HFA/HVA detection (GHSA-h52h-3759-xqm4) + +commit 6383099aae8ed4cfc314430a22315e261acafd5c +Merge: fa9a7093 39fd231e +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:06:32 2026 -0500 + + Merge remote-tracking branch 'origin/master' into h52h-merge + + # Conflicts: + # README.md + +commit 39fd231e4b54d1519143da4eadbf33ff786ddaa9 +Merge: 70a894ae ee3d6126 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 14:04:39 2026 -0500 + + Merge pull request #1066 from libffi/fix/ghsa-fq46-69xf-x5gf-tramp-path + + Harden static-trampoline code-table lookup against path attacks (GHSA-fq46-69xf-x5gf) + +commit cdc4a549fe7305cb6956f17b7f57db3dc7c8e2f5 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 13:56:36 2026 -0500 + + s390x: pass 128-bit integer arguments to closures by reference + + The s390x call path passes __int128 (and complex and long double) by + reference: one GPR slot holds a pointer to the value. The closure helper + ffi_closure_helper_SYSV handled complex and long double this way but had + no SINT128/UINT128 case, so those fell into the switch default + (FFI_ASSERT(0), a no-op in release builds). The avalue[] entry for the + argument was left uninitialised, so the handler received a stale stack + pointer and dereferenced it (a 16-byte out-of-bounds read); and because + no GPR slot was consumed, every following argument was decoded from a + shifted slot. + + Group SINT128/UINT128 with COMPLEX in the by-reference handling, so one + GPR slot is consumed and the pointer is dereferenced into avalue[], + mirroring the call side. + + Add a closures regression test (closure_int128.c) that passes a 128-bit + integer, and an argument after it, through a closure. Verified on s390x + (GCC compile farm): before the fix the handler returned a garbage value, + after it returns the correct one, and the call/closure/complex suites + pass (1088). + + Reported-by: zerovulnlabs (https://github.com/zerovulnlabs) + Advisory: GHSA-wf8m-qr3x-cch4 + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit fa9a709309d8961b43dea0bdb3bb144ff9428ca5 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 13:39:00 2026 -0500 + + aarch64: fix homogeneous-aggregate detection (HFA/HVA) + + is_vfp_type decided whether an aggregate is a homogeneous floating-point + or vector aggregate using helpers that were too strict in one way and + not recursive enough in another: + + * It required every vector lane in an HVA to have the same scalar type. + AAPCS64 (and GCC and Clang) treat two short vectors as the same + fundamental type when they are the same size; the lane type does not + matter. So { float32x4_t, int32x4_t } was rejected and sent down the + >16-byte memory path, while a native callee passed/returned it in + q0/q1. As a closure return that meant the handler wrote through a + stale x8; as an argument it shifted every later argument by a + register. + + * The vector-width and lane checks ran only on the outermost members + and is_simd() looked only at the first nested aggregate, so a nested + aggregate that mixes a vector with scalars (e.g. + struct { struct { float32x4_t v; float a,b,c,d; }; }) was wrongly + accepted as a two-register HVA and passed in v0/v1, where both + compilers pass it by reference in x0. + + Replace is_hfa0/is_simd/is_hfa1 with a single recursive hfa_flatten() + that flattens the aggregate and requires every leaf to share one + fundamental type -- a floating-point scalar, or a short vector matched by + size (lane type ignored) -- with 1 to 4 leaves. The AARCH64_RET_* + encoding is unchanged. + + Verified on aarch64 (cfarm185) against native GCC callees: the two + mismatching cases now agree with the native ABI, and the full testsuite + passes (1788). + + Reported-by: karimabisaad (https://github.com/karimabisaad) + Advisory: GHSA-h52h-3759-xqm4 + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit da4db395c00c77e3615f44554fb44bb986dbc592 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 13:25:15 2026 -0500 + + aarch64: place spilled large-struct pointer at an 8-byte-aligned slot + + When ffi_call passes a non-HFA composite larger than 16 bytes by value, + AAPCS64 B.4 replaces it with a pointer that occupies a plain 8-byte, + 8-aligned stack slot. ffi_call_int copied the payload and jumped to + do_pointer with the pointer in hand, but left `ty' pointing at the + composite, so allocate_to_stack used the composite's alignment (16, or 4 + on Darwin) for the pointer slot instead of 8. + + With the x registers exhausted and NSAA not 16-aligned (for example nine + sint64 arguments followed by a 32-byte, 16-aligned struct), the pointer + was written 8 bytes higher than where the callee reads it. libffi's own + closure path uses sizeof(void*) for the same slot, so ffi_call and + closures disagreed even without any compiler involved; the callee + dereferenced uninitialised stack as the struct address. + + Re-point `ty' at ffi_type_pointer before the jump so the slot is aligned + by 8. Confirmed on aarch64 (cfarm185): a native GCC callee taking nine + int64s and a 32-byte struct crashed before and returns the correct value + after; the call and closure suites pass (954). + + Reported-by: karimabisaad (https://github.com/karimabisaad) + Advisory: GHSA-h52h-3759-xqm4 + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit ee3d61264a180953293914aedb37c520f1253a1f +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 13:11:24 2026 -0500 + + Harden static-trampoline code-table lookup against path attacks + + On Linux, ffi_tramp_get_libffi() located the file backing the static + trampoline code table by parsing /proc/self/maps, then reopened the path + it read and mapped it PROT_READ | PROT_EXEC. Two problems let that file + be attacker-controlled: + + 1. The path was read with sscanf("%s"), which stops at the first + whitespace. /proc/self/maps does not escape spaces in the name + field, so a libffi or executable path containing a space was + truncated and libffi opened the truncated path. + 2. The parsed device and inode were never used, so nothing checked + that the reopened file was the one the mapping was backed by. The + path could be replaced or symlinked between the read and the open. + + Either way the bytes of an attacker-supplied file could become the + executable trampoline code table, and every closure allocated from it + would run attacker code (GHSA-fq46-69xf-x5gf, CWE-59/CWE-367/CWE-706). + + Read the whole path (the rest of the maps line, which keeps embedded + spaces) rather than a whitespace-delimited token, and after opening it + fstat the descriptor and require its inode to match the mapping's inode, + falling back to the temp-file trampoline otherwise. Only the inode is + compared: the /proc/self/maps device field does not equal stat(2)'s + st_dev on btrfs, overlayfs and some other filesystems, so comparing + st_dev would reject the real file there (and /proc/self/map_files, which + would avoid the path entirely, is capability-gated and returns EPERM for + a process's own mappings on common kernels). + + Verified on x86-64: a closure built under a path containing a space now + opens the full path and runs correctly while ignoring a file planted at + the truncated path; the libffi.closures suite still passes (610). + + Reported-by: zerovulnlabs (https://github.com/zerovulnlabs) + Advisory: GHSA-fq46-69xf-x5gf + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 70a894ae395756653d08f65e411220fd3ee61efc +Merge: dc84815c 7b13cee9 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 12:33:12 2026 -0500 + + Merge pull request #1065 from libffi/fix/ghsa-23hx-9rxv-9qfp-trampoline-uaf + + Fix heap use-after-free in Darwin trampoline-table closure allocator (GHSA-23hx-9rxv-9qfp) + +commit 7b13cee9c321d58d1f2226c49190c04eec4c7aac +Merge: 13888a72 dc84815c +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 12:33:00 2026 -0500 + + Merge remote-tracking branch 'origin/master' into fix/ghsa-23hx-9rxv-9qfp-trampoline-uaf + + # Conflicts: + # README.md + +commit dc84815c9177de730d27d7ed87486cc42566859d +Merge: d02afc25 d06f515a +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 12:32:27 2026 -0500 + + Merge pull request #1064 from libffi/fix/ghsa-5pc3-hr6f-q3mm-vector-abi + + Reject x86-64 vector types with an undefined calling convention (GHSA-5pc3-hr6f-q3mm) + +commit d06f515abea2964969d720ac7ded3eb475bc4476 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Nov 13 12:15:49 2026 -0500 + + Reject x86-64 vector types with an undefined calling convention + + On x86-64 System V the psABI only defines how 8- and 16-byte vectors + (the __m64/__m128 shapes) are passed and returned. Narrower vectors and + the single-element <1 x double> are unspecified, and GCC and Clang + disagree on them: for <1 x double> GCC uses memory/sret while Clang uses + %xmm0, and for <1 x float> GCC uses memory while Clang returns it in an + integer register. + + ffi_prep_cif_machdep classified every 8-byte vector as SSE, so for + <1 x double> f(long x) against a GCC-built target libffi passed no sret + pointer and left x in %rdi; the callee then stored its result through + %rdi -- i.e. through the caller's integer argument, an attacker- + influenced out-of-bounds write (CWE-843 type confusion -> CWE-787). + + libffi cannot tell which compiler built the target, and the two + conventions genuinely diverge, so there is no classification that is + correct for both. Reject the undefined shapes instead: a type that is, + or recursively contains, a vector is now FFI_BAD_TYPEDEF unless the + vector is 16 bytes, or 8 bytes and not <1 x double> -- the shapes both + compilers agree on and this port implements. Multi-lane 8- and 16-byte + vectors keep working. + + Add a vector regression test asserting FFI_BAD_TYPEDEF for the undefined + shapes (including a struct that contains one) and FFI_OK for the agreed + ones, and note the change in the README history. + + Reported-by: karimabisaad (https://github.com/karimabisaad) + Advisory: GHSA-5pc3-hr6f-q3mm + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 13888a72978e222cfedcaa376c0bdd5ad88365c4 +Author: Anthony Green <green@moxielogic.com> +Date: Thu Nov 12 08:46:02 2026 -0500 + + Fix heap use-after-free in Darwin trampoline-table closure allocator + + ffi_closure_free() bumped a non-head trampoline table to the front of + ffi_trampoline_tables without first unlinking it from its old position. + The old neighbours kept pointing at the moved table, turning the + doubly-linked list into a cycle with stale prev/next links. A later + ffi_trampoline_table_free() then unlinked through those stale links, + writing a pointer into freed heap memory (CWE-416), and called + vm_deallocate() from inside a corrupted list. + + This affects only the FFI_EXEC_TRAMPOLINE_TABLE + __MACH__ allocator + (aarch64-apple-* and *arm*-apple-*, where it is the default) once a + process spans more than one trampoline table, i.e. more than 1024 live + closures. The trigger is an ordinary sequence of ffi_closure_alloc and + ffi_closure_free calls, so script-driven FFI runtimes that create + callbacks dynamically can reach it. + + Fix it by unlinking the table from its current position before pushing + it to the head of the list. Add a closures regression test that churns + many live closures across several trampoline tables, and note the fix + in the README history. + + Reported-by: karimabisaad (https://github.com/karimabisaad) + Advisory: GHSA-23hx-9rxv-9qfp + + Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> + +commit 6a1bdb5d0ad16dc66169b23cf94ef1c4458650f5 +Author: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com> +Date: Thu Nov 12 14:31:08 2026 +0530 + + Fix WASM heap view indexing at 2 GiB and above + +commit 1c7d90afa7524085764ab5177f1f5cff0befdbb8 +Author: Visa Hankala <visa@hankala.org> +Date: Tue Nov 10 15:23:41 2026 +0000 + + mips: Use CFI directives in N32/N64 assembly + + Use CFI directives in N32/N64 assembly when the assembler + supports them. + + This fixes build on OpenBSD/mips64 with LLVM LLD. The manually + constructed .eh_frame generates R_MIPS_64 relocations against local + symbols that LLD does not handle. With CFI directives the assembler + produces PC-relative relocations that LLD accepts. + +commit 2cb14fc08a7c74ec4114ef5d0086c0862f495d47 +Author: 7thplanetyt <221369153+7thplanetyt@users.noreply.github.com> +Date: Fri Nov 6 21:33:18 2026 -0600 + + configure: keep assembler defaults in sync with final CFLAGS + + Supply a make-time CFLAGS default before AM_PROG_AS when CCASFLAGS is unset. + Preserve explicit environment and configure-argument values, including empty + ones. Add six configure regression cases and one native Linux CI step. + + Implements Peter Bergner's late-bound default suggestion from issue #890. + Prepared and independently reviewed with Codex AI assistance. + +commit a80fe93964cc67bdcf1cd7b82ce6205d44fb6311 +Author: Stian Halseth <stian@itx.no> +Date: Fri Nov 6 12:14:36 2026 +0100 + + x86-64: return a struct with one long double member in %st0 + + The psABI classifies a struct whose only member is an x87 long double + as X87/X87UP, and returns it in %st0 like a plain long double. + ffi_prep_cif_machdep() sent it down the RAX/RDX struct path instead. + ffi_call() then stores garbage, and leaves the callee's value on the + x87 register stack, so after a few calls later long double arithmetic + in the caller gives NaN. A closure returning such a struct leaves %st0 + empty, and its caller reads NaN. + + Add cls_struct_ld_return to check the return through ffi_call and a + closure. + + Signed-off-by: Stian Halseth <stian@itx.no> + +commit d02afc25e8ea3aac9e78e227748e1fd7c9f14c82 +Merge: 5f667d18 e71a504b +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 14:49:52 2026 -0400 + + Merge pull request #1055 from libffi/fix/issue-1032-bounded-dlmmap + + Fix unbounded executable mmap retries + +commit e71a504b6448b32e0afeff75126a6f26407f3811 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 12:52:02 2026 -0400 + + Fix unbounded executable mmap retries + +commit 5f667d1863b3b4473972b8c75dfcf8abc1c200a6 +Merge: eb894dff a5ddf9f8 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 10:27:06 2026 -0400 + + Merge pull request #1054 from libffi/codex/pr-1028-rebased + + configure: honor explicit --enable-docs + +commit a5ddf9f8e3583eb60a54bebae42b3b758e130ab9 +Author: fhgffy <102001626+fhgffy@users.noreply.github.com> +Date: Tue Oct 6 07:12:33 2026 +0800 + + configure: honor explicit --enable-docs + + Preserve Autoconf's parsed docs value instead of unconditionally disabling + documentation whenever either option polarity is supplied. Add a five-case + configuration regression and run it in the native Linux CI job. + +commit eb894dff6927f92cd47011c9a18326745ec86b94 +Merge: 595c3930 fc0cd5d2 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 09:55:18 2026 -0400 + + Merge pull request #1031 from dannf/dlmalloc-static-decls + + closures: keep the dlmalloc 2.8.6 additions static + +commit 595c3930a3d6f72d4d5ae2ed85390dab17e7f1d1 +Merge: a8c5a70e 1ae71737 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 09:49:28 2026 -0400 + + Merge pull request #1027 from NotAFlightRisk/plan-vector-upper-half + + x86-64: copy the upper half of 16-byte vector arguments in call plans + +commit a8c5a70e18288a36a9119b74f59456fcf86c6bca +Merge: daec8db4 5fdd801e +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 08:59:44 2026 -0400 + + Merge pull request #1026 from HNO3Miracle/fix/riscv-void-return + + riscv: ignore return buffer for void calls + +commit daec8db406d7dec17b72008f7450a88d8109afe5 +Merge: c38051bf e1aac2a7 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 07:54:08 2026 -0400 + + Merge pull request #1045 from mohd-akram/fix-x64-cfi + + x86-64: fix build with missing CFI + +commit c38051bf796c1ad7948db75dd2a55f3a78b78a8c +Merge: a6d36760 d8127bda +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 07:41:37 2026 -0400 + + Merge pull request #1044 from libffi/fix-pr1022-complete + + configure: respect every explicit libdir spelling + +commit a6d367602ad2552ac58f4a840932ebbd8c76f151 +Merge: 61a20c6c 0762e0da +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 07:17:07 2026 -0400 + + Merge pull request #1053 from libffi/fix-mips64-complex-abi + + mips: bound small complex return stores + +commit 0762e0daeea915d1890c93c2dde69efc85ee2c2f +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 07:14:59 2026 -0400 + + mips: bound small complex return stores + + The N32/N64 assembly writes complex GPR returns in 8-byte chunks. Bounce values smaller than 16 bytes through an aligned temporary buffer so callers' result objects are not overrun, and account for big-endian right justification. Do the matching right justification for closure returns smaller than one register.\n\nReported-by: Daniel Golle <daniel@makrotopia.org> + +commit 61a20c6c9ad62a3650921b811e82ac87e3652340 +Merge: 871815cb 8a1db735 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 06:43:31 2026 -0400 + + Merge pull request #1052 from libffi/fix-mips-o32-complex-reg-exhaustion + + mips: fix O32 complex call and closure returns + +commit 8a1db7350d1037671747fbf135204c8976fb60fd +Author: Anthony Green <green@moxielogic.com> +Date: Wed Oct 28 06:23:32 2026 -0400 + + mips: fix O32 complex call and closure returns + + Handle all integer-complex sizes in the O32 call path and return soft-float complex values through the ABI-defined GPR set. Restore hard-float closure results from the FP save area, preserve the argument flags, and pass the complex result size back to assembly explicitly. + + Reported-by: Daniel Golle <daniel@makrotopia.org> + +commit 871815cbc2553e6871a1d51b2e8abebf2f75cd9a +Merge: 83944b00 94eb0e5b +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 21:45:43 2026 -0400 + + Merge pull request #1051 from libffi/fix-qemu-binfmt-comment + + ci: name the QEMU binfmt package correctly + +commit 94eb0e5b8cf5d7671e31391fb32cd227e67cab97 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 21:42:01 2026 -0400 + + ci: name the QEMU binfmt package correctly + +commit 83944b006a6bda260bbe24e4013851168aba5b2b +Merge: fc345b31 3365ad8b +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 21:20:00 2026 -0400 + + Merge pull request #1050 from libffi/fix-aarch64-darwin-stack-slots + + aarch64: fix small composite stack slots on Darwin + +commit 3365ad8b968a9b742922b6f1188462fe6ce142ec +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 20:44:21 2026 -0400 + + aarch64: match Darwin stack slots to compiler ABI + +commit 8c8b07941c73f23eb2c87023d9b9add2ec174708 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 27 17:25:24 2026 +0000 + + testsuite: check a small struct passed on the stack + + A struct smaller than a register that goes to the stack once the + argument registers are exhausted, followed by another scalar, checks + that the struct occupies the slot the ABI assigns and that the argument + behind it is found at the right offset. Nothing in the testsuite passes + a struct in that position through ffi_call; complex_int_small covers the + complex counterpart. + + Add struct_stack_small, which passes eight ints, a struct of two chars + and a short through ffi_call and a closure. + + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 2472245a3430b9d24f085b7654e896e074bceb82 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 27 17:25:24 2026 +0000 + + aarch64: give small composites full stack slots on Darwin + + Darwin packs scalar arguments on the stack to their natural alignment, + and libffi applies the same rule to composites of up to 16 bytes that + are not HFAs. Apple's compilers coerce such composites, structs and + complex types alike, to an array of register-sized words, so each takes + a pointer-aligned slot whose size is a multiple of the pointer size. A + struct of two chars or a _Complex char after the eighth integer + argument therefore lands at the wrong offset, as does every argument + behind it, in ffi_call and in closures (cf. issue #750). + + Round the alignment and the occupied size of such a composite up to the + pointer size on Apple targets. The generic cif->bytes accounting + already reserves a full slot per argument, so the stack frame stays + large enough. + + Fixes: 4330fdcd92e6 ("Darwin/aarch64: Respect iOS ABI re: stack argument alignment") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit fc345b3124c9a0d9024cad6a12b4cd9e184eaa05 +Merge: 2e9e98b9 8c9efed8 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 20:17:57 2026 -0400 + + Merge pull request #1049 from libffi/fix-sparc64-small-complex-abi + + sparc64: fix small integer complex ABI handling + +commit 8c9efed896188e360e1ba8ae1fb41b590cb8979e +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 15:48:42 2026 -0400 + + sparc64: fix small integer complex ABI handling + +commit 2e9e98b9c9300881b43580f7877c038f7b0aa746 +Merge: 4d78f2dc 22f21a37 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 18:58:25 2026 -0400 + + Merge pull request #1046 from libffi/fix-ci-cross-qemu-provisioning + + ci: fix QEMU package provisioning on Ubuntu 26.04 + +commit 22f21a378930791a977ee312ed154feab6690953 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 14:30:52 2026 -0400 + + ci: keep MIPS64EL cross build on Ubuntu 24.04 + +commit dadb494441d4d5fc4ea12ec3e8389c8822226317 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 14:11:52 2026 -0400 + + ci: fix qemu package provisioning on Ubuntu 26.04 + +commit e1aac2a712e30164970d9e7b61c7b36ade9e9ff1 +Author: Mohamed Akram <mohd.akram@outlook.com> +Date: Tue Oct 27 19:13:52 2026 +0400 + + x86-64: fix build with missing CFI + +commit d8127bda2811496d5606c56c5ea73b3c2e695fc1 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 11:00:34 2026 -0400 + + configure: respect every explicit libdir spelling + + Detect all libdir option forms accepted by Autoconf before applying GCC's multi-OS directory adjustment. Add configure-level coverage for full, abbreviated, single-dash, equals, and separate-value forms. + + Co-authored-by: huangwenbin <huangwenbin@kylinos.cn> + +commit 4d78f2dc2e6b67b52f59a99391f25c80158543dd +Merge: 8a59aed1 4106e56a +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 10:34:01 2026 -0400 + + Merge pull request #1025 from hilbert149/handle_sysconf_failure + + NetBSD: handle sysconf failure in ffi_closure_alloc + +commit 8a59aed1127bf8228e3098f5419068e30c1e13ec +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 08:39:45 2026 -0400 + + README: note cross-architecture ABI improvements + +commit db3c27ff7567c7caf591e9843bb895ddaf68e475 +Merge: 9c143241 807644a1 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 08:20:07 2026 -0400 + + Merge pull request #1033 from dangowrt/arm-complex + + arm: fix struct return argument space and small complex values + +commit 807644a16854a435bedba7a1b15bdd7c4c2e9655 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Wed Oct 21 01:24:08 2026 +0000 + + arm: pass sub-word complex arguments to big-endian closures in place + + On big-endian ARM, an integer argument narrower than 4 bytes is in the + low-order end of its register or stack slot, at offset 4 - size, which + the closure argument code now takes into account for everything except + structs. Complex values are composite types like structs, though, and + are passed as if loaded from memory with LDR, at offset 0: GCC passes a + _Complex char in the upper half of r0. + + Exclude complex types from the adjustment as well. + + complex_int_small failed on ixp4xx (xscale, big-endian) under qemu-user + when a closure read a _Complex signed char argument. + + Fixes: 2b53369681cc ("arm: fix big-endian sub-word argument offsets in closures") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit ca494a1fc657acdaf4945e4a7dde7adf1e7ac535 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Wed Oct 21 01:24:00 2026 +0000 + + arm: lay out the arguments behind the hidden struct return pointer + + A function that returns a struct or complex value of more than 4 bytes + takes the address of the return value in r0, ahead of its arguments. + ffi_prep_cif_machdep() accounts for that by adding 4 bytes to the + argument size computed by ffi_prep_cif_core(), but that size was + computed without the pointer. Moving the arguments up by 4 bytes can + add up to 4 bytes of padding in front of the first 8-byte aligned one, + which ffi_prep_args_SYSV() then writes past the end of the argument + area, into the call frame that follows it. + + Compute the size again with the pointer in front of the arguments, + using the same alignment as ffi_prep_args_SYSV(). + + With soft float, a call returning float _Complex after seven doubles + and before an int (complex_regs_float) passed garbage for the int and + returned garbage on mxs (arm926ej-s) and ixp4xx (xscale, big-endian) + under qemu-user. The same happens for any struct returned in memory + whenever the pointer adds such padding. + + Fixes: 6fa617dabc3d ("arm: Add argument space for the hidden struct return pointer") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 9c1432412bcb6777f4cd74a33f28222cd231cd6a +Merge: c2042b26 e3640d03 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 08:17:11 2026 -0400 + + Merge pull request #1042 from dangowrt/loongarch-complex + + loongarch: add support for complex types + +commit e3640d035f23802b42a4f1d329c9148a07176e95 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 22:59:41 2026 +0000 + + loongarch: add support for complex types + + The LoongArch psABI passes a complex floating-point number, and a struct + containing just one, as though it were a struct of two floating-point + reals. That is exactly the rule libffi already implements for structs + in struct_passed_as_elements(): two floats go in two FPRs if two are + free, otherwise the value follows the integer convention, in up to two + GPRs or by reference if larger than 2*GRLEN. + + Flatten an FFI_TYPE_COMPLEX into two elements of its base type, let the + float struct handling in marshal(), unmarshal() and passed_by_ref() + accept complex types, and define FFI_TARGET_HAS_COMPLEX_TYPE. Everything + else follows from the existing struct code: + + - float and double _Complex use $f0/$f1 when two FPRs are left, and + one or two GPRs otherwise, never one FPR and one GPR; + - variadic complex arguments use the integer convention; + - long double _Complex (32 bytes) is passed by reference and returned + through a hidden pointer; + - integer complex types are packed into GPRs like a small struct; + - a struct holding a single complex value flattens to the same two + reals and is passed the same way. + + This matches GCC's code generation for lp64d. On the single-float and + soft-float ABIs the parts that are not IS_FLOAT fall back to the integer + convention, again as the psABI requires. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit c2042b260affb0b9dfe6d9ea35221c06551c53e4 +Merge: b8d8667d 53b49e1b +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 08:10:53 2026 -0400 + + Merge pull request #1041 from dangowrt/riscv-complex + + riscv: add support for complex types + +commit 53b49e1bb8302fa8e5eb9ccdbe4e0e9823a104ff +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 22:57:49 2026 +0000 + + riscv: add support for complex types + + The RISC-V psABI passes a complex floating-point number, and a struct + containing just one, as though it were a struct of two floating-point + reals. That is exactly the rule libffi already implements for structs + in struct_passed_as_elements(): two floats go in two FPRs if two are + free, otherwise the value follows the integer convention, in up to two + GPRs or by reference if larger than 2*XLEN. + + Flatten an FFI_TYPE_COMPLEX into two elements of its base type, let the + float struct handling in marshal(), unmarshal() and passed_by_ref() + accept complex types, and define FFI_TARGET_HAS_COMPLEX_TYPE. Everything + else follows from the existing struct code: + + - float and double _Complex use fa0/fa1 when two FPRs are left, and + one or two GPRs otherwise, never one FPR and one GPR; + - variadic complex arguments use the integer convention; + - long double _Complex (32 bytes) is passed by reference and returned + through a hidden pointer; + - integer complex types are packed into GPRs like a small struct; + - a struct holding a single complex value flattens to the same two + reals and is passed the same way. + + This matches GCC's code generation for lp64d. On FLEN=32 and soft-float + ABIs the double and soft-float parts are not IS_FLOAT and fall back to the + integer convention, again as the psABI requires. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit b8d8667d7284a92aa6cf1a384e2f863c759ada26 +Merge: b271ecd9 abec7eac +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 08:01:13 2026 -0400 + + Merge pull request #1037 from dangowrt/mips-n64-soft-fp-structs + + mips: fix N32/N64 soft-float returns of floating-point structs + +commit b271ecd9d42ecca232a2e35965857f39a463ff37 +Merge: 89d70eda 0074d8a1 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:58:14 2026 -0400 + + Merge pull request #1036 from dangowrt/mips-n64-be-closure-ints + + mips: fix big-endian N32/N64 closure returns of small integers + +commit 89d70eda19c9456c25fb380754ec4fb43cf7de2e +Merge: cca77404 5e9f34d6 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:56:35 2026 -0400 + + Merge pull request #1034 from dangowrt/powerpc32-complex + + powerpc: add complex type support for 32-bit SYSV + +commit 5e9f34d6e75fb538ae039bd5117b5d6f24ed30e0 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 23:08:27 2026 +0000 + + powerpc: add complex type support for 32-bit SYSV + + The 32-bit SYSV ABI passes and returns complex values in GPRs, never in + FPRs, even with hard float. GCC does not split them for this ABI but + treats each one as a single item of as many words as it needs, and + those items follow the same rules as integers of the same size: + + - one word (_Complex char and short) like an int, right-justified; + - two words (float and int _Complex) like long long: in an even/odd + GPR pair (r3:r4, r5:r6, r7:r8, r9:r10), otherwise 8-byte aligned on + the stack, and the remaining GPRs count as used; + - more words (double and long long _Complex, four words) in + consecutive GPRs with no pair alignment if they all fit, otherwise + 4-byte aligned on the stack, and every later argument goes to the + stack too; + - returned in r3, r3:r4 or r3-r6. + + All of these already exist for soft-float long double (FFI_TYPE_UINT128) + and long long, so map complex types onto them by size in a new + translate_type(), used everywhere translate_float() was. + + With a 128-bit long double, long double _Complex takes eight words: it + goes in r3-r10 when it is the first argument and on the stack otherwise, + and is returned in r3-r10. Handle it as an internal FFI_TYPE_UINT256, + passed like FFI_TYPE_UINT128 with eight words, with a new + FLAG_RETURNS_256BITS that makes ffi_call_SYSV also store r7-r10, and a + PPC32_LD_R3R10 closure return entry. The closure's return value area + is exactly 32 bytes. + + A _Complex char is returned right-justified in r3, so ffi_call uses the + small struct bounce buffer for it and the closure helper shifts it into + place. The ELFv2 handling of that bounce buffer for integer complex + types is now limited to powerpc64. + + ffi_prep_types_sysv() resizes ffi_type_longdouble according to the abi; + keep ffi_type_complex_longdouble in step with it, as ffi_linux64.c does. + + This matches GCC's code generation for 8548 (soft-float) and 464fp + (hard-float), with 64-bit long double (musl) and with + -mlong-double-128. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit cca77404fe0571afb049a7a50455f41270915816 +Merge: d857d416 ba994921 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:54:52 2026 -0400 + + Merge pull request #1043 from dangowrt/powerpc-small-struct-closures + + powerpc: fix big-endian closure returns of small structs + +commit d857d4168da77e7757d6e83b2efa62682ba42059 +Merge: 610e1f00 198b8ef4 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:51:28 2026 -0400 + + Merge pull request #1039 from dangowrt/x86-complex-small + + x86: pass complex arguments of up to 4 bytes like structs on i386 + +commit 610e1f007f2ac2a075b1cec071aad4e67b7474e5 +Merge: bc553867 a68cd578 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:47:12 2026 -0400 + + Merge pull request #1040 from dangowrt/complex-tests + + testsuite: complex arguments near register exhaustion, small integer complex + +commit abec7eacd17eae31961b0b63c476eb80cab1a5e5 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:45:22 2026 -0400 + + testsuite: use register-sized struct return storage + +commit 198b8ef4c94942166ba747b45ec66619c79e828a +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:45:22 2026 -0400 + + x86: leave complex arguments out of native raw calls + +commit a68cd578c6bb42841506719f5f372ebfdebc575f +Author: Anthony Green <green@moxielogic.com> +Date: Tue Oct 27 07:45:22 2026 -0400 + + testsuite: use register-sized complex return storage + +commit 0074d8a10c332b61d5d88c3b2bd840490be1ffb9 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Wed Oct 21 01:24:10 2026 +0000 + + mips: fix big-endian N32/N64 closure returns of small integers + + Closures store an integer return value narrower than ffi_arg widened to + an ffi_arg, as the documentation requires and the testsuite does. When + the return value handling moved to returning the exact type, the jump + table in ffi_closure_N32 started to load these values with lw, lh, lhu, + lb or lbu from the start of the ffi_arg, which on big-endian holds the + upper bits. Every closure returning a char, short or int there now + returned 0 or garbage. + + Load them from the end of the ffi_arg on big-endian. Two values share + the 32-bit integer path without being widened by the closure: a float + with soft float, and a pointer on N32. Widen those in + ffi_closure_mips_inner_N32() first, as ffi_call() already reads a + soft-float float return value from the end of the doubleword. + + This fixes cls_uchar, cls_sshort, cls_uint, cls_multi_*, closure_fn*, + closure_simple, the *_va closure tests and most of + libffi.bhaible/test-callback on malta (mips64r2) and octeon (octeon+), + both big-endian n64 soft-float, under qemu-user. N32 is compile-tested + only. + + Fixes: 04f6fa310dde ("mips: Fix N32 ABI return value handling (#813)") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit ba994921506147dfeb2f38ad4d2874a5bd6e4f09 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 23:37:11 2026 +0000 + + powerpc: fix big-endian SVR4 closure returns of 1- and 2-byte structs + + With FFI_SYSV_STRUCT_RET a struct of up to 8 bytes is returned in r3/r4, + right-justified if smaller than 4 bytes. The closure function stores it + at the start of the return value area, but closures returning a 1- or + 2-byte struct use the PPC_LD_U8 and PPC_LD_U16 jump table entries, which + on big-endian load from offset 3 and 2, where an integer widened to + ffi_arg is. + + Before the closure return handling moved from assembly to C, these + structs were loaded from offset 0. Add PPC32_SYSV_LD_STRUCT_1 and + PPC32_SYSV_LD_STRUCT_2 entries that do so again on big-endian, and alias + them to the integer entries on little-endian. PPC32_SYSV_LD_STRUCT_7 + now branches to .Lstruct567 instead of falling through into it, so that + the new entries follow it in the table. + + FFI_SYSV_STRUCT_RET is not the default on Linux, so the testsuite does + not cover it. Verified by building cls_1_1byte, cls_2byte and the other + small struct closure tests with -msvr4-struct-return -D__SVR4_STRUCT_RETURN + for 8548 and 464fp under qemu-user: cls_1_1byte and cls_2byte abort + without this change and pass with it, the others pass either way. + + Fixes: 840add3b6a1c ("Add conditional target support for __int128 (#951)") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 4686b25129cb5ee205b28329daa5d4a34ecbb8b1 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Wed Oct 21 01:24:14 2026 +0000 + + mips: fix N32/N64 soft-float returns of floating-point structs + + With soft float, GCC returns a struct of one or two float or double + fields with the first field in v0 and the second in a0, each like a + scalar of its type, i.e. a float in the low 32 bits. libffi got this + partly wrong: + + - ffi_call_N32 took the second field of a struct of two floats or of + a double and a float from v1; 2e825e219fa0 ("MIPS: fix some N32 + test failure (#701)") had changed the other two cases to a0. + - ffi_closure_N32 had no soft-float struct cases at all and returned + these structs like any small struct, as the first 16 bytes of the + return value in v0 and v1. That puts the second field in the wrong + register, and on big-endian a single float in the upper half of v0. + + Store the second field from a0 in ffi_call_N32, and return soft-float + structs of one or two floating-point fields from the closure in v0 and + a0. Like the soft-float cases in ffi_call_N32, the new closure cases + are outside the hard-float #ifdef, so a library built for hard float + also handles cifs for the soft-float ABIs. + + This fixes cls_struct_fp_return on malta (mips64r2, both endians) and + octeon (octeon+), n64 soft-float, under qemu-user, and the remaining + failure of libffi.bhaible/test-callback on big-endian, a closure + returning struct { float x; }. This code predates the git history. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 63213836c52800a255985a3f222a239020bcbce9 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Wed Oct 21 03:44:34 2026 +0000 + + x86: pass complex arguments of up to 4 bytes like structs on i386 + + ffi_call_int() passes an argument of up to 4 bytes that is not a struct + as an integer widened by extend_basic_type(), which aborts on anything + but the basic integer and float types. A _Complex char or _Complex + short is such an argument, so ffi_call() aborted for them. GCC passes + these values like small structs, as their memory image in a 4-byte + stack slot, and ffi_closure_inner() would have taken them from a + register with FFI_FASTCALL or FFI_THISCALL. + + Handle complex types like structs in ffi_call_int(), ffi_closure_inner() + and ffi_raw_call(). + + complex_int_small aborted on x86 (pentium4, musl) and passes now. For + FFI_FASTCALL and FFI_THISCALL this follows what libffi does for small + structs, which has not been checked against GCC. + + Fixes: 198f469e9107 ("x86: Add support for Complex") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 93ab6af85e78bb98e331692875193145645c58fd +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 23:37:11 2026 +0000 + + powerpc64: fix big-endian ELFv2 closure returns of 1- to 4-byte structs + + ELFv2 returns a struct of up to 8 bytes right-justified in r3. The + closure function stores it at the start of the return value area, in + its normal memory layout, so on big-endian the closure assembly has to + load the struct from offset 0 and shift it right. That is what + PPC64_LD_STRUCT_5/6/7 do, but structs of 1, 2 and 4 bytes use the jump + table entries for integer return values, which load from the end of the + doubleword where an integer widened to ffi_arg is. PPC64_LD_STRUCT_3 + loads from offset 4 and shifts by the contents of r8. + + The integer entries were introduced for structs when the closure return + handling moved from assembly to C, replacing the old shift of the first + doubleword by 8 - size bytes. Restore that behaviour with entries for + 1-, 2- and 4-byte structs on big-endian, which alias the integer entries + on little-endian as before, and make PPC64_LD_STRUCT_3 load and shift + the doubleword like the others. + + This fixes cls_1_1byte, cls_2byte, cls_3_1byte, cls_3byte1, cls_3byte2, + cls_4_1byte, cls_4byte, single_entry_structs1 and single_entry_structs3, + and the struct-returning callbacks in libffi.bhaible/test-callback, on + big-endian ELFv2 (musl powerpc64, e5500 under qemu-user). + + Fixes: 840add3b6a1c ("Add conditional target support for __int128 (#951)") + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 463ae02e66f4ea6be45a9e2bb2f646fa3da7d62a +Author: Daniel Golle <daniel@makrotopia.org> +Date: Wed Oct 21 01:24:14 2026 +0000 + + testsuite: check return values of structs with one or two floating-point fields + + Many ABIs return a struct of one or two float or double fields + differently from other small structs, in floating-point registers, or + with soft float in other GPRs than an integer struct of the same size. + Only a few of these combinations are covered, mostly through ffi_call. + + Add cls_struct_fp_return, which returns structs of float, double, two + floats, two doubles, float and double, and double and float, both + through ffi_call and through closures. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit 6452020c205cb88eca00a1865619e64860da5ed0 +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 23:48:34 2026 +0000 + + testsuite: check integer complex types smaller than a register + + complex_int.c defines a _Complex unsigned char type but only uses + _Complex int, so nothing tests complex values that fit into a single + register or stack slot. Several targets pass and return those + differently from the larger complex types, e.g. right-justified within + the register. + + Add complex_int_small, which passes and returns _Complex signed char and + _Complex short through ffi_call and through closures, both in registers + and, after eight ints, on the stack. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit dff6b142cef03fbba747344496abeb5941e1fe6b +Author: Daniel Golle <daniel@makrotopia.org> +Date: Tue Oct 20 22:57:49 2026 +0000 + + testsuite: check complex arguments when argument registers run low + + The complex tests pass at most a few complex values in a row, so they never + reach the argument-passing rules that apply once registers start to run + out. Those rules differ from the plain cases on several targets: + + - On RISC-V and LoongArch a complex float is passed like a struct of two + reals: in two FPRs if two are free, otherwise in integer registers as a + whole. It is never split between an FPR and a GPR. + - On 32-bit PowerPC SysV a two-word complex value takes an even/odd GPR + pair like long long, and a larger one either fits completely into the + remaining GPRs or goes to the stack, which also moves every later + argument to the stack. + + Add complex_regs_{float,double,longdouble}, which pass a complex value + after seven doubles, after five ints, and after eight doubles and eight + ints, followed by an int, and check the result both through ffi_call and + through a closure. + Assisted-by: LLM + Signed-off-by: Daniel Golle <daniel@makrotopia.org> + +commit fc0cd5d231506d0e211e006334b30b4b571d73ed +Author: dann frazier <dann.frazier@chainguard.dev> +Date: Fri Oct 23 15:38:01 2026 -0600 + + testsuite: check closures.o keeps dlmalloc symbols private + + Add a "make check" step. It fails when closures.o defines any dl* + symbol as external. + + closures.c keeps a static list of dlmalloc functions. Someone has + to update that list by hand when dlmalloc.c gains a function. The + 2.8.6 update missed five. The new check names each function that a + later update misses. + + testsuite/check-dlmalloc-static.sh reads the objects that + src/closures.lo points to. It runs $(NM) on them. It skips when NM + is dumpbin. + + Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> + Signed-off-by: dann frazier <dann.frazier@chainguard.dev> + +commit 3a05fc20fc219cdb005e81bdd8c7969a59c1a008 +Author: dann frazier <dann.frazier@chainguard.dev> +Date: Fri Oct 23 15:37:53 2026 -0600 + + closures: keep the dlmalloc 2.8.6 additions static + + closures.c includes dlmalloc.c after declaring each dl* function + static. This keeps the bundled allocator private to libffi. The + update to dlmalloc 2.8.6 (2a0b4b52) added five functions that are not + in that list: dlrealloc_in_place, dlposix_memalign, + dlmalloc_footprint_limit, dlmalloc_set_footprint_limit and + dlbulk_free. They now get dlmalloc's default extern linkage. + + libffi.so hides them through its version script. libffi.a has no + such script. A shared object that links libffi.a exports all five + whenever the link pulls in closures.o. On aarch64 every link does, + because ffi_prep_closure_loc in ffi.o calls ffi_data_to_code_pointer. + cffi's test_no_unknown_exported_symbols fails on such a build. + + Declare the five functions static along with the rest. + + Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> + Signed-off-by: dann frazier <dann.frazier@chainguard.dev> + +commit 1ae717371e00e29f52a36fd70465ee9d3c22bf93 +Author: Iain <iain1970@protonmail.com> +Date: Fri Oct 2 20:47:13 2026 +0100 + + x86-64: copy the upper half of 16-byte vector arguments in call plans + +commit 5fdd801e466a1ac28106e4ce9a3cb596c267d73d +Author: HNO3Miracle <xiangao.or@isrc.iscas.ac.cn> +Date: Tue Sep 29 14:23:17 2026 +0800 + + riscv: ignore return buffer for void calls + + ffi_call documents that rvalue is ignored for FFI_TYPE_VOID. The RISC-V + backend instead unmarshals the return whenever rvalue is non-null. Since + ffi_type_void has size 1, this copies one byte to the supplied pointer. + Miri passes the dangling data pointer of an empty return buffer, causing + its native-library tests to receive SIGSEGV on riscv64. + + Skip return unmarshalling for FFI_TYPE_VOID. Add a regression test that + checks a non-null return buffer remains unchanged, verifies that the + function runs with both non-null and null buffers, and include the test + in the distribution manifest. + + Related: https://github.com/rust-lang/miri/issues/5356 + + Signed-off-by: HNO3Miracle <xiangao.or@isrc.iscas.ac.cn> + +commit 4106e56a75c7f3558518829cba0861495c80a9bd +Author: panzhe <panzhe@kylinos.cn> +Date: Sun Sep 27 13:11:05 2026 +0800 + + NetBSD: handle sysconf failure in ffi_closure_alloc + +commit bc553867367246d140cd156f060bd0409f57f157 +Merge: ecdfe588 09884002 +Author: Anthony Green <green@moxielogic.com> +Date: Mon Sep 21 06:20:38 2026 -0400 + + Merge pull request #1023 from hilbert149/check_calloc_in_ffi_trampoline_table_alloc + + closures: check calloc return values in ffi_trampoline_table_alloc + +commit ecdfe5886d1778a47dadf65dbff32a15bc25c88f +Merge: be99c823 9b1cbb63 +Author: Anthony Green <green@moxielogic.com> +Date: Mon Sep 21 06:19:45 2026 -0400 + + Merge pull request #1024 from hilbert149/fix_typos_preceding + + Fix typos + +commit 9b1cbb631be1c9f065131276ad0f2de247847f43 +Author: panzhe <panzhe@kylinos.cn> +Date: Mon Sep 21 16:48:57 2026 +0800 + + Fix typos + +commit 09884002533a8c806940d274d0f80062eb64795c +Author: panzhe <panzhe@kylinos.cn> +Date: Mon Sep 21 16:36:06 2026 +0800 + + closures: check calloc return values in ffi_trampoline_table_alloc + +commit be99c823432142b771a765b82ebddc6ba281107a +Author: Anthony Green <green@moxielogic.com> +Date: Fri Sep 18 06:41:25 2026 -0400 + + README: note the ppc64 complex long double, closure, wasm and Apple fixes + + The TBD section had only the aarch64/arm big-endian closure entry. Four + more fixes have landed since: the powerpc64 _Complex long double size and + alignment now tracking the abi's long double, graceful failure when the + runtime page size lookup fails (#1015), the wasm EM_JS_DEPS declaration + that unbreaks the build on newer Emscripten (#1019), and + subsections_via_symbols on Apple platforms so the linker can dead-strip + unused code (#1017). + + Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> + +commit 5cad43c09f09c24fe94b41298afb3b20495d4576 +Author: Anthony Green <green@moxielogic.com> +Date: Wed Sep 16 06:15:21 2026 -0400 + + powerpc64: keep _Complex long double in step with the abi's long double + + ffi_prep_types_linux64() rewrites ffi_type_longdouble to 8 or 16 bytes + according to the FFI_LINUX_LONG_DOUBLE_128 bit of the abi it is handed. That + hook, and the fact that ffi_type_longdouble is one of only two non-const + ffi_type objects on this target, exist so that a single libffi can describe + calls into libraries built with either long double width. + + ffi_type_complex_longdouble is the other non-const one, for the same reason, + but was never updated: its size and alignment stayed frozen at whatever + sizeof(_Complex long double) was when libffi itself was compiled. A caller + asking for the other width therefore got a type that disagreed with its own + element -- an element of 8 bytes inside an aggregate still claiming 32 -- which + matters twice over: + + - ffi_call_int() completes a floating-point small-struct return with + memcpy (rvalue, smst_buffer, cif->rtype->size), so the return value is + copied at the build-time size. On a 128-bit build handed the 64-bit abi + that writes 32 bytes into a 16-byte value; the other way around it + truncates the imaginary half. + + - initialize_aggregate() sizes and aligns struct members from ->size and + ->alignment, so any struct containing a _Complex long double comes out the + build-time size and ffi_get_struct_offsets() reports wrong offsets. + + Derive both fields from ffi_type_longdouble, which the same function has just + set. No test reached this because the testsuite only ever passes + FFI_DEFAULT_ABI, where the frozen size happens to be correct, so add one that + checks the types agree at each width the hook distinguishes and that a struct + built from the complex type matches. Verified on ppc64le under emulation: the + new test aborts against a library without this change and passes with it, on + both a 128-bit and a -mlong-double-64 build, and it is unsupported off + powerpc64. + + Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> + +commit 1cdc1a8085b9968c00eee325483864568709442b +Author: Anthony Green <green@moxielogic.com> +Date: Tue Sep 15 10:12:56 2026 -0400 + + testsuite: pin -mlong-double-128 by compiler, not by target triplet + + cls_longdouble.c, cls_align_longdouble_split.c, cls_align_longdouble_split2.c + and huge_struct.c force -mlong-double-128 on every powerpc64*-*-linux-gnu* + target. That only works when libffi itself was built with a 128-bit long + double: the powerpc linker refuses to merge objects that disagree about the + long double ABI, so against a -mlong-double-64 library each of these fails to + link with + + ld: libffi.a(ffi_linux64.o) uses 64-bit long double, foo.o uses 128-bit + long double + + The triplet is the wrong thing to test -- what matters is what the compiler + does. Add a check_effective_target_ppc64_longdouble128 probe (via the existing + libffi_feature_test facility) and select on that instead. Where long double is + already 128 bits the option is applied exactly as before; where it is 64 bits + the option is dropped and the tests exercise the 64-bit long double, which is + the ABI the library was built for. + + Verified on ppc64le under emulation: with a 128-bit long double all four tests + still get the flag and still pass, and with CC="gcc -mlong-double-64" all four + now pass instead of failing to link. + + Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> + +commit a2c1286984fb36e0fd95b5c1554bf621d4d91c17 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Sep 15 07:34:00 2026 -0400 + + CI: test ppc64le with a 64-bit long double + + Nothing in CI covered a powerpc64 target whose long double is 64 bits while + FFI_TYPE_LONGDOUBLE stays distinct from FFI_TYPE_DOUBLE, which is how musl + configures ppc64le -- that gap is why the _Complex long double breakage of + issue #1013 shipped unnoticed. + + Add a second ppc64le entry to the QEMU matrix that builds with + CC="gcc -mlong-double-64", reproducing musl's choice inside the existing glibc + container without needing a musl toolchain. The flag belongs in CC rather than + CFLAGS because configure copies CC into CC_FOR_TARGET in local.exp, so the + testsuite then compiles the tests with it as well; a CFLAGS-only build would + test a 64-bit-long-double library against 128-bit-long-double tests. + + CXX is deliberately not overridden. The image installs gcc but not gcc-c++, + and while an unset CXX leaves configure to skip the C++ tests -- as it already + does for the existing ppc64le job -- an explicitly set one makes configure fail + its C++ preprocessor sanity check outright. + + build_foreign_linux forwards CC/CXX into the container only when non-empty, so + the other matrix entries keep configure's own compiler detection. + + Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> + +commit c043378d261d0a32e966fb5622ff36fbf9eaed95 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Sep 15 07:34:00 2026 -0400 + + powerpc64: fix _Complex long double when long double is 64 bits + + PR #1003 added _Complex long double support for the IBM-128 and IEEE-128 + formats, but it read "not IEEE-128" as "IBM-128" and so assumed + sizeof(long double) == 16 wherever FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE. + On powerpc that condition says nothing about the width: HAVE_LONG_DOUBLE_VARIANT + forces HAVE_LONG_DOUBLE on, and the actual width comes from the + FFI_LINUX_LONG_DOUBLE_128 bit of the ABI at runtime. + + Targets with a distinct but 64-bit long double -- musl ppc64le, or any build + with -mlong-double-64 -- therefore counted 4 FPRs and 4 GPR shadow slots for + each _Complex long double argument and read four doubles out of a 16-byte + value, crashing complex_longdouble, return_complex1_longdouble, + return_complex2_longdouble and cls_complex_va_longdouble. + + Normalize the complex element type to FFI_TYPE_DOUBLE when the ABI says long + double is 64 bits, as discover_homogeneous_aggregate and both _Complex return + paths already do, letting the existing double code handle those values. The + three argument paths fixed here were the only ones that hardcoded the IBM-128 + width; the rest are driven by rtype->size or by the element count from + discover_homogeneous_aggregate and were already correct. + + Reported and diagnosed by Janis Gertulla, who also proposed a fix. + + Fixes #1013 + + Co-authored-by: Janis Gertulla <coffeeimpliescode@proton.me> + Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> + +commit 98962d38dbb4e634878592117c30e6a61e245b21 +Merge: 5aff6a0b 9e807970 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Sep 15 06:24:49 2026 -0400 + + Merge pull request #1020 from hoodmane/emscripten-jspi + + Emscripten: Make closures work with wasm stack switching + +commit 9e807970afa7e0cf34215ca4f2bdbca69005c10c +Author: Hood Chatham <roberthoodchatham@gmail.com> +Date: Sun Sep 13 11:19:28 2026 -0700 + + Emscripten: Make closures work with wasm stack switching + + WebAssembly stack switching (more specifically JavaScript Promise Integration, + abbreviated JSPI) allows webassembly code to call a function that appears to be + synchronous that suspends until a JavaScript Promise is resolved. This comes + with the restriction that there can be no JavaScript frames on the stack when + this happens. + + In order to work well with this, the closure that `ffi_prep_closure_loc_js()` + makes should not put a JavaScript frame on the stack when making the onward + call. It can still use JavaScript helpers as the prelude and epilogue, but the + closure itself needs to be implemented in WebAssembly. + + This reworks `ffi_prep_closure_loc_js` to satisfy these constraints. This + does not change `ffi_call_js` so it still doesn't work with stack switching. It + will need a similar transform to make it work with JSPI, but I figured it was + better to do them separately to keep the PRs smaller. + + I also factored ffi_prep_closure_loc_js into smaller functions to try to + improve readability. + +commit 5aff6a0b6832baee81087c860050ecc6b38c45d0 +Merge: fb6495c6 c575818c +Author: Anthony Green <green@moxielogic.com> +Date: Mon Sep 14 07:18:48 2026 -0400 + + Merge pull request #1018 from 1234binpig/fix/check-linker-family + + build: check linker family before GNU ld version + +commit fb6495c6ec4ee03a261e897d0792fdfaee060ea0 +Merge: e044ec8d bf480c39 +Author: Anthony Green <green@moxielogic.com> +Date: Mon Sep 14 07:16:13 2026 -0400 + + Merge pull request #1019 from hoodmane/emscripten-version-bump + + CI: Update Emscripten, Node version, and pytest-pyodide to most recent versions + +commit bf480c3967ea9199764a346e07c64704cd414f44 +Author: Hood Chatham <roberthoodchatham@gmail.com> +Date: Sat Sep 12 17:47:07 2026 -0700 + + CI: Update Emscripten, Node version, and pytest-pyodide to most recent versions + + And fix misleading comment in CI config + +commit c575818ce67cb471467c580a01ae8f7b6538a6e2 +Author: huangwenbin <huangwenbin@kylinos.cn> +Date: Fri Sep 11 16:32:50 2026 +0800 + + build: check linker family before GNU ld version + + Known GNU-compatible linkers such as gold, LLD, and mold are detected + separately, but the symbol-versioning check previously compared the + parsed GNU ld version first. + + For mold and LLD, that parsed value is not meaningful and can make the + linker appear to be an old GNU BFD ld before its linker-family check is + reached. + + Check the known linker families first, and only apply the minimum GNU + ld version check afterward. + + Signed-off-by: huangwenbin <huangwenbin@kylinos.cn> + +commit e044ec8d00631edb77fa072187f2d9c02fb8950d +Merge: 57d48c93 1877747a +Author: Anthony Green <green@moxielogic.com> +Date: Fri Sep 4 09:12:22 2026 -0400 + + Merge pull request #1015 from 1234binpig/fix-closure-pagesize-check + + closures: handle page size lookup failure + +commit 57d48c93044c8c4f1615b0069cae29b213e88a51 +Merge: 33cfefc7 8ec82287 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Sep 4 09:10:07 2026 -0400 + + Merge pull request #1014 from 1234binpig/fix-tsan-thread-failure + + testsuite: propagate tsan worker failures + +commit 33cfefc7d93deba08084557e05728c721b276ade +Merge: 71ce128d 07a2a9a3 +Author: Anthony Green <green@moxielogic.com> +Date: Fri Sep 4 07:33:48 2026 -0400 + + Merge pull request #1017 from dmaclach/patch-1 + + Added `subsections_via_symbols` for Apple platforms + +commit 07a2a9a370565fad046f955942866883383218b3 +Author: Dave MacLachlan <dmaclach@gmail.com> +Date: Thu Sep 3 13:50:36 2026 -0700 + + Added `subsections_via_symbols` for Apple platforms + + `.subsections_via_symbols` is an assembler directive for Apple/Mach-O targets that tells the linker that a section can be safely split into independent, fine-grained subsections. This is on for x86_64 targets but was missing for arm64. Handcrafted assembly files must explicitly include .subsections_via_symbols at the end of the file to enable dead-stripping. + +commit 1877747a8966a9466802b8f807f4dec9141f9a48 +Author: huangwenbin <huangwenbin@kylinos.cn> +Date: Mon Aug 31 17:29:27 2026 +0800 + + closures: handle page size lookup failure + + allocate_space() uses the value returned by sysconf(_SC_PAGESIZE) + as the size of a local buffer without checking for failure. + + Return early when the page size lookup fails or produces an invalid + value, avoiding creation of an invalid variable-length array. + + Signed-off-by: huangwenbin <huangwenbin@kylinos.cn> + +commit 8ec82287e13ee539bf07bd349b89f9a4375c2611 +Author: huangwenbin <huangwenbin@kylinos.cn> +Date: Mon Aug 31 17:11:24 2026 +0800 + + testsuite: propagate tsan worker failures + + The tsan worker returned NULL both on success and on setup failures, + while main ignored the result from pthread_join(). + + This allowed failures in ffi_prep_cif() or ffi_prep_closure_loc() to be + reported as a successful test run. + + Return a distinct failure value from worker threads and check both + pthread_join() and the joined thread result. + + Signed-off-by: huangwenbin <huangwenbin@kylinos.cn> + +commit 71ce128d7acf4ef4c2c675c0751e2e37661dd868 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Aug 18 22:13:46 2026 -0400 + + README: start TBD notes with aarch64/arm big-endian fix + + Add a TBD History section for the merged #1012, which fixes big-endian + sub-word argument and return offsets on aarch64 and arm (closes #1011 + and #675). + + Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> + +commit 72e44aa8e60f8295f1c881ded8a69faa868e5c6e +Merge: 303a0031 2b533696 +Author: Anthony Green <green@moxielogic.com> +Date: Tue Aug 18 22:10:18 2026 -0400 + + Merge pull request #1012 from CoffeeImpliesCode/big-endian-closures + + aarch64, arm: fix big-endian sub-word argument/return offsets + +commit 2b53369681cc85094e936efe18e27bff2d63f4c0 +Author: Janis Gertulla <coffeeimpliescode@proton.me> +Date: Tue Aug 18 06:46:29 2026 +0200 + + arm: fix big-endian sub-word argument offsets in closures + + Sub-4-byte integer args passed in 32-bit registers or on the stack sit + in the LSB of the 4-byte slot, which on big-endian ARM is at offset + 4 - size. Previously assumed little-endian (offset 0). Adjust in + ffi_prep_incoming_args_SYSV and ffi_prep_incoming_args_VFP. + +commit b5f729755e888f4babff0d923b55f8848943059c +Author: Janis Gertulla <coffeeimpliescode@proton.me> +Date: Tue Aug 18 06:46:20 2026 +0200 + + aarch64: fix big-endian argument and return offsets in closures + + Sub-64-bit integer and scalar-float arguments passed in registers or + stack slots sit in the LSB of a 64-bit slot, which on big-endian is at + the high-address end. Add a BE() helper and offset the extracted + argument/return pointers by BE(sizeof(UINT64) - size) in + allocate_int_to_reg_or_stack, ffi_call_int and ffi_closure_SYSV_inner, + and by the register offset in compress_hfa_type. + + Fixes the big-endian closure failures (cf. issue #675). + +commit 303a0031a58a43c403ffa464e292183680ae0bd1 +Author: Anthony Green <green@moxielogic.com> +Date: Sun Aug 9 06:05:36 2026 -0400 + + release: verify README Status line matches the tag + + The top-of-README status line is a manual edit that was missed in the + 3.8.0 release. Fail the release (like the existing configure.ac check) + when it does not match the tag version. + + Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> + +commit 6e8371bcf314f154af9e252897803f024bb5ace9 +Author: Anthony Green <green@moxielogic.com> +Date: Sun Aug 9 06:04:39 2026 -0400 + + README: update Status line to 3.8.0 + + The top-of-README status line still named 3.7.1 after the 3.8.0 release. + + Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> + commit 12ffd1f9dc56fcea79d2f742f424301ae668d663 Author: Anthony Green <green@moxielogic.com> Date: Sat Aug 8 18:08:29 2026 -0400 diff --git a/deps/libffi/Makefile.am b/deps/libffi/Makefile.am index 74f87259b179..e35113b2b008 100644 --- a/deps/libffi/Makefile.am +++ b/deps/libffi/Makefile.am @@ -26,10 +26,14 @@ EXTRA_DIST = LICENSE ChangeLog.old \ libffi.xcodeproj/project.pbxproj \ src/powerpc/t-aix \ libtool-ldflags libtool-version configure.host README.md \ - libffi.map.in LICENSE-BUILDTOOLS msvc_build make_sunver.pl + libffi.map.in LICENSE-BUILDTOOLS msvc_build make_sunver.pl \ + testsuite/check-dlmalloc-static.sh + +check-local: src/closures.lo + $(SHELL) $(srcdir)/testsuite/check-dlmalloc-static.sh "$(NM)" src/closures.lo # local.exp is generated by configure -DISTCLEANFILES = local.exp +DISTCLEANFILES = local.exp libffi.map libffi.map-sun # Subdir rules rely on $(FLAGS_TO_PASS) FLAGS_TO_PASS = $(AM_MAKEFLAGS) @@ -154,8 +158,16 @@ AM_CPPFLAGS = -I. -I$(top_srcdir)/include -Iinclude -I$(top_srcdir)/src AM_CCASFLAGS = '$(AM_CPPFLAGS)' dist-hook: - d=`(cd $(distdir); pwd)`; (cd doc; make pdf; cp *.pdf $$d/doc) +if BUILD_DOCS + d=`(cd $(distdir); pwd)`; \ + if (cd doc && make pdf && cp *.pdf $$d/doc); then \ + :; \ + else \ + echo "dist-hook: PDF manual not built (no TeX engine?), omitting it from the dist"; \ + fi +endif if [ -d $(top_srcdir)/.git ] ; then (cd $(top_srcdir); git log --no-decorate) ; else echo 'See git log for history.' ; fi > $(distdir)/ChangeLog + rm -f $(distdir)/README.md; \ s=`awk '/was released on/{ print NR; exit}' $(top_srcdir)/README.md`; \ if [ -n "$$s" ]; then tail -n +$$(($$s-1)) $(top_srcdir)/README.md; else cat $(top_srcdir)/README.md; fi > $(distdir)/README.md diff --git a/deps/libffi/Makefile.in b/deps/libffi/Makefile.in index c29cbb6bb650..f8471e28be46 100644 --- a/deps/libffi/Makefile.in +++ b/deps/libffi/Makefile.in @@ -1,7 +1,7 @@ -# Makefile.in generated by automake 1.16.5 from Makefile.am. +# Makefile.in generated by automake 1.18.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2021 Free Software Foundation, Inc. +# Copyright (C) 1994-2025 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -72,6 +72,8 @@ am__make_running_with_option = \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +am__rm_f = rm -f $(am__rm_f_notfound) +am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -145,10 +147,9 @@ am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ - test -z "$$files" \ - || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ - || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ - $(am__cd) "$$dir" && rm -f $$files; }; \ + { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__installdirs = "$(DESTDIR)$(toolexeclibdir)" \ "$(DESTDIR)$(pkgconfigdir)" @@ -336,8 +337,8 @@ distdir = $(PACKAGE)-$(VERSION) top_distdir = $(distdir) am__remove_distdir = \ if test -d "$(distdir)"; then \ - find "$(distdir)" -type d ! -perm -200 -exec chmod u+w {} ';' \ - && rm -rf "$(distdir)" \ + find "$(distdir)" -type d ! -perm -700 -exec chmod u+rwx {} ';' \ + ; rm -rf "$(distdir)" \ || { sleep 5 && rm -rf "$(distdir)"; }; \ else :; fi am__post_remove_distdir = $(am__remove_distdir) @@ -367,14 +368,16 @@ am__relativize = \ done; \ reldir="$$dir2" DIST_ARCHIVES = $(distdir).tar.gz -GZIP_ENV = --best +GZIP_ENV = -9 DIST_TARGETS = dist-gzip # Exists only to be overridden by the user if desired. AM_DISTCHECK_DVI_TARGET = dvi distuninstallcheck_listfiles = find . -type f -print am__distuninstallcheck_listfiles = $(distuninstallcheck_listfiles) \ | sed 's|^\./|$(prefix)/|' | grep -v '$(infodir)/dir$$' -distcleancheck_listfiles = find . -type f -print +distcleancheck_listfiles = \ + find . \( -type f -a \! \ + \( -name .nfs* -o -name .smb* -o -name .__afs* \) \) -print ACLOCAL = @ACLOCAL@ AMTAR = @AMTAR@ AM_DEFAULT_VERBOSITY = @AM_DEFAULT_VERBOSITY@ @@ -476,8 +479,10 @@ ac_ct_READELF = @ac_ct_READELF@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ +am__xargs_n = @am__xargs_n@ ax_enable_builddir_sed = @ax_enable_builddir_sed@ bindir = @bindir@ build = @build@ @@ -539,11 +544,12 @@ EXTRA_DIST = LICENSE ChangeLog.old \ libffi.xcodeproj/project.pbxproj \ src/powerpc/t-aix \ libtool-ldflags libtool-version configure.host README.md \ - libffi.map.in LICENSE-BUILDTOOLS msvc_build make_sunver.pl + libffi.map.in LICENSE-BUILDTOOLS msvc_build make_sunver.pl \ + testsuite/check-dlmalloc-static.sh # local.exp is generated by configure -DISTCLEANFILES = local.exp +DISTCLEANFILES = local.exp libffi.map libffi.map-sun # Subdir rules rely on $(FLAGS_TO_PASS) FLAGS_TO_PASS = $(AM_MAKEFLAGS) @@ -671,12 +677,12 @@ fficonfig.h: stamp-h1 @test -f $@ || $(MAKE) $(AM_MAKEFLAGS) stamp-h1 stamp-h1: $(srcdir)/fficonfig.h.in $(top_builddir)/config.status - @rm -f stamp-h1 - cd $(top_builddir) && $(SHELL) ./config.status fficonfig.h + $(AM_V_at)rm -f stamp-h1 + $(AM_V_GEN)cd $(top_builddir) && $(SHELL) ./config.status fficonfig.h $(srcdir)/fficonfig.h.in: @MAINTAINER_MODE_TRUE@ $(am__configure_deps) - ($(am__cd) $(top_srcdir) && $(AUTOHEADER)) - rm -f stamp-h1 - touch $@ + $(AM_V_GEN)($(am__cd) $(top_srcdir) && $(AUTOHEADER)) + $(AM_V_at)rm -f stamp-h1 + $(AM_V_at)touch $@ distclean-hdr: -rm -f fficonfig.h stamp-h1 @@ -684,15 +690,13 @@ libffi.pc: $(top_builddir)/config.status $(srcdir)/libffi.pc.in cd $(top_builddir) && $(SHELL) ./config.status $@ clean-noinstLTLIBRARIES: - -test -z "$(noinst_LTLIBRARIES)" || rm -f $(noinst_LTLIBRARIES) + -$(am__rm_f) $(noinst_LTLIBRARIES) @list='$(noinst_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ - test -z "$$locs" || { \ - echo rm -f $${locs}; \ - rm -f $${locs}; \ - } + echo rm -f $${locs}; \ + $(am__rm_f) $${locs} install-toolexeclibLTLIBRARIES: $(toolexeclib_LTLIBRARIES) @$(NORMAL_INSTALL) @@ -719,21 +723,19 @@ uninstall-toolexeclibLTLIBRARIES: done clean-toolexeclibLTLIBRARIES: - -test -z "$(toolexeclib_LTLIBRARIES)" || rm -f $(toolexeclib_LTLIBRARIES) + -$(am__rm_f) $(toolexeclib_LTLIBRARIES) @list='$(toolexeclib_LTLIBRARIES)'; \ locs=`for p in $$list; do echo $$p; done | \ sed 's|^[^/]*$$|.|; s|/[^/]*$$||; s|$$|/so_locations|' | \ sort -u`; \ - test -z "$$locs" || { \ - echo rm -f $${locs}; \ - rm -f $${locs}; \ - } + echo rm -f $${locs}; \ + $(am__rm_f) $${locs} src/$(am__dirstamp): @$(MKDIR_P) src - @: > src/$(am__dirstamp) + @: >>src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/$(DEPDIR) - @: > src/$(DEPDIR)/$(am__dirstamp) + @: >>src/$(DEPDIR)/$(am__dirstamp) src/prep_cif.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) src/types.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) src/raw_api.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) @@ -743,10 +745,10 @@ src/tramp.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) src/debug.lo: src/$(am__dirstamp) src/$(DEPDIR)/$(am__dirstamp) src/aarch64/$(am__dirstamp): @$(MKDIR_P) src/aarch64 - @: > src/aarch64/$(am__dirstamp) + @: >>src/aarch64/$(am__dirstamp) src/aarch64/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/aarch64/$(DEPDIR) - @: > src/aarch64/$(DEPDIR)/$(am__dirstamp) + @: >>src/aarch64/$(DEPDIR)/$(am__dirstamp) src/aarch64/ffi.lo: src/aarch64/$(am__dirstamp) \ src/aarch64/$(DEPDIR)/$(am__dirstamp) src/aarch64/sysv.lo: src/aarch64/$(am__dirstamp) \ @@ -755,30 +757,30 @@ src/aarch64/win64_armasm.lo: src/aarch64/$(am__dirstamp) \ src/aarch64/$(DEPDIR)/$(am__dirstamp) src/alpha/$(am__dirstamp): @$(MKDIR_P) src/alpha - @: > src/alpha/$(am__dirstamp) + @: >>src/alpha/$(am__dirstamp) src/alpha/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/alpha/$(DEPDIR) - @: > src/alpha/$(DEPDIR)/$(am__dirstamp) + @: >>src/alpha/$(DEPDIR)/$(am__dirstamp) src/alpha/ffi.lo: src/alpha/$(am__dirstamp) \ src/alpha/$(DEPDIR)/$(am__dirstamp) src/alpha/osf.lo: src/alpha/$(am__dirstamp) \ src/alpha/$(DEPDIR)/$(am__dirstamp) src/arc/$(am__dirstamp): @$(MKDIR_P) src/arc - @: > src/arc/$(am__dirstamp) + @: >>src/arc/$(am__dirstamp) src/arc/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/arc/$(DEPDIR) - @: > src/arc/$(DEPDIR)/$(am__dirstamp) + @: >>src/arc/$(DEPDIR)/$(am__dirstamp) src/arc/ffi.lo: src/arc/$(am__dirstamp) \ src/arc/$(DEPDIR)/$(am__dirstamp) src/arc/arcompact.lo: src/arc/$(am__dirstamp) \ src/arc/$(DEPDIR)/$(am__dirstamp) src/arm/$(am__dirstamp): @$(MKDIR_P) src/arm - @: > src/arm/$(am__dirstamp) + @: >>src/arm/$(am__dirstamp) src/arm/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/arm/$(DEPDIR) - @: > src/arm/$(DEPDIR)/$(am__dirstamp) + @: >>src/arm/$(DEPDIR)/$(am__dirstamp) src/arm/ffi.lo: src/arm/$(am__dirstamp) \ src/arm/$(DEPDIR)/$(am__dirstamp) src/arm/sysv.lo: src/arm/$(am__dirstamp) \ @@ -787,48 +789,48 @@ src/arm/sysv_msvc_arm32.lo: src/arm/$(am__dirstamp) \ src/arm/$(DEPDIR)/$(am__dirstamp) src/avr32/$(am__dirstamp): @$(MKDIR_P) src/avr32 - @: > src/avr32/$(am__dirstamp) + @: >>src/avr32/$(am__dirstamp) src/avr32/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/avr32/$(DEPDIR) - @: > src/avr32/$(DEPDIR)/$(am__dirstamp) + @: >>src/avr32/$(DEPDIR)/$(am__dirstamp) src/avr32/ffi.lo: src/avr32/$(am__dirstamp) \ src/avr32/$(DEPDIR)/$(am__dirstamp) src/avr32/sysv.lo: src/avr32/$(am__dirstamp) \ src/avr32/$(DEPDIR)/$(am__dirstamp) src/bfin/$(am__dirstamp): @$(MKDIR_P) src/bfin - @: > src/bfin/$(am__dirstamp) + @: >>src/bfin/$(am__dirstamp) src/bfin/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/bfin/$(DEPDIR) - @: > src/bfin/$(DEPDIR)/$(am__dirstamp) + @: >>src/bfin/$(DEPDIR)/$(am__dirstamp) src/bfin/ffi.lo: src/bfin/$(am__dirstamp) \ src/bfin/$(DEPDIR)/$(am__dirstamp) src/bfin/sysv.lo: src/bfin/$(am__dirstamp) \ src/bfin/$(DEPDIR)/$(am__dirstamp) src/cris/$(am__dirstamp): @$(MKDIR_P) src/cris - @: > src/cris/$(am__dirstamp) + @: >>src/cris/$(am__dirstamp) src/cris/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/cris/$(DEPDIR) - @: > src/cris/$(DEPDIR)/$(am__dirstamp) + @: >>src/cris/$(DEPDIR)/$(am__dirstamp) src/cris/ffi.lo: src/cris/$(am__dirstamp) \ src/cris/$(DEPDIR)/$(am__dirstamp) src/cris/sysv.lo: src/cris/$(am__dirstamp) \ src/cris/$(DEPDIR)/$(am__dirstamp) src/frv/$(am__dirstamp): @$(MKDIR_P) src/frv - @: > src/frv/$(am__dirstamp) + @: >>src/frv/$(am__dirstamp) src/frv/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/frv/$(DEPDIR) - @: > src/frv/$(DEPDIR)/$(am__dirstamp) + @: >>src/frv/$(DEPDIR)/$(am__dirstamp) src/frv/ffi.lo: src/frv/$(am__dirstamp) \ src/frv/$(DEPDIR)/$(am__dirstamp) src/csky/$(am__dirstamp): @$(MKDIR_P) src/csky - @: > src/csky/$(am__dirstamp) + @: >>src/csky/$(am__dirstamp) src/csky/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/csky/$(DEPDIR) - @: > src/csky/$(DEPDIR)/$(am__dirstamp) + @: >>src/csky/$(DEPDIR)/$(am__dirstamp) src/csky/ffi.lo: src/csky/$(am__dirstamp) \ src/csky/$(DEPDIR)/$(am__dirstamp) src/csky/sysv.lo: src/csky/$(am__dirstamp) \ @@ -837,70 +839,70 @@ src/frv/eabi.lo: src/frv/$(am__dirstamp) \ src/frv/$(DEPDIR)/$(am__dirstamp) src/ia64/$(am__dirstamp): @$(MKDIR_P) src/ia64 - @: > src/ia64/$(am__dirstamp) + @: >>src/ia64/$(am__dirstamp) src/ia64/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/ia64/$(DEPDIR) - @: > src/ia64/$(DEPDIR)/$(am__dirstamp) + @: >>src/ia64/$(DEPDIR)/$(am__dirstamp) src/ia64/ffi.lo: src/ia64/$(am__dirstamp) \ src/ia64/$(DEPDIR)/$(am__dirstamp) src/ia64/unix.lo: src/ia64/$(am__dirstamp) \ src/ia64/$(DEPDIR)/$(am__dirstamp) src/m32r/$(am__dirstamp): @$(MKDIR_P) src/m32r - @: > src/m32r/$(am__dirstamp) + @: >>src/m32r/$(am__dirstamp) src/m32r/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/m32r/$(DEPDIR) - @: > src/m32r/$(DEPDIR)/$(am__dirstamp) + @: >>src/m32r/$(DEPDIR)/$(am__dirstamp) src/m32r/ffi.lo: src/m32r/$(am__dirstamp) \ src/m32r/$(DEPDIR)/$(am__dirstamp) src/m32r/sysv.lo: src/m32r/$(am__dirstamp) \ src/m32r/$(DEPDIR)/$(am__dirstamp) src/m68k/$(am__dirstamp): @$(MKDIR_P) src/m68k - @: > src/m68k/$(am__dirstamp) + @: >>src/m68k/$(am__dirstamp) src/m68k/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/m68k/$(DEPDIR) - @: > src/m68k/$(DEPDIR)/$(am__dirstamp) + @: >>src/m68k/$(DEPDIR)/$(am__dirstamp) src/m68k/ffi.lo: src/m68k/$(am__dirstamp) \ src/m68k/$(DEPDIR)/$(am__dirstamp) src/m68k/sysv.lo: src/m68k/$(am__dirstamp) \ src/m68k/$(DEPDIR)/$(am__dirstamp) src/m88k/$(am__dirstamp): @$(MKDIR_P) src/m88k - @: > src/m88k/$(am__dirstamp) + @: >>src/m88k/$(am__dirstamp) src/m88k/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/m88k/$(DEPDIR) - @: > src/m88k/$(DEPDIR)/$(am__dirstamp) + @: >>src/m88k/$(DEPDIR)/$(am__dirstamp) src/m88k/ffi.lo: src/m88k/$(am__dirstamp) \ src/m88k/$(DEPDIR)/$(am__dirstamp) src/m88k/obsd.lo: src/m88k/$(am__dirstamp) \ src/m88k/$(DEPDIR)/$(am__dirstamp) src/metag/$(am__dirstamp): @$(MKDIR_P) src/metag - @: > src/metag/$(am__dirstamp) + @: >>src/metag/$(am__dirstamp) src/metag/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/metag/$(DEPDIR) - @: > src/metag/$(DEPDIR)/$(am__dirstamp) + @: >>src/metag/$(DEPDIR)/$(am__dirstamp) src/metag/ffi.lo: src/metag/$(am__dirstamp) \ src/metag/$(DEPDIR)/$(am__dirstamp) src/metag/sysv.lo: src/metag/$(am__dirstamp) \ src/metag/$(DEPDIR)/$(am__dirstamp) src/microblaze/$(am__dirstamp): @$(MKDIR_P) src/microblaze - @: > src/microblaze/$(am__dirstamp) + @: >>src/microblaze/$(am__dirstamp) src/microblaze/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/microblaze/$(DEPDIR) - @: > src/microblaze/$(DEPDIR)/$(am__dirstamp) + @: >>src/microblaze/$(DEPDIR)/$(am__dirstamp) src/microblaze/ffi.lo: src/microblaze/$(am__dirstamp) \ src/microblaze/$(DEPDIR)/$(am__dirstamp) src/microblaze/sysv.lo: src/microblaze/$(am__dirstamp) \ src/microblaze/$(DEPDIR)/$(am__dirstamp) src/mips/$(am__dirstamp): @$(MKDIR_P) src/mips - @: > src/mips/$(am__dirstamp) + @: >>src/mips/$(am__dirstamp) src/mips/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/mips/$(DEPDIR) - @: > src/mips/$(DEPDIR)/$(am__dirstamp) + @: >>src/mips/$(DEPDIR)/$(am__dirstamp) src/mips/ffi.lo: src/mips/$(am__dirstamp) \ src/mips/$(DEPDIR)/$(am__dirstamp) src/mips/o32.lo: src/mips/$(am__dirstamp) \ @@ -909,30 +911,30 @@ src/mips/n32.lo: src/mips/$(am__dirstamp) \ src/mips/$(DEPDIR)/$(am__dirstamp) src/moxie/$(am__dirstamp): @$(MKDIR_P) src/moxie - @: > src/moxie/$(am__dirstamp) + @: >>src/moxie/$(am__dirstamp) src/moxie/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/moxie/$(DEPDIR) - @: > src/moxie/$(DEPDIR)/$(am__dirstamp) + @: >>src/moxie/$(DEPDIR)/$(am__dirstamp) src/moxie/ffi.lo: src/moxie/$(am__dirstamp) \ src/moxie/$(DEPDIR)/$(am__dirstamp) src/moxie/eabi.lo: src/moxie/$(am__dirstamp) \ src/moxie/$(DEPDIR)/$(am__dirstamp) src/or1k/$(am__dirstamp): @$(MKDIR_P) src/or1k - @: > src/or1k/$(am__dirstamp) + @: >>src/or1k/$(am__dirstamp) src/or1k/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/or1k/$(DEPDIR) - @: > src/or1k/$(DEPDIR)/$(am__dirstamp) + @: >>src/or1k/$(DEPDIR)/$(am__dirstamp) src/or1k/ffi.lo: src/or1k/$(am__dirstamp) \ src/or1k/$(DEPDIR)/$(am__dirstamp) src/or1k/sysv.lo: src/or1k/$(am__dirstamp) \ src/or1k/$(DEPDIR)/$(am__dirstamp) src/pa/$(am__dirstamp): @$(MKDIR_P) src/pa - @: > src/pa/$(am__dirstamp) + @: >>src/pa/$(am__dirstamp) src/pa/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/pa/$(DEPDIR) - @: > src/pa/$(DEPDIR)/$(am__dirstamp) + @: >>src/pa/$(DEPDIR)/$(am__dirstamp) src/pa/ffi.lo: src/pa/$(am__dirstamp) src/pa/$(DEPDIR)/$(am__dirstamp) src/pa/linux.lo: src/pa/$(am__dirstamp) \ src/pa/$(DEPDIR)/$(am__dirstamp) @@ -942,10 +944,10 @@ src/pa/hpux64.lo: src/pa/$(am__dirstamp) \ src/pa/$(DEPDIR)/$(am__dirstamp) src/powerpc/$(am__dirstamp): @$(MKDIR_P) src/powerpc - @: > src/powerpc/$(am__dirstamp) + @: >>src/powerpc/$(am__dirstamp) src/powerpc/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/powerpc/$(DEPDIR) - @: > src/powerpc/$(DEPDIR)/$(am__dirstamp) + @: >>src/powerpc/$(DEPDIR)/$(am__dirstamp) src/powerpc/ffi.lo: src/powerpc/$(am__dirstamp) \ src/powerpc/$(DEPDIR)/$(am__dirstamp) src/powerpc/ffi_sysv.lo: src/powerpc/$(am__dirstamp) \ @@ -972,49 +974,49 @@ src/powerpc/ffi_darwin.lo: src/powerpc/$(am__dirstamp) \ src/powerpc/$(DEPDIR)/$(am__dirstamp) src/riscv/$(am__dirstamp): @$(MKDIR_P) src/riscv - @: > src/riscv/$(am__dirstamp) + @: >>src/riscv/$(am__dirstamp) src/riscv/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/riscv/$(DEPDIR) - @: > src/riscv/$(DEPDIR)/$(am__dirstamp) + @: >>src/riscv/$(DEPDIR)/$(am__dirstamp) src/riscv/ffi.lo: src/riscv/$(am__dirstamp) \ src/riscv/$(DEPDIR)/$(am__dirstamp) src/riscv/sysv.lo: src/riscv/$(am__dirstamp) \ src/riscv/$(DEPDIR)/$(am__dirstamp) src/s390/$(am__dirstamp): @$(MKDIR_P) src/s390 - @: > src/s390/$(am__dirstamp) + @: >>src/s390/$(am__dirstamp) src/s390/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/s390/$(DEPDIR) - @: > src/s390/$(DEPDIR)/$(am__dirstamp) + @: >>src/s390/$(DEPDIR)/$(am__dirstamp) src/s390/ffi.lo: src/s390/$(am__dirstamp) \ src/s390/$(DEPDIR)/$(am__dirstamp) src/s390/sysv.lo: src/s390/$(am__dirstamp) \ src/s390/$(DEPDIR)/$(am__dirstamp) src/sh/$(am__dirstamp): @$(MKDIR_P) src/sh - @: > src/sh/$(am__dirstamp) + @: >>src/sh/$(am__dirstamp) src/sh/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/sh/$(DEPDIR) - @: > src/sh/$(DEPDIR)/$(am__dirstamp) + @: >>src/sh/$(DEPDIR)/$(am__dirstamp) src/sh/ffi.lo: src/sh/$(am__dirstamp) src/sh/$(DEPDIR)/$(am__dirstamp) src/sh/sysv.lo: src/sh/$(am__dirstamp) \ src/sh/$(DEPDIR)/$(am__dirstamp) src/sh64/$(am__dirstamp): @$(MKDIR_P) src/sh64 - @: > src/sh64/$(am__dirstamp) + @: >>src/sh64/$(am__dirstamp) src/sh64/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/sh64/$(DEPDIR) - @: > src/sh64/$(DEPDIR)/$(am__dirstamp) + @: >>src/sh64/$(DEPDIR)/$(am__dirstamp) src/sh64/ffi.lo: src/sh64/$(am__dirstamp) \ src/sh64/$(DEPDIR)/$(am__dirstamp) src/sh64/sysv.lo: src/sh64/$(am__dirstamp) \ src/sh64/$(DEPDIR)/$(am__dirstamp) src/sparc/$(am__dirstamp): @$(MKDIR_P) src/sparc - @: > src/sparc/$(am__dirstamp) + @: >>src/sparc/$(am__dirstamp) src/sparc/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/sparc/$(DEPDIR) - @: > src/sparc/$(DEPDIR)/$(am__dirstamp) + @: >>src/sparc/$(DEPDIR)/$(am__dirstamp) src/sparc/ffi.lo: src/sparc/$(am__dirstamp) \ src/sparc/$(DEPDIR)/$(am__dirstamp) src/sparc/ffi64.lo: src/sparc/$(am__dirstamp) \ @@ -1025,40 +1027,40 @@ src/sparc/v9.lo: src/sparc/$(am__dirstamp) \ src/sparc/$(DEPDIR)/$(am__dirstamp) src/tile/$(am__dirstamp): @$(MKDIR_P) src/tile - @: > src/tile/$(am__dirstamp) + @: >>src/tile/$(am__dirstamp) src/tile/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/tile/$(DEPDIR) - @: > src/tile/$(DEPDIR)/$(am__dirstamp) + @: >>src/tile/$(DEPDIR)/$(am__dirstamp) src/tile/ffi.lo: src/tile/$(am__dirstamp) \ src/tile/$(DEPDIR)/$(am__dirstamp) src/tile/tile.lo: src/tile/$(am__dirstamp) \ src/tile/$(DEPDIR)/$(am__dirstamp) src/vax/$(am__dirstamp): @$(MKDIR_P) src/vax - @: > src/vax/$(am__dirstamp) + @: >>src/vax/$(am__dirstamp) src/vax/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/vax/$(DEPDIR) - @: > src/vax/$(DEPDIR)/$(am__dirstamp) + @: >>src/vax/$(DEPDIR)/$(am__dirstamp) src/vax/ffi.lo: src/vax/$(am__dirstamp) \ src/vax/$(DEPDIR)/$(am__dirstamp) src/vax/elfbsd.lo: src/vax/$(am__dirstamp) \ src/vax/$(DEPDIR)/$(am__dirstamp) src/x86/$(am__dirstamp): @$(MKDIR_P) src/x86 - @: > src/x86/$(am__dirstamp) + @: >>src/x86/$(am__dirstamp) src/x86/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/x86/$(DEPDIR) - @: > src/x86/$(DEPDIR)/$(am__dirstamp) + @: >>src/x86/$(DEPDIR)/$(am__dirstamp) src/x86/ffi.lo: src/x86/$(am__dirstamp) \ src/x86/$(DEPDIR)/$(am__dirstamp) src/x86/sysv.lo: src/x86/$(am__dirstamp) \ src/x86/$(DEPDIR)/$(am__dirstamp) src/wasm/$(am__dirstamp): @$(MKDIR_P) src/wasm - @: > src/wasm/$(am__dirstamp) + @: >>src/wasm/$(am__dirstamp) src/wasm/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/wasm/$(DEPDIR) - @: > src/wasm/$(DEPDIR)/$(am__dirstamp) + @: >>src/wasm/$(DEPDIR)/$(am__dirstamp) src/wasm/ffi.lo: src/wasm/$(am__dirstamp) \ src/wasm/$(DEPDIR)/$(am__dirstamp) src/x86/ffiw64.lo: src/x86/$(am__dirstamp) \ @@ -1075,30 +1077,30 @@ src/x86/win64_intel.lo: src/x86/$(am__dirstamp) \ src/x86/$(DEPDIR)/$(am__dirstamp) src/xtensa/$(am__dirstamp): @$(MKDIR_P) src/xtensa - @: > src/xtensa/$(am__dirstamp) + @: >>src/xtensa/$(am__dirstamp) src/xtensa/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/xtensa/$(DEPDIR) - @: > src/xtensa/$(DEPDIR)/$(am__dirstamp) + @: >>src/xtensa/$(DEPDIR)/$(am__dirstamp) src/xtensa/ffi.lo: src/xtensa/$(am__dirstamp) \ src/xtensa/$(DEPDIR)/$(am__dirstamp) src/xtensa/sysv.lo: src/xtensa/$(am__dirstamp) \ src/xtensa/$(DEPDIR)/$(am__dirstamp) src/kvx/$(am__dirstamp): @$(MKDIR_P) src/kvx - @: > src/kvx/$(am__dirstamp) + @: >>src/kvx/$(am__dirstamp) src/kvx/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/kvx/$(DEPDIR) - @: > src/kvx/$(DEPDIR)/$(am__dirstamp) + @: >>src/kvx/$(DEPDIR)/$(am__dirstamp) src/kvx/ffi.lo: src/kvx/$(am__dirstamp) \ src/kvx/$(DEPDIR)/$(am__dirstamp) src/kvx/sysv.lo: src/kvx/$(am__dirstamp) \ src/kvx/$(DEPDIR)/$(am__dirstamp) src/loongarch/$(am__dirstamp): @$(MKDIR_P) src/loongarch - @: > src/loongarch/$(am__dirstamp) + @: >>src/loongarch/$(am__dirstamp) src/loongarch/$(DEPDIR)/$(am__dirstamp): @$(MKDIR_P) src/loongarch/$(DEPDIR) - @: > src/loongarch/$(DEPDIR)/$(am__dirstamp) + @: >>src/loongarch/$(DEPDIR)/$(am__dirstamp) src/loongarch/ffi.lo: src/loongarch/$(am__dirstamp) \ src/loongarch/$(DEPDIR)/$(am__dirstamp) src/loongarch/sysv.lo: src/loongarch/$(am__dirstamp) \ @@ -1278,7 +1280,7 @@ distclean-compile: $(am__depfiles_remade): @$(MKDIR_P) $(@D) - @echo '# dummy' >$@-t && $(am__mv) $@-t $@ + @: >>$@ am--depfiles: $(am__depfiles_remade) @@ -1498,12 +1500,13 @@ cscopelist-am: $(am__tagged_files) distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags -rm -f cscope.out cscope.in.out cscope.po.out cscope.files + distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am distdir-am: $(DISTFILES) $(am__remove_distdir) - test -d "$(distdir)" || mkdir "$(distdir)" + $(AM_V_at)$(MKDIR_P) "$(distdir)" @srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \ list='$(DISTFILES)'; \ @@ -1576,6 +1579,10 @@ dist-bzip2: distdir tardir=$(distdir) && $(am__tar) | BZIP2=$${BZIP2--9} bzip2 -c >$(distdir).tar.bz2 $(am__post_remove_distdir) +dist-bzip3: distdir + tardir=$(distdir) && $(am__tar) | bzip3 -c >$(distdir).tar.bz3 + $(am__post_remove_distdir) + dist-lzip: distdir tardir=$(distdir) && $(am__tar) | lzip -c $${LZIP_OPT--9} >$(distdir).tar.lz $(am__post_remove_distdir) @@ -1617,9 +1624,11 @@ dist dist-all: distcheck: dist case '$(DIST_ARCHIVES)' in \ *.tar.gz*) \ - eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).tar.gz | $(am__untar) ;;\ + eval GZIP= gzip -dc $(distdir).tar.gz | $(am__untar) ;;\ *.tar.bz2*) \ bzip2 -dc $(distdir).tar.bz2 | $(am__untar) ;;\ + *.tar.bz3*) \ + bzip3 -dc $(distdir).tar.bz3 | $(am__untar) ;;\ *.tar.lz*) \ lzip -dc $(distdir).tar.lz | $(am__untar) ;;\ *.tar.xz*) \ @@ -1627,7 +1636,7 @@ distcheck: dist *.tar.Z*) \ uncompress -c $(distdir).tar.Z | $(am__untar) ;;\ *.shar.gz*) \ - eval GZIP= gzip $(GZIP_ENV) -dc $(distdir).shar.gz | unshar ;;\ + eval GZIP= gzip -dc $(distdir).shar.gz | unshar ;;\ *.zip*) \ unzip $(distdir).zip ;;\ *.tar.zst*) \ @@ -1699,6 +1708,7 @@ distcleancheck: distclean $(distcleancheck_listfiles) ; \ exit 1; } >&2 check-am: all-am + $(MAKE) $(AM_MAKEFLAGS) check-local check: check-recursive all-am: Makefile $(LTLIBRARIES) $(DATA) $(HEADERS) fficonfig.h installdirs: installdirs-recursive @@ -1730,75 +1740,75 @@ mostlyclean-generic: clean-generic: distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) - -rm -f src/$(DEPDIR)/$(am__dirstamp) - -rm -f src/$(am__dirstamp) - -rm -f src/aarch64/$(DEPDIR)/$(am__dirstamp) - -rm -f src/aarch64/$(am__dirstamp) - -rm -f src/alpha/$(DEPDIR)/$(am__dirstamp) - -rm -f src/alpha/$(am__dirstamp) - -rm -f src/arc/$(DEPDIR)/$(am__dirstamp) - -rm -f src/arc/$(am__dirstamp) - -rm -f src/arm/$(DEPDIR)/$(am__dirstamp) - -rm -f src/arm/$(am__dirstamp) - -rm -f src/avr32/$(DEPDIR)/$(am__dirstamp) - -rm -f src/avr32/$(am__dirstamp) - -rm -f src/bfin/$(DEPDIR)/$(am__dirstamp) - -rm -f src/bfin/$(am__dirstamp) - -rm -f src/cris/$(DEPDIR)/$(am__dirstamp) - -rm -f src/cris/$(am__dirstamp) - -rm -f src/csky/$(DEPDIR)/$(am__dirstamp) - -rm -f src/csky/$(am__dirstamp) - -rm -f src/frv/$(DEPDIR)/$(am__dirstamp) - -rm -f src/frv/$(am__dirstamp) - -rm -f src/ia64/$(DEPDIR)/$(am__dirstamp) - -rm -f src/ia64/$(am__dirstamp) - -rm -f src/kvx/$(DEPDIR)/$(am__dirstamp) - -rm -f src/kvx/$(am__dirstamp) - -rm -f src/loongarch/$(DEPDIR)/$(am__dirstamp) - -rm -f src/loongarch/$(am__dirstamp) - -rm -f src/m32r/$(DEPDIR)/$(am__dirstamp) - -rm -f src/m32r/$(am__dirstamp) - -rm -f src/m68k/$(DEPDIR)/$(am__dirstamp) - -rm -f src/m68k/$(am__dirstamp) - -rm -f src/m88k/$(DEPDIR)/$(am__dirstamp) - -rm -f src/m88k/$(am__dirstamp) - -rm -f src/metag/$(DEPDIR)/$(am__dirstamp) - -rm -f src/metag/$(am__dirstamp) - -rm -f src/microblaze/$(DEPDIR)/$(am__dirstamp) - -rm -f src/microblaze/$(am__dirstamp) - -rm -f src/mips/$(DEPDIR)/$(am__dirstamp) - -rm -f src/mips/$(am__dirstamp) - -rm -f src/moxie/$(DEPDIR)/$(am__dirstamp) - -rm -f src/moxie/$(am__dirstamp) - -rm -f src/or1k/$(DEPDIR)/$(am__dirstamp) - -rm -f src/or1k/$(am__dirstamp) - -rm -f src/pa/$(DEPDIR)/$(am__dirstamp) - -rm -f src/pa/$(am__dirstamp) - -rm -f src/powerpc/$(DEPDIR)/$(am__dirstamp) - -rm -f src/powerpc/$(am__dirstamp) - -rm -f src/riscv/$(DEPDIR)/$(am__dirstamp) - -rm -f src/riscv/$(am__dirstamp) - -rm -f src/s390/$(DEPDIR)/$(am__dirstamp) - -rm -f src/s390/$(am__dirstamp) - -rm -f src/sh/$(DEPDIR)/$(am__dirstamp) - -rm -f src/sh/$(am__dirstamp) - -rm -f src/sh64/$(DEPDIR)/$(am__dirstamp) - -rm -f src/sh64/$(am__dirstamp) - -rm -f src/sparc/$(DEPDIR)/$(am__dirstamp) - -rm -f src/sparc/$(am__dirstamp) - -rm -f src/tile/$(DEPDIR)/$(am__dirstamp) - -rm -f src/tile/$(am__dirstamp) - -rm -f src/vax/$(DEPDIR)/$(am__dirstamp) - -rm -f src/vax/$(am__dirstamp) - -rm -f src/wasm/$(DEPDIR)/$(am__dirstamp) - -rm -f src/wasm/$(am__dirstamp) - -rm -f src/x86/$(DEPDIR)/$(am__dirstamp) - -rm -f src/x86/$(am__dirstamp) - -rm -f src/xtensa/$(DEPDIR)/$(am__dirstamp) - -rm -f src/xtensa/$(am__dirstamp) - -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) + -$(am__rm_f) $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) + -$(am__rm_f) $(DISTCLEANFILES) + -$(am__rm_f) src/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/$(am__dirstamp) + -$(am__rm_f) src/aarch64/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/aarch64/$(am__dirstamp) + -$(am__rm_f) src/alpha/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/alpha/$(am__dirstamp) + -$(am__rm_f) src/arc/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/arc/$(am__dirstamp) + -$(am__rm_f) src/arm/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/arm/$(am__dirstamp) + -$(am__rm_f) src/avr32/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/avr32/$(am__dirstamp) + -$(am__rm_f) src/bfin/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/bfin/$(am__dirstamp) + -$(am__rm_f) src/cris/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/cris/$(am__dirstamp) + -$(am__rm_f) src/csky/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/csky/$(am__dirstamp) + -$(am__rm_f) src/frv/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/frv/$(am__dirstamp) + -$(am__rm_f) src/ia64/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/ia64/$(am__dirstamp) + -$(am__rm_f) src/kvx/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/kvx/$(am__dirstamp) + -$(am__rm_f) src/loongarch/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/loongarch/$(am__dirstamp) + -$(am__rm_f) src/m32r/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/m32r/$(am__dirstamp) + -$(am__rm_f) src/m68k/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/m68k/$(am__dirstamp) + -$(am__rm_f) src/m88k/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/m88k/$(am__dirstamp) + -$(am__rm_f) src/metag/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/metag/$(am__dirstamp) + -$(am__rm_f) src/microblaze/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/microblaze/$(am__dirstamp) + -$(am__rm_f) src/mips/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/mips/$(am__dirstamp) + -$(am__rm_f) src/moxie/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/moxie/$(am__dirstamp) + -$(am__rm_f) src/or1k/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/or1k/$(am__dirstamp) + -$(am__rm_f) src/pa/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/pa/$(am__dirstamp) + -$(am__rm_f) src/powerpc/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/powerpc/$(am__dirstamp) + -$(am__rm_f) src/riscv/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/riscv/$(am__dirstamp) + -$(am__rm_f) src/s390/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/s390/$(am__dirstamp) + -$(am__rm_f) src/sh/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/sh/$(am__dirstamp) + -$(am__rm_f) src/sh64/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/sh64/$(am__dirstamp) + -$(am__rm_f) src/sparc/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/sparc/$(am__dirstamp) + -$(am__rm_f) src/tile/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/tile/$(am__dirstamp) + -$(am__rm_f) src/vax/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/vax/$(am__dirstamp) + -$(am__rm_f) src/wasm/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/wasm/$(am__dirstamp) + -$(am__rm_f) src/x86/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/x86/$(am__dirstamp) + -$(am__rm_f) src/xtensa/$(DEPDIR)/$(am__dirstamp) + -$(am__rm_f) src/xtensa/$(am__dirstamp) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -1810,7 +1820,7 @@ clean-am: clean-generic clean-libtool clean-noinstLTLIBRARIES \ distclean: distclean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) - -rm -f src/$(DEPDIR)/closures.Plo + -rm -f src/$(DEPDIR)/closures.Plo -rm -f src/$(DEPDIR)/debug.Plo -rm -f src/$(DEPDIR)/java_raw_api.Plo -rm -f src/$(DEPDIR)/prep_cif.Plo @@ -1950,7 +1960,7 @@ installcheck-am: maintainer-clean: maintainer-clean-recursive -rm -f $(am__CONFIG_DISTCLEAN_FILES) -rm -rf $(top_srcdir)/autom4te.cache - -rm -f src/$(DEPDIR)/closures.Plo + -rm -f src/$(DEPDIR)/closures.Plo -rm -f src/$(DEPDIR)/debug.Plo -rm -f src/$(DEPDIR)/java_raw_api.Plo -rm -f src/$(DEPDIR)/prep_cif.Plo @@ -2061,28 +2071,28 @@ ps-am: uninstall-am: uninstall-pkgconfigDATA uninstall-toolexeclibLTLIBRARIES -.MAKE: $(am__recursive_targets) all install-am install-strip +.MAKE: $(am__recursive_targets) all check-am install-am install-strip .PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am \ - am--depfiles am--refresh check check-am clean clean-cscope \ - clean-generic clean-libtool clean-noinstLTLIBRARIES \ - clean-toolexeclibLTLIBRARIES cscope cscopelist-am ctags \ - ctags-am dist dist-all dist-bzip2 dist-gzip dist-hook \ - dist-lzip dist-shar dist-tarZ dist-xz dist-zip dist-zstd \ - distcheck distclean distclean-compile distclean-generic \ - distclean-hdr distclean-libtool distclean-tags distcleancheck \ - distdir distuninstallcheck dvi dvi-am html html-am info \ - info-am install install-am install-data install-data-am \ - install-dvi install-dvi-am install-exec install-exec-am \ - install-html install-html-am install-info install-info-am \ - install-man install-pdf install-pdf-am install-pkgconfigDATA \ - install-ps install-ps-am install-strip \ - install-toolexeclibLTLIBRARIES installcheck installcheck-am \ - installdirs installdirs-am maintainer-clean \ - maintainer-clean-generic mostlyclean mostlyclean-compile \ - mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \ - tags tags-am uninstall uninstall-am uninstall-pkgconfigDATA \ - uninstall-toolexeclibLTLIBRARIES + am--depfiles am--refresh check check-am check-local clean \ + clean-cscope clean-generic clean-libtool \ + clean-noinstLTLIBRARIES clean-toolexeclibLTLIBRARIES cscope \ + cscopelist-am ctags ctags-am dist dist-all dist-bzip2 \ + dist-bzip3 dist-gzip dist-hook dist-lzip dist-shar dist-tarZ \ + dist-xz dist-zip dist-zstd distcheck distclean \ + distclean-compile distclean-generic distclean-hdr \ + distclean-libtool distclean-tags distcleancheck distdir \ + distuninstallcheck dvi dvi-am html html-am info info-am \ + install install-am install-data install-data-am install-dvi \ + install-dvi-am install-exec install-exec-am install-html \ + install-html-am install-info install-info-am install-man \ + install-pdf install-pdf-am install-pkgconfigDATA install-ps \ + install-ps-am install-strip install-toolexeclibLTLIBRARIES \ + installcheck installcheck-am installdirs installdirs-am \ + maintainer-clean maintainer-clean-generic mostlyclean \ + mostlyclean-compile mostlyclean-generic mostlyclean-libtool \ + pdf pdf-am ps ps-am tags tags-am uninstall uninstall-am \ + uninstall-pkgconfigDATA uninstall-toolexeclibLTLIBRARIES .PRECIOUS: Makefile @@ -2090,6 +2100,9 @@ uninstall-am: uninstall-pkgconfigDATA uninstall-toolexeclibLTLIBRARIES # Alias required by AX_ENABLE_BUILDDIR / config-ml .PHONY: all-configured all-configured: all + +check-local: src/closures.lo + $(SHELL) $(srcdir)/testsuite/check-dlmalloc-static.sh "$(NM)" src/closures.lo @LIBFFI_BUILD_VERSIONED_SHLIB_SUN_TRUE@@LIBFFI_BUILD_VERSIONED_SHLIB_TRUE@libffi.map-sun : libffi.map $(top_srcdir)/make_sunver.pl \ @LIBFFI_BUILD_VERSIONED_SHLIB_SUN_TRUE@@LIBFFI_BUILD_VERSIONED_SHLIB_TRUE@ $(libffi_la_OBJECTS) $(libffi_la_LIBADD) @LIBFFI_BUILD_VERSIONED_SHLIB_SUN_TRUE@@LIBFFI_BUILD_VERSIONED_SHLIB_TRUE@ perl $(top_srcdir)/make_sunver.pl libffi.map \ @@ -2102,8 +2115,14 @@ libffi.map: $(top_srcdir)/libffi.map.in -E -x assembler-with-cpp -o $@ $(top_srcdir)/libffi.map.in dist-hook: - d=`(cd $(distdir); pwd)`; (cd doc; make pdf; cp *.pdf $$d/doc) +@BUILD_DOCS_TRUE@ d=`(cd $(distdir); pwd)`; \ +@BUILD_DOCS_TRUE@ if (cd doc && make pdf && cp *.pdf $$d/doc); then \ +@BUILD_DOCS_TRUE@ :; \ +@BUILD_DOCS_TRUE@ else \ +@BUILD_DOCS_TRUE@ echo "dist-hook: PDF manual not built (no TeX engine?), omitting it from the dist"; \ +@BUILD_DOCS_TRUE@ fi if [ -d $(top_srcdir)/.git ] ; then (cd $(top_srcdir); git log --no-decorate) ; else echo 'See git log for history.' ; fi > $(distdir)/ChangeLog + rm -f $(distdir)/README.md; \ s=`awk '/was released on/{ print NR; exit}' $(top_srcdir)/README.md`; \ if [ -n "$$s" ]; then tail -n +$$(($$s-1)) $(top_srcdir)/README.md; else cat $(top_srcdir)/README.md; fi > $(distdir)/README.md @@ -2113,3 +2132,10 @@ dist-hook: # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: + +# Tell GNU make to disable its built-in pattern rules. +%:: %,v +%:: RCS/%,v +%:: RCS/% +%:: s.% +%:: SCCS/s.% diff --git a/deps/libffi/README.md b/deps/libffi/README.md index 797d0fd9aa8e..efc73d71566b 100644 --- a/deps/libffi/README.md +++ b/deps/libffi/README.md @@ -1,5 +1,5 @@ -libffi-3.7.1 was released on July 10, 2026. +libffi-3.8.1 was released on November 14, 2026. What is libffi? @@ -201,6 +201,45 @@ History See the git log for details at http://github.com/libffi/libffi. + 3.8.1 November-14-2026 + Improve ABI conformance and test coverage for complex-number + calls, closures, and small aggregates across ARM, x86, PowerPC, + MIPS, RISC-V, LoongArch, and SPARC. + aarch64/arm: fix big-endian closures receiving garbage sub-word + integer and float arguments, and big-endian sub-word and float + return values (#1012, closes #1011, #675). Correct the stack + offset of a by-value composite larger than 16 bytes and the + AAPCS64 HFA/HVA detection (GHSA-h52h-3759-xqm4, + GHSA-vg77-j273-647r). + x86-64: return a single-long-double struct in %st0 like a bare + long double (#1058); copy the upper half of 16-byte vector + arguments in reusable call plans; and reject vector types whose + ABI is undefined, where GCC and Clang disagree, instead of + marshalling them the wrong way (GHSA-5pc3-hr6f-q3mm). + powerpc64: fix _Complex long double when the ABI's long double is + 64 bits (e.g. -mlong-double-64 or musl). + s390x: pass 128-bit integer closure arguments by reference, like + complex types, instead of leaving the value pointer + uninitialized (GHSA-wf8m-qr3x-cch4). + RISC-V: ignore the caller's return buffer for void calls. + MIPS: emit CFI in the N32/N64 assembly so unwinding works through + libffi frames (#1063). + wasm: correct heap accesses at or above 2 GiB (#1062), make + closures work with stack switching, and declare the stack-helper + dependencies in EM_JS_DEPS for newer Emscripten (#1019). + Closures and trampolines: fail allocation gracefully when the + page-size lookup fails (#1015) and bound the executable-mmap + retry loop (#1055). Fix a Darwin trampoline-table use-after-free + (GHSA-23hx-9rxv-9qfp), a Linux static-trampoline path mix-up that + could map the wrong file as code (GHSA-fq46-69xf-x5gf), and a + raw-API closure that passed the wrong handler data under static + trampolines (GHSA-w6j9-w53f-2857). + Keep the bundled dlmalloc symbols static so they cannot clash with + an application's allocator, and emit subsections_via_symbols on + Apple platforms for linker dead-stripping (#1017). + Build and packaging: honor an explicit --enable-docs, respect every + --libdir spelling, and keep CCASFLAGS in sync with CFLAGS (#1060). + 3.8.0 August-8-2026 Add FFI_TYPE_VECTOR (SIMD) type support with libffi-computed layout, for aarch64 and x86-64 (#1000, closes #773). diff --git a/deps/libffi/acinclude.m4 b/deps/libffi/acinclude.m4 index 9624bbed0bdf..09dec37f4ba2 100644 --- a/deps/libffi/acinclude.m4 +++ b/deps/libffi/acinclude.m4 @@ -334,14 +334,14 @@ libat_min_gnu_ld_version=21400 # Change "yes" into either "no" or a style name. if test $enable_symvers != no && test $libat_shared_libgcc = yes; then if test $with_gnu_ld = yes; then - if test $libat_gnu_ld_version -ge $libat_min_gnu_ld_version ; then - enable_symvers=gnu - elif test $libat_ld_is_gold = yes ; then + if test $libat_ld_is_gold = yes ; then enable_symvers=gnu elif test $libat_ld_is_lld = yes ; then enable_symvers=gnu elif test $libat_ld_is_mold = yes ; then enable_symvers=gnu + elif test $libat_gnu_ld_version -ge $libat_min_gnu_ld_version ; then + enable_symvers=gnu else # The right tools, the right setup, but too old. Fallbacks? AC_MSG_WARN(=== Linker version $libat_gnu_ld_version is too old for) diff --git a/deps/libffi/aclocal.m4 b/deps/libffi/aclocal.m4 index de83b0ad0aa4..5ab9ad2daa13 100644 --- a/deps/libffi/aclocal.m4 +++ b/deps/libffi/aclocal.m4 @@ -1,6 +1,6 @@ -# generated automatically by aclocal 1.16.5 -*- Autoconf -*- +# generated automatically by aclocal 1.18.1 -*- Autoconf -*- -# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# Copyright (C) 1996-2025 Free Software Foundation, Inc. # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -14,15 +14,15 @@ m4_ifndef([AC_CONFIG_MACRO_DIRS], [m4_defun([_AM_CONFIG_MACRO_DIRS], [])m4_defun([AC_CONFIG_MACRO_DIRS], [_AM_CONFIG_MACRO_DIRS($@)])]) m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl -m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.71],, -[m4_warning([this file was generated for autoconf 2.71. +m4_if(m4_defn([AC_AUTOCONF_VERSION]), [2.72],, +[m4_warning([this file was generated for autoconf 2.72. You have another version of autoconf. It may work, but is not guaranteed to. If you have problems, you may need to regenerate the build system entirely. To do so, use the procedure documented by the package, typically 'autoreconf'.])]) # ltdl.m4 - Configure ltdl for the target system. -*-Autoconf-*- # -# Copyright (C) 1999-2008, 2011-2019, 2021-2022 Free Software +# Copyright (C) 1999-2008, 2011-2019, 2021-2024 Free Software # Foundation, Inc. # Written by Thomas Tanner, 1999 # @@ -30,7 +30,7 @@ To do so, use the procedure documented by the package, typically 'autoreconf'.]) # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. -# serial 21 LTDL_INIT +# serial 24 LTDL_INIT # LT_CONFIG_LTDL_DIR(DIRECTORY, [LTDL-MODE]) # ------------------------------------------ @@ -457,7 +457,8 @@ esac m4_ifdef([AM_CONDITIONAL], [AM_CONDITIONAL(INSTALL_LTDL, test no != "${enable_ltdl_install-no}") - AM_CONDITIONAL(CONVENIENCE_LTDL, test no != "${enable_ltdl_convenience-no}")]) + AM_CONDITIONAL(CONVENIENCE_LTDL, test no != "${enable_ltdl_convenience-no}") + AM_CONDITIONAL(LTARGZH_EXISTS, test -n "$LT_ARGZ_H")]) ])# _LT_ENABLE_INSTALL @@ -488,9 +489,6 @@ AC_CACHE_CHECK([whether deplibs are loaded by dlopen], ;; esac ;; - bitrig*) - lt_cv_sys_dlopen_deplibs=yes - ;; darwin*) # Assuming the user has installed a libdl from somewhere, this is true # If you are looking for one http://www.opendarwin.org/projects/dlcompat @@ -519,6 +517,9 @@ AC_CACHE_CHECK([whether deplibs are loaded by dlopen], # at 6.2 and later dlopen does load deplibs. lt_cv_sys_dlopen_deplibs=yes ;; + *-mlibc) + lt_cv_sys_dlopen_deplibs=yes + ;; netbsd* | netbsdelf*-gnu) lt_cv_sys_dlopen_deplibs=yes ;; @@ -735,7 +736,7 @@ darwin[[1567]].*) beos*) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}load_add_on.la" ;; -cygwin* | mingw* | pw32*) +cygwin* | mingw* | windows* | pw32*) AC_CHECK_DECLS([cygwin_conv_path], [], [], [[#include <sys/cygwin.h>]]) LT_DLLOADERS="$LT_DLLOADERS ${lt_dlopen_dir+$lt_dlopen_dir/}loadlibrary.la" ;; @@ -783,7 +784,7 @@ AC_CACHE_CHECK([for _ prefix in compiled symbols], [lt_cv_sys_symbol_underscore=no cat > conftest.$ac_ext <<_LT_EOF void nm_test_func(){} -int main(){nm_test_func;return 0;} +int main(void){nm_test_func;return 0;} _LT_EOF if AC_TRY_EVAL(ac_compile); then # Now try to grab the symbols. @@ -887,7 +888,7 @@ _LT_EOF # define RTLD_NOW 0 # endif #endif -int main () { +int main (void) { void *handle = dlopen ("`pwd`/$libname$libltdl_cv_shlibext", RTLD_GLOBAL|RTLD_NOW); int status = $libltdl_dlunknown; if (handle) { @@ -931,7 +932,7 @@ AU_ALIAS([AC_LTDL_DLSYM_USCORE], [LT_FUNC_DLSYM_USCORE]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([AC_LTDL_DLSYM_USCORE], []) -# Copyright (C) 2002-2021 Free Software Foundation, Inc. +# Copyright (C) 2002-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -943,10 +944,10 @@ dnl AC_DEFUN([AC_LTDL_DLSYM_USCORE], []) # generated from the m4 files accompanying Automake X.Y. # (This private macro should not be called outside this file.) AC_DEFUN([AM_AUTOMAKE_VERSION], -[am__api_version='1.16' +[am__api_version='1.18' dnl Some users find AM_AUTOMAKE_VERSION and mistake it for a way to dnl require some minimum version. Point them to the right macro. -m4_if([$1], [1.16.5], [], +m4_if([$1], [1.18.1], [], [AC_FATAL([Do not call $0, use AM_INIT_AUTOMAKE([$1]).])])dnl ]) @@ -962,14 +963,14 @@ m4_define([_AM_AUTOCONF_VERSION], []) # Call AM_AUTOMAKE_VERSION and AM_AUTOMAKE_VERSION so they can be traced. # This function is AC_REQUIREd by AM_INIT_AUTOMAKE. AC_DEFUN([AM_SET_CURRENT_AUTOMAKE_VERSION], -[AM_AUTOMAKE_VERSION([1.16.5])dnl +[AM_AUTOMAKE_VERSION([1.18.1])dnl m4_ifndef([AC_AUTOCONF_VERSION], [m4_copy([m4_PACKAGE_VERSION], [AC_AUTOCONF_VERSION])])dnl _AM_AUTOCONF_VERSION(m4_defn([AC_AUTOCONF_VERSION]))]) # Figure out how to run the assembler. -*- Autoconf -*- -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -989,7 +990,7 @@ _AM_IF_OPTION([no-dependencies],, [_AM_DEPENDENCIES([CCAS])])dnl # AM_AUX_DIR_EXPAND -*- Autoconf -*- -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1041,7 +1042,7 @@ am_aux_dir=`cd "$ac_aux_dir" && pwd` # AM_CONDITIONAL -*- Autoconf -*- -# Copyright (C) 1997-2021 Free Software Foundation, Inc. +# Copyright (C) 1997-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1072,7 +1073,7 @@ AC_CONFIG_COMMANDS_PRE( Usually this means the macro was only invoked conditionally.]]) fi])]) -# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# Copyright (C) 1999-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1204,7 +1205,7 @@ AC_CACHE_CHECK([dependency style of $depcc], # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. - # When given -MP, icc 7.0 and 7.1 complain thusly: + # When given -MP, icc 7.0 and 7.1 complain thus: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported @@ -1263,7 +1264,7 @@ _AM_SUBST_NOTMAKE([am__nodep])dnl # Generate code to set up dependency tracking. -*- Autoconf -*- -# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# Copyright (C) 1999-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1331,7 +1332,7 @@ AC_DEFUN([AM_OUTPUT_DEPENDENCY_COMMANDS], # Do all the work for Automake. -*- Autoconf -*- -# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# Copyright (C) 1996-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1431,8 +1432,9 @@ AC_REQUIRE([AC_PROG_AWK])dnl AC_REQUIRE([AC_PROG_MAKE_SET])dnl AC_REQUIRE([AM_SET_LEADING_DOT])dnl _AM_IF_OPTION([tar-ustar], [_AM_PROG_TAR([ustar])], - [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], - [_AM_PROG_TAR([v7])])]) + [_AM_IF_OPTION([tar-pax], [_AM_PROG_TAR([pax])], + [_AM_IF_OPTION([tar-v7], [_AM_PROG_TAR([v7])], + [_AM_PROG_TAR([ustar])])])]) _AM_IF_OPTION([no-dependencies],, [AC_PROVIDE_IFELSE([AC_PROG_CC], [_AM_DEPENDENCIES([CC])], @@ -1465,7 +1467,7 @@ if test -z "$CSCOPE"; then fi AC_SUBST([CSCOPE]) -AC_REQUIRE([AM_SILENT_RULES])dnl +AC_REQUIRE([_AM_SILENT_RULES])dnl dnl The testsuite driver may need to know about EXEEXT, so add the dnl 'am__EXEEXT' conditional if _AM_COMPILER_EXEEXT was seen. This dnl macro is hooked onto _AC_COMPILER_EXEEXT early, see below. @@ -1473,47 +1475,9 @@ AC_CONFIG_COMMANDS_PRE(dnl [m4_provide_if([_AM_COMPILER_EXEEXT], [AM_CONDITIONAL([am__EXEEXT], [test -n "$EXEEXT"])])])dnl -# POSIX will say in a future version that running "rm -f" with no argument -# is OK; and we want to be able to make that assumption in our Makefile -# recipes. So use an aggressive probe to check that the usage we want is -# actually supported "in the wild" to an acceptable degree. -# See automake bug#10828. -# To make any issue more visible, cause the running configure to be aborted -# by default if the 'rm' program in use doesn't match our expectations; the -# user can still override this though. -if rm -f && rm -fr && rm -rf; then : OK; else - cat >&2 <<'END' -Oops! - -Your 'rm' program seems unable to run without file operands specified -on the command line, even when the '-f' option is present. This is contrary -to the behaviour of most rm programs out there, and not conforming with -the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542> - -Please tell bug-automake@gnu.org about your system, including the value -of your $PATH and any error possibly output before this message. This -can help us improve future automake versions. - -END - if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then - echo 'Configuration will proceed anyway, since you have set the' >&2 - echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 - echo >&2 - else - cat >&2 <<'END' -Aborting the configuration process, to ensure you take notice of the issue. - -You can download and install GNU coreutils to get an 'rm' implementation -that behaves properly: <https://www.gnu.org/software/coreutils/>. - -If you want to complete the configuration process using your problematic -'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM -to "yes", and re-run configure. +AC_REQUIRE([_AM_PROG_RM_F]) +AC_REQUIRE([_AM_PROG_XARGS_N]) -END - AC_MSG_ERROR([Your 'rm' program is bad, sorry.]) - fi -fi dnl The trailing newline in this macro's definition is deliberate, for dnl backward compatibility and to allow trailing 'dnl'-style comments dnl after the AM_INIT_AUTOMAKE invocation. See automake bug#16841. @@ -1546,7 +1510,7 @@ for _am_header in $config_headers :; do done echo "timestamp for $_am_arg" >`AS_DIRNAME(["$_am_arg"])`/stamp-h[]$_am_stamp_count]) -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1567,7 +1531,7 @@ if test x"${install_sh+set}" != xset; then fi AC_SUBST([install_sh])]) -# Copyright (C) 2003-2021 Free Software Foundation, Inc. +# Copyright (C) 2003-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1589,7 +1553,7 @@ AC_SUBST([am__leading_dot])]) # Add --enable-maintainer-mode option to configure. -*- Autoconf -*- # From Jim Meyering -# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# Copyright (C) 1996-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1624,7 +1588,7 @@ AC_MSG_CHECKING([whether to enable maintainer-specific portions of Makefiles]) # Check to see how 'make' treats includes. -*- Autoconf -*- -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1667,7 +1631,7 @@ AC_SUBST([am__quote])]) # Fake the existence of programs that GNU maintainers use. -*- Autoconf -*- -# Copyright (C) 1997-2021 Free Software Foundation, Inc. +# Copyright (C) 1997-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1701,7 +1665,7 @@ fi # Helper functions for option handling. -*- Autoconf -*- -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1730,7 +1694,7 @@ AC_DEFUN([_AM_SET_OPTIONS], AC_DEFUN([_AM_IF_OPTION], [m4_ifset(_AM_MANGLE_OPTION([$1]), [$2], [$3])]) -# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# Copyright (C) 1999-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1762,7 +1726,10 @@ AC_CACHE_CHECK( break fi done - rm -f core conftest* + # aligned with autoconf, so not including core; see bug#72225. + rm -f -r a.out a.exe b.out conftest.$ac_ext conftest.$ac_objext \ + conftest.dSYM conftest1.$ac_ext conftest1.$ac_objext conftest1.dSYM \ + conftest2.$ac_ext conftest2.$ac_objext conftest2.dSYM unset am_i]) if test "$am_cv_prog_cc_c_o" != yes; then # Losing compiler, so override with the script. @@ -1777,7 +1744,23 @@ AC_LANG_POP([C])]) # For backward compatibility. AC_DEFUN_ONCE([AM_PROG_CC_C_O], [AC_REQUIRE([AC_PROG_CC])]) -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# Copyright (C) 2022-2025 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_PROG_RM_F +# --------------- +# Check whether 'rm -f' without any arguments works. +# https://bugs.gnu.org/10828 +AC_DEFUN([_AM_PROG_RM_F], +[am__rm_f_notfound= +AS_IF([(rm -f && rm -fr && rm -rf) 2>/dev/null], [], [am__rm_f_notfound='""']) +AC_SUBST(am__rm_f_notfound) +]) + +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1796,26 +1779,181 @@ AC_DEFUN([AM_RUN_LOG], # Check to make sure that the build environment is sane. -*- Autoconf -*- -# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# Copyright (C) 1996-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. +# _AM_SLEEP_FRACTIONAL_SECONDS +# ---------------------------- +AC_DEFUN([_AM_SLEEP_FRACTIONAL_SECONDS], [dnl +AC_CACHE_CHECK([whether sleep supports fractional seconds], + am_cv_sleep_fractional_seconds, [dnl +AS_IF([sleep 0.001 2>/dev/null], [am_cv_sleep_fractional_seconds=yes], + [am_cv_sleep_fractional_seconds=no]) +])]) + +# _AM_FILESYSTEM_TIMESTAMP_RESOLUTION +# ----------------------------------- +# Determine the filesystem's resolution for file modification +# timestamps. The coarsest we know of is FAT, with a resolution +# of only two seconds, even with the most recent "exFAT" extensions. +# The finest (e.g. ext4 with large inodes, XFS, ZFS) is one +# nanosecond, matching clock_gettime. However, it is probably not +# possible to delay execution of a shell script for less than one +# millisecond, due to process creation overhead and scheduling +# granularity, so we don't check for anything finer than that. (See below.) +AC_DEFUN([_AM_FILESYSTEM_TIMESTAMP_RESOLUTION], [dnl +AC_REQUIRE([_AM_SLEEP_FRACTIONAL_SECONDS]) +AC_CACHE_CHECK([filesystem timestamp resolution], + am_cv_filesystem_timestamp_resolution, [dnl +# Default to the worst case. +am_cv_filesystem_timestamp_resolution=2 + +# Only try to go finer than 1 sec if sleep can do it. +# Don't try 1 sec, because if 0.01 sec and 0.1 sec don't work, +# - 1 sec is not much of a win compared to 2 sec, and +# - it takes 2 seconds to perform the test whether 1 sec works. +# +# Instead, just use the default 2s on platforms that have 1s resolution, +# accept the extra 1s delay when using $sleep in the Automake tests, in +# exchange for not incurring the 2s delay for running the test for all +# packages. +# +am_try_resolutions= +if test "$am_cv_sleep_fractional_seconds" = yes; then + # Even a millisecond often causes a bunch of false positives, + # so just try a hundredth of a second. The time saved between .001 and + # .01 is not terribly consequential. + am_try_resolutions="0.01 0.1 $am_try_resolutions" +fi + +# In order to catch current-generation FAT out, we must *modify* files +# that already exist; the *creation* timestamp is finer. Use names +# that make ls -t sort them differently when they have equal +# timestamps than when they have distinct timestamps, keeping +# in mind that ls -t prints the *newest* file first. +rm -f conftest.ts? +: > conftest.ts1 +: > conftest.ts2 +: > conftest.ts3 + +# Make sure ls -t actually works. Do 'set' in a subshell so we don't +# clobber the current shell's arguments. (Outer-level square brackets +# are removed by m4; they're present so that m4 does not expand +# <dollar><star>; be careful, easy to get confused.) +if ( + set X `[ls -t conftest.ts[12]]` && + { + test "$[]*" != "X conftest.ts1 conftest.ts2" || + test "$[]*" != "X conftest.ts2 conftest.ts1"; + } +); then :; else + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + _AS_ECHO_UNQUOTED( + ["Bad output from ls -t: \"`[ls -t conftest.ts[12]]`\""], + [AS_MESSAGE_LOG_FD]) + AC_MSG_FAILURE([ls -t produces unexpected output. +Make sure there is not a broken ls alias in your environment.]) +fi + +for am_try_res in $am_try_resolutions; do + # Any one fine-grained sleep might happen to cross the boundary + # between two values of a coarser actual resolution, but if we do + # two fine-grained sleeps in a row, at least one of them will fall + # entirely within a coarse interval. + echo alpha > conftest.ts1 + sleep $am_try_res + echo beta > conftest.ts2 + sleep $am_try_res + echo gamma > conftest.ts3 + + # We assume that 'ls -t' will make use of high-resolution + # timestamps if the operating system supports them at all. + if (set X `ls -t conftest.ts?` && + test "$[]2" = conftest.ts3 && + test "$[]3" = conftest.ts2 && + test "$[]4" = conftest.ts1); then + # + # Ok, ls -t worked. If we're at a resolution of 1 second, we're done, + # because we don't need to test make. + make_ok=true + if test $am_try_res != 1; then + # But if we've succeeded so far with a subsecond resolution, we + # have one more thing to check: make. It can happen that + # everything else supports the subsecond mtimes, but make doesn't; + # notably on macOS, which ships make 3.81 from 2006 (the last one + # released under GPLv2). https://bugs.gnu.org/68808 + # + # We test $MAKE if it is defined in the environment, else "make". + # It might get overridden later, but our hope is that in practice + # it does not matter: it is the system "make" which is (by far) + # the most likely to be broken, whereas if the user overrides it, + # probably they did so with a better, or at least not worse, make. + # https://lists.gnu.org/archive/html/automake/2024-06/msg00051.html + # + # Create a Makefile (real tab character here): + rm -f conftest.mk + echo 'conftest.ts1: conftest.ts2' >conftest.mk + echo ' touch conftest.ts2' >>conftest.mk + # + # Now, running + # touch conftest.ts1; touch conftest.ts2; make + # should touch ts1 because ts2 is newer. This could happen by luck, + # but most often, it will fail if make's support is insufficient. So + # test for several consecutive successes. + # + # (We reuse conftest.ts[12] because we still want to modify existing + # files, not create new ones, per above.) + n=0 + make=${MAKE-make} + until test $n -eq 3; do + echo one > conftest.ts1 + sleep $am_try_res + echo two > conftest.ts2 # ts2 should now be newer than ts1 + if $make -f conftest.mk | grep 'up to date' >/dev/null; then + make_ok=false + break # out of $n loop + fi + n=`expr $n + 1` + done + fi + # + if $make_ok; then + # Everything we know to check worked out, so call this resolution good. + am_cv_filesystem_timestamp_resolution=$am_try_res + break # out of $am_try_res loop + fi + # Otherwise, we'll go on to check the next resolution. + fi +done +rm -f conftest.ts? +# (end _am_filesystem_timestamp_resolution) +])]) + # AM_SANITY_CHECK # --------------- AC_DEFUN([AM_SANITY_CHECK], -[AC_MSG_CHECKING([whether build environment is sane]) +[AC_REQUIRE([_AM_FILESYSTEM_TIMESTAMP_RESOLUTION]) +# This check should not be cached, as it may vary across builds of +# different projects. +AC_MSG_CHECKING([whether build environment is sane]) # Reject unsafe characters in $srcdir or the absolute working directory # name. Accept space and tab only in the latter. am_lf=' ' case `pwd` in *[[\\\"\#\$\&\'\`$am_lf]]*) + AC_MSG_RESULT([no]) AC_MSG_ERROR([unsafe absolute working directory name]);; esac case $srcdir in *[[\\\"\#\$\&\'\`$am_lf\ \ ]]*) + AC_MSG_RESULT([no]) AC_MSG_ERROR([unsafe srcdir value: '$srcdir']);; esac @@ -1824,49 +1962,40 @@ esac # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). -if ( - am_has_slept=no - for am_try in 1 2; do - echo "timestamp, slept: $am_has_slept" > conftest.file - set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` - if test "$[*]" = "X"; then - # -L didn't work. - set X `ls -t "$srcdir/configure" conftest.file` - fi - if test "$[*]" != "X $srcdir/configure conftest.file" \ - && test "$[*]" != "X conftest.file $srcdir/configure"; then - - # If neither matched, then we have a broken ls. This can happen - # if, for instance, CONFIG_SHELL is bash and it inherits a - # broken ls alias from the environment. This has actually - # happened. Such a system could not be considered "sane". - AC_MSG_ERROR([ls -t appears to fail. Make sure there is not a broken - alias in your environment]) - fi - if test "$[2]" = conftest.file || test $am_try -eq 2; then - break - fi - # Just in case. - sleep 1 - am_has_slept=yes - done - test "$[2]" = conftest.file - ) -then - # Ok. - : -else - AC_MSG_ERROR([newly created file is older than distributed files! +am_build_env_is_sane=no +am_has_slept=no +rm -f conftest.file +for am_try in 1 2; do + echo "timestamp, slept: $am_has_slept" > conftest.file + if ( + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$[]*" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + test "$[]2" = conftest.file + ); then + am_build_env_is_sane=yes + break + fi + # Just in case. + sleep "$am_cv_filesystem_timestamp_resolution" + am_has_slept=yes +done + +AC_MSG_RESULT([$am_build_env_is_sane]) +if test "$am_build_env_is_sane" = no; then + AC_MSG_ERROR([newly created file is older than distributed files! Check your system clock]) fi -AC_MSG_RESULT([yes]) + # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= -if grep 'slept: no' conftest.file >/dev/null 2>&1; then - ( sleep 1 ) & +AS_IF([test -e conftest.file || grep 'slept: no' conftest.file >/dev/null 2>&1],, [dnl + ( sleep "$am_cv_filesystem_timestamp_resolution" ) & am_sleep_pid=$! -fi +]) AC_CONFIG_COMMANDS_PRE( [AC_MSG_CHECKING([that generated files are newer than configure]) if test -n "$am_sleep_pid"; then @@ -1877,18 +2006,18 @@ AC_CONFIG_COMMANDS_PRE( rm -f conftest.file ]) -# Copyright (C) 2009-2021 Free Software Foundation, Inc. +# Copyright (C) 2009-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, # with or without modifications, as long as this notice is preserved. -# AM_SILENT_RULES([DEFAULT]) -# -------------------------- -# Enable less verbose build rules; with the default set to DEFAULT -# ("yes" being less verbose, "no" or empty being verbose). -AC_DEFUN([AM_SILENT_RULES], -[AC_ARG_ENABLE([silent-rules], [dnl +# _AM_SILENT_RULES +# ---------------- +# Enable less verbose build rules support. +AC_DEFUN([_AM_SILENT_RULES], +[AM_DEFAULT_VERBOSITY=1 +AC_ARG_ENABLE([silent-rules], [dnl AS_HELP_STRING( [--enable-silent-rules], [less verbose build output (undo: "make V=1")]) @@ -1896,11 +2025,6 @@ AS_HELP_STRING( [--disable-silent-rules], [verbose build output (undo: "make V=0")])dnl ]) -case $enable_silent_rules in @%:@ ((( - yes) AM_DEFAULT_VERBOSITY=0;; - no) AM_DEFAULT_VERBOSITY=1;; - *) AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1]);; -esac dnl dnl A few 'make' implementations (e.g., NonStop OS and NextStep) dnl do not support nested variable expansions. @@ -1919,14 +2043,6 @@ am__doit: else am_cv_make_support_nested_variables=no fi]) -if test $am_cv_make_support_nested_variables = yes; then - dnl Using '$V' instead of '$(V)' breaks IRIX make. - AM_V='$(V)' - AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' -else - AM_V=$AM_DEFAULT_VERBOSITY - AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY -fi AC_SUBST([AM_V])dnl AM_SUBST_NOTMAKE([AM_V])dnl AC_SUBST([AM_DEFAULT_V])dnl @@ -1935,9 +2051,37 @@ AC_SUBST([AM_DEFAULT_VERBOSITY])dnl AM_BACKSLASH='\' AC_SUBST([AM_BACKSLASH])dnl _AM_SUBST_NOTMAKE([AM_BACKSLASH])dnl +dnl Delay evaluation of AM_DEFAULT_VERBOSITY to the end to allow multiple calls +dnl to AM_SILENT_RULES to change the default value. +AC_CONFIG_COMMANDS_PRE([dnl +case $enable_silent_rules in @%:@ ((( + yes) AM_DEFAULT_VERBOSITY=0;; + no) AM_DEFAULT_VERBOSITY=1;; +esac +if test $am_cv_make_support_nested_variables = yes; then + dnl Using '$V' instead of '$(V)' breaks IRIX make. + AM_V='$(V)' + AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' +else + AM_V=$AM_DEFAULT_VERBOSITY + AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY +fi +])dnl ]) -# Copyright (C) 2001-2021 Free Software Foundation, Inc. +# AM_SILENT_RULES([DEFAULT]) +# -------------------------- +# Set the default verbosity level to DEFAULT ("yes" being less verbose, "no" or +# empty being verbose). +AC_DEFUN([AM_SILENT_RULES], +[AC_REQUIRE([_AM_SILENT_RULES]) +AM_DEFAULT_VERBOSITY=m4_if([$1], [yes], [0], [1])m4_newline +dnl We intentionally force a newline after the assignment, since a) nothing +dnl good can come of more text following, and b) that was the behavior +dnl before 1.17. See https://bugs.gnu.org/72267. +]) + +# Copyright (C) 2001-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1965,7 +2109,7 @@ fi INSTALL_STRIP_PROGRAM="\$(install_sh) -c -s" AC_SUBST([INSTALL_STRIP_PROGRAM])]) -# Copyright (C) 2006-2021 Free Software Foundation, Inc. +# Copyright (C) 2006-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -1984,7 +2128,7 @@ AC_DEFUN([AM_SUBST_NOTMAKE], [_AM_SUBST_NOTMAKE($@)]) # Check how to create a tarball. -*- Autoconf -*- -# Copyright (C) 2004-2021 Free Software Foundation, Inc. +# Copyright (C) 2004-2025 Free Software Foundation, Inc. # # This file is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -2030,15 +2174,19 @@ m4_if([$1], [v7], am_uid=`id -u || echo unknown` am_gid=`id -g || echo unknown` AC_MSG_CHECKING([whether UID '$am_uid' is supported by ustar format]) - if test $am_uid -le $am_max_uid; then - AC_MSG_RESULT([yes]) + if test x$am_uid = xunknown; then + AC_MSG_WARN([ancient id detected; assuming current UID is ok, but dist-ustar might not work]) + elif test $am_uid -le $am_max_uid; then + AC_MSG_RESULT([yes]) else - AC_MSG_RESULT([no]) - _am_tools=none + AC_MSG_RESULT([no]) + _am_tools=none fi AC_MSG_CHECKING([whether GID '$am_gid' is supported by ustar format]) - if test $am_gid -le $am_max_gid; then - AC_MSG_RESULT([yes]) + if test x$gm_gid = xunknown; then + AC_MSG_WARN([ancient id detected; assuming current GID is ok, but dist-ustar might not work]) + elif test $am_gid -le $am_max_gid; then + AC_MSG_RESULT([yes]) else AC_MSG_RESULT([no]) _am_tools=none @@ -2115,6 +2263,26 @@ AC_SUBST([am__tar]) AC_SUBST([am__untar]) ]) # _AM_PROG_TAR +# Copyright (C) 2022-2025 Free Software Foundation, Inc. +# +# This file is free software; the Free Software Foundation +# gives unlimited permission to copy and/or distribute it, +# with or without modifications, as long as this notice is preserved. + +# _AM_PROG_XARGS_N +# ---------------- +# Check whether 'xargs -n' works. It should work everywhere, so the fallback +# is not optimized at all as we never expect to use it. +AC_DEFUN([_AM_PROG_XARGS_N], +[AC_CACHE_CHECK([xargs -n works], am_cv_xargs_n_works, [dnl +AS_IF([test "`echo 1 2 3 | xargs -n2 echo`" = "1 2 +3"], [am_cv_xargs_n_works=yes], [am_cv_xargs_n_works=no])]) +AS_IF([test "$am_cv_xargs_n_works" = yes], [am__xargs_n='xargs -n'], [dnl + am__xargs_n='am__xargs_n () { shift; sed "s/ /\\n/g" | while read am__xargs_n_arg; do "$@" "$am__xargs_n_arg"; done; }' +])dnl +AC_SUBST(am__xargs_n) +]) + m4_include([m4/asmcfi.m4]) m4_include([m4/ax_cc_maxopt.m4]) m4_include([m4/ax_cflags_warn_all.m4]) diff --git a/deps/libffi/compile b/deps/libffi/compile index df363c8fbfbc..02ff093c33c7 100755 --- a/deps/libffi/compile +++ b/deps/libffi/compile @@ -1,9 +1,9 @@ #! /bin/sh # Wrapper for compilers which do not understand '-c -o'. -scriptversion=2018-03-07.03; # UTC +scriptversion=2025-06-18.21; # UTC -# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# Copyright (C) 1999-2025 Free Software Foundation, Inc. # Written by Tom Tromey <tromey@cygnus.com>. # # This program is free software; you can redistribute it and/or modify @@ -37,11 +37,11 @@ IFS=" "" $nl" file_conv= -# func_file_conv build_file lazy +# func_file_conv build_file unneeded_conversions # Convert a $build file to $host form and store it in $file # Currently only supports Windows hosts. If the determined conversion -# type is listed in (the comma separated) LAZY, no conversion will -# take place. +# type is listed in (the comma separated) UNNEEDED_CONVERSIONS, no +# conversion will take place. func_file_conv () { file=$1 @@ -51,9 +51,20 @@ func_file_conv () # lazily determine how to convert abs files case `uname -s` in MINGW*) - file_conv=mingw + if test -n "$MSYSTEM" && (cygpath --version) >/dev/null 2>&1; then + # MSYS2 environment. + file_conv=cygwin + else + # Original MinGW environment. + file_conv=mingw + fi ;; - CYGWIN* | MSYS*) + MSYS*) + # Old MSYS environment, or MSYS2 with 32-bit MSYS2 shell. + file_conv=cygwin + ;; + CYGWIN*) + # Cygwin environment. file_conv=cygwin ;; *) @@ -63,12 +74,14 @@ func_file_conv () fi case $file_conv/,$2, in *,$file_conv,*) + # This is the optimization mentioned above: + # If UNNEEDED_CONVERSIONS contains $file_conv, don't convert. ;; mingw/*) file=`cmd //C echo "$file " | sed -e 's/"\(.*\) " *$/\1/'` ;; - cygwin/* | msys/*) - file=`cygpath -m "$file" || echo "$file"` + cygwin/*) + file=`cygpath -w "$file" || echo "$file"` ;; wine/*) file=`winepath -w "$file" || echo "$file"` @@ -143,7 +156,7 @@ func_cl_wrapper () # configure might choose to run compile as 'compile cc -o foo foo.c'. eat=1 case $2 in - *.o | *.[oO][bB][jJ]) + *.o | *.lo | *.[oO][bB][jJ]) func_file_conv "$2" set x "$@" -Fo"$file" shift @@ -248,14 +261,17 @@ If you are trying to build a whole package this is not the right script to run: please start by reading the file 'INSTALL'. Report bugs to <bug-automake@gnu.org>. +GNU Automake home page: <https://www.gnu.org/software/automake/>. +General help using GNU software: <https://www.gnu.org/gethelp/>. EOF exit $? ;; -v | --v*) - echo "compile $scriptversion" + echo "compile (GNU Automake) $scriptversion" exit $? ;; cl | *[/\\]cl | cl.exe | *[/\\]cl.exe | \ + clang-cl | *[/\\]clang-cl | clang-cl.exe | *[/\\]clang-cl.exe | \ icl | *[/\\]icl | icl.exe | *[/\\]icl.exe ) func_cl_wrapper "$@" # Doesn't return... ;; @@ -340,9 +356,9 @@ exit $ret # Local Variables: # mode: shell-script # sh-indentation: 2 -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/config.guess b/deps/libffi/config.guess index 7f76b6228f73..48a684601bd2 100755 --- a/deps/libffi/config.guess +++ b/deps/libffi/config.guess @@ -1,10 +1,10 @@ #! /bin/sh # Attempt to guess a canonical system name. -# Copyright 1992-2022 Free Software Foundation, Inc. +# Copyright 1992-2024 Free Software Foundation, Inc. # shellcheck disable=SC2006,SC2268 # see below for rationale -timestamp='2022-01-09' +timestamp='2024-07-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -47,7 +47,7 @@ me=`echo "$0" | sed -e 's,.*/,,'` usage="\ Usage: $0 [OPTION] -Output the configuration name of the system \`$me' is run on. +Output the configuration name of the system '$me' is run on. Options: -h, --help print this help, then exit @@ -60,13 +60,13 @@ version="\ GNU config.guess ($timestamp) Originally written by Per Bothner. -Copyright 1992-2022 Free Software Foundation, Inc. +Copyright 1992-2024 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" -Try \`$me --help' for more information." +Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do @@ -102,8 +102,8 @@ GUESS= # temporary files to be created and, as you can see below, it is a # headache to deal with in a portable fashion. -# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still -# use `HOST_CC' if defined, but it is deprecated. +# Historically, 'CC_FOR_BUILD' used to be named 'HOST_CC'. We still +# use 'HOST_CC' if defined, but it is deprecated. # Portable tmp directory creation inspired by the Autoconf team. @@ -123,7 +123,7 @@ set_cc_for_build() { dummy=$tmp/dummy case ${CC_FOR_BUILD-},${HOST_CC-},${CC-} in ,,) echo "int x;" > "$dummy.c" - for driver in cc gcc c89 c99 ; do + for driver in cc gcc c17 c99 c89 ; do if ($driver -c -o "$dummy.o" "$dummy.c") >/dev/null 2>&1 ; then CC_FOR_BUILD=$driver break @@ -155,6 +155,9 @@ Linux|GNU|GNU/*) set_cc_for_build cat <<-EOF > "$dummy.c" + #if defined(__ANDROID__) + LIBC=android + #else #include <features.h> #if defined(__UCLIBC__) LIBC=uclibc @@ -162,6 +165,8 @@ Linux|GNU|GNU/*) LIBC=dietlibc #elif defined(__GLIBC__) LIBC=gnu + #elif defined(__LLVM_LIBC__) + LIBC=llvm #else #include <stdarg.h> /* First heuristic to detect musl libc. */ @@ -169,6 +174,7 @@ Linux|GNU|GNU/*) LIBC=musl #endif #endif + #endif EOF cc_set_libc=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^LIBC' | sed 's, ,,g'` eval "$cc_set_libc" @@ -459,7 +465,7 @@ case $UNAME_MACHINE:$UNAME_SYSTEM:$UNAME_RELEASE:$UNAME_VERSION in UNAME_RELEASE=`uname -v` ;; esac - # Japanese Language versions have a version number like `4.1.3-JL'. + # Japanese Language versions have a version number like '4.1.3-JL'. SUN_REL=`echo "$UNAME_RELEASE" | sed -e 's/-/_/'` GUESS=sparc-sun-sunos$SUN_REL ;; @@ -628,7 +634,8 @@ EOF sed 's/^ //' << EOF > "$dummy.c" #include <sys/systemcfg.h> - main() + int + main () { if (!__power_pc()) exit(1); @@ -712,7 +719,8 @@ EOF #include <stdlib.h> #include <unistd.h> - int main () + int + main () { #if defined(_SC_KERNEL_BITS) long bits = sysconf(_SC_KERNEL_BITS); @@ -904,7 +912,7 @@ EOF fi ;; *:FreeBSD:*:*) - UNAME_PROCESSOR=`/usr/bin/uname -p` + UNAME_PROCESSOR=`uname -p` case $UNAME_PROCESSOR in amd64) UNAME_PROCESSOR=x86_64 ;; @@ -966,11 +974,37 @@ EOF GNU_REL=`echo "$UNAME_RELEASE" | sed -e 's/[-(].*//'` GUESS=$UNAME_MACHINE-unknown-$GNU_SYS$GNU_REL-$LIBC ;; + x86_64:[Mm]anagarm:*:*|i?86:[Mm]anagarm:*:*) + GUESS="$UNAME_MACHINE-pc-managarm-mlibc" + ;; + *:[Mm]anagarm:*:*) + GUESS="$UNAME_MACHINE-unknown-managarm-mlibc" + ;; *:Minix:*:*) GUESS=$UNAME_MACHINE-unknown-minix ;; aarch64:Linux:*:*) - GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + set_cc_for_build + CPU=$UNAME_MACHINE + LIBCABI=$LIBC + if test "$CC_FOR_BUILD" != no_compiler_found; then + ABI=64 + sed 's/^ //' << EOF > "$dummy.c" + #ifdef __ARM_EABI__ + #ifdef __ARM_PCS_VFP + ABI=eabihf + #else + ABI=eabi + #endif + #endif +EOF + cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` + eval "$cc_set_abi" + case $ABI in + eabi | eabihf) CPU=armv8l; LIBCABI=$LIBC$ABI ;; + esac + fi + GUESS=$CPU-unknown-linux-$LIBCABI ;; aarch64_be:Linux:*:*) UNAME_MACHINE=aarch64_be @@ -1036,7 +1070,16 @@ EOF k1om:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; - loongarch32:Linux:*:* | loongarch64:Linux:*:* | loongarchx32:Linux:*:*) + kvx:Linux:*:*) + GUESS=$UNAME_MACHINE-unknown-linux-$LIBC + ;; + kvx:cos:*:*) + GUESS=$UNAME_MACHINE-unknown-cos + ;; + kvx:mbr:*:*) + GUESS=$UNAME_MACHINE-unknown-mbr + ;; + loongarch32:Linux:*:* | loongarch64:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC ;; m32r*:Linux:*:*) @@ -1151,16 +1194,27 @@ EOF ;; x86_64:Linux:*:*) set_cc_for_build + CPU=$UNAME_MACHINE LIBCABI=$LIBC if test "$CC_FOR_BUILD" != no_compiler_found; then - if (echo '#ifdef __ILP32__'; echo IS_X32; echo '#endif') | \ - (CCOPTS="" $CC_FOR_BUILD -E - 2>/dev/null) | \ - grep IS_X32 >/dev/null - then - LIBCABI=${LIBC}x32 - fi + ABI=64 + sed 's/^ //' << EOF > "$dummy.c" + #ifdef __i386__ + ABI=x86 + #else + #ifdef __ILP32__ + ABI=x32 + #endif + #endif +EOF + cc_set_abi=`$CC_FOR_BUILD -E "$dummy.c" 2>/dev/null | grep '^ABI' | sed 's, ,,g'` + eval "$cc_set_abi" + case $ABI in + x86) CPU=i686 ;; + x32) LIBCABI=${LIBC}x32 ;; + esac fi - GUESS=$UNAME_MACHINE-pc-linux-$LIBCABI + GUESS=$CPU-pc-linux-$LIBCABI ;; xtensa*:Linux:*:*) GUESS=$UNAME_MACHINE-unknown-linux-$LIBC @@ -1180,7 +1234,7 @@ EOF GUESS=$UNAME_MACHINE-pc-sysv4.2uw$UNAME_VERSION ;; i*86:OS/2:*:*) - # If we were able to find `uname', then EMX Unix compatibility + # If we were able to find 'uname', then EMX Unix compatibility # is probably installed. GUESS=$UNAME_MACHINE-pc-os2-emx ;; @@ -1321,7 +1375,7 @@ EOF GUESS=ns32k-sni-sysv fi ;; - PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + PENTIUM:*:4.0*:*) # Unisys 'ClearPath HMP IX 4000' SVR4/MP effort # says <Richard.M.Bartel@ccMail.Census.GOV> GUESS=i586-unisys-sysv4 ;; @@ -1367,8 +1421,11 @@ EOF BePC:Haiku:*:*) # Haiku running on Intel PC compatible. GUESS=i586-pc-haiku ;; - x86_64:Haiku:*:*) - GUESS=x86_64-unknown-haiku + ppc:Haiku:*:*) # Haiku running on Apple PowerPC + GUESS=powerpc-apple-haiku + ;; + *:Haiku:*:*) # Haiku modern gcc (not bound by BeOS compat) + GUESS=$UNAME_MACHINE-unknown-haiku ;; SX-4:SUPER-UX:*:*) GUESS=sx4-nec-superux$UNAME_RELEASE @@ -1540,6 +1597,9 @@ EOF *:Unleashed:*:*) GUESS=$UNAME_MACHINE-unknown-unleashed$UNAME_RELEASE ;; + *:Ironclad:*:*) + GUESS=$UNAME_MACHINE-unknown-ironclad + ;; esac # Do we have a guess based on uname results? @@ -1563,6 +1623,7 @@ cat > "$dummy.c" <<EOF #endif #endif #endif +int main () { #if defined (sony) diff --git a/deps/libffi/config.sub b/deps/libffi/config.sub index dba16e84c77c..4aaae46f6f74 100755 --- a/deps/libffi/config.sub +++ b/deps/libffi/config.sub @@ -1,10 +1,10 @@ #! /bin/sh # Configuration validation subroutine script. -# Copyright 1992-2022 Free Software Foundation, Inc. +# Copyright 1992-2024 Free Software Foundation, Inc. -# shellcheck disable=SC2006,SC2268 # see below for rationale +# shellcheck disable=SC2006,SC2268,SC2162 # see below for rationale -timestamp='2022-01-03' +timestamp='2024-05-27' # This file is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by @@ -76,13 +76,13 @@ Report bugs and patches to <config-patches@gnu.org>." version="\ GNU config.sub ($timestamp) -Copyright 1992-2022 Free Software Foundation, Inc. +Copyright 1992-2024 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." help=" -Try \`$me --help' for more information." +Try '$me --help' for more information." # Parse command line while test $# -gt 0 ; do @@ -120,7 +120,6 @@ case $# in esac # Split fields of configuration type -# shellcheck disable=SC2162 saved_IFS=$IFS IFS="-" read field1 field2 field3 field4 <<EOF $1 @@ -130,7 +129,7 @@ IFS=$saved_IFS # Separate into logical components for further validation case $1 in *-*-*-*-*) - echo Invalid configuration \`"$1"\': more than four components >&2 + echo "Invalid configuration '$1': more than four components" >&2 exit 1 ;; *-*-*-*) @@ -142,10 +141,21 @@ case $1 in # parts maybe_os=$field2-$field3 case $maybe_os in - nto-qnx* | linux-* | uclinux-uclibc* \ - | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* \ - | netbsd*-eabi* | kopensolaris*-gnu* | cloudabi*-eabi* \ - | storm-chaos* | os2-emx* | rtmk-nova*) + cloudabi*-eabi* \ + | kfreebsd*-gnu* \ + | knetbsd*-gnu* \ + | kopensolaris*-gnu* \ + | linux-* \ + | managarm-* \ + | netbsd*-eabi* \ + | netbsd*-gnu* \ + | nto-qnx* \ + | os2-emx* \ + | rtmk-nova* \ + | storm-chaos* \ + | uclinux-gnu* \ + | uclinux-uclibc* \ + | windows-* ) basic_machine=$field1 basic_os=$maybe_os ;; @@ -160,8 +170,12 @@ case $1 in esac ;; *-*) - # A lone config we happen to match not fitting any pattern case $field1-$field2 in + # Shorthands that happen to contain a single dash + convex-c[12] | convex-c3[248]) + basic_machine=$field2-convex + basic_os= + ;; decstation-3100) basic_machine=mips-dec basic_os= @@ -169,28 +183,88 @@ case $1 in *-*) # Second component is usually, but not always the OS case $field2 in - # Prevent following clause from handling this valid os + # Do not treat sunos as a manufacturer sun*os*) basic_machine=$field1 basic_os=$field2 ;; - zephyr*) - basic_machine=$field1-unknown - basic_os=$field2 - ;; # Manufacturers - dec* | mips* | sequent* | encore* | pc533* | sgi* | sony* \ - | att* | 7300* | 3300* | delta* | motorola* | sun[234]* \ - | unicom* | ibm* | next | hp | isi* | apollo | altos* \ - | convergent* | ncr* | news | 32* | 3600* | 3100* \ - | hitachi* | c[123]* | convex* | sun | crds | omron* | dg \ - | ultra | tti* | harris | dolphin | highlevel | gould \ - | cbm | ns | masscomp | apple | axis | knuth | cray \ - | microblaze* | sim | cisco \ - | oki | wec | wrs | winbond) + 3100* \ + | 32* \ + | 3300* \ + | 3600* \ + | 7300* \ + | acorn \ + | altos* \ + | apollo \ + | apple \ + | atari \ + | att* \ + | axis \ + | be \ + | bull \ + | cbm \ + | ccur \ + | cisco \ + | commodore \ + | convergent* \ + | convex* \ + | cray \ + | crds \ + | dec* \ + | delta* \ + | dg \ + | digital \ + | dolphin \ + | encore* \ + | gould \ + | harris \ + | highlevel \ + | hitachi* \ + | hp \ + | ibm* \ + | intergraph \ + | isi* \ + | knuth \ + | masscomp \ + | microblaze* \ + | mips* \ + | motorola* \ + | ncr* \ + | news \ + | next \ + | ns \ + | oki \ + | omron* \ + | pc533* \ + | rebel \ + | rom68k \ + | rombug \ + | semi \ + | sequent* \ + | siemens \ + | sgi* \ + | siemens \ + | sim \ + | sni \ + | sony* \ + | stratus \ + | sun \ + | sun[234]* \ + | tektronix \ + | tti* \ + | ultra \ + | unicom* \ + | wec \ + | winbond \ + | wrs) basic_machine=$field1-$field2 basic_os= ;; + zephyr*) + basic_machine=$field1-unknown + basic_os=$field2 + ;; *) basic_machine=$field1 basic_os=$field2 @@ -271,26 +345,6 @@ case $1 in basic_machine=arm-unknown basic_os=cegcc ;; - convex-c1) - basic_machine=c1-convex - basic_os=bsd - ;; - convex-c2) - basic_machine=c2-convex - basic_os=bsd - ;; - convex-c32) - basic_machine=c32-convex - basic_os=bsd - ;; - convex-c34) - basic_machine=c34-convex - basic_os=bsd - ;; - convex-c38) - basic_machine=c38-convex - basic_os=bsd - ;; cray) basic_machine=j90-cray basic_os=unicos @@ -713,15 +767,26 @@ case $basic_machine in vendor=dec basic_os=tops20 ;; - delta | 3300 | motorola-3300 | motorola-delta \ - | 3300-motorola | delta-motorola) + delta | 3300 | delta-motorola | 3300-motorola | motorola-delta | motorola-3300) cpu=m68k vendor=motorola ;; - dpx2*) + # This used to be dpx2*, but that gets the RS6000-based + # DPX/20 and the x86-based DPX/2-100 wrong. See + # https://oldskool.silicium.org/stations/bull_dpx20.htm + # https://www.feb-patrimoine.com/english/bull_dpx2.htm + # https://www.feb-patrimoine.com/english/unix_and_bull.htm + dpx2 | dpx2[23]00 | dpx2[23]xx) cpu=m68k vendor=bull - basic_os=sysv3 + ;; + dpx2100 | dpx21xx) + cpu=i386 + vendor=bull + ;; + dpx20) + cpu=rs6000 + vendor=bull ;; encore | umax | mmax) cpu=ns32k @@ -836,18 +901,6 @@ case $basic_machine in next | m*-next) cpu=m68k vendor=next - case $basic_os in - openstep*) - ;; - nextstep*) - ;; - ns2*) - basic_os=nextstep2 - ;; - *) - basic_os=nextstep3 - ;; - esac ;; np1) cpu=np1 @@ -936,14 +989,13 @@ case $basic_machine in ;; *-*) - # shellcheck disable=SC2162 saved_IFS=$IFS IFS="-" read cpu vendor <<EOF $basic_machine EOF IFS=$saved_IFS ;; - # We use `pc' rather than `unknown' + # We use 'pc' rather than 'unknown' # because (1) that's what they normally are, and # (2) the word "unknown" tends to confuse beginning users. i*86 | x86_64) @@ -971,15 +1023,19 @@ unset -v basic_machine # Decode basic machines in the full and proper CPU-Company form. case $cpu-$vendor in - # Here we handle the default manufacturer of certain CPU types in canonical form. It is in - # some cases the only manufacturer, in others, it is the most popular. + # Here we handle the default manufacturer of certain CPU types in canonical form. + # It is in some cases the only manufacturer, in others, it is the most popular. + c[12]-convex | c[12]-unknown | c3[248]-convex | c3[248]-unknown) + vendor=convex + basic_os=${basic_os:-bsd} + ;; craynv-unknown) vendor=cray basic_os=${basic_os:-unicosmp} ;; c90-unknown | c90-cray) vendor=cray - basic_os=${Basic_os:-unicos} + basic_os=${basic_os:-unicos} ;; fx80-unknown) vendor=alliant @@ -1025,11 +1081,29 @@ case $cpu-$vendor in vendor=alt basic_os=${basic_os:-linux-gnueabihf} ;; - dpx20-unknown | dpx20-bull) - cpu=rs6000 - vendor=bull + + # Normalized CPU+vendor pairs that imply an OS, if not otherwise specified + m68k-isi) + basic_os=${basic_os:-sysv} + ;; + m68k-sony) + basic_os=${basic_os:-newsos} + ;; + m68k-tektronix) + basic_os=${basic_os:-bsd} + ;; + m88k-harris) + basic_os=${basic_os:-sysv3} + ;; + i386-bull | m68k-bull) + basic_os=${basic_os:-sysv3} + ;; + rs6000-bull) basic_os=${basic_os:-bosx} ;; + mips-sni) + basic_os=${basic_os:-sysv4} + ;; # Here we normalize CPU types irrespective of the vendor amd64-*) @@ -1037,7 +1111,7 @@ case $cpu-$vendor in ;; blackfin-*) cpu=bfin - basic_os=linux + basic_os=${basic_os:-linux} ;; c54x-*) cpu=tic54x @@ -1060,7 +1134,7 @@ case $cpu-$vendor in ;; m68knommu-*) cpu=m68k - basic_os=linux + basic_os=${basic_os:-linux} ;; m9s12z-* | m68hcs12z-* | hcs12z-* | s12z-*) cpu=s12z @@ -1070,12 +1144,12 @@ case $cpu-$vendor in ;; parisc-*) cpu=hppa - basic_os=linux + basic_os=${basic_os:-linux} ;; pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) cpu=i586 ;; - pentiumpro-* | p6-* | 6x86-* | athlon-* | athalon_*-*) + pentiumpro-* | p6-* | 6x86-* | athlon-* | athlon_*-*) cpu=i686 ;; pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) @@ -1084,9 +1158,6 @@ case $cpu-$vendor in pentium4-*) cpu=i786 ;; - pc98-*) - cpu=i386 - ;; ppc-* | ppcbe-*) cpu=powerpc ;; @@ -1120,9 +1191,6 @@ case $cpu-$vendor in tx39el-*) cpu=mipstx39el ;; - x64-*) - cpu=x86_64 - ;; xscale-* | xscalee[bl]-*) cpu=`echo "$cpu" | sed 's/^xscale/arm/'` ;; @@ -1178,114 +1246,231 @@ case $cpu-$vendor in # Recognize the canonical CPU types that are allowed with any # company name. case $cpu in - 1750a | 580 \ + 1750a \ + | 580 \ + | [cjt]90 \ | a29k \ - | aarch64 | aarch64_be \ + | aarch64 \ + | aarch64_be \ + | aarch64c \ | abacus \ - | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] \ - | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] \ - | alphapca5[67] | alpha64pca5[67] \ + | alpha \ + | alpha64 \ + | alpha64ev56 \ + | alpha64ev6[78] \ + | alpha64ev[4-8] \ + | alpha64pca5[67] \ + | alphaev56 \ + | alphaev6[78] \ + | alphaev[4-8] \ + | alphapca5[67] \ | am33_2.0 \ | amdgcn \ - | arc | arceb | arc32 | arc64 \ - | arm | arm[lb]e | arme[lb] | armv* \ - | avr | avr32 \ + | arc \ + | arc32 \ + | arc64 \ + | arceb \ + | arm \ + | arm64e \ + | arm64ec \ + | arm[lb]e \ + | arme[lb] \ + | armv* \ | asmjs \ + | avr \ + | avr32 \ | ba \ - | be32 | be64 \ - | bfin | bpf | bs2000 \ - | c[123]* | c30 | [cjt]90 | c4x \ - | c8051 | clipper | craynv | csky | cydra \ - | d10v | d30v | dlx | dsp16xx \ - | e2k | elxsi | epiphany \ - | f30[01] | f700 | fido | fr30 | frv | ft32 | fx80 \ - | h8300 | h8500 \ - | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | be32 \ + | be64 \ + | bfin \ + | bpf \ + | bs2000 \ + | c30 \ + | c4x \ + | c8051 \ + | c[123]* \ + | clipper \ + | craynv \ + | csky \ + | cydra \ + | d10v \ + | d30v \ + | dlx \ + | dsp16xx \ + | e2k \ + | elxsi \ + | epiphany \ + | f30[01] \ + | f700 \ + | fido \ + | fr30 \ + | frv \ + | ft32 \ + | fx80 \ + | h8300 \ + | h8500 \ | hexagon \ - | i370 | i*86 | i860 | i960 | ia16 | ia64 \ - | ip2k | iq2000 \ + | hppa \ + | hppa1.[01] \ + | hppa2.0 \ + | hppa2.0[nw] \ + | hppa64 \ + | i*86 \ + | i370 \ + | i860 \ + | i960 \ + | ia16 \ + | ia64 \ + | ip2k \ + | iq2000 \ + | javascript \ | k1om \ - | le32 | le64 \ + | kvx \ + | le32 \ + | le64 \ | lm32 \ - | loongarch32 | loongarch64 | loongarchx32 \ - | m32c | m32r | m32rle \ - | m5200 | m68000 | m680[012346]0 | m68360 | m683?2 | m68k \ - | m6811 | m68hc11 | m6812 | m68hc12 | m68hcs12x \ - | m88110 | m88k | maxq | mb | mcore | mep | metag \ - | microblaze | microblazeel \ - | mips | mipsbe | mipseb | mipsel | mipsle \ - | mips16 \ - | mips64 | mips64eb | mips64el \ - | mips64octeon | mips64octeonel \ - | mips64orion | mips64orionel \ - | mips64r5900 | mips64r5900el \ - | mips64vr | mips64vrel \ - | mips64vr4100 | mips64vr4100el \ - | mips64vr4300 | mips64vr4300el \ - | mips64vr5000 | mips64vr5000el \ - | mips64vr5900 | mips64vr5900el \ - | mipsisa32 | mipsisa32el \ - | mipsisa32r2 | mipsisa32r2el \ - | mipsisa32r3 | mipsisa32r3el \ - | mipsisa32r5 | mipsisa32r5el \ - | mipsisa32r6 | mipsisa32r6el \ - | mipsisa64 | mipsisa64el \ - | mipsisa64r2 | mipsisa64r2el \ - | mipsisa64r3 | mipsisa64r3el \ - | mipsisa64r5 | mipsisa64r5el \ - | mipsisa64r6 | mipsisa64r6el \ - | mipsisa64sb1 | mipsisa64sb1el \ - | mipsisa64sr71k | mipsisa64sr71kel \ - | mipsr5900 | mipsr5900el \ - | mipstx39 | mipstx39el \ + | loongarch32 \ + | loongarch64 \ + | m32c \ + | m32r \ + | m32rle \ + | m5200 \ + | m68000 \ + | m680[012346]0 \ + | m6811 \ + | m6812 \ + | m68360 \ + | m683?2 \ + | m68hc11 \ + | m68hc12 \ + | m68hcs12x \ + | m68k \ + | m88110 \ + | m88k \ + | maxq \ + | mb \ + | mcore \ + | mep \ + | metag \ + | microblaze \ + | microblazeel \ + | mips* \ | mmix \ - | mn10200 | mn10300 \ + | mn10200 \ + | mn10300 \ | moxie \ - | mt \ | msp430 \ - | nds32 | nds32le | nds32be \ + | mt \ + | nanomips* \ + | nds32 \ + | nds32be \ + | nds32le \ | nfp \ - | nios | nios2 | nios2eb | nios2el \ - | none | np1 | ns16k | ns32k | nvptx \ + | nios \ + | nios2 \ + | nios2eb \ + | nios2el \ + | none \ + | np1 \ + | ns16k \ + | ns32k \ + | nvptx \ | open8 \ | or1k* \ | or32 \ | orion \ + | pdp10 \ + | pdp11 \ | picochip \ - | pdp10 | pdp11 | pj | pjl | pn | power \ - | powerpc | powerpc64 | powerpc64le | powerpcle | powerpcspe \ + | pj \ + | pjl \ + | pn \ + | power \ + | powerpc \ + | powerpc64 \ + | powerpc64le \ + | powerpcle \ + | powerpcspe \ | pru \ | pyramid \ - | riscv | riscv32 | riscv32be | riscv64 | riscv64be \ - | rl78 | romp | rs6000 | rx \ - | s390 | s390x \ + | riscv \ + | riscv32 \ + | riscv32be \ + | riscv64 \ + | riscv64be \ + | rl78 \ + | romp \ + | rs6000 \ + | rx \ + | s390 \ + | s390x \ | score \ - | sh | shl \ - | sh[1234] | sh[24]a | sh[24]ae[lb] | sh[23]e | she[lb] | sh[lb]e \ - | sh[1234]e[lb] | sh[12345][lb]e | sh[23]ele | sh64 | sh64le \ - | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet \ + | sh \ + | sh64 \ + | sh64le \ + | sh[12345][lb]e \ + | sh[1234] \ + | sh[1234]e[lb] \ + | sh[23]e \ + | sh[23]ele \ + | sh[24]a \ + | sh[24]ae[lb] \ + | sh[lb]e \ + | she[lb] \ + | shl \ + | sparc \ + | sparc64 \ + | sparc64b \ + | sparc64v \ + | sparc86x \ + | sparclet \ | sparclite \ - | sparcv8 | sparcv9 | sparcv9b | sparcv9v | sv1 | sx* \ + | sparcv8 \ + | sparcv9 \ + | sparcv9b \ + | sparcv9v \ | spu \ + | sv1 \ + | sx* \ | tahoe \ | thumbv7* \ - | tic30 | tic4x | tic54x | tic55x | tic6x | tic80 \ + | tic30 \ + | tic4x \ + | tic54x \ + | tic55x \ + | tic6x \ + | tic80 \ | tron \ | ubicom32 \ - | v70 | v850 | v850e | v850e1 | v850es | v850e2 | v850e2v3 \ + | v70 \ + | v810 \ + | v850 \ + | v850e \ + | v850e1 \ + | v850e2 \ + | v850e2v3 \ + | v850es \ | vax \ + | vc4 \ | visium \ | w65 \ - | wasm32 | wasm64 \ + | wasm32 \ + | wasm64 \ | we32k \ - | x86 | x86_64 | xc16x | xgate | xps100 \ - | xstormy16 | xtensa* \ + | x86 \ + | x86_64 \ + | xc16x \ + | xgate \ + | xps100 \ + | xstormy16 \ + | xtensa* \ | ymp \ - | z8k | z80) + | z80 \ + | z8k) ;; *) - echo Invalid configuration \`"$1"\': machine \`"$cpu-$vendor"\' not recognized 1>&2 + echo "Invalid configuration '$1': machine '$cpu-$vendor' not recognized" 1>&2 exit 1 ;; esac @@ -1306,11 +1491,12 @@ esac # Decode manufacturer-specific aliases for certain operating systems. -if test x$basic_os != x +if test x"$basic_os" != x then # First recognize some ad-hoc cases, or perhaps split kernel-os, or else just # set os. +obj= case $basic_os in gnu/linux*) kernel=linux @@ -1325,7 +1511,6 @@ case $basic_os in os=`echo "$basic_os" | sed -e 's|nto-qnx|qnx|'` ;; *-*) - # shellcheck disable=SC2162 saved_IFS=$IFS IFS="-" read kernel os <<EOF $basic_os @@ -1341,6 +1526,10 @@ EOF kernel=linux os=`echo "$basic_os" | sed -e 's|linux|gnu|'` ;; + managarm*) + kernel=managarm + os=`echo "$basic_os" | sed -e 's|managarm|mlibc|'` + ;; *) kernel= os=$basic_os @@ -1368,6 +1557,23 @@ case $os in unixware*) os=sysv4.2uw ;; + # The marketing names for NeXT's operating systems were + # NeXTSTEP, NeXTSTEP 2, OpenSTEP 3, OpenSTEP 4. 'openstep' is + # mapped to 'openstep3', but 'openstep1' and 'openstep2' are + # mapped to 'nextstep' and 'nextstep2', consistent with the + # treatment of SunOS/Solaris. + ns | ns1 | nextstep | nextstep1 | openstep1) + os=nextstep + ;; + ns2 | nextstep2 | openstep2) + os=nextstep2 + ;; + ns3 | nextstep3 | openstep | openstep3) + os=openstep3 + ;; + ns4 | nextstep4 | openstep4) + os=openstep4 + ;; # es1800 is here to avoid being matched by es* (a different OS) es1800*) os=ose @@ -1438,6 +1644,7 @@ case $os in ;; utek*) os=bsd + vendor=`echo "$vendor" | sed -e 's|^unknown$|tektronix|'` ;; dynix*) os=bsd @@ -1454,21 +1661,25 @@ case $os in 386bsd) os=bsd ;; - ctix* | uts*) + ctix*) os=sysv + vendor=`echo "$vendor" | sed -e 's|^unknown$|convergent|'` ;; - nova*) - os=rtmk-nova + uts*) + os=sysv ;; - ns2) - os=nextstep2 + nova*) + kernel=rtmk + os=nova ;; # Preserve the version number of sinix5. sinix5.*) os=`echo "$os" | sed -e 's|sinix|sysv|'` + vendor=`echo "$vendor" | sed -e 's|^unknown$|sni|'` ;; sinix*) os=sysv4 + vendor=`echo "$vendor" | sed -e 's|^unknown$|sni|'` ;; tpf*) os=tpf @@ -1506,10 +1717,16 @@ case $os in os=eabi ;; *) - os=elf + os= + obj=elf ;; esac ;; + aout* | coff* | elf* | pe*) + # These are machine code file formats, not OSes + obj=$os + os= + ;; *) # No normalization, but not necessarily accepted, that comes below. ;; @@ -1528,12 +1745,15 @@ else # system, and we'll never get to this point. kernel= +obj= case $cpu-$vendor in score-*) - os=elf + os= + obj=elf ;; spu-*) - os=elf + os= + obj=elf ;; *-acorn) os=riscix1.2 @@ -1543,28 +1763,35 @@ case $cpu-$vendor in os=gnu ;; arm*-semi) - os=aout + os= + obj=aout ;; c4x-* | tic4x-*) - os=coff + os= + obj=coff ;; c8051-*) - os=elf + os= + obj=elf ;; clipper-intergraph) os=clix ;; hexagon-*) - os=elf + os= + obj=elf ;; tic54x-*) - os=coff + os= + obj=coff ;; tic55x-*) - os=coff + os= + obj=coff ;; tic6x-*) - os=coff + os= + obj=coff ;; # This must come before the *-dec entry. pdp10-*) @@ -1586,28 +1813,43 @@ case $cpu-$vendor in os=sunos3 ;; m68*-cisco) - os=aout + os= + obj=aout ;; mep-*) - os=elf + os= + obj=elf + ;; + # The -sgi and -siemens entries must be before the mips- entry + # or we get the wrong os. + *-sgi) + os=irix + ;; + *-siemens) + os=sysv4 ;; mips*-cisco) - os=elf + os= + obj=elf ;; - mips*-*) - os=elf + mips*-*|nanomips*-*) + os= + obj=elf ;; or32-*) - os=coff + os= + obj=coff ;; - *-tti) # must be before sparc entry or we get the wrong os. + # This must be before the sparc-* entry or we get the wrong os. + *-tti) os=sysv3 ;; sparc-* | *-sun) os=sunos4.1.1 ;; pru-*) - os=elf + os= + obj=elf ;; *-be) os=beos @@ -1631,7 +1873,7 @@ case $cpu-$vendor in os=hpux ;; *-hitachi) - os=hiux + os=hiuxwe2 ;; i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) os=sysv @@ -1675,12 +1917,6 @@ case $cpu-$vendor in *-encore) os=bsd ;; - *-sgi) - os=irix - ;; - *-siemens) - os=sysv4 - ;; *-masscomp) os=rtu ;; @@ -1688,10 +1924,12 @@ case $cpu-$vendor in os=uxpv ;; *-rom68k) - os=coff + os= + obj=coff ;; *-*bug) - os=coff + os= + obj=coff ;; *-apple) os=macos @@ -1709,10 +1947,11 @@ esac fi -# Now, validate our (potentially fixed-up) OS. +# Now, validate our (potentially fixed-up) individual pieces (OS, OBJ). + case $os in # Sometimes we do "kernel-libc", so those need to count as OSes. - musl* | newlib* | relibc* | uclibc*) + llvm* | musl* | newlib* | relibc* | uclibc*) ;; # Likewise for "kernel-abi" eabi* | gnueabi*) @@ -1720,83 +1959,308 @@ case $os in # VxWorks passes extra cpu info in the 4th filed. simlinux | simwindows | spe) ;; + # See `case $cpu-$os` validation below + ghcjs) + ;; # Now accept the basic system types. - # The portable systems comes first. # Each alternative MUST end in a * to match a version number. - gnu* | android* | bsd* | mach* | minix* | genix* | ultrix* | irix* \ - | *vms* | esix* | aix* | cnk* | sunos | sunos[34]* \ - | hpux* | unos* | osf* | luna* | dgux* | auroraux* | solaris* \ - | sym* | plan9* | psp* | sim* | xray* | os68k* | v88r* \ - | hiux* | abug | nacl* | netware* | windows* \ - | os9* | macos* | osx* | ios* \ - | mpw* | magic* | mmixware* | mon960* | lnews* \ - | amigaos* | amigados* | msdos* | newsos* | unicos* | aof* \ - | aos* | aros* | cloudabi* | sortix* | twizzler* \ - | nindy* | vxsim* | vxworks* | ebmon* | hms* | mvs* \ - | clix* | riscos* | uniplus* | iris* | isc* | rtu* | xenix* \ - | mirbsd* | netbsd* | dicos* | openedition* | ose* \ - | bitrig* | openbsd* | secbsd* | solidbsd* | libertybsd* | os108* \ - | ekkobsd* | freebsd* | riscix* | lynxos* | os400* \ - | bosx* | nextstep* | cxux* | aout* | elf* | oabi* \ - | ptx* | coff* | ecoff* | winnt* | domain* | vsta* \ - | udi* | lites* | ieee* | go32* | aux* | hcos* \ - | chorusrdb* | cegcc* | glidix* | serenity* \ - | cygwin* | msys* | pe* | moss* | proelf* | rtems* \ - | midipix* | mingw32* | mingw64* | mint* \ - | uxpv* | beos* | mpeix* | udk* | moxiebox* \ - | interix* | uwin* | mks* | rhapsody* | darwin* \ - | openstep* | oskit* | conix* | pw32* | nonstopux* \ - | storm-chaos* | tops10* | tenex* | tops20* | its* \ - | os2* | vos* | palmos* | uclinux* | nucleus* | morphos* \ - | scout* | superux* | sysv* | rtmk* | tpf* | windiss* \ - | powermax* | dnix* | nx6 | nx7 | sei* | dragonfly* \ - | skyos* | haiku* | rdos* | toppers* | drops* | es* \ - | onefs* | tirtos* | phoenix* | fuchsia* | redox* | bme* \ - | midnightbsd* | amdhsa* | unleashed* | emscripten* | wasi* \ - | nsk* | powerunix* | genode* | zvmoe* | qnx* | emx* | zephyr* \ - | fiwix* ) + abug \ + | aix* \ + | amdhsa* \ + | amigados* \ + | amigaos* \ + | android* \ + | aof* \ + | aos* \ + | aros* \ + | atheos* \ + | auroraux* \ + | aux* \ + | beos* \ + | bitrig* \ + | bme* \ + | bosx* \ + | bsd* \ + | cegcc* \ + | chorusos* \ + | chorusrdb* \ + | clix* \ + | cloudabi* \ + | cnk* \ + | conix* \ + | cos* \ + | cxux* \ + | cygwin* \ + | darwin* \ + | dgux* \ + | dicos* \ + | dnix* \ + | domain* \ + | dragonfly* \ + | drops* \ + | ebmon* \ + | ecoff* \ + | ekkobsd* \ + | emscripten* \ + | emx* \ + | es* \ + | fiwix* \ + | freebsd* \ + | fuchsia* \ + | genix* \ + | genode* \ + | glidix* \ + | gnu* \ + | go32* \ + | haiku* \ + | hcos* \ + | hiux* \ + | hms* \ + | hpux* \ + | ieee* \ + | interix* \ + | ios* \ + | iris* \ + | irix* \ + | ironclad* \ + | isc* \ + | its* \ + | l4re* \ + | libertybsd* \ + | lites* \ + | lnews* \ + | luna* \ + | lynxos* \ + | mach* \ + | macos* \ + | magic* \ + | mbr* \ + | midipix* \ + | midnightbsd* \ + | mingw32* \ + | mingw64* \ + | minix* \ + | mint* \ + | mirbsd* \ + | mks* \ + | mlibc* \ + | mmixware* \ + | mon960* \ + | morphos* \ + | moss* \ + | moxiebox* \ + | mpeix* \ + | mpw* \ + | msdos* \ + | msys* \ + | mvs* \ + | nacl* \ + | netbsd* \ + | netware* \ + | newsos* \ + | nextstep* \ + | nindy* \ + | nonstopux* \ + | nova* \ + | nsk* \ + | nucleus* \ + | nx6 \ + | nx7 \ + | oabi* \ + | ohos* \ + | onefs* \ + | openbsd* \ + | openedition* \ + | openstep* \ + | os108* \ + | os2* \ + | os400* \ + | os68k* \ + | os9* \ + | ose* \ + | osf* \ + | oskit* \ + | osx* \ + | palmos* \ + | phoenix* \ + | plan9* \ + | powermax* \ + | powerunix* \ + | proelf* \ + | psos* \ + | psp* \ + | ptx* \ + | pw32* \ + | qnx* \ + | rdos* \ + | redox* \ + | rhapsody* \ + | riscix* \ + | riscos* \ + | rtems* \ + | rtmk* \ + | rtu* \ + | scout* \ + | secbsd* \ + | sei* \ + | serenity* \ + | sim* \ + | skyos* \ + | solaris* \ + | solidbsd* \ + | sortix* \ + | storm-chaos* \ + | sunos \ + | sunos[34]* \ + | superux* \ + | syllable* \ + | sym* \ + | sysv* \ + | tenex* \ + | tirtos* \ + | toppers* \ + | tops10* \ + | tops20* \ + | tpf* \ + | tvos* \ + | twizzler* \ + | uclinux* \ + | udi* \ + | udk* \ + | ultrix* \ + | unicos* \ + | uniplus* \ + | unleashed* \ + | unos* \ + | uwin* \ + | uxpv* \ + | v88r* \ + |*vms* \ + | vos* \ + | vsta* \ + | vxsim* \ + | vxworks* \ + | wasi* \ + | watchos* \ + | wince* \ + | windiss* \ + | windows* \ + | winnt* \ + | xenix* \ + | xray* \ + | zephyr* \ + | zvmoe* ) ;; # This one is extra strict with allowed versions sco3.2v2 | sco3.2v[4-9]* | sco5v6*) # Don't forget version if it is 3.2v4 or newer. ;; + # This refers to builds using the UEFI calling convention + # (which depends on the architecture) and PE file format. + # Note that this is both a different calling convention and + # different file format than that of GNU-EFI + # (x86_64-w64-mingw32). + uefi) + ;; none) ;; + kernel* | msvc* ) + # Restricted further below + ;; + '') + if test x"$obj" = x + then + echo "Invalid configuration '$1': Blank OS only allowed with explicit machine code file format" 1>&2 + fi + ;; + *) + echo "Invalid configuration '$1': OS '$os' not recognized" 1>&2 + exit 1 + ;; +esac + +case $obj in + aout* | coff* | elf* | pe*) + ;; + '') + # empty is fine + ;; *) - echo Invalid configuration \`"$1"\': OS \`"$os"\' not recognized 1>&2 + echo "Invalid configuration '$1': Machine code format '$obj' not recognized" 1>&2 + exit 1 + ;; +esac + +# Here we handle the constraint that a (synthetic) cpu and os are +# valid only in combination with each other and nowhere else. +case $cpu-$os in + # The "javascript-unknown-ghcjs" triple is used by GHC; we + # accept it here in order to tolerate that, but reject any + # variations. + javascript-ghcjs) + ;; + javascript-* | *-ghcjs) + echo "Invalid configuration '$1': cpu '$cpu' is not valid with os '$os$obj'" 1>&2 exit 1 ;; esac # As a final step for OS-related things, validate the OS-kernel combination # (given a valid OS), if there is a kernel. -case $kernel-$os in - linux-gnu* | linux-dietlibc* | linux-android* | linux-newlib* \ - | linux-musl* | linux-relibc* | linux-uclibc* ) +case $kernel-$os-$obj in + linux-gnu*- | linux-android*- | linux-dietlibc*- | linux-llvm*- \ + | linux-mlibc*- | linux-musl*- | linux-newlib*- \ + | linux-relibc*- | linux-uclibc*- | linux-ohos*- ) + ;; + uclinux-uclibc*- | uclinux-gnu*- ) + ;; + managarm-mlibc*- | managarm-kernel*- ) ;; - uclinux-uclibc* ) + windows*-msvc*-) ;; - -dietlibc* | -newlib* | -musl* | -relibc* | -uclibc* ) + -dietlibc*- | -llvm*- | -mlibc*- | -musl*- | -newlib*- | -relibc*- \ + | -uclibc*- ) # These are just libc implementations, not actual OSes, and thus # require a kernel. - echo "Invalid configuration \`$1': libc \`$os' needs explicit kernel." 1>&2 + echo "Invalid configuration '$1': libc '$os' needs explicit kernel." 1>&2 exit 1 ;; - kfreebsd*-gnu* | kopensolaris*-gnu*) + -kernel*- ) + echo "Invalid configuration '$1': '$os' needs explicit kernel." 1>&2 + exit 1 ;; - vxworks-simlinux | vxworks-simwindows | vxworks-spe) + *-kernel*- ) + echo "Invalid configuration '$1': '$kernel' does not support '$os'." 1>&2 + exit 1 ;; - nto-qnx*) + *-msvc*- ) + echo "Invalid configuration '$1': '$os' needs 'windows'." 1>&2 + exit 1 ;; - os2-emx) + kfreebsd*-gnu*- | knetbsd*-gnu*- | netbsd*-gnu*- | kopensolaris*-gnu*-) + ;; + vxworks-simlinux- | vxworks-simwindows- | vxworks-spe-) + ;; + nto-qnx*-) ;; - *-eabi* | *-gnueabi*) + os2-emx-) ;; - -*) + rtmk-nova-) + ;; + *-eabi*- | *-gnueabi*-) + ;; + none--*) + # None (no kernel, i.e. freestanding / bare metal), + # can be paired with an machine code file format + ;; + -*-) # Blank kernel with real OS is always fine. ;; - *-*) - echo "Invalid configuration \`$1': Kernel \`$kernel' not known to work with OS \`$os'." 1>&2 + --*) + # Blank kernel and OS with real machine code file format is always fine. + ;; + *-*-*) + echo "Invalid configuration '$1': Kernel '$kernel' not known to work with OS '$os'." 1>&2 exit 1 ;; esac @@ -1809,7 +2273,7 @@ case $vendor in *-riscix*) vendor=acorn ;; - *-sunos*) + *-sunos* | *-solaris*) vendor=sun ;; *-cnk* | *-aix*) @@ -1879,7 +2343,7 @@ case $vendor in ;; esac -echo "$cpu-$vendor-${kernel:+$kernel-}$os" +echo "$cpu-$vendor${kernel:+-$kernel}${os:+-$os}${obj:+-$obj}" exit # Local variables: diff --git a/deps/libffi/configure b/deps/libffi/configure index 7b8a4cb375d1..321c6400860f 100755 --- a/deps/libffi/configure +++ b/deps/libffi/configure @@ -1,11 +1,11 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.71 for libffi 3.8.0. +# Generated by GNU Autoconf 2.72 for libffi 3.8.1. # # Report bugs to <http://github.com/libffi/libffi/issues>. # # -# Copyright (C) 1992-1996, 1998-2017, 2020-2021 Free Software Foundation, +# Copyright (C) 1992-1996, 1998-2017, 2020-2023 Free Software Foundation, # Inc. # # @@ -17,7 +17,6 @@ # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -as_nop=: if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 then : emulate sh @@ -26,12 +25,13 @@ then : # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST -else $as_nop - case `(set -o) 2>/dev/null` in #( +else case e in #( + e) case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; +esac ;; esac fi @@ -103,7 +103,7 @@ IFS=$as_save_IFS ;; esac -# We did not find ourselves, most probably we were run as `sh COMMAND' +# We did not find ourselves, most probably we were run as 'sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 @@ -133,15 +133,14 @@ case $- in # (((( esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail -# out after a failed `exec'. +# out after a failed 'exec'. printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi # We don't want this to propagate to other subprocesses. { _as_can_reexec=; unset _as_can_reexec;} if test "x$CONFIG_SHELL" = x; then - as_bourne_compatible="as_nop=: -if test \${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 + as_bourne_compatible="if test \${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 then : emulate sh NULLCMD=: @@ -149,12 +148,13 @@ then : # is contrary to our usage. Disable this feature. alias -g '\${1+\"\$@\"}'='\"\$@\"' setopt NO_GLOB_SUBST -else \$as_nop - case \`(set -o) 2>/dev/null\` in #( +else case e in #( + e) case \`(set -o) 2>/dev/null\` in #( *posix*) : set -o posix ;; #( *) : ;; +esac ;; esac fi " @@ -172,8 +172,9 @@ as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } if ( set x; as_fn_ret_success y && test x = \"\$1\" ) then : -else \$as_nop - exitcode=1; echo positional parameters were not saved. +else case e in #( + e) exitcode=1; echo positional parameters were not saved. ;; +esac fi test x\$exitcode = x0 || exit 1 blah=\$(echo \$(echo blah)) @@ -195,14 +196,15 @@ test \$(( 1 + 1 )) = 2 || exit 1 if (eval "$as_required") 2>/dev/null then : as_have_required=yes -else $as_nop - as_have_required=no +else case e in #( + e) as_have_required=no ;; +esac fi if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null then : -else $as_nop - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +else case e in #( + e) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR as_found=false for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH do @@ -235,12 +237,13 @@ IFS=$as_save_IFS if $as_found then : -else $as_nop - if { test -f "$SHELL" || test -f "$SHELL.exe"; } && +else case e in #( + e) if { test -f "$SHELL" || test -f "$SHELL.exe"; } && as_run=a "$SHELL" -c "$as_bourne_compatible""$as_required" 2>/dev/null then : CONFIG_SHELL=$SHELL as_have_required=yes -fi +fi ;; +esac fi @@ -262,7 +265,7 @@ case $- in # (((( esac exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} # Admittedly, this is quite paranoid, since all the known shells bail -# out after a failed `exec'. +# out after a failed 'exec'. printf "%s\n" "$0: could not re-execute with $CONFIG_SHELL" >&2 exit 255 fi @@ -282,7 +285,8 @@ $0: message. Then install a modern shell, or manually run $0: the script under such a shell if you do have one." fi exit 1 -fi +fi ;; +esac fi fi SHELL=${CONFIG_SHELL-/bin/sh} @@ -321,14 +325,6 @@ as_fn_exit () as_fn_set_status $1 exit $1 } # as_fn_exit -# as_fn_nop -# --------- -# Do nothing but, unlike ":", preserve the value of $?. -as_fn_nop () -{ - return $? -} -as_nop=as_fn_nop # as_fn_mkdir_p # ------------- @@ -397,11 +393,12 @@ then : { eval $1+=\$2 }' -else $as_nop - as_fn_append () +else case e in #( + e) as_fn_append () { eval $1=\$$1\$2 - } + } ;; +esac fi # as_fn_append # as_fn_arith ARG... @@ -415,21 +412,14 @@ then : { as_val=$(( $* )) }' -else $as_nop - as_fn_arith () +else case e in #( + e) as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` - } + } ;; +esac fi # as_fn_arith -# as_fn_nop -# --------- -# Do nothing but, unlike ":", preserve the value of $?. -as_fn_nop () -{ - return $? -} -as_nop=as_fn_nop # as_fn_error STATUS ERROR [LINENO LOG_FD] # ---------------------------------------- @@ -503,6 +493,8 @@ as_cr_alnum=$as_cr_Letters$as_cr_digits /[$]LINENO/= ' <$as_myself | sed ' + t clear + :clear s/[$]LINENO.*/&-/ t lineno b @@ -551,7 +543,6 @@ esac as_echo='printf %s\n' as_echo_n='printf %s' - rm -f conf$$ conf$$.exe conf$$.file if test -d conf$$.dir; then rm -f conf$$.dir/conf$$.file @@ -563,9 +554,9 @@ if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -pR'. + # 1) On MSYS, both 'ln -s file dir' and 'ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; 'ln -s' creates a wrapper executable. + # In both cases, we have to default to 'cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then @@ -590,10 +581,12 @@ as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" +as_sed_cpp="y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g" +as_tr_cpp="eval sed '$as_sed_cpp'" # deprecated # Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" +as_sed_sh="y%*+%pp%;s%[^_$as_cr_alnum]%_%g" +as_tr_sh="eval sed '$as_sed_sh'" # deprecated SHELL=${CONFIG_SHELL-/bin/sh} @@ -621,8 +614,8 @@ MAKEFLAGS= # Identity of this package. PACKAGE_NAME='libffi' PACKAGE_TARNAME='libffi' -PACKAGE_VERSION='3.8.0' -PACKAGE_STRING='libffi 3.8.0' +PACKAGE_VERSION='3.8.1' +PACKAGE_STRING='libffi 3.8.1' PACKAGE_BUGREPORT='http://github.com/libffi/libffi/issues' PACKAGE_URL='' @@ -748,6 +741,8 @@ CPPFLAGS LDFLAGS CFLAGS CC +am__xargs_n +am__rm_f_notfound AM_BACKSLASH AM_DEFAULT_VERBOSITY AM_DEFAULT_V @@ -841,8 +836,10 @@ enable_silent_rules enable_dependency_tracking enable_shared enable_static +enable_pic with_pic enable_fast_install +enable_aix_soname with_aix_soname with_gnu_ld with_sysroot @@ -977,7 +974,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid feature name: \`$ac_useropt'" + as_fn_error $? "invalid feature name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1003,7 +1000,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid feature name: \`$ac_useropt'" + as_fn_error $? "invalid feature name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1216,7 +1213,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid package name: \`$ac_useropt'" + as_fn_error $? "invalid package name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1232,7 +1229,7 @@ do ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` # Reject names that are not valid shell variable names. expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && - as_fn_error $? "invalid package name: \`$ac_useropt'" + as_fn_error $? "invalid package name: '$ac_useropt'" ac_useropt_orig=$ac_useropt ac_useropt=`printf "%s\n" "$ac_useropt" | sed 's/[-+.]/_/g'` case $ac_user_opts in @@ -1262,8 +1259,8 @@ do | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) x_libraries=$ac_optarg ;; - -*) as_fn_error $? "unrecognized option: \`$ac_option' -Try \`$0 --help' for more information" + -*) as_fn_error $? "unrecognized option: '$ac_option' +Try '$0 --help' for more information" ;; *=*) @@ -1271,7 +1268,7 @@ Try \`$0 --help' for more information" # Reject names that are not valid shell variable names. case $ac_envvar in #( '' | [0-9]* | *[!_$as_cr_alnum]* ) - as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + as_fn_error $? "invalid variable name: '$ac_envvar'" ;; esac eval $ac_envvar=\$ac_optarg export $ac_envvar ;; @@ -1321,7 +1318,7 @@ do as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" done -# There might be people who depend on the old broken behavior: `$host' +# There might be people who depend on the old broken behavior: '$host' # used to hold the argument of --host etc. # FIXME: To remove some day. build=$build_alias @@ -1389,7 +1386,7 @@ if test ! -r "$srcdir/$ac_unique_file"; then test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" fi -ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_msg="sources are in $srcdir, but 'cd $srcdir' does not work" ac_abs_confdir=`( cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" pwd)` @@ -1417,7 +1414,7 @@ if test "$ac_init_help" = "long"; then # Omit some internal or obsolete options to make the list less imposing. # This message is too long to be a string in the A/UX 3.1 sh. cat <<_ACEOF -\`configure' configures libffi 3.8.0 to adapt to many kinds of systems. +'configure' configures libffi 3.8.1 to adapt to many kinds of systems. Usage: $0 [OPTION]... [VAR=VALUE]... @@ -1431,11 +1428,11 @@ Configuration: --help=short display options specific to this package --help=recursive display the short help of all the included packages -V, --version display version information and exit - -q, --quiet, --silent do not print \`checking ...' messages + -q, --quiet, --silent do not print 'checking ...' messages --cache-file=FILE cache test results in FILE [disabled] - -C, --config-cache alias for \`--cache-file=config.cache' + -C, --config-cache alias for '--cache-file=config.cache' -n, --no-create do not create output files - --srcdir=DIR find the sources in DIR [configure dir or \`..'] + --srcdir=DIR find the sources in DIR [configure dir or '..'] Installation directories: --prefix=PREFIX install architecture-independent files in PREFIX @@ -1443,10 +1440,10 @@ Installation directories: --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX [PREFIX] -By default, \`make install' will install all the files in -\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify -an installation prefix other than \`$ac_default_prefix' using \`--prefix', -for instance \`--prefix=\$HOME'. +By default, 'make install' will install all the files in +'$ac_default_prefix/bin', '$ac_default_prefix/lib' etc. You can specify +an installation prefix other than '$ac_default_prefix' using '--prefix', +for instance '--prefix=\$HOME'. For better control, use the options below. @@ -1489,7 +1486,7 @@ fi if test -n "$ac_init_help"; then case $ac_init_help in - short | recursive ) echo "Configuration of libffi 3.8.0:";; + short | recursive ) echo "Configuration of libffi 3.8.1:";; esac cat <<\_ACEOF @@ -1507,8 +1504,13 @@ Optional Features: speeds up one-time build --enable-shared[=PKGS] build shared libraries [default=yes] --enable-static[=PKGS] build static libraries [default=yes] + --enable-pic[=PKGS] try to use only PIC/non-PIC objects [default=use + both] --enable-fast-install[=PKGS] optimize for fast installation [default=yes] + --enable-aix-soname=aix|svr4|both + shared library versioning (aka "SONAME") variant to + provide on AIX, [default=aix]. --disable-libtool-lock avoid locking (might break parallel builds) --enable-portable-binary disable compiler optimizations that would produce @@ -1531,11 +1533,6 @@ Optional Features: Optional Packages: --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) - --with-pic[=PKGS] try to use only PIC/non-PIC objects [default=use - both] - --with-aix-soname=aix|svr4|both - shared library versioning (aka "SONAME") variant to - provide on AIX, [default=aix]. --with-gnu-ld assume the C compiler uses GNU ld [default=no] --with-sysroot[=DIR] Search for dependent libraries within DIR (or the compiler's sysroot if not specified). @@ -1561,7 +1558,7 @@ Some influential environment variables: Used only for the wasm64 target. Set to 1 (default) or 2 for Emscripten's -sMEMORY64 mode -Use these variables to override the choices made by `configure' or to help +Use these variables to override the choices made by 'configure' or to help it to find libraries and programs with nonstandard names/locations. Report bugs to <http://github.com/libffi/libffi/issues>. @@ -1628,10 +1625,10 @@ fi test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF -libffi configure 3.8.0 -generated by GNU Autoconf 2.71 +libffi configure 3.8.1 +generated by GNU Autoconf 2.72 -Copyright (C) 2021 Free Software Foundation, Inc. +Copyright (C) 2023 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it. _ACEOF @@ -1670,11 +1667,12 @@ printf "%s\n" "$ac_try_echo"; } >&5 } && test -s conftest.$ac_objext then : ac_retval=0 -else $as_nop - printf "%s\n" "$as_me: failed program was:" >&5 +else case e in #( + e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_retval=1 + ac_retval=1 ;; +esac fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval @@ -1709,11 +1707,12 @@ printf "%s\n" "$ac_try_echo"; } >&5 } && test -s conftest.$ac_objext then : ac_retval=0 -else $as_nop - printf "%s\n" "$as_me: failed program was:" >&5 +else case e in #( + e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_retval=1 + ac_retval=1 ;; +esac fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval @@ -1751,11 +1750,12 @@ printf "%s\n" "$ac_try_echo"; } >&5 } then : ac_retval=0 -else $as_nop - printf "%s\n" "$as_me: failed program was:" >&5 +else case e in #( + e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_retval=1 + ac_retval=1 ;; +esac fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would @@ -1779,8 +1779,8 @@ printf %s "checking for $2... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 #include <$2> @@ -1788,10 +1788,12 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$3=yes" -else $as_nop - eval "$3=no" +else case e in #( + e) eval "$3=no" ;; +esac fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -1811,15 +1813,15 @@ printf %s "checking for $2... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Define $2 to an innocuous variant, in case <limits.h> declares $2. For example, HP-UX 11i <limits.h> declares gettimeofday. */ #define $2 innocuous_$2 /* System header to define __stub macros and hopefully few prototypes, - which can conflict with char $2 (); below. */ + which can conflict with char $2 (void); below. */ #include <limits.h> #undef $2 @@ -1830,7 +1832,7 @@ else $as_nop #ifdef __cplusplus extern "C" #endif -char $2 (); +char $2 (void); /* The GNU C library defines this for functions which it implements to always fail with ENOSYS. Some functions are actually named something starting with __ and the normal name is an alias. */ @@ -1849,11 +1851,13 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : eval "$3=yes" -else $as_nop - eval "$3=no" +else case e in #( + e) eval "$3=no" ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ - conftest$ac_exeext conftest.$ac_ext + conftest$ac_exeext conftest.$ac_ext ;; +esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -1889,11 +1893,12 @@ printf "%s\n" "$ac_try_echo"; } >&5 } then : ac_retval=0 -else $as_nop - printf "%s\n" "$as_me: failed program was:" >&5 +else case e in #( + e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_retval=1 + ac_retval=1 ;; +esac fi eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval @@ -1931,11 +1936,12 @@ printf "%s\n" "$ac_try_echo"; } >&5 } then : ac_retval=0 -else $as_nop - printf "%s\n" "$as_me: failed program was:" >&5 +else case e in #( + e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_retval=1 + ac_retval=1 ;; +esac fi # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would @@ -1977,12 +1983,13 @@ printf "%s\n" "$ac_try_echo"; } >&5 test $ac_status = 0; }; } then : ac_retval=0 -else $as_nop - printf "%s\n" "$as_me: program exited with status $ac_status" >&5 +else case e in #( + e) printf "%s\n" "$as_me: program exited with status $ac_status" >&5 printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 - ac_retval=$ac_status + ac_retval=$ac_status ;; +esac fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno @@ -2035,18 +2042,19 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_hi=$ac_mid; break -else $as_nop - as_fn_arith $ac_mid + 1 && ac_lo=$as_val +else case e in #( + e) as_fn_arith $ac_mid + 1 && ac_lo=$as_val if test $ac_lo -le $ac_mid; then ac_lo= ac_hi= break fi - as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val + as_fn_arith 2 '*' $ac_mid + 1 && ac_mid=$as_val ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext done -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 int @@ -2081,20 +2089,23 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_lo=$ac_mid; break -else $as_nop - as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val +else case e in #( + e) as_fn_arith '(' $ac_mid ')' - 1 && ac_hi=$as_val if test $ac_mid -le $ac_hi; then ac_lo= ac_hi= break fi - as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val + as_fn_arith 2 '*' $ac_mid && ac_mid=$as_val ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext done -else $as_nop - ac_lo= ac_hi= +else case e in #( + e) ac_lo= ac_hi= ;; +esac fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext # Binary search between lo and hi bounds. @@ -2117,8 +2128,9 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_hi=$ac_mid -else $as_nop - as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val +else case e in #( + e) as_fn_arith '(' $ac_mid ')' + 1 && ac_lo=$as_val ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext done @@ -2166,8 +2178,9 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : echo >>conftest.val; read $3 <conftest.val; ac_retval=0 -else $as_nop - ac_retval=1 +else case e in #( + e) ac_retval=1 ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ conftest.$ac_objext conftest.beam conftest.$ac_ext @@ -2191,8 +2204,8 @@ printf %s "checking for $2... " >&6; } if eval test \${$3+y} then : printf %s "(cached) " >&6 -else $as_nop - eval "$3=no" +else case e in #( + e) eval "$3=no" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $4 @@ -2222,12 +2235,14 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : -else $as_nop - eval "$3=yes" +else case e in #( + e) eval "$3=yes" ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi eval ac_res=\$$3 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -2259,8 +2274,8 @@ cat >config.log <<_ACEOF This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. -It was created by libffi $as_me 3.8.0, which was -generated by GNU Autoconf 2.71. Invocation command line was +It was created by libffi $as_me 3.8.1, which was +generated by GNU Autoconf 2.72. Invocation command line was $ $0$ac_configure_args_raw @@ -2506,10 +2521,10 @@ esac printf "%s\n" "$as_me: loading site script $ac_site_file" >&6;} sed 's/^/| /' "$ac_site_file" >&5 . "$ac_site_file" \ - || { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} + || { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } fi done @@ -2545,9 +2560,7 @@ struct stat; /* Most of the following tests are stolen from RCS 5.7 src/conf.sh. */ struct buf { int x; }; struct buf * (*rcsopen) (struct buf *, struct stat *, int); -static char *e (p, i) - char **p; - int i; +static char *e (char **p, int i) { return p[i]; } @@ -2561,6 +2574,21 @@ static char *f (char * (*g) (char **, int), char **p, ...) return s; } +/* C89 style stringification. */ +#define noexpand_stringify(a) #a +const char *stringified = noexpand_stringify(arbitrary+token=sequence); + +/* C89 style token pasting. Exercises some of the corner cases that + e.g. old MSVC gets wrong, but not very hard. */ +#define noexpand_concat(a,b) a##b +#define expand_concat(a,b) noexpand_concat(a,b) +extern int vA; +extern int vbee; +#define aye A +#define bee B +int *pvA = &expand_concat(v,aye); +int *pvbee = &noexpand_concat(v,bee); + /* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has function prototypes and stuff, but not \xHH hex character constants. These do not provoke an error unfortunately, instead are silently treated @@ -2588,16 +2616,19 @@ ok |= (argc == 0 || f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]); # Test code for whether the C compiler supports C99 (global declarations) ac_c_conftest_c99_globals=' -// Does the compiler advertise C99 conformance? +/* Does the compiler advertise C99 conformance? */ #if !defined __STDC_VERSION__ || __STDC_VERSION__ < 199901L # error "Compiler does not advertise C99 conformance" #endif +// See if C++-style comments work. + #include <stdbool.h> extern int puts (const char *); extern int printf (const char *, ...); extern int dprintf (int, const char *, ...); extern void *malloc (size_t); +extern void free (void *); // Check varargs macros. These examples are taken from C99 6.10.3.5. // dprintf is used instead of fprintf to avoid needing to declare @@ -2647,7 +2678,6 @@ typedef const char *ccp; static inline int test_restrict (ccp restrict text) { - // See if C++-style comments work. // Iterate through items via the restricted pointer. // Also check for declarations in for loops. for (unsigned int i = 0; *(text+i) != '\''\0'\''; ++i) @@ -2713,6 +2743,8 @@ ac_c_conftest_c99_main=' ia->datasize = 10; for (int i = 0; i < ia->datasize; ++i) ia->data[i] = i * 1.234; + // Work around memory leak warnings. + free (ia); // Check named initializers. struct named_init ni = { @@ -2734,7 +2766,7 @@ ac_c_conftest_c99_main=' # Test code for whether the C compiler supports C11 (global declarations) ac_c_conftest_c11_globals=' -// Does the compiler advertise C11 conformance? +/* Does the compiler advertise C11 conformance? */ #if !defined __STDC_VERSION__ || __STDC_VERSION__ < 201112L # error "Compiler does not advertise C11 conformance" #endif @@ -3142,8 +3174,9 @@ IFS=$as_save_IFS if $as_found then : -else $as_nop - as_fn_error $? "cannot find required auxiliary files:$ac_missing_aux_files" "$LINENO" 5 +else case e in #( + e) as_fn_error $? "cannot find required auxiliary files:$ac_missing_aux_files" "$LINENO" 5 ;; +esac fi @@ -3171,12 +3204,12 @@ for ac_var in $ac_precious_vars; do eval ac_new_val=\$ac_env_${ac_var}_value case $ac_old_set,$ac_new_set in set,) - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 -printf "%s\n" "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: '$ac_var' was set to '$ac_old_val' in the previous run" >&5 +printf "%s\n" "$as_me: error: '$ac_var' was set to '$ac_old_val' in the previous run" >&2;} ac_cache_corrupted=: ;; ,set) - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 -printf "%s\n" "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: '$ac_var' was not set in the previous run" >&5 +printf "%s\n" "$as_me: error: '$ac_var' was not set in the previous run" >&2;} ac_cache_corrupted=: ;; ,);; *) @@ -3185,18 +3218,18 @@ printf "%s\n" "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} ac_old_val_w=`echo x $ac_old_val` ac_new_val_w=`echo x $ac_new_val` if test "$ac_old_val_w" != "$ac_new_val_w"; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 -printf "%s\n" "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: '$ac_var' has changed since the previous run:" >&5 +printf "%s\n" "$as_me: error: '$ac_var' has changed since the previous run:" >&2;} ac_cache_corrupted=: else - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 -printf "%s\n" "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in '$ac_var' since the previous run:" >&5 +printf "%s\n" "$as_me: warning: ignoring whitespace changes in '$ac_var' since the previous run:" >&2;} eval $ac_var=\$ac_old_val fi - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 -printf "%s\n" "$as_me: former value: \`$ac_old_val'" >&2;} - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 -printf "%s\n" "$as_me: current value: \`$ac_new_val'" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: former value: '$ac_old_val'" >&5 +printf "%s\n" "$as_me: former value: '$ac_old_val'" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: current value: '$ac_new_val'" >&5 +printf "%s\n" "$as_me: current value: '$ac_new_val'" >&2;} fi;; esac # Pass precious variables to config.status. @@ -3212,11 +3245,11 @@ printf "%s\n" "$as_me: current value: \`$ac_new_val'" >&2;} fi done if $ac_cache_corrupted; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 printf "%s\n" "$as_me: error: changes in the environment can compromise the build" >&2;} - as_fn_error $? "run \`${MAKE-make} distclean' and/or \`rm $cache_file' + as_fn_error $? "run '${MAKE-make} distclean' and/or 'rm $cache_file' and start over" "$LINENO" 5 fi ## -------------------- ## @@ -3233,10 +3266,10 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu ac_config_headers="$ac_config_headers fficonfig.h" -FFI_VERSION_STRING="3.8.0" -ffi_version_major=`echo "3.8.0" | cut -d. -f1` -ffi_version_minor=`echo "3.8.0" | cut -d. -f2 | sed 's/[^0-9].*//'` -ffi_version_micro=`echo "3.8.0" | cut -d. -f3 | sed 's/[^0-9].*//'` +FFI_VERSION_STRING="3.8.1" +ffi_version_major=`echo "3.8.1" | cut -d. -f1` +ffi_version_minor=`echo "3.8.1" | cut -d. -f2 | sed 's/[^0-9].*//'` +ffi_version_micro=`echo "3.8.1" | cut -d. -f3 | sed 's/[^0-9].*//'` FFI_VERSION_NUMBER=`expr ${ffi_version_major:-0} \* 10000 + ${ffi_version_minor:-0} \* 100 + ${ffi_version_micro:-0}` @@ -3253,15 +3286,16 @@ printf %s "checking build system type... " >&6; } if test ${ac_cv_build+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_build_alias=$build_alias +else case e in #( + e) ac_build_alias=$build_alias test "x$ac_build_alias" = x && ac_build_alias=`$SHELL "${ac_aux_dir}config.guess"` test "x$ac_build_alias" = x && as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 ac_cv_build=`$SHELL "${ac_aux_dir}config.sub" $ac_build_alias` || as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $ac_build_alias failed" "$LINENO" 5 - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 printf "%s\n" "$ac_cv_build" >&6; } @@ -3288,14 +3322,15 @@ printf %s "checking host system type... " >&6; } if test ${ac_cv_host+y} then : printf %s "(cached) " >&6 -else $as_nop - if test "x$host_alias" = x; then +else case e in #( + e) if test "x$host_alias" = x; then ac_cv_host=$ac_cv_build else ac_cv_host=`$SHELL "${ac_aux_dir}config.sub" $host_alias` || as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $host_alias failed" "$LINENO" 5 fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 printf "%s\n" "$ac_cv_host" >&6; } @@ -3322,14 +3357,15 @@ printf %s "checking target system type... " >&6; } if test ${ac_cv_target+y} then : printf %s "(cached) " >&6 -else $as_nop - if test "x$target_alias" = x; then +else case e in #( + e) if test "x$target_alias" = x; then ac_cv_target=$ac_cv_host else ac_cv_target=`$SHELL "${ac_aux_dir}config.sub" $target_alias` || as_fn_error $? "$SHELL ${ac_aux_dir}config.sub $target_alias failed" "$LINENO" 5 fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_target" >&5 printf "%s\n" "$ac_cv_target" >&6; } @@ -3384,8 +3420,9 @@ ax_enable_builddir="." if test ${enable_builddir+y} then : enableval=$enable_builddir; ax_enable_builddir="$enableval" -else $as_nop - ax_enable_builddir="auto" +else case e in #( + e) ax_enable_builddir="auto" ;; +esac fi if test ".$ac_srcdir_defaulted" != ".no" ; then @@ -3434,8 +3471,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_ax_enable_builddir_sed+y} then : printf %s "(cached) " >&6 -else $as_nop - case $ax_enable_builddir_sed in +else case e in #( + e) case $ax_enable_builddir_sed in [\\/]* | ?:[\\/]*) ac_cv_path_ax_enable_builddir_sed="$ax_enable_builddir_sed" # Let the user override the test with a path. ;; @@ -3461,6 +3498,7 @@ IFS=$as_save_IFS test -z "$ac_cv_path_ax_enable_builddir_sed" && ac_cv_path_ax_enable_builddir_sed="sed" ;; +esac ;; esac fi ax_enable_builddir_sed=$ac_cv_path_ax_enable_builddir_sed @@ -3477,7 +3515,7 @@ ax_enable_builddir_auxdir="$am_aux_dir" ac_config_commands="$ac_config_commands buildir" -am__api_version='1.16' +am__api_version='1.18' # Find a good install program. We prefer a C program (faster), @@ -3500,8 +3538,8 @@ if test -z "$INSTALL"; then if test ${ac_cv_path_install+y} then : printf %s "(cached) " >&6 -else $as_nop - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +else case e in #( + e) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH do IFS=$as_save_IFS @@ -3555,7 +3593,8 @@ esac IFS=$as_save_IFS rm -rf conftest.one conftest.two conftest.dir - + ;; +esac fi if test ${ac_cv_path_install+y}; then INSTALL=$ac_cv_path_install @@ -3578,6 +3617,165 @@ test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether sleep supports fractional seconds" >&5 +printf %s "checking whether sleep supports fractional seconds... " >&6; } +if test ${am_cv_sleep_fractional_seconds+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) if sleep 0.001 2>/dev/null +then : + am_cv_sleep_fractional_seconds=yes +else case e in #( + e) am_cv_sleep_fractional_seconds=no ;; +esac +fi + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_sleep_fractional_seconds" >&5 +printf "%s\n" "$am_cv_sleep_fractional_seconds" >&6; } + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking filesystem timestamp resolution" >&5 +printf %s "checking filesystem timestamp resolution... " >&6; } +if test ${am_cv_filesystem_timestamp_resolution+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) # Default to the worst case. +am_cv_filesystem_timestamp_resolution=2 + +# Only try to go finer than 1 sec if sleep can do it. +# Don't try 1 sec, because if 0.01 sec and 0.1 sec don't work, +# - 1 sec is not much of a win compared to 2 sec, and +# - it takes 2 seconds to perform the test whether 1 sec works. +# +# Instead, just use the default 2s on platforms that have 1s resolution, +# accept the extra 1s delay when using $sleep in the Automake tests, in +# exchange for not incurring the 2s delay for running the test for all +# packages. +# +am_try_resolutions= +if test "$am_cv_sleep_fractional_seconds" = yes; then + # Even a millisecond often causes a bunch of false positives, + # so just try a hundredth of a second. The time saved between .001 and + # .01 is not terribly consequential. + am_try_resolutions="0.01 0.1 $am_try_resolutions" +fi + +# In order to catch current-generation FAT out, we must *modify* files +# that already exist; the *creation* timestamp is finer. Use names +# that make ls -t sort them differently when they have equal +# timestamps than when they have distinct timestamps, keeping +# in mind that ls -t prints the *newest* file first. +rm -f conftest.ts? +: > conftest.ts1 +: > conftest.ts2 +: > conftest.ts3 + +# Make sure ls -t actually works. Do 'set' in a subshell so we don't +# clobber the current shell's arguments. (Outer-level square brackets +# are removed by m4; they're present so that m4 does not expand +# <dollar><star>; be careful, easy to get confused.) +if ( + set X `ls -t conftest.ts[12]` && + { + test "$*" != "X conftest.ts1 conftest.ts2" || + test "$*" != "X conftest.ts2 conftest.ts1"; + } +); then :; else + # If neither matched, then we have a broken ls. This can happen + # if, for instance, CONFIG_SHELL is bash and it inherits a + # broken ls alias from the environment. This has actually + # happened. Such a system could not be considered "sane". + printf "%s\n" ""Bad output from ls -t: \"`ls -t conftest.ts[12]`\""" >&5 + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} +as_fn_error $? "ls -t produces unexpected output. +Make sure there is not a broken ls alias in your environment. +See 'config.log' for more details" "$LINENO" 5; } +fi + +for am_try_res in $am_try_resolutions; do + # Any one fine-grained sleep might happen to cross the boundary + # between two values of a coarser actual resolution, but if we do + # two fine-grained sleeps in a row, at least one of them will fall + # entirely within a coarse interval. + echo alpha > conftest.ts1 + sleep $am_try_res + echo beta > conftest.ts2 + sleep $am_try_res + echo gamma > conftest.ts3 + + # We assume that 'ls -t' will make use of high-resolution + # timestamps if the operating system supports them at all. + if (set X `ls -t conftest.ts?` && + test "$2" = conftest.ts3 && + test "$3" = conftest.ts2 && + test "$4" = conftest.ts1); then + # + # Ok, ls -t worked. If we're at a resolution of 1 second, we're done, + # because we don't need to test make. + make_ok=true + if test $am_try_res != 1; then + # But if we've succeeded so far with a subsecond resolution, we + # have one more thing to check: make. It can happen that + # everything else supports the subsecond mtimes, but make doesn't; + # notably on macOS, which ships make 3.81 from 2006 (the last one + # released under GPLv2). https://bugs.gnu.org/68808 + # + # We test $MAKE if it is defined in the environment, else "make". + # It might get overridden later, but our hope is that in practice + # it does not matter: it is the system "make" which is (by far) + # the most likely to be broken, whereas if the user overrides it, + # probably they did so with a better, or at least not worse, make. + # https://lists.gnu.org/archive/html/automake/2024-06/msg00051.html + # + # Create a Makefile (real tab character here): + rm -f conftest.mk + echo 'conftest.ts1: conftest.ts2' >conftest.mk + echo ' touch conftest.ts2' >>conftest.mk + # + # Now, running + # touch conftest.ts1; touch conftest.ts2; make + # should touch ts1 because ts2 is newer. This could happen by luck, + # but most often, it will fail if make's support is insufficient. So + # test for several consecutive successes. + # + # (We reuse conftest.ts[12] because we still want to modify existing + # files, not create new ones, per above.) + n=0 + make=${MAKE-make} + until test $n -eq 3; do + echo one > conftest.ts1 + sleep $am_try_res + echo two > conftest.ts2 # ts2 should now be newer than ts1 + if $make -f conftest.mk | grep 'up to date' >/dev/null; then + make_ok=false + break # out of $n loop + fi + n=`expr $n + 1` + done + fi + # + if $make_ok; then + # Everything we know to check worked out, so call this resolution good. + am_cv_filesystem_timestamp_resolution=$am_try_res + break # out of $am_try_res loop + fi + # Otherwise, we'll go on to check the next resolution. + fi +done +rm -f conftest.ts? +# (end _am_filesystem_timestamp_resolution) + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_filesystem_timestamp_resolution" >&5 +printf "%s\n" "$am_cv_filesystem_timestamp_resolution" >&6; } + +# This check should not be cached, as it may vary across builds of +# different projects. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether build environment is sane" >&5 printf %s "checking whether build environment is sane... " >&6; } # Reject unsafe characters in $srcdir or the absolute working directory @@ -3586,10 +3784,14 @@ am_lf=' ' case `pwd` in *[\\\"\#\$\&\'\`$am_lf]*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } as_fn_error $? "unsafe absolute working directory name" "$LINENO" 5;; esac case $srcdir in *[\\\"\#\$\&\'\`$am_lf\ \ ]*) + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } as_fn_error $? "unsafe srcdir value: '$srcdir'" "$LINENO" 5;; esac @@ -3598,49 +3800,45 @@ esac # symlink; some systems play weird games with the mod time of symlinks # (eg FreeBSD returns the mod time of the symlink's containing # directory). -if ( - am_has_slept=no - for am_try in 1 2; do - echo "timestamp, slept: $am_has_slept" > conftest.file - set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` - if test "$*" = "X"; then - # -L didn't work. - set X `ls -t "$srcdir/configure" conftest.file` - fi - if test "$*" != "X $srcdir/configure conftest.file" \ - && test "$*" != "X conftest.file $srcdir/configure"; then - - # If neither matched, then we have a broken ls. This can happen - # if, for instance, CONFIG_SHELL is bash and it inherits a - # broken ls alias from the environment. This has actually - # happened. Such a system could not be considered "sane". - as_fn_error $? "ls -t appears to fail. Make sure there is not a broken - alias in your environment" "$LINENO" 5 - fi - if test "$2" = conftest.file || test $am_try -eq 2; then - break - fi - # Just in case. - sleep 1 - am_has_slept=yes - done - test "$2" = conftest.file - ) -then - # Ok. - : -else - as_fn_error $? "newly created file is older than distributed files! +am_build_env_is_sane=no +am_has_slept=no +rm -f conftest.file +for am_try in 1 2; do + echo "timestamp, slept: $am_has_slept" > conftest.file + if ( + set X `ls -Lt "$srcdir/configure" conftest.file 2> /dev/null` + if test "$*" = "X"; then + # -L didn't work. + set X `ls -t "$srcdir/configure" conftest.file` + fi + test "$2" = conftest.file + ); then + am_build_env_is_sane=yes + break + fi + # Just in case. + sleep "$am_cv_filesystem_timestamp_resolution" + am_has_slept=yes +done + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_build_env_is_sane" >&5 +printf "%s\n" "$am_build_env_is_sane" >&6; } +if test "$am_build_env_is_sane" = no; then + as_fn_error $? "newly created file is older than distributed files! Check your system clock" "$LINENO" 5 fi -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -printf "%s\n" "yes" >&6; } + # If we didn't sleep, we still need to ensure time stamps of config.status and # generated files are strictly newer. am_sleep_pid= -if grep 'slept: no' conftest.file >/dev/null 2>&1; then - ( sleep 1 ) & +if test -e conftest.file || grep 'slept: no' conftest.file >/dev/null 2>&1 +then : + +else case e in #( + e) ( sleep "$am_cv_filesystem_timestamp_resolution" ) & am_sleep_pid=$! + ;; +esac fi rm -f conftest.file @@ -3651,7 +3849,7 @@ test "$program_prefix" != NONE && test "$program_suffix" != NONE && program_transform_name="s&\$&$program_suffix&;$program_transform_name" # Double any \ or $. -# By default was `s,x,x', remove it if useless. +# By default was 's,x,x', remove it if useless. ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' program_transform_name=`printf "%s\n" "$program_transform_name" | sed "$ac_script"` @@ -3690,8 +3888,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_STRIP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$STRIP"; then +else case e in #( + e) if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -3713,7 +3911,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then @@ -3735,8 +3934,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_STRIP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_STRIP"; then +else case e in #( + e) if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -3758,7 +3957,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then @@ -3794,8 +3994,8 @@ if test -z "$MKDIR_P"; then if test ${ac_cv_path_mkdir+y} then : printf %s "(cached) " >&6 -else $as_nop - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +else case e in #( + e) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR for as_dir in $PATH$PATH_SEPARATOR/opt/sfw/bin do IFS=$as_save_IFS @@ -3809,7 +4009,7 @@ do as_fn_executable_p "$as_dir$ac_prog$ac_exec_ext" || continue case `"$as_dir$ac_prog$ac_exec_ext" --version 2>&1` in #( 'mkdir ('*'coreutils) '* | \ - 'BusyBox '* | \ + *'BusyBox '* | \ 'mkdir (fileutils) '4.1*) ac_cv_path_mkdir=$as_dir$ac_prog$ac_exec_ext break 3;; @@ -3818,18 +4018,17 @@ do done done IFS=$as_save_IFS - + ;; +esac fi test -d ./--version && rmdir ./--version if test ${ac_cv_path_mkdir+y}; then MKDIR_P="$ac_cv_path_mkdir -p" else - # As a last resort, use the slow shell script. Don't cache a - # value for MKDIR_P within a source directory, because that will - # break other packages using the cache if that directory is - # removed, or if the value is a relative name. - MKDIR_P="$ac_install_sh -d" + # As a last resort, use plain mkdir -p, + # in the hope it doesn't have the bugs of ancient mkdir. + MKDIR_P='mkdir -p' fi fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $MKDIR_P" >&5 @@ -3844,8 +4043,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_AWK+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$AWK"; then +else case e in #( + e) if test -n "$AWK"; then ac_cv_prog_AWK="$AWK" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -3867,7 +4066,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi AWK=$ac_cv_prog_AWK if test -n "$AWK"; then @@ -3889,8 +4089,8 @@ ac_make=`printf "%s\n" "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` if eval test \${ac_cv_prog_make_${ac_make}_set+y} then : printf %s "(cached) " >&6 -else $as_nop - cat >conftest.make <<\_ACEOF +else case e in #( + e) cat >conftest.make <<\_ACEOF SHELL = /bin/sh all: @echo '@@@%%%=$(MAKE)=@@@%%%' @@ -3902,7 +4102,8 @@ case `${MAKE-make} -f conftest.make 2>/dev/null` in *) eval ac_cv_prog_make_${ac_make}_set=no;; esac -rm -f conftest.make +rm -f conftest.make ;; +esac fi if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 @@ -3923,25 +4124,21 @@ else fi rmdir .tst 2>/dev/null +AM_DEFAULT_VERBOSITY=1 # Check whether --enable-silent-rules was given. if test ${enable_silent_rules+y} then : enableval=$enable_silent_rules; fi -case $enable_silent_rules in # ((( - yes) AM_DEFAULT_VERBOSITY=0;; - no) AM_DEFAULT_VERBOSITY=1;; - *) AM_DEFAULT_VERBOSITY=1;; -esac am_make=${MAKE-make} { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether $am_make supports nested variables" >&5 printf %s "checking whether $am_make supports nested variables... " >&6; } if test ${am_cv_make_support_nested_variables+y} then : printf %s "(cached) " >&6 -else $as_nop - if printf "%s\n" 'TRUE=$(BAR$(V)) +else case e in #( + e) if printf "%s\n" 'TRUE=$(BAR$(V)) BAR0=false BAR1=true V=1 @@ -3951,19 +4148,50 @@ am__doit: am_cv_make_support_nested_variables=yes else am_cv_make_support_nested_variables=no -fi +fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_make_support_nested_variables" >&5 printf "%s\n" "$am_cv_make_support_nested_variables" >&6; } -if test $am_cv_make_support_nested_variables = yes; then - AM_V='$(V)' - AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' -else - AM_V=$AM_DEFAULT_VERBOSITY - AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY -fi AM_BACKSLASH='\' +am__rm_f_notfound= +if (rm -f && rm -fr && rm -rf) 2>/dev/null +then : + +else case e in #( + e) am__rm_f_notfound='""' ;; +esac +fi + + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking xargs -n works" >&5 +printf %s "checking xargs -n works... " >&6; } +if test ${am_cv_xargs_n_works+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) if test "`echo 1 2 3 | xargs -n2 echo`" = "1 2 +3" +then : + am_cv_xargs_n_works=yes +else case e in #( + e) am_cv_xargs_n_works=no ;; +esac +fi ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_xargs_n_works" >&5 +printf "%s\n" "$am_cv_xargs_n_works" >&6; } +if test "$am_cv_xargs_n_works" = yes +then : + am__xargs_n='xargs -n' +else case e in #( + e) am__xargs_n='am__xargs_n () { shift; sed "s/ /\\n/g" | while read am__xargs_n_arg; do "" "$am__xargs_n_arg"; done; }' + ;; +esac +fi + if test "`cd $srcdir && pwd`" != "`pwd`"; then # Use -I$(srcdir) only when $(srcdir) != ., so that make's output # is not polluted with repeated "-I." @@ -3986,7 +4214,7 @@ fi # Define the identity of the package. PACKAGE='libffi' - VERSION='3.8.0' + VERSION='3.8.1' printf "%s\n" "#define PACKAGE \"$PACKAGE\"" >>confdefs.h @@ -4024,9 +4252,133 @@ AMTAR='$${TAR-tar}' # We'll loop over all known methods to create a tar archive until one works. -_am_tools='gnutar pax cpio none' +_am_tools='gnutar plaintar pax cpio none' + +# The POSIX 1988 'ustar' format is defined with fixed-size fields. + # There is notably a 21 bits limit for the UID and the GID. In fact, + # the 'pax' utility can hang on bigger UID/GID (see automake bug#8343 + # and bug#13588). + am_max_uid=2097151 # 2^21 - 1 + am_max_gid=$am_max_uid + # The $UID and $GID variables are not portable, so we need to resort + # to the POSIX-mandated id(1) utility. Errors in the 'id' calls + # below are definitely unexpected, so allow the users to see them + # (that is, avoid stderr redirection). + am_uid=`id -u || echo unknown` + am_gid=`id -g || echo unknown` + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether UID '$am_uid' is supported by ustar format" >&5 +printf %s "checking whether UID '$am_uid' is supported by ustar format... " >&6; } + if test x$am_uid = xunknown; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: ancient id detected; assuming current UID is ok, but dist-ustar might not work" >&5 +printf "%s\n" "$as_me: WARNING: ancient id detected; assuming current UID is ok, but dist-ustar might not work" >&2;} + elif test $am_uid -le $am_max_uid; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + _am_tools=none + fi + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether GID '$am_gid' is supported by ustar format" >&5 +printf %s "checking whether GID '$am_gid' is supported by ustar format... " >&6; } + if test x$gm_gid = xunknown; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: ancient id detected; assuming current GID is ok, but dist-ustar might not work" >&5 +printf "%s\n" "$as_me: WARNING: ancient id detected; assuming current GID is ok, but dist-ustar might not work" >&2;} + elif test $am_gid -le $am_max_gid; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } + else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } + _am_tools=none + fi + + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking how to create a ustar tar archive" >&5 +printf %s "checking how to create a ustar tar archive... " >&6; } + + # Go ahead even if we have the value already cached. We do so because we + # need to set the values for the 'am__tar' and 'am__untar' variables. + _am_tools=${am_cv_prog_tar_ustar-$_am_tools} + + for _am_tool in $_am_tools; do + case $_am_tool in + gnutar) + for _am_tar in tar gnutar gtar; do + { echo "$as_me:$LINENO: $_am_tar --version" >&5 + ($_am_tar --version) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } && break + done + am__tar="$_am_tar --format=ustar -chf - "'"$$tardir"' + am__tar_="$_am_tar --format=ustar -chf - "'"$tardir"' + am__untar="$_am_tar -xf -" + ;; + plaintar) + # Must skip GNU tar: if it does not support --format= it doesn't create + # ustar tarball either. + (tar --version) >/dev/null 2>&1 && continue + am__tar='tar chf - "$$tardir"' + am__tar_='tar chf - "$tardir"' + am__untar='tar xf -' + ;; + pax) + am__tar='pax -L -x ustar -w "$$tardir"' + am__tar_='pax -L -x ustar -w "$tardir"' + am__untar='pax -r' + ;; + cpio) + am__tar='find "$$tardir" -print | cpio -o -H ustar -L' + am__tar_='find "$tardir" -print | cpio -o -H ustar -L' + am__untar='cpio -i -H ustar -d' + ;; + none) + am__tar=false + am__tar_=false + am__untar=false + ;; + esac + + # If the value was cached, stop now. We just wanted to have am__tar + # and am__untar set. + test -n "${am_cv_prog_tar_ustar}" && break + + # tar/untar a dummy directory, and stop if the command works. + rm -rf conftest.dir + mkdir conftest.dir + echo GrepMe > conftest.dir/file + { echo "$as_me:$LINENO: tardir=conftest.dir && eval $am__tar_ >conftest.tar" >&5 + (tardir=conftest.dir && eval $am__tar_ >conftest.tar) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + rm -rf conftest.dir + if test -s conftest.tar; then + { echo "$as_me:$LINENO: $am__untar <conftest.tar" >&5 + ($am__untar <conftest.tar) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + { echo "$as_me:$LINENO: cat conftest.dir/file" >&5 + (cat conftest.dir/file) >&5 2>&5 + ac_status=$? + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + (exit $ac_status); } + grep GrepMe conftest.dir/file >/dev/null 2>&1 && break + fi + done + rm -rf conftest.dir + + if test ${am_cv_prog_tar_ustar+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) am_cv_prog_tar_ustar=$_am_tool ;; +esac +fi -am__tar='$${TAR-tar} chof - "$$tardir"' am__untar='$${TAR-tar} xf -' + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_tar_ustar" >&5 +printf "%s\n" "$am_cv_prog_tar_ustar" >&6; } @@ -4047,47 +4399,9 @@ fi -# POSIX will say in a future version that running "rm -f" with no argument -# is OK; and we want to be able to make that assumption in our Makefile -# recipes. So use an aggressive probe to check that the usage we want is -# actually supported "in the wild" to an acceptable degree. -# See automake bug#10828. -# To make any issue more visible, cause the running configure to be aborted -# by default if the 'rm' program in use doesn't match our expectations; the -# user can still override this though. -if rm -f && rm -fr && rm -rf; then : OK; else - cat >&2 <<'END' -Oops! - -Your 'rm' program seems unable to run without file operands specified -on the command line, even when the '-f' option is present. This is contrary -to the behaviour of most rm programs out there, and not conforming with -the upcoming POSIX standard: <http://austingroupbugs.net/view.php?id=542> -Please tell bug-automake@gnu.org about your system, including the value -of your $PATH and any error possibly output before this message. This -can help us improve future automake versions. -END - if test x"$ACCEPT_INFERIOR_RM_PROGRAM" = x"yes"; then - echo 'Configuration will proceed anyway, since you have set the' >&2 - echo 'ACCEPT_INFERIOR_RM_PROGRAM variable to "yes"' >&2 - echo >&2 - else - cat >&2 <<'END' -Aborting the configuration process, to ensure you take notice of the issue. - -You can download and install GNU coreutils to get an 'rm' implementation -that behaves properly: <https://www.gnu.org/software/coreutils/>. - -If you want to complete the configuration process using your problematic -'rm' anyway, export the environment variable ACCEPT_INFERIOR_RM_PROGRAM -to "yes", and re-run configure. -END - as_fn_error $? "Your 'rm' program is bad, sorry." "$LINENO" 5 - fi -fi # The same as in boehm-gc and libstdc++. Have to borrow it from there. @@ -4122,8 +4436,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$CC"; then +else case e in #( + e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4145,7 +4459,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then @@ -4167,8 +4482,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_CC"; then +else case e in #( + e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4190,7 +4505,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then @@ -4225,8 +4541,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$CC"; then +else case e in #( + e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4248,7 +4564,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then @@ -4270,8 +4587,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$CC"; then +else case e in #( + e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else ac_prog_rejected=no @@ -4310,7 +4627,8 @@ if test $ac_prog_rejected = yes; then ac_cv_prog_CC="$as_dir$ac_word${1+' '}$@" fi fi -fi +fi ;; +esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then @@ -4334,8 +4652,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$CC"; then +else case e in #( + e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4357,7 +4675,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then @@ -4383,8 +4702,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_CC"; then +else case e in #( + e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4406,7 +4725,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then @@ -4444,8 +4764,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$CC"; then +else case e in #( + e) if test -n "$CC"; then ac_cv_prog_CC="$CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4467,7 +4787,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi CC=$ac_cv_prog_CC if test -n "$CC"; then @@ -4489,8 +4810,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CC+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_CC"; then +else case e in #( + e) if test -n "$ac_ct_CC"; then ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -4512,7 +4833,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_CC=$ac_cv_prog_ac_ct_CC if test -n "$ac_ct_CC"; then @@ -4541,10 +4863,10 @@ fi fi -test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +test -z "$CC" && { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 @@ -4616,8 +4938,8 @@ printf "%s\n" "$ac_try_echo"; } >&5 printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then : - # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. -# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' + # Autoconf-2.13 could set the ac_cv_exeext variable to 'no'. +# So ignore a value of 'no', otherwise this would lead to 'EXEEXT = no' # in a Makefile. We should not override ac_cv_exeext if it was cached, # so that the user can short-circuit this test for compilers unknown to # Autoconf. @@ -4637,7 +4959,7 @@ do ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` fi # We set ac_cv_exeext here because the later test for it is not - # safe: cross compilers may not add the suffix if given an `-o' + # safe: cross compilers may not add the suffix if given an '-o' # argument, so we may need to know it at that point already. # Even if this section looks crufty: it has the advantage of # actually working. @@ -4648,8 +4970,9 @@ do done test "$ac_cv_exeext" = no && ac_cv_exeext= -else $as_nop - ac_file='' +else case e in #( + e) ac_file='' ;; +esac fi if test -z "$ac_file" then : @@ -4658,13 +4981,14 @@ printf "%s\n" "no" >&6; } printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables -See \`config.log' for more details" "$LINENO" 5; } -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 -printf "%s\n" "yes" >&6; } +See 'config.log' for more details" "$LINENO" 5; } +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +printf "%s\n" "yes" >&6; } ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 printf %s "checking for C compiler default output file name... " >&6; } @@ -4688,10 +5012,10 @@ printf "%s\n" "$ac_try_echo"; } >&5 printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } then : - # If both `conftest.exe' and `conftest' are `present' (well, observable) -# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will -# work properly (i.e., refer to `conftest.exe'), while it won't with -# `rm'. + # If both 'conftest.exe' and 'conftest' are 'present' (well, observable) +# catch 'conftest.exe'. For instance with Cygwin, 'ls conftest' will +# work properly (i.e., refer to 'conftest.exe'), while it won't with +# 'rm'. for ac_file in conftest.exe conftest conftest.*; do test -f "$ac_file" || continue case $ac_file in @@ -4701,11 +5025,12 @@ for ac_file in conftest.exe conftest conftest.*; do * ) break;; esac done -else $as_nop - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +else case e in #( + e) { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } ;; +esac fi rm -f conftest conftest$ac_cv_exeext { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 @@ -4721,6 +5046,8 @@ int main (void) { FILE *f = fopen ("conftest.out", "w"); + if (!f) + return 1; return ferror (f) || fclose (f) != 0; ; @@ -4760,26 +5087,27 @@ printf "%s\n" "$ac_try_echo"; } >&5 if test "$cross_compiling" = maybe; then cross_compiling=yes else - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "cannot run C compiled programs. -If you meant to cross compile, use \`--host'. -See \`config.log' for more details" "$LINENO" 5; } +If you meant to cross compile, use '--host'. +See 'config.log' for more details" "$LINENO" 5; } fi fi fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 printf "%s\n" "$cross_compiling" >&6; } -rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +rm -f conftest.$ac_ext conftest$ac_cv_exeext \ + conftest.o conftest.obj conftest.out ac_clean_files=$ac_clean_files_save { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 printf %s "checking for suffix of object files... " >&6; } if test ${ac_cv_objext+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -4811,16 +5139,18 @@ then : break;; esac done -else $as_nop - printf "%s\n" "$as_me: failed program was:" >&5 +else case e in #( + e) printf "%s\n" "$as_me: failed program was:" >&5 sed 's/^/| /' conftest.$ac_ext >&5 -{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +{ { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } ;; +esac fi -rm -f conftest.$ac_cv_objext conftest.$ac_ext +rm -f conftest.$ac_cv_objext conftest.$ac_ext ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 printf "%s\n" "$ac_cv_objext" >&6; } @@ -4831,8 +5161,8 @@ printf %s "checking whether the compiler supports GNU C... " >&6; } if test ${ac_cv_c_compiler_gnu+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -4849,12 +5179,14 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_compiler_gnu=yes -else $as_nop - ac_compiler_gnu=no +else case e in #( + e) ac_compiler_gnu=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_cv_c_compiler_gnu=$ac_compiler_gnu - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 printf "%s\n" "$ac_cv_c_compiler_gnu" >&6; } @@ -4872,8 +5204,8 @@ printf %s "checking whether $CC accepts -g... " >&6; } if test ${ac_cv_prog_cc_g+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_save_c_werror_flag=$ac_c_werror_flag +else case e in #( + e) ac_save_c_werror_flag=$ac_c_werror_flag ac_c_werror_flag=yes ac_cv_prog_cc_g=no CFLAGS="-g" @@ -4891,8 +5223,8 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_g=yes -else $as_nop - CFLAGS="" +else case e in #( + e) CFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -4907,8 +5239,8 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : -else $as_nop - ac_c_werror_flag=$ac_save_c_werror_flag +else case e in #( + e) ac_c_werror_flag=$ac_save_c_werror_flag CFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -4925,12 +5257,15 @@ if ac_fn_c_try_compile "$LINENO" then : ac_cv_prog_cc_g=yes fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - ac_c_werror_flag=$ac_save_c_werror_flag + ac_c_werror_flag=$ac_save_c_werror_flag ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 printf "%s\n" "$ac_cv_prog_cc_g" >&6; } @@ -4957,8 +5292,8 @@ printf %s "checking for $CC option to enable C11 features... " >&6; } if test ${ac_cv_prog_cc_c11+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_cv_prog_cc_c11=no +else case e in #( + e) ac_cv_prog_cc_c11=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -4975,25 +5310,28 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c11" != "xno" && break done rm -f conftest.$ac_ext -CC=$ac_save_CC +CC=$ac_save_CC ;; +esac fi if test "x$ac_cv_prog_cc_c11" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } -else $as_nop - if test "x$ac_cv_prog_cc_c11" = x +else case e in #( + e) if test "x$ac_cv_prog_cc_c11" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c11" >&5 printf "%s\n" "$ac_cv_prog_cc_c11" >&6; } - CC="$CC $ac_cv_prog_cc_c11" + CC="$CC $ac_cv_prog_cc_c11" ;; +esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c11 - ac_prog_cc_stdc=c11 + ac_prog_cc_stdc=c11 ;; +esac fi fi if test x$ac_prog_cc_stdc = xno @@ -5003,8 +5341,8 @@ printf %s "checking for $CC option to enable C99 features... " >&6; } if test ${ac_cv_prog_cc_c99+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_cv_prog_cc_c99=no +else case e in #( + e) ac_cv_prog_cc_c99=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -5021,25 +5359,28 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c99" != "xno" && break done rm -f conftest.$ac_ext -CC=$ac_save_CC +CC=$ac_save_CC ;; +esac fi if test "x$ac_cv_prog_cc_c99" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } -else $as_nop - if test "x$ac_cv_prog_cc_c99" = x +else case e in #( + e) if test "x$ac_cv_prog_cc_c99" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c99" >&5 printf "%s\n" "$ac_cv_prog_cc_c99" >&6; } - CC="$CC $ac_cv_prog_cc_c99" + CC="$CC $ac_cv_prog_cc_c99" ;; +esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c99 - ac_prog_cc_stdc=c99 + ac_prog_cc_stdc=c99 ;; +esac fi fi if test x$ac_prog_cc_stdc = xno @@ -5049,8 +5390,8 @@ printf %s "checking for $CC option to enable C89 features... " >&6; } if test ${ac_cv_prog_cc_c89+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_cv_prog_cc_c89=no +else case e in #( + e) ac_cv_prog_cc_c89=no ac_save_CC=$CC cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -5067,25 +5408,28 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cc_c89" != "xno" && break done rm -f conftest.$ac_ext -CC=$ac_save_CC +CC=$ac_save_CC ;; +esac fi if test "x$ac_cv_prog_cc_c89" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } -else $as_nop - if test "x$ac_cv_prog_cc_c89" = x +else case e in #( + e) if test "x$ac_cv_prog_cc_c89" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 printf "%s\n" "$ac_cv_prog_cc_c89" >&6; } - CC="$CC $ac_cv_prog_cc_c89" + CC="$CC $ac_cv_prog_cc_c89" ;; +esac fi ac_cv_prog_cc_stdc=$ac_cv_prog_cc_c89 - ac_prog_cc_stdc=c89 + ac_prog_cc_stdc=c89 ;; +esac fi fi @@ -5106,8 +5450,8 @@ printf %s "checking whether $CC understands -c and -o together... " >&6; } if test ${am_cv_prog_cc_c_o+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -5136,8 +5480,12 @@ _ACEOF break fi done - rm -f core conftest* - unset am_i + # aligned with autoconf, so not including core; see bug#72225. + rm -f -r a.out a.exe b.out conftest.$ac_ext conftest.$ac_objext \ + conftest.dSYM conftest1.$ac_ext conftest1.$ac_objext conftest1.dSYM \ + conftest2.$ac_ext conftest2.$ac_objext conftest2.dSYM + unset am_i ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_prog_cc_c_o" >&5 printf "%s\n" "$am_cv_prog_cc_c_o" >&6; } @@ -5227,8 +5575,8 @@ printf %s "checking dependency style of $depcc... " >&6; } if test ${am_cv_CC_dependencies_compiler_type+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then +else case e in #( + e) if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up @@ -5315,7 +5663,7 @@ else $as_nop # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. - # When given -MP, icc 7.0 and 7.1 complain thusly: + # When given -MP, icc 7.0 and 7.1 complain thus: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported @@ -5332,7 +5680,8 @@ else $as_nop else am_cv_CC_dependencies_compiler_type=none fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_CC_dependencies_compiler_type" >&5 printf "%s\n" "$am_cv_CC_dependencies_compiler_type" >&6; } @@ -5374,8 +5723,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$CXX"; then +else case e in #( + e) if test -n "$CXX"; then ac_cv_prog_CXX="$CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -5397,7 +5746,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi CXX=$ac_cv_prog_CXX if test -n "$CXX"; then @@ -5423,8 +5773,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_CXX"; then +else case e in #( + e) if test -n "$ac_ct_CXX"; then ac_cv_prog_ac_ct_CXX="$ac_ct_CXX" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -5446,7 +5796,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_CXX=$ac_cv_prog_ac_ct_CXX if test -n "$ac_ct_CXX"; then @@ -5506,8 +5857,8 @@ printf %s "checking whether the compiler supports GNU C++... " >&6; } if test ${ac_cv_cxx_compiler_gnu+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -5524,12 +5875,14 @@ _ACEOF if ac_fn_cxx_try_compile "$LINENO" then : ac_compiler_gnu=yes -else $as_nop - ac_compiler_gnu=no +else case e in #( + e) ac_compiler_gnu=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_cv_cxx_compiler_gnu=$ac_compiler_gnu - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cxx_compiler_gnu" >&5 printf "%s\n" "$ac_cv_cxx_compiler_gnu" >&6; } @@ -5547,8 +5900,8 @@ printf %s "checking whether $CXX accepts -g... " >&6; } if test ${ac_cv_prog_cxx_g+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_save_cxx_werror_flag=$ac_cxx_werror_flag +else case e in #( + e) ac_save_cxx_werror_flag=$ac_cxx_werror_flag ac_cxx_werror_flag=yes ac_cv_prog_cxx_g=no CXXFLAGS="-g" @@ -5566,8 +5919,8 @@ _ACEOF if ac_fn_cxx_try_compile "$LINENO" then : ac_cv_prog_cxx_g=yes -else $as_nop - CXXFLAGS="" +else case e in #( + e) CXXFLAGS="" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -5582,8 +5935,8 @@ _ACEOF if ac_fn_cxx_try_compile "$LINENO" then : -else $as_nop - ac_cxx_werror_flag=$ac_save_cxx_werror_flag +else case e in #( + e) ac_cxx_werror_flag=$ac_save_cxx_werror_flag CXXFLAGS="-g" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -5600,12 +5953,15 @@ if ac_fn_cxx_try_compile "$LINENO" then : ac_cv_prog_cxx_g=yes fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - ac_cxx_werror_flag=$ac_save_cxx_werror_flag + ac_cxx_werror_flag=$ac_save_cxx_werror_flag ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_g" >&5 printf "%s\n" "$ac_cv_prog_cxx_g" >&6; } @@ -5632,8 +5988,8 @@ printf %s "checking for $CXX option to enable C++11 features... " >&6; } if test ${ac_cv_prog_cxx_cxx11+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_cv_prog_cxx_cxx11=no +else case e in #( + e) ac_cv_prog_cxx_cxx11=no ac_save_CXX=$CXX cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -5650,25 +6006,28 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cxx_cxx11" != "xno" && break done rm -f conftest.$ac_ext -CXX=$ac_save_CXX +CXX=$ac_save_CXX ;; +esac fi if test "x$ac_cv_prog_cxx_cxx11" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } -else $as_nop - if test "x$ac_cv_prog_cxx_cxx11" = x +else case e in #( + e) if test "x$ac_cv_prog_cxx_cxx11" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_cxx11" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_cxx11" >&5 printf "%s\n" "$ac_cv_prog_cxx_cxx11" >&6; } - CXX="$CXX $ac_cv_prog_cxx_cxx11" + CXX="$CXX $ac_cv_prog_cxx_cxx11" ;; +esac fi ac_cv_prog_cxx_stdcxx=$ac_cv_prog_cxx_cxx11 - ac_prog_cxx_stdcxx=cxx11 + ac_prog_cxx_stdcxx=cxx11 ;; +esac fi fi if test x$ac_prog_cxx_stdcxx = xno @@ -5678,8 +6037,8 @@ printf %s "checking for $CXX option to enable C++98 features... " >&6; } if test ${ac_cv_prog_cxx_cxx98+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_cv_prog_cxx_cxx98=no +else case e in #( + e) ac_cv_prog_cxx_cxx98=no ac_save_CXX=$CXX cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -5696,25 +6055,28 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam test "x$ac_cv_prog_cxx_cxx98" != "xno" && break done rm -f conftest.$ac_ext -CXX=$ac_save_CXX +CXX=$ac_save_CXX ;; +esac fi if test "x$ac_cv_prog_cxx_cxx98" = xno then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 printf "%s\n" "unsupported" >&6; } -else $as_nop - if test "x$ac_cv_prog_cxx_cxx98" = x +else case e in #( + e) if test "x$ac_cv_prog_cxx_cxx98" = x then : { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 printf "%s\n" "none needed" >&6; } -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_cxx98" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cxx_cxx98" >&5 printf "%s\n" "$ac_cv_prog_cxx_cxx98" >&6; } - CXX="$CXX $ac_cv_prog_cxx_cxx98" + CXX="$CXX $ac_cv_prog_cxx_cxx98" ;; +esac fi ac_cv_prog_cxx_stdcxx=$ac_cv_prog_cxx_cxx98 - ac_prog_cxx_stdcxx=cxx98 + ac_prog_cxx_stdcxx=cxx98 ;; +esac fi fi @@ -5731,8 +6093,8 @@ printf %s "checking dependency style of $depcc... " >&6; } if test ${am_cv_CXX_dependencies_compiler_type+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then +else case e in #( + e) if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up @@ -5819,7 +6181,7 @@ else $as_nop # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. - # When given -MP, icc 7.0 and 7.1 complain thusly: + # When given -MP, icc 7.0 and 7.1 complain thus: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported @@ -5836,7 +6198,8 @@ else $as_nop else am_cv_CXX_dependencies_compiler_type=none fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_CXX_dependencies_compiler_type" >&5 printf "%s\n" "$am_cv_CXX_dependencies_compiler_type" >&6; } @@ -5859,6 +6222,11 @@ CFLAGS=$save_CFLAGS +# Use the final compiler flags, including target flags added below, when make +# assembles sources. Keep explicit CCASFLAGS values, including empty ones. +if test "${CCASFLAGS+set}" != set; then + CCASFLAGS='$(CFLAGS)' +fi # By default we simply use the C compiler to build assembly code. test "${CCAS+set}" = set || CCAS=$CC @@ -5873,8 +6241,8 @@ printf %s "checking dependency style of $depcc... " >&6; } if test ${am_cv_CCAS_dependencies_compiler_type+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then +else case e in #( + e) if test -z "$AMDEP_TRUE" && test -f "$am_depcomp"; then # We make a subdir and do the tests there. Otherwise we can end up # making bogus files that we don't know about and never remove. For # instance it was reported that on HP-UX the gcc test will end up @@ -5959,7 +6327,7 @@ else $as_nop # icc doesn't choke on unknown options, it will just issue warnings # or remarks (even with -Werror). So we grep stderr for any message # that says an option was ignored or not supported. - # When given -MP, icc 7.0 and 7.1 complain thusly: + # When given -MP, icc 7.0 and 7.1 complain thus: # icc: Command line warning: ignoring option '-M'; no argument required # The diagnosis changed in icc 8.0: # icc: Command line remark: option '-MP' not supported @@ -5976,7 +6344,8 @@ else $as_nop else am_cv_CCAS_dependencies_compiler_type=none fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $am_cv_CCAS_dependencies_compiler_type" >&5 printf "%s\n" "$am_cv_CCAS_dependencies_compiler_type" >&6; } @@ -5999,8 +6368,8 @@ printf %s "checking for grep that handles long lines and -e... " >&6; } if test ${ac_cv_path_GREP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -z "$GREP"; then +else case e in #( + e) if test -z "$GREP"; then ac_path_GREP_found=false # Loop through the user's path and test for each of PROGNAME-LIST as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -6019,9 +6388,10 @@ do as_fn_executable_p "$ac_path_GREP" || continue # Check for GNU ac_path_GREP and select it if it is found. # Check for GNU $ac_path_GREP -case `"$ac_path_GREP" --version 2>&1` in +case `"$ac_path_GREP" --version 2>&1` in #( *GNU*) ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +#( *) ac_count=0 printf %s 0123456789 >"conftest.in" @@ -6056,7 +6426,8 @@ IFS=$as_save_IFS else ac_cv_path_GREP=$GREP fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 printf "%s\n" "$ac_cv_path_GREP" >&6; } @@ -6068,8 +6439,8 @@ printf %s "checking for egrep... " >&6; } if test ${ac_cv_path_EGREP+y} then : printf %s "(cached) " >&6 -else $as_nop - if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 +else case e in #( + e) if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 then ac_cv_path_EGREP="$GREP -E" else if test -z "$EGREP"; then @@ -6091,9 +6462,10 @@ do as_fn_executable_p "$ac_path_EGREP" || continue # Check for GNU ac_path_EGREP and select it if it is found. # Check for GNU $ac_path_EGREP -case `"$ac_path_EGREP" --version 2>&1` in +case `"$ac_path_EGREP" --version 2>&1` in #( *GNU*) ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +#( *) ac_count=0 printf %s 0123456789 >"conftest.in" @@ -6129,12 +6501,15 @@ else ac_cv_path_EGREP=$EGREP fi - fi + fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 printf "%s\n" "$ac_cv_path_EGREP" >&6; } EGREP="$ac_cv_path_EGREP" + EGREP_TRADITIONAL=$EGREP + ac_cv_path_EGREP_TRADITIONAL=$EGREP case `pwd` in *\ * | *\ *) @@ -6144,8 +6519,8 @@ esac -macro_version='2.4.7' -macro_revision='2.4.7' +macro_version='2.5.4' +macro_revision='2.5.4' @@ -6236,8 +6611,8 @@ printf %s "checking for a sed that does not truncate output... " >&6; } if test ${ac_cv_path_SED+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ +else case e in #( + e) ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ for ac_i in 1 2 3 4 5 6 7; do ac_script="$ac_script$as_nl$ac_script" done @@ -6262,9 +6637,10 @@ do as_fn_executable_p "$ac_path_SED" || continue # Check for GNU ac_path_SED and select it if it is found. # Check for GNU $ac_path_SED -case `"$ac_path_SED" --version 2>&1` in +case `"$ac_path_SED" --version 2>&1` in #( *GNU*) ac_cv_path_SED="$ac_path_SED" ac_path_SED_found=:;; +#( *) ac_count=0 printf %s 0123456789 >"conftest.in" @@ -6299,7 +6675,8 @@ IFS=$as_save_IFS else ac_cv_path_SED=$SED fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_SED" >&5 printf "%s\n" "$ac_cv_path_SED" >&6; } @@ -6324,8 +6701,8 @@ printf %s "checking for fgrep... " >&6; } if test ${ac_cv_path_FGREP+y} then : printf %s "(cached) " >&6 -else $as_nop - if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 +else case e in #( + e) if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 then ac_cv_path_FGREP="$GREP -F" else if test -z "$FGREP"; then @@ -6347,9 +6724,10 @@ do as_fn_executable_p "$ac_path_FGREP" || continue # Check for GNU ac_path_FGREP and select it if it is found. # Check for GNU $ac_path_FGREP -case `"$ac_path_FGREP" --version 2>&1` in +case `"$ac_path_FGREP" --version 2>&1` in #( *GNU*) ac_cv_path_FGREP="$ac_path_FGREP" ac_path_FGREP_found=:;; +#( *) ac_count=0 printf %s 0123456789 >"conftest.in" @@ -6385,7 +6763,8 @@ else ac_cv_path_FGREP=$FGREP fi - fi + fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_FGREP" >&5 printf "%s\n" "$ac_cv_path_FGREP" >&6; } @@ -6416,8 +6795,9 @@ test -z "$GREP" && GREP=grep if test ${with_gnu_ld+y} then : withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes -else $as_nop - with_gnu_ld=no +else case e in #( + e) with_gnu_ld=no ;; +esac fi ac_prog=ld @@ -6426,7 +6806,7 @@ if test yes = "$GCC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 printf %s "checking for ld used by $CC... " >&6; } case $host in - *-*-mingw*) + *-*-mingw* | *-*-windows*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) @@ -6462,8 +6842,8 @@ fi if test ${lt_cv_path_LD+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -z "$LD"; then +else case e in #( + e) if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs @@ -6486,7 +6866,8 @@ else $as_nop IFS=$lt_save_ifs else lt_cv_path_LD=$LD # Let the user override the test with a path. -fi +fi ;; +esac fi LD=$lt_cv_path_LD @@ -6503,8 +6884,8 @@ printf %s "checking if the linker ($LD) is GNU ld... " >&6; } if test ${lt_cv_prog_gnu_ld+y} then : printf %s "(cached) " >&6 -else $as_nop - # I'd rather use --version here, but apparently some GNU lds only accept -v. +else case e in #( + e) # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 </dev/null` in *GNU* | *'with BFD'*) lt_cv_prog_gnu_ld=yes @@ -6512,6 +6893,7 @@ case `$LD -v 2>&1 </dev/null` in *) lt_cv_prog_gnu_ld=no ;; +esac ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5 @@ -6531,8 +6913,8 @@ printf %s "checking for BSD- or MS-compatible name lister (nm)... " >&6; } if test ${lt_cv_path_NM+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$NM"; then +else case e in #( + e) if test -n "$NM"; then # Let the user override the test. lt_cv_path_NM=$NM else @@ -6553,7 +6935,7 @@ else # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in - mingw*) lt_bad_file=conftest.nm/nofile ;; + mingw* | windows*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | $SED '1q'` in @@ -6579,7 +6961,8 @@ else IFS=$lt_save_ifs done : ${lt_cv_path_NM=no} -fi +fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_NM" >&5 printf "%s\n" "$lt_cv_path_NM" >&6; } @@ -6600,8 +6983,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DUMPBIN+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$DUMPBIN"; then +else case e in #( + e) if test -n "$DUMPBIN"; then ac_cv_prog_DUMPBIN="$DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -6623,7 +7006,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi DUMPBIN=$ac_cv_prog_DUMPBIN if test -n "$DUMPBIN"; then @@ -6649,8 +7033,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_DUMPBIN+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_DUMPBIN"; then +else case e in #( + e) if test -n "$ac_ct_DUMPBIN"; then ac_cv_prog_ac_ct_DUMPBIN="$ac_ct_DUMPBIN" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -6672,7 +7056,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_DUMPBIN=$ac_cv_prog_ac_ct_DUMPBIN if test -n "$ac_ct_DUMPBIN"; then @@ -6726,8 +7111,8 @@ printf %s "checking the name lister ($NM) interface... " >&6; } if test ${lt_cv_nm_interface+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_nm_interface="BSD nm" +else case e in #( + e) lt_cv_nm_interface="BSD nm" echo "int some_variable = 0;" > conftest.$ac_ext (eval echo "\"\$as_me:$LINENO: $ac_compile\"" >&5) (eval "$ac_compile" 2>conftest.err) @@ -6740,7 +7125,8 @@ else $as_nop if $GREP 'External.*some_variable' conftest.out > /dev/null; then lt_cv_nm_interface="MS dumpbin" fi - rm -f conftest* + rm -f conftest* ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_nm_interface" >&5 printf "%s\n" "$lt_cv_nm_interface" >&6; } @@ -6762,8 +7148,8 @@ printf %s "checking the maximum length of command line arguments... " >&6; } if test ${lt_cv_sys_max_cmd_len+y} then : printf %s "(cached) " >&6 -else $as_nop - i=0 +else case e in #( + e) i=0 teststring=ABCD case $build_os in @@ -6775,14 +7161,14 @@ else $as_nop lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; - gnu*) - # Under GNU Hurd, this test is not required because there is - # no limit to the length of command line arguments. + gnu* | ironclad*) + # Under GNU Hurd and Ironclad, this test is not required because there + # is no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; - cygwin* | mingw* | cegcc*) + cygwin* | mingw* | windows* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, @@ -6804,7 +7190,7 @@ else $as_nop lt_cv_sys_max_cmd_len=8192; ;; - bitrig* | darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) + darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` @@ -6885,7 +7271,8 @@ else $as_nop fi ;; esac - + ;; +esac fi if test -n "$lt_cv_sys_max_cmd_len"; then @@ -6942,11 +7329,11 @@ printf %s "checking how to convert $build file names to $host format... " >&6; } if test ${lt_cv_to_host_file_cmd+y} then : printf %s "(cached) " >&6 -else $as_nop - case $host in +else case e in #( + e) case $host in *-*-mingw* ) case $build in - *-*-mingw* ) # actually msys + *-*-mingw* | *-*-windows* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) @@ -6959,7 +7346,7 @@ else $as_nop ;; *-*-cygwin* ) case $build in - *-*-mingw* ) # actually msys + *-*-mingw* | *-*-windows* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) @@ -6974,7 +7361,8 @@ else $as_nop lt_cv_to_host_file_cmd=func_convert_file_noop ;; esac - + ;; +esac fi to_host_file_cmd=$lt_cv_to_host_file_cmd @@ -6990,19 +7378,20 @@ printf %s "checking how to convert $build file names to toolchain format... " >& if test ${lt_cv_to_tool_file_cmd+y} then : printf %s "(cached) " >&6 -else $as_nop - #assume ordinary cross tools, or native build. +else case e in #( + e) #assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in - *-*-mingw* ) + *-*-mingw* | *-*-windows* ) case $build in - *-*-mingw* ) # actually msys + *-*-mingw* | *-*-windows* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac ;; esac - + ;; +esac fi to_tool_file_cmd=$lt_cv_to_tool_file_cmd @@ -7018,8 +7407,9 @@ printf %s "checking for $LD option to reload object files... " >&6; } if test ${lt_cv_ld_reload_flag+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_ld_reload_flag='-r' +else case e in #( + e) lt_cv_ld_reload_flag='-r' ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_reload_flag" >&5 printf "%s\n" "$lt_cv_ld_reload_flag" >&6; } @@ -7030,7 +7420,7 @@ case $reload_flag in esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) if test yes != "$GCC"; then reload_cmds=false fi @@ -7052,16 +7442,15 @@ esac -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}file", so it can be a program name with args. -set dummy ${ac_tool_prefix}file; ac_word=$2 +# Extract the first word of "file", so it can be a program name with args. +set dummy file; ac_word=$2 { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_FILECMD+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$FILECMD"; then +else case e in #( + e) if test -n "$FILECMD"; then ac_cv_prog_FILECMD="$FILECMD" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7075,7 +7464,7 @@ do esac for ac_exec_ext in '' $ac_executable_extensions; do if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then - ac_cv_prog_FILECMD="${ac_tool_prefix}file" + ac_cv_prog_FILECMD="file" printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 break 2 fi @@ -7083,7 +7472,9 @@ done done IFS=$as_save_IFS -fi + test -z "$ac_cv_prog_FILECMD" && ac_cv_prog_FILECMD=":" +fi ;; +esac fi FILECMD=$ac_cv_prog_FILECMD if test -n "$FILECMD"; then @@ -7095,65 +7486,6 @@ printf "%s\n" "no" >&6; } fi -fi -if test -z "$ac_cv_prog_FILECMD"; then - ac_ct_FILECMD=$FILECMD - # Extract the first word of "file", so it can be a program name with args. -set dummy file; ac_word=$2 -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -printf %s "checking for $ac_word... " >&6; } -if test ${ac_cv_prog_ac_ct_FILECMD+y} -then : - printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_FILECMD"; then - ac_cv_prog_ac_ct_FILECMD="$ac_ct_FILECMD" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - case $as_dir in #((( - '') as_dir=./ ;; - */) ;; - *) as_dir=$as_dir/ ;; - esac - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then - ac_cv_prog_ac_ct_FILECMD="file" - printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_FILECMD=$ac_cv_prog_ac_ct_FILECMD -if test -n "$ac_ct_FILECMD"; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_FILECMD" >&5 -printf "%s\n" "$ac_ct_FILECMD" >&6; } -else - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 -printf "%s\n" "no" >&6; } -fi - - if test "x$ac_ct_FILECMD" = x; then - FILECMD=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - FILECMD=$ac_ct_FILECMD - fi -else - FILECMD="$ac_cv_prog_FILECMD" -fi - @@ -7168,8 +7500,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_OBJDUMP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$OBJDUMP"; then +else case e in #( + e) if test -n "$OBJDUMP"; then ac_cv_prog_OBJDUMP="$OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7191,7 +7523,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi OBJDUMP=$ac_cv_prog_OBJDUMP if test -n "$OBJDUMP"; then @@ -7213,8 +7546,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_OBJDUMP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_OBJDUMP"; then +else case e in #( + e) if test -n "$ac_ct_OBJDUMP"; then ac_cv_prog_ac_ct_OBJDUMP="$ac_ct_OBJDUMP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7236,7 +7569,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_OBJDUMP=$ac_cv_prog_ac_ct_OBJDUMP if test -n "$ac_ct_OBJDUMP"; then @@ -7277,8 +7611,8 @@ printf %s "checking how to recognize dependent libraries... " >&6; } if test ${lt_cv_deplibs_check_method+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_file_magic_cmd='$MAGIC_CMD' +else case e in #( + e) lt_cv_file_magic_cmd='$MAGIC_CMD' lt_cv_file_magic_test_file= lt_cv_deplibs_check_method='unknown' # Need to set the preceding variable on all platforms that support @@ -7286,7 +7620,6 @@ lt_cv_deplibs_check_method='unknown' # 'none' -- dependencies not supported. # 'unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. -# 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # that responds to the $file_magic_cmd with a given extended regex. # If you have 'file' or equivalent on your system and you're not sure @@ -7313,7 +7646,7 @@ cygwin*) lt_cv_file_magic_cmd='func_win32_libid' ;; -mingw* | pw32*) +mingw* | windows* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. @@ -7322,7 +7655,7 @@ mingw* | pw32*) lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. - lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' + lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64|pe-aarch64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; @@ -7395,6 +7728,10 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; +*-mlibc) + lt_cv_deplibs_check_method=pass_all + ;; + netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|_pic\.a)$' @@ -7413,7 +7750,7 @@ newos6*) lt_cv_deplibs_check_method=pass_all ;; -openbsd* | bitrig*) +openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then lt_cv_deplibs_check_method='match_pattern /lib[^/]+(\.so\.[0-9]+\.[0-9]+|\.so|_pic\.a)$' else @@ -7429,6 +7766,10 @@ rdos*) lt_cv_deplibs_check_method=pass_all ;; +serenity*) + lt_cv_deplibs_check_method=pass_all + ;; + solaris*) lt_cv_deplibs_check_method=pass_all ;; @@ -7471,7 +7812,8 @@ os2*) lt_cv_deplibs_check_method=pass_all ;; esac - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_deplibs_check_method" >&5 printf "%s\n" "$lt_cv_deplibs_check_method" >&6; } @@ -7480,7 +7822,7 @@ file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in - mingw* | pw32*) + mingw* | windows* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else @@ -7523,8 +7865,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DLLTOOL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$DLLTOOL"; then +else case e in #( + e) if test -n "$DLLTOOL"; then ac_cv_prog_DLLTOOL="$DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7546,7 +7888,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi DLLTOOL=$ac_cv_prog_DLLTOOL if test -n "$DLLTOOL"; then @@ -7568,8 +7911,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_DLLTOOL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_DLLTOOL"; then +else case e in #( + e) if test -n "$ac_ct_DLLTOOL"; then ac_cv_prog_ac_ct_DLLTOOL="$ac_ct_DLLTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7591,7 +7934,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_DLLTOOL=$ac_cv_prog_ac_ct_DLLTOOL if test -n "$ac_ct_DLLTOOL"; then @@ -7633,11 +7977,11 @@ printf %s "checking how to associate runtime and link libraries... " >&6; } if test ${lt_cv_sharedlib_from_linklib_cmd+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_sharedlib_from_linklib_cmd='unknown' +else case e in #( + e) lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh; # decide which one to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in @@ -7654,7 +7998,8 @@ cygwin* | mingw* | pw32* | cegcc*) lt_cv_sharedlib_from_linklib_cmd=$ECHO ;; esac - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sharedlib_from_linklib_cmd" >&5 printf "%s\n" "$lt_cv_sharedlib_from_linklib_cmd" >&6; } @@ -7668,6 +8013,110 @@ test -z "$sharedlib_from_linklib_cmd" && sharedlib_from_linklib_cmd=$ECHO +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. +set dummy ${ac_tool_prefix}ranlib; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_RANLIB+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) if test -n "$RANLIB"; then + ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi ;; +esac +fi +RANLIB=$ac_cv_prog_RANLIB +if test -n "$RANLIB"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 +printf "%s\n" "$RANLIB" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_RANLIB"; then + ac_ct_RANLIB=$RANLIB + # Extract the first word of "ranlib", so it can be a program name with args. +set dummy ranlib; ac_word=$2 +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +printf %s "checking for $ac_word... " >&6; } +if test ${ac_cv_prog_ac_ct_RANLIB+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) if test -n "$ac_ct_RANLIB"; then + ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + case $as_dir in #((( + '') as_dir=./ ;; + */) ;; + *) as_dir=$as_dir/ ;; + esac + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_RANLIB="ranlib" + printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi ;; +esac +fi +ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB +if test -n "$ac_ct_RANLIB"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 +printf "%s\n" "$ac_ct_RANLIB" >&6; } +else + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 +printf "%s\n" "no" >&6; } +fi + + if test "x$ac_ct_RANLIB" = x; then + RANLIB=":" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + RANLIB=$ac_ct_RANLIB + fi +else + RANLIB="$ac_cv_prog_RANLIB" +fi + if test -n "$ac_tool_prefix"; then for ac_prog in ar do @@ -7678,8 +8127,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_AR+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$AR"; then +else case e in #( + e) if test -n "$AR"; then ac_cv_prog_AR="$AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7701,7 +8150,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi AR=$ac_cv_prog_AR if test -n "$AR"; then @@ -7727,8 +8177,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_AR+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_AR"; then +else case e in #( + e) if test -n "$ac_ct_AR"; then ac_cv_prog_ac_ct_AR="$ac_ct_AR" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7750,7 +8200,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_AR=$ac_cv_prog_ac_ct_AR if test -n "$ac_ct_AR"; then @@ -7787,7 +8238,7 @@ fi # Use ARFLAGS variable as AR's operation code to sync the variable naming with # Automake. If both AR_FLAGS and ARFLAGS are specified, AR_FLAGS should have -# higher priority because thats what people were doing historically (setting +# higher priority because that's what people were doing historically (setting # ARFLAGS for automake and AR_FLAGS for libtool). FIXME: Make the AR_FLAGS # variable obsoleted/removed. @@ -7812,8 +8263,8 @@ printf %s "checking for archiver @FILE support... " >&6; } if test ${lt_cv_ar_at_file+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_ar_at_file=no +else case e in #( + e) lt_cv_ar_at_file=no cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -7850,7 +8301,8 @@ then : fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ar_at_file" >&5 printf "%s\n" "$lt_cv_ar_at_file" >&6; } @@ -7875,8 +8327,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_STRIP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$STRIP"; then +else case e in #( + e) if test -n "$STRIP"; then ac_cv_prog_STRIP="$STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7898,7 +8350,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi STRIP=$ac_cv_prog_STRIP if test -n "$STRIP"; then @@ -7920,8 +8373,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_STRIP+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_STRIP"; then +else case e in #( + e) if test -n "$ac_ct_STRIP"; then ac_cv_prog_ac_ct_STRIP="$ac_ct_STRIP" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -7943,7 +8396,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_STRIP=$ac_cv_prog_ac_ct_STRIP if test -n "$ac_ct_STRIP"; then @@ -7976,107 +8430,6 @@ test -z "$STRIP" && STRIP=: -if test -n "$ac_tool_prefix"; then - # Extract the first word of "${ac_tool_prefix}ranlib", so it can be a program name with args. -set dummy ${ac_tool_prefix}ranlib; ac_word=$2 -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -printf %s "checking for $ac_word... " >&6; } -if test ${ac_cv_prog_RANLIB+y} -then : - printf %s "(cached) " >&6 -else $as_nop - if test -n "$RANLIB"; then - ac_cv_prog_RANLIB="$RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - case $as_dir in #((( - '') as_dir=./ ;; - */) ;; - *) as_dir=$as_dir/ ;; - esac - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then - ac_cv_prog_RANLIB="${ac_tool_prefix}ranlib" - printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -RANLIB=$ac_cv_prog_RANLIB -if test -n "$RANLIB"; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $RANLIB" >&5 -printf "%s\n" "$RANLIB" >&6; } -else - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 -printf "%s\n" "no" >&6; } -fi - - -fi -if test -z "$ac_cv_prog_RANLIB"; then - ac_ct_RANLIB=$RANLIB - # Extract the first word of "ranlib", so it can be a program name with args. -set dummy ranlib; ac_word=$2 -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -printf %s "checking for $ac_word... " >&6; } -if test ${ac_cv_prog_ac_ct_RANLIB+y} -then : - printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_RANLIB"; then - ac_cv_prog_ac_ct_RANLIB="$ac_ct_RANLIB" # Let the user override the test. -else -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - case $as_dir in #((( - '') as_dir=./ ;; - */) ;; - *) as_dir=$as_dir/ ;; - esac - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir$ac_word$ac_exec_ext"; then - ac_cv_prog_ac_ct_RANLIB="ranlib" - printf "%s\n" "$as_me:${as_lineno-$LINENO}: found $as_dir$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - -fi -fi -ac_ct_RANLIB=$ac_cv_prog_ac_ct_RANLIB -if test -n "$ac_ct_RANLIB"; then - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_ct_RANLIB" >&5 -printf "%s\n" "$ac_ct_RANLIB" >&6; } -else - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: no" >&5 -printf "%s\n" "no" >&6; } -fi - - if test "x$ac_ct_RANLIB" = x; then - RANLIB=":" - else - case $cross_compiling:$ac_tool_warned in -yes:) -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 -printf "%s\n" "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} -ac_tool_warned=yes ;; -esac - RANLIB=$ac_ct_RANLIB - fi -else - RANLIB="$ac_cv_prog_RANLIB" -fi test -z "$RANLIB" && RANLIB=: @@ -8091,15 +8444,8 @@ old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then - case $host_os in - bitrig* | openbsd*) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" - ;; - *) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" - ;; - esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in @@ -8163,8 +8509,8 @@ printf %s "checking command to parse $NM output from $compiler object... " >&6; if test ${lt_cv_sys_global_symbol_pipe+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) # These are sane defaults that work on at least a few old systems. # [They come from Ultrix. What could be older than Ultrix?!! ;)] @@ -8179,7 +8525,7 @@ case $host_os in aix*) symcode='[BCDT]' ;; -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) symcode='[ABCDGISTW]' ;; hpux*) @@ -8194,7 +8540,7 @@ osf*) symcode='[BCDEGQRST]' ;; solaris*) - symcode='[BDRT]' + symcode='[BCDRT]' ;; sco3.2v5*) symcode='[DT]' @@ -8258,7 +8604,7 @@ $lt_c_name_lib_hook\ # Handle CRLF in mingw tool chain opt_cr= case $build_os in -mingw*) +mingw* | windows*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac @@ -8309,7 +8655,7 @@ void nm_test_func(void){} #ifdef __cplusplus } #endif -int main(){nm_test_var='a';nm_test_func();return(0);} +int main(void){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 @@ -8416,7 +8762,8 @@ _LT_EOF lt_cv_sys_global_symbol_pipe= fi done - + ;; +esac fi if test -z "$lt_cv_sys_global_symbol_pipe"; then @@ -8480,8 +8827,9 @@ printf %s "checking for sysroot... " >&6; } if test ${with_sysroot+y} then : withval=$with_sysroot; -else $as_nop - with_sysroot=no +else case e in #( + e) with_sysroot=no ;; +esac fi @@ -8489,7 +8837,9 @@ lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then - lt_sysroot=`$CC --print-sysroot 2>/dev/null` + # Trim trailing / since we'll always append absolute paths and we want + # to avoid //, if only for less confusing output for the user. + lt_sysroot=`$CC --print-sysroot 2>/dev/null | $SED 's:/\+$::'` fi ;; #( /*) @@ -8516,8 +8866,8 @@ printf %s "checking for a working dd... " >&6; } if test ${ac_cv_path_lt_DD+y} then : printf %s "(cached) " >&6 -else $as_nop - printf 0123456789abcdef0123456789abcdef >conftest.i +else case e in #( + e) printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i : ${lt_DD:=$DD} if test -z "$lt_DD"; then @@ -8553,7 +8903,8 @@ else ac_cv_path_lt_DD=$lt_DD fi -rm -f conftest.i conftest2.i conftest.out +rm -f conftest.i conftest2.i conftest.out ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_lt_DD" >&5 printf "%s\n" "$ac_cv_path_lt_DD" >&6; } @@ -8564,8 +8915,8 @@ printf %s "checking how to truncate binary pipes... " >&6; } if test ${lt_cv_truncate_bin+y} then : printf %s "(cached) " >&6 -else $as_nop - printf 0123456789abcdef0123456789abcdef >conftest.i +else case e in #( + e) printf 0123456789abcdef0123456789abcdef >conftest.i cat conftest.i conftest.i >conftest2.i lt_cv_truncate_bin= if "$ac_cv_path_lt_DD" bs=32 count=1 <conftest2.i >conftest.out 2>/dev/null; then @@ -8573,7 +8924,8 @@ if "$ac_cv_path_lt_DD" bs=32 count=1 <conftest2.i >conftest.out 2>/dev/null; the && lt_cv_truncate_bin="$ac_cv_path_lt_DD bs=4096 count=1" fi rm -f conftest.i conftest2.i conftest.out -test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q" +test -z "$lt_cv_truncate_bin" && lt_cv_truncate_bin="$SED -e 4q" ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_truncate_bin" >&5 printf "%s\n" "$lt_cv_truncate_bin" >&6; } @@ -8704,7 +9056,7 @@ mips64*-*linux*) ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ -s390*-*linux*|s390*-*tpf*|sparc*-*linux*) +s390*-*linux*|s390*-*tpf*|sparc*-*linux*|x86_64-gnu*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. Note that the listed cases only cover the # situations where additional linker options are needed (such as when @@ -8723,7 +9075,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; - x86_64-*linux*) + x86_64-*linux*|x86_64-gnu*) case `$FILECMD conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" @@ -8752,7 +9104,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; - x86_64-*linux*) + x86_64-*linux*|x86_64-gnu*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*linux*) @@ -8783,8 +9135,8 @@ printf %s "checking whether the C compiler needs -belf... " >&6; } if test ${lt_cv_cc_needs_belf+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_ext=c +else case e in #( + e) ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' @@ -8804,8 +9156,9 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_cv_cc_needs_belf=yes -else $as_nop - lt_cv_cc_needs_belf=no +else case e in #( + e) lt_cv_cc_needs_belf=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext @@ -8814,7 +9167,8 @@ ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_cc_needs_belf" >&5 printf "%s\n" "$lt_cv_cc_needs_belf" >&6; } @@ -8872,8 +9226,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_MANIFEST_TOOL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$MANIFEST_TOOL"; then +else case e in #( + e) if test -n "$MANIFEST_TOOL"; then ac_cv_prog_MANIFEST_TOOL="$MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -8895,7 +9249,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi MANIFEST_TOOL=$ac_cv_prog_MANIFEST_TOOL if test -n "$MANIFEST_TOOL"; then @@ -8917,8 +9272,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_MANIFEST_TOOL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_MANIFEST_TOOL"; then +else case e in #( + e) if test -n "$ac_ct_MANIFEST_TOOL"; then ac_cv_prog_ac_ct_MANIFEST_TOOL="$ac_ct_MANIFEST_TOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -8940,7 +9295,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_MANIFEST_TOOL=$ac_cv_prog_ac_ct_MANIFEST_TOOL if test -n "$ac_ct_MANIFEST_TOOL"; then @@ -8969,22 +9325,23 @@ fi test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $MANIFEST_TOOL is a manifest tool" >&5 printf %s "checking if $MANIFEST_TOOL is a manifest tool... " >&6; } -if test ${lt_cv_path_mainfest_tool+y} +if test ${lt_cv_path_manifest_tool+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_path_mainfest_tool=no +else case e in #( + e) lt_cv_path_manifest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&5 $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&5 if $GREP 'Manifest Tool' conftest.out > /dev/null; then - lt_cv_path_mainfest_tool=yes + lt_cv_path_manifest_tool=yes fi - rm -f conftest* + rm -f conftest* ;; +esac fi -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_mainfest_tool" >&5 -printf "%s\n" "$lt_cv_path_mainfest_tool" >&6; } -if test yes != "$lt_cv_path_mainfest_tool"; then +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_path_manifest_tool" >&5 +printf "%s\n" "$lt_cv_path_manifest_tool" >&6; } +if test yes != "$lt_cv_path_manifest_tool"; then MANIFEST_TOOL=: fi @@ -9003,8 +9360,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_DSYMUTIL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$DSYMUTIL"; then +else case e in #( + e) if test -n "$DSYMUTIL"; then ac_cv_prog_DSYMUTIL="$DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9026,7 +9383,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi DSYMUTIL=$ac_cv_prog_DSYMUTIL if test -n "$DSYMUTIL"; then @@ -9048,8 +9406,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_DSYMUTIL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_DSYMUTIL"; then +else case e in #( + e) if test -n "$ac_ct_DSYMUTIL"; then ac_cv_prog_ac_ct_DSYMUTIL="$ac_ct_DSYMUTIL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9071,7 +9429,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_DSYMUTIL=$ac_cv_prog_ac_ct_DSYMUTIL if test -n "$ac_ct_DSYMUTIL"; then @@ -9105,8 +9464,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_NMEDIT+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$NMEDIT"; then +else case e in #( + e) if test -n "$NMEDIT"; then ac_cv_prog_NMEDIT="$NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9128,7 +9487,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi NMEDIT=$ac_cv_prog_NMEDIT if test -n "$NMEDIT"; then @@ -9150,8 +9510,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_NMEDIT+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_NMEDIT"; then +else case e in #( + e) if test -n "$ac_ct_NMEDIT"; then ac_cv_prog_ac_ct_NMEDIT="$ac_ct_NMEDIT" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9173,7 +9533,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_NMEDIT=$ac_cv_prog_ac_ct_NMEDIT if test -n "$ac_ct_NMEDIT"; then @@ -9207,8 +9568,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_LIPO+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$LIPO"; then +else case e in #( + e) if test -n "$LIPO"; then ac_cv_prog_LIPO="$LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9230,7 +9591,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi LIPO=$ac_cv_prog_LIPO if test -n "$LIPO"; then @@ -9252,8 +9614,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_LIPO+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_LIPO"; then +else case e in #( + e) if test -n "$ac_ct_LIPO"; then ac_cv_prog_ac_ct_LIPO="$ac_ct_LIPO" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9275,7 +9637,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_LIPO=$ac_cv_prog_ac_ct_LIPO if test -n "$ac_ct_LIPO"; then @@ -9309,8 +9672,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_OTOOL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$OTOOL"; then +else case e in #( + e) if test -n "$OTOOL"; then ac_cv_prog_OTOOL="$OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9332,7 +9695,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi OTOOL=$ac_cv_prog_OTOOL if test -n "$OTOOL"; then @@ -9354,8 +9718,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_OTOOL+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_OTOOL"; then +else case e in #( + e) if test -n "$ac_ct_OTOOL"; then ac_cv_prog_ac_ct_OTOOL="$ac_ct_OTOOL" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9377,7 +9741,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_OTOOL=$ac_cv_prog_ac_ct_OTOOL if test -n "$ac_ct_OTOOL"; then @@ -9411,8 +9776,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_OTOOL64+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$OTOOL64"; then +else case e in #( + e) if test -n "$OTOOL64"; then ac_cv_prog_OTOOL64="$OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9434,7 +9799,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi OTOOL64=$ac_cv_prog_OTOOL64 if test -n "$OTOOL64"; then @@ -9456,8 +9822,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_OTOOL64+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_OTOOL64"; then +else case e in #( + e) if test -n "$ac_ct_OTOOL64"; then ac_cv_prog_ac_ct_OTOOL64="$ac_ct_OTOOL64" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -9479,7 +9845,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_OTOOL64=$ac_cv_prog_ac_ct_OTOOL64 if test -n "$ac_ct_OTOOL64"; then @@ -9536,8 +9903,8 @@ printf %s "checking for -single_module linker flag... " >&6; } if test ${lt_cv_apple_cc_single_mod+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_apple_cc_single_mod=no +else case e in #( + e) lt_cv_apple_cc_single_mod=no if test -z "$LT_MULTI_MODULE"; then # By default we will add the -single_module flag. You can override # by either setting the environment variable LT_MULTI_MODULE @@ -9563,18 +9930,58 @@ else $as_nop fi rm -rf libconftest.dylib* rm -f conftest.* - fi + fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_apple_cc_single_mod" >&5 printf "%s\n" "$lt_cv_apple_cc_single_mod" >&6; } + # Feature test to disable chained fixups since it is not + # compatible with '-undefined dynamic_lookup' + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -no_fixup_chains linker flag" >&5 +printf %s "checking for -no_fixup_chains linker flag... " >&6; } +if test ${lt_cv_support_no_fixup_chains+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS -Wl,-no_fixup_chains" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main (void) +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO" +then : + lt_cv_support_no_fixup_chains=yes +else case e in #( + e) lt_cv_support_no_fixup_chains=no + ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext + LDFLAGS=$save_LDFLAGS + + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_support_no_fixup_chains" >&5 +printf "%s\n" "$lt_cv_support_no_fixup_chains" >&6; } + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for -exported_symbols_list linker flag" >&5 printf %s "checking for -exported_symbols_list linker flag... " >&6; } if test ${lt_cv_ld_exported_symbols_list+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_ld_exported_symbols_list=no +else case e in #( + e) lt_cv_ld_exported_symbols_list=no save_LDFLAGS=$LDFLAGS echo "_main" > conftest.sym LDFLAGS="$LDFLAGS -Wl,-exported_symbols_list,conftest.sym" @@ -9592,13 +9999,15 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_cv_ld_exported_symbols_list=yes -else $as_nop - lt_cv_ld_exported_symbols_list=no +else case e in #( + e) lt_cv_ld_exported_symbols_list=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_exported_symbols_list" >&5 printf "%s\n" "$lt_cv_ld_exported_symbols_list" >&6; } @@ -9608,8 +10017,8 @@ printf %s "checking for -force_load linker flag... " >&6; } if test ${lt_cv_ld_force_load+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_ld_force_load=no +else case e in #( + e) lt_cv_ld_force_load=no cat > conftest.c << _LT_EOF int forced_loaded() { return 2;} _LT_EOF @@ -9620,7 +10029,7 @@ _LT_EOF echo "$RANLIB libconftest.a" >&5 $RANLIB libconftest.a 2>&5 cat > conftest.c << _LT_EOF -int main() { return 0;} +int main(void) { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&5 $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err @@ -9634,7 +10043,8 @@ _LT_EOF fi rm -f conftest.err libconftest.a conftest conftest.c rm -rf conftest.dSYM - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_ld_force_load" >&5 printf "%s\n" "$lt_cv_ld_force_load" >&6; } @@ -9648,13 +10058,32 @@ printf "%s\n" "$lt_cv_ld_force_load" >&6; } 10.[012],*|,*powerpc*-darwin[5-8]*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; *) - _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; + _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' + if test yes = "$lt_cv_support_no_fixup_chains"; then + as_fn_append _lt_dar_allow_undefined ' $wl-no_fixup_chains' + fi + ;; esac ;; esac if test yes = "$lt_cv_apple_cc_single_mod"; then _lt_dar_single_mod='$single_module' fi + _lt_dar_needs_single_mod=no + case $host_os in + rhapsody* | darwin1.*) + _lt_dar_needs_single_mod=yes ;; + darwin*) + # When targeting Mac OS X 10.4 (darwin 8) or later, + # -single_module is the default and -multi_module is unsupported. + # The toolchain on macOS 10.14 (darwin 18) and later cannot + # target any OS version that needs -single_module. + case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in + 10.0,*-darwin[567].*|10.[0-3],*-darwin[5-9].*|10.[0-3],*-darwin1[0-7].*) + _lt_dar_needs_single_mod=yes ;; + esac + ;; + esac if test yes = "$lt_cv_ld_exported_symbols_list"; then _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' else @@ -9785,8 +10214,9 @@ then : IFS=$lt_save_ifs ;; esac -else $as_nop - enable_shared=yes +else case e in #( + e) enable_shared=yes ;; +esac fi @@ -9817,8 +10247,9 @@ then : IFS=$lt_save_ifs ;; esac -else $as_nop - enable_static=yes +else case e in #( + e) enable_static=yes ;; +esac fi @@ -9829,28 +10260,52 @@ fi - -# Check whether --with-pic was given. + # Check whether --enable-pic was given. +if test ${enable_pic+y} +then : + enableval=$enable_pic; lt_p=${PACKAGE-default} + case $enableval in + yes|no) pic_mode=$enableval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for lt_pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS=$lt_save_ifs + ;; + esac +else case e in #( + e) # Check whether --with-pic was given. if test ${with_pic+y} then : withval=$with_pic; lt_p=${PACKAGE-default} - case $withval in - yes|no) pic_mode=$withval ;; - *) - pic_mode=default - # Look at the argument we got. We use all the common list separators. - lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, - for lt_pkg in $withval; do - IFS=$lt_save_ifs - if test "X$lt_pkg" = "X$lt_p"; then - pic_mode=yes - fi - done - IFS=$lt_save_ifs - ;; - esac -else $as_nop - pic_mode=default + case $withval in + yes|no) pic_mode=$withval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for lt_pkg in $withval; do + IFS=$lt_save_ifs + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS=$lt_save_ifs + ;; + esac +else case e in #( + e) pic_mode=default ;; +esac +fi + + ;; +esac fi @@ -9880,8 +10335,9 @@ then : IFS=$lt_save_ifs ;; esac -else $as_nop - enable_fast_install=yes +else case e in #( + e) enable_fast_install=yes ;; +esac fi @@ -9896,29 +10352,46 @@ case $host,$enable_shared in power*-*-aix[5-9]*,yes) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking which variant of shared library versioning to provide" >&5 printf %s "checking which variant of shared library versioning to provide... " >&6; } - -# Check whether --with-aix-soname was given. + # Check whether --enable-aix-soname was given. +if test ${enable_aix_soname+y} +then : + enableval=$enable_aix_soname; case $enableval in + aix|svr4|both) + ;; + *) + as_fn_error $? "Unknown argument to --enable-aix-soname" "$LINENO" 5 + ;; + esac + lt_cv_with_aix_soname=$enable_aix_soname +else case e in #( + e) # Check whether --with-aix-soname was given. if test ${with_aix_soname+y} then : withval=$with_aix_soname; case $withval in - aix|svr4|both) - ;; - *) - as_fn_error $? "Unknown argument to --with-aix-soname" "$LINENO" 5 - ;; - esac - lt_cv_with_aix_soname=$with_aix_soname -else $as_nop - if test ${lt_cv_with_aix_soname+y} + aix|svr4|both) + ;; + *) + as_fn_error $? "Unknown argument to --with-aix-soname" "$LINENO" 5 + ;; + esac + lt_cv_with_aix_soname=$with_aix_soname +else case e in #( + e) if test ${lt_cv_with_aix_soname+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_with_aix_soname=aix +else case e in #( + e) lt_cv_with_aix_soname=aix ;; +esac +fi + ;; +esac fi - with_aix_soname=$lt_cv_with_aix_soname + enable_aix_soname=$lt_cv_with_aix_soname ;; +esac fi + with_aix_soname=$enable_aix_soname { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $with_aix_soname" >&5 printf "%s\n" "$with_aix_soname" >&6; } if test aix != "$with_aix_soname"; then @@ -10007,8 +10480,8 @@ printf %s "checking for objdir... " >&6; } if test ${lt_cv_objdir+y} then : printf %s "(cached) " >&6 -else $as_nop - rm -f .libs 2>/dev/null +else case e in #( + e) rm -f .libs 2>/dev/null mkdir .libs 2>/dev/null if test -d .libs; then lt_cv_objdir=.libs @@ -10016,7 +10489,8 @@ else # MS-DOS does not allow filenames that begin with a dot. lt_cv_objdir=_libs fi -rmdir .libs 2>/dev/null +rmdir .libs 2>/dev/null ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_objdir" >&5 printf "%s\n" "$lt_cv_objdir" >&6; } @@ -10077,8 +10551,8 @@ printf %s "checking for ${ac_tool_prefix}file... " >&6; } if test ${lt_cv_path_MAGIC_CMD+y} then : printf %s "(cached) " >&6 -else $as_nop - case $MAGIC_CMD in +else case e in #( + e) case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; @@ -10121,6 +10595,7 @@ _LT_EOF IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; +esac ;; esac fi @@ -10144,8 +10619,8 @@ printf %s "checking for file... " >&6; } if test ${lt_cv_path_MAGIC_CMD+y} then : printf %s "(cached) " >&6 -else $as_nop - case $MAGIC_CMD in +else case e in #( + e) case $MAGIC_CMD in [\\/*] | ?:[\\/]*) lt_cv_path_MAGIC_CMD=$MAGIC_CMD # Let the user override the test with a path. ;; @@ -10188,6 +10663,7 @@ _LT_EOF IFS=$lt_save_ifs MAGIC_CMD=$lt_save_MAGIC_CMD ;; +esac ;; esac fi @@ -10231,7 +10707,7 @@ objext=$objext lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests -lt_simple_link_test_code='int main(){return(0);}' +lt_simple_link_test_code='int main(void){return(0);}' @@ -10287,8 +10763,8 @@ printf %s "checking if $compiler supports -fno-rtti -fno-exceptions... " >&6; } if test ${lt_cv_prog_compiler_rtti_exceptions+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_rtti_exceptions=no +else case e in #( + e) lt_cv_prog_compiler_rtti_exceptions=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="-fno-rtti -fno-exceptions" ## exclude from sc_useless_quotes_in_assignment @@ -10316,7 +10792,8 @@ else $as_nop fi fi $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_rtti_exceptions" >&5 printf "%s\n" "$lt_cv_prog_compiler_rtti_exceptions" >&6; } @@ -10372,7 +10849,7 @@ lt_prog_compiler_static= # PIC is the default for these OSes. ;; - mingw* | cygwin* | pw32* | os2* | cegcc*) + mingw* | windows* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style @@ -10475,7 +10952,7 @@ lt_prog_compiler_static= esac ;; - mingw* | cygwin* | pw32* | os2* | cegcc*) + mingw* | windows* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic='-DDLL_EXPORT' @@ -10516,6 +10993,12 @@ lt_prog_compiler_static= lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-static' ;; + *flang* | ftn | f18* | f95*) + # Flang compiler. + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; # flang / f18. f95 an alias for gfortran or flang on Debian flang* | f18* | f95*) lt_prog_compiler_wl='-Wl,' @@ -10604,6 +11087,12 @@ lt_prog_compiler_static= lt_prog_compiler_static='-Bstatic' ;; + *-mlibc) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. @@ -10620,6 +11109,9 @@ lt_prog_compiler_static= lt_prog_compiler_static='-non_shared' ;; + serenity*) + ;; + solaris*) lt_prog_compiler_pic='-KPIC' lt_prog_compiler_static='-Bstatic' @@ -10687,8 +11179,9 @@ printf %s "checking for $compiler option to produce PIC... " >&6; } if test ${lt_cv_prog_compiler_pic+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_pic=$lt_prog_compiler_pic +else case e in #( + e) lt_cv_prog_compiler_pic=$lt_prog_compiler_pic ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 printf "%s\n" "$lt_cv_prog_compiler_pic" >&6; } @@ -10703,8 +11196,8 @@ printf %s "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; if test ${lt_cv_prog_compiler_pic_works+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_pic_works=no +else case e in #( + e) lt_cv_prog_compiler_pic_works=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic -DPIC" ## exclude from sc_useless_quotes_in_assignment @@ -10732,7 +11225,8 @@ else $as_nop fi fi $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 printf "%s\n" "$lt_cv_prog_compiler_pic_works" >&6; } @@ -10768,8 +11262,8 @@ printf %s "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; if test ${lt_cv_prog_compiler_static_works+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_static_works=no +else case e in #( + e) lt_cv_prog_compiler_static_works=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext @@ -10790,7 +11284,8 @@ else $as_nop fi $RM -r conftest* LDFLAGS=$save_LDFLAGS - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 printf "%s\n" "$lt_cv_prog_compiler_static_works" >&6; } @@ -10812,8 +11307,8 @@ printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if test ${lt_cv_prog_compiler_c_o+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_c_o=no +else case e in #( + e) lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest @@ -10853,7 +11348,8 @@ else $as_nop cd .. $RM -r conftest $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 printf "%s\n" "$lt_cv_prog_compiler_c_o" >&6; } @@ -10868,8 +11364,8 @@ printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if test ${lt_cv_prog_compiler_c_o+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_c_o=no +else case e in #( + e) lt_cv_prog_compiler_c_o=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest @@ -10909,7 +11405,8 @@ else $as_nop cd .. $RM -r conftest $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o" >&5 printf "%s\n" "$lt_cv_prog_compiler_c_o" >&6; } @@ -10988,7 +11485,7 @@ printf %s "checking whether the $compiler linker ($LD) supports shared libraries extract_expsyms_cmds= case $host_os in - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. @@ -11000,9 +11497,6 @@ printf %s "checking whether the $compiler linker ($LD) supports shared libraries # we just hope/assume this is gcc and not c89 (= MSVC++ or ICC) with_gnu_ld=yes ;; - openbsd* | bitrig*) - with_gnu_ld=no - ;; linux* | k*bsd*-gnu | gnu*) link_all_deplibs=no ;; @@ -11106,7 +11600,7 @@ _LT_EOF fi ;; - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, ) is actually meaningless, # as there is no search path for DLLs. hardcode_libdir_flag_spec='-L$libdir' @@ -11116,6 +11610,7 @@ _LT_EOF enable_shared_with_static_runtimes=yes export_symbols_cmds='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[BCDGRS][ ]/s/.*[ ]\([^ ]*\)/\1 DATA/;s/^.*[ ]__nm__\([^ ]*\)[ ][^ ]*/\1 DATA/;/^I[ ]/d;/^[AITW][ ]/s/.* //'\'' | sort | uniq > $export_symbols' exclude_expsyms='[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname' + file_list_spec='@' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' @@ -11135,7 +11630,7 @@ _LT_EOF haiku*) archive_cmds='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' - link_all_deplibs=yes + link_all_deplibs=no ;; os2*) @@ -11162,7 +11657,7 @@ _LT_EOF cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' - old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + old_archive_from_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes=yes file_list_spec='@' ;; @@ -11262,6 +11757,11 @@ _LT_EOF fi ;; + *-mlibc) + archive_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + archive_expsym_cmds='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + ;; + netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' @@ -11508,8 +12008,8 @@ else if test ${lt_cv_aix_libpath_+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -11541,7 +12041,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam \ if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=/usr/lib:/lib fi - + ;; +esac fi aix_libpath=$lt_cv_aix_libpath_ @@ -11563,8 +12064,8 @@ else if test ${lt_cv_aix_libpath_+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -11596,7 +12097,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam \ if test -z "$lt_cv_aix_libpath_"; then lt_cv_aix_libpath_=/usr/lib:/lib fi - + ;; +esac fi aix_libpath=$lt_cv_aix_libpath_ @@ -11652,7 +12154,7 @@ fi export_dynamic_flag_spec=-rdynamic ;; - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. # hardcode_libdir_flag_spec is actually meaningless, as there is @@ -11669,14 +12171,14 @@ fi # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. - archive_cmds='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' + archive_cmds='$CC -Fe$output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' archive_expsym_cmds='if test DEF = "`$SED -n -e '\''s/^[ ]*//'\'' -e '\''/^\(;.*\)*$/d'\'' -e '\''s/^\(EXPORTS\|LIBRARY\)\([ ].*\)*$/DEF/p'\'' -e q $export_symbols`" ; then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ - $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + $CC -Fe$tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, )='true' @@ -11847,8 +12349,8 @@ printf %s "checking if $CC understands -b... " >&6; } if test ${lt_cv_prog_compiler__b+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler__b=no +else case e in #( + e) lt_cv_prog_compiler__b=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -b" echo "$lt_simple_link_test_code" > conftest.$ac_ext @@ -11869,7 +12371,8 @@ else $as_nop fi $RM -r conftest* LDFLAGS=$save_LDFLAGS - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler__b" >&5 printf "%s\n" "$lt_cv_prog_compiler__b" >&6; } @@ -11917,8 +12420,8 @@ printf %s "checking whether the $host_os linker accepts -exported_symbol... " >& if test ${lt_cv_irix_exported_symbol+y} then : printf %s "(cached) " >&6 -else $as_nop - save_LDFLAGS=$LDFLAGS +else case e in #( + e) save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS -shared $wl-exported_symbol ${wl}foo $wl-update_registry $wl/dev/null" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -11927,12 +12430,14 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : lt_cv_irix_exported_symbol=yes -else $as_nop - lt_cv_irix_exported_symbol=no +else case e in #( + e) lt_cv_irix_exported_symbol=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext - LDFLAGS=$save_LDFLAGS + LDFLAGS=$save_LDFLAGS ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_irix_exported_symbol" >&5 printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } @@ -11962,6 +12467,9 @@ printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } esac ;; + *-mlibc) + ;; + netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out @@ -11984,7 +12492,7 @@ printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } *nto* | *qnx*) ;; - openbsd* | bitrig*) + openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct=yes hardcode_shlibpath_var=no @@ -12027,7 +12535,7 @@ printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' - old_archive_From_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + old_archive_from_new_cmds='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes=yes file_list_spec='@' ;; @@ -12063,6 +12571,9 @@ printf "%s\n" "$lt_cv_irix_exported_symbol" >&6; } hardcode_libdir_separator=: ;; + serenity*) + ;; + solaris*) no_undefined_flag=' -z defs' if test yes = "$GCC"; then @@ -12260,8 +12771,8 @@ printf %s "checking whether -lc should be explicitly linked in... " >&6; } if test ${lt_cv_archive_cmds_need_lc+y} then : printf %s "(cached) " >&6 -else $as_nop - $RM conftest* +else case e in #( + e) $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 @@ -12297,7 +12808,8 @@ else $as_nop cat conftest.err 1>&5 fi $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc" >&5 printf "%s\n" "$lt_cv_archive_cmds_need_lc" >&6; } @@ -12468,7 +12980,7 @@ if test yes = "$GCC"; then *) lt_awk_arg='/^libraries:/' ;; esac case $host_os in - mingw* | cegcc*) lt_sed_strip_eq='s|=\([A-Za-z]:\)|\1|g' ;; + mingw* | windows* | cegcc*) lt_sed_strip_eq='s|=\([A-Za-z]:\)|\1|g' ;; *) lt_sed_strip_eq='s|=/|/|g' ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` @@ -12526,7 +13038,7 @@ BEGIN {RS = " "; FS = "/|\n";} { # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in - mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ + mingw* | windows* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's|/\([A-Za-z]:\)|\1|g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` @@ -12600,7 +13112,7 @@ aix[4-9]*) # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl - # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. + # linker flag in LDFLAGS as well, or --enable-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the @@ -12694,7 +13206,7 @@ bsdi[45]*) # libtool to hard-code these into programs ;; -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no @@ -12705,15 +13217,29 @@ cygwin* | mingw* | pw32* | cegcc*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds - postinstall_cmds='base_file=`basename \$file`~ - dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ - dldir=$destdir/`dirname \$dlpath`~ - test -d \$dldir || mkdir -p \$dldir~ - $install_prog $dir/$dlname \$dldir/$dlname~ - chmod a+x \$dldir/$dlname~ - if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then - eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; - fi' + # If user builds GCC with multilib enabled, + # it should just install on $(libdir) + # not on $(libdir)/../bin or 32 bits dlls would override 64 bit ones. + if test xyes = x"$multilib"; then + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + $install_prog $dir/$dlname $destdir/$dlname~ + chmod a+x $destdir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib $destdir/$dlname'\'' || exit \$?; + fi' + else + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + fi postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' @@ -12726,7 +13252,7 @@ cygwin* | mingw* | pw32* | cegcc*) sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api" ;; - mingw* | cegcc*) + mingw* | windows* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; @@ -12745,7 +13271,7 @@ cygwin* | mingw* | pw32* | cegcc*) library_names_spec='$libname.dll.lib' case $build_os in - mingw*) + mingw* | windows*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' @@ -12852,7 +13378,28 @@ freebsd* | dragonfly* | midnightbsd*) need_version=yes ;; esac + case $host_cpu in + powerpc64) + # On FreeBSD bi-arch platforms, a different variable is used for 32-bit + # binaries. See <https://man.freebsd.org/cgi/man.cgi?query=ld.so>. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int test_pointer_size[sizeof (void *) - 5]; + +_ACEOF +if ac_fn_c_try_compile "$LINENO" +then : shlibpath_var=LD_LIBRARY_PATH +else case e in #( + e) shlibpath_var=LD_32_LIBRARY_PATH ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + ;; + *) + shlibpath_var=LD_LIBRARY_PATH + ;; + esac case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes @@ -12882,8 +13429,9 @@ haiku*) soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no - sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' - hardcode_into_libs=yes + sys_lib_search_path_spec='/boot/system/non-packaged/develop/lib /boot/system/develop/lib' + sys_lib_dlsearch_path_spec='/boot/home/config/non-packaged/lib /boot/home/config/lib /boot/system/non-packaged/lib /boot/system/lib' + hardcode_into_libs=no ;; hpux9* | hpux10* | hpux11*) @@ -12993,7 +13541,7 @@ linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no - library_names_spec='$libname$release$shared_ext' + library_names_spec='$libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH @@ -13005,8 +13553,9 @@ linux*android*) hardcode_into_libs=yes dynamic_linker='Android linker' - # Don't embed -rpath directories since the linker doesn't support them. - hardcode_libdir_flag_spec='-L$libdir' + # -rpath works at least for libraries that are not overridden by + # libraries installed in system locations. + hardcode_libdir_flag_spec='$wl-rpath $wl$libdir' ;; # This must be glibc/ELF. @@ -13024,8 +13573,8 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) if test ${lt_cv_shlibpath_overrides_runpath+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_shlibpath_overrides_runpath=no +else case e in #( + e) lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl\"; \ @@ -13052,7 +13601,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir - + ;; +esac fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath @@ -13062,7 +13612,7 @@ fi # before this can be enabled. hardcode_into_libs=yes - # Ideally, we could use ldconfig to report *all* directores which are + # Ideally, we could use ldconfig to report *all* directories which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, @@ -13082,6 +13632,18 @@ fi dynamic_linker='GNU/Linux ld.so' ;; +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + netbsdelf*-gnu) version_type=linux need_lib_prefix=no @@ -13112,6 +13674,18 @@ netbsd*) hardcode_into_libs=yes ;; +*-mlibc) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='mlibc ld.so' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' @@ -13131,7 +13705,7 @@ newsos6) dynamic_linker='ldqnx.so' ;; -openbsd* | bitrig*) +openbsd*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no @@ -13191,6 +13765,17 @@ rdos*) dynamic_linker=no ;; +serenity*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + dynamic_linker='SerenityOS LibELF' + ;; + solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no @@ -13288,77 +13873,573 @@ uts4*) shlibpath_var=LD_LIBRARY_PATH ;; -*) - dynamic_linker=no - ;; -esac -{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 -printf "%s\n" "$dynamic_linker" >&6; } -test no = "$dynamic_linker" && can_build_shared=no - -variables_saved_for_relink="PATH $shlibpath_var $runpath_var" -if test yes = "$GCC"; then - variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" -fi - -if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then - sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec -fi - -if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then - sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec -fi - -# remember unaugmented sys_lib_dlsearch_path content for libtool script decls... -configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec - -# ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code -func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" - -# to be used as default LT_SYS_LIBRARY_PATH value in generated libtool -configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +emscripten*) + version_type=none + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext' + soname_spec='$libname$release$shared_ext' + finish_cmds= + dynamic_linker="Emscripten linker" + lt_prog_compiler_wl= +lt_prog_compiler_pic= +lt_prog_compiler_static= + + + if test yes = "$GCC"; then + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_static='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + fi + lt_prog_compiler_pic='-fPIC' + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + lt_prog_compiler_pic='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the '-m68020' flag to GCC prevents building anything better, + # like '-m68040'. + lt_prog_compiler_pic='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + + mingw* | windows* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic='-DDLL_EXPORT' + case $host_os in + os2*) + lt_prog_compiler_static='$wl-static' + ;; + esac + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + ;; + + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + lt_prog_compiler_static= + ;; + + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + ;; + + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + + msdosdjgpp*) + # Just because we use GCC doesn't mean we suddenly get shared libraries + # on systems that don't support them. + lt_prog_compiler_can_build_shared=no + enable_shared=no + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic=-Kconform_pic + fi + ;; + + *) + lt_prog_compiler_pic='-fPIC' + ;; + esac + + case $cc_basename in + nvcc*) # Cuda Compiler Driver 2.2 + lt_prog_compiler_wl='-Xlinker ' + if test -n "$lt_prog_compiler_pic"; then + lt_prog_compiler_pic="-Xcompiler $lt_prog_compiler_pic" + fi + ;; + esac + else + # PORTME Check for flag to pass linker flags through the system compiler. + case $host_os in + aix*) + lt_prog_compiler_wl='-Wl,' + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static='-Bstatic' + else + lt_prog_compiler_static='-bnso -bI:/lib/syscalls.exp' + fi + ;; + + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic='-fno-common' + case $cc_basename in + nagfor*) + # NAG Fortran compiler + lt_prog_compiler_wl='-Wl,-Wl,,' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + esac + ;; + + mingw* | windows* | cygwin* | pw32* | os2* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic='-DDLL_EXPORT' + case $host_os in + os2*) + lt_prog_compiler_static='$wl-static' + ;; + esac + ;; + + hpux9* | hpux10* | hpux11*) + lt_prog_compiler_wl='-Wl,' + # PIC is the default for IA64 HP-UX and 64-bit HP-UX, but + # not for PA HP-UX. + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic='+Z' + ;; + esac + # Is there a better lt_prog_compiler_static that works with the bundled CC? + lt_prog_compiler_static='$wl-a ${wl}archive' + ;; + + irix5* | irix6* | nonstopux*) + lt_prog_compiler_wl='-Wl,' + # PIC (with -KPIC) is the default. + lt_prog_compiler_static='-non_shared' + ;; + + linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + case $cc_basename in + # old Intel for x86_64, which still supported -KPIC. + ecc*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-static' + ;; + *flang* | ftn | f18* | f95*) + # Flang compiler. + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # flang / f18. f95 an alias for gfortran or flang on Debian + flang* | f18* | f95*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # icc used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + icc* | ifort*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + # Lahey Fortran 8.1. + lf95*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='--shared' + lt_prog_compiler_static='--static' + ;; + nagfor*) + # NAG Fortran compiler + lt_prog_compiler_wl='-Wl,-Wl,,' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + tcc*) + # Fabrice Bellard et al's Tiny C Compiler + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + pgcc* | pgf77* | pgf90* | pgf95* | pgfortran*) + # Portland Group compilers (*not* the Pentium gcc compiler, + # which looks to be a dead project) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + ccc*) + lt_prog_compiler_wl='-Wl,' + # All Alpha code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + xl* | bgxl* | bgf* | mpixl*) + # IBM XL C 8.0/Fortran 10.1, 11.1 on PPC and BlueGene + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-qpic' + lt_prog_compiler_static='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ Ceres\ Fortran* | *Sun*Fortran*\ [1-7].* | *Sun*Fortran*\ 8.[0-3]*) + # Sun Fortran 8.3 passes all unrecognized flags to the linker + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='' + ;; + *Sun\ F* | *Sun*Fortran*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Qoption ld ' + ;; + *Sun\ C*) + # Sun C 5.9 + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + lt_prog_compiler_wl='-Wl,' + ;; + *Intel*\ [CF]*Compiler*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + *Portland\ Group*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fpic' + lt_prog_compiler_static='-Bstatic' + ;; + esac + ;; + esac + ;; + + newsos6) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + *-mlibc) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-fPIC' + lt_prog_compiler_static='-static' + ;; + + *nto* | *qnx*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic='-fPIC -shared' + ;; + + osf3* | osf4* | osf5*) + lt_prog_compiler_wl='-Wl,' + # All OSF/1 code is PIC. + lt_prog_compiler_static='-non_shared' + ;; + + rdos*) + lt_prog_compiler_static='-non_shared' + ;; + + serenity*) + ;; + + solaris*) + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + case $cc_basename in + f77* | f90* | f95* | sunf77* | sunf90* | sunf95*) + lt_prog_compiler_wl='-Qoption ld ';; + *) + lt_prog_compiler_wl='-Wl,';; + esac + ;; + + sunos4*) + lt_prog_compiler_wl='-Qoption ld ' + lt_prog_compiler_pic='-PIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4 | sysv4.2uw2* | sysv4.3*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic='-Kconform_pic' + lt_prog_compiler_static='-Bstatic' + fi + ;; + + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_pic='-KPIC' + lt_prog_compiler_static='-Bstatic' + ;; + + unicos*) + lt_prog_compiler_wl='-Wl,' + lt_prog_compiler_can_build_shared=no + ;; + + uts4*) + lt_prog_compiler_pic='-pic' + lt_prog_compiler_static='-Bstatic' + ;; + + *) + lt_prog_compiler_can_build_shared=no + ;; + esac + fi + +case $host_os in + # For platforms that do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic= + ;; + *) + lt_prog_compiler_pic="$lt_prog_compiler_pic -DPIC" + ;; +esac + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 +printf %s "checking for $compiler option to produce PIC... " >&6; } +if test ${lt_cv_prog_compiler_pic+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) lt_cv_prog_compiler_pic=$lt_prog_compiler_pic ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic" >&5 +printf "%s\n" "$lt_cv_prog_compiler_pic" >&6; } +lt_prog_compiler_pic=$lt_cv_prog_compiler_pic + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic works" >&5 +printf %s "checking if $compiler PIC flag $lt_prog_compiler_pic works... " >&6; } +if test ${lt_cv_prog_compiler_pic_works+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) lt_cv_prog_compiler_pic_works=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic -DPIC" ## exclude from sc_useless_quotes_in_assignment + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_pic_works=yes + fi + fi + $RM conftest* + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works" >&5 +printf "%s\n" "$lt_cv_prog_compiler_pic_works" >&6; } + +if test yes = "$lt_cv_prog_compiler_pic_works"; then + case $lt_prog_compiler_pic in + "" | " "*) ;; + *) lt_prog_compiler_pic=" $lt_prog_compiler_pic" ;; + esac +else + lt_prog_compiler_pic= + lt_prog_compiler_can_build_shared=no +fi + +fi + + + + + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl eval lt_tmp_static_flag=\"$lt_prog_compiler_static\" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +printf %s "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } +if test ${lt_cv_prog_compiler_static_works+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) lt_cv_prog_compiler_static_works=no + save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_static_works=yes + fi + else + lt_cv_prog_compiler_static_works=yes + fi + fi + $RM -r conftest* + LDFLAGS=$save_LDFLAGS + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works" >&5 +printf "%s\n" "$lt_cv_prog_compiler_static_works" >&6; } + +if test yes = "$lt_cv_prog_compiler_static_works"; then + : +else + lt_prog_compiler_static= +fi + + + +='-fPIC' + archive_cmds='$CC -sSIDE_MODULE=2 -shared $libobjs $deplibs $compiler_flags -o $lib' + archive_expsym_cmds='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -sSIDE_MODULE=2 -shared $libobjs $deplibs $compiler_flags -o $lib -s EXPORTED_FUNCTIONS=@$output_objdir/$soname.expsym' + archive_cmds_need_lc=no + no_undefined_flag= + ;; + +*) + dynamic_linker=no + ;; +esac +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $dynamic_linker" >&5 +printf "%s\n" "$dynamic_linker" >&6; } +test no = "$dynamic_linker" && can_build_shared=no + +variables_saved_for_relink="PATH $shlibpath_var $runpath_var" +if test yes = "$GCC"; then + variables_saved_for_relink="$variables_saved_for_relink GCC_EXEC_PREFIX COMPILER_PATH LIBRARY_PATH" +fi + +if test set = "${lt_cv_sys_lib_search_path_spec+set}"; then + sys_lib_search_path_spec=$lt_cv_sys_lib_search_path_spec +fi + +if test set = "${lt_cv_sys_lib_dlsearch_path_spec+set}"; then + sys_lib_dlsearch_path_spec=$lt_cv_sys_lib_dlsearch_path_spec +fi + +# remember unaugmented sys_lib_dlsearch_path content for libtool script decls... +configure_time_dlsearch_path=$sys_lib_dlsearch_path_spec + +# ... but it needs LT_SYS_LIBRARY_PATH munging for other configure-time code +func_munge_path_list sys_lib_dlsearch_path_spec "$LT_SYS_LIBRARY_PATH" + +# to be used as default LT_SYS_LIBRARY_PATH value in generated libtool +configure_time_lt_sys_library_path=$LT_SYS_LIBRARY_PATH + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -13472,7 +14553,7 @@ else lt_cv_dlopen_self=yes ;; - mingw* | pw32* | cegcc*) + mingw* | windows* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; @@ -13489,16 +14570,22 @@ printf %s "checking for dlopen in -ldl... " >&6; } if test ${ac_cv_lib_dl_dlopen+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_check_lib_save_LIBS=$LIBS +else case e in #( + e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dlopen (); + builtin and then its argument prototype would still apply. + The 'extern "C"' is for builds by C++ compilers; + although this is not generally supported in C code supporting it here + has little cost and some practical benefit (sr 110532). */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (void); int main (void) { @@ -13510,24 +14597,27 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dl_dlopen=yes -else $as_nop - ac_cv_lib_dl_dlopen=no +else case e in #( + e) ac_cv_lib_dl_dlopen=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +LIBS=$ac_check_lib_save_LIBS ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 printf "%s\n" "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl -else $as_nop - +else case e in #( + e) lt_cv_dlopen=dyld lt_cv_dlopen_libs= lt_cv_dlopen_self=yes - + ;; +esac fi ;; @@ -13545,22 +14635,28 @@ fi if test "x$ac_cv_func_shl_load" = xyes then : lt_cv_dlopen=shl_load -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for shl_load in -ldld" >&5 printf %s "checking for shl_load in -ldld... " >&6; } if test ${ac_cv_lib_dld_shl_load+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_check_lib_save_LIBS=$LIBS +else case e in #( + e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char shl_load (); + builtin and then its argument prototype would still apply. + The 'extern "C"' is for builds by C++ compilers; + although this is not generally supported in C code supporting it here + has little cost and some practical benefit (sr 110532). */ +#ifdef __cplusplus +extern "C" +#endif +char shl_load (void); int main (void) { @@ -13572,39 +14668,47 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dld_shl_load=yes -else $as_nop - ac_cv_lib_dld_shl_load=no +else case e in #( + e) ac_cv_lib_dld_shl_load=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +LIBS=$ac_check_lib_save_LIBS ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_shl_load" >&5 printf "%s\n" "$ac_cv_lib_dld_shl_load" >&6; } if test "x$ac_cv_lib_dld_shl_load" = xyes then : lt_cv_dlopen=shl_load lt_cv_dlopen_libs=-ldld -else $as_nop - ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" +else case e in #( + e) ac_fn_c_check_func "$LINENO" "dlopen" "ac_cv_func_dlopen" if test "x$ac_cv_func_dlopen" = xyes then : lt_cv_dlopen=dlopen -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 printf %s "checking for dlopen in -ldl... " >&6; } if test ${ac_cv_lib_dl_dlopen+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_check_lib_save_LIBS=$LIBS +else case e in #( + e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldl $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dlopen (); + builtin and then its argument prototype would still apply. + The 'extern "C"' is for builds by C++ compilers; + although this is not generally supported in C code supporting it here + has little cost and some practical benefit (sr 110532). */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (void); int main (void) { @@ -13616,34 +14720,42 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dl_dlopen=yes -else $as_nop - ac_cv_lib_dl_dlopen=no +else case e in #( + e) ac_cv_lib_dl_dlopen=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +LIBS=$ac_check_lib_save_LIBS ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 printf "%s\n" "$ac_cv_lib_dl_dlopen" >&6; } if test "x$ac_cv_lib_dl_dlopen" = xyes then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-ldl -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dlopen in -lsvld" >&5 printf %s "checking for dlopen in -lsvld... " >&6; } if test ${ac_cv_lib_svld_dlopen+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_check_lib_save_LIBS=$LIBS +else case e in #( + e) ac_check_lib_save_LIBS=$LIBS LIBS="-lsvld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dlopen (); + builtin and then its argument prototype would still apply. + The 'extern "C"' is for builds by C++ compilers; + although this is not generally supported in C code supporting it here + has little cost and some practical benefit (sr 110532). */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (void); int main (void) { @@ -13655,34 +14767,42 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_svld_dlopen=yes -else $as_nop - ac_cv_lib_svld_dlopen=no +else case e in #( + e) ac_cv_lib_svld_dlopen=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +LIBS=$ac_check_lib_save_LIBS ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_svld_dlopen" >&5 printf "%s\n" "$ac_cv_lib_svld_dlopen" >&6; } if test "x$ac_cv_lib_svld_dlopen" = xyes then : lt_cv_dlopen=dlopen lt_cv_dlopen_libs=-lsvld -else $as_nop - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 +else case e in #( + e) { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for dld_link in -ldld" >&5 printf %s "checking for dld_link in -ldld... " >&6; } if test ${ac_cv_lib_dld_dld_link+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_check_lib_save_LIBS=$LIBS +else case e in #( + e) ac_check_lib_save_LIBS=$LIBS LIBS="-ldld $LIBS" cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ /* Override any GCC internal prototype to avoid an error. Use char because int might match the return type of a GCC - builtin and then its argument prototype would still apply. */ -char dld_link (); + builtin and then its argument prototype would still apply. + The 'extern "C"' is for builds by C++ compilers; + although this is not generally supported in C code supporting it here + has little cost and some practical benefit (sr 110532). */ +#ifdef __cplusplus +extern "C" +#endif +char dld_link (void); int main (void) { @@ -13694,12 +14814,14 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : ac_cv_lib_dld_dld_link=yes -else $as_nop - ac_cv_lib_dld_dld_link=no +else case e in #( + e) ac_cv_lib_dld_dld_link=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext -LIBS=$ac_check_lib_save_LIBS +LIBS=$ac_check_lib_save_LIBS ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dld_dld_link" >&5 printf "%s\n" "$ac_cv_lib_dld_dld_link" >&6; } @@ -13708,19 +14830,24 @@ then : lt_cv_dlopen=dld_link lt_cv_dlopen_libs=-ldld fi - + ;; +esac fi - + ;; +esac fi - + ;; +esac fi - + ;; +esac fi - + ;; +esac fi ;; @@ -13748,8 +14875,8 @@ printf %s "checking whether a program can dlopen itself... " >&6; } if test ${lt_cv_dlopen_self+y} then : printf %s "(cached) " >&6 -else $as_nop - if test yes = "$cross_compiling"; then : +else case e in #( + e) if test yes = "$cross_compiling"; then : lt_cv_dlopen_self=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 @@ -13799,11 +14926,11 @@ else /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) -int fnord () __attribute__((visibility("default"))); +int fnord (void) __attribute__((visibility("default"))); #endif -int fnord () { return 42; } -int main () +int fnord (void) { return 42; } +int main (void) { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; @@ -13843,7 +14970,8 @@ _LT_EOF fi rm -fr conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self" >&5 printf "%s\n" "$lt_cv_dlopen_self" >&6; } @@ -13855,8 +14983,8 @@ printf %s "checking whether a statically linked program can dlopen itself... " > if test ${lt_cv_dlopen_self_static+y} then : printf %s "(cached) " >&6 -else $as_nop - if test yes = "$cross_compiling"; then : +else case e in #( + e) if test yes = "$cross_compiling"; then : lt_cv_dlopen_self_static=cross else lt_dlunknown=0; lt_dlno_uscore=1; lt_dlneed_uscore=2 @@ -13906,11 +15034,11 @@ else /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) -int fnord () __attribute__((visibility("default"))); +int fnord (void) __attribute__((visibility("default"))); #endif -int fnord () { return 42; } -int main () +int fnord (void) { return 42; } +int main (void) { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; @@ -13950,7 +15078,8 @@ _LT_EOF fi rm -fr conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_dlopen_self_static" >&5 printf "%s\n" "$lt_cv_dlopen_self_static" >&6; } @@ -14108,8 +15237,8 @@ if test -z "$CXXCPP"; then if test ${ac_cv_prog_CXXCPP+y} then : printf %s "(cached) " >&6 -else $as_nop - # Double quotes because $CXX needs to be expanded +else case e in #( + e) # Double quotes because $CXX needs to be expanded for CXXCPP in "$CXX -E" cpp /lib/cpp do ac_preproc_ok=false @@ -14127,9 +15256,10 @@ _ACEOF if ac_fn_cxx_try_cpp "$LINENO" then : -else $as_nop - # Broken: fails on valid input. -continue +else case e in #( + e) # Broken: fails on valid input. +continue ;; +esac fi rm -f conftest.err conftest.i conftest.$ac_ext @@ -14143,15 +15273,16 @@ if ac_fn_cxx_try_cpp "$LINENO" then : # Broken: success on invalid input. continue -else $as_nop - # Passes both tests. +else case e in #( + e) # Passes both tests. ac_preproc_ok=: -break +break ;; +esac fi rm -f conftest.err conftest.i conftest.$ac_ext done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +# Because of 'break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok then : @@ -14160,7 +15291,8 @@ fi done ac_cv_prog_CXXCPP=$CXXCPP - + ;; +esac fi CXXCPP=$ac_cv_prog_CXXCPP else @@ -14183,9 +15315,10 @@ _ACEOF if ac_fn_cxx_try_cpp "$LINENO" then : -else $as_nop - # Broken: fails on valid input. -continue +else case e in #( + e) # Broken: fails on valid input. +continue ;; +esac fi rm -f conftest.err conftest.i conftest.$ac_ext @@ -14199,24 +15332,26 @@ if ac_fn_cxx_try_cpp "$LINENO" then : # Broken: success on invalid input. continue -else $as_nop - # Passes both tests. +else case e in #( + e) # Passes both tests. ac_preproc_ok=: -break +break ;; +esac fi rm -f conftest.err conftest.i conftest.$ac_ext done -# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +# Because of 'break', _AC_PREPROC_IFELSE's cleaning code was skipped. rm -f conftest.i conftest.err conftest.$ac_ext if $ac_preproc_ok then : -else $as_nop - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +else case e in #( + e) { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } ;; +esac fi ac_ext=c @@ -14353,8 +15488,9 @@ cc_basename=$func_cc_basename_result if test ${with_gnu_ld+y} then : withval=$with_gnu_ld; test no = "$withval" || with_gnu_ld=yes -else $as_nop - with_gnu_ld=no +else case e in #( + e) with_gnu_ld=no ;; +esac fi ac_prog=ld @@ -14363,7 +15499,7 @@ if test yes = "$GCC"; then { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for ld used by $CC" >&5 printf %s "checking for ld used by $CC... " >&6; } case $host in - *-*-mingw*) + *-*-mingw* | *-*-windows*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) @@ -14399,8 +15535,8 @@ fi if test ${lt_cv_path_LD+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -z "$LD"; then +else case e in #( + e) if test -z "$LD"; then lt_save_ifs=$IFS; IFS=$PATH_SEPARATOR for ac_dir in $PATH; do IFS=$lt_save_ifs @@ -14423,7 +15559,8 @@ else $as_nop IFS=$lt_save_ifs else lt_cv_path_LD=$LD # Let the user override the test with a path. -fi +fi ;; +esac fi LD=$lt_cv_path_LD @@ -14440,8 +15577,8 @@ printf %s "checking if the linker ($LD) is GNU ld... " >&6; } if test ${lt_cv_prog_gnu_ld+y} then : printf %s "(cached) " >&6 -else $as_nop - # I'd rather use --version here, but apparently some GNU lds only accept -v. +else case e in #( + e) # I'd rather use --version here, but apparently some GNU lds only accept -v. case `$LD -v 2>&1 </dev/null` in *GNU* | *'with BFD'*) lt_cv_prog_gnu_ld=yes @@ -14449,6 +15586,7 @@ case `$LD -v 2>&1 </dev/null` in *) lt_cv_prog_gnu_ld=no ;; +esac ;; esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_gnu_ld" >&5 @@ -14476,8 +15614,7 @@ with_gnu_ld=$lt_cv_prog_gnu_ld wlarc='$wl' # ancient GNU ld didn't support --whole-archive et. al. - if eval "`$CC -print-prog-name=ld` --help 2>&1" | - $GREP 'no-whole-archive' > /dev/null; then + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then whole_archive_flag_spec_CXX=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else whole_archive_flag_spec_CXX= @@ -14497,7 +15634,7 @@ with_gnu_ld=$lt_cv_prog_gnu_ld # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [-]L"' else GXX=no @@ -14648,8 +15785,8 @@ else if test ${lt_cv_aix_libpath__CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -14681,7 +15818,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam \ if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=/usr/lib:/lib fi - + ;; +esac fi aix_libpath=$lt_cv_aix_libpath__CXX @@ -14704,8 +15842,8 @@ else if test ${lt_cv_aix_libpath__CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int @@ -14737,7 +15875,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam \ if test -z "$lt_cv_aix_libpath__CXX"; then lt_cv_aix_libpath__CXX=/usr/lib:/lib fi - + ;; +esac fi aix_libpath=$lt_cv_aix_libpath__CXX @@ -14795,7 +15934,7 @@ fi esac ;; - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl* | ,icl* | no,icl*) # Native MSVC or ICC @@ -14848,6 +15987,7 @@ fi allow_undefined_flag_CXX=unsupported always_export_symbols_CXX=no enable_shared_with_static_runtimes_CXX=yes + file_list_spec_CXX='@' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then archive_cmds_CXX='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' @@ -14891,7 +16031,7 @@ fi module_cmds_CXX="\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dsymutil" archive_expsym_cmds_CXX="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" module_expsym_cmds_CXX="$SED -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" - if test yes != "$lt_cv_apple_cc_single_mod"; then + if test yes = "$_lt_dar_needs_single_mod" -a yes != "$lt_cv_apple_cc_single_mod"; then archive_cmds_CXX="\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dsymutil" archive_expsym_cmds_CXX="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dar_export_syms$_lt_dsymutil" fi @@ -14926,7 +16066,7 @@ fi cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' - old_archive_From_new_cmds_CXX='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + old_archive_from_new_cmds_CXX='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' enable_shared_with_static_runtimes_CXX=yes file_list_spec_CXX='@' ;; @@ -14967,7 +16107,7 @@ fi haiku*) archive_cmds_CXX='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' - link_all_deplibs_CXX=yes + link_all_deplibs_CXX=no ;; hpux9*) @@ -14994,7 +16134,7 @@ fi # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. - output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP " \-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "[-]L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then @@ -15059,7 +16199,7 @@ fi # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. - output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP " \-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP " [-]L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then @@ -15291,6 +16431,10 @@ fi esac ;; + *-mlibc) + ld_shlibs_CXX=yes + ;; + netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then archive_cmds_CXX='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' @@ -15307,7 +16451,7 @@ fi ld_shlibs_CXX=yes ;; - openbsd* | bitrig*) + openbsd*) if test -f /usr/libexec/ld.so; then hardcode_direct_CXX=yes hardcode_shlibpath_var_CXX=no @@ -15398,7 +16542,7 @@ fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [-]L"' else # FIXME: insert proper C++ library support @@ -15413,6 +16557,9 @@ fi ld_shlibs_CXX=no ;; + serenity*) + ;; + sunos4*) case $cc_basename in CC*) @@ -15482,7 +16629,7 @@ fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [-]L"' else # g++ 2.7 appears to require '-G' NOT '-shared' on this # platform. @@ -15493,7 +16640,7 @@ fi # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [-]L"' fi hardcode_libdir_flag_spec_CXX='$wl-R $wl$libdir' @@ -15636,10 +16783,11 @@ if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 case $prev$p in -L* | -R* | -l*) - # Some compilers place space between "-{L,R}" and the path. + # Some compilers place space between "-{L,R,l}" and the path. # Remove the space. - if test x-L = "$p" || - test x-R = "$p"; then + if test x-L = x"$p" || + test x-R = x"$p" || + test x-l = x"$p"; then prev=$p continue fi @@ -15806,7 +16954,7 @@ lt_prog_compiler_static_CXX= beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; - mingw* | cygwin* | os2* | pw32* | cegcc*) + mingw* | windows* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style @@ -15881,7 +17029,7 @@ lt_prog_compiler_static_CXX= ;; esac ;; - mingw* | cygwin* | os2* | pw32* | cegcc*) + mingw* | windows* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). lt_prog_compiler_pic_CXX='-DDLL_EXPORT' @@ -16008,6 +17156,8 @@ lt_prog_compiler_static_CXX= ;; netbsd* | netbsdelf*-gnu) ;; + *-mlibc) + ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. @@ -16036,6 +17186,8 @@ lt_prog_compiler_static_CXX= ;; psos*) ;; + serenity*) + ;; solaris*) case $cc_basename in CC* | sunCC*) @@ -16109,8 +17261,9 @@ printf %s "checking for $compiler option to produce PIC... " >&6; } if test ${lt_cv_prog_compiler_pic_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX +else case e in #( + e) lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5 printf "%s\n" "$lt_cv_prog_compiler_pic_CXX" >&6; } @@ -16125,8 +17278,8 @@ printf %s "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " > if test ${lt_cv_prog_compiler_pic_works_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_pic_works_CXX=no +else case e in #( + e) lt_cv_prog_compiler_pic_works_CXX=no ac_outfile=conftest.$ac_objext echo "$lt_simple_compile_test_code" > conftest.$ac_ext lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" ## exclude from sc_useless_quotes_in_assignment @@ -16154,7 +17307,8 @@ else $as_nop fi fi $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5 printf "%s\n" "$lt_cv_prog_compiler_pic_works_CXX" >&6; } @@ -16184,8 +17338,8 @@ printf %s "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; if test ${lt_cv_prog_compiler_static_works_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_static_works_CXX=no +else case e in #( + e) lt_cv_prog_compiler_static_works_CXX=no save_LDFLAGS=$LDFLAGS LDFLAGS="$LDFLAGS $lt_tmp_static_flag" echo "$lt_simple_link_test_code" > conftest.$ac_ext @@ -16206,7 +17360,8 @@ else $as_nop fi $RM -r conftest* LDFLAGS=$save_LDFLAGS - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5 printf "%s\n" "$lt_cv_prog_compiler_static_works_CXX" >&6; } @@ -16225,8 +17380,8 @@ printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if test ${lt_cv_prog_compiler_c_o_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_c_o_CXX=no +else case e in #( + e) lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest @@ -16266,7 +17421,8 @@ else $as_nop cd .. $RM -r conftest $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 printf "%s\n" "$lt_cv_prog_compiler_c_o_CXX" >&6; } @@ -16278,8 +17434,8 @@ printf %s "checking if $compiler supports -c -o file.$ac_objext... " >&6; } if test ${lt_cv_prog_compiler_c_o_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_prog_compiler_c_o_CXX=no +else case e in #( + e) lt_cv_prog_compiler_c_o_CXX=no $RM -r conftest 2>/dev/null mkdir conftest cd conftest @@ -16319,7 +17475,8 @@ else $as_nop cd .. $RM -r conftest $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_c_o_CXX" >&5 printf "%s\n" "$lt_cv_prog_compiler_c_o_CXX" >&6; } @@ -16375,7 +17532,7 @@ printf %s "checking whether the $compiler linker ($LD) supports shared libraries pw32*) export_symbols_cmds_CXX=$ltdll_cmds ;; - cygwin* | mingw* | cegcc*) + cygwin* | mingw* | windows* | cegcc*) case $cc_basename in cl* | icl*) exclude_expsyms_CXX='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' @@ -16427,8 +17584,8 @@ printf %s "checking whether -lc should be explicitly linked in... " >&6; } if test ${lt_cv_archive_cmds_need_lc_CXX+y} then : printf %s "(cached) " >&6 -else $as_nop - $RM conftest* +else case e in #( + e) $RM conftest* echo "$lt_simple_compile_test_code" > conftest.$ac_ext if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 @@ -16464,7 +17621,8 @@ else $as_nop cat conftest.err 1>&5 fi $RM conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_archive_cmds_need_lc_CXX" >&5 printf "%s\n" "$lt_cv_archive_cmds_need_lc_CXX" >&6; } @@ -16606,7 +17764,7 @@ aix[4-9]*) # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl - # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. + # linker flag in LDFLAGS as well, or --enable-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the @@ -16700,7 +17858,7 @@ bsdi[45]*) # libtool to hard-code these into programs ;; -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no @@ -16711,15 +17869,29 @@ cygwin* | mingw* | pw32* | cegcc*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds - postinstall_cmds='base_file=`basename \$file`~ - dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ - dldir=$destdir/`dirname \$dlpath`~ - test -d \$dldir || mkdir -p \$dldir~ - $install_prog $dir/$dlname \$dldir/$dlname~ - chmod a+x \$dldir/$dlname~ - if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then - eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; - fi' + # If user builds GCC with multilib enabled, + # it should just install on $(libdir) + # not on $(libdir)/../bin or 32 bits dlls would override 64 bit ones. + if test xyes = x"$multilib"; then + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + $install_prog $dir/$dlname $destdir/$dlname~ + chmod a+x $destdir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib $destdir/$dlname'\'' || exit \$?; + fi' + else + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + fi postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' @@ -16731,7 +17903,7 @@ cygwin* | mingw* | pw32* | cegcc*) soname_spec='`echo $libname | $SED -e 's/^lib/cyg/'``echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; - mingw* | cegcc*) + mingw* | windows* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[.]/-/g'`$versuffix$shared_ext' ;; @@ -16750,7 +17922,7 @@ cygwin* | mingw* | pw32* | cegcc*) library_names_spec='$libname.dll.lib' case $build_os in - mingw*) + mingw* | windows*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' @@ -16856,7 +18028,28 @@ freebsd* | dragonfly* | midnightbsd*) need_version=yes ;; esac + case $host_cpu in + powerpc64) + # On FreeBSD bi-arch platforms, a different variable is used for 32-bit + # binaries. See <https://man.freebsd.org/cgi/man.cgi?query=ld.so>. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int test_pointer_size[sizeof (void *) - 5]; + +_ACEOF +if ac_fn_cxx_try_compile "$LINENO" +then : shlibpath_var=LD_LIBRARY_PATH +else case e in #( + e) shlibpath_var=LD_32_LIBRARY_PATH ;; +esac +fi +rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext + ;; + *) + shlibpath_var=LD_LIBRARY_PATH + ;; + esac case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes @@ -16886,8 +18079,9 @@ haiku*) soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no - sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' - hardcode_into_libs=yes + sys_lib_search_path_spec='/boot/system/non-packaged/develop/lib /boot/system/develop/lib' + sys_lib_dlsearch_path_spec='/boot/home/config/non-packaged/lib /boot/home/config/lib /boot/system/non-packaged/lib /boot/system/lib' + hardcode_into_libs=no ;; hpux9* | hpux10* | hpux11*) @@ -16997,7 +18191,7 @@ linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no - library_names_spec='$libname$release$shared_ext' + library_names_spec='$libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH @@ -17009,8 +18203,9 @@ linux*android*) hardcode_into_libs=yes dynamic_linker='Android linker' - # Don't embed -rpath directories since the linker doesn't support them. - hardcode_libdir_flag_spec_CXX='-L$libdir' + # -rpath works at least for libraries that are not overridden by + # libraries installed in system locations. + hardcode_libdir_flag_spec_CXX='$wl-rpath $wl$libdir' ;; # This must be glibc/ELF. @@ -17028,8 +18223,8 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) if test ${lt_cv_shlibpath_overrides_runpath+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_shlibpath_overrides_runpath=no +else case e in #( + e) lt_cv_shlibpath_overrides_runpath=no save_LDFLAGS=$LDFLAGS save_libdir=$libdir eval "libdir=/foo; wl=\"$lt_prog_compiler_wl_CXX\"; \ @@ -17056,7 +18251,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext LDFLAGS=$save_LDFLAGS libdir=$save_libdir - + ;; +esac fi shlibpath_overrides_runpath=$lt_cv_shlibpath_overrides_runpath @@ -17066,7 +18262,7 @@ fi # before this can be enabled. hardcode_into_libs=yes - # Ideally, we could use ldconfig to report *all* directores which are + # Ideally, we could use ldconfig to report *all* directories which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, @@ -17086,6 +18282,18 @@ fi dynamic_linker='GNU/Linux ld.so' ;; +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + netbsdelf*-gnu) version_type=linux need_lib_prefix=no @@ -17116,6 +18324,18 @@ netbsd*) hardcode_into_libs=yes ;; +*-mlibc) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='mlibc ld.so' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' @@ -17135,7 +18355,7 @@ newsos6) dynamic_linker='ldqnx.so' ;; -openbsd* | bitrig*) +openbsd*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no @@ -17195,6 +18415,17 @@ rdos*) dynamic_linker=no ;; +serenity*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + dynamic_linker='SerenityOS LibELF' + ;; + solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no @@ -17243,53 +18474,526 @@ sysv4 | sysv4.3*) esac ;; -sysv4*MP*) - if test -d /usr/nec; then - version_type=linux # correct to gnu/linux during the next big refactor - library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' - soname_spec='$libname$shared_ext.$major' - shlibpath_var=LD_LIBRARY_PATH - fi - ;; +sysv4*MP*) + if test -d /usr/nec; then + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$shared_ext.$versuffix $libname$shared_ext.$major $libname$shared_ext' + soname_spec='$libname$shared_ext.$major' + shlibpath_var=LD_LIBRARY_PATH + fi + ;; + +sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) + version_type=sco + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=yes + hardcode_into_libs=yes + if test yes = "$with_gnu_ld"; then + sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' + else + sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' + case $host_os in + sco3.2v5*) + sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" + ;; + esac + fi + sys_lib_dlsearch_path_spec='/usr/lib' + ;; + +tpf*) + # TPF is a cross-target only. Preferred cross-host = GNU/Linux. + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + +uts4*) + version_type=linux # correct to gnu/linux during the next big refactor + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + ;; + +emscripten*) + version_type=none + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext' + soname_spec='$libname$release$shared_ext' + finish_cmds= + dynamic_linker="Emscripten linker" + lt_prog_compiler_wl_CXX= +lt_prog_compiler_pic_CXX= +lt_prog_compiler_static_CXX= + + + # C++ specific cases for pic, static, wl, etc. + if test yes = "$GXX"; then + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-static' + + case $host_os in + aix*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + fi + lt_prog_compiler_pic_CXX='-fPIC' + ;; + + amigaos*) + case $host_cpu in + powerpc) + # see comment about AmigaOS4 .so support + lt_prog_compiler_pic_CXX='-fPIC' + ;; + m68k) + # FIXME: we need at least 68020 code to build shared libraries, but + # adding the '-m68020' flag to GCC prevents building anything better, + # like '-m68040'. + lt_prog_compiler_pic_CXX='-m68020 -resident32 -malways-restore-a4' + ;; + esac + ;; + + beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) + # PIC is the default for these OSes. + ;; + mingw* | windows* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + # Although the cygwin gcc ignores -fPIC, still need this for old-style + # (--disable-auto-import) libraries + lt_prog_compiler_pic_CXX='-DDLL_EXPORT' + case $host_os in + os2*) + lt_prog_compiler_static_CXX='$wl-static' + ;; + esac + ;; + darwin* | rhapsody*) + # PIC is the default on this platform + # Common symbols not allowed in MH_DYLIB files + lt_prog_compiler_pic_CXX='-fno-common' + ;; + *djgpp*) + # DJGPP does not support shared libraries at all + lt_prog_compiler_pic_CXX= + ;; + haiku*) + # PIC is the default for Haiku. + # The "-static" flag exists, but is broken. + lt_prog_compiler_static_CXX= + ;; + interix[3-9]*) + # Interix 3.x gcc -fpic/-fPIC options generate broken code. + # Instead, we relocate shared libraries at runtime. + ;; + sysv4*MP*) + if test -d /usr/nec; then + lt_prog_compiler_pic_CXX=-Kconform_pic + fi + ;; + hpux*) + # PIC is the default for 64-bit PA HP-UX, but not for 32-bit + # PA HP-UX. On IA64 HP-UX, PIC is the default but the pic flag + # sets the default TLS model and affects inlining. + case $host_cpu in + hppa*64*) + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic_CXX='-fPIC -shared' + ;; + *) + lt_prog_compiler_pic_CXX='-fPIC' + ;; + esac + else + case $host_os in + aix[4-9]*) + # All AIX code is PIC. + if test ia64 = "$host_cpu"; then + # AIX 5 now supports IA64 processor + lt_prog_compiler_static_CXX='-Bstatic' + else + lt_prog_compiler_static_CXX='-bnso -bI:/lib/syscalls.exp' + fi + ;; + chorus*) + case $cc_basename in + cxch68*) + # Green Hills C++ Compiler + # _LT_TAGVAR(lt_prog_compiler_static, CXX)="--no_auto_instantiation -u __main -u __premain -u _abort -r $COOL_DIR/lib/libOrb.a $MVME_DIR/lib/CC/libC.a $MVME_DIR/lib/classix/libcx.s.a" + ;; + esac + ;; + mingw* | windows* | cygwin* | os2* | pw32* | cegcc*) + # This hack is so that the source file can tell whether it is being + # built for inclusion in a dll (and should export symbols for example). + lt_prog_compiler_pic_CXX='-DDLL_EXPORT' + ;; + dgux*) + case $cc_basename in + ec++*) + lt_prog_compiler_pic_CXX='-KPIC' + ;; + ghcx*) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + freebsd* | dragonfly* | midnightbsd*) + # FreeBSD uses GNU C++ + ;; + hpux9* | hpux10* | hpux11*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='$wl-a ${wl}archive' + if test ia64 != "$host_cpu"; then + lt_prog_compiler_pic_CXX='+Z' + fi + ;; + aCC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='$wl-a ${wl}archive' + case $host_cpu in + hppa*64*|ia64*) + # +Z the default + ;; + *) + lt_prog_compiler_pic_CXX='+Z' + ;; + esac + ;; + *) + ;; + esac + ;; + interix*) + # This is c89, which is MS Visual C++ (no shared libs) + # Anyone wants to do a port? + ;; + irix5* | irix6* | nonstopux*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_static_CXX='-non_shared' + # CC pic flag -KPIC is the default. + ;; + *) + ;; + esac + ;; + linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) + case $cc_basename in + KCC*) + # KAI C++ Compiler + lt_prog_compiler_wl_CXX='--backend -Wl,' + lt_prog_compiler_pic_CXX='-fPIC' + ;; + ecpc* ) + # old Intel C++ for x86_64, which still supported -KPIC. + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-static' + ;; + icpc* ) + # Intel C++, used to be incompatible with GCC. + # ICC 10 doesn't accept -KPIC any more. + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-fPIC' + lt_prog_compiler_static_CXX='-static' + ;; + pgCC* | pgcpp*) + # Portland Group C++ compiler + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-fpic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + cxx*) + # Compaq C++ + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + xlc* | xlC* | bgxl[cC]* | mpixl[cC]*) + # IBM XL 8.0, 9.0 on PPC and BlueGene + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-qpic' + lt_prog_compiler_static_CXX='-qstaticlink' + ;; + *) + case `$CC -V 2>&1 | $SED 5q` in + *Sun\ C*) + # Sun C++ 5.9 + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + esac + ;; + esac + ;; + lynxos*) + ;; + m88k*) + ;; + mvs*) + case $cc_basename in + cxx*) + lt_prog_compiler_pic_CXX='-W c,exportall' + ;; + *) + ;; + esac + ;; + netbsd* | netbsdelf*-gnu) + ;; + *-mlibc) + ;; + *qnx* | *nto*) + # QNX uses GNU C++, but need to define -shared option too, otherwise + # it will coredump. + lt_prog_compiler_pic_CXX='-fPIC -shared' + ;; + osf3* | osf4* | osf5*) + case $cc_basename in + KCC*) + lt_prog_compiler_wl_CXX='--backend -Wl,' + ;; + RCC*) + # Rational C++ 2.4.1 + lt_prog_compiler_pic_CXX='-pic' + ;; + cxx*) + # Digital/Compaq C++ + lt_prog_compiler_wl_CXX='-Wl,' + # Make sure the PIC flag is empty. It appears that all Alpha + # Linux and Compaq Tru64 Unix objects are PIC. + lt_prog_compiler_pic_CXX= + lt_prog_compiler_static_CXX='-non_shared' + ;; + *) + ;; + esac + ;; + psos*) + ;; + serenity*) + ;; + solaris*) + case $cc_basename in + CC* | sunCC*) + # Sun C++ 4.2, 5.x and Centerline C++ + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + lt_prog_compiler_wl_CXX='-Qoption ld ' + ;; + gcx*) + # Green Hills C++ Compiler + lt_prog_compiler_pic_CXX='-PIC' + ;; + *) + ;; + esac + ;; + sunos4*) + case $cc_basename in + CC*) + # Sun C++ 4.x + lt_prog_compiler_pic_CXX='-pic' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + lcc*) + # Lucid + lt_prog_compiler_pic_CXX='-pic' + ;; + *) + ;; + esac + ;; + sysv5* | unixware* | sco3.2v5* | sco5v6* | OpenUNIX*) + case $cc_basename in + CC*) + lt_prog_compiler_wl_CXX='-Wl,' + lt_prog_compiler_pic_CXX='-KPIC' + lt_prog_compiler_static_CXX='-Bstatic' + ;; + esac + ;; + tandem*) + case $cc_basename in + NCC*) + # NonStop-UX NCC 3.20 + lt_prog_compiler_pic_CXX='-KPIC' + ;; + *) + ;; + esac + ;; + vxworks*) + ;; + *) + lt_prog_compiler_can_build_shared_CXX=no + ;; + esac + fi + +case $host_os in + # For platforms that do not support PIC, -DPIC is meaningless: + *djgpp*) + lt_prog_compiler_pic_CXX= + ;; + *) + lt_prog_compiler_pic_CXX="$lt_prog_compiler_pic_CXX -DPIC" + ;; +esac + +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for $compiler option to produce PIC" >&5 +printf %s "checking for $compiler option to produce PIC... " >&6; } +if test ${lt_cv_prog_compiler_pic_CXX+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) lt_cv_prog_compiler_pic_CXX=$lt_prog_compiler_pic_CXX ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_CXX" >&5 +printf "%s\n" "$lt_cv_prog_compiler_pic_CXX" >&6; } +lt_prog_compiler_pic_CXX=$lt_cv_prog_compiler_pic_CXX + +# +# Check to make sure the PIC flag actually works. +# +if test -n "$lt_prog_compiler_pic_CXX"; then + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works" >&5 +printf %s "checking if $compiler PIC flag $lt_prog_compiler_pic_CXX works... " >&6; } +if test ${lt_cv_prog_compiler_pic_works_CXX+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) lt_cv_prog_compiler_pic_works_CXX=no + ac_outfile=conftest.$ac_objext + echo "$lt_simple_compile_test_code" > conftest.$ac_ext + lt_compiler_flag="$lt_prog_compiler_pic_CXX -DPIC" ## exclude from sc_useless_quotes_in_assignment + # Insert the option either (1) after the last *FLAGS variable, or + # (2) before a word containing "conftest.", or (3) at the end. + # Note that $ac_compile itself does not contain backslashes and begins + # with a dollar sign (not a hyphen), so the echo should work correctly. + # The option is referenced via a variable to avoid confusing sed. + lt_compile=`echo "$ac_compile" | $SED \ + -e 's:.*FLAGS}\{0,1\} :&$lt_compiler_flag :; t' \ + -e 's: [^ ]*conftest\.: $lt_compiler_flag&:; t' \ + -e 's:$: $lt_compiler_flag:'` + (eval echo "\"\$as_me:$LINENO: $lt_compile\"" >&5) + (eval "$lt_compile" 2>conftest.err) + ac_status=$? + cat conftest.err >&5 + echo "$as_me:$LINENO: \$? = $ac_status" >&5 + if (exit $ac_status) && test -s "$ac_outfile"; then + # The compiler can only warn and ignore the option if not recognized + # So say no if there are warnings other than the usual output. + $ECHO "$_lt_compiler_boilerplate" | $SED '/^$/d' >conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if test ! -s conftest.er2 || diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_pic_works_CXX=yes + fi + fi + $RM conftest* + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_pic_works_CXX" >&5 +printf "%s\n" "$lt_cv_prog_compiler_pic_works_CXX" >&6; } + +if test yes = "$lt_cv_prog_compiler_pic_works_CXX"; then + case $lt_prog_compiler_pic_CXX in + "" | " "*) ;; + *) lt_prog_compiler_pic_CXX=" $lt_prog_compiler_pic_CXX" ;; + esac +else + lt_prog_compiler_pic_CXX= + lt_prog_compiler_can_build_shared_CXX=no +fi + +fi + + + + + +# +# Check to make sure the static flag actually works. +# +wl=$lt_prog_compiler_wl_CXX eval lt_tmp_static_flag=\"$lt_prog_compiler_static_CXX\" +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking if $compiler static flag $lt_tmp_static_flag works" >&5 +printf %s "checking if $compiler static flag $lt_tmp_static_flag works... " >&6; } +if test ${lt_cv_prog_compiler_static_works_CXX+y} +then : + printf %s "(cached) " >&6 +else case e in #( + e) lt_cv_prog_compiler_static_works_CXX=no + save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS $lt_tmp_static_flag" + echo "$lt_simple_link_test_code" > conftest.$ac_ext + if (eval $ac_link 2>conftest.err) && test -s conftest$ac_exeext; then + # The linker can only warn and ignore the option if not recognized + # So say no if there are warnings + if test -s conftest.err; then + # Append any errors to the config.log. + cat conftest.err 1>&5 + $ECHO "$_lt_linker_boilerplate" | $SED '/^$/d' > conftest.exp + $SED '/^$/d; /^ *+/d' conftest.err >conftest.er2 + if diff conftest.exp conftest.er2 >/dev/null; then + lt_cv_prog_compiler_static_works_CXX=yes + fi + else + lt_cv_prog_compiler_static_works_CXX=yes + fi + fi + $RM -r conftest* + LDFLAGS=$save_LDFLAGS + ;; +esac +fi +{ printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_prog_compiler_static_works_CXX" >&5 +printf "%s\n" "$lt_cv_prog_compiler_static_works_CXX" >&6; } + +if test yes = "$lt_cv_prog_compiler_static_works_CXX"; then + : +else + lt_prog_compiler_static_CXX= +fi -sysv5* | sco3.2v5* | sco5v6* | unixware* | OpenUNIX* | sysv4*uw2*) - version_type=sco - need_lib_prefix=no - need_version=no - library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext $libname$shared_ext' - soname_spec='$libname$release$shared_ext$major' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=yes - hardcode_into_libs=yes - if test yes = "$with_gnu_ld"; then - sys_lib_search_path_spec='/usr/local/lib /usr/gnu/lib /usr/ccs/lib /usr/lib /lib' - else - sys_lib_search_path_spec='/usr/ccs/lib /usr/lib' - case $host_os in - sco3.2v5*) - sys_lib_search_path_spec="$sys_lib_search_path_spec /lib" - ;; - esac - fi - sys_lib_dlsearch_path_spec='/usr/lib' - ;; -tpf*) - # TPF is a cross-target only. Preferred cross-host = GNU/Linux. - version_type=linux # correct to gnu/linux during the next big refactor - need_lib_prefix=no - need_version=no - library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' - shlibpath_var=LD_LIBRARY_PATH - shlibpath_overrides_runpath=no - hardcode_into_libs=yes - ;; -uts4*) - version_type=linux # correct to gnu/linux during the next big refactor - library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' - soname_spec='$libname$release$shared_ext$major' - shlibpath_var=LD_LIBRARY_PATH +='-fPIC' + archive_cmds_CXX='$CC -sSIDE_MODULE=2 -shared $libobjs $deplibs $compiler_flags -o $lib' + archive_expsym_cmds_CXX='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -sSIDE_MODULE=2 -shared $libobjs $deplibs $compiler_flags -o $lib -s EXPORTED_FUNCTIONS=@$output_objdir/$soname.expsym' + archive_cmds_need_lc_CXX=no + no_undefined_flag_CXX= ;; *) @@ -17459,8 +19163,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_READELF+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$READELF"; then +else case e in #( + e) if test -n "$READELF"; then ac_cv_prog_READELF="$READELF" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -17482,7 +19186,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi READELF=$ac_cv_prog_READELF if test -n "$READELF"; then @@ -17508,8 +19213,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_prog_ac_ct_READELF+y} then : printf %s "(cached) " >&6 -else $as_nop - if test -n "$ac_ct_READELF"; then +else case e in #( + e) if test -n "$ac_ct_READELF"; then ac_cv_prog_ac_ct_READELF="$ac_ct_READELF" # Let the user override the test. else as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -17531,7 +19236,8 @@ done done IFS=$as_save_IFS -fi +fi ;; +esac fi ac_ct_READELF=$ac_cv_prog_ac_ct_READELF if test -n "$ac_ct_READELF"; then @@ -17563,28 +19269,30 @@ fi # Test for 64-bit build. # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# declarations like 'int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of size_t" >&5 printf %s "checking size of size_t... " >&6; } if test ${ac_cv_sizeof_size_t+y} then : printf %s "(cached) " >&6 -else $as_nop - if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (size_t))" "ac_cv_sizeof_size_t" "$ac_includes_default" +else case e in #( + e) if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (size_t))" "ac_cv_sizeof_size_t" "$ac_includes_default" then : -else $as_nop - if test "$ac_cv_type_size_t" = yes; then - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +else case e in #( + e) if test "$ac_cv_type_size_t" = yes; then + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (size_t) -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_size_t=0 - fi + fi ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_size_t" >&5 printf "%s\n" "$ac_cv_sizeof_size_t" >&6; } @@ -17600,8 +19308,8 @@ printf %s "checking for C compiler vendor... " >&6; } if test ${ax_cv_c_compiler_vendor+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) vendors=" intel: __ICC,__ECC,__INTEL_COMPILER ibm: __xlc__,__xlC__,__IBMC__,__IBMCPP__,__ibmxl__ @@ -17662,7 +19370,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext done ax_cv_c_compiler_vendor=`echo $vendor | cut -d: -f1` - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_c_compiler_vendor" >&5 printf "%s\n" "$ax_cv_c_compiler_vendor" >&6; } @@ -17676,8 +19385,9 @@ printf "%s\n" "$ax_cv_c_compiler_vendor" >&6; } if test ${enable_portable_binary+y} then : enableval=$enable_portable_binary; acx_maxopt_portable=$enableval -else $as_nop - acx_maxopt_portable=no +else case e in #( + e) acx_maxopt_portable=no ;; +esac fi @@ -17704,14 +19414,14 @@ if test "x$ac_test_CFLAGS" = "x"; then else xlc_opt="-qtune=auto" fi - as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$xlc_opt" | $as_tr_sh` + as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$xlc_opt" | sed "$as_sed_sh"` { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler accepts $xlc_opt" >&5 printf %s "checking whether the C compiler accepts $xlc_opt... " >&6; } if eval test \${$as_CACHEVAR+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -17731,11 +19441,13 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$as_CACHEVAR=yes" -else $as_nop - eval "$as_CACHEVAR=no" +else case e in #( + e) eval "$as_CACHEVAR=no" ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi eval ac_res=\$$as_CACHEVAR { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -17743,8 +19455,8 @@ printf "%s\n" "$ac_res" >&6; } if eval test \"x\$"$as_CACHEVAR"\" = x"yes" then : CFLAGS="$CFLAGS -O3 -qansialias -w $xlc_opt" -else $as_nop - CFLAGS="$CFLAGS -O3 -qansialias -w" +else case e in #( + e) CFLAGS="$CFLAGS -O3 -qansialias -w" echo "******************************************************" echo "* You seem to have the IBM C compiler. It is *" echo "* recommended for best performance that you use: *" @@ -17754,7 +19466,8 @@ else $as_nop echo "* where xxx is pwr2, pwr3, 604, or whatever kind of *" echo "* CPU you have. (Set the CFLAGS environment var. *" echo "* and re-run configure.) For more info, man cc. *" - echo "******************************************************" + echo "******************************************************" ;; +esac fi ;; @@ -17778,12 +19491,12 @@ printf %s "checking for x86 cpuid 0 output... " >&6; } if test ${ax_cv_gcc_x86_cpuid_0+y} then : printf %s "(cached) " >&6 -else $as_nop - if test "$cross_compiling" = yes +else case e in #( + e) if test "$cross_compiling" = yes then : ax_cv_gcc_x86_cpuid_0=unknown -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <stdio.h> int @@ -17810,13 +19523,16 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : ax_cv_gcc_x86_cpuid_0=`cat conftest_cpuid`; rm -f conftest_cpuid -else $as_nop - ax_cv_gcc_x86_cpuid_0=unknown; rm -f conftest_cpuid +else case e in #( + e) ax_cv_gcc_x86_cpuid_0=unknown; rm -f conftest_cpuid ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext + conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_gcc_x86_cpuid_0" >&5 printf "%s\n" "$ax_cv_gcc_x86_cpuid_0" >&6; } @@ -17840,12 +19556,12 @@ printf %s "checking for x86 cpuid 1 output... " >&6; } if test ${ax_cv_gcc_x86_cpuid_1+y} then : printf %s "(cached) " >&6 -else $as_nop - if test "$cross_compiling" = yes +else case e in #( + e) if test "$cross_compiling" = yes then : ax_cv_gcc_x86_cpuid_1=unknown -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <stdio.h> int @@ -17872,13 +19588,16 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : ax_cv_gcc_x86_cpuid_1=`cat conftest_cpuid`; rm -f conftest_cpuid -else $as_nop - ax_cv_gcc_x86_cpuid_1=unknown; rm -f conftest_cpuid +else case e in #( + e) ax_cv_gcc_x86_cpuid_1=unknown; rm -f conftest_cpuid ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext + conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_gcc_x86_cpuid_1" >&5 printf "%s\n" "$ax_cv_gcc_x86_cpuid_1" >&6; } @@ -17909,14 +19628,14 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu esac if test "x$icc_flags" != x; then for flag in $icc_flags; do - as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$flag" | $as_tr_sh` + as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$flag" | sed "$as_sed_sh"` { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler accepts $flag" >&5 printf %s "checking whether the C compiler accepts $flag... " >&6; } if eval test \${$as_CACHEVAR+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -17936,11 +19655,13 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$as_CACHEVAR=yes" -else $as_nop - eval "$as_CACHEVAR=no" +else case e in #( + e) eval "$as_CACHEVAR=no" ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi eval ac_res=\$$as_CACHEVAR { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -17948,8 +19669,9 @@ printf "%s\n" "$ac_res" >&6; } if eval test \"x\$"$as_CACHEVAR"\" = x"yes" then : icc_archflag=$flag; break -else $as_nop - : +else case e in #( + e) : ;; +esac fi done @@ -17984,8 +19706,8 @@ printf %s "checking whether the C compiler accepts -fstrict-aliasing... " >&6; } if test ${ax_cv_check_cflags___fstrict_aliasing+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -18005,19 +19727,22 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ax_cv_check_cflags___fstrict_aliasing=yes -else $as_nop - ax_cv_check_cflags___fstrict_aliasing=no +else case e in #( + e) ax_cv_check_cflags___fstrict_aliasing=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_check_cflags___fstrict_aliasing" >&5 printf "%s\n" "$ax_cv_check_cflags___fstrict_aliasing" >&6; } if test "x$ax_cv_check_cflags___fstrict_aliasing" = xyes then : CFLAGS="$CFLAGS -fstrict-aliasing" -else $as_nop - : +else case e in #( + e) : ;; +esac fi @@ -18027,8 +19752,8 @@ printf %s "checking whether the C compiler accepts -ffast-math... " >&6; } if test ${ax_cv_check_cflags___ffast_math+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -18048,19 +19773,22 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ax_cv_check_cflags___ffast_math=yes -else $as_nop - ax_cv_check_cflags___ffast_math=no +else case e in #( + e) ax_cv_check_cflags___ffast_math=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_check_cflags___ffast_math" >&5 printf "%s\n" "$ax_cv_check_cflags___ffast_math" >&6; } if test "x$ax_cv_check_cflags___ffast_math" = xyes then : CFLAGS="$CFLAGS -ffast-math" -else $as_nop - : +else case e in #( + e) : ;; +esac fi @@ -18074,8 +19802,9 @@ fi if test ${with_gcc_arch+y} then : withval=$with_gcc_arch; ax_gcc_arch=$withval -else $as_nop - ax_gcc_arch=yes +else case e in #( + e) ax_gcc_arch=yes ;; +esac fi @@ -18086,8 +19815,8 @@ printf "%s\n" "" >&6; } if test ${ax_cv_gcc_archflag+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_cv_gcc_archflag="unknown" if test "$GCC" = yes; then @@ -18109,12 +19838,12 @@ printf %s "checking for x86 cpuid 0 output... " >&6; } if test ${ax_cv_gcc_x86_cpuid_0+y} then : printf %s "(cached) " >&6 -else $as_nop - if test "$cross_compiling" = yes +else case e in #( + e) if test "$cross_compiling" = yes then : ax_cv_gcc_x86_cpuid_0=unknown -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <stdio.h> int @@ -18141,13 +19870,16 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : ax_cv_gcc_x86_cpuid_0=`cat conftest_cpuid`; rm -f conftest_cpuid -else $as_nop - ax_cv_gcc_x86_cpuid_0=unknown; rm -f conftest_cpuid +else case e in #( + e) ax_cv_gcc_x86_cpuid_0=unknown; rm -f conftest_cpuid ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext + conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_gcc_x86_cpuid_0" >&5 printf "%s\n" "$ax_cv_gcc_x86_cpuid_0" >&6; } @@ -18171,12 +19903,12 @@ printf %s "checking for x86 cpuid 1 output... " >&6; } if test ${ax_cv_gcc_x86_cpuid_1+y} then : printf %s "(cached) " >&6 -else $as_nop - if test "$cross_compiling" = yes +else case e in #( + e) if test "$cross_compiling" = yes then : ax_cv_gcc_x86_cpuid_1=unknown -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ #include <stdio.h> int @@ -18203,13 +19935,16 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : ax_cv_gcc_x86_cpuid_1=`cat conftest_cpuid`; rm -f conftest_cpuid -else $as_nop - ax_cv_gcc_x86_cpuid_1=unknown; rm -f conftest_cpuid +else case e in #( + e) ax_cv_gcc_x86_cpuid_1=unknown; rm -f conftest_cpuid ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext + conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_gcc_x86_cpuid_1" >&5 printf "%s\n" "$ax_cv_gcc_x86_cpuid_1" >&6; } @@ -18300,8 +20035,8 @@ printf %s "checking for $ac_word... " >&6; } if test ${ac_cv_path_PRTDIAG+y} then : printf %s "(cached) " >&6 -else $as_nop - case $PRTDIAG in +else case e in #( + e) case $PRTDIAG in [\\/]* | ?:[\\/]*) ac_cv_path_PRTDIAG="$PRTDIAG" # Let the user override the test with a path. ;; @@ -18328,6 +20063,7 @@ IFS=$as_save_IFS test -z "$ac_cv_path_PRTDIAG" && ac_cv_path_PRTDIAG="prtdiag" ;; +esac ;; esac fi PRTDIAG=$ac_cv_path_PRTDIAG @@ -18421,14 +20157,14 @@ fi for flag_prefix in $flag_prefixes; do for arch in $ax_gcc_arch; do flag="$flag_prefix$arch" - as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$flag" | $as_tr_sh` + as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$flag" | sed "$as_sed_sh"` { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler accepts $flag" >&5 printf %s "checking whether the C compiler accepts $flag... " >&6; } if eval test \${$as_CACHEVAR+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -18448,11 +20184,13 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$as_CACHEVAR=yes" -else $as_nop - eval "$as_CACHEVAR=no" +else case e in #( + e) eval "$as_CACHEVAR=no" ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi eval ac_res=\$$as_CACHEVAR { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -18464,8 +20202,9 @@ then : if test "x$flag" = "x-march=$arch"; then flag=-mtune=$arch; fi fi fi; ax_cv_gcc_archflag=$flag; break -else $as_nop - : +else case e in #( + e) : ;; +esac fi done @@ -18474,7 +20213,8 @@ done fi fi # $GCC=yes - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking for gcc architecture flag" >&5 @@ -18506,14 +20246,14 @@ fi CFLAGS="$CFLAGS -O3" fi - as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$CFLAGS" | $as_tr_sh` + as_CACHEVAR=`printf "%s\n" "ax_cv_check_cflags__$CFLAGS" | sed "$as_sed_sh"` { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking whether the C compiler accepts $CFLAGS" >&5 printf %s "checking whether the C compiler accepts $CFLAGS... " >&6; } if eval test \${$as_CACHEVAR+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -18533,11 +20273,13 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : eval "$as_CACHEVAR=yes" -else $as_nop - eval "$as_CACHEVAR=no" +else case e in #( + e) eval "$as_CACHEVAR=no" ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi eval ac_res=\$$as_CACHEVAR { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 @@ -18545,8 +20287,8 @@ printf "%s\n" "$ac_res" >&6; } if eval test \"x\$"$as_CACHEVAR"\" = x"yes" then : : -else $as_nop - +else case e in #( + e) echo "" echo "********************************************************" echo "* WARNING: The guessed CFLAGS don't seem to work with *" @@ -18554,7 +20296,8 @@ else $as_nop echo "* Use ./configure CFLAGS=... to specify your own flags *" echo "********************************************************" echo "" - + ;; +esac fi @@ -18578,8 +20321,8 @@ printf %s "checking CFLAGS for most reasonable warnings... " >&6; } if test ${ac_cv_cflags_warn_all+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ac_cv_cflags_warn_all="" ac_save_cflags_warn_all_found="yes" case "$ax_cv_c_compiler_vendor" in #( @@ -18668,23 +20411,26 @@ then : ;; esac -else $as_nop - +else case e in #( + e) CFLAGS=$ac_cv_cflags_warn_all { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: : CFLAGS=\"\$CFLAGS\""; } >&5 (: CFLAGS="$CFLAGS") 2>&5 ac_status=$? printf "%s\n" "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 test $ac_status = 0; } - + ;; +esac fi fi -else $as_nop - true - -fi +else case e in #( + e) true + ;; +esac +fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_cflags_warn_all" >&5 printf "%s\n" "$ac_cv_cflags_warn_all" >&6; } @@ -18715,8 +20461,9 @@ printf %s "checking whether to enable maintainer-specific portions of Makefiles. if test ${enable_maintainer_mode+y} then : enableval=$enable_maintainer_mode; USE_MAINTAINER_MODE=$enableval -else $as_nop - USE_MAINTAINER_MODE=no +else case e in #( + e) USE_MAINTAINER_MODE=no ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $USE_MAINTAINER_MODE" >&5 @@ -18787,28 +20534,30 @@ fi # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# declarations like 'int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of double" >&5 printf %s "checking size of double... " >&6; } if test ${ac_cv_sizeof_double+y} then : printf %s "(cached) " >&6 -else $as_nop - if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default" +else case e in #( + e) if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (double))" "ac_cv_sizeof_double" "$ac_includes_default" then : -else $as_nop - if test "$ac_cv_type_double" = yes; then - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +else case e in #( + e) if test "$ac_cv_type_double" = yes; then + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (double) -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_double=0 - fi + fi ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_double" >&5 printf "%s\n" "$ac_cv_sizeof_double" >&6; } @@ -18820,28 +20569,30 @@ printf "%s\n" "#define SIZEOF_DOUBLE $ac_cv_sizeof_double" >>confdefs.h # The cast to long int works around a bug in the HP C Compiler # version HP92453-01 B.11.11.23709.GP, which incorrectly rejects -# declarations like `int a3[[(sizeof (unsigned char)) >= 0]];'. +# declarations like 'int a3[[(sizeof (unsigned char)) >= 0]];'. # This bug is HP SR number 8606223364. { printf "%s\n" "$as_me:${as_lineno-$LINENO}: checking size of long double" >&5 printf %s "checking size of long double... " >&6; } if test ${ac_cv_sizeof_long_double+y} then : printf %s "(cached) " >&6 -else $as_nop - if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default" +else case e in #( + e) if ac_fn_c_compute_int "$LINENO" "(long int) (sizeof (long double))" "ac_cv_sizeof_long_double" "$ac_includes_default" then : -else $as_nop - if test "$ac_cv_type_long_double" = yes; then - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} +else case e in #( + e) if test "$ac_cv_type_long_double" = yes; then + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (long double) -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_long_double=0 - fi + fi ;; +esac fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sizeof_long_double" >&5 printf "%s\n" "$ac_cv_sizeof_long_double" >&6; } @@ -18888,8 +20639,8 @@ printf %s "checking whether byte ordering is bigendian... " >&6; } if test ${ac_cv_c_bigendian+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_cv_c_bigendian=unknown +else case e in #( + e) ac_cv_c_bigendian=unknown # See if we're dealing with a universal compiler. cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -18935,8 +20686,8 @@ rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext int main (void) { -#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \ - && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \ +#if ! (defined BYTE_ORDER && defined BIG_ENDIAN \\ + && defined LITTLE_ENDIAN && BYTE_ORDER && BIG_ENDIAN \\ && LITTLE_ENDIAN) bogus endian macros #endif @@ -18967,8 +20718,9 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_c_bigendian=yes -else $as_nop - ac_cv_c_bigendian=no +else case e in #( + e) ac_cv_c_bigendian=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi @@ -19012,8 +20764,9 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ac_cv_c_bigendian=yes -else $as_nop - ac_cv_c_bigendian=no +else case e in #( + e) ac_cv_c_bigendian=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext fi @@ -19040,22 +20793,23 @@ unsigned short int ascii_mm[] = int use_ebcdic (int i) { return ebcdic_mm[i] + ebcdic_ii[i]; } - extern int foo; - -int -main (void) -{ -return use_ascii (foo) == use_ebcdic (foo); - ; - return 0; -} + int + main (int argc, char **argv) + { + /* Intimidate the compiler so that it does not + optimize the arrays away. */ + char *p = argv[0]; + ascii_mm[1] = *p++; ebcdic_mm[1] = *p++; + ascii_ii[1] = *p++; ebcdic_ii[1] = *p++; + return use_ascii (argc) == use_ebcdic (*p); + } _ACEOF -if ac_fn_c_try_compile "$LINENO" +if ac_fn_c_try_link "$LINENO" then : - if grep BIGenDianSyS conftest.$ac_objext >/dev/null; then + if grep BIGenDianSyS conftest$ac_exeext >/dev/null; then ac_cv_c_bigendian=yes fi - if grep LiTTleEnDian conftest.$ac_objext >/dev/null ; then + if grep LiTTleEnDian conftest$ac_exeext >/dev/null ; then if test "$ac_cv_c_bigendian" = unknown; then ac_cv_c_bigendian=no else @@ -19064,9 +20818,10 @@ then : fi fi fi -rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +rm -f core conftest.err conftest.$ac_objext conftest.beam \ + conftest$ac_exeext conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ $ac_includes_default int @@ -19089,14 +20844,17 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : ac_cv_c_bigendian=no -else $as_nop - ac_cv_c_bigendian=yes +else case e in #( + e) ac_cv_c_bigendian=yes ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext + conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi - fi + fi ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_bigendian" >&5 printf "%s\n" "$ac_cv_c_bigendian" >&6; } @@ -19123,8 +20881,8 @@ printf %s "checking assembler .cfi pseudo-op support... " >&6; } if test ${gcc_cv_as_cfi_pseudo_op+y} then : printf %s "(cached) " >&6 -else $as_nop - ac_ext=c +else case e in #( + e) ac_ext=c ac_cpp='$CPP $CPPFLAGS' ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' @@ -19147,8 +20905,9 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : gcc_cv_as_cfi_pseudo_op=yes -else $as_nop - gcc_cv_as_cfi_pseudo_op=no +else case e in #( + e) gcc_cv_as_cfi_pseudo_op=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext ac_ext=c @@ -19157,7 +20916,8 @@ ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' ac_compiler_gnu=$ac_cv_c_compiler_gnu - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $gcc_cv_as_cfi_pseudo_op" >&5 printf "%s\n" "$gcc_cv_as_cfi_pseudo_op" >&6; } @@ -19178,8 +20938,8 @@ printf %s "checking assembler and linker support unaligned pc related relocs... if test ${libffi_cv_as_sparc_ua_pcrel+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) save_CFLAGS="$CFLAGS" save_LDFLAGS="$LDFLAGS" CFLAGS="$CFLAGS -fpic" @@ -19198,13 +20958,15 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : libffi_cv_as_sparc_ua_pcrel=yes -else $as_nop - libffi_cv_as_sparc_ua_pcrel=no +else case e in #( + e) libffi_cv_as_sparc_ua_pcrel=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext CFLAGS="$save_CFLAGS" - LDFLAGS="$save_LDFLAGS" + LDFLAGS="$save_LDFLAGS" ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_as_sparc_ua_pcrel" >&5 printf "%s\n" "$libffi_cv_as_sparc_ua_pcrel" >&6; } @@ -19219,8 +20981,8 @@ printf %s "checking assembler .register pseudo-op support... " >&6; } if test ${libffi_cv_as_register_pseudo_op+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) libffi_cv_as_register_pseudo_op=unknown # Check if we have .register cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -19237,11 +20999,13 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : libffi_cv_as_register_pseudo_op=yes -else $as_nop - libffi_cv_as_register_pseudo_op=no +else case e in #( + e) libffi_cv_as_register_pseudo_op=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_as_register_pseudo_op" >&5 printf "%s\n" "$libffi_cv_as_register_pseudo_op" >&6; } @@ -19258,14 +21022,15 @@ printf %s "checking assembler supports pc related relocs... " >&6; } if test ${libffi_cv_as_x86_pcrel+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) libffi_cv_as_x86_pcrel=no echo '.text; foo: nop; .data; .long foo-.; .text' > conftest.s if $CC $CFLAGS -c conftest.s > /dev/null 2>&1; then libffi_cv_as_x86_pcrel=yes fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_as_x86_pcrel" >&5 printf "%s\n" "$libffi_cv_as_x86_pcrel" >&6; } @@ -19282,8 +21047,8 @@ printf %s "checking compiler uses zarch features... " >&6; } if test ${libffi_cv_as_s390_zarch+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) libffi_cv_as_s390_zarch=no echo 'void foo(void) { bar(); bar(); }' > conftest.c if $CC $CFLAGS -S conftest.c > /dev/null 2>&1; then @@ -19291,7 +21056,8 @@ else $as_nop libffi_cv_as_s390_zarch=yes fi fi - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_as_s390_zarch" >&5 printf "%s\n" "$libffi_cv_as_s390_zarch" >&6; } @@ -19321,8 +21087,8 @@ printf %s "checking whether compiler supports pointer authentication... " >&6; } if test ${libffi_cv_as_ptrauth+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) libffi_cv_as_ptrauth=unknown cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ @@ -19348,11 +21114,13 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : libffi_cv_as_ptrauth=yes -else $as_nop - libffi_cv_as_ptrauth=no +else case e in #( + e) libffi_cv_as_ptrauth=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_as_ptrauth" >&5 printf "%s\n" "$libffi_cv_as_ptrauth" >&6; } @@ -19385,11 +21153,11 @@ printf %s "checking for _ prefix in compiled symbols... " >&6; } if test ${lt_cv_sys_symbol_underscore+y} then : printf %s "(cached) " >&6 -else $as_nop - lt_cv_sys_symbol_underscore=no +else case e in #( + e) lt_cv_sys_symbol_underscore=no cat > conftest.$ac_ext <<_LT_EOF void nm_test_func(){} -int main(){nm_test_func;return 0;} +int main(void){nm_test_func;return 0;} _LT_EOF if { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_compile\""; } >&5 (eval $ac_compile) 2>&5 @@ -19421,7 +21189,8 @@ _LT_EOF cat conftest.c >&5 fi rm -rf conftest* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $lt_cv_sys_symbol_underscore" >&5 printf "%s\n" "$lt_cv_sys_symbol_underscore" >&6; } @@ -19464,8 +21233,8 @@ printf %s "checking toolchain supports unwind section type... " >&6; } if test ${libffi_cv_as_x86_64_unwind_section_type+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) cat > conftest1.s << EOF .text .globl foo @@ -19484,10 +21253,12 @@ EOF # we ensure that we can compile _and_ link an assembly file containing an @unwind section # since the compiler can support it and not the linker (ie old binutils) if $CC -Wa,--fatal-warnings $CFLAGS -c conftest1.s > /dev/null 2>&1 && \ - $CC conftest2.c conftest1.o > /dev/null 2>&1 ; then + $CC conftest2.c conftest1.o -o conftest$ac_exeext > /dev/null 2>&1 ; then libffi_cv_as_x86_64_unwind_section_type=yes fi - + rm -f conftest1.s conftest1.o conftest2.c conftest$ac_exeext a.out + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_as_x86_64_unwind_section_type" >&5 printf "%s\n" "$libffi_cv_as_x86_64_unwind_section_type" >&6; } @@ -19504,8 +21275,8 @@ printf %s "checking whether the C compiler accepts -fno-lto... " >&6; } if test ${ax_cv_check_cflags___fno_lto+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) ax_check_save_flags=$CFLAGS if test x"$GCC" = xyes ; then add_gnu_werror="-Werror" @@ -19525,19 +21296,22 @@ _ACEOF if ac_fn_c_try_compile "$LINENO" then : ax_cv_check_cflags___fno_lto=yes -else $as_nop - ax_cv_check_cflags___fno_lto=no +else case e in #( + e) ax_cv_check_cflags___fno_lto=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam conftest.$ac_ext - CFLAGS=$ax_check_save_flags + CFLAGS=$ax_check_save_flags ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $ax_cv_check_cflags___fno_lto" >&5 printf "%s\n" "$ax_cv_check_cflags___fno_lto" >&6; } if test "x$ax_cv_check_cflags___fno_lto" = xyes then : libffi_cv_no_lto=-fno-lto -else $as_nop - : +else case e in #( + e) : ;; +esac fi @@ -19546,8 +21320,8 @@ printf %s "checking whether .eh_frame section should be read-only... " >&6; } if test ${libffi_cv_ro_eh_frame+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) libffi_cv_ro_eh_frame=yes echo 'extern void foo (void); void bar (void) { foo (); foo (); }' > conftest.c if $CC $CFLAGS -c -fpic -fexceptions $libffi_cv_no_lto -o conftest.o conftest.c > /dev/null 2>&1; then @@ -19556,7 +21330,8 @@ else $as_nop fi fi rm -f conftest.* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_ro_eh_frame" >&5 printf "%s\n" "$libffi_cv_ro_eh_frame" >&6; } @@ -19578,8 +21353,8 @@ printf %s "checking for __attribute__((visibility(\"hidden\")))... " >&6; } if test ${libffi_cv_hidden_visibility_attribute+y} then : printf %s "(cached) " >&6 -else $as_nop - +else case e in #( + e) echo 'int __attribute__ ((visibility ("hidden"))) foo (void) { return 1 ; }' > conftest.c libffi_cv_hidden_visibility_attribute=no if { ac_try='${CC-cc} -Werror -S conftest.c -o conftest.s 1>&5' @@ -19593,7 +21368,8 @@ else $as_nop fi fi rm -f conftest.* - + ;; +esac fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: $libffi_cv_hidden_visibility_attribute" >&5 printf "%s\n" "$libffi_cv_hidden_visibility_attribute" >&6; } @@ -19607,9 +21383,10 @@ fi # Check whether --enable-docs was given. if test ${enable_docs+y} then : - enableval=$enable_docs; enable_docs=no -else $as_nop - enable_docs=yes + enableval=$enable_docs; +else case e in #( + e) enable_docs=yes ;; +esac fi if test x$enable_docs = xyes; then @@ -19731,6 +21508,20 @@ then : fi +# Match every libdir spelling accepted by Autoconf's option parser. +libdir_explicit=no +eval "set x $ac_configure_args" +shift +for arg +do + case $arg in + -libdir | --libdir | --libdi | --libd | \ + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir_explicit=yes + break ;; + esac +done + # These variables are only ever used when we cross-build to X86_WIN32. # And we only support this with GCC, so... if test "x$GCC" = "xyes"; then @@ -19742,7 +21533,8 @@ if test "x$GCC" = "xyes"; then toolexecdir='${libdir}'/gcc-lib/'$(target_alias)' toolexeclibdir='${libdir}' fi - if test x"$enable_multi_os_directory" != x"no"; then + if test x"$enable_multi_os_directory" != x"no" && + test x"$libdir_explicit" != x"yes"; then multi_os_directory=`$CC $CFLAGS -print-multi-os-directory` case $multi_os_directory in .) ;; # Avoid trailing /. @@ -19833,8 +21625,8 @@ printf %s "checking for ld that supports -Wl,--gc-sections... " >&6; } if test "$cross_compiling" = yes then : ac_sectionLDflags=yes -else $as_nop - cat confdefs.h - <<_ACEOF >conftest.$ac_ext +else case e in #( + e) cat confdefs.h - <<_ACEOF >conftest.$ac_ext /* end confdefs.h. */ int main(void) @@ -19848,11 +21640,13 @@ _ACEOF if ac_fn_c_try_run "$LINENO" then : ac_sectionLDflags=yes -else $as_nop - ac_sectionLDflags=no +else case e in #( + e) ac_sectionLDflags=no ;; +esac fi rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ - conftest.$ac_objext conftest.beam conftest.$ac_ext + conftest.$ac_objext conftest.beam conftest.$ac_ext ;; +esac fi if test "$ac_test_CFLAGS" = set; then @@ -19887,8 +21681,9 @@ then : *) as_fn_error $? "Unknown argument to enable/disable symvers" "$LINENO" 5 ;; esac -else $as_nop - enable_symvers=yes +else case e in #( + e) enable_symvers=yes ;; +esac fi @@ -19956,8 +21751,9 @@ _ACEOF if ac_fn_c_try_link "$LINENO" then : libat_shared_libgcc=yes -else $as_nop - libat_shared_libgcc=no +else case e in #( + e) libat_shared_libgcc=no ;; +esac fi rm -f core conftest.err conftest.$ac_objext conftest.beam \ conftest$ac_exeext conftest.$ac_ext @@ -20006,14 +21802,14 @@ libat_min_gnu_ld_version=21400 # Change "yes" into either "no" or a style name. if test $enable_symvers != no && test $libat_shared_libgcc = yes; then if test $with_gnu_ld = yes; then - if test $libat_gnu_ld_version -ge $libat_min_gnu_ld_version ; then - enable_symvers=gnu - elif test $libat_ld_is_gold = yes ; then + if test $libat_ld_is_gold = yes ; then enable_symvers=gnu elif test $libat_ld_is_lld = yes ; then enable_symvers=gnu elif test $libat_ld_is_mold = yes ; then enable_symvers=gnu + elif test $libat_gnu_ld_version -ge $libat_min_gnu_ld_version ; then + enable_symvers=gnu else # The right tools, the right setup, but too old. Fallbacks? { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: === Linker version $libat_gnu_ld_version is too old for" >&5 @@ -20103,8 +21899,8 @@ cat >confcache <<\_ACEOF # config.status only pays attention to the cache file if you give it # the --recheck option to rerun configure. # -# `ac_cv_env_foo' variables (set or unset) will be overridden when -# loading this file, other *unset* `ac_cv_foo' will be assigned the +# 'ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* 'ac_cv_foo' will be assigned the # following values. _ACEOF @@ -20134,14 +21930,14 @@ printf "%s\n" "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} (set) 2>&1 | case $as_nl`(ac_space=' '; set) 2>&1` in #( *${as_nl}ac_space=\ *) - # `set' does not quote correctly, so add quotes: double-quote + # 'set' does not quote correctly, so add quotes: double-quote # substitution turns \\\\ into \\, and sed turns \\ into \. sed -n \ "s/'/'\\\\''/g; s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" ;; #( *) - # `set' quotes correctly as required by POSIX, so do not add quotes. + # 'set' quotes correctly as required by POSIX, so do not add quotes. sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" ;; esac | @@ -20210,6 +22006,18 @@ printf %s "checking that generated files are newer than configure... " >&6; } fi { printf "%s\n" "$as_me:${as_lineno-$LINENO}: result: done" >&5 printf "%s\n" "done" >&6; } +case $enable_silent_rules in # ((( + yes) AM_DEFAULT_VERBOSITY=0;; + no) AM_DEFAULT_VERBOSITY=1;; +esac +if test $am_cv_make_support_nested_variables = yes; then + AM_V='$(V)' + AM_DEFAULT_V='$(AM_DEFAULT_VERBOSITY)' +else + AM_V=$AM_DEFAULT_VERBOSITY + AM_DEFAULT_V=$AM_DEFAULT_VERBOSITY +fi + if test -n "$EXEEXT"; then am__EXEEXT_TRUE= am__EXEEXT_FALSE='#' @@ -20300,7 +22108,6 @@ cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 # Be more Bourne compatible DUALCASE=1; export DUALCASE # for MKS sh -as_nop=: if test ${ZSH_VERSION+y} && (emulate sh) >/dev/null 2>&1 then : emulate sh @@ -20309,12 +22116,13 @@ then : # is contrary to our usage. Disable this feature. alias -g '${1+"$@"}'='"$@"' setopt NO_GLOB_SUBST -else $as_nop - case `(set -o) 2>/dev/null` in #( +else case e in #( + e) case `(set -o) 2>/dev/null` in #( *posix*) : set -o posix ;; #( *) : ;; +esac ;; esac fi @@ -20386,7 +22194,7 @@ IFS=$as_save_IFS ;; esac -# We did not find ourselves, most probably we were run as `sh COMMAND' +# We did not find ourselves, most probably we were run as 'sh COMMAND' # in which case we are not to be found in the path. if test "x$as_myself" = x; then as_myself=$0 @@ -20415,7 +22223,6 @@ as_fn_error () } # as_fn_error - # as_fn_set_status STATUS # ----------------------- # Set $? to STATUS, without forking. @@ -20455,11 +22262,12 @@ then : { eval $1+=\$2 }' -else $as_nop - as_fn_append () +else case e in #( + e) as_fn_append () { eval $1=\$$1\$2 - } + } ;; +esac fi # as_fn_append # as_fn_arith ARG... @@ -20473,11 +22281,12 @@ then : { as_val=$(( $* )) }' -else $as_nop - as_fn_arith () +else case e in #( + e) as_fn_arith () { as_val=`expr "$@" || test $? -eq 1` - } + } ;; +esac fi # as_fn_arith @@ -20560,9 +22369,9 @@ if (echo >conf$$.file) 2>/dev/null; then if ln -s conf$$.file conf$$ 2>/dev/null; then as_ln_s='ln -s' # ... but there are two gotchas: - # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. - # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. - # In both cases, we have to default to `cp -pR'. + # 1) On MSYS, both 'ln -s file dir' and 'ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; 'ln -s' creates a wrapper executable. + # In both cases, we have to default to 'cp -pR'. ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || as_ln_s='cp -pR' elif ln conf$$.file conf$$ 2>/dev/null; then @@ -20643,10 +22452,12 @@ as_test_x='test -x' as_executable_p=as_fn_executable_p # Sed expression to map a string onto a valid CPP name. -as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" +as_sed_cpp="y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g" +as_tr_cpp="eval sed '$as_sed_cpp'" # deprecated # Sed expression to map a string onto a valid variable name. -as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" +as_sed_sh="y%*+%pp%;s%[^_$as_cr_alnum]%_%g" +as_tr_sh="eval sed '$as_sed_sh'" # deprecated exec 6>&1 @@ -20661,8 +22472,8 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # report actual input values of CONFIG_FILES etc. instead of their # values after options handling. ac_log=" -This file was extended by libffi $as_me 3.8.0, which was -generated by GNU Autoconf 2.71. Invocation command line was +This file was extended by libffi $as_me 3.8.1, which was +generated by GNU Autoconf 2.72. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -20694,7 +22505,7 @@ _ACEOF cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 ac_cs_usage="\ -\`$as_me' instantiates files and other configuration actions +'$as_me' instantiates files and other configuration actions from templates according to the current configuration. Unless the files and actions are specified as TAGs, all are instantiated by default. @@ -20729,11 +22540,11 @@ ac_cs_config_escaped=`printf "%s\n" "$ac_cs_config" | sed "s/^ //; s/'/'\\\\\\\\ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config='$ac_cs_config_escaped' ac_cs_version="\\ -libffi config.status 3.8.0 -configured by $0, generated by GNU Autoconf 2.71, +libffi config.status 3.8.1 +configured by $0, generated by GNU Autoconf 2.72, with options \\"\$ac_cs_config\\" -Copyright (C) 2021 Free Software Foundation, Inc. +Copyright (C) 2023 Free Software Foundation, Inc. This config.status script is free software; the Free Software Foundation gives unlimited permission to copy, distribute and modify it." @@ -20795,8 +22606,8 @@ do ac_need_defaults=false;; --he | --h) # Conflict between --help and --header - as_fn_error $? "ambiguous option: \`$1' -Try \`$0 --help' for more information.";; + as_fn_error $? "ambiguous option: '$1' +Try '$0 --help' for more information.";; --help | --hel | -h ) printf "%s\n" "$ac_cs_usage"; exit ;; -q | -quiet | --quiet | --quie | --qui | --qu | --q \ @@ -20804,8 +22615,8 @@ Try \`$0 --help' for more information.";; ac_cs_silent=: ;; # This is an error. - -*) as_fn_error $? "unrecognized option: \`$1' -Try \`$0 --help' for more information." ;; + -*) as_fn_error $? "unrecognized option: '$1' +Try '$0 --help' for more information." ;; *) as_fn_append ac_config_targets " $1" ac_need_defaults=false ;; @@ -21264,7 +23075,7 @@ do "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;; "libffi.pc") CONFIG_FILES="$CONFIG_FILES libffi.pc" ;; - *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + *) as_fn_error $? "invalid argument: '$ac_config_target'" "$LINENO" 5;; esac done @@ -21284,7 +23095,7 @@ fi # creating and moving files from /tmp can sometimes cause problems. # Hook for its removal unless debugging. # Note that there is a small window in which the directory will not be cleaned: -# after its creation but before its name has been assigned to `$tmp'. +# after its creation but before its name has been assigned to '$tmp'. $debug || { tmp= ac_tmp= @@ -21308,7 +23119,7 @@ ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. -# This happens for instance with `./config.status config.h'. +# This happens for instance with './config.status config.h'. if test -n "$CONFIG_FILES"; then @@ -21466,13 +23277,13 @@ fi # test -n "$CONFIG_FILES" # Set up the scripts for CONFIG_HEADERS section. # No need to generate them if there are no CONFIG_HEADERS. -# This happens for instance with `./config.status Makefile'. +# This happens for instance with './config.status Makefile'. if test -n "$CONFIG_HEADERS"; then cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF -# Transform confdefs.h into an awk script `defines.awk', embedded as +# Transform confdefs.h into an awk script 'defines.awk', embedded as # here-document in config.status, that substitutes the proper values into # config.h.in to produce config.h. @@ -21582,7 +23393,7 @@ do esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :L* | :C*:*) as_fn_error $? "invalid tag '$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac @@ -21604,19 +23415,19 @@ do -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, - # because $ac_f cannot contain `:'. + # because $ac_f cannot contain ':'. test -f "$ac_f" || case $ac_f in [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + as_fn_error 1 "cannot find input file: '$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`printf "%s\n" "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" done - # Let's still pretend it is `configure' which instantiates (i.e., don't + # Let's still pretend it is 'configure' which instantiates (i.e., don't # use $as_me), people would be surprised to read: # /* config.h. Generated by config.status. */ configure_input='Generated from '` @@ -21749,7 +23560,7 @@ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 esac _ACEOF -# Neutralize VPATH when `$srcdir' = `.'. +# Neutralize VPATH when '$srcdir' = '.'. # Shell code in configure.ac might set extrasub. # FIXME: do we really want to maintain this feature? cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 @@ -21780,9 +23591,9 @@ test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ "$ac_tmp/out"`; test -z "$ac_out"; } && - { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' + { printf "%s\n" "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable 'datarootdir' which seems to be undefined. Please make sure it is defined" >&5 -printf "%s\n" "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +printf "%s\n" "$as_me: WARNING: $ac_file contains a reference to the variable 'datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} rm -f "$ac_tmp/stdin" @@ -22081,15 +23892,15 @@ printf "%s\n" X/"$am_mf" | (exit $ac_status); } || am_rc=$? done if test $am_rc -ne 0; then - { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 -printf "%s\n" "$as_me: error: in \`$ac_pwd':" >&2;} + { { printf "%s\n" "$as_me:${as_lineno-$LINENO}: error: in '$ac_pwd':" >&5 +printf "%s\n" "$as_me: error: in '$ac_pwd':" >&2;} as_fn_error $? "Something went wrong bootstrapping makefile fragments for automatic dependency tracking. If GNU make was not used, consider re-running the configure script with MAKE=\"gmake\" (or whatever is necessary). You can also try re-running configure with the '--disable-dependency-tracking' option to at least be able to build the package (albeit without support for automatic dependency tracking). -See \`config.log' for more details" "$LINENO" 5; } +See 'config.log' for more details" "$LINENO" 5; } fi { am_dirpart=; unset am_dirpart;} { am_filepart=; unset am_filepart;} @@ -22118,13 +23929,13 @@ See \`config.log' for more details" "$LINENO" 5; } # Provide generalized library-building support services. # Written by Gordon Matzigkeit, 1996 -# Copyright (C) 2014 Free Software Foundation, Inc. +# Copyright (C) 2024 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of of the License, or +# the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, if you @@ -22505,7 +24316,7 @@ hardcode_direct=$hardcode_direct # Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes # DIR into the resulting binary and the resulting library dependency is -# "absolute",i.e impossible to change by setting \$shlibpath_var if the +# "absolute",i.e. impossible to change by setting \$shlibpath_var if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute @@ -22748,7 +24559,7 @@ hardcode_direct=$hardcode_direct_CXX # Set to "yes" if using DIR/libNAME\$shared_ext during linking hardcodes # DIR into the resulting binary and the resulting library dependency is -# "absolute",i.e impossible to change by setting \$shlibpath_var if the +# "absolute",i.e. impossible to change by setting \$shlibpath_var if the # library is relocated. hardcode_direct_absolute=$hardcode_direct_absolute_CXX diff --git a/deps/libffi/configure.ac b/deps/libffi/configure.ac index 826b453b8353..63731dd8eed7 100644 --- a/deps/libffi/configure.ac +++ b/deps/libffi/configure.ac @@ -2,7 +2,7 @@ dnl Process this with autoconf to create configure AC_PREREQ([2.68]) -AC_INIT([libffi],[3.8.0],[http://github.com/libffi/libffi/issues]) +AC_INIT([libffi],[3.8.1],[http://github.com/libffi/libffi/issues]) AC_CONFIG_HEADERS([fficonfig.h]) dnl Derive the version macros from AC_INIT so they cannot drift when the @@ -47,6 +47,11 @@ m4_rename_force([real_PRECIOUS],[_AC_ARG_VAR_PRECIOUS]) AC_SUBST(CFLAGS) +# Use the final compiler flags, including target flags added below, when make +# assembles sources. Keep explicit CCASFLAGS values, including empty ones. +if test "${CCASFLAGS+set}" != set; then + CCASFLAGS='$(CFLAGS)' +fi AM_PROG_AS AM_PROG_CC_C_O AC_PROG_EGREP @@ -285,9 +290,10 @@ EOF # we ensure that we can compile _and_ link an assembly file containing an @unwind section # since the compiler can support it and not the linker (ie old binutils) if $CC -Wa,--fatal-warnings $CFLAGS -c conftest1.s > /dev/null 2>&1 && \ - $CC conftest2.c conftest1.o > /dev/null 2>&1 ; then + $CC conftest2.c conftest1.o -o conftest$ac_exeext > /dev/null 2>&1 ; then libffi_cv_as_x86_64_unwind_section_type=yes fi + rm -f conftest1.s conftest1.o conftest2.c conftest$ac_exeext a.out ]) if test "x$libffi_cv_as_x86_64_unwind_section_type" = xyes; then AC_DEFINE(HAVE_AS_X86_64_UNWIND_SECTION_TYPE, 1, @@ -338,7 +344,7 @@ fi AC_ARG_ENABLE(docs, AS_HELP_STRING([--disable-docs],[Disable building of docs (default: no)]), - [enable_docs=no], + [], [enable_docs=yes]) AM_CONDITIONAL(BUILD_DOCS, [test x$enable_docs = xyes]) @@ -427,6 +433,20 @@ AC_ARG_ENABLE(multi-os-directory, [ --disable-multi-os-directory disable use of gcc --print-multi-os-directory to change the library installation directory]) +# Match every libdir spelling accepted by Autoconf's option parser. +libdir_explicit=no +eval "set x $ac_configure_args" +shift +for arg +do + case $arg in + -libdir | --libdir | --libdi | --libd | \ + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir_explicit=yes + break ;; + esac +done + # These variables are only ever used when we cross-build to X86_WIN32. # And we only support this with GCC, so... if test "x$GCC" = "xyes"; then @@ -438,7 +458,8 @@ if test "x$GCC" = "xyes"; then toolexecdir='${libdir}'/gcc-lib/'$(target_alias)' toolexeclibdir='${libdir}' fi - if test x"$enable_multi_os_directory" != x"no"; then + if test x"$enable_multi_os_directory" != x"no" && + test x"$libdir_explicit" != x"yes"; then multi_os_directory=`$CC $CFLAGS -print-multi-os-directory` case $multi_os_directory in .) ;; # Avoid trailing /. diff --git a/deps/libffi/depcomp b/deps/libffi/depcomp index 715e34311ed2..9f6725b9e0f5 100755 --- a/deps/libffi/depcomp +++ b/deps/libffi/depcomp @@ -1,9 +1,9 @@ #! /bin/sh # depcomp - compile a program generating dependencies as side-effects -scriptversion=2018-03-07.03; # UTC +scriptversion=2025-06-18.21; # UTC -# Copyright (C) 1999-2021 Free Software Foundation, Inc. +# Copyright (C) 1999-2025 Free Software Foundation, Inc. # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -47,11 +47,13 @@ Environment variables: libtool Whether libtool is used (yes/no). Report bugs to <bug-automake@gnu.org>. +GNU Automake home page: <https://www.gnu.org/software/automake/>. +General help using GNU software: <https://www.gnu.org/gethelp/>. EOF exit $? ;; -v | --v*) - echo "depcomp $scriptversion" + echo "depcomp (GNU Automake) $scriptversion" exit $? ;; esac @@ -113,7 +115,6 @@ nl=' # These definitions help. upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ lower=abcdefghijklmnopqrstuvwxyz -digits=0123456789 alpha=${upper}${lower} if test -z "$depmode" || test -z "$source" || test -z "$object"; then @@ -128,7 +129,7 @@ tmpdepfile=${tmpdepfile-`echo "$depfile" | sed 's/\.\([^.]*\)$/.T\1/'`} rm -f "$tmpdepfile" -# Avoid interferences from the environment. +# Avoid interference from the environment. gccflag= dashmflag= # Some modes work just like other modes, but use different flags. We @@ -198,8 +199,8 @@ gcc3) ;; gcc) -## Note that this doesn't just cater to obsosete pre-3.x GCC compilers. -## but also to in-use compilers like IMB xlc/xlC and the HP C compiler. +## Note that this doesn't just cater to obsolete pre-3.x GCC compilers. +## but also to in-use compilers like IBM xlc/xlC and the HP C compiler. ## (see the conditional assignment to $gccflag above). ## There are various ways to get dependency output from gcc. Here's ## why we pick this rather obscure method: @@ -783,9 +784,9 @@ exit 0 # Local Variables: # mode: shell-script # sh-indentation: 2 -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/doc/Makefile.in b/deps/libffi/doc/Makefile.in index 02a675ee87dc..47dce4f87a46 100644 --- a/deps/libffi/doc/Makefile.in +++ b/deps/libffi/doc/Makefile.in @@ -1,7 +1,7 @@ -# Makefile.in generated by automake 1.16.5 from Makefile.am. +# Makefile.in generated by automake 1.18.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2021 Free Software Foundation, Inc. +# Copyright (C) 1994-2025 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -69,6 +69,8 @@ am__make_running_with_option = \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +am__rm_f = rm -f $(am__rm_f_notfound) +am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -195,10 +197,9 @@ am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ - test -z "$$files" \ - || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ - || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ - $(am__cd) "$$dir" && rm -f $$files; }; \ + { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP) am__DIST_COMMON = $(srcdir)/Makefile.in mdate-sh texinfo.tex @@ -304,8 +305,10 @@ ac_ct_READELF = @ac_ct_READELF@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ +am__xargs_n = @am__xargs_n@ ax_enable_builddir_sed = @ax_enable_builddir_sed@ bindir = @bindir@ build = @build@ @@ -422,13 +425,13 @@ clean-libtool: .texi.dvi: $(AM_V_TEXI2DVI)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir)' \ - $(TEXI2DVI) $(AM_V_texinfo) --build-dir=$(@:.dvi=.t2d) -o $@ $(AM_V_texidevnull) \ + $(TEXI2DVI) $(AM_TEXI2FLAGS) -I $(srcdir) $(AM_V_texinfo) --build-dir=$(@:.dvi=.t2d) -o $@ $(AM_V_texidevnull) \ $< .texi.pdf: $(AM_V_TEXI2PDF)TEXINPUTS="$(am__TEXINFO_TEX_DIR)$(PATH_SEPARATOR)$$TEXINPUTS" \ MAKEINFO='$(MAKEINFO) $(AM_MAKEINFOFLAGS) $(MAKEINFOFLAGS) -I $(srcdir)' \ - $(TEXI2PDF) $(AM_V_texinfo) --build-dir=$(@:.pdf=.t2p) -o $@ $(AM_V_texidevnull) \ + $(TEXI2PDF) $(AM_TEXI2FLAGS) -I $(srcdir) $(AM_V_texinfo) --build-dir=$(@:.pdf=.t2p) -o $@ $(AM_V_texidevnull) \ $< .texi.html: @@ -545,11 +548,10 @@ dist-info: $(INFO_DEPS) done mostlyclean-aminfo: - -rm -rf libffi.t2d libffi.t2p + -$(am__rm_rf) libffi.t2d libffi.t2p clean-aminfo: - -test -z "libffi.dvi libffi.pdf libffi.ps libffi.html" \ - || rm -rf libffi.dvi libffi.pdf libffi.ps libffi.html + -$(am__rm_rf) libffi.dvi libffi.pdf libffi.ps libffi.html maintainer-clean-aminfo: @list='$(INFO_DEPS)'; for i in $$list; do \ @@ -563,6 +565,7 @@ ctags CTAGS: cscope cscopelist: + distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am @@ -630,8 +633,8 @@ mostlyclean-generic: clean-generic: distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + -$(am__rm_f) $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -820,3 +823,10 @@ uninstall-am: uninstall-dvi-am uninstall-html-am uninstall-info-am \ # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: + +# Tell GNU make to disable its built-in pattern rules. +%:: %,v +%:: RCS/%,v +%:: RCS/% +%:: s.% +%:: SCCS/s.% diff --git a/deps/libffi/doc/libffi.info b/deps/libffi/doc/libffi.info index 4c1abc85f777..ef2df81be6b6 100644 --- a/deps/libffi/doc/libffi.info +++ b/deps/libffi/doc/libffi.info @@ -1,4 +1,4 @@ -This is libffi.info, produced by makeinfo version 7.1 from libffi.texi. +This is libffi.info, produced by makeinfo version 7.2 from libffi.texi. This manual is for libffi, a portable foreign function interface library. @@ -515,6 +515,12 @@ array. structure types created like this should only be used to refer to members of real ‘FFI_TYPE_STRUCT’ objects. + Some ABIs classify array fields differently from structurally +identical structure fields. Because ‘ffi_type’ has no separate array +tag, this emulation cannot express that distinction. On those targets, +passing or returning an enclosing structure containing an emulated array +by value is not supported. + However, a phony array type like this will not cause any errors from ‘libffi’ if you use it as an argument or return type. This may be confusing. @@ -1052,7 +1058,6 @@ A trivial example that creates a new ‘puts’ by binding ‘fputs’ with return 0; } -  File: libffi.info, Node: Thread Safety, Prev: Closure Example, Up: Using libffi @@ -1208,7 +1213,6 @@ Index * void <3>: The Closure API. (line 19) * void <4>: The Closure API. (line 26) -  Tag Table: Node: Top1387 @@ -1221,18 +1225,18 @@ Node: Primitive Types12967 Node: Structures15284 Node: Size and Alignment16395 Node: Arrays Unions Enums18666 -Node: Type Example21643 -Node: Complex22949 -Node: Complex Type Example24463 -Node: Vector Types27536 -Node: Multiple ABIs31575 -Node: Reusable Call Plans31962 -Node: The Closure API34155 -Node: Closure Example38497 -Node: Thread Safety40141 -Node: Memory Usage40974 -Node: Missing Features42249 -Node: Index42626 +Node: Type Example21955 +Node: Complex23261 +Node: Complex Type Example24775 +Node: Vector Types27848 +Node: Multiple ABIs31887 +Node: Reusable Call Plans32274 +Node: The Closure API34467 +Node: Closure Example38809 +Node: Thread Safety40452 +Node: Memory Usage41285 +Node: Missing Features42560 +Node: Index42937  End Tag Table diff --git a/deps/libffi/doc/libffi.pdf b/deps/libffi/doc/libffi.pdf index 75458a8f7d5d..4e98b8d634fb 100644 Binary files a/deps/libffi/doc/libffi.pdf and b/deps/libffi/doc/libffi.pdf differ diff --git a/deps/libffi/doc/libffi.texi b/deps/libffi/doc/libffi.texi index 4d2802c5bd97..619c4ed34e99 100644 --- a/deps/libffi/doc/libffi.texi +++ b/deps/libffi/doc/libffi.texi @@ -566,6 +566,12 @@ Note that arrays cannot be passed or returned by value in C -- structure types created like this should only be used to refer to members of real @code{FFI_TYPE_STRUCT} objects. +Some ABIs classify array fields differently from structurally identical +structure fields. Because @code{ffi_type} has no separate array tag, this +emulation cannot express that distinction. On those targets, passing or +returning an enclosing structure containing an emulated array by value is +not supported. + However, a phony array type like this will not cause any errors from @code{libffi} if you use it as an argument or return type. This may be confusing. diff --git a/deps/libffi/doc/mdate-sh b/deps/libffi/doc/mdate-sh index e6d572d4cee9..22396e406796 100755 --- a/deps/libffi/doc/mdate-sh +++ b/deps/libffi/doc/mdate-sh @@ -1,9 +1,10 @@ #!/bin/sh -# Get modification time of a file or directory and pretty-print it. +# Get modification time of a file or directory, or value of +# $SOURCE_DATE_EPOCH, and pretty-print it, formatted like 1 January 2000. -scriptversion=2018-03-07.03; # UTC +scriptversion=2025-06-25.21; # UTC -# Copyright (C) 1995-2021 Free Software Foundation, Inc. +# Copyright (C) 1995-2025 Free Software Foundation, Inc. # written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, June 1995 # # This program is free software; you can redistribute it and/or modify @@ -50,21 +51,46 @@ Pretty-print the modification day of FILE, in the format: 1 January 1970 Report bugs to <bug-automake@gnu.org>. +GNU Automake home page: <https://www.gnu.org/software/automake/>. +General help using GNU software: <https://www.gnu.org/gethelp/>. EOF exit $? ;; -v | --v*) - echo "mdate-sh $scriptversion" + echo "mdate-sh (GNU Automake) $scriptversion" exit $? ;; esac +# Warn if more than one file given. +if test $# -ne 1; then + echo "$0: warning: multiple files given, using first: $*" >&2 +fi + error () { echo "$0: $1" >&2 exit 1 } +# set $month ("January") and $nummonth (1) given arg MON ("Jan"). +mon_to_month () +{ + case $1 in + Jan) month=January; nummonth=1;; + Feb) month=February; nummonth=2;; + Mar) month=March; nummonth=3;; + Apr) month=April; nummonth=4;; + May) month=May; nummonth=5;; + Jun) month=June; nummonth=6;; + Jul) month=July; nummonth=7;; + Aug) month=August; nummonth=8;; + Sep) month=September; nummonth=9;; + Oct) month=October; nummonth=10;; + Nov) month=November; nummonth=11;; + Dec) month=December; nummonth=12;; + esac +} # Prevent date giving response in another language. LANG=C @@ -78,6 +104,7 @@ export LC_TIME TZ=UTC0 export TZ +# # GNU ls changes its time format in response to the TIME_STYLE # variable. Since we cannot assume 'unset' works, revert this # variable to its documented default. @@ -123,20 +150,7 @@ do shift # Add another shift to the command. command="$command shift;" - case $1 in - Jan) month=January; nummonth=1;; - Feb) month=February; nummonth=2;; - Mar) month=March; nummonth=3;; - Apr) month=April; nummonth=4;; - May) month=May; nummonth=5;; - Jun) month=June; nummonth=6;; - Jul) month=July; nummonth=7;; - Aug) month=August; nummonth=8;; - Sep) month=September; nummonth=9;; - Oct) month=October; nummonth=10;; - Nov) month=November; nummonth=11;; - Dec) month=December; nummonth=12;; - esac + mon_to_month $1 done test -n "$month" || error "failed parsing '$ls_command /' output" @@ -150,7 +164,6 @@ eval $command # Because of the dummy argument above, month is in $2. # # On a POSIX system, we should have -# # $# = 5 # $1 = file size # $2 = month @@ -159,7 +172,6 @@ eval $command # $5 = filename # # On Darwin 7.7.0 and 7.6.0, we have -# # $# = 4 # $1 = day # $2 = month @@ -167,20 +179,7 @@ eval $command # $4 = filename # Get the month. -case $2 in - Jan) month=January; nummonth=1;; - Feb) month=February; nummonth=2;; - Mar) month=March; nummonth=3;; - Apr) month=April; nummonth=4;; - May) month=May; nummonth=5;; - Jun) month=June; nummonth=6;; - Jul) month=July; nummonth=7;; - Aug) month=August; nummonth=8;; - Sep) month=September; nummonth=9;; - Oct) month=October; nummonth=10;; - Nov) month=November; nummonth=11;; - Dec) month=December; nummonth=12;; -esac +mon_to_month $2 case $3 in ???*) day=$1;; @@ -205,9 +204,9 @@ case $3 in Nov) nummonthtod=11;; Dec) nummonthtod=12;; esac - # For the first six month of the year the time notation can also + # For the first six months of the year the time notation can also # be used for files modified in the last year. - if (expr $nummonth \> $nummonthtod) > /dev/null; + if (expr $nummonth \> $nummonthtod) >/dev/null; then year=`expr $year - 1` fi;; @@ -220,9 +219,9 @@ echo $day $month $year # Local Variables: # mode: shell-script # sh-indentation: 2 -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/doc/stamp-vti b/deps/libffi/doc/stamp-vti index dc281e38e0f6..c9adde9c03f9 100644 --- a/deps/libffi/doc/stamp-vti +++ b/deps/libffi/doc/stamp-vti @@ -1,4 +1,4 @@ -@set UPDATED 8 August 2026 -@set UPDATED-MONTH August 2026 -@set EDITION 3.8.0 -@set VERSION 3.8.0 +@set UPDATED 14 November 2026 +@set UPDATED-MONTH November 2026 +@set EDITION 3.8.1 +@set VERSION 3.8.1 diff --git a/deps/libffi/doc/texinfo.tex b/deps/libffi/doc/texinfo.tex index e48383defc4a..5d2f174ee9b2 100755 --- a/deps/libffi/doc/texinfo.tex +++ b/deps/libffi/doc/texinfo.tex @@ -1,11 +1,11 @@ % texinfo.tex -- TeX macros to handle Texinfo files. -% +% % Load plain if necessary, i.e., if running under initex. \expandafter\ifx\csname fmtname\endcsname\relax\input plain\fi % -\def\texinfoversion{2021-04-25.21} +\def\texinfoversion{2025-10-25.20} % -% Copyright 1985, 1986, 1988, 1990-2021 Free Software Foundation, Inc. +% Copyright 1985, 1986, 1988, 1990-2025 Free Software Foundation, Inc. % % This texinfo.tex file is free software: you can redistribute it and/or % modify it under the terms of the GNU General Public License as @@ -58,12 +58,6 @@ \message{Loading texinfo [version \texinfoversion]:} -% If in a .fmt file, print the version number -% and turn on active characters that we couldn't do earlier because -% they might have appeared in the input file name. -\everyjob{\message{[Texinfo version \texinfoversion]}% - \catcode`+=\active \catcode`\_=\active} - % LaTeX's \typeout. This ensures that the messages it is used for % are identical in format to the corresponding ones from latex/pdflatex. \def\typeout{\immediate\write17}% @@ -162,8 +156,9 @@ % Give the space character the catcode for a space. \def\spaceisspace{\catcode`\ =10\relax} -% Likewise for ^^M, the end of line character. -\def\endlineisspace{\catcode13=10\relax} +% Used to ignore an active newline that may appear immediately after +% a macro name. +{\catcode13=\active \gdef\ignoreactivenewline{\let^^M\empty}} \chardef\dashChar = `\- \chardef\slashChar = `\/ @@ -218,7 +213,7 @@ % @errormsg{MSG}. Do the index-like expansions on MSG, but if things % aren't perfect, it's not the end of the world, being an error message, % after all. -% +% \def\errormsg{\begingroup \indexnofonts \doerrormsg} \def\doerrormsg#1{\errmessage{#1}} @@ -241,9 +236,6 @@ % \def\finalout{\overfullrule=0pt } -\newdimen\outerhsize \newdimen\outervsize % set by the paper size routines -\newdimen\topandbottommargin \topandbottommargin=.75in - % Output a mark which sets \thischapter, \thissection and \thiscolor. % We dump everything together because we only have one kind of mark. % This works because we only use \botmark / \topmark, not \firstmark. @@ -284,8 +276,7 @@ % \topmark doesn't work for the very first chapter (after the title % page or the contents), so we use \firstmark there -- this gets us % the mark with the chapter defs, unless the user sneaks in, e.g., -% @setcolor (or @url, or @link, etc.) between @contents and the very -% first @chapter. +% @setcolor (or @url etc.) between @contents and the very first @chapter. \def\gettopheadingmarks{% \ifcase0\the\savedtopmark\fi \ifx\thischapter\empty \ifcase0\firstmark\fi \fi @@ -296,7 +287,6 @@ % Avoid "undefined control sequence" errors. \def\currentchapterdefs{} \def\currentsectiondefs{} -\def\currentsection{} \def\prevchapterdefs{} \def\prevsectiondefs{} \def\currentcolordefs{} @@ -317,16 +307,8 @@ \newbox\footlinebox % When outputting the double column layout for indices, an output routine -% is run several times, which hides the original value of \topmark. This -% can lead to a page heading being output and duplicating the chapter heading -% of the index. Hence, save the contents of \topmark at the beginning of -% the output routine. The saved contents are valid until we actually -% \shipout a page. -% -% (We used to run a short output routine to actually set \topmark and -% \firstmark to the right values, but if this was called with an empty page -% containing whatsits for writing index entries, the whatsits would be thrown -% away and the index auxiliary file would remain empty.) +% is run several times, hiding the original value of \topmark. Hence, save +% \topmark at the beginning. % \newtoks\savedtopmark \newif\iftopmarksaved @@ -351,15 +333,9 @@ % \checkchapterpage % - % Retrieve the information for the headings from the marks in the page, - % and call Plain TeX's \makeheadline and \makefootline, which use the - % values in \headline and \footline. - % - % Common context changes for both heading and footing. - % Do this outside of the \shipout so @code etc. will be expanded in - % the headline as they should be, not taken literally (outputting ''code). + % Make the heading and footing. \makeheadline and \makefootline + % use the contents of \headline and \footline. \def\commonheadfootline{\let\hsize=\txipagewidth \texinfochars} - % \ifodd\pageno \getoddheadingmarks \else \getevenheadingmarks \fi \global\setbox\headlinebox = \vbox{\commonheadfootline \makeheadline}% \ifodd\pageno \getoddfootingmarks \else \getevenfootingmarks \fi @@ -449,43 +425,22 @@ }% } -% First remove any @comment, then any @c comment. Pass the result on to -% \argcheckspaces. +% First remove any @comment, then any @c comment. Pass the result on to +% \argremovespace. \def\argremovecomment#1\comment#2\ArgTerm{\argremovec #1\c\ArgTerm} -\def\argremovec#1\c#2\ArgTerm{\argcheckspaces#1\^^M\ArgTerm} - -% Each occurrence of `\^^M' or `<space>\^^M' is replaced by a single space. -% -% \argremovec might leave us with trailing space, e.g., +\def\argremovec#1\c#2\ArgTerm{\argremovespace#1$ $\ArgTerm} +% \argremovec might leave us with trailing space, though; e.g., % @end itemize @c foo -% This space token undergoes the same procedure and is eventually removed -% by \finishparsearg. -% -\def\argcheckspaces#1\^^M{\argcheckspacesX#1\^^M \^^M} -\def\argcheckspacesX#1 \^^M{\argcheckspacesY#1\^^M} -\def\argcheckspacesY#1\^^M#2\^^M#3\ArgTerm{% - \def\temp{#3}% - \ifx\temp\empty - % Do not use \next, perhaps the caller of \parsearg uses it; reuse \temp: - \let\temp\finishparsearg - \else - \let\temp\argcheckspaces - \fi - % Put the space token in: - \temp#1 #3\ArgTerm -} +% Note that the argument cannot contain the TeX $, as its catcode is +% changed to \other when Texinfo source is read. +\def\argremovespace#1 $#2\ArgTerm{\finishparsearg#1$\ArgTerm} % If a _delimited_ argument is enclosed in braces, they get stripped; so % to get _exactly_ the rest of the line, we had to prevent such situation. -% We prepended an \empty token at the very beginning and we expand it now, -% just before passing the control to \argtorun. -% (Similarly, we have to think about #3 of \argcheckspacesY above: it is -% either the null string, or it ends with \^^M---thus there is no danger -% that a pair of braces would be stripped. -% -% But first, we have to remove the trailing space token. -% -\def\finishparsearg#1 \ArgTerm{\expandafter\argtorun\expandafter{#1}} +% We prepended an \empty token at the very beginning and we expand it +% just before passing the control to \next. +% (But first, we have to remove the remaining $ or two.) +\def\finishparsearg#1$#2\ArgTerm{\expandafter\argtorun\expandafter{#1}} % \parseargdef - define a command taking an argument on the line @@ -528,8 +483,8 @@ % \envdef\foo{...} % \def\Efoo{...} % -% It's the responsibility of \envdef to insert \begingroup before the -% actual body; @end closes the group after calling \Efoo. \envdef also +% \envdef inserts \begingroup before the actual body; @end calls +% \Efoo then closes the group with \endgroup. \envdef also % defines \thisenv, so the current environment is known; @end checks % whether the environment name matches. The \checkenv macro can also be % used to check whether the current environment is the one expected. @@ -547,7 +502,7 @@ % ... but they get defined via ``\envdef\foo{...}'': \long\def\envdef#1#2{\def#1{\startenvironment#1#2}} -\def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}} +\long\def\envparseargdef#1#2{\parseargdef#1{\startenvironment#1#2}} % Check whether we're in the right environment: \def\checkenv#1{% @@ -608,6 +563,9 @@ % @/ allows a line break. \let\/=\allowbreak +% @- allows explicit insertion of hyphenation points +\def\-{\discretionary{\normaldash}{}{}}% + % @. is an end-of-sentence period. \def\.{.\spacefactor=\endofsentencespacefactor\space} @@ -617,21 +575,6 @@ % @? is an end-of-sentence query. \def\?{?\spacefactor=\endofsentencespacefactor\space} -% @frenchspacing on|off says whether to put extra space after punctuation. -% -\def\onword{on} -\def\offword{off} -% -\parseargdef\frenchspacing{% - \def\temp{#1}% - \ifx\temp\onword \plainfrenchspacing - \else\ifx\temp\offword \plainnonfrenchspacing - \else - \errhelp = \EMsimple - \errmessage{Unknown @frenchspacing option `\temp', must be on|off}% - \fi\fi -} - % @w prevents a word break. Without the \leavevmode, @w at the % beginning of a paragraph, when TeX is still in vertical mode, would % produce a whole line of output instead of starting the paragraph. @@ -725,32 +668,22 @@ \dimen2 = \ht\strutbox \advance\dimen2 by \dp\strutbox \ifdim\dimen0 > \dimen2 + % This is similar to the 'needspace' module in LaTeX. + % The first penalty allows a break if the end of the page is + % not too far away. Following penalties and skips are discarded. + % Otherwise, require at least \dimen0 of vertical space. % - % Do a \strut just to make the height of this box be normal, so the - % normal leading is inserted relative to the preceding line. - % And a page break here is fine. - \vtop to #1\mil{\strut\vfil}% - % - % TeX does not even consider page breaks if a penalty added to the - % main vertical list is 10000 or more. But in order to see if the - % empty box we just added fits on the page, we must make it consider - % page breaks. On the other hand, we don't want to actually break the - % page after the empty box. So we use a penalty of 9999. - % - % There is an extremely small chance that TeX will actually break the - % page at this \penalty, if there are no other feasible breakpoints in - % sight. (If the user is using lots of big @group commands, which - % almost-but-not-quite fill up a page, TeX will have a hard time doing - % good page breaking, for example.) However, I could not construct an - % example where a page broke at this \penalty; if it happens in a real - % document, then we can reconsider our strategy. + % (We used to use a \vtop to reserve space, but this had spacing issues + % when followed by a section heading, as it was not a "discardable item". + % This also has the benefit of providing glue before the page break if + % there isn't enough space.) + \vskip0pt plus \dimen0 + \penalty-100 + \vskip0pt plus -\dimen0 + \vskip \dimen0 \penalty9999 - % - % Back up by the size of the box, whether we did a page break or not. - \kern -#1\mil - % - % Do not allow a page break right after this kern. - \nobreak + \vskip -\dimen0 + \penalty0\relax % this hides the above glue from \safewhatsit and \dobreak \fi } @@ -1018,8 +951,16 @@ \let\setfilename=\comment % @bye. -\outer\def\bye{\chappager\pagelabels\tracingstats=1\ptexend} +\outer\def\bye{% + \chappager\pagelabels + % possibly set in \printindex + \ifx\byeerror\relax\else\errmessage{\byeerror}\fi + \tracingstats=1\ptexend} +% set in \donoderef below, but we need to define this here so that +% conditionals balance inside the large \ifpdf ... \fi blocks below. +\newif\ifnodeseen +\nodeseenfalse \message{pdf,} % adobe `portable' document format @@ -1038,15 +979,52 @@ \newif\ifpdf \newif\ifpdfmakepagedest +% when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1 +% can be set). So we test for \relax and 0 as well as being undefined. +\ifx\pdfoutput\thisisundefined +\else + \ifx\pdfoutput\relax + \else + \ifcase\pdfoutput + \else + \pdftrue + \fi + \fi +\fi + +\newif\ifxetex +\ifx\XeTeXrevision\thisisundefined\else + \xetextrue +\fi + +\newif\ifluatex +\ifx\luatexversion\thisisundefined\else + \luatextrue + \ifnum\luatexversion>84 + \pdftrue + \fi +\fi + +\newif\ifpdforxetex +\ifpdf + \pdforxetextrue +\fi +\ifxetex + \pdforxetextrue +\fi + + + +% Whether to use non-ASCII bytes in internal link targets. Presently this +% is almost always on. +\newif\iftxiuseunicodedestname +\txiuseunicodedestnametrue + % % For LuaTeX % -\newif\iftxiuseunicodedestname -\txiuseunicodedestnamefalse % For pdfTeX etc. - -\ifx\luatexversion\thisisundefined -\else +\ifluatex % Use Unicode destination names \txiuseunicodedestnametrue % Escape PDF strings with converting UTF-16 from UTF-8 @@ -1093,13 +1071,13 @@ end end } - % The -2 in the arguments here gives all the input to TeX catcode 12 - % (other) or 10 (space), preventing undefined control sequence errors. See + % The -2 in the arguments here gives all the input to TeX catcode 12 + % (other) or 10 (space), preventing undefined control sequence errors. See % https://lists.gnu.org/archive/html/bug-texinfo/2019-08/msg00031.html % \endgroup \def\pdfescapestring#1{\directlua{PDFescstr('\luaescapestring{#1}')}} - \ifnum\luatexversion>84 + \ifpdf % For LuaTeX >= 0.85 \def\pdfdest{\pdfextension dest} \let\pdfoutput\outputmode @@ -1122,52 +1100,36 @@ \fi \fi -% when pdftex is run in dvi mode, \pdfoutput is defined (so \pdfoutput=1 -% can be set). So we test for \relax and 0 as well as being undefined. -\ifx\pdfoutput\thisisundefined -\else - \ifx\pdfoutput\relax - \else - \ifcase\pdfoutput - \else - \pdftrue - \fi - \fi -\fi - -\newif\ifpdforxetex -\pdforxetexfalse -\ifpdf - \pdforxetextrue -\fi -\ifx\XeTeXrevision\thisisundefined\else - \pdforxetextrue -\fi - % Output page labels information. % See PDF reference v.1.7 p.594, section 8.3.1. +% Page label ranges must be increasing. \ifpdf \def\pagelabels{% \def\title{0 << /P (T-) /S /D >>}% - \edef\roman{\the\romancount << /S /r >>}% - \edef\arabic{\the\arabiccount << /S /D >>}% - % - % Page label ranges must be increasing. Remove any duplicates. - % (There is a slight chance of this being wrong if e.g. there is - % a @contents but no @titlepage, etc.) % - \ifnum\romancount=0 \def\roman{}\fi - \ifnum\arabiccount=0 \def\title{}% - \else - \ifnum\romancount=\arabiccount \def\roman{}\fi - \fi - % - \ifnum\romancount<\arabiccount - \pdfcatalog{/PageLabels << /Nums [\title \roman \arabic ] >> }\relax + % support @contents at very end of document + \ifnum\contentsendcount=\pagecount + \ifnum\arabiccount<\romancount + \pdfcatalog{/PageLabels << /Nums + [\title + \the\arabiccount << /S /D >> + \the\romancount << /S /r >> + ] >> }\relax + \fi + % no contents in document + \else\ifnum\contentsendcount=0 + \pdfcatalog{/PageLabels << /Nums + [\title + \the\arabiccount << /S /D >> + ] >> }\relax \else - \pdfcatalog{/PageLabels << /Nums [\title \arabic \roman ] >> }\relax - \fi + \pdfcatalog{/PageLabels << /Nums + [\title + \the\romancount << /S /r >> + \the\contentsendcount << /S /D >> + ] >> }\relax + \fi\fi } \else \let\pagelabels\relax @@ -1176,6 +1138,8 @@ \newcount\pagecount \pagecount=0 \newcount\romancount \romancount=0 \newcount\arabiccount \arabiccount=0 +\newcount\contentsendcount \contentsendcount=0 + \ifpdf \let\ptxadvancepageno\advancepageno \def\advancepageno{% @@ -1188,7 +1152,7 @@ % for display in the outlines, and in other places. Thus, we have to % double any backslashes. Otherwise, a name like "\node" will be % interpreted as a newline (\n), followed by o, d, e. Not good. -% +% % See http://www.ntg.nl/pipermail/ntg-pdftex/2004-July/000654.html and % related messages. The final outcome is that it is up to the TeX user % to double the backslashes and otherwise make the string valid, so @@ -1222,54 +1186,90 @@ be supported due to the design of the PDF format; use regular TeX (DVI output) for that.)} +% definitions for pdftex or luatex with pdf output \ifpdf + % Strings in PDF outlines can either be ASCII, or encoded in UTF-16BE + % with BOM. Unfortunately there is no simple way with pdftex to output + % UTF-16, so we have to do some quite convoluted expansion games if we + % find the string contains a non-ASCII codepoint if we want these to + % display correctly. We generated the UTF-16 sequences in + % \DeclareUnicodeCharacter and we access them here. + % + \def\defpdfoutlinetextunicode#1{% + \def\pdfoutlinetext{#1}% + % + % Make UTF-8 sequences expand to UTF-16 definitions. + \passthroughcharsfalse \utfbytespdftrue + \utfviiidefinedwarningfalse + % + % Completely expand, eliminating any control sequences such as \code, + % leaving only possibly \utfbytes. + \let\utfbytes\relax + \pdfaccentliterals + \xdef\pdfoutlinetextchecked{#1}% + \checkutfbytes + }% + % Check if \utfbytes occurs in expansion. + \def\checkutfbytes{% + \expandafter\checkutfbytesz\pdfoutlinetextchecked\utfbytes\finish + }% + \def\checkutfbytesz#1\utfbytes#2\finish{% + \def\after{#2}% + \ifx\after\empty + % No further action needed. Output ASCII string as-is, as converting + % to UTF-16 is somewhat slow (and uses more space). + \global\let\pdfoutlinetext\pdfoutlinetextchecked + \else + \passthroughcharstrue % pass UTF-8 sequences unaltered + \xdef\pdfoutlinetext{\pdfoutlinetext}% + \expandafter\expandutfsixteen\expandafter{\pdfoutlinetext}\pdfoutlinetext + \fi + }% % - % Color manipulation macros using ideas from pdfcolor.tex, - % except using rgb instead of cmyk; the latter is said to render as a - % very dark gray on-screen and a very dark halftone in print, instead - % of actual black. The dark red here is dark enough to print on paper as - % nearly black, but still distinguishable for online viewing. We use - % black by default, though. - \def\rgbDarkRed{0.50 0.09 0.12} - \def\rgbBlack{0 0 0} - % - % rg sets the color for filling (usual text, etc.); - % RG sets the color for stroking (thin rules, e.g., normal _'s). - \def\pdfsetcolor#1{\pdfliteral{#1 rg #1 RG}} + \catcode2=1 % begin-group character + \catcode3=2 % end-group character % - % Set color, and create a mark which defines \thiscolor accordingly, - % so that \makeheadline knows which color to restore. - \def\setcolor#1{% - \xdef\currentcolordefs{\gdef\noexpand\thiscolor{#1}}% - \domark - \pdfsetcolor{#1}% - } + % argument should be pure UTF-8 with no control sequences. convert to + % UTF-16BE by inserting null bytes before bytes < 128 and expanding + % UTF-8 multibyte sequences to saved UTF-16BE sequences. + \def\expandutfsixteen#1#2{% + \bgroup \asciitounicode + \passthroughcharsfalse + \let\utfbytes\asis + % + % for Byte Order Mark (BOM) + \catcode"FE=12 + \catcode"FF=12 + % + % we want to treat { and } in #1 as any other ASCII bytes. however, + % we need grouping characters for \scantokens and definitions/assignments, + % so define alternative grouping characters using control characters + % that are unlikely to occur. + % this does not affect 0x02 or 0x03 bytes arising from expansion as + % these are tokens with different catcodes. + \catcode"02=1 % begin-group character + \catcode"03=2 % end-group character + % + \expandafter\xdef\expandafter#2\scantokens{% + ^^02^^fe^^ff#1^^03}% + % NB we need \scantokens to provide both the open and close group tokens + % for \xdef otherwise there is an e-TeX error "File ended while + % scanning definition of..." + % NB \scantokens is a e-TeX command which is assumed to be provided by + % pdfTeX. + % + \egroup + }% % - \def\maincolor{\rgbBlack} - \pdfsetcolor{\maincolor} - \edef\thiscolor{\maincolor} - \def\currentcolordefs{} + \catcode2=12 \catcode3=12 % defaults % - \def\makefootline{% - \baselineskip24pt - \line{\pdfsetcolor{\maincolor}\the\footline}% - } + % Color support % - \def\makeheadline{% - \vbox to 0pt{% - \vskip-22.5pt - \line{% - \vbox to8.5pt{}% - % Extract \thiscolor definition from the marks. - \getcolormarks - % Typeset the headline with \maincolor, then restore the color. - \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}% - }% - \vss - }% - \nointerlineskip - } + % rg sets the color for filling (usual text, etc.); + % RG sets the color for stroking (thin rules, e.g., normal _'s). + \def\pdfsetcolor#1{\pdfliteral{#1 rg #1 RG}} % + % PDF outline support % \pdfcatalog{/PageMode /UseOutlines} % @@ -1366,18 +1366,15 @@ \def\pdfoutlinetext{#1}% \else \ifx \declaredencoding \utfeight - \ifx\luatexversion\thisisundefined - % For pdfTeX with UTF-8. - % TODO: the PDF format can use UTF-16 in bookmark strings, - % but the code for this isn't done yet. - % Use ASCII approximations. - \passthroughcharsfalse - \def\pdfoutlinetext{#1}% - \else + \ifluatex % For LuaTeX with UTF-8. % Pass through Unicode characters for title texts. \passthroughcharstrue - \def\pdfoutlinetext{#1}% + \pdfaccentliterals + \xdef\pdfoutlinetext{#1}% + \else + % For pdfTeX with UTF-8. + \defpdfoutlinetextunicode{#1}% \fi \else % For non-Latin-1 or non-UTF-8 encodings. @@ -1396,14 +1393,6 @@ \safewhatsit{\pdfdest name{\pdfdestname} xyz}% } % - % used to mark target names; must be expandable. - \def\pdfmkpgn#1{#1} - % - % by default, use black for everything. - \def\urlcolor{\rgbBlack} - \def\linkcolor{\rgbBlack} - \def\endlink{\setcolor{\maincolor}\pdfendlink} - % % Adding outlines to PDF; macros for calculating structure of outlines % come from Petr Olsak \def\expnumber#1{\expandafter\ifx\csname#1\endcsname\relax 0% @@ -1429,7 +1418,7 @@ \def\pdfdestname{#4}% \fi % - \pdfoutline goto name{\pdfmkpgn{\pdfdestname}}#2{\pdfoutlinetext}% + \pdfoutline goto name{\pdfdestname}#2{\pdfoutlinetext}% } % \def\pdfmakeoutlines{% @@ -1440,15 +1429,18 @@ \def\thischapnum{##2}% \def\thissecnum{0}% \def\thissubsecnum{0}% + \def\indexlastsec{chap\thischapnum}% }% \def\numsecentry##1##2##3##4{% \advancenumber{chap\thischapnum}% \def\thissecnum{##2}% \def\thissubsecnum{0}% + \def\indexlastsec{sec\thissecnum}% }% \def\numsubsecentry##1##2##3##4{% \advancenumber{sec\thissecnum}% \def\thissubsecnum{##2}% + \def\indexlastsec{subsec\thissecnum}% }% \def\numsubsubsecentry##1##2##3##4{% \advancenumber{subsec\thissubsecnum}% @@ -1456,7 +1448,13 @@ \def\thischapnum{0}% \def\thissecnum{0}% \def\thissubsecnum{0}% + \let\indexlastsec\empty % + % Index initials are subsidiary to whatever sectioning command just + % occurred, usually @appendix or @chapter but occasionally a lower level. + \def\idxinitialentry##1##2##3##4{% + \expandafter\advancenumber\expandafter{\indexlastsec}% + }% % use \def rather than \let here because we redefine \chapentry et % al. a second time, below. \def\appentry{\numchapentry}% @@ -1467,6 +1465,7 @@ \def\unnsecentry{\numsecentry}% \def\unnsubsecentry{\numsubsecentry}% \def\unnsubsubsecentry{\numsubsubsecentry}% + % \readdatafile{toc}% % % Read toc second time, this time actually producing the outlines. @@ -1476,7 +1475,7 @@ % We use the node names as the destinations. % % Currently we prefix the section name with the section number - % for chapter and appendix headings only in order to avoid too much + % for chapter and appendix headings only in order to avoid too much % horizontal space being required in the PDF viewer. \def\numchapentry##1##2##3##4{% \dopdfoutline{##2 ##1}{count-\expnumber{chap##2}}{##3}{##4}}% @@ -1488,28 +1487,23 @@ \dopdfoutline{##1}{count-\expnumber{subsec##2}}{##3}{##4}}% \def\numsubsubsecentry##1##2##3##4{% count is always zero \dopdfoutline{##1}{}{##3}{##4}}% - % - % PDF outlines are displayed using system fonts, instead of - % document fonts. Therefore we cannot use special characters, - % since the encoding is unknown. For example, the eogonek from - % Latin 2 (0xea) gets translated to a | character. Info from - % Staszek Wawrykiewicz, 19 Jan 2004 04:09:24 +0100. - % - % TODO this right, we have to translate 8-bit characters to - % their "best" equivalent, based on the @documentencoding. Too - % much work for too little return. Just use the ASCII equivalents - % we use for the index sort strings. - % - \indexnofonts + \def\idxinitialentry##1##2##3##4{% + \dopdfoutline{##1}{}{idx.##1.##2}{##4}}% + % + \ifnodeseen\else \dopdfoutlinecontents \fi % for @contents at beginning \setupdatafile % We can have normal brace characters in the PDF outlines, unlike % Texinfo index files. So set that up. \def\{{\lbracecharliteral}% \def\}{\rbracecharliteral}% \catcode`\\=\active \otherbackslash - \input \tocreadfilename + \input \tocreadfilename\relax + \ifnodeseen \dopdfoutlinecontents \fi % for @contents at end \endgroup } + \def\dopdfoutlinecontents{% + \expandafter\dopdfoutline\expandafter{\putwordTOC}{}{txi.CONTENTS}{}% + } {\catcode`[=1 \catcode`]=2 \catcode`{=\other \catcode`}=\other \gdef\lbracecharliteral[{]% @@ -1535,54 +1529,16 @@ \else \let \startlink \pdfstartlink \fi - % make a live url in pdf output. - \def\pdfurl#1{% - \begingroup - % it seems we really need yet another set of dummies; have not - % tried to figure out what each command should do in the context - % of @url. for now, just make @/ a no-op, that's the only one - % people have actually reported a problem with. - % - \normalturnoffactive - \def\@{@}% - \let\/=\empty - \makevalueexpandable - % do we want to go so far as to use \indexnofonts instead of just - % special-casing \var here? - \def\var##1{##1}% - % - \leavevmode\setcolor{\urlcolor}% - \startlink attr{/Border [0 0 0]}% - user{/Subtype /Link /A << /S /URI /URI (#1) >>}% - \endgroup} - % \pdfgettoks - Surround page numbers in #1 with @pdflink. #1 may - % be a simple number, or a list of numbers in the case of an index - % entry. - \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} - \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} - \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} - \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} - \def\maketoks{% - \expandafter\poptoks\the\toksA|ENDTOKS|\relax - \ifx\first0\adn0 - \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 - \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 - \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 - \else - \ifnum0=\countA\else\makelink\fi - \ifx\first.\let\next=\done\else - \let\next=\maketoks - \addtokens{\toksB}{\the\toksD} - \ifx\first,\addtokens{\toksB}{\space}\fi - \fi - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi - \next} - \def\makelink{\addtokens{\toksB}% - {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} - \def\pdflink#1{% - \startlink attr{/Border [0 0 0]} goto name{\pdfmkpgn{#1}} - \setcolor{\linkcolor}#1\endlink} - \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} + \def\pdfmakeurl#1{% + \startlink attr{/Border [0 0 0]}% + user{/Subtype /Link /A << /S /URI /URI (#1) >>}% + }% + \def\endlink{\setcolor{\maincolor}\pdfendlink} + % + \def\pdflink#1{\pdflinkpage{#1}{#1}}% + \def\pdflinkpage#1#2{% + \startlink attr{/Border [0 0 0]} goto name{#1} + \setcolor{\linkcolor}#2\endlink} \else % non-pdf mode \let\pdfmkdest = \gobble @@ -1591,13 +1547,12 @@ \let\setcolor = \gobble \let\pdfsetcolor = \gobble \let\pdfmakeoutlines = \relax -\fi % \ifx\pdfoutput +\fi % % For XeTeX % -\ifx\XeTeXrevision\thisisundefined -\else +\ifxetex % % XeTeX version check % @@ -1623,45 +1578,8 @@ \fi % % Color support - % - \def\rgbDarkRed{0.50 0.09 0.12} - \def\rgbBlack{0 0 0} - % \def\pdfsetcolor#1{\special{pdf:scolor [#1]}} % - % Set color, and create a mark which defines \thiscolor accordingly, - % so that \makeheadline knows which color to restore. - \def\setcolor#1{% - \xdef\currentcolordefs{\gdef\noexpand\thiscolor{#1}}% - \domark - \pdfsetcolor{#1}% - } - % - \def\maincolor{\rgbBlack} - \pdfsetcolor{\maincolor} - \edef\thiscolor{\maincolor} - \def\currentcolordefs{} - % - \def\makefootline{% - \baselineskip24pt - \line{\pdfsetcolor{\maincolor}\the\footline}% - } - % - \def\makeheadline{% - \vbox to 0pt{% - \vskip-22.5pt - \line{% - \vbox to8.5pt{}% - % Extract \thiscolor definition from the marks. - \getcolormarks - % Typeset the headline with \maincolor, then restore the color. - \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}% - }% - \vss - }% - \nointerlineskip - } - % % PDF outline support % % Emulate pdfTeX primitive @@ -1699,11 +1617,6 @@ \safewhatsit{\pdfdest name{\pdfdestname} xyz}% } % - % by default, use black for everything. - \def\urlcolor{\rgbBlack} - \def\linkcolor{\rgbBlack} - \def\endlink{\setcolor{\maincolor}\pdfendlink} - % \def\dopdfoutline#1#2#3#4{% \setpdfoutlinetext{#1} \setpdfdestname{#3} @@ -1717,24 +1630,30 @@ % \def\pdfmakeoutlines{% \begingroup - % % For XeTeX, counts of subentries are not necessary. % Therefore, we read toc only once. % % We use node names as destinations. % % Currently we prefix the section name with the section number - % for chapter and appendix headings only in order to avoid too much + % for chapter and appendix headings only in order to avoid too much % horizontal space being required in the PDF viewer. \def\partentry##1##2##3##4{}% ignore parts in the outlines \def\numchapentry##1##2##3##4{% - \dopdfoutline{##2 ##1}{1}{##3}{##4}}% + \dopdfoutline{##2 ##1}{1}{##3}{##4}% + \def\indexseclevel{2}}% \def\numsecentry##1##2##3##4{% - \dopdfoutline{##1}{2}{##3}{##4}}% + \dopdfoutline{##1}{2}{##3}{##4}% + \def\indexseclevel{3}}% \def\numsubsecentry##1##2##3##4{% - \dopdfoutline{##1}{3}{##3}{##4}}% + \dopdfoutline{##1}{3}{##3}{##4}% + \def\indexseclevel{4}}% \def\numsubsubsecentry##1##2##3##4{% - \dopdfoutline{##1}{4}{##3}{##4}}% + \dopdfoutline{##1}{4}{##3}{##4}% + \def\indexseclevel{5}}% + % + \def\idxinitialentry##1##2##3##4{% + \dopdfoutline{##1}{\indexseclevel}{idx.##1.##2}{##4}}% % \let\appentry\numchapentry% \let\appsecentry\numsecentry% @@ -1750,15 +1669,25 @@ % Therefore, the encoding and the language may not be considered. % \indexnofonts + \pdfaccentliterals + \ifnodeseen\else \dopdfoutlinecontents \fi % for @contents at beginning + % \setupdatafile % We can have normal brace characters in the PDF outlines, unlike % Texinfo index files. So set that up. \def\{{\lbracecharliteral}% \def\}{\rbracecharliteral}% \catcode`\\=\active \otherbackslash - \input \tocreadfilename + \xetexpreauxfile + \input \tocreadfilename\relax + \xetexpostauxfile + \ifnodeseen \dopdfoutlinecontents \fi % for @contents at end \endgroup } + \def\dopdfoutlinecontents{% + \expandafter\dopdfoutline\expandafter + {\putwordTOC}{1}{txi.CONTENTS}{txi.CONTENTS}% + } {\catcode`[=1 \catcode`]=2 \catcode`{=\other \catcode`}=\other \gdef\lbracecharliteral[{]% @@ -1771,7 +1700,7 @@ % However, due to a UTF-16 conversion issue of xdvipdfmx 20150315, % ``\special{pdf:dest ...}'' cannot handle non-ASCII strings. % It is fixed by xdvipdfmx 20160106 (TeX Live SVN r39753). -% + % \def\skipspaces#1{\def\PP{#1}\def\D{|}% \ifx\PP\D\let\nextsp\relax \else\let\nextsp\skipspaces @@ -1786,54 +1715,17 @@ \edef\temp{#1}% \expandafter\skipspaces\temp|\relax } - % make a live url in pdf output. - \def\pdfurl#1{% - \begingroup - % it seems we really need yet another set of dummies; have not - % tried to figure out what each command should do in the context - % of @url. for now, just make @/ a no-op, that's the only one - % people have actually reported a problem with. - % - \normalturnoffactive - \def\@{@}% - \let\/=\empty - \makevalueexpandable - % do we want to go so far as to use \indexnofonts instead of just - % special-casing \var here? - \def\var##1{##1}% - % - \leavevmode\setcolor{\urlcolor}% - \special{pdf:bann << /Border [0 0 0] - /Subtype /Link /A << /S /URI /URI (#1) >> >>}% - \endgroup} + \def\pdfmakeurl#1{% + \special{pdf:bann << /Border [0 0 0] + /Subtype /Link /A << /S /URI /URI (#1) >> >>}% + } \def\endlink{\setcolor{\maincolor}\special{pdf:eann}} - \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} - \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} - \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} - \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} - \def\maketoks{% - \expandafter\poptoks\the\toksA|ENDTOKS|\relax - \ifx\first0\adn0 - \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 - \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 - \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 - \else - \ifnum0=\countA\else\makelink\fi - \ifx\first.\let\next=\done\else - \let\next=\maketoks - \addtokens{\toksB}{\the\toksD} - \ifx\first,\addtokens{\toksB}{\space}\fi - \fi - \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi - \next} - \def\makelink{\addtokens{\toksB}% - {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} - \def\pdflink#1{% + \def\pdflink#1{\pdflinkpage{#1}{#1}}% + \def\pdflinkpage#1#2{% \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A << /S /GoTo /D (#1) >> >>}% - \setcolor{\linkcolor}#1\endlink} - \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} -% + \setcolor{\linkcolor}#2\endlink} + % % % @image support % @@ -1890,6 +1782,164 @@ } \fi +% common definitions and code for pdftex, luatex and xetex +\ifpdforxetex + % The dark red here is dark enough to print on paper as + % nearly black, but still distinguishable for online viewing. We use + % black by default, though. + \def\rgbDarkRed{0.50 0.09 0.12} + \def\rgbBlack{0 0 0} + % + % Set color, and create a mark which defines \thiscolor accordingly, + % so that \makeheadline knows which color to restore. + \def\curcolor{0 0 0}% + \def\setcolor#1{% + \ifx#1\curcolor\else + \xdef\currentcolordefs{\gdef\noexpand\thiscolor{#1}}% + \domark + \pdfsetcolor{#1}% + \xdef\curcolor{#1}% + \fi + } + % + \let\maincolor\rgbBlack + \pdfsetcolor{\maincolor} + \edef\thiscolor{\maincolor} + \def\currentcolordefs{} + % + \def\makefootline{% + \baselineskip24pt + \line{\pdfsetcolor{\maincolor}\the\footline}% + } + % + \def\makeheadline{% + \vbox to 0pt{% + \vskip-22.5pt + \line{% + \vbox to8.5pt{}% + % Extract \thiscolor definition from the marks. + \getcolormarks + % Typeset the headline with \maincolor, then restore the color. + \pdfsetcolor{\maincolor}\the\headline\pdfsetcolor{\thiscolor}% + }% + \vss + }% + \nointerlineskip + } + % + % by default, use black for everything. + \def\urlcolor{\rgbBlack} + \let\linkcolor\rgbBlack + % + % make a live url in pdf output. + \def\pdfurl#1{% + \begingroup + % it seems we really need yet another set of dummies; have not + % tried to figure out what each command should do in the context + % of @url. for now, just make @/ a no-op, that's the only one + % people have actually reported a problem with. + % + \normalturnoffactive + \def\@{@}% + \let\/=\empty + \makevalueexpandable + % do we want to go so far as to use \indexnofonts instead of just + % special-casing \var here? + \def\var##1{##1}% + % + \leavevmode\setcolor{\urlcolor}% + \pdfmakeurl{#1}% + \endgroup} + % + % \pdfgettoks - Surround page numbers in #1 with @pdflink. #1 may + % be a simple number, or a list of numbers in the case of an index + % entry. + \def\pdfgettoks#1.{\setbox\boxA=\hbox{\toksA={#1.}\toksB={}\maketoks}} + \def\addtokens#1#2{\edef\addtoks{\noexpand#1={\the#1#2}}\addtoks} + \def\adn#1{\addtokens{\toksC}{#1}\global\countA=1\let\next=\maketoks} + \def\poptoks#1#2|ENDTOKS|{\let\first=#1\toksD={#1}\toksA={#2}} + \def\maketoks{% + \expandafter\poptoks\the\toksA|ENDTOKS|\relax + \ifx\first0\adn0 + \else\ifx\first1\adn1 \else\ifx\first2\adn2 \else\ifx\first3\adn3 + \else\ifx\first4\adn4 \else\ifx\first5\adn5 \else\ifx\first6\adn6 + \else\ifx\first7\adn7 \else\ifx\first8\adn8 \else\ifx\first9\adn9 + \else + \ifnum0=\countA\else\makelink\fi + \ifx\first.\let\next=\done\else + \let\next=\maketoks + \addtokens{\toksB}{\the\toksD} + \ifx\first,\addtokens{\toksB}{\space}\fi + \fi + \fi\fi\fi\fi\fi\fi\fi\fi\fi\fi + \next} + \def\makelink{\addtokens{\toksB}% + {\noexpand\pdflink{\the\toksC}}\toksC={}\global\countA=0} + \def\done{\edef\st{\global\noexpand\toksA={\the\toksB}}\st} +\fi + +\ifpdforxetex + % for pdftex. + {\catcode`^^cc=13 + \gdef\pdfaccentliteralsutfviii{% + % For PDF outline only. Unicode combining accents follow the + % character they modify. Note we need at least the first byte + % of the UTF-8 sequences to have an active catcode to allow the + % definitions to do their magic. + \def\"##1{##1^^cc^^88}% U+0308 + \def\'##1{##1^^cc^^81}% U+0301 + \def\,##1{##1^^cc^^a7}% U+0327 + \def\=##1{##1^^cc^^85}% U+0305 + \def\^##1{##1^^cc^^82}% U+0302 + \def\`##1{##1^^cc^^80}% U+0300 + \def\~##1{##1^^cc^^83}% U+0303 + \def\dotaccent##1{##1^^cc^^87}% U+0307 + \def\H##1{##1^^cc^^8b}% U+030B + \def\ogonek##1{##1^^cc^^a8}% U+0328 + \def\ringaccent##1{##1^^cc^^8a}% U+030A + \def\u##1{##1^^cc^^8c}% U+0306 + \def\ubaraccent##1{##1^^cc^^b1}% U+0331 + \def\udotaccent##1{##1^^cc^^a3}% U+0323 + \def\v##1{##1^^cc^^8c}% U+030C + % this definition of @tieaccent will only work with exactly two characters + % in argument as we need to insert the combining character between them. + \def\tieaccent##1{\tieaccentz##1}% + \def\tieaccentz##1##2{##1^^cd^^a1##2} % U+0361 + }}% + % + % for xetex and luatex, which both support extended ^^^^ escapes and + % process the Unicode codepoint as a single token. + \gdef\pdfaccentliteralsnative{% + \def\"##1{##1^^^^0308}% + \def\'##1{##1^^^^0301}% + \def\,##1{##1^^^^0327}% + \def\=##1{##1^^^^0305}% + \def\^##1{##1^^^^0302}% + \def\`##1{##1^^^^0300}% + \def\~##1{##1^^^^0303}% + \def\dotaccent##1{##1^^^^0307}% + \def\H##1{##1^^^^030b}% + \def\ogonek##1{##1^^^^0328}% + \def\ringaccent##1{##1^^^^030a}% + \def\u##1{##1^^^^0306}% + \def\ubaraccent##1{##1^^^^0331}% + \def\udotaccent##1{##1^^^^0323}% + \def\v##1{##1^^^^030c}% + \def\tieaccent##1{\tieaccentz##1}% + \def\tieaccentz##1##2{##1^^^^0361##2} % U+0361 + }% + % + % use the appropriate definition + \ifluatex + \let\pdfaccentliterals\pdfaccentliteralsnative + \else + \ifxetex + \let\pdfaccentliterals\pdfaccentliteralsnative + \else + \let\pdfaccentliterals\pdfaccentliteralsutfviii + \fi + \fi +\fi % \message{fonts,} @@ -2176,6 +2226,11 @@ \pdffontattr#1{/ToUnicode \the\pdflastobj\space 0 R}% }% \fi\fi +% +% This is what gets called when #5 of \setfont is empty. +\let\cmap\gobble +% +% (end of cmaps) % Set the font macro #1 to the font named \fontprefix#2. @@ -2191,11 +2246,10 @@ \def\setfont#1#2#3#4#5{% \font#1=\fontprefix#2#3 scaled #4 \csname cmap#5\endcsname#1% + \ifx#2\ttshape\hyphenchar#1=-1 \fi + \ifx#2\ttbshape\hyphenchar#1=-1 \fi + \ifx#2\ttslshape\hyphenchar#1=-1 \fi } -% This is what gets called when #5 of \setfont is empty. -\let\cmap\gobble -% -% (end of cmaps) % Use cm as the default font prefix. % To specify the font prefix, you must define \fontprefix @@ -2558,7 +2612,7 @@ \def\it{\fam=\itfam \setfontstyle{it}} \def\sl{\fam=\slfam \setfontstyle{sl}} \def\bf{\fam=\bffam \setfontstyle{bf}}\def\bfstylename{bf} -\def\tt{\fam=\ttfam \setfontstyle{tt}}\def\ttstylename{tt} +\def\tt{\fam=\ttfam \setfontstyle{tt}} % Texinfo sort of supports the sans serif font style, which plain TeX does not. % So we set up a \sf. @@ -2586,34 +2640,30 @@ \scriptfont\sffam=\sevensf } -% -% The font-changing commands (all called \...fonts) redefine the meanings -% of \STYLEfont, instead of just \STYLE. We do this because \STYLE needs -% to also set the current \fam for math mode. Our \STYLE (e.g., \rm) -% commands hardwire \STYLEfont to set the current font. -% -% The fonts used for \ifont are for "math italics" (\itfont is for italics -% in regular text). \syfont is also used in math mode only. -% -% Each font-changing command also sets the names \lsize (one size lower) -% and \lllsize (three sizes lower). These relative commands are used -% in, e.g., the LaTeX logo and acronyms. -% -% This all needs generalizing, badly. + +% \defineassignfonts{SIZE} - +% Define sequence \assignfontsSIZE, which switches between font sizes +% by redefining the meanings of \STYLEfont. (Just \STYLE additionally sets +% the current \fam for math mode.) % +\def\defineassignfonts#1{% + \expandafter\edef\csname assignfonts#1\endcsname{% + \let\noexpand\rmfont\csname #1rm\endcsname + \let\noexpand\itfont\csname #1it\endcsname + \let\noexpand\slfont\csname #1sl\endcsname + \let\noexpand\bffont\csname #1bf\endcsname + \let\noexpand\ttfont\csname #1tt\endcsname + \let\noexpand\smallcaps\csname #1sc\endcsname + \let\noexpand\sffont \csname #1sf\endcsname + \let\noexpand\ifont \csname #1i\endcsname + \let\noexpand\syfont \csname #1sy\endcsname + \let\noexpand\ttslfont\csname #1ttsl\endcsname + } +} \def\assignfonts#1{% - \expandafter\let\expandafter\rmfont\csname #1rm\endcsname - \expandafter\let\expandafter\itfont\csname #1it\endcsname - \expandafter\let\expandafter\slfont\csname #1sl\endcsname - \expandafter\let\expandafter\bffont\csname #1bf\endcsname - \expandafter\let\expandafter\ttfont\csname #1tt\endcsname - \expandafter\let\expandafter\smallcaps\csname #1sc\endcsname - \expandafter\let\expandafter\sffont \csname #1sf\endcsname - \expandafter\let\expandafter\ifont \csname #1i\endcsname - \expandafter\let\expandafter\syfont \csname #1sy\endcsname - \expandafter\let\expandafter\ttslfont\csname #1ttsl\endcsname + \csname assignfonts#1\endcsname } \newif\ifrmisbold @@ -2637,12 +2687,21 @@ \csname\curfontstyle\endcsname }% +% Define the font-changing commands (all called \...fonts). +% Each font-changing command also sets the names \lsize (one size lower) +% and \lllsize (three sizes lower). These relative commands are used +% in, e.g., the LaTeX logo and acronyms. +% +% Note: The fonts used for \ifont are for "math italics" (\itfont is for +% italics in regular text). \syfont is also used in math mode only. +% \def\definefontsetatsize#1#2#3#4#5{% + \defineassignfonts{#1}% \expandafter\def\csname #1fonts\endcsname{% \def\curfontsize{#1}% \def\lsize{#2}\def\lllsize{#3}% \csname rmisbold#5\endcsname - \assignfonts{#1}% + \csname assignfonts#1\endcsname \resetmathfonts \setleading{#4}% }} @@ -2687,9 +2746,22 @@ % Check if we are currently using a typewriter font. Since all the % Computer Modern typewriter fonts have zero interword stretch (and % shrink), and it is reasonable to expect all typewriter fonts to have -% this property, we can check that font parameter. -% -\def\ifmonospace{\ifdim\fontdimen3\font=0pt } +% this property, we can check that font parameter. #1 is what to +% print if we are indeed using \tt; #2 is what to print otherwise. +\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi} + +% Same as above, but check for italic font. Actually this also catches +% non-italic slanted fonts since it is impossible to distinguish them from +% italic fonts. But since this is only used by $ and it uses \sl anyway +% this is not a problem. +\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi} + + +% Check if internal flag is clear, i.e. has not been @set. +\def\ifflagclear#1#2#3{% + \expandafter\ifx\csname SET#1\endcsname\relax + #2\else#3\fi +} { \catcode`\'=\active @@ -2698,45 +2770,37 @@ \gdef\setcodequotes{\let`\codequoteleft \let'\codequoteright} \gdef\setregularquotes{\let`\lq \let'\rq} } +\setregularquotes -% Allow an option to not use regular directed right quote/apostrophe -% (char 0x27), but instead the undirected quote from cmtt (char 0x0d). -% The undirected quote is ugly, so don't make it the default, but it -% works for pasting with more pdf viewers (at least evince), the -% lilypond developers report. xpdf does work with the regular 0x27. +% output for ' in @code +% in tt font hex 0D (undirected) or 27 (curly right quote) % \def\codequoteright{% - \ifmonospace - \expandafter\ifx\csname SETtxicodequoteundirected\endcsname\relax - \expandafter\ifx\csname SETcodequoteundirected\endcsname\relax - '% - \else \char'15 \fi - \else \char'15 \fi - \else - '% - \fi + \ifusingtt + {\ifflagclear{txicodequoteundirected}% + {\ifflagclear{codequoteundirected}% + {'}% + {\char"0D }}% + {\char"0D }}% + {'}% } -% -% and a similar option for the left quote char vs. a grave accent. -% Modern fonts display ASCII 0x60 as a grave accent, so some people like -% the code environments to do likewise. + +% output for ` in @code +% in tt font hex 12 (grave accent) or 60 (curly left quote) +% \relax disables Spanish ligatures ?` and !` of \tt font. % \def\codequoteleft{% - \ifmonospace - \expandafter\ifx\csname SETtxicodequotebacktick\endcsname\relax - \expandafter\ifx\csname SETcodequotebacktick\endcsname\relax - % [Knuth] pp. 380,381,391 - % \relax disables Spanish ligatures ?` and !` of \tt font. - \relax`% - \else \char'22 \fi - \else \char'22 \fi - \else - \relax`% - \fi + \ifusingtt + {\ifflagclear{txicodequotebacktick}% + {\ifflagclear{codequotebacktick}% + {\relax`}% + {\char"12 }}% + {\char"12 }}% + {\relax`}% } % Commands to set the quote options. -% +% \parseargdef\codequoteundirected{% \def\temp{#1}% \ifx\temp\onword @@ -2750,7 +2814,7 @@ \errmessage{Unknown @codequoteundirected value `\temp', must be on|off}% \fi\fi } -% + \parseargdef\codequotebacktick{% \def\temp{#1}% \ifx\temp\onword @@ -2765,6 +2829,11 @@ \fi\fi } +% Turn them on by default +\let\SETtxicodequoteundirected = t +\let\SETtxicodequotebacktick = t + + % [Knuth] pp. 380,381,391, disable Spanish ligatures ?` and !` of \tt font. \def\noligaturesquoteleft{\relax\lq} @@ -2777,17 +2846,18 @@ % If we are in a monospaced environment, however, 1) always use \ttsl, % and 2) do not add an italic correction. \def\dosmartslant#1#2{% - \ifusingtt + \ifusingtt {{\ttsl #2}\let\next=\relax}% - {\def\next{{#1#2}\futurelet\next\smartitaliccorrection}}% + {\def\next{{#1#2}\smartitaliccorrection}}% \next } \def\smartslanted{\dosmartslant\sl} \def\smartitalic{\dosmartslant\it} -% Output an italic correction unless \next (presumed to be the following -% character) is such as not to need one. -\def\smartitaliccorrection{% +% Output an italic correction unless the following character is such as +% not to need one. +\def\smartitaliccorrection{\futurelet\next\smartitaliccorrectionx} +\def\smartitaliccorrectionx{% \ifx\next,% \else\ifx\next-% \else\ifx\next.% @@ -2798,43 +2868,52 @@ \aftersmartic } -% Unconditional use \ttsl, and no ic. @var is set to this for defuns. -\def\ttslanted#1{{\ttsl #1}} - -% @cite is like \smartslanted except unconditionally use \sl. We never want -% ttsl for book titles, do we? -\def\cite#1{{\sl #1}\futurelet\next\smartitaliccorrection} +% @cite unconditionally uses \sl with \smartitaliccorrection. +\def\cite#1{{\sl #1}\smartitaliccorrection} +% By default, use ttsl font for @var when used in code context. +% To unconditionally use \sl for @var, @clear txicodevaristt. This +% gives consistency for parameter names whether they are in @def, +% @table @code or a regular paragraph. \def\aftersmartic{} \def\var#1{% \let\saveaftersmartic = \aftersmartic \def\aftersmartic{\null\let\aftersmartic=\saveaftersmartic}% - \smartslanted{#1}% + % The \null is to reset \spacefactor. + % + \ifflagclear{txicodevaristt}% + {\def\varnext{{{\sl #1}}\smartitaliccorrection}}% + {\def\varnext{\smartslanted{#1}}}% + \varnext } +\def\SETtxicodevaristt{}% @set txicodevaristt + \let\i=\smartitalic \let\slanted=\smartslanted \let\dfn=\smartslanted \let\emph=\smartitalic -% Explicit font changes: @r, @sc, undocumented @ii. -\def\r#1{{\rm #1}} % roman font +% @r for roman font, used for code comment +\def\r#1{{% + \usenormaldash % get --, --- ligatures even if in @code + \defcharsdefault % in case on def line + \rm #1}} +{\catcode`-=\active \gdef\usenormaldash{\let-\normaldash}} + +% @sc, undocumented @ii. \def\sc#1{{\smallcaps#1}} % smallcaps font \def\ii#1{{\it #1}} % italic font % @b, explicit bold. Also @strong. -\def\b#1{{\bf #1}} +\def\b#1{{\bf \defcharsdefault #1}} \let\strong=\b % @sansserif, explicit sans. \def\sansserif#1{{\sf #1}} -% We can't just use \exhyphenpenalty, because that only has effect at -% the end of a paragraph. Restore normal hyphenation at the end of the -% group within which \nohyphenation is presumably called. -% -\def\nohyphenation{\hyphenchar\font = -1 \aftergroup\restorehyphenation} -\def\restorehyphenation{\hyphenchar\font = `- } +\newif\iffrenchspacing +\frenchspacingfalse % Set sfcode to normal for the chars that usually have another value. % Can't use plain's \frenchspacing because it uses the `\x notation, and @@ -2842,21 +2921,45 @@ % \catcode`@=11 \def\plainfrenchspacing{% - \sfcode`\.=\@m \sfcode`\?=\@m \sfcode`\!=\@m - \sfcode`\:=\@m \sfcode`\;=\@m \sfcode`\,=\@m - \def\endofsentencespacefactor{1000}% for @. and friends + \iffrenchspacing\else + \frenchspacingtrue + \sfcode`\.=\@m \sfcode`\?=\@m \sfcode`\!=\@m + \sfcode`\:=\@m \sfcode`\;=\@m \sfcode`\,=\@m + \def\endofsentencespacefactor{1000}% for @. and friends + \fi } \def\plainnonfrenchspacing{% - \sfcode`\.3000\sfcode`\?3000\sfcode`\!3000 - \sfcode`\:2000\sfcode`\;1500\sfcode`\,1250 - \def\endofsentencespacefactor{3000}% for @. and friends + \iffrenchspacing + \frenchspacingfalse + \sfcode`\.3000\sfcode`\?3000\sfcode`\!3000 + \sfcode`\:2000\sfcode`\;1500\sfcode`\,1250 + \def\endofsentencespacefactor{3000}% for @. and friends + \fi } \catcode`@=\other \def\endofsentencespacefactor{3000}% default +% @frenchspacing on|off says whether to put extra space after punctuation. +% +\def\onword{on} +\def\offword{off} +% +\let\frenchspacingsetting\plainnonfrenchspacing % used in output routine +\parseargdef\frenchspacing{% + \def\temp{#1}% + \ifx\temp\onword \let\frenchspacingsetting\plainfrenchspacing + \else\ifx\temp\offword \let\frenchspacingsetting\plainnonfrenchspacing + \else + \errhelp = \EMsimple + \errmessage{Unknown @frenchspacing option `\temp', must be on|off}% + \fi\fi + \frenchspacingsetting +} + + % @t, explicit typewriter. \def\t#1{% - {\tt \plainfrenchspacing #1}% + {\tt \defcharsdefault \plainfrenchspacing #1}% \null } @@ -2877,27 +2980,29 @@ % Switch to typewriter. \tt % - % But `\ ' produces the large typewriter interword space. + % `\ ' produces the large typewriter interword space. \def\ {{\spaceskip = 0pt{} }}% % - % Turn off hyphenation. - \nohyphenation - % \plainfrenchspacing #1% }% \null % reset spacefactor to 1000 } -% We *must* turn on hyphenation at `-' and `_' in @code. -% (But see \codedashfinish below.) +% This is for LuaTeX: It is not sufficient to disable hyphenation at +% explicit dashes by setting `\hyphenchar` to -1. +\def\dashnobreak{% + \normaldash + \penalty 10000 } + +% We must turn on hyphenation at `-' and `_' in @code. % Otherwise, it is too hard to avoid overfull hboxes % in the Emacs manual, the Library manual, etc. +% We explicitly allow hyphenation at these characters +% using \discretionary. % -% Unfortunately, TeX uses one parameter (\hyphenchar) to control -% both hyphenation at - and hyphenation within words. -% We must therefore turn them both off (\tclose does that) -% and arrange explicitly to hyphenate at a dash. -- rms. +% Hyphenation at - and hyphenation within words was turned off +% by default for the tt fonts using the \hyphenchar parameter of TeX. { \catcode`\-=\active \catcode`\_=\active \catcode`\'=\active \catcode`\`=\active @@ -2910,37 +3015,42 @@ \let-\codedash \let_\codeunder \else - \let-\normaldash + \let-\dashnobreak \let_\realunder \fi - % Given -foo (with a single dash), we do not want to allow a break - % after the hyphen. - \global\let\codedashprev=\codedash - % \codex } % \gdef\codedash{\futurelet\next\codedashfinish} \gdef\codedashfinish{% \normaldash % always output the dash character itself. - % + % % Now, output a discretionary to allow a line break, unless % (a) the next character is a -, or - % (b) the preceding character is a -. + % (b) the preceding character is a -, or + % (c) we are at the start of the string. + % In both cases (b) and (c), \codedashnobreak should be set to \codedash. + % % E.g., given --posix, we do not want to allow a break after either -. % Given --foo-bar, we do want to allow a break between the - and the b. \ifx\next\codedash \else - \ifx\codedashprev\codedash + \ifx\codedashnobreak\codedash \else \discretionary{}{}{}\fi \fi % we need the space after the = for the case when \next itself is a % space token; it would get swallowed otherwise. As in @code{- a}. - \global\let\codedashprev= \next + \global\let\codedashnobreak= \next } } \def\normaldash{-} % -\def\codex #1{\tclose{#1}\endgroup} +\def\codex #1{\tclose{% + % Given -foo (with a single dash), we do not want to allow a break + % after the -. \codedashnobreak is set to the first character in + % @code. + \futurelet\codedashnobreak\relax + #1% +}\endgroup} \def\codeunder{% % this is all so @math{@code{var_name}+1} can work. In math mode, _ @@ -3020,25 +3130,25 @@ % For pdfTeX and LuaTeX \ifurefurlonlylink % PDF plus option to not display url, show just arg - \unhbox0 + \unhbox0 \else % PDF, normally display both arg and url for consistency, % visibility, if the pdf is eventually used to print, etc. \unhbox0\ (\urefcode{#1})% \fi \else - \ifx\XeTeXrevision\thisisundefined - \unhbox0\ (\urefcode{#1})% DVI, always show arg and url - \else + \ifxetex % For XeTeX \ifurefurlonlylink % PDF plus option to not display url, show just arg - \unhbox0 + \unhbox0 \else % PDF, normally display both arg and url for consistency, % visibility, if the pdf is eventually used to print, etc. \unhbox0\ (\urefcode{#1})% \fi + \else + \unhbox0\ (\urefcode{#1})% DVI, always show arg and url \fi \fi \else @@ -3091,10 +3201,10 @@ } } -% By default we'll break after the special characters, but some people like to -% break before the special chars, so allow that. Also allow no breaking at +% By default we'll break after the special characters, but some people like to +% break before the special chars, so allow that. Also allow no breaking at % all, for manual control. -% +% \parseargdef\urefbreakstyle{% \def\txiarg{#1}% \ifx\txiarg\wordnone @@ -3113,16 +3223,17 @@ \def\wordnone{none} % Allow a ragged right output to aid breaking long URL's. There can -% be a break at the \allowbreak with no extra glue (if the existing stretch in +% be a break at the \allowbreak with no extra glue (if the existing stretch in % the line is sufficient), a break at the \penalty with extra glue added % at the end of the line, or no break at all here. -% Changing the value of the penalty and/or the amount of stretch affects how +% Changing the value of the penalty and/or the amount of stretch affects how % preferable one choice is over the other. +% Check test cases in doc/texinfo-tex-test.texi before making any changes. \def\urefallowbreak{% \penalty0\relax - \hskip 0pt plus 2 em\relax + \hskip 0pt plus 3 em\relax \penalty1000\relax - \hskip 0pt plus -2 em\relax + \hskip 0pt plus -3 em\relax } \urefbreakstyle after @@ -3171,16 +3282,8 @@ % Default is `distinct'. \kbdinputstyle distinct -% @kbd is like @code, except that if the argument is just one @key command, -% then @kbd has no effect. -\def\kbd#1{{\def\look{#1}\expandafter\kbdsub\look??\par}} - -\def\xkey{\key} -\def\kbdsub#1#2#3\par{% - \def\one{#1}\def\three{#3}\def\threex{??}% - \ifx\one\xkey\ifx\threex\three \key{#2}% - \else{\tclose{\kbdfont\setcodequotes\look}}\fi - \else{\tclose{\kbdfont\setcodequotes\look}}\fi +\def\kbd#1{% + \tclose{\kbdfont\setcodequotes#1}% } % definition of @key that produces a lozenge. Doesn't adjust to text size. @@ -3193,14 +3296,9 @@ % \kern-0.4pt\hrule}% % \kern-.06em\raise0.4pt\hbox{\angleright}}}} -% definition of @key with no lozenge. If the current font is already -% monospace, don't change it; that way, we respect @kbdinputstyle. But -% if it isn't monospace, then use \tt. +% definition of @key with no lozenge. % -\def\key#1{{\setregularquotes - \nohyphenation - \ifmonospace\else\tt\fi - #1}\null} +\def\key#1{{\setregularquotes \tt #1}\null} % @clicksequence{File @click{} Open ...} \def\clicksequence#1{\begingroup #1\endgroup} @@ -3344,7 +3442,7 @@ % @inlinefmt{FMTNAME,PROCESSED-TEXT} and @inlineraw{FMTNAME,RAW-TEXT}. % Ignore unless FMTNAME == tex; then it is like @iftex and @tex, % except specified as a normal braced arg, so no newlines to worry about. -% +% \def\outfmtnametex{tex} % \long\def\inlinefmt#1{\doinlinefmt #1,\finish} @@ -3352,7 +3450,7 @@ \def\inlinefmtname{#1}% \ifx\inlinefmtname\outfmtnametex \ignorespaces #2\fi } -% +% % @inlinefmtifelse{FMTNAME,THEN-TEXT,ELSE-TEXT} expands THEN-TEXT if % FMTNAME is tex, else ELSE-TEXT. \long\def\inlinefmtifelse#1{\doinlinefmtifelse #1,,,\finish} @@ -3368,7 +3466,7 @@ % *right* brace they would have to use a command anyway, so they may as % well use a command to get a left brace too. We could re-use the % delimiter character idea from \verb, but it seems like overkill. -% +% \long\def\inlineraw{\tex \doinlineraw} \long\def\doinlineraw#1{\doinlinerawtwo #1,\finish} \def\doinlinerawtwo#1,#2,\finish{% @@ -3403,8 +3501,8 @@ \let\atchar=\@ % @{ @} @lbracechar{} @rbracechar{} all generate brace characters. -\def\lbracechar{{\ifmonospace\char123\else\ensuremath\lbrace\fi}} -\def\rbracechar{{\ifmonospace\char125\else\ensuremath\rbrace\fi}} +\def\lbracechar{{\ifusingtt{\char123}{\ensuremath\lbrace}}} +\def\rbracechar{{\ifusingtt{\char125}{\ensuremath\rbrace}}} \let\{=\lbracechar \let\}=\rbracechar @@ -3458,8 +3556,13 @@ % Revert to plain's \scriptsize, which is 7pt. \count255=\the\fam $\fam\count255 \scriptstyle A$% \else - % For 11pt, we can use our lllsize. - \switchtolllsize A% + \ifx\curfontsize\smallword + % For footnotes and indices + \count255=\the\fam $\fam\count255 \scriptstyle A$% + \else + % For 11pt, we can use our lllsize. + \switchtolllsize A% + \fi \fi }% \vss @@ -3467,6 +3570,7 @@ \kern-.15em \TeX } +\def\smallword{small} % Some math mode symbols. Define \ensuremath to switch into math mode % unless we are already there. Expansion tricks may not be needed here, @@ -3545,7 +3649,7 @@ % @pounds{} is a sterling sign, which Knuth put in the CM italic font. % -\def\pounds{\ifmonospace{\ecfont\char"BF}\else{\it\$}\fi} +\def\pounds{{\ifusingtt{\ecfont\char"BF}{\it\$}}} % @euro{} comes from a separate font, depending on the current style. % We use the free feym* fonts from the eurosym package by Henrik @@ -3614,6 +3718,9 @@ \def\quotedblbase{{\ecfont \char"12}} \def\quotesinglbase{{\ecfont \char"0D}} % +\def\L{{\ecfont \char"8A}} % L with stroke +\def\l{{\ecfont \char"AA}} % l with stroke +% % This positioning is not perfect (see the ogonek LaTeX package), but % we have the precomposed glyphs for the most common cases. We put the % tests to use those glyphs in the single \ogonek macro so we have fewer @@ -3645,7 +3752,7 @@ % for non-CM glyphs. That is ec* for regular text and tc* for the text % companion symbols (LaTeX TS1 encoding). Both are part of the ec % package and follow the same conventions. -% +% \def\ecfont{\etcfont{e}} \def\tcfont{\etcfont{t}} % @@ -3656,21 +3763,29 @@ % hopefully nobody will notice/care. \edef\ecsize{\csname\curfontsize ecsize\endcsname}% \edef\nominalsize{\csname\curfontsize nominalsize\endcsname}% - \ifmonospace - % typewriter: - \font\thisecfont = #1ctt\ecsize \space at \nominalsize - \else - \ifx\curfontstyle\bfstylename - % bold: - \font\thisecfont = #1cb\ifusingit{i}{x}\ecsize \space at \nominalsize - \else - % regular: - \font\thisecfont = #1c\ifusingit{ti}{rm}\ecsize \space at \nominalsize - \fi - \fi + \ifusingtt + % typewriter: + {\font\thisecfont = #1ctt\ecsize \space at \nominalsize}% + % else + {\ifx\curfontstyle\bfstylename + \etcfontbold{#1}% + \else + \ifrmisbold + \etcfontbold{#1}% + \else + % regular: + \font\thisecfont = #1c\ifusingit{ti}{rm}\ecsize \space + at \nominalsize + \fi + \fi}% \thisecfont } +\def\etcfontbold#1{% + % bold: + \font\thisecfont = #1cb\ifusingit{i}{x}\ecsize \space at \nominalsize +} + % @registeredsymbol - R in a circle. The font for the R should really % be smaller yet, but lllsize is the best we can do for now. % Adapted from the plain.tex definition of \copyright. @@ -3683,7 +3798,10 @@ % @textdegree - the normal degrees sign. % -\def\textdegree{$^\circ$} +\def\textdegree{% + \ifmmode ^\circ + \else {\tcfont \char 176}% + \fi} % Laurent Siebenmann reports \Orb undefined with: % Textures 1.7.7 (preloaded format=plain 93.10.14) (68K) 16 APR 2004 02:38 @@ -3700,11 +3818,11 @@ % only change font for tt for correct kerning and to avoid using % \ecfont unless necessary. \def\quotedblleft{% - \ifmonospace{\ecfont\char"10}\else{\char"5C}\fi + \ifusingtt{{\ecfont\char"10}}{{\char"5C}}% } \def\quotedblright{% - \ifmonospace{\ecfont\char"11}\else{\char`\"}\fi + \ifusingtt{{\ecfont\char"11}}{{\char`\"}}% } @@ -3725,17 +3843,18 @@ after the title page.}}% \def\setshortcontentsaftertitlepage{% \errmessage{@setshortcontentsaftertitlepage has been removed as a Texinfo - command; move your @shortcontents and @contents commands if you + command; move your @shortcontents and @contents commands if you want the contents after the title page.}}% \parseargdef\shorttitlepage{% - \begingroup \hbox{}\vskip 1.5in \chaprm \centerline{#1}% - \endgroup\page\hbox{}\page} + {\headingsoff \begingroup \hbox{}\vskip 1.5in \chaprm \centerline{#1}% + \endgroup\page\hbox{}\page}\pageone} \envdef\titlepage{% % Open one extra group, as we want to close it in the middle of \Etitlepage. \begingroup \parindent=0pt \textfonts + \headingsoff % Leave some space at the very top of the page. \vglue\titlepagetopglue % No rule at page bottom unless we print one at the top with @title. @@ -3763,15 +3882,14 @@ % If we use the new definition of \page, we always get a blank page % after the title page, which we certainly don't want. \oldpage + \pageone \endgroup % - % Need this before the \...aftertitlepage checks so that if they are - % in effect the toc pages will come out with page numbers. - \HEADINGSon } \def\finishtitlepage{% - \vskip4pt \hrule height 2pt width \hsize + \ifseenauthor \vskip4pt \else \vskip 0pt plus 1filll \fi + \hrule height 2pt width \hsize \vskip\titlepagebottomglue \finishedtitlepagetrue } @@ -3780,7 +3898,7 @@ % don't worry much about spacing, ragged right. This should be used % inside a \vbox, and fonts need to be set appropriately first. \par should % be specified before the end of the \vbox, since a vbox is a group. -% +% \def\raggedtitlesettings{% \rm \hyphenpenalty=10000 @@ -3794,33 +3912,105 @@ \let\subtitlerm=\rmfont \def\subtitlefont{\subtitlerm \normalbaselineskip = 13pt \normalbaselines} +\let\savedtitle\empty +\let\savedsubtitlegroup\empty +\let\savedauthorgroup\empty + \parseargdef\title{% - \checkenv\titlepage - \vbox{\titlefonts \raggedtitlesettings #1\par}% - % print a rule at the page bottom also. - \finishedtitlepagefalse - \vskip4pt \hrule height 4pt width \hsize \vskip4pt + \expandafter\ifx\thisenv\documentinfo + \gdef\savedtitle{#1}% + \else + \checkenv\titlepage + \vbox{\titlefonts \raggedtitlesettings #1\par}% + % print a rule at the page bottom also. + \finishedtitlepagefalse + \vskip4pt \hrule height 4pt width \hsize \vskip4pt + \fi } \parseargdef\subtitle{% - \checkenv\titlepage - {\subtitlefont \rightline{#1}}% + \expandafter\ifx\thisenv\documentinfo + \ifx\savedsubtitlegroup\empty + \gdef\savedsubtitlegroup{\savedsubtitle{#1}}% + \else + \expandafter\gdef\expandafter\savedsubtitlegroup\expandafter{% + \savedsubtitlegroup\savedsubtitle{#1}}% + \fi + \else + \checkenv\titlepage + {\subtitlefont \rightline{#1}}% + \fi } % @author should come last, but may come many times. % It can also be used inside @quotation. % \parseargdef\author{% - \def\temp{\quotation}% - \ifx\thisenv\temp - \def\quotationauthor{#1}% printed in \Equotation. - \else - \checkenv\titlepage - \ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi - {\secfonts\rm \leftline{#1}}% + \expandafter\ifx\thisenv\documentinfo + \ifx\savedauthorgroup\empty + \gdef\savedauthorgroup{\savedauthor{#1}}% + \else + \expandafter\gdef\expandafter\savedauthorgroup\expandafter{% + \savedauthorgroup\savedauthor{#1}}% + \fi + \else + \def\temp{\quotation}% + \ifx\thisenv\temp + \def\quotationauthor{#1}% printed in \Equotation. + \else + \checkenv\titlepage + \ifseenauthor\else \vskip 0pt plus 1filll \seenauthortrue \fi + {\secfonts\rm \leftline{#1}}% + \fi + \fi +} + +% @maketitle +{\obeylines +\gdef\maketitle{% +\titlepage +\ifx\savedtitle\empty\else + \title \savedtitle + \ifx\savedsubtitlegroup\empty\else + \savedsubtitlegroup +\fi\fi +\ifx\savedauthorgroup\empty\else + \savedauthorgroup +\fi +% start verso page if either copying or publication text is given +\ifx\copyingtext\relax + \ifx\publicationtext\relax\else + \page \vskip 0pt plus 1filll \fi +\else + \page \vskip 0pt plus 1filll +\fi +\ifx\publicationtext\relax\else + \insertpublication + \sp 1 +\fi +\ifx\copyingtext\relax\else + \insertcopying +\fi +\end titlepage } +% \savedauthor{#1}, called with braces. output an @author line. +\gdef\savedauthor#1{% +\author#1 +} + +% \savedsubtitle{#1}, called with braces. output a @subtitle line. +\gdef\savedsubtitle#1{% +\subtitle#1 +} +} % \obeylines + +% @documentinfo block +\envdef\documentinfo{% +} +\def\Edocumentinfo{}% + % Set up page headings and footings. @@ -3834,15 +4024,16 @@ \newtoks\oddfootline % footline on odd pages % Now make \makeheadline and \makefootline in Plain TeX use those variables -\headline={{\textfonts\rm +\headline={{\textfonts\rm\frenchspacingsetting \ifchapterpage \ifodd\pageno\the\oddchapheadline\else\the\evenchapheadline\fi \else \ifodd\pageno\the\oddheadline\else\the\evenheadline\fi \fi}} -\footline={{\textfonts\rm \ifodd\pageno \the\oddfootline - \else \the\evenfootline \fi}\HEADINGShook} +\footline={{\textfonts\rm\frenchspacingsetting + \ifodd\pageno \the\oddfootline \else \the\evenfootline \fi}% + \HEADINGShook} \let\HEADINGShook=\relax % Commands to set those variables. @@ -3935,46 +4126,37 @@ } \def\HEADINGSoff{{\globaldefs=1 \headingsoff}} % global setting -\HEADINGSoff % it's the default -% When we turn headings on, set the page number to 1. +% Set the page number to 1. \def\pageone{ \global\pageno=1 \global\arabiccount = \pagecount } +\let\contentsalignmacro = \chappager + +% \def\HEADINGSon{\HEADINGSdouble} % defined by \CHAPPAGon + % For double-sided printing, put current file name in lower left corner, % chapter name on inside top of right hand pages, document % title on inside top of left hand pages, and page numbers on outside top % edge of all pages. -\def\HEADINGSdouble{% -\pageone -\HEADINGSdoublex -} -\let\contentsalignmacro = \chappager - -% For single-sided printing, chapter title goes across top left of page, -% page number on top right. -\def\HEADINGSsingle{% -\pageone -\HEADINGSsinglex -} -\def\HEADINGSon{\HEADINGSdouble} - -\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdoublex} +\def\HEADINGSafter{\let\HEADINGShook=\HEADINGSdouble} \let\HEADINGSdoubleafter=\HEADINGSafter -\def\HEADINGSdoublex{% +\def\HEADINGSdouble{% \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\folio\hfil\thistitle}} \global\oddheadline={\line{\thischapter\hfil\folio}} -\global\evenchapheadline={\line{\folio\hfil}} +\global\evenchapheadline={\line{\folio\hfil\thistitle}} \global\oddchapheadline={\line{\hfil\folio}} \global\let\contentsalignmacro = \chapoddpage } -\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsinglex} -\def\HEADINGSsinglex{% +% For single-sided printing, chapter title goes across top left of page, +% page number on top right. +\def\HEADINGSsingleafter{\let\HEADINGShook=\HEADINGSsingle} +\def\HEADINGSsingle{% \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} @@ -3986,7 +4168,6 @@ % for @setchapternewpage off \def\HEADINGSsinglechapoff{% -\pageone \global\evenfootline={\hfil} \global\oddfootline={\hfil} \global\evenheadline={\line{\thischapter\hfil\folio}} @@ -4356,8 +4537,7 @@ % undo it ourselves. \def\headitemfont{\b}% for people to use in the template row; not changeable \def\headitem{% - \checkenv\multitable - \crcr + \crcr % must appear first \gdef\headitemcrhook{\nobreak}% attempt to avoid page break after headings \global\everytab={\bf}% can't use \headitemfont since the parsing differs \the\everytab % for the first item @@ -4419,7 +4599,7 @@ % Find the correct column width \hsize=\expandafter\csname col\the\colcount\endcsname % - \rightskip=0pt + \advance\rightskip by -1\rightskip % Zero leaving only any stretch \ifnum\colcount=1 \advance\hsize by\leftskip % Add indent of surrounding text \else @@ -4442,7 +4622,7 @@ \message{conditionals,} -% @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotplaintext, +% @iftex, @ifnotdocbook, @ifnothtml, @ifnotinfo, @ifnotlatex, @ifnotplaintext, % @ifnotxml always succeed. They currently do nothing; we don't % attempt to check whether the conditionals are properly nested. But we % have to remember that they are conditionals, so that @end doesn't @@ -4456,6 +4636,7 @@ \makecond{ifnotdocbook} \makecond{ifnothtml} \makecond{ifnotinfo} +\makecond{ifnotlatex} \makecond{ifnotplaintext} \makecond{ifnotxml} @@ -4468,10 +4649,12 @@ \def\ifdocbook{\doignore{ifdocbook}} \def\ifhtml{\doignore{ifhtml}} \def\ifinfo{\doignore{ifinfo}} +\def\iflatex{\doignore{iflatex}} \def\ifnottex{\doignore{ifnottex}} \def\ifplaintext{\doignore{ifplaintext}} \def\ifxml{\doignore{ifxml}} \def\ignore{\doignore{ignore}} +\def\latex{\doignore{latex}} \def\menu{\doignore{menu}} \def\xml{\doignore{xml}} @@ -4613,7 +4796,7 @@ % Like \expandablevalue, but completely expandable (the \message in the % definition above operates at the execution level of TeX). Used when % writing to auxiliary files, due to the expansion that \write does. -% If flag is undefined, pass through an unexpanded @value command: maybe it +% If flag is undefined, pass through an unexpanded @value command: maybe it % will be set by the time it is read back in. % % NB flag names containing - or _ may not work here. @@ -4637,7 +4820,7 @@ % @ifset VAR ... @end ifset reads the `...' iff VAR has been defined % with @set. -% +% % To get the special treatment we need for `@end ifset,' we call % \makecond and then redefine. % @@ -4670,7 +4853,7 @@ % without the @) is in fact defined. We can only feasibly check at the % TeX level, so something like `mathcode' is going to considered % defined even though it is not a Texinfo command. -% +% \makecond{ifcommanddefined} \def\ifcommanddefined{\parsearg{\doifcmddefined{\let\next=\ifcmddefinedfail}}} % @@ -4710,13 +4893,11 @@ % except not \outer, so it can be used within macros and \if's. \edef\newwrite{\makecsname{ptexnewwrite}} -% \newindex {foo} defines an index named IX. +% \newindex {IX} defines an index named IX. % It automatically defines \IXindex such that % \IXindex ...rest of line... puts an entry in the index IX. % It also defines \IXindfile to be the number of the output channel for % the file that accumulates this index. The file's extension is IX. -% The name of an index should be no more than 2 characters long -% for the sake of vms. % \def\newindex#1{% \expandafter\chardef\csname#1indfile\endcsname=0 @@ -4778,22 +4959,7 @@ \def\docodeindex#1{\edef\indexname{#1}\parsearg\docodeindexxxx} \def\docodeindexxxx #1{\docind{\indexname}{#1}} - -% Used for the aux, toc and index files to prevent expansion of Texinfo -% commands. -% -\def\atdummies{% - \definedummyletter\@% - \definedummyletter\ % - \definedummyletter\{% - \definedummyletter\}% - \definedummyletter\&% - % - % Do the redefinitions. - \definedummies - \otherbackslash -} - + % \definedummyword defines \#1 as \string\#1\space, thus effectively % preventing its expansion. This is used only for control words, % not control letters, because the \space would be incorrect for @@ -4809,110 +4975,91 @@ % \def\definedummyword #1{\def#1{\string#1\space}}% \def\definedummyletter#1{\def#1{\string#1}}% -\let\definedummyaccent\definedummyletter -% Called from \atdummies to prevent the expansion of commands. +% Used for the aux, toc and index files to prevent expansion of Texinfo +% commands. Most of the commands are controlled through the +% \ifdummies conditional. % -\def\definedummies{% +\def\atdummies{% + \dummiestrue % - \let\commondummyword\definedummyword - \let\commondummyletter\definedummyletter - \let\commondummyaccent\definedummyaccent - \commondummiesnofonts + \definedummyletter\@% + \definedummyletter\ % + \definedummyletter\{% + \definedummyletter\}% + \definedummyletter\&% % \definedummyletter\_% \definedummyletter\-% % - % Non-English letters. - \definedummyword\AA - \definedummyword\AE - \definedummyword\DH - \definedummyword\L - \definedummyword\O - \definedummyword\OE - \definedummyword\TH - \definedummyword\aa - \definedummyword\ae - \definedummyword\dh - \definedummyword\exclamdown - \definedummyword\l - \definedummyword\o - \definedummyword\oe - \definedummyword\ordf - \definedummyword\ordm - \definedummyword\questiondown - \definedummyword\ss - \definedummyword\th - % - % Although these internal commands shouldn't show up, sometimes they do. - \definedummyword\bf - \definedummyword\gtr - \definedummyword\hat - \definedummyword\less - \definedummyword\sf - \definedummyword\sl - \definedummyword\tclose - \definedummyword\tt - % - \definedummyword\LaTeX - \definedummyword\TeX - % - % Assorted special characters. - \definedummyword\ampchar - \definedummyword\atchar - \definedummyword\arrow - \definedummyword\backslashchar - \definedummyword\bullet - \definedummyword\comma - \definedummyword\copyright - \definedummyword\registeredsymbol - \definedummyword\dots - \definedummyword\enddots - \definedummyword\entrybreak - \definedummyword\equiv - \definedummyword\error - \definedummyword\euro - \definedummyword\expansion - \definedummyword\geq - \definedummyword\guillemetleft - \definedummyword\guillemetright - \definedummyword\guilsinglleft - \definedummyword\guilsinglright - \definedummyword\lbracechar - \definedummyword\leq - \definedummyword\mathopsup - \definedummyword\minus - \definedummyword\ogonek - \definedummyword\pounds - \definedummyword\point - \definedummyword\print - \definedummyword\quotedblbase - \definedummyword\quotedblleft - \definedummyword\quotedblright - \definedummyword\quoteleft - \definedummyword\quoteright - \definedummyword\quotesinglbase - \definedummyword\rbracechar - \definedummyword\result - \definedummyword\sub - \definedummyword\sup - \definedummyword\textdegree - % \definedummyword\subentry % % We want to disable all macros so that they are not expanded by \write. + \let\commondummyword\definedummyword \macrolist \let\value\dummyvalue % - \normalturnoffactive -} - -% \commondummiesnofonts: common to \definedummies and \indexnofonts. -% Define \commondummyletter, \commondummyaccent and \commondummyword before -% using. Used for accents, font commands, and various control letters. -% -\def\commondummiesnofonts{% - % Control letters and accents. + \turnoffactive +} + +\newif\ifdummies +\newif\ifindexnofonts + +\def\commondummyletter#1{% + \expandafter\let\csname\string#1:impl\endcsname#1% + \edef#1{% + \noexpand\ifindexnofonts + % empty expansion + \noexpand\else + \noexpand\ifdummies\string#1% + \noexpand\else + \noexpand\jumptwofi % dispose of the \fi + \expandafter\noexpand\csname\string#1:impl\endcsname + \noexpand\fi + \noexpand\fi}% +} + +\def\commondummyaccent#1{% + \expandafter\let\csname\string#1:impl\endcsname#1% + \edef#1{% + \noexpand\ifindexnofonts + \noexpand\expandafter % dispose of \else ... \fi + \noexpand\asis + \noexpand\else + \noexpand\ifdummies\string#1% + \noexpand\else + \noexpand\jumptwofi % dispose of the \fi + \expandafter\noexpand\csname\string#1:impl\endcsname + \noexpand\fi + \noexpand\fi}% +} + +% Like \commondummyaccent but add a \space at the end of the dummy expansion +% #2 is the expansion used for \indexnofonts. #2 is always followed by +% \asis to remove a pair of following braces. +\def\commondummyword#1#2{% + \expandafter\let\csname\string#1:impl\endcsname#1% + \expandafter\def\csname\string#1:ixnf\endcsname{#2\asis}% + \edef#1{% + \noexpand\ifindexnofonts + \noexpand\expandafter % dispose of \else ... \fi + \expandafter\noexpand\csname\string#1:ixnf\endcsname + \noexpand\else + \noexpand\ifdummies\string#1\space + \noexpand\else + \noexpand\jumptwofi % dispose of the \fi \fi + \expandafter\noexpand\csname\string#1:impl\endcsname + \noexpand\fi + \noexpand\fi}% +} +\def\jumptwofi#1\fi\fi{\fi\fi#1} + +% For \atdummies and \indexnofonts. \atdummies sets +% \dummiestrue and \indexnofonts sets \indexnofontstrue. +\def\definedummies{ + % @-sign is always an escape character when reading auxiliary files + \escapechar = `\@ + % \commondummyletter\!% \commondummyaccent\"% \commondummyaccent\'% @@ -4926,58 +5073,124 @@ \commondummyaccent\^% \commondummyaccent\`% \commondummyaccent\~% - \commondummyword\u - \commondummyword\v - \commondummyword\H - \commondummyword\dotaccent - \commondummyword\ogonek - \commondummyword\ringaccent - \commondummyword\tieaccent - \commondummyword\ubaraccent - \commondummyword\udotaccent - \commondummyword\dotless + % + % Control letters and accents. + \commondummyword\u {}% + \commondummyword\v {}% + \commondummyword\H {}% + \commondummyword\dotaccent {}% + \commondummyword\ogonek {}% + \commondummyword\ringaccent {}% + \commondummyword\tieaccent {}% + \commondummyword\ubaraccent {}% + \commondummyword\udotaccent {}% + \commondummyword\dotless {}% % % Texinfo font commands. - \commondummyword\b - \commondummyword\i - \commondummyword\r - \commondummyword\sansserif - \commondummyword\sc - \commondummyword\slanted - \commondummyword\t + \commondummyword\b {}% + \commondummyword\i {}% + \commondummyword\r {}% + \commondummyword\sansserif {}% + \commondummyword\sc {}% + \commondummyword\slanted {}% + \commondummyword\t {}% % % Commands that take arguments. - \commondummyword\abbr - \commondummyword\acronym - \commondummyword\anchor - \commondummyword\cite - \commondummyword\code - \commondummyword\command - \commondummyword\dfn - \commondummyword\dmn - \commondummyword\email - \commondummyword\emph - \commondummyword\env - \commondummyword\file - \commondummyword\image - \commondummyword\indicateurl - \commondummyword\inforef - \commondummyword\kbd - \commondummyword\key - \commondummyword\math - \commondummyword\option - \commondummyword\pxref - \commondummyword\ref - \commondummyword\samp - \commondummyword\strong - \commondummyword\tie - \commondummyword\U - \commondummyword\uref - \commondummyword\url - \commondummyword\var - \commondummyword\verb - \commondummyword\w - \commondummyword\xref + \commondummyword\abbr {}% + \commondummyword\acronym {}% + \commondummyword\anchor {}% + \commondummyword\cite {}% + \commondummyword\code {}% + \commondummyword\command {}% + \commondummyword\dfn {}% + \commondummyword\dmn {}% + \commondummyword\email {}% + \commondummyword\emph {}% + \commondummyword\env {}% + \commondummyword\file {}% + \commondummyword\image {}% + \commondummyword\indicateurl{}% + \commondummyword\inforef {}% + \commondummyword\kbd {}% + \commondummyword\key {}% + \commondummyword\link {}% + \commondummyword\math {}% + \commondummyword\option {}% + \commondummyword\pxref {}% + \commondummyword\ref {}% + \commondummyword\samp {}% + \commondummyword\strong {}% + \commondummyword\tie {}% + \commondummyword\U {}% + \commondummyword\uref {}% + \commondummyword\url {}% + \commondummyword\var {}% + \commondummyword\verb {}% + \commondummyword\w {}% + \commondummyword\xref {}% + % + \commondummyword\AA {AA}% + \commondummyword\AE {AE}% + \commondummyword\DH {DZZ}% + \commondummyword\L {L}% + \commondummyword\O {O}% + \commondummyword\OE {OE}% + \commondummyword\TH {TH}% + \commondummyword\aa {aa}% + \commondummyword\ae {ae}% + \commondummyword\dh {dzz}% + \commondummyword\exclamdown {!}% + \commondummyword\l {l}% + \commondummyword\o {o}% + \commondummyword\oe {oe}% + \commondummyword\ordf {a}% + \commondummyword\ordm {o}% + \commondummyword\questiondown {?}% + \commondummyword\ss {ss}% + \commondummyword\th {th}% + % + \commondummyword\LaTeX {LaTeX}% + \commondummyword\TeX {TeX}% + % + % Assorted special characters. + \commondummyword\ampchar {\normalamp}% + \commondummyword\atchar {\@}% + \commondummyword\arrow {->}% + \commondummyword\backslashchar {\realbackslash}% + \commondummyword\bullet {bullet}% + \commondummyword\comma {,}% + \commondummyword\copyright {copyright}% + \commondummyword\dots {...}% + \commondummyword\enddots {...}% + \commondummyword\entrybreak {}% + \commondummyword\equiv {===}% + \commondummyword\error {error}% + \commondummyword\euro {euro}% + \commondummyword\expansion {==>}% + \commondummyword\geq {>=}% + \commondummyword\guillemetleft {<<}% + \commondummyword\guillemetright {>>}% + \commondummyword\guilsinglleft {<}% + \commondummyword\guilsinglright {>}% + \commondummyword\lbracechar {\{}% + \commondummyword\leq {<=}% + \commondummyword\mathopsup {sup}% + \commondummyword\minus {-}% + \commondummyword\pounds {pounds}% + \commondummyword\point {.}% + \commondummyword\print {-|}% + \commondummyword\quotedblbase {"}% + \commondummyword\quotedblleft {"}% + \commondummyword\quotedblright {"}% + \commondummyword\quoteleft {`}% + \commondummyword\quoteright {'}% + \commondummyword\quotesinglbase {,}% + \commondummyword\rbracechar {\}}% + \commondummyword\registeredsymbol {R}% + \commondummyword\result {=>}% + \commondummyword\sub {}% + \commondummyword\sup {}% + \commondummyword\textdegree {o}% } \let\indexlbrace\relax @@ -4995,25 +5208,24 @@ \catcode`\-=13 \catcode`\`=13 \gdef\indexnonalnumdisappear{% - \expandafter\ifx\csname SETtxiindexlquoteignore\endcsname\relax\else + \ifflagclear{txiindexlquoteignore}{}{% % @set txiindexlquoteignore makes us ignore left quotes in the sort term. % (Introduced for FSFS 2nd ed.) \let`=\empty - \fi + }% % - \expandafter\ifx\csname SETtxiindexbackslashignore\endcsname\relax\else + \ifflagclear{txiindexbackslashignore}{}{% \backslashdisappear - \fi - % - \expandafter\ifx\csname SETtxiindexhyphenignore\endcsname\relax\else + }% + \ifflagclear{txiindexhyphenignore}{}{% \def-{}% - \fi - \expandafter\ifx\csname SETtxiindexlessthanignore\endcsname\relax\else + }% + \ifflagclear{txiindexlessthanignore}{}{% \def<{}% - \fi - \expandafter\ifx\csname SETtxiindexatsignignore\endcsname\relax\else + }% + \ifflagclear{txiindexatsignignore}{}{% \def\@{}% - \fi + }% } \gdef\indexnonalnumreappear{% @@ -5029,18 +5241,7 @@ % would be for a given command (usually its argument). % \def\indexnofonts{% - % Accent commands should become @asis. - \def\commondummyaccent##1{\let##1\asis}% - % We can just ignore other control letters. - \def\commondummyletter##1{\let##1\empty}% - % All control words become @asis by default; overrides below. - \let\commondummyword\commondummyaccent - \commondummiesnofonts - % - % Don't no-op \tt, since it isn't a user-level command - % and is used in the definitions of the active chars like <, >, |, etc. - % Likewise with the other plain tex font commands. - %\let\tt=\asis + \indexnofontstrue % \def\ { }% \def\@{@}% @@ -5049,88 +5250,23 @@ % \uccode`\1=`\{ \uppercase{\def\{{1}}% \uccode`\1=`\} \uppercase{\def\}{1}}% - \let\lbracechar\{% - \let\rbracechar\}% - % - % Non-English letters. - \def\AA{AA}% - \def\AE{AE}% - \def\DH{DZZ}% - \def\L{L}% - \def\OE{OE}% - \def\O{O}% - \def\TH{TH}% - \def\aa{aa}% - \def\ae{ae}% - \def\dh{dzz}% - \def\exclamdown{!}% - \def\l{l}% - \def\oe{oe}% - \def\ordf{a}% - \def\ordm{o}% - \def\o{o}% - \def\questiondown{?}% - \def\ss{ss}% - \def\th{th}% - % - \let\do\indexnofontsdef - % - \do\LaTeX{LaTeX}% - \do\TeX{TeX}% + \def\lbracechar##1{\{}% + \def\rbracechar##1{\}}% % - % Assorted special characters. - \do\atchar{@}% - \do\arrow{->}% - \do\bullet{bullet}% - \do\comma{,}% - \do\copyright{copyright}% - \do\dots{...}% - \do\enddots{...}% - \do\equiv{==}% - \do\error{error}% - \do\euro{euro}% - \do\expansion{==>}% - \do\geq{>=}% - \do\guillemetleft{<<}% - \do\guillemetright{>>}% - \do\guilsinglleft{<}% - \do\guilsinglright{>}% - \do\leq{<=}% - \do\lbracechar{\{}% - \do\minus{-}% - \do\point{.}% - \do\pounds{pounds}% - \do\print{-|}% - \do\quotedblbase{"}% - \do\quotedblleft{"}% - \do\quotedblright{"}% - \do\quoteleft{`}% - \do\quoteright{'}% - \do\quotesinglbase{,}% - \do\rbracechar{\}}% - \do\registeredsymbol{R}% - \do\result{=>}% - \do\textdegree{o}% % % We need to get rid of all macros, leaving only the arguments (if present). % Of course this is not nearly correct, but it is the best we can do for now. - % makeinfo does not expand macros in the argument to @deffn, which ends up - % writing an index entry, and texindex isn't prepared for an index sort entry - % that starts with \. % % Since macro invocations are followed by braces, we can just redefine them % to take a single TeX argument. The case of a macro invocation that % goes to end-of-line is not handled. % + \def\commondummyword##1{\let##1\asis}% \macrolist \let\value\indexnofontsvalue } -% Give the control sequence a definition that removes the {} that follows -% its use, e.g. @AA{} -> AA -\def\indexnofontsdef#1#2{\def#1##1{#2}}% - - + % #1 is the index name, #2 is the entry text. @@ -5171,7 +5307,7 @@ \ifx\suffix\indexisfl\def\suffix{f1}\fi % Open the file \immediate\openout\csname#1indfile\endcsname \jobname.\suffix - % Using \immediate above here prevents an object entering into the current + % Using \immediate above here prevents an object entering into the current % box, which could confound checks such as those in \safewhatsit for % preceding skips. \typeout{Writing index file \jobname.\suffix}% @@ -5223,7 +5359,7 @@ \ifx\segment\isfinish \else % - % Fully expand the segment, throwing away any @sortas directives, and + % Fully expand the segment, throwing away any @sortas directives, and % trim spaces. \edef\trimmed{\segment}% \edef\trimmed{\expandafter\eatspaces\expandafter{\trimmed}}% @@ -5260,7 +5396,10 @@ \xdef\trimmed{\segment}% \xdef\trimmed{\expandafter\eatspaces\expandafter{\trimmed}}% \xdef\indexsortkey{\trimmed}% - \ifx\indexsortkey\empty\xdef\indexsortkey{ }\fi + \ifx\indexsortkey\empty + \message{Empty index sort key near line \the\inputlineno}% + \xdef\indexsortkey{ }% + \fi }\fi % % Append to \fullindexsortkey. @@ -5284,14 +5423,14 @@ % the current value of \escapechar. \def\escapeisbackslash{\escapechar=`\\} -% Use \ in index files by default. texi2dvi didn't support @ as the escape -% character (as it checked for "\entry" in the files, and not "@entry"). When -% the new version of texi2dvi has had a chance to become more prevalent, then -% the escape character can change back to @ again. This should be an easy -% change to make now because both @ and \ are only used as escape characters in -% index files, never standing for themselves. +% Uncomment to use \ in index files by default. Old texi2dvi (before 2019) +% didn't support @ as the escape character (as it checked for "\entry" in +% the files, and not "@entry"). +% In the future we can remove this flag and simplify the code for +% index files and backslashes, once the support is no longer likely to be +% useful. % -\set txiindexescapeisbackslash +% \set txiindexescapeisbackslash % Write the entry in \indextext to the index file. % @@ -5305,16 +5444,14 @@ % \atdummies % - \expandafter\ifx\csname SETtxiindexescapeisbackslash\endcsname\relax\else - \escapeisbackslash - \fi + \ifflagclear{txiindexescapeisbackslash}{}{\escapeisbackslash}% % % For texindex which always views { and } as separators. \def\{{\lbracechar{}}% \def\}{\rbracechar{}}% \uccode`\~=`\\ \uppercase{\def~{\backslashchar{}}}% % - % Split the entry into primary entry and any subentries, and get the index + % Split the entry into primary entry and any subentries, and get the index % sort key. \splitindexentry\indextext % @@ -5459,6 +5596,8 @@ \tolerance = 9500 \plainfrenchspacing \everypar = {}% don't want the \kern\-parindent from indentation suppression. + \let\entry\indexentry + \ifxetex\xetexpreauxfile\fi % % See comment in \requireopenindexfile. \def\indexname{#1}\ifx\indexname\indexisfl\def\indexname{f1}\fi @@ -5484,40 +5623,48 @@ \fi \fi \closein 1 + \ifxetex\xetexpostauxfile\fi \endgroup} +% Checked in @bye +\let\byeerror\relax + % If the index file starts with a backslash, forgo reading the index % file altogether. If somebody upgrades texinfo.tex they may still have % old index files using \ as the escape character. Reading this would % at best lead to typesetting garbage, at worst a TeX syntax error. \def\printindexzz#1#2\finish{% - \expandafter\ifx\csname SETtxiindexescapeisbackslash\endcsname\relax + \ifflagclear{txiindexescapeisbackslash}{% \uccode`\~=`\\ \uppercase{\if\noexpand~}\noexpand#1 - \expandafter\ifx\csname SETtxiskipindexfileswithbackslash\endcsname\relax -\errmessage{% -ERROR: A sorted index file in an obsolete format was skipped. + \ifflagclear{txiskipindexfileswithbackslash}{% + % Delay the error message until the very end to give a chance + % for the whole index to be output as input for texindex. + \global\def\byeerror{% +ERROR: A sorted index file in an obsolete format was skipped. To fix this problem, please upgrade your version of 'texi2dvi' or 'texi2pdf' to that at <https://ftp.gnu.org/gnu/texinfo>. -If you are using an old version of 'texindex' (part of the Texinfo +If you are using an old version of 'texindex' (part of the Texinfo distribution), you may also need to upgrade to a newer version (at least 6.0). You may be able to typeset the index if you run 'texindex \jobname.\indexname' yourself. -You could also try setting the 'txiindexescapeisbackslash' flag by +You could also try setting the 'txiindexescapeisbackslash' flag by running a command like -'texi2dvi -t "@set txiindexescapeisbackslash" \jobname.texi'. If you do +'texi2dvi -t "@set txiindexescapeisbackslash" \jobname.texi'. If you do this, Texinfo will try to use index files in the old format. -If you continue to have problems, deleting the index files and starting again +If you continue to have problems, deleting the index files and starting again might help (with 'rm \jobname.?? \jobname.??s')% }% - \else + }{% (Skipped sorted index file in obsolete format) - \fi + }% \else \begindoublecolumns + \ifxetex\xetexpreauxfile\fi \input \jobname.\indexname s + \ifxetex\xetexpostauxfile\fi \enddoublecolumns \fi - \else + }{% \begindoublecolumns \catcode`\\=0\relax % @@ -5525,11 +5672,39 @@ % should work because we (hopefully) don't otherwise use @ in index files. %\catcode`\@=12\relax \catcode`\@=0\relax + \ifxetex\xetexpreauxfile\fi \input \jobname.\indexname s + \ifxetex\xetexpostauxfile\fi \enddoublecolumns + }% +} + +\def\indexentry#1#2{% + \let\entrypagetarget\empty + \ifpdforxetex + % only link the index text to the page if no comma appears in the + % list of pages, i.e. there is only one page + \checkpagelistcomma{#2}\pagelistcomma + \expandafter\ifcase\pagelistcomma + \def\entrypagetarget{#2}% + \fi + \fi% + \entryinternal{#1}{#2}% +} + +\def\checkpagelistcomma#1#2{% + \checkpagelistcommaxx#2#1,\finish +} +\def\checkpagelistcommaxx#1#2,#3\finish{% + \def\tmp{#3}% + \ifx\tmp\empty + \def#1{0\relax} + \else + \def#1{1\relax} \fi } + % These macros are used by the sorted index file itself. % Change them to control the appearance of the index. @@ -5566,7 +5741,6 @@ \def\initial{% \bgroup - \initialglyphs \initialx } @@ -5579,7 +5753,7 @@ % bottom of a column to reduce an increase in inter-line spacing. \nobreak \vskip 0pt plus 5\baselineskip - \penalty -300 + \penalty -300 \vskip 0pt plus -5\baselineskip % % Typeset the initial. Making this add up to a whole number of @@ -5589,7 +5763,10 @@ % % No shrink because it confuses \balancecolumns. \vskip 1.67\baselineskip plus 1\baselineskip - \leftline{\secfonts \kern-0.05em \secbf #1}% + \doindexinitialentry{#1}% + \initialglyphs + \leftline{% + \secfonts \kern-0.05em \secbf #1}% % \secfonts is inside the argument of \leftline so that the change of % \baselineskip will not affect any glue inserted before the vbox that % \leftline creates. @@ -5599,14 +5776,48 @@ \egroup % \initialglyphs } +\def\doindexinitialentry#1{% + \ifpdforxetex + \global\advance\idxinitialno by 1 + \def\indexlbrace{\{}% + \def\indexrbrace{\}}% + \def\indexbackslash{\realbackslash}% + \def\indexatchar{\@}% + \writetocentry{idxinitial}{\asis #1}{IDX\the\idxinitialno}% + % The @asis removes a pair of braces around e.g. {@indexatchar} that + % are output by texindex. + % + \pdfmkdest{idx.\asis #1.IDX\the\idxinitialno}% + \fi +} + +% No listing in TOC +\def\idxinitialentry#1#2#3#4{} + +% For index initials. +\newcount\idxinitialno \idxinitialno=1 + + \newdimen\entryrightmargin \entryrightmargin=0pt -% \entry typesets a paragraph consisting of the text (#1), dot leaders, and -% then page number (#2) flushed to the right margin. It is used for index -% and table of contents entries. The paragraph is indented by \leftskip. -% -\def\entry{% +% amount to indent subsequent lines in an entry when it spans more than +% one line. +\newdimen\entrycontskip +\entrycontskip=1em + +% for PDF output, whether to make the text of the entry a link to the section. +% set for @contents and @shortcontents. +\newif\iflinkentrytext + +% \entryinternal typesets a paragraph consisting of the text (#1), dot +% leaders, and then page number (#2) flushed to the right margin. It is +% used for index and table of contents entries. The paragraph is indented +% by \leftskip. +% For PDF output, if \linkentrytexttrue and \tocnodetarget is set, link text +% to the referenced node. Else if \entrypagetarget is set, link text to the +% page. +\def\entryinternal{% \begingroup % % Start a new paragraph if necessary, so our assignments below can't @@ -5628,7 +5839,7 @@ } \def\entrybreak{\unskip\space\ignorespaces}% \def\doentry{% - % Save the text of the entry + % Save the text of the entry in \boxA \global\setbox\boxA=\hbox\bgroup \bgroup % Instead of the swallowed brace. \noindent @@ -5638,12 +5849,31 @@ % with catcodes occurring. } {\catcode`\@=11 +% #1 is the page number \gdef\finishentry#1{% - \egroup % end box A + \egroup % end \boxA \dimen@ = \wd\boxA % Length of text of entry + % add any leaders and page number to \boxA. \global\setbox\boxA=\hbox\bgroup - \unhbox\boxA - % #1 is the page number. + \ifpdforxetex + \iflinkentrytext + \ifx\tocnodetarget\empty + \unhbox\boxA + \else + \startxreflink{\tocnodetarget}{}% + \unhbox\boxA + \endlink + \fi + \else + \ifx\entrypagetarget\empty + \unhbox\boxA + \else + \pdflinkpage{\entrypagetarget}{\unhbox\boxA}% + \fi + \fi + \else + \unhbox\boxA + \fi % % Get the width of the page numbers, and only use % leaders if they are present. @@ -5654,14 +5884,23 @@ % \null\nobreak\indexdotfill % Have leaders before the page number. % + \hskip\skip\thinshrinkable \ifpdforxetex - \pdfgettoks#1.% - \hskip\skip\thinshrinkable\the\toksA + \ifx\tocnodetarget\empty + \pdfgettoks#1.% + \the\toksA + \else + % Should just be a single page number in toc + \startxreflink{\tocnodetarget}{}% + #1\endlink + \fi \else - \hskip\skip\thinshrinkable #1% + #1% \fi \fi \egroup % end \boxA + % + % now output \ifdim\wd\boxB = 0pt \noindent\unhbox\boxA\par \nobreak @@ -5679,41 +5918,17 @@ \parfillskip=0pt plus -1fill % \advance\rightskip by \entryrightmargin - % Determine how far we can stretch into the margin. - % This allows, e.g., "Appendix H GNU Free Documentation License" to - % fit on one line in @letterpaper format. - \ifdim\entryrightmargin>2.1em - \dimen@i=2.1em - \else - \dimen@i=0em - \fi - \advance \parfillskip by 0pt minus 1\dimen@i % \dimen@ii = \hsize \advance\dimen@ii by -1\leftskip \advance\dimen@ii by -1\entryrightmargin - \advance\dimen@ii by 1\dimen@i \ifdim\wd\boxA > \dimen@ii % If the entry doesn't fit in one line \ifdim\dimen@ > 0.8\dimen@ii % due to long index text - % Try to split the text roughly evenly. \dimen@ will be the length of - % the first line. - \dimen@ = 0.7\dimen@ - \dimen@ii = \hsize - \ifnum\dimen@>\dimen@ii - % If the entry is too long (for example, if it needs more than - % two lines), use all the space in the first line. - \dimen@ = \dimen@ii - \fi \advance\leftskip by 0pt plus 1fill % ragged right - \advance \dimen@ by 1\rightskip - \parshape = 2 0pt \dimen@ 0em \dimen@ii - % Ideally we'd add a finite glue at the end of the first line only, - % instead of using \parshape with explicit line lengths, but TeX - % doesn't seem to provide a way to do such a thing. % % Indent all lines but the first one. - \advance\leftskip by 1em - \advance\parindent by -1em + \advance\leftskip by \entrycontskip + \advance\parindent by -\entrycontskip \fi\fi \indent % start paragraph \unhbox\boxA @@ -5736,12 +5951,11 @@ \newskip\thinshrinkable \skip\thinshrinkable=.15em minus .15em -% Like plain.tex's \dotfill, except uses up at least 1 em. +% Like plain.tex's \dotfill, except uses up at least 0.5 em. % The filll stretch here overpowers both the fil and fill stretch to push % the page number to the right. \def\indexdotfill{\cleaders - \hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 1em plus 1filll} - + \hbox{$\mathsurround=0pt \mkern1.5mu.\mkern1.5mu$}\hskip 0.5em plus 1filll} \def\primary #1{\line{#1\hfil}} @@ -5794,7 +6008,7 @@ % below is chosen so that the gutter has the same value (well, +-<1pt) % as it did when we hard-coded it. % - % We put the result in a separate register, \doublecolumhsize, so we + % We put the result in a separate register, \doublecolumnhsize, so we % can restore it in \pagesofar, after \hsize itself has (potentially) % been clobbered. % @@ -5903,7 +6117,7 @@ \newbox\balancedcolumns \setbox\balancedcolumns=\vbox{shouldnt see this}% % -% Only called for the last of the double column material. \doublecolumnout +% Only called for the last of the double column material. \doublecolumnout % does the others. \def\balancecolumns{% \setbox0 = \vbox{\unvbox\PAGE}% like \box255 but more efficient, see p.120. @@ -5931,7 +6145,7 @@ }% % Now the left column is in box 1, and the right column in box 3. % - % Check whether the left column has come out higher than the page itself. + % Check whether the left column has come out higher than the page itself. % (Note that we have doubled \vsize for the double columns, so % the actual height of the page is 0.5\vsize). \ifdim2\ht1>\vsize @@ -5963,7 +6177,7 @@ % Chapters, sections, etc. % Let's start with @part. -\outer\parseargdef\part{\partzzz{#1}} +\parseargdef\part{\partzzz{#1}} \def\partzzz#1{% \chapoddpage \null @@ -6189,8 +6403,7 @@ % normally unnmhead0 calls unnumberedzzz: \outer\parseargdef\unnumbered{\unnmhead0{#1}} \def\unnumberedzzz#1{% - \global\secno=0 \global\subsecno=0 \global\subsubsecno=0 - \global\advance\unnumberedno by 1 + \global\advance\unnumberedno by 1 % % Since an unnumbered has no number, no prefix for figures. \global\let\chaplevelprefix = \empty @@ -6228,7 +6441,7 @@ \let\top\unnumbered % Sections. -% +% \outer\parseargdef\numberedsec{\numhead1{#1}} % normally calls seczzz \def\seczzz#1{% \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 @@ -6246,12 +6459,12 @@ % normally calls unnumberedseczzz: \outer\parseargdef\unnumberedsec{\unnmhead1{#1}} \def\unnumberedseczzz#1{% - \global\subsecno=0 \global\subsubsecno=0 \global\advance\secno by 1 - \sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno.\the\secno}% + \global\advance\unnumberedno by 1 + \sectionheading{#1}{sec}{Ynothing}{\the\unnumberedno}% } % Subsections. -% +% % normally calls numberedsubseczzz: \outer\parseargdef\numberedsubsec{\numhead2{#1}} \def\numberedsubseczzz#1{% @@ -6270,13 +6483,12 @@ % normally calls unnumberedsubseczzz: \outer\parseargdef\unnumberedsubsec{\unnmhead2{#1}} \def\unnumberedsubseczzz#1{% - \global\subsubsecno=0 \global\advance\subsecno by 1 - \sectionheading{#1}{subsec}{Ynothing}% - {\the\unnumberedno.\the\secno.\the\subsecno}% + \global\advance\unnumberedno by 1 + \sectionheading{#1}{subsec}{Ynothing}{\the\unnumberedno}% } % Subsubsections. -% +% % normally numberedsubsubseczzz: \outer\parseargdef\numberedsubsubsec{\numhead3{#1}} \def\numberedsubsubseczzz#1{% @@ -6296,9 +6508,8 @@ % normally unnumberedsubsubseczzz: \outer\parseargdef\unnumberedsubsubsec{\unnmhead3{#1}} \def\unnumberedsubsubseczzz#1{% - \global\advance\subsubsecno by 1 - \sectionheading{#1}{subsubsec}{Ynothing}% - {\the\unnumberedno.\the\secno.\the\subsecno.\the\subsubsecno}% + \global\advance\unnumberedno by 1 + \sectionheading{#1}{subsubsec}{Ynothing}{\the\unnumberedno}% } % These macros control what the section commands do, according @@ -6330,6 +6541,10 @@ \parseargdef\subsubheading{\sectionheading{#1}{subsubsec}{Yomitfromtoc}{} \suppressfirstparagraphindent} +% @xrefname - give text with printed name for linking to node and allow +% referencing node, but do not print any heading. +\parseargdef\xrefname{\donoderef{Yomitfromtoc}{#1}}% + % These macros generate a chapter, section, etc. heading only % (including whitespace, linebreaking, etc. around it), % given all the information in convenient, parsed form. @@ -6361,7 +6576,7 @@ \fi } -\parseargdef\setchapternewpage{\csname CHAPPAG#1\endcsname} +\parseargdef\setchapternewpage{\csname CHAPPAG#1\endcsname\HEADINGSon} \def\CHAPPAGoff{% \global\let\contentsalignmacro = \chappager @@ -6378,7 +6593,7 @@ \global\let\pchapsepmacro=\chapoddpage \global\def\HEADINGSon{\HEADINGSdouble}} -\CHAPPAGon +\setchapternewpage on % \chapmacro - Chapter opening. % @@ -6391,6 +6606,16 @@ \def\Yappendixkeyword{Yappendix} \def\Yomitfromtockeyword{Yomitfromtoc} % +% +% Definitions for @thischapter. These can be overridden in translation +% files. +\def\thischapterAppendix{% + \putwordAppendix{} \thischapternum: \thischaptername} + +\def\thischapterChapter{% + \putwordChapter{} \thischapternum: \thischaptername} +% +% \def\chapmacro#1#2#3{% \expandafter\ifx\thisenv\titlepage\else \checkenv{}% chapters, etc., should not start inside an environment. @@ -6413,22 +6638,14 @@ \xdef\currentchapterdefs{% \gdef\noexpand\thischaptername{\the\toks0}% \gdef\noexpand\thischapternum{\appendixletter}% - % \noexpand\putwordAppendix avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thischapter{\noexpand\putwordAppendix{} - \noexpand\thischapternum: - \noexpand\thischaptername}% + \let\noexpand\thischapter\noexpand\thischapterAppendix }% \else \toks0={#1}% \xdef\currentchapterdefs{% \gdef\noexpand\thischaptername{\the\toks0}% \gdef\noexpand\thischapternum{\the\chapno}% - % \noexpand\putwordChapter avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thischapter{\noexpand\putwordChapter{} - \noexpand\thischapternum: - \noexpand\thischaptername}% + \let\noexpand\thischapter\noexpand\thischapterChapter }% \fi\fi\fi % @@ -6449,11 +6666,6 @@ \chapfonts \rm \let\footnote=\errfootnoteheading % give better error message % - % Have to define \currentsection before calling \donoderef, because the - % xref code eventually uses it. On the other hand, it has to be called - % after \pchapsepmacro, or the headline will change too soon. - \gdef\currentsection{#1}% - % % Only insert the separating space if we have a chapter/appendix % number, and don't print the unnumbered ``number''. \ifx\temptype\Ynothingkeyword @@ -6480,7 +6692,7 @@ % been typeset. If the destination for the pdf outline is after the % text, then jumping from the outline may wind up with the text not % being visible, for instance under high magnification. - \donoderef{#2}% + \donoderef{#2}{#1}% % % Typeset the actual heading. \nobreak % Avoid page breaks at the interline glue. @@ -6514,6 +6726,12 @@ \def\subsubsecheadingskip{\subsecheadingskip} \def\subsubsecheadingbreak{\subsecheadingbreak} +% Definition for @thissection. This can be overridden in translation +% files. +\def\thissectionDef{% + \putwordSection{} \thissectionnum: \thissectionname} +% + % Print any size, any type, section title. % @@ -6555,11 +6773,7 @@ \xdef\currentsectiondefs{% \gdef\noexpand\thissectionname{\the\toks0}% \gdef\noexpand\thissectionnum{#4}% - % \noexpand\putwordSection avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thissection{\noexpand\putwordSection{} - \noexpand\thissectionnum: - \noexpand\thissectionname}% + \let\noexpand\thissection\noexpand\thissectionDef }% \fi \else @@ -6568,11 +6782,7 @@ \xdef\currentsectiondefs{% \gdef\noexpand\thissectionname{\the\toks0}% \gdef\noexpand\thissectionnum{#4}% - % \noexpand\putwordSection avoids expanding indigestible - % commands in some of the translations. - \gdef\noexpand\thissection{\noexpand\putwordSection{} - \noexpand\thissectionnum: - \noexpand\thissectionname}% + \let\noexpand\thissection\noexpand\thissectionDef }% \fi \fi\fi\fi @@ -6598,21 +6808,17 @@ \ifx\temptype\Ynothingkeyword \setbox0 = \hbox{}% \def\toctype{unn}% - \gdef\currentsection{#1}% \else\ifx\temptype\Yomitfromtockeyword - % for @headings -- no section number, don't include in toc, - % and don't redefine \currentsection. + % for @headings -- no section number, don't include in toc. \setbox0 = \hbox{}% \def\toctype{omit}% \let\sectionlevel=\empty \else\ifx\temptype\Yappendixkeyword \setbox0 = \hbox{#4\enspace}% \def\toctype{app}% - \gdef\currentsection{#1}% \else \setbox0 = \hbox{#4\enspace}% \def\toctype{num}% - \gdef\currentsection{#1}% \fi\fi\fi % % Write the toc entry (before \donoderef). See comments in \chapmacro. @@ -6620,7 +6826,7 @@ % % Write the node reference (= pdf destination for pdftex). % Again, see comments in \chapmacro. - \donoderef{#3}% + \donoderef{#3}{#1}% % % Interline glue will be inserted when the vbox is completed. % That glue will be a valid breakpoint for the page, since it'll be @@ -6732,18 +6938,95 @@ \input \tocreadfilename } +% process toc file to find the maximum width of the section numbers for +% each chapter +\def\findsecnowidths{% + \begingroup + \setupdatafile + \activecatcodes + \secentryfonts + % Redefinitions + \def\numchapentry##1##2##3##4{% + \def\curchapname{secnowidth-##2}% + \curchapmax=0pt + }% + \let\appentry\numchapentry + % + \def\numsecentry##1##2##3##4{% + \def\cursecname{secnowidth-##2}% + \cursecmax=0pt + % + \setbox0=\hbox{##2}% + \ifdim\wd0>\curchapmax + \curchapmax=\wd0 + \expandafter\xdef\csname\curchapname\endcsname{\the\wd0}% + \fi + }% + \let\appsecentry\numsecentry + % + \def\numsubsecentry##1##2##3##4{% + \def\curssecname{secnowidth-##2}% + \curssecmax=0pt + % + \setbox0=\hbox{##2}% + \ifdim\wd0>\cursecmax + \cursecmax=\wd0 + \expandafter\xdef\csname\cursecname\endcsname{\the\wd0}% + \fi + }% + \let\appsubsecentry\numsubsecentry + % + \def\numsubsubsecentry##1##2##3##4{% + \setbox0=\hbox{##2}% + \ifdim\wd0>\curssecmax + \curssecmax=\wd0 + \expandafter\xdef\csname\curssecname\endcsname{\the\wd0}% + \fi + }% + \let\appsubsubsecentry\numsubsubsecentry + % + % Discard any output by outputting to dummy vbox, in case the toc file + % contains macros that we have not redefined above. + \setbox\dummybox\vbox\bgroup + \input \tocreadfilename\relax + \egroup + \endgroup +} +\newdimen\curchapmax +\newdimen\cursecmax +\newdimen\curssecmax + + +% set #1 to the maximum section width for #2 +\def\retrievesecnowidth#1#2{% + \expandafter\let\expandafter\savedsecnowidth \csname secnowidth-#2\endcsname + \ifx\savedsecnowidth\relax + #1=0pt + \else + #1=\savedsecnowidth + \fi +} +\newdimen\secnowidthchap +\secnowidthchap=0pt +\newdimen\secnowidthsec +\secnowidthsec=0pt +\newdimen\secnowidthssec +\secnowidthssec=0pt + + \newskip\contentsrightmargin \contentsrightmargin=1in \newcount\savepageno \newcount\lastnegativepageno \lastnegativepageno = -1 % Prepare to read what we've written to \tocfile. % -\def\startcontents#1{% +\def\startcontents#1#2{% % If @setchapternewpage on, and @headings double, the contents should % start on an odd page, unlike chapters. \contentsalignmacro \immediate\closeout\tocfile % + #2% % Don't need to put `Contents' or `Short Contents' in the headline. % It is abundantly clear what they are. \chapmacro{#1}{Yomitfromtoc}{}% @@ -6758,8 +7041,14 @@ \def\thistitle{}% no title in double-sided headings % Record where the Roman numerals started. \ifnum\romancount=0 \global\romancount=\pagecount \fi + \linkentrytexttrue } +% \raggedbottom in plain.tex hardcodes \topskip so override it +\catcode`\@=11 +\def\raggedbottom{\advance\topskip by 0pt plus30pt \r@ggedbottomtrue} +\catcode`\@=\other + % redefined for the two-volume lispref. We always output on % \jobname.toc even if this is redefined. % @@ -6768,9 +7057,12 @@ % Normal (long) toc. % \def\contents{% - \startcontents{\putwordTOC}% + \startcontents{\putwordTOC}{\contentsmkdest}% + \ifxetex\xetexpreauxfile\fi + \penalty2 % mark beginning of contents \openin 1 \tocreadfilename\space \ifeof 1 \else + \findsecnowidths \readtocfile \fi \vfill \eject @@ -6779,13 +7071,18 @@ \pdfmakeoutlines \fi \closein 1 + \ifxetex\xetexpostauxfile\fi \endgroup \contentsendroman } +\def\contentsmkdest{% + \pdfmkdest{txi.CONTENTS}% +} + % And just the chapters. \def\summarycontents{% - \startcontents{\putwordShortTOC}% + \startcontents{\putwordShortTOC}{}% % \let\partentry = \shortpartentry \let\numchapentry = \shortchapentry @@ -6798,6 +7095,7 @@ \rm \hyphenpenalty = 10000 \advance\baselineskip by 1pt % Open it up a little. + \extrasecnoskip=0.4pt \def\numsecentry##1##2##3##4{} \let\appsecentry = \numsecentry \let\unnsecentry = \numsecentry @@ -6807,11 +7105,13 @@ \let\numsubsubsecentry = \numsecentry \let\appsubsubsecentry = \numsecentry \let\unnsubsubsecentry = \numsecentry + \ifxetex\xetexpreauxfile\fi \openin 1 \tocreadfilename\space \ifeof 1 \else \readtocfile \fi \closein 1 + \ifxetex\xetexpostauxfile\fi \vfill \eject \contentsalignmacro % in case @setchapternewpage odd is in effect \endgroup @@ -6822,12 +7122,8 @@ % Get ready to use Arabic numerals again \def\contentsendroman{% \lastnegativepageno = \pageno - \global\pageno = \savepageno - % - % If \romancount > \arabiccount, the contents are at the end of the - % document. Otherwise, advance where the Arabic numerals start for - % the page numbers. - \ifnum\romancount>\arabiccount\else\global\arabiccount=\pagecount\fi + \global\pageno=1 + \contentsendcount = \pagecount } % Typeset the label for a chapter or appendix for the short contents. @@ -6837,8 +7133,6 @@ % This space should be enough, since a single number is .5em, and the % widest letter (M) is 1em, at least in the Computer Modern fonts. % But use \hss just in case. - % (This space doesn't include the extra space that gets added after - % the label; that gets put in by \shortchapentry above.) % % We'd like to right-justify chapter numbers, but that looks strange % with appendix letters. And right-justifying numbers and @@ -6848,39 +7142,55 @@ \hbox to 1em{#1\hss}% } -% These macros generate individual entries in the table of contents. -% The first argument is the chapter or section name. -% The last argument is the page number. -% The arguments in between are the chapter number, section number, ... +% These macros generate individual entries in the table of contents, +% and are read in from the *.toc file. +% +% The arguments are like: +% \def\numchapentry#1#2#3#4 +% #1 - the chapter or section name. +% #2 - section number +% #3 - level of section (e.g "chap", "sec") +% #4 - page number -% Parts, in the main contents. Replace the part number, which doesn't -% exist, with an empty box. Let's hope all the numbers have the same width. -% Also ignore the page number, which is conventionally not printed. -\def\numeralbox{\setbox0=\hbox{8}\hbox to \wd0{\hfil}} +% Parts, in the main contents. Ignore the page number, which is +% conventionally not printed. \def\partentry#1#2#3#4{% + \ifnum\lastpenalty = 2 + % use less space if at very first entry of contents + \vskip 1\baselineskip plus .33\baselineskip minus .25\baselineskip + \else + \vskip 2\baselineskip plus .66\baselineskip minus .5\baselineskip + \fi % Add stretch and a bonus for breaking the page before the part heading. % This reduces the chance of the page being broken immediately after the % part heading, before a following chapter heading. - \vskip 0pt plus 5\baselineskip + \vskip 0pt plus 3\baselineskip \penalty-300 - \vskip 0pt plus -5\baselineskip - \dochapentry{\numeralbox\labelspace#1}{}% + \vskip 0pt plus -3\baselineskip + \begingroup + \secfonts \rm + \entryinternal{#1}{}% + \endgroup + \afterpartentrytrue } +\newif\ifafterpartentry % % Parts, in the short toc. \def\shortpartentry#1#2#3#4{% \penalty-300 \vskip.5\baselineskip plus.15\baselineskip minus.1\baselineskip - \shortchapentry{{\bf #1}}{\numeralbox}{}{}% + \tocentry{{\bf #1}}{}{}{}% } % Chapters, in the main contents. -\def\numchapentry#1#2#3#4{\dochapentry{#2\labelspace#1}{#4}} +\def\numchapentry#1#2#3#4{% + \retrievesecnowidth\secnowidthchap{#2}% + \dochapentry{#1}{#2}{#3}{#4}% +} % Chapters, in the short toc. -% See comments in \dochapentry re vbox and related settings. \def\shortchapentry#1#2#3#4{% - \tocentry{\shortchaplabel{#2}\labelspace #1}{\doshortpageno\bgroup#4\egroup}% + \tocentry{#1}{\shortchaplabel{#2}}{#3}{#4}% } % Appendices, in the main contents. @@ -6891,70 +7201,119 @@ \setbox0 = \hbox{\putwordAppendix{} M}% \hbox to \wd0{\putwordAppendix{} #1\hss}} % -\def\appentry#1#2#3#4{\dochapentry{\appendixbox{#2}\hskip.7em#1}{#4}} +\def\appentry#1#2#3#4{% + \retrievesecnowidth\secnowidthchap{#2}% + \dochapentry{\appendixbox{#2}\hskip.7em#1}{}{#3}{#4}% +} % Unnumbered chapters. -\def\unnchapentry#1#2#3#4{\dochapentry{#1}{#4}} -\def\shortunnchapentry#1#2#3#4{\tocentry{#1}{\doshortpageno\bgroup#4\egroup}} +\def\unnchapentry#1#2#3#4{\dochapentry{#1}{}{#3}{#4}} +\def\shortunnchapentry#1#2#3#4{\tocentry{#1}{}{#3}{#4}} % Sections. -\def\numsecentry#1#2#3#4{\dosecentry{#2\labelspace#1}{#4}} +\def\numsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthsec{#2}% + \dosecentry{#1}{#2}{#3}{#4}% +} \let\appsecentry=\numsecentry -\def\unnsecentry#1#2#3#4{\dosecentry{#1}{#4}} +\def\unnsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthsec{#2}% + \dosecentry{#1}{}{#3}{#4}% +} % Subsections. -\def\numsubsecentry#1#2#3#4{\dosubsecentry{#2\labelspace#1}{#4}} +\def\numsubsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthssec{#2}% + \dosubsecentry{#1}{#2}{#3}{#4}% +} \let\appsubsecentry=\numsubsecentry -\def\unnsubsecentry#1#2#3#4{\dosubsecentry{#1}{#4}} +\def\unnsubsecentry#1#2#3#4{% + \retrievesecnowidth\secnowidthssec{#2}% + \dosubsecentry{#1}{}{#3}{#4}% +} % And subsubsections. -\def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#2\labelspace#1}{#4}} +\def\numsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#2}{#3}{#4}} \let\appsubsubsecentry=\numsubsubsecentry -\def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{#4}} +\def\unnsubsubsecentry#1#2#3#4{\dosubsubsecentry{#1}{}{#3}{#4}} % This parameter controls the indentation of the various levels. % Same as \defaultparindent. \newdimen\tocindent \tocindent = 15pt -% Now for the actual typesetting. In all these, #1 is the text and #2 is the -% page number. +% Now for the actual typesetting. In all these, #1 is the text, #2 is +% a section number if present, #3 is the node, and #4 is the page number. % % If the toc has to be broken over pages, we want it to be at chapters % if at all possible; hence the \penalty. -\def\dochapentry#1#2{% - \penalty-300 \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip +\def\dochapentry#1#2#3#4{% + \ifafterpartentry + \afterpartentryfalse + \penalty5000 + \else + \penalty-300 + \fi + \vskip1\baselineskip plus.33\baselineskip minus.25\baselineskip \begingroup % Move the page numbers slightly to the right \advance\entryrightmargin by -0.05em \chapentryfonts - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \extrasecnoskip=0.4em % separate chapter number more + \tocentry{#1}{#2}{#3}{#4}% \endgroup \nobreak\vskip .25\baselineskip plus.1\baselineskip } -\def\dosecentry#1#2{\begingroup +\def\dosecentry#1#2#3#4{\begingroup + \secnowidth=\secnowidthchap \secentryfonts \leftskip=\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \tocentry{#1}{#2}{#3}{#4}% \endgroup} -\def\dosubsecentry#1#2{\begingroup +\def\dosubsecentry#1#2#3#4{\begingroup + \secnowidth=\secnowidthsec \subsecentryfonts \leftskip=2\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \tocentry{#1}{#2}{#3}{#4}% \endgroup} -\def\dosubsubsecentry#1#2{\begingroup +\def\dosubsubsecentry#1#2#3#4{\begingroup + \secnowidth=\secnowidthssec \subsubsecentryfonts \leftskip=3\tocindent - \tocentry{#1}{\dopageno\bgroup#2\egroup}% + \tocentry{#1}{#2}{#3}{#4}% \endgroup} -% We use the same \entry macro as for the index entries. -\let\tocentry = \entry +% Used for the maximum width of a section number so we can align +% section titles. +\newdimen\secnowidth +\secnowidth=0pt +\newdimen\extrasecnoskip +\extrasecnoskip=0pt -% Space between chapter (or whatever) number and the title. -\def\labelspace{\hskip1em \relax} +\let\tocnodetarget\empty +\let\entrypagetarget\empty -\def\dopageno#1{{\rm #1}} -\def\doshortpageno#1{{\rm #1}} +% \tocentry{TITLE}{SEC NO}{NODE}{PAGE} +% +\def\tocentry#1#2#3#4{% + \def\tocnodetarget{#3}% + \def\secno{#2}% + \ifx\empty\secno + \entryinternal{#1}{#4}% + \else + \ifdim 0pt=\secnowidth + \setbox0=\hbox{#2\hskip\labelspace\hskip\extrasecnoskip}% + \else + \advance\secnowidth by \labelspace + \advance\secnowidth by \extrasecnoskip + \setbox0=\hbox to \secnowidth{% + #2\hskip\labelspace\hskip\extrasecnoskip\hfill}% + \fi + \entrycontskip=\wd0 + \entryinternal{\box0 #1}{#4}% + \fi +} +\newdimen\labelspace +\labelspace=0.6em \def\chapentryfonts{\secfonts \rm} \def\secentryfonts{\textfonts} @@ -7100,19 +7459,25 @@ \newdimen\cartouter\newdimen\cartinner \newskip\normbskip\newskip\normpskip\newskip\normlskip - -\envdef\cartouche{% +\envparseargdef\cartouche{% \cartouchefontdefs \ifhmode\par\fi % can't be in the midst of a paragraph. \startsavinginserts \lskip=\leftskip \rskip=\rightskip \leftskip=0pt\rightskip=0pt % we want these *outside*. + % + % Set paragraph width for text inside cartouche. There are + % left and right margins of 3pt each plus two vrules 0.4pt each. \cartinner=\hsize \advance\cartinner by-\lskip \advance\cartinner by-\rskip + \advance\cartinner by -6.8pt + % + % For drawing top and bottom of cartouche. Each corner char + % adds 6pt and we take off the width of a rule to line up with the + % right boundary perfectly. \cartouter=\hsize - \advance\cartouter by 18.4pt % allow for 3pt kerns on either - % side, and for 6pt waste from - % each corner char, and rule thickness + \advance\cartouter by 11.6pt + % \normbskip=\baselineskip \normpskip=\parskip \normlskip=\lineskip % % If this cartouche directly follows a sectioning command, we need the @@ -7120,20 +7485,23 @@ % collide with the section heading. \ifnum\lastpenalty>10000 \vskip\parskip \penalty\lastpenalty \fi % - \setbox\groupbox=\vbox\bgroup + \setbox\groupbox=\vtop\bgroup \baselineskip=0pt\parskip=0pt\lineskip=0pt \carttop \hbox\bgroup - \hskip\lskip - \vrule\kern3pt - \vbox\bgroup - \kern3pt - \hsize=\cartinner - \baselineskip=\normbskip - \lineskip=\normlskip - \parskip=\normpskip - \vskip -\parskip - \comment % For explanation, see the end of def\group. + \hskip\lskip + \vrule\kern3pt + \vbox\bgroup + \hsize=\cartinner + \baselineskip=\normbskip + \lineskip=\normlskip + \parskip=\normpskip + \def\arg{#1}% + \ifx\arg\empty\else + \centerV{\hfil \bf #1 \hfil}% + \fi + \kern3pt + \vskip -\parskip } \def\Ecartouche{% \ifhmode\par\fi @@ -7287,22 +7655,6 @@ } \let\Eraggedright\par -\envdef\raggedleft{% - \parindent=0pt \leftskip0pt plus2em - \spaceskip.3333em \xspaceskip.5em \parfillskip=0pt - \hbadness=10000 % Last line will usually be underfull, so turn off - % badness reporting. -} -\let\Eraggedleft\par - -\envdef\raggedcenter{% - \parindent=0pt \rightskip0pt plus1em \leftskip0pt plus1em - \spaceskip.3333em \xspaceskip.5em \parfillskip=0pt - \hbadness=10000 % Last line will usually be underfull, so turn off - % badness reporting. -} -\let\Eraggedcenter\par - % @quotation does normal linebreaking (hence we can't use \nonfillstart) % and narrows the margins. We keep \parskip nonzero in general, since @@ -7342,7 +7694,7 @@ % @indentedblock is like @quotation, but indents only on the left and % has no optional argument. -% +% \makedispenvdef{indentedblock}{\indentedblockstart} % \def\indentedblockstart{% @@ -7400,8 +7752,9 @@ \endgroup % \def\setupverb{% - \tt % easiest (and conventionally used) font for verbatim + \tt \def\par{\leavevmode\endgraf}% + \parindent = 0pt \setcodequotes \tabeightspaces % Respect line breaks, @@ -7525,9 +7878,12 @@ % file; b) letting users define the frontmatter in as flexible order as % possible is desirable. % -\def\copying{\checkenv{}\begingroup\scanargctxt\docopying} -\def\docopying#1@end copying{\endgroup\def\copyingtext{#1}} -% +\def\copying{\checkenv{}\begingroup\macrobodyctxt\docopying} +{\catcode`\ =\other +\gdef\docopying#1@end copying{\endgroup\def\copyingtext{#1}} +} +\let\copyingtext\relax + \def\insertcopying{% \begingroup \parindent = 0pt % paragraph indentation looks wrong on title page @@ -7535,6 +7891,18 @@ \endgroup } +\def\publication{\checkenv{}\begingroup\macrobodyctxt\dopublication} +{\catcode`\ =\other +\gdef\dopublication#1@end publication{\endgroup\def\publicationtext{#1}} +} +\let\publicationtext\relax + +\def\insertpublication{% + \begingroup + \parindent = 0pt % paragraph indentation looks wrong on title page + \scanexp\publicationtext + \endgroup +} \message{defuns,} % @defun etc. @@ -7575,31 +7943,19 @@ \exdentamount=\defbodyindent } -\def\dodefunx#1{% - % First, check whether we are in the right environment: - \checkenv#1% - % - % As above, allow line break if we have multiple x headers in a row. - % It's not a great place, though. - \ifnum\lastpenalty=10002 \penalty3000 \else \defunpenalty=10002 \fi - % - % And now, it's time to reuse the body of the original defun: - \expandafter\gobbledefun#1% -} -\def\gobbledefun#1\startdefun{} - -% \printdefunline \deffnheader{text} +% Called as \printdefunline \deffooheader{text} % \def\printdefunline#1#2{% \begingroup - % call \deffnheader: + \plainfrenchspacing + % call \deffooheader: #1#2 \endheader % common ending: \interlinepenalty = 10000 \advance\rightskip by 0pt plus 1fil\relax \endgraf \nobreak\vskip -\parskip - \penalty\defunpenalty % signal to \startdefun and \dodefunx + \penalty\defunpenalty % signal to \startdefun and \deffoox % Some of the @defun-type tags do not enable magic parentheses, % rendering the following check redundant. But we don't optimize. \checkparencounts @@ -7608,29 +7964,55 @@ \def\Edefun{\endgraf\medbreak} -% \makedefun{deffn} creates \deffn, \deffnx and \Edeffn; -% the only thing remaining is to define \deffnheader. +% @defblock, @defline do not automatically create index entries +\envdef\defblock{% + \startdefun +} +\let\Edefblock\Edefun + +\def\defline{% + \doingtypefnfalse + \parseargusing\activeparens{\printdefunline\deflineheader}% +} +\def\deflineheader#1 #2 #3\endheader{% + \printdefname{#1}{}{#2}\magicamp\defunargs{#3\unskip}% +} + +\def\deftypeline{% + \doingtypefntrue + \parseargusing\activeparens{\printdefunline\deftypelineheader}% +} +\def\deftypelineheader#1 #2 #3 #4\endheader{% + \printdefname{#1}{#2}{#3}\magicamp\defunargs{#4\unskip}% +} + +% \makedefun{deffoo} (\deffooheader parameters) { (\deffooheader expansion) } % +% Define \deffoo, \deffoox \Edeffoo and \deffooheader. \def\makedefun#1{% \expandafter\let\csname E#1\endcsname = \Edefun \edef\temp{\noexpand\domakedefun \makecsname{#1}\makecsname{#1x}\makecsname{#1header}}% \temp } - -% \domakedefun \deffn \deffnx \deffnheader { (defn. of \deffnheader) } -% -% Define \deffn and \deffnx, without parameters. -% \deffnheader has to be defined explicitly. -% \def\domakedefun#1#2#3{% \envdef#1{% \startdefun \doingtypefnfalse % distinguish typed functions from all else \parseargusing\activeparens{\printdefunline#3}% }% - \def#2{\dodefunx#1}% - \def#3% + \def#2{% + % First, check whether we are in the right environment: + \checkenv#1% + % + % As in \startdefun, allow line break if we have multiple x headers + % in a row. It's not a great place, though. + \ifnum\lastpenalty=10002 \penalty3000 \else \defunpenalty=10002 \fi + % + \doingtypefnfalse % distinguish typed functions from all else + \parseargusing\activeparens{\printdefunline#3}% + }% + \def#3% definition of \deffooheader follows } \newif\ifdoingtypefn % doing typed function? @@ -7639,7 +8021,7 @@ % @deftypefnnewline on|off says whether the return type of typed functions % are printed on their own line. This affects @deftypefn, @deftypefun, % @deftypeop, and @deftypemethod. -% +% \parseargdef\deftypefnnewline{% \def\temp{#1}% \ifx\temp\onword @@ -7655,74 +8037,51 @@ \fi\fi } -% \dosubind {index}{topic}{subtopic} -% -% If SUBTOPIC is present, precede it with a space, and call \doind. -% (At some time during the 20th century, this made a two-level entry in an -% index such as the operation index. Nobody seemed to notice the change in -% behaviour though.) -\def\dosubind#1#2#3{% - \def\thirdarg{#3}% - \ifx\thirdarg\empty - \doind{#1}{#2}% - \else - \doind{#1}{#2\space#3}% - \fi -} - % Untyped functions: % @deffn category name args -\makedefun{deffn}{\deffngeneral{}} - -% @deffn category class name args -\makedefun{defop}#1 {\defopon{#1\ \putwordon}} - -% \defopon {category on}class name args -\def\defopon#1#2 {\deffngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} } +\makedefun{deffn}#1 #2 #3\endheader{% + \doind{fn}{\code{#2}}% + \printdefname{#1}{}{#2}\magicamp\defunargs{#3\unskip}% +} -% \deffngeneral {subind}category name args -% -\def\deffngeneral#1#2 #3 #4\endheader{% - \dosubind{fn}{\code{#3}}{#1}% - \defname{#2}{}{#3}\magicamp\defunargs{#4\unskip}% +% @defop category class name args +\makedefun{defop}#1 {\defopheaderx{#1\ \putwordon}} +\def\defopheaderx#1#2 #3 #4\endheader{% + \doind{fn}{\code{#3}\space\putwordon\ \code{#2}}% + \printdefname{#1\ \code{#2}}{}{#3}\magicamp\defunargs{#4\unskip}% } % Typed functions: % @deftypefn category type name args -\makedefun{deftypefn}{\deftypefngeneral{}} +\makedefun{deftypefn}#1 #2 #3 #4\endheader{% + \doind{fn}{\code{#3}}% + \doingtypefntrue + \printdefname{#1}{#2}{#3}\defunargs{#4\unskip}% +} % @deftypeop category class type name args -\makedefun{deftypeop}#1 {\deftypeopon{#1\ \putwordon}} - -% \deftypeopon {category on}class type name args -\def\deftypeopon#1#2 {\deftypefngeneral{\putwordon\ \code{#2}}{#1\ \code{#2}} } - -% \deftypefngeneral {subind}category type name args -% -\def\deftypefngeneral#1#2 #3 #4 #5\endheader{% - \dosubind{fn}{\code{#4}}{#1}% +\makedefun{deftypeop}#1 {\deftypeopheaderx{#1\ \putwordon}} +\def\deftypeopheaderx#1#2 #3 #4 #5\endheader{% + \doind{fn}{\code{#4}\space\putwordon\ \code{#1\ \code{#2}}}% \doingtypefntrue - \defname{#2}{#3}{#4}\defunargs{#5\unskip}% + \printdefname{#1\ \code{#2}}{#3}{#4}\defunargs{#5\unskip}% } % Typed variables: % @deftypevr category type var args -\makedefun{deftypevr}{\deftypecvgeneral{}} +\makedefun{deftypevr}#1 #2 #3 #4\endheader{% + \doind{vr}{\code{#3}}% + \printdefname{#1}{#2}{#3}\defunargs{#4\unskip}% +} % @deftypecv category class type var args -\makedefun{deftypecv}#1 {\deftypecvof{#1\ \putwordof}} - -% \deftypecvof {category of}class type var args -\def\deftypecvof#1#2 {\deftypecvgeneral{\putwordof\ \code{#2}}{#1\ \code{#2}} } - -% \deftypecvgeneral {subind}category type var args -% -\def\deftypecvgeneral#1#2 #3 #4 #5\endheader{% - \dosubind{vr}{\code{#4}}{#1}% - \defname{#2}{#3}{#4}\defunargs{#5\unskip}% +\makedefun{deftypecv}#1 {\deftypecvheaderx{#1\ \putwordof}} +\def\deftypecvheaderx#1#2 #3 #4 #5\endheader{% + \doind{vr}{\code{#4}\space\putwordof\ \code{#2}}% + \printdefname{#1\ \code{#2}}{#3}{#4}\defunargs{#5\unskip}% } % Untyped variables: @@ -7731,17 +8090,15 @@ \makedefun{defvr}#1 {\deftypevrheader{#1} {} } % @defcv category class var args -\makedefun{defcv}#1 {\defcvof{#1\ \putwordof}} - -% \defcvof {category of}class var args -\def\defcvof#1#2 {\deftypecvof{#1}#2 {} } +\makedefun{defcv}#1 {\defcvheaderx{#1\ \putwordof}} +\def\defcvheaderx#1#2 {\deftypecvheaderx{#1}#2 {} } % Types: % @deftp category name args \makedefun{deftp}#1 #2 #3\endheader{% \doind{tp}{\code{#2}}% - \defname{#1}{}{#2}\defunargs{#3\unskip}% + \printdefname{#1}{}{#2}\defunargs{#3\unskip}% } % Remaining @defun-like shortcuts: @@ -7752,19 +8109,19 @@ \makedefun{defvar}{\defvrheader{\putwordDefvar} } \makedefun{defopt}{\defvrheader{\putwordDefopt} } \makedefun{deftypevar}{\deftypevrheader{\putwordDefvar} } -\makedefun{defmethod}{\defopon\putwordMethodon} -\makedefun{deftypemethod}{\deftypeopon\putwordMethodon} -\makedefun{defivar}{\defcvof\putwordInstanceVariableof} -\makedefun{deftypeivar}{\deftypecvof\putwordInstanceVariableof} +\makedefun{defmethod}{\defopheaderx\putwordMethodon} +\makedefun{deftypemethod}{\deftypeopheaderx\putwordMethodon} +\makedefun{defivar}{\defcvheaderx\putwordInstanceVariableof} +\makedefun{deftypeivar}{\deftypecvheaderx\putwordInstanceVariableof} -% \defname, which formats the name of the @def (not the args). +% \printdefname, which formats the name of the @def (not the args). % #1 is the category, such as "Function". % #2 is the return type, if any. % #3 is the function name. % % We are followed by (but not passed) the arguments, if any. % -\def\defname#1#2#3{% +\def\printdefname#1#2#3{% \par % Get the values of \leftskip and \rightskip as they were outside the @def... \advance\leftskip by -\defbodyindent @@ -7774,9 +8131,7 @@ \rettypeownlinefalse \ifdoingtypefn % doing a typed function specifically? % then check user option for putting return type on its own line: - \expandafter\ifx\csname SETtxideftypefnnl\endcsname\relax \else - \rettypeownlinetrue - \fi + \ifflagclear{txideftypefnnl}{}{\rettypeownlinetrue}% \fi % % How we'll format the category name. Putting it in brackets helps @@ -7820,6 +8175,8 @@ \tolerance=10000 \hbadness=10000 \exdentamount=\defbodyindent {% + \def\^^M{}% for line continuation + % % defun fonts. We use typewriter by default (used to be bold) because: % . we're printing identifiers, they should be in tt in principle. % . in languages with many accents, such as Czech or French, it's @@ -7834,37 +8191,33 @@ \tclose{\temp}% typeset the return type \ifrettypeownline % put return type on its own line; prohibit line break following: - \hfil\vadjust{\nobreak}\break + \hfil\vadjust{\nobreak}\break \else \space % type on same line, so just followed by a space \fi \fi % no return type #3% output function name }% - {\rm\enskip}% hskip 0.5 em of \rmfont + \ifflagclear{txidefnamenospace}{% + {\rm\enskip}% hskip 0.5 em of \rmfont + }{}% % - \boldbrax + \parenbrackglyphs % arguments will be output next, if any. } -% Print arguments in slanted roman (not ttsl), inconsistently with using -% tt for the name. This is because literal text is sometimes needed in -% the argument list (groff manual), and ttsl and tt are not very -% distinguishable. Prevent hyphenation at `-' chars. -% +% Print arguments. Use slanted for @def*, typewriter for @deftype*. \def\defunargs#1{% - % use sl by default (not ttsl), - % tt for the names. - \df \sl \hyphenchar\font=0 - % - % On the other hand, if an argument has two dashes (for instance), we - % want a way to get ttsl. We used to recommend @var for that, so - % leave the code in, but it's strange for @var to lead to typewriter. - % Nowadays we recommend @code, since the difference between a ttsl hyphen - % and a tt hyphen is pretty tiny. @code also disables ?` !`. - \def\var##1{{\setregularquotes\ttslanted{##1}}}% - #1% - \sl\hyphenchar\font=45 + \bgroup + \def\^^M{}% for line continuation + \df \ifdoingtypefn \tt \else \sl \fi + \ifflagclear{txicodevaristt}{}% + % use \ttsl for @var in both @def* and @deftype*. + % the kern prevents an italic correction at end, which appears + % too much for ttsl. + {\def\var##1{{\setregularquotes \ttsl ##1\kern 0pt }}}% + #1% + \egroup } % We want ()&[] to print specially on the defun line. @@ -7879,57 +8232,40 @@ \let\lparen = ( \let\rparen = ) % Be sure that we always have a definition for `(', etc. For example, -% if the fn name has parens in it, \boldbrax will not be in effect yet, -% so TeX would otherwise complain about undefined control sequence. +% if the fn name has parens in it, \parenbrackglyphs will not be in +% effect yet, so TeX would otherwise complain about undefined control +% sequence. { \activeparens - \global\let(=\lparen \global\let)=\rparen - \global\let[=\lbrack \global\let]=\rbrack - \global\let& = \& + \gdef\defcharsdefault{% + \let(=\lparen \let)=\rparen + \let[=\lbrack \let]=\rbrack + \let& = \&% + } + \globaldefs=1 \defcharsdefault - \gdef\boldbrax{\let(=\opnr\let)=\clnr\let[=\lbrb\let]=\rbrb} + \gdef\parenbrackglyphs{\let(=\opnr\let)=\cpnr\let[=\lbrb\let]=\rbrb} \gdef\magicamp{\let&=\amprm} } \let\ampchar\& -\newcount\parencount - -% If we encounter &foo, then turn on ()-hacking afterwards -\newif\ifampseen -\def\amprm#1 {\ampseentrue{\bf\ }} - -\def\parenfont{% - \ifampseen - % At the first level, print parens in roman, - % otherwise use the default font. - \ifnum \parencount=1 \rm \fi - \else - % The \sf parens (in \boldbrax) actually are a little bolder than - % the contained text. This is especially needed for [ and ] . - \sf - \fi -} -\def\infirstlevel#1{% - \ifampseen - \ifnum\parencount=1 - #1% - \fi - \fi -} -\def\bfafterword#1 {#1 \bf} +\def\amprm#1 {{\rm\ }} +\newcount\parencount +% opening and closing parentheses in roman font \def\opnr{% + \ptexslash % italic correction \global\advance\parencount by 1 - {\parenfont(}% - \infirstlevel \bfafterword + {\sf(}% } -\def\clnr{% - {\parenfont)}% - \infirstlevel \sl +\def\cpnr{% + \ptexslash % italic correction + {\sf)}% \global\advance\parencount by -1 } \newcount\brackcount +% left and right square brackets in bold font \def\lbrb{% \global\advance\brackcount by 1 {\bf[}% @@ -7971,24 +8307,17 @@ } \fi -\let\E=\expandafter - % Used at the time of macro expansion. % Argument is macro body with arguments substituted \def\scanmacro#1{% \newlinechar`\^^M - % expand the expansion of \eatleadingcr twice to maybe remove a leading - % newline (and \else and \fi tokens), then call \eatspaces on the result. - \def\xeatspaces##1{% - \E\E\E\E\E\E\E\eatspaces\E\E\E\E\E\E\E{\eatleadingcr##1% - }}% - \def\xempty##1{}% + \def\xeatspaces##1{\eatleadingcrthen\eatspaces{##1}}% % % Process the macro body under the current catcode regime. \scantokens{#1@comment}% % % The \comment is to remove the \newlinechar added by \scantokens, and - % can be noticed by \parsearg. Note \c isn't used because this means cedilla + % can be noticed by \parsearg. Note \c isn't used because this means cedilla % in math mode. } @@ -8035,10 +8364,12 @@ \unbrace{\gdef\trim@@@ #1 } #2@{#1} } -{\catcode`\^^M=\other% -\gdef\eatleadingcr#1{\if\noexpand#1\noexpand^^M\else\E#1\fi}}% -% Warning: this won't work for a delimited argument -% or for an empty argument +% Trim a single leading ^^M off a string, then call #1 +{\catcode`\^^M=\active \catcode`\Q=3% +\gdef\eatleadingcrthen #1#2{\eatlcra #1Q#2Q^^MQ}% +\gdef\eatlcra #1#2Q^^M{\eatlcrb #1#2Q}% +\gdef\eatlcrb #1Q#2Q#3Q{#1{#2}}% +} % Trim a single trailing ^^M off a string. {\catcode`\^^M=\other \catcode`\Q=3% @@ -8069,24 +8400,17 @@ \catcode`\_=\other \catcode`\|=\other \catcode`\~=\other - \passthroughcharstrue -} - -\def\scanargctxt{% used for copying and captions, not macros. - \scanctxt \catcode`\@=\other - \catcode`\\=\other \catcode`\^^M=\other + \catcode`\\=\active + \passthroughcharstrue } -\def\macrobodyctxt{% used for @macro definitions +\def\macrobodyctxt{% used for @macro definitions and @copying \scanctxt \catcode`\ =\other - \catcode`\@=\other \catcode`\{=\other \catcode`\}=\other - \catcode`\^^M=\other - \usembodybackslash } % Used when scanning braced macro arguments. Note, however, that catcode @@ -8095,14 +8419,10 @@ \def\macroargctxt{% \scanctxt \catcode`\ =\active - \catcode`\@=\other - \catcode`\^^M=\other - \catcode`\\=\active } \def\macrolineargctxt{% used for whole-line arguments without braces \scanctxt - \catcode`\@=\other \catcode`\{=\other \catcode`\}=\other } @@ -8146,7 +8466,7 @@ \global\expandafter\let\csname ismacro.\the\macname\endcsname=1% \addtomacrolist{\the\macname}% \fi - \begingroup \macrobodyctxt + \begingroup \macrobodyctxt \usembodybackslash \ifrecursive \expandafter\parsermacbody \else \expandafter\parsemacbody \fi} @@ -8161,8 +8481,6 @@ \let\commondummyword\unmacrodo \xdef\macrolist{\macrolist}% \endgroup - \else - \errmessage{Macro #1 not defined}% \fi } @@ -8187,6 +8505,10 @@ % <parameter list> is #, then the preceding argument is delimited by % an opening brace, and that opening brace is not consumed. +% Make @ a letter, so that we can make private-to-Texinfo macro names. +\edef\texiatcatcode{\the\catcode`\@} +\catcode `@=11\relax + % Parse the optional {params} list to @macro or @rmacro. % Set \paramno to the number of arguments, % and \paramlist to a parameter text for the macro (e.g. #1,#2,#3 for a @@ -8194,19 +8516,18 @@ % list to some hook where the argument is to be expanded. If there are % less than 10 arguments that hook is to be replaced by ##N where N % is the position in that list, that is to say the macro arguments are to be -% defined `a la TeX in the macro body. +% defined `a la TeX in the macro body. % % That gets used by \mbodybackslash (above). % % If there are 10 or more arguments, a different technique is used: see -% \parsemmanyargdef. +% \parsemmanyargdef@@. % \def\parsemargdef#1;{% \paramno=0\def\paramlist{}% \let\hash\relax % \hash is redefined to `#' later to get it into definitions \let\xeatspaces\relax - \let\xempty\relax \parsemargdefxxx#1,;,% \ifnum\paramno<10\relax\else \paramno0\relax @@ -8218,29 +8539,25 @@ \else \let\next=\parsemargdefxxx \advance\paramno by 1 \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname - {\xeatspaces{\hash\the\paramno\noexpand\xempty{}}}% + {\xeatspaces{\hash\the\paramno}}% \edef\paramlist{\paramlist\hash\the\paramno,}% \fi\next} -% the \xempty{} is to give \eatleadingcr an argument in the case of an -% empty macro argument. % \parsemacbody, \parsermacbody % % Read recursive and nonrecursive macro bodies. (They're different since % rec and nonrec macros end differently.) -% -% We are in \macrobodyctxt, and the \xdef causes backslashshes in the macro +% +% We are in \macrobodyctxt, and the \xdef causes backslashes in the macro % body to be transformed. -% Set \macrobody to the body of the macro, and call \defmacro. +% Set \macrobody to the body of the macro, and call \macrodef. % +\catcode `\@\texiatcatcode {\catcode`\ =\other\long\gdef\parsemacbody#1@end macro{% -\xdef\macrobody{\eatcr{#1}}\endgroup\defmacro}}% +\xdef\macrobody{\eatcr{#1}}\endgroup\macrodef}}% {\catcode`\ =\other\long\gdef\parsermacbody#1@end rmacro{% -\xdef\macrobody{\eatcr{#1}}\endgroup\defmacro}}% - -% Make @ a letter, so that we can make private-to-Texinfo macro names. -\edef\texiatcatcode{\the\catcode`\@} -\catcode `@=11\relax +\xdef\macrobody{\eatcr{#1}}\endgroup\macrodef}}% +\catcode `\@=11\relax %%%%%%%%%%%%%% Code for > 10 arguments only %%%%%%%%%%%%%%%%%% @@ -8263,7 +8580,7 @@ % twice the \macarg.BLAH macros does not cost too much processing power. \def\parsemmanyargdef@@#1,{% \if#1;\let\next=\relax - \else + \else \let\next=\parsemmanyargdef@@ \edef\tempb{\eatspaces{#1}}% \expandafter\def\expandafter\tempa @@ -8348,7 +8665,7 @@ % Replace arguments by their values in the macro body, and place the result % in macro \@tempa. -% +% \def\macvalstoargs@{% % To do this we use the property that token registers that are \the'ed % within an \edef expand only once. So we are going to place all argument @@ -8372,9 +8689,9 @@ \expandafter\def\expandafter\@tempa\expandafter{\@tempc}% } -% Define the named-macro outside of this group and then close this group. -% -\def\macargexpandinbody@{% +% Define the named-macro outside of this group and then close this group. +% +\def\macargexpandinbody@{% \expandafter \endgroup \macargdeflist@ @@ -8412,7 +8729,7 @@ } % Trailing missing arguments are set to empty. -% +% \def\setemptyargvalues@{% \ifx\paramlist\nilm@ \let\next\macargexpandinbody@ @@ -8455,60 +8772,59 @@ % \xdef is used so that macro definitions will survive the file % they're defined in: @include reads the file inside a group. % -\def\defmacro{% +\def\macrodef{% \let\hash=##% convert placeholders to macro parameter chars \ifnum\paramno=1 - \def\xeatspaces##1{##1}% - % This removes the pair of braces around the argument. We don't - % use \eatspaces, because this can cause ends of lines to be lost - % when the argument to \eatspaces is read, leading to line-based - % commands like "@itemize" not being read correctly. + \long\def\xeatspaces##1{##1}% + % We don't use \xeatspaces for single-argument macros, because we + % want to keep ends of lines. This definition removes \xeatspaces + % when \macrobody is expanded below. \else - \let\xeatspaces\relax % suppress expansion + \def\xeatspaces{\string\xeatspaces}% + % This expands \xeatspaces as a sequence of character tokens, which + % stops \scantokens inserting an extra space after the control sequence. \fi \ifcase\paramno % 0 \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup + \begingroup \noexpand\spaceisspace - \noexpand\endlineisspace + \noexpand\ignoreactivenewline \noexpand\expandafter % skip any whitespace after the macro name. \expandafter\noexpand\csname\the\macname @@@\endcsname}% \expandafter\xdef\csname\the\macname @@@\endcsname{% - \egroup + \endgroup \noexpand\scanmacro{\macrobody}}% \or % 1 \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup + \begingroup \noexpand\braceorline \expandafter\noexpand\csname\the\macname @@@\endcsname}% \expandafter\xdef\csname\the\macname @@@\endcsname##1{% - \egroup + \endgroup \noexpand\scanmacro{\macrobody}% }% \else % at most 9 \ifnum\paramno<10\relax % @MACNAME sets the context for reading the macro argument - % @MACNAME@@ gets the argument, processes backslashes and appends a + % @MACNAME@@ gets the argument, processes backslashes and appends a % comma. % @MACNAME@@@ removes braces surrounding the argument list. % @MACNAME@@@@ scans the macro body with arguments substituted. \expandafter\xdef\csname\the\macname\endcsname{% - \bgroup + \begingroup \noexpand\expandafter % This \expandafter skip any spaces after the \noexpand\macroargctxt % macro before we change the catcode of space. \noexpand\expandafter \expandafter\noexpand\csname\the\macname @@\endcsname}% \expandafter\xdef\csname\the\macname @@\endcsname##1{% - \noexpand\passargtomacro - \expandafter\noexpand\csname\the\macname @@@\endcsname{##1,}}% + \noexpand\passargtomacro + \expandafter\noexpand\csname\the\macname @@@\endcsname{##1,}}% \expandafter\xdef\csname\the\macname @@@\endcsname##1{% - \expandafter\noexpand\csname\the\macname @@@@\endcsname ##1}% - \expandafter\expandafter - \expandafter\xdef - \expandafter\expandafter - \csname\the\macname @@@@\endcsname\paramlist{% - \egroup\noexpand\scanmacro{\macrobody}}% + \expandafter\noexpand\csname\the\macname @@@@\endcsname ##1}% + \expandaftergroup{\expandafter\xdef\csname\the\macname @@@@\endcsname}% + \paramlist{% + \endgroup\noexpand\scanmacro{\macrobody}}% \else % 10 or more: \expandafter\xdef\csname\the\macname\endcsname{% \noexpand\getargvals@{\the\macname}{\argl}% @@ -8520,6 +8836,16 @@ \catcode `\@\texiatcatcode\relax % end private-to-Texinfo catcodes +% utility definition to avoid excessive use of \expandafter. call +% as \expandaftergroup{CONTENT}\WORD to expand \WORD exactly once and remove +% braces around CONTENT. +\def\expandaftergroup#1#2{% + \expandafter\expandaftergroupx\expandafter{#2}{#1}% +} +\def\expandaftergroupx#1#2{% + #2#1% +} + \def\norecurse#1{\bgroup\cslet{#1}{macsave.#1}} @@ -8533,11 +8859,11 @@ % Call #1 with a list of tokens #2, with any doubled backslashes in #2 % compressed to one. % -% This implementation works by expansion, and not execution (so we cannot use -% \def or similar). This reduces the risk of this failing in contexts where -% complete expansion is done with no execution (for example, in writing out to +% This implementation works by expansion, and not execution (so we cannot use +% \def or similar). This reduces the risk of this failing in contexts where +% complete expansion is done with no execution (for example, in writing out to % an auxiliary file for an index entry). -% +% % State is kept in the input stream: the argument passed to % @look_ahead, @gobble_and_check_finish and @add_segment is % @@ -8559,11 +8885,11 @@ % #3 - NEXT_TOKEN % #4 used to look ahead % -% If the next token is not a backslash, process the rest of the argument; +% If the next token is not a backslash, process the rest of the argument; % otherwise, remove the next token. @gdef@look_ahead#1!#2#3#4{% @ifx#4\% - @expandafter@gobble_and_check_finish + @expandafter@gobble_and_check_finish @else @expandafter@add_segment @fi#1!{#2}#4#4% @@ -8587,9 +8913,9 @@ % #3 - NEXT_TOKEN % #4 is input stream until next backslash % -% Input stream is either at the start of the argument, or just after a -% backslash sequence, either a lone backslash, or a doubled backslash. -% NEXT_TOKEN contains the first token in the input stream: if it is \finish, +% Input stream is either at the start of the argument, or just after a +% backslash sequence, either a lone backslash, or a doubled backslash. +% NEXT_TOKEN contains the first token in the input stream: if it is \finish, % finish; otherwise, append to ARG_RESULT the segment of the argument up until % the next backslash. PENDING_BACKSLASH contains a backslash to represent % a backslash just before the start of the input stream that has not been @@ -8601,13 +8927,13 @@ % append the pending backslash to the result, followed by the next segment @expandafter@is_fi@look_ahead#1#2#4!{\}@fi % this @fi is discarded by @look_ahead. - % we can't get rid of it with \expandafter because we don't know how + % we can't get rid of it with \expandafter because we don't know how % long #4 is. } % #1 - THE_MACRO % #2 - ARG_RESULT -% #3 discards the res of the conditional in @add_segment, and @is_fi ends the +% #3 discards the res of the conditional in @add_segment, and @is_fi ends the % conditional. @gdef@call_the_macro#1#2!#3@fi{@is_fi #1{#2}} @@ -8619,7 +8945,7 @@ % for reading the argument (slightly different in the two cases). Then, % to read the argument, in the whole-line case, it then calls the regular % \parsearg MAC; in the lbrace case, it calls \passargtomacro MAC. -% +% \def\braceorline#1{\let\macnamexxx=#1\futurelet\nchar\braceorlinexxx} \def\braceorlinexxx{% \ifx\nchar\bgroup @@ -8630,6 +8956,74 @@ \fi \macnamexxx} +% @linemacro + +\parseargdef\linemacro{% + \getargs{#1}% now \macname is the macname and \argl the arglist + \ifx\argl\empty + \paramno=0 + \let\hash\relax + \def\paramlist{\hash 1\endlinemacro}% + \else + \expandafter\linegetparamlist\argl;% + \fi + \begingroup \macrobodyctxt \usembodybackslash + \parselinemacrobody +} + +% Build up \paramlist which will be used as the parameter text for the macro. +% At the end it will be like "#1 #2 #3\endlinemacro". +\def\linegetparamlist#1;{% + \paramno=0\def\paramlist{}% + \let\hash\relax + \linegetparamlistxxx#1,;,% +} +\def\linegetparamlistxxx#1,{% + \if#1;\let\next=\linegetparamlistxxxx + \else \let\next=\linegetparamlistxxx + \advance\paramno by 1 + \expandafter\edef\csname macarg.\eatspaces{#1}\endcsname + {\hash\the\paramno}% + \edef\paramlist{\paramlist\hash\the\paramno\space}% + \fi\next} +\def\linegetparamlistxxxx{% + \expandafter\fixparamlist\paramlist\fixparamlist +} +% Replace final space token +\def\fixparamlist#1 \fixparamlist{% + \def\paramlist{#1\endlinemacro}% +} + +% Read the body of the macro, replacing backslash-surrounded variables +% +{\catcode`\ =\other\long\gdef\parselinemacrobody#1@end linemacro{% +\xdef\macrobody{#1}% +\endgroup +\linemacrodef +}} + +% Make the definition +\def\linemacrodef{% + \let\hash=##% + \expandafter\xdef\csname\the\macname\endcsname{% + \bgroup + \noexpand\parsearg + \expandafter\noexpand\csname\the\macname @@\endcsname + } + \expandafter\xdef\csname\the\macname @@\endcsname##1{% + \egroup + \expandafter\noexpand + \csname\the\macname @@@\endcsname##1\noexpand\endlinemacro + } + \expandaftergroup{\expandafter\xdef\csname\the\macname @@@\endcsname}% + \paramlist{% + \newlinechar=13 % split \macrobody into lines + \noexpand\scantokens{\macrobody}% + } +} + + + % @alias. % We need some trickery to remove the optional spaces around the equal % sign. Make them active and then expand them all to nothing. @@ -8673,7 +9067,7 @@ % Used so that the @top node doesn't have to be wrapped in an @ifnottex % conditional. -% \doignore goes to more effort to skip nested conditionals but we don't need +% \doignore goes to more effort to skip nested conditionals but we don't need % that here. \def\omittopnode{% \ifx\lastnode\wordTop @@ -8681,9 +9075,11 @@ } \def\wordTop{Top} -% Until the next @node or @bye command, divert output to a box that is not -% output. -\def\ignorenode{\setbox\dummybox\vbox\bgroup\def\node{\egroup\node}% +% Until the next @node, @part or @bye command, divert output to a box that +% is not output. +\def\ignorenode{\setbox\dummybox\vbox\bgroup +\def\part{\egroup\part}% +\def\node{\egroup\node}% \ignorenodebye } @@ -8695,14 +9091,24 @@ \let\lastnode=\empty % Write a cross-reference definition for the current node. #1 is the -% type (Ynumbered, Yappendix, Ynothing). +% type (Ynumbered, Yappendix, Ynothing). #2 is the section title. % -\def\donoderef#1{% +\def\donoderef#1#2{% \ifx\lastnode\empty\else - \setref{\lastnode}{#1}% + \setref{\lastnode}{#1}{#2}% \global\let\lastnode=\empty + \setnodeseenonce \fi } +\def\setnodeseenonce{ + \global\nodeseentrue + \let\setnodeseenonce\relax +} + +% @nodedescription, @nodedescriptionblock - do nothing for TeX +\parseargdef\nodedescription{} +\def\nodedescriptionblock{\doignore{nodedescriptionblock}} + % @anchor{NAME} -- define xref target at arbitrary point. % @@ -8710,21 +9116,28 @@ % \def\savesf{\relax \ifhmode \savesfregister=\spacefactor \fi} \def\restoresf{\relax \ifhmode \spacefactor=\savesfregister \fi} -\def\anchor#1{\savesf \setref{#1}{Ynothing}\restoresf \ignorespaces} - -% \setref{NAME}{SNT} defines a cross-reference point NAME (a node or an -% anchor), which consists of three parts: -% 1) NAME-title - the current sectioning name taken from \currentsection, -% or the anchor name. -% 2) NAME-snt - section number and type, passed as the SNT arg, or -% empty for anchors. +\def\anchor#1{% + \savesf \setref{#1}{Yanchor}{#1}\restoresf \ignorespaces +} + +% @namedanchor{NAME, XREFNAME} -- define xref target at arbitrary point +% with label text for cross-references to it. +\def\namedanchor#1{\donamedanchor#1\finish}% +\def\donamedanchor#1,#2\finish{% + \savesf \setref{#1}{Yanchor}{\ignorespaces #2\unskip}\restoresf \ignorespaces +} + +% \setref{NAME}{SNT}{TITLE} defines a cross-reference point NAME (a node +% or an anchor), which consists of three parts: +% 1) NAME-title - the current sectioning name +% 2) NAME-snt - section number and type, passed as the SNT arg. % 3) NAME-pg - the page number. % % This is called from \donoderef, \anchor, and \dofloat. In the case of % floats, there is an additional part, which is not written here: % 4) NAME-lof - the text as it should appear in a @listoffloats. % -\def\setref#1#2{% +\def\setref#1#2#3{% \pdfmkdest{#1}% \iflinks {% @@ -8736,7 +9149,7 @@ \write\auxfile{@xrdef{#1-% #1 of \setref, expanded by the \edef ##1}{##2}}% these are parameters of \writexrdef }% - \toks0 = \expandafter{\currentsection}% + \toks0 = {#3}% \immediate \writexrdef{title}{\the\toks0 }% \immediate \writexrdef{snt}{\csname #2\endcsname}% \Ynumbered etc. \safewhatsit{\writexrdef{pg}{\folio}}% will be written later, at \shipout @@ -8748,7 +9161,7 @@ % automatically in xrefs, if the third arg is not explicitly specified. % This was provided as a "secret" @set xref-automatic-section-title % variable, now it's official. -% +% \parseargdef\xrefautomaticsectiontitle{% \def\temp{#1}% \ifx\temp\onword @@ -8764,7 +9177,7 @@ \fi\fi } -% +% % @xref, @pxref, and @ref generate cross-references. For \xrefX, #1 is % the node name, #2 the name of the Info cross-reference, #3 the printed % node name, #4 the name of the Info file, #5 the name of the printed @@ -8785,118 +9198,12 @@ \def\xrefX[#1,#2,#3,#4,#5,#6]{\begingroup \unsepspaces % - % Get args without leading/trailing spaces. - \def\printedrefname{\ignorespaces #3}% - \setbox\printedrefnamebox = \hbox{\printedrefname\unskip}% - % + \getprintedrefname{#1}{#3}{#5}% \def\infofilename{\ignorespaces #4}% \setbox\infofilenamebox = \hbox{\infofilename\unskip}% % - \def\printedmanual{\ignorespaces #5}% - \setbox\printedmanualbox = \hbox{\printedmanual\unskip}% - % - % If the printed reference name (arg #3) was not explicitly given in - % the @xref, figure out what we want to use. - \ifdim \wd\printedrefnamebox = 0pt - % No printed node name was explicitly given. - \expandafter\ifx\csname SETxref-automatic-section-title\endcsname \relax - % Not auto section-title: use node name inside the square brackets. - \def\printedrefname{\ignorespaces #1}% - \else - % Auto section-title: use chapter/section title inside - % the square brackets if we have it. - \ifdim \wd\printedmanualbox > 0pt - % It is in another manual, so we don't have it; use node name. - \def\printedrefname{\ignorespaces #1}% - \else - \ifhavexrefs - % We (should) know the real title if we have the xref values. - \def\printedrefname{\refx{#1-title}}% - \else - % Otherwise just copy the Info node name. - \def\printedrefname{\ignorespaces #1}% - \fi% - \fi - \fi - \fi - % - % Make link in pdf output. - \ifpdf - % For pdfTeX and LuaTeX - {\indexnofonts - \makevalueexpandable - \turnoffactive - % This expands tokens, so do it after making catcode changes, so _ - % etc. don't get their TeX definitions. This ignores all spaces in - % #4, including (wrongly) those in the middle of the filename. - \getfilename{#4}% - % - % This (wrongly) does not take account of leading or trailing - % spaces in #1, which should be ignored. - \setpdfdestname{#1}% - % - \ifx\pdfdestname\empty - \def\pdfdestname{Top}% no empty targets - \fi - % - \leavevmode - \startlink attr{/Border [0 0 0]}% - \ifnum\filenamelength>0 - goto file{\the\filename.pdf} name{\pdfdestname}% - \else - goto name{\pdfmkpgn{\pdfdestname}}% - \fi - }% - \setcolor{\linkcolor}% - \else - \ifx\XeTeXrevision\thisisundefined - \else - % For XeTeX - {\indexnofonts - \makevalueexpandable - \turnoffactive - % This expands tokens, so do it after making catcode changes, so _ - % etc. don't get their TeX definitions. This ignores all spaces in - % #4, including (wrongly) those in the middle of the filename. - \getfilename{#4}% - % - % This (wrongly) does not take account of leading or trailing - % spaces in #1, which should be ignored. - \setpdfdestname{#1}% - % - \ifx\pdfdestname\empty - \def\pdfdestname{Top}% no empty targets - \fi - % - \leavevmode - \ifnum\filenamelength>0 - % With default settings, - % XeTeX (xdvipdfmx) replaces link destination names with integers. - % In this case, the replaced destination names of - % remote PDFs are no longer known. In order to avoid a replacement, - % you can use xdvipdfmx's command line option `-C 0x0010'. - % If you use XeTeX 0.99996+ (TeX Live 2016+), - % this command line option is no longer necessary - % because we can use the `dvipdfmx:config' special. - \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A - << /S /GoToR /F (\the\filename.pdf) /D (\pdfdestname) >> >>}% - \else - \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A - << /S /GoTo /D (\pdfdestname) >> >>}% - \fi - }% - \setcolor{\linkcolor}% - \fi - \fi - {% - % Have to otherify everything special to allow the \csname to - % include an _ in the xref name, etc. - \indexnofonts - \turnoffactive - \def\value##1{##1}% - \expandafter\global\expandafter\let\expandafter\Xthisreftitle - \csname XR#1-title\endcsname - }% + \startxreflink{#1}{#4}% + \getrefx{#1-title}\Xthisreftitle % % Float references are printed completely differently: "Figure 1.2" % instead of "[somenode], p.3". \iffloat distinguishes them by @@ -8929,31 +9236,32 @@ % Cross-manual reference with a printed manual name. % \crossmanualxref{\cite{\printedmanual\unskip}}% - % \else\ifdim \wd\infofilenamebox > 0pt % Cross-manual reference with only an info filename (arg 4), no % printed manual name (arg 5). This is essentially the same as % the case above; we output the filename, since we have nothing else. % \crossmanualxref{\code{\infofilename\unskip}}% - % \else % Reference within this manual. % - % Only output a following space if the -snt ref is nonempty, as the ref - % will be empty for @unnumbered and @anchor. - \setbox2 = \hbox{\ignorespaces \refx{#1-snt}}% - \ifdim \wd2 > 0pt \refx{#1-snt}\space\fi + % Only output a following space if the -snt ref is nonempty, as is + % the case for @unnumbered and @anchor. + \getrefx{#1-snt}\tmp + \ifx\tmp\empty\else + \ifx\tmp\Yanchor\else + \tmp\space + \fi + \fi % % output the `[mynode]' via the macro below so it can be overridden. \xrefprintnodename\printedrefname % - \expandafter\ifx\csname SETtxiomitxrefpg\endcsname\relax - % But we always want a comma and a space: - ,\space - % + \ifflagclear{txiomitxrefpg}{% + % We always want a comma + ,% % output the `page 3'. - \turnoffactive \putwordpage\tie\refx{#1-pg}% + \turnoffactive \putpageref{#1}% % Add a , if xref followed by a space \if\space\noexpand\tokenafterxref ,% \else\ifx\ \tokenafterxref ,% @TAB @@ -8963,27 +9271,118 @@ \tokenafterxref ,% @NL \else\ifx\tie\tokenafterxref ,% @tie \fi\fi\fi\fi\fi\fi - \fi + }{}% \fi\fi \fi - \endlink -\endgroup} + \endlink +\endgroup} + +% \getprintedrefname{NODE}{LABEL}{MANUAL} +% - set \printedrefname and \printedmanual +% +\def\getprintedrefname#1#2#3{% + % Get args without leading/trailing spaces. + \def\printedrefname{\ignorespaces #2}% + \setbox\printedrefnamebox = \hbox{\printedrefname\unskip}% + % + \def\printedmanual{\ignorespaces #3}% + \setbox\printedmanualbox = \hbox{\printedmanual\unskip}% + % + % If the printed reference name (arg #2) was not explicitly given in + % the @xref, figure out what we want to use. + \ifdim \wd\printedrefnamebox = 0pt + % No printed node name was explicitly given. + \expandafter\ifx\csname SETxref-automatic-section-title\endcsname \relax + % Not auto section-title: use node name inside the square brackets. + \def\printedrefname{\ignorespaces #1}% + \else + % Auto section-title: use chapter/section title inside + % the square brackets if we have it. + \ifdim \wd\printedmanualbox > 0pt + % It is in another manual, so we don't have it; use node name. + \def\printedrefname{\ignorespaces #1}% + \else + \ifhavexrefs + % We (should) know the real title if we have the xref values. + \def\printedrefname{\refx{#1-title}}% + \else + % Otherwise just copy the Info node name. + \def\printedrefname{\ignorespaces #1}% + \fi + \fi + \fi + \fi +} + +% \startxreflink{NODE}{FILE} - start link in pdf output. +\def\startxreflink#1#2{% + \ifpdforxetex + % For pdfTeX and LuaTeX + {\indexnofonts + \makevalueexpandable + \turnoffactive + % This expands tokens, so do it after making catcode changes, so _ + % etc. don't get their TeX definitions. This ignores all spaces in + % #2, including (wrongly) those in the middle of the filename. + \getfilename{#2}% + % + % This (wrongly) does not take account of leading or trailing + % spaces in #1, which should be ignored. + \setpdfdestname{#1}% + % + \ifx\pdfdestname\empty + \def\pdfdestname{Top}% no empty targets + \fi + % + \leavevmode + \ifpdf + \startlink attr{/Border [0 0 0]}% + \ifnum\filenamelength>0 + goto file{\the\filename.pdf} name{\pdfdestname}% + \else + goto name{\pdfdestname}% + \fi + \else % XeTeX + \ifnum\filenamelength>0 + % With default settings, + % XeTeX (xdvipdfmx) replaces link destination names with integers. + % In this case, the replaced destination names of + % remote PDFs are no longer known. In order to avoid a replacement, + % you can use xdvipdfmx's command line option `-C 0x0010'. + % If you use XeTeX 0.99996+ (TeX Live 2016+), + % this command line option is no longer necessary + % because we can use the `dvipdfmx:config' special. + \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A + << /S /GoToR /F (\the\filename.pdf) /D (\pdfdestname) >> >>}% + \else + \special{pdf:bann << /Border [0 0 0] /Type /Annot /Subtype /Link /A + << /S /GoTo /D (\pdfdestname) >> >>}% + \fi + \fi + }% + \setcolor{\linkcolor}% + \fi +} + +% can be overridden in translation files +\def\putpageref#1{% + \space\putwordpage\tie\refx{#1-pg}} % Output a cross-manual xref to #1. Used just above (twice). -% +% % Only include the text "Section ``foo'' in" if the foo is neither % missing or Top. Thus, @xref{,,,foo,The Foo Manual} outputs simply % "see The Foo Manual", the idea being to refer to the whole manual. -% +% % But, this being TeX, we can't easily compare our node name against the % string "Top" while ignoring the possible spaces before and after in % the input. By adding the arbitrary 7sp below, we make it much less % likely that a real node name would have the same width as "Top" (e.g., % in a monospaced font). Hopefully it will never happen in practice. -% +% % For the same basic reason, we retypeset the "Top" at every % reference, since the current font is indeterminate. -% +% \def\crossmanualxref#1{% \setbox\toprefbox = \hbox{Top\kern7sp}% \setbox2 = \hbox{\ignorespaces \printedrefname \unskip \kern7sp}% @@ -9002,10 +9401,26 @@ % \def\xrefprintnodename#1{[#1]} +% @link{NODENAME, LABEL, MANUAL} - create a "plain" link, with no +% page number. Not useful if printed on paper. +% +\def\link#1{\linkX[#1,,,]} +\def\linkX[#1,#2,#3,#4]{% + \begingroup + \unsepspaces + \getprintedrefname{#1}{#2}{#3}% + \startxreflink{#1}{#3}% + \printedrefname + \endlink + \endgroup +} + + % Things referred to by \setref. % \def\Ynothing{} \def\Yomitfromtoc{} +\def\Yanchor{\isanchor} \let\isanchor\relax \def\Ynumbered{% \ifnum\secno=0 \putwordChapter@tie \the\chapno @@ -9032,14 +9447,7 @@ % \refx{NAME} - reference a cross-reference string named NAME. \def\refx#1{% - \requireauxfile - {% - \indexnofonts - \turnoffactive - \def\value##1{##1}% - \expandafter\global\expandafter\let\expandafter\thisrefX - \csname XR#1\endcsname - }% + \getrefx{#1}\thisrefX \ifx\thisrefX\relax % If not defined, say something at least. \angleleft un\-de\-fined\angleright @@ -9060,9 +9468,20 @@ \fi } -% This is the macro invoked by entries in the aux file. Define a control -% sequence for a cross-reference target (we prepend XR to the control sequence -% name to avoid collisions). The value is the page number. If this is a float +% Set #2 to xref string #1 +\def\getrefx#1#2{% + \requireauxfile + {% + \indexnofonts + \turnoffactive + \def\value##1{##1}% + \expandafter\global\expandafter\let\expandafter#2\csname XR#1\endcsname + }% +} + +% This is the macro invoked by entries in the aux file. Define a control +% sequence for a cross-reference target (we prepend XR to the control sequence +% name to avoid collisions). The value is the page number. If this is a float % type, we have more work to do. % \def\xrdef#1#2{% @@ -9078,10 +9497,10 @@ \bgroup \expandafter\gdef\csname XR\safexrefname\endcsname{#2}% \egroup - % We put the \gdef inside a group to avoid the definitions building up on - % TeX's save stack, which can cause it to run out of space for aux files with + % We put the \gdef inside a group to avoid the definitions building up on + % TeX's save stack, which can cause it to run out of space for aux files with % thousands of lines. \gdef doesn't use the save stack, but \csname does - % when it defines an unknown control sequence as \relax. + % when it defines an unknown control sequence as \relax. % % Was that xref control sequence that we just defined for a float? \expandafter\iffloat\csname XR\safexrefname\endcsname @@ -9102,6 +9521,7 @@ \expandafter\xdef\csname floatlist\iffloattype\endcsname{\the\toks0 {\safexrefname}}% \fi + \ignorespaces % ignore ends of line in aux file } % If working on a large document in chapters, it is convenient to @@ -9124,12 +9544,14 @@ % Read the last existing aux file, if any. No error if none exists. % \def\tryauxfile{% + \ifxetex\xetexpreauxfile\fi \openin 1 \jobname.aux \ifeof 1 \else \readdatafile{aux}% \global\havexrefstrue \fi \closein 1 + \ifxetex\xetexpostauxfile\fi } \def\setupdatafile{% @@ -9212,7 +9634,10 @@ % Auto-number footnotes. Otherwise like plain. \gdef\footnote{% \global\advance\footnoteno by \@ne - \edef\thisfootno{$^{\the\footnoteno}$}% + % + % Output for the footnote marker. If we are immediately after another + % footnote, output a comma and small space first. + \edef\thisfootno{$^{\ifnum\lastpenalty=3 ,\mskip 1mu \fi\the\footnoteno}$}% % % In case the footnote comes at the end of a sentence, preserve the % extra spacing after we do the footnote number. @@ -9221,19 +9646,25 @@ % % Remove inadvertent blank space before typesetting the footnote number. \unskip - \thisfootno\@sf + % + % \scriptspace is 0.5pt by default and gives excessive space before the + % comma if we have multiple footnote markers in a row. + \bgroup\scriptspace=0pt + \thisfootno\@sf + \egroup \dofootnote }% -% Don't bother with the trickery in plain.tex to not require the -% footnote text as a parameter. Our footnotes don't need to be so general. -% -% Oh yes, they do; otherwise, @ifset (and anything else that uses -% \parseargline) fails inside footnotes because the tokens are fixed when -% the footnote is read. --karl, 16nov96. +% marker for immediately after a footnote marker +\gdef\footnoteendmarker{\penalty3 } + +% Do not require the footnote text as a parameter; otherwise, @ifset +% (and anything else that uses \parseargline) fails inside footnotes +% because the tokens are fixed when the footnote is read. % \gdef\dofootnote{% \insert\footins\bgroup + \aftergroup\footnoteendmarker % % Nested footnotes are not supported in TeX, that would take a lot % more work. (\startsavinginserts does not suffice.) @@ -9264,14 +9695,14 @@ % Hang the footnote text off the number. Use \everypar in case the % footnote extends for more than one paragraph. \everypar = {\hang}% - \textindent{\thisfootno}% + \textindent{$^{\the\footnoteno}$}% % % Don't crash into the line above the footnote text. Since this % expands into a box, it must come within the paragraph, lest it % provide a place where TeX can split the footnote. \footstrut % - % Invoke rest of plain TeX footnote routine. + % Eat opening brace and invoke rest of plain TeX footnote routine. \futurelet\next\fo@t } }%end \catcode `\@=11 @@ -9380,6 +9811,12 @@ \imagexxx #1,,,,,\finish \fi } + +% Approximate height of a line in the standard text font. +\newdimen\capheight +\setbox0=\vbox{\tenrm H} +\capheight=\ht0 + % % Arguments to @image: % #1 is (mandatory) image filename; we tack on .eps extension. @@ -9392,39 +9829,39 @@ \catcode`\^^M = 5 % in case we're inside an example \normalturnoffactive % allow _ et al. in names \makevalueexpandable - % If the image is by itself, center it. \ifvmode \imagevmodetrue - \else \ifx\centersub\centerV - % for @center @image, we need a vbox so we can have our vertical space - \imagevmodetrue - \vbox\bgroup % vbox has better behavior than vtop herev - \fi\fi - % - \ifimagevmode - \nobreak\medskip + \medskip % Usually we'll have text after the image which will insert % \parskip glue, so insert it here too to equalize the space % above and below. - \nobreak\vskip\parskip - \nobreak + \vskip\parskip + % + % Place image in a \vtop for a top page margin that is (close to) correct, + % as \topskip glue is relative to the first baseline. + \vtop\bgroup \kern -\capheight \vskip-\parskip \fi % - % Leave vertical mode so that indentation from an enclosing - % environment such as @quotation is respected. - % However, if we're at the top level, we don't want the - % normal paragraph indentation. - % On the other hand, if we are in the case of @center @image, we don't - % want to start a paragraph, which will create a hsize-width box and - % eradicate the centering. - \ifx\centersub\centerV \else \imageindent \fi + \ifx\centersub\centerV + % For @center @image, enter vertical mode and add vertical space + % Enter an extra \parskip because @center doesn't add space itself. + \vbox\bgroup\vskip\parskip\medskip\vskip\parskip + \else + % Enter horizontal mode so that indentation from an enclosing + % environment such as @quotation is respected. + % However, if we're at the top level, we don't want the + % normal paragraph indentation. + \imageindent + \fi % % Output the image. \ifpdf % For pdfTeX and LuaTeX <= 0.80 \dopdfimage{#1}{#2}{#3}% \else - \ifx\XeTeXrevision\thisisundefined + \ifxetex + \doxeteximage{#1}{#2}{#3}% + \else % For epsf.tex % \epsfbox itself resets \epsf?size at each figure. \setbox0 = \hbox{\ignorespaces #2}% @@ -9432,16 +9869,17 @@ \setbox0 = \hbox{\ignorespaces #3}% \ifdim\wd0 > 0pt \epsfysize=#3\relax \fi \epsfbox{#1.eps}% - \else - % For XeTeX - \doxeteximage{#1}{#2}{#3}% \fi \fi % \ifimagevmode + \egroup \medskip % space after a standalone image \fi - \ifx\centersub\centerV \egroup \fi + \ifx\centersub\centerV % @center @image + \medskip + \egroup % close \vbox + \fi \endgroup} @@ -9508,14 +9946,15 @@ \global\advance\floatno by 1 % {% - % This magic value for \currentsection is output by \setref as the - % XREFLABEL-title value. \xrefX uses it to distinguish float + % This magic value for the third argument of \setref is output as + % the XREFLABEL-title value. \xrefX uses it to distinguish float % labels (which have a completely different output format) from % node and anchor labels. And \xrdef uses it to construct the % lists of floats. % - \edef\currentsection{\floatmagic=\safefloattype}% - \setref{\floatlabel}{Yfloat}% + \edef\tmp{\noexpand\setref{\noexpand\floatlabel}{Yfloat}% + {\floatmagic=\safefloattype}}% + \tmp }% \fi % @@ -9608,8 +10047,8 @@ % \def\caption{\docaption\thiscaption} \def\shortcaption{\docaption\thisshortcaption} -\def\docaption{\checkenv\float \bgroup\scanargctxt\defcaption} -\def\defcaption#1#2{\egroup \def#1{#2}} +\def\docaption{\checkenv\float \bgroup\scanctxt\docaptionz} +\def\docaptionz#1#2{\egroup \def#1{#2}} % The parameter is the control sequence identifying the counter we are % going to use. Create it if it doesn't exist and assign it to \floatno. @@ -9637,7 +10076,7 @@ % #1 is the control sequence we are passed; we expand into a conditional % which is true if #1 represents a float ref. That is, the magic -% \currentsection value which we \setref above. +% value which we passed to \setref above. % \def\iffloat#1{\expandafter\doiffloat#1==\finish} % @@ -9694,6 +10133,7 @@ \toksA = \expandafter{\csname XR#1-lof\endcsname}% % % use the same \entry macro we use to generate the TOC and index. + \let\entry\entryinternal \edef\writeentry{\noexpand\entry{\the\toksA}{\csname XR#1-pg\endcsname}}% \writeentry }} @@ -9729,8 +10169,18 @@ \gdef\documentlanguagetrywithoutunderscore#1_#2\finish{% \openin 1 txi-#1.tex \ifeof 1 - \errhelp = \nolanghelp - \errmessage{Cannot read language file txi-#1.tex}% + \def\lang{#1}% + \def\enword{en}% + \ifx\lang\enword + % for English only, keep on going rather than issuing a fatal error + % message, as txi-en.tex likely doesn't contain any changes from the + % defaults. note that this is a problem if we already loaded another + % language file and want to switch back to English. + \message{Cannot read language file txi-#1.tex}% + \else + \errhelp = \nolanghelp + \errmessage{Cannot read language file txi-#1.tex}% + \fi \else \globaldefs = 1 % everything in the txi-LL files needs to persist \input txi-#1.tex @@ -9776,35 +10226,40 @@ \newif\iftxinativeunicodecapable \newif\iftxiusebytewiseio -\ifx\XeTeXrevision\thisisundefined - \ifx\luatexversion\thisisundefined - \txinativeunicodecapablefalse - \txiusebytewiseiotrue - \else +\ifxetex + \txinativeunicodecapabletrue + \txiusebytewiseiofalse +\else + \ifluatex \txinativeunicodecapabletrue \txiusebytewiseiofalse + \else + \txinativeunicodecapablefalse + \txiusebytewiseiotrue \fi -\else - \txinativeunicodecapabletrue - \txiusebytewiseiofalse \fi +\let\xetexpreauxfile\relax +\let\xetexpostauxfile\relax + % Set I/O by bytes instead of UTF-8 sequence for XeTeX and LuaTex % for non-UTF-8 (byte-wise) encodings. % \def\setbytewiseio{% - \ifx\XeTeXrevision\thisisundefined - \else - \XeTeXdefaultencoding "bytes" % For subsequent files to be read - \XeTeXinputencoding "bytes" % For document root file - % Unfortunately, there seems to be no corresponding XeTeX command for - % output encoding. This is a problem for auxiliary index and TOC files. - % The only solution would be perhaps to write out @U{...} sequences in - % place of non-ASCII characters. + \ifxetex + % For document root file + \XeTeXinputencoding "bytes" + % + % Setting for subsequent files to be read with @include. + \XeTeXdefaultencoding "bytes" + % + % Use UTF-8 for reading auxiliary index and TOC files, which are + % always output in UTF-8 with XeTeX. + \def\xetexpreauxfile{\XeTeXdefaultencoding "UTF-8"}% + \def\xetexpostauxfile{\XeTeXdefaultencoding "bytes"}% \fi - \ifx\luatexversion\thisisundefined - \else + \ifluatex \directlua{ local utf8_char, byte, gsub = unicode.utf8.char, string.byte, string.gsub local function convert_char (char) @@ -9898,12 +10353,10 @@ % For native Unicode handling (XeTeX and LuaTeX) \nativeunicodechardefs \else - % For treating UTF-8 as byte sequences (TeX, eTeX and pdfTeX) + % For treating UTF-8 as byte sequences (TeX, eTeX and pdfTeX). + % Since we already invoke \utfeightchardefs at the top level, + % making non-ascii chars active is sufficient. \setnonasciicharscatcode\active - % since we already invoked \utfeightchardefs at the top level - % (below), do not re-invoke it, otherwise our check for duplicated - % definitions gets triggered. Making non-ascii chars active is - % sufficient. \fi % \else @@ -9915,8 +10368,7 @@ \fi % lattwo \fi % ascii % - \ifx\XeTeXrevision\thisisundefined - \else + \ifxetex \ifx \declaredencoding \utfeight \else \ifx \declaredencoding \ascii @@ -9928,7 +10380,6 @@ \fi } -% emacs-page % A message to be logged when using a character that isn't available % the default font encoding (OT1). % @@ -9937,12 +10388,6 @@ % Take account of \c (plain) vs. \, (Texinfo) difference. \def\cedilla#1{\ifx\c\ptexc\c{#1}\else\,{#1}\fi} -% First, make active non-ASCII characters in order for them to be -% correctly categorized when TeX reads the replacement text of -% macros containing the character definitions. -\setnonasciicharscatcode\active -% - \def\gdefchar#1#2{% \gdef#1{% \ifpassthroughchars @@ -9952,8 +10397,14 @@ \fi }} +\begingroup + +% Make non-ASCII characters active for defining the character definition +% macros. +\setnonasciicharscatcode\active + % Latin1 (ISO-8859-1) character definitions. -\def\latonechardefs{% +\gdef\latonechardefs{% \gdefchar^^a0{\tie} \gdefchar^^a1{\exclamdown} \gdefchar^^a2{{\tcfont \char162}} % cent @@ -10058,7 +10509,7 @@ } % Latin9 (ISO-8859-15) encoding character definitions. -\def\latninechardefs{% +\gdef\latninechardefs{% % Encoding is almost identical to Latin1. \latonechardefs % @@ -10073,7 +10524,7 @@ } % Latin2 (ISO-8859-2) character definitions. -\def\lattwochardefs{% +\gdef\lattwochardefs{% \gdefchar^^a0{\tie} \gdefchar^^a1{\ogonek{A}} \gdefchar^^a2{\u{}} @@ -10091,7 +10542,7 @@ \gdefchar^^ae{\v Z} \gdefchar^^af{\dotaccent Z} % - \gdefchar^^b0{\textdegree{}} + \gdefchar^^b0{\textdegree} \gdefchar^^b1{\ogonek{a}} \gdefchar^^b2{\ogonek{ }} \gdefchar^^b3{\l} @@ -10177,6 +10628,8 @@ \gdefchar^^ff{\dotaccent{}} } +\endgroup % active chars + % UTF-8 character definitions. % % This code to support UTF-8 is based on LaTeX's utf8.def, with some @@ -10198,11 +10651,15 @@ \gdef\UTFviiiDefined#1{% \ifx #1\relax - \message{\linenumber Unicode char \string #1 not defined for Texinfo}% + \ifutfviiidefinedwarning + \message{\linenumber Unicode char \string #1 not defined for Texinfo}% + \fi \else \expandafter #1% \fi } +\newif\ifutfviiidefinedwarning +\utfviiidefinedwarningtrue % Give non-ASCII bytes the active definitions for processing UTF-8 sequences \begingroup @@ -10212,8 +10669,8 @@ % Loop from \countUTFx to \countUTFy, performing \UTFviiiTmp % substituting ~ and $ with a character token of that value. - \def\UTFviiiLoop{% - \global\catcode\countUTFx\active + \gdef\UTFviiiLoop{% + \catcode\countUTFx\active \uccode`\~\countUTFx \uccode`\$\countUTFx \uppercase\expandafter{\UTFviiiTmp}% @@ -10221,7 +10678,7 @@ \ifnum\countUTFx < \countUTFy \expandafter\UTFviiiLoop \fi} - + % % For bytes other than the first in a UTF-8 sequence. Not expected to % be expanded except when writing to auxiliary files. \countUTFx = "80 @@ -10255,6 +10712,16 @@ \else\expandafter\UTFviiiFourOctets\expandafter$\fi }}% \UTFviiiLoop + % + % for pdftex only, used to expand ASCII to UTF-16BE. + \gdef\asciitounicode{% + \countUTFx = "20 + \countUTFy = "80 + \def\UTFviiiTmp{% + \def~{\nullbyte $}}% + \UTFviiiLoop + } + {\catcode0=11 \gdef\nullbyte{^^00}}% \endgroup \def\globallet{\global\let} % save some \expandafter's below @@ -10271,7 +10738,7 @@ \uppercase{.} \endgroup \else - \errhelp = \EMsimple + \errhelp = \EMsimple \errmessage{Unicode character U+#1 not supported, sorry}% \fi \else @@ -10279,8 +10746,8 @@ \fi } -% These macros are used here to construct the name of a control -% sequence to be defined. +% These macros are used here to construct the names of macros +% that expand to the definitions for UTF-8 sequences. \def\UTFviiiTwoOctetsName#1#2{% \csname u8:#1\string #2\endcsname}% \def\UTFviiiThreeOctetsName#1#2#3{% @@ -10288,6 +10755,35 @@ \def\UTFviiiFourOctetsName#1#2#3#4{% \csname u8:#1\string #2\string #3\string #4\endcsname}% +% generate UTF-16 from codepoint +\def\utfsixteentotoks#1#2{% + \countUTFz = "#2\relax + \ifnum \countUTFz > 65535 + % doesn't work for codepoints > U+FFFF + % we don't define glyphs for any of these anyway, so it doesn't matter + #1={U+#2}% + \else + \countUTFx = \countUTFz + \divide\countUTFx by 256 + \countUTFy = \countUTFx + \multiply\countUTFx by 256 + \advance\countUTFz by -\countUTFx + \uccode`,=\countUTFy + \uccode`;=\countUTFz + \ifnum\countUTFy = 0 + \uppercase{#1={\nullbyte\string;}}% + \else\ifnum\countUTFz = 0 + \uppercase{#1={\string,\nullbyte}}% + \else + \uppercase{#1={\string,\string;}}% + \fi\fi + % NB \uppercase cannot insert a null byte + \fi +} + +\newif\ifutfbytespdf +\utfbytespdffalse + % For UTF-8 byte sequences (TeX, e-TeX and pdfTeX), % provide a definition macro to replace a Unicode character; % this gets used by the @U command @@ -10304,19 +10800,23 @@ \countUTFz = "#1\relax \begingroup \parseXMLCharref - - % Give \u8:... its definition. The sequence of seven \expandafter's - % expands after the \gdef three times, e.g. % + % Completely expand \UTFviiiTmp, which looks like: % 1. \UTFviiTwoOctetsName B1 B2 % 2. \csname u8:B1 \string B2 \endcsname % 3. \u8: B1 B2 (a single control sequence token) + \xdef\UTFviiiTmp{\UTFviiiTmp}% % - \expandafter\expandafter - \expandafter\expandafter - \expandafter\expandafter - \expandafter\gdef \UTFviiiTmp{#2}% - % + \ifpdf + \toksA={#2}% + \utfsixteentotoks\toksB{#1}% + \expandafter\xdef\UTFviiiTmp{% + \noexpand\ifutfbytespdf\noexpand\utfbytes{\the\toksB}% + \noexpand\else\the\toksA\noexpand\fi}% + \else + \expandafter\gdef\UTFviiiTmp{#2}% + \fi + % \expandafter\ifx\csname uni:#1\endcsname \relax \else \message{Internal error, already defined: #1}% \fi @@ -10325,12 +10825,13 @@ \expandafter\globallet\csname uni:#1\endcsname \UTFviiiTmp \endgroup} % - % Given the value in \countUTFz as a Unicode code point, set \UTFviiiTmp - % to the corresponding UTF-8 sequence. + % Given the value in \countUTFz as a Unicode code point, set + % \UTFviiiTmp to one of the \UTVviii*OctetsName macros followed by + % the corresponding UTF-8 sequence. \gdef\parseXMLCharref{% - \ifnum\countUTFz < "A0\relax + \ifnum\countUTFz < "20\relax \errhelp = \EMsimple - \errmessage{Cannot define Unicode char value < 00A0}% + \errmessage{Cannot define Unicode char value < 0020}% \else\ifnum\countUTFz < "800\relax \parseUTFviiiA,% \parseUTFviiiB C\UTFviiiTwoOctetsName.,% @@ -10355,7 +10856,7 @@ \divide\countUTFz by 64 \countUTFy = \countUTFz % Save to be the future value of \countUTFz. \multiply\countUTFz by 64 - + % \countUTFz is now \countUTFx with the last 5 bits cleared. Subtract % in order to get the last five bits. \advance\countUTFx by -\countUTFz @@ -10385,12 +10886,22 @@ \catcode"#1=\other } +% Suppress ligature creation from adjacent characters. +\ifluatex + % Braces do not suppress ligature creation in LuaTeX, e.g. in of{}fice + % to suppress the "ff" ligature. Using a kern appears to be the only + % workaround. + \def\nolig{\kern0pt{}} +\else + \def\nolig{{}} +\fi + % https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_M % U+0000..U+007F = https://en.wikipedia.org/wiki/Basic_Latin_(Unicode_block) % U+0080..U+00FF = https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block) % U+0100..U+017F = https://en.wikipedia.org/wiki/Latin_Extended-A % U+0180..U+024F = https://en.wikipedia.org/wiki/Latin_Extended-B -% +% % Many of our renditions are less than wonderful, and all the missing % characters are available somewhere. Loading the necessary fonts % awaits user request. We can't truly support Unicode without @@ -10400,6 +10911,103 @@ % least make most of the characters not bomb out. % \def\unicodechardefs{% + \DeclareUnicodeCharacter{0020}{ } % space + \DeclareUnicodeCharacter{0021}{\char"21 }% % space to terminate number + \DeclareUnicodeCharacter{0022}{\char"22 }% + \DeclareUnicodeCharacter{0023}{\char"23 }% + \DeclareUnicodeCharacter{0024}{\char"24 }% + \DeclareUnicodeCharacter{0025}{\char"25 }% + \DeclareUnicodeCharacter{0026}{\char"26 }% + \DeclareUnicodeCharacter{0027}{\char"27 }% + \DeclareUnicodeCharacter{0028}{\char"28 }% + \DeclareUnicodeCharacter{0029}{\char"29 }% + \DeclareUnicodeCharacter{002A}{\char"2A }% + \DeclareUnicodeCharacter{002B}{\char"2B }% + \DeclareUnicodeCharacter{002C}{\char"2C }% + \DeclareUnicodeCharacter{002D}{\char"2D }% + \DeclareUnicodeCharacter{002E}{\char"2E }% + \DeclareUnicodeCharacter{002F}{\char"2F }% + \DeclareUnicodeCharacter{0030}{0}% + \DeclareUnicodeCharacter{0031}{1}% + \DeclareUnicodeCharacter{0032}{2}% + \DeclareUnicodeCharacter{0033}{3}% + \DeclareUnicodeCharacter{0034}{4}% + \DeclareUnicodeCharacter{0035}{5}% + \DeclareUnicodeCharacter{0036}{6}% + \DeclareUnicodeCharacter{0037}{7}% + \DeclareUnicodeCharacter{0038}{8}% + \DeclareUnicodeCharacter{0039}{9}% + \DeclareUnicodeCharacter{003A}{\char"3A }% + \DeclareUnicodeCharacter{003B}{\char"3B }% + \DeclareUnicodeCharacter{003C}{\char"3C }% + \DeclareUnicodeCharacter{003D}{\char"3D }% + \DeclareUnicodeCharacter{003E}{\char"3E }% + \DeclareUnicodeCharacter{003F}{\char"3F }% + \DeclareUnicodeCharacter{0040}{\char"40 }% + \DeclareUnicodeCharacter{0041}{A}% + \DeclareUnicodeCharacter{0042}{B}% + \DeclareUnicodeCharacter{0043}{C}% + \DeclareUnicodeCharacter{0044}{D}% + \DeclareUnicodeCharacter{0045}{E}% + \DeclareUnicodeCharacter{0046}{F}% + \DeclareUnicodeCharacter{0047}{G}% + \DeclareUnicodeCharacter{0048}{H}% + \DeclareUnicodeCharacter{0049}{I}% + \DeclareUnicodeCharacter{004A}{J}% + \DeclareUnicodeCharacter{004B}{K}% + \DeclareUnicodeCharacter{004C}{L}% + \DeclareUnicodeCharacter{004D}{M}% + \DeclareUnicodeCharacter{004E}{N}% + \DeclareUnicodeCharacter{004F}{O}% + \DeclareUnicodeCharacter{0050}{P}% + \DeclareUnicodeCharacter{0051}{Q}% + \DeclareUnicodeCharacter{0052}{R}% + \DeclareUnicodeCharacter{0053}{S}% + \DeclareUnicodeCharacter{0054}{T}% + \DeclareUnicodeCharacter{0055}{U}% + \DeclareUnicodeCharacter{0056}{V}% + \DeclareUnicodeCharacter{0057}{W}% + \DeclareUnicodeCharacter{0058}{X}% + \DeclareUnicodeCharacter{0059}{Y}% + \DeclareUnicodeCharacter{005A}{Z}% + \DeclareUnicodeCharacter{005B}{\char"5B }% + \DeclareUnicodeCharacter{005C}{\char"5C }% + \DeclareUnicodeCharacter{005D}{\char"5D }% + \DeclareUnicodeCharacter{005E}{\char"5E }% + \DeclareUnicodeCharacter{005F}{\char"5F }% + \DeclareUnicodeCharacter{0060}{\char"60 }% + \DeclareUnicodeCharacter{0061}{a}% + \DeclareUnicodeCharacter{0062}{b}% + \DeclareUnicodeCharacter{0063}{c}% + \DeclareUnicodeCharacter{0064}{d}% + \DeclareUnicodeCharacter{0065}{e}% + \DeclareUnicodeCharacter{0066}{f}% + \DeclareUnicodeCharacter{0067}{g}% + \DeclareUnicodeCharacter{0068}{h}% + \DeclareUnicodeCharacter{0069}{i}% + \DeclareUnicodeCharacter{006A}{j}% + \DeclareUnicodeCharacter{006B}{k}% + \DeclareUnicodeCharacter{006C}{l}% + \DeclareUnicodeCharacter{006D}{m}% + \DeclareUnicodeCharacter{006E}{n}% + \DeclareUnicodeCharacter{006F}{o}% + \DeclareUnicodeCharacter{0070}{p}% + \DeclareUnicodeCharacter{0071}{q}% + \DeclareUnicodeCharacter{0072}{r}% + \DeclareUnicodeCharacter{0073}{s}% + \DeclareUnicodeCharacter{0074}{t}% + \DeclareUnicodeCharacter{0075}{u}% + \DeclareUnicodeCharacter{0076}{v}% + \DeclareUnicodeCharacter{0077}{w}% + \DeclareUnicodeCharacter{0078}{x}% + \DeclareUnicodeCharacter{0079}{y}% + \DeclareUnicodeCharacter{007A}{z}% + \DeclareUnicodeCharacter{007B}{\char"7B }% + \DeclareUnicodeCharacter{007C}{\char"7C }% + \DeclareUnicodeCharacter{007D}{\char"7D }% + \DeclareUnicodeCharacter{007E}{\char"7E }% + % \DeclareUnicodeCharacter{007F}{} % DEL + % \DeclareUnicodeCharacter{00A0}{\tie}% \DeclareUnicodeCharacter{00A1}{\exclamdown}% \DeclareUnicodeCharacter{00A2}{{\tcfont \char162}}% 0242=cent @@ -10417,7 +11025,7 @@ \DeclareUnicodeCharacter{00AE}{\registeredsymbol{}}% \DeclareUnicodeCharacter{00AF}{\={ }}% % - \DeclareUnicodeCharacter{00B0}{\ringaccent{ }}% + \DeclareUnicodeCharacter{00B0}{\textdegree}% \DeclareUnicodeCharacter{00B1}{\ensuremath\pm}% \DeclareUnicodeCharacter{00B2}{$^2$}% \DeclareUnicodeCharacter{00B3}{$^3$}% @@ -10899,11 +11507,14 @@ \DeclareUnicodeCharacter{1EF8}{\~Y}% \DeclareUnicodeCharacter{1EF9}{\~y}% % + % Exotic spaces + \DeclareUnicodeCharacter{2007}{\hphantom{0}}% + % % Punctuation \DeclareUnicodeCharacter{2013}{--}% \DeclareUnicodeCharacter{2014}{---}% - \DeclareUnicodeCharacter{2018}{\quoteleft{}}% - \DeclareUnicodeCharacter{2019}{\quoteright{}}% + \DeclareUnicodeCharacter{2018}{\quoteleft\nolig}% + \DeclareUnicodeCharacter{2019}{\quoteright\nolig}% \DeclareUnicodeCharacter{201A}{\quotesinglbase{}}% \DeclareUnicodeCharacter{201C}{\quotedblleft{}}% \DeclareUnicodeCharacter{201D}{\quotedblright{}}% @@ -10918,7 +11529,7 @@ % \DeclareUnicodeCharacter{20AC}{\euro{}}% % - \DeclareUnicodeCharacter{2192}{\expansion{}}% + \DeclareUnicodeCharacter{2192}{\arrow}% \DeclareUnicodeCharacter{21D2}{\result{}}% % % Mathematical symbols @@ -10938,7 +11549,7 @@ \DeclareUnicodeCharacter{2287}{\ensuremath\supseteq}% % \DeclareUnicodeCharacter{2016}{\ensuremath\Vert}% - \DeclareUnicodeCharacter{2032}{\ensuremath\prime}% + \DeclareUnicodeCharacter{2032}{\ensuremath{^\prime}}% \DeclareUnicodeCharacter{210F}{\ensuremath\hbar}% \DeclareUnicodeCharacter{2111}{\ensuremath\Im}% \DeclareUnicodeCharacter{2113}{\ensuremath\ell}% @@ -11061,6 +11672,25 @@ % \global\mathchardef\checkmark="1370% actually the square root sign \DeclareUnicodeCharacter{2713}{\ensuremath\checkmark}% + % + % These are all the combining accents. We need these empty definitions + % at present for the sake of PDF outlines. + \DeclareUnicodeCharacter{0300}{}% + \DeclareUnicodeCharacter{0301}{}% + \DeclareUnicodeCharacter{0302}{}% + \DeclareUnicodeCharacter{0303}{}% + \DeclareUnicodeCharacter{0305}{}% + \DeclareUnicodeCharacter{0306}{}% + \DeclareUnicodeCharacter{0307}{}% + \DeclareUnicodeCharacter{0308}{}% + \DeclareUnicodeCharacter{030A}{}% + \DeclareUnicodeCharacter{030B}{}% + \DeclareUnicodeCharacter{030C}{}% + \DeclareUnicodeCharacter{0323}{}% + \DeclareUnicodeCharacter{0327}{}% + \DeclareUnicodeCharacter{0328}{}% + \DeclareUnicodeCharacter{0331}{}% + \DeclareUnicodeCharacter{0361}{}% }% end of \unicodechardefs % UTF-8 byte sequence (pdfTeX) definitions (replacing and @U command) @@ -11081,24 +11711,26 @@ % provide a definition macro to replace/pass-through a Unicode character % \def\DeclareUnicodeCharacterNative#1#2{% - \catcode"#1=\active - \def\dodeclareunicodecharacternative##1##2##3{% + \ifnum"#1>"7F % only make non-ASCII chars active + \catcode"#1=\active + \def\dodeclareunicodecharacternative##1##2##3{% + \begingroup + \uccode`\~="##2\relax + \uppercase{\gdef~}{% + \ifpassthroughchars + ##1% + \else + ##3% + \fi + } + \endgroup + } \begingroup - \uccode`\~="##2\relax - \uppercase{\gdef~}{% - \ifpassthroughchars - ##1% - \else - ##3% - \fi - } + \uccode`\.="#1\relax + \uppercase{\def\UTFNativeTmp{.}}% + \expandafter\dodeclareunicodecharacternative\UTFNativeTmp{#1}{#2}% \endgroup - } - \begingroup - \uccode`\.="#1\relax - \uppercase{\def\UTFNativeTmp{.}}% - \expandafter\dodeclareunicodecharacternative\UTFNativeTmp{#1}{#2}% - \endgroup + \fi } % Native Unicode handling (XeTeX and LuaTeX) character replacing definition. @@ -11127,14 +11759,14 @@ \relax } -% Define all Unicode characters we know about. This makes UTF-8 the default -% input encoding and allows @U to work. +% Define all Unicode characters we know about \iftxinativeunicodecapable \nativeunicodechardefsatu \else \utfeightchardefs \fi + \message{formatting,} \newdimen\defaultparindent \defaultparindent = 15pt @@ -11181,13 +11813,9 @@ % \vsize = #1\relax \advance\vsize by \topskip - \outervsize = \vsize - \advance\outervsize by 2\topandbottommargin \txipageheight = \vsize % \hsize = #2\relax - \outerhsize = \hsize - \advance\outerhsize by 0.5in \txipagewidth = \hsize % \normaloffset = #4\relax @@ -11201,12 +11829,12 @@ \pdfhorigin = 1 true in \pdfvorigin = 1 true in \else - \ifx\XeTeXrevision\thisisundefined - \special{papersize=#8,#7}% - \else + \ifxetex \pdfpageheight #7\relax \pdfpagewidth #8\relax % XeTeX does not have \pdfhorigin and \pdfvorigin. + \else + \special{papersize=#8,#7}% \fi \fi % @@ -11244,23 +11872,6 @@ \defbodyindent = .5cm }} -% Use @smallerbook to reset parameters for 6x9 trim size. -% (Just testing, parameters still in flux.) -\def\smallerbook{{\globaldefs = 1 - \parskip = 1.5pt plus 1pt - \textleading = 12pt - % - \internalpagesizes{7.4in}{4.8in}% - {-.2in}{-.4in}% - {0pt}{14pt}% - {9in}{6in}% - % - \lispnarrowing = 0.25in - \tolerance = 700 - \contentsrightmargin = 0pt - \defbodyindent = .4cm -}} - % Use @afourpaper to print on European A4 paper. \def\afourpaper{{\globaldefs = 1 \parskip = 3pt plus 2pt minus 1pt @@ -11294,7 +11905,7 @@ \textleading = 12.5pt % \internalpagesizes{160mm}{120mm}% - {\voffset}{\hoffset}% + {\voffset}{-11.4mm}% {\bindingoffset}{8pt}% {210mm}{148mm}% % @@ -11373,9 +11984,138 @@ \hfuzz = 1pt +\message{microtype,} + +% protrusion, from Thanh's protcode.tex. +\def\mtsetprotcode#1{% + \rpcode#1`\!=200 \rpcode#1`\,=700 \rpcode#1`\-=700 \rpcode#1`\.=700 + \rpcode#1`\;=500 \rpcode#1`\:=500 \rpcode#1`\?=200 + \rpcode#1`\'=700 + \rpcode#1 34=500 % '' + \rpcode#1 123=300 % -- + \rpcode#1 124=200 % --- + \rpcode#1`\)=50 \rpcode#1`\A=50 \rpcode#1`\F=50 \rpcode#1`\K=50 + \rpcode#1`\L=50 \rpcode#1`\T=50 \rpcode#1`\V=50 \rpcode#1`\W=50 + \rpcode#1`\X=50 \rpcode#1`\Y=50 \rpcode#1`\k=50 \rpcode#1`\r=50 + \rpcode#1`\t=50 \rpcode#1`\v=50 \rpcode#1`\w=50 \rpcode#1`\x=50 + \rpcode#1`\y=50 + % + \lpcode#1`\`=700 + \lpcode#1 92=500 % `` + \lpcode#1`\(=50 \lpcode#1`\A=50 \lpcode#1`\J=50 \lpcode#1`\T=50 + \lpcode#1`\V=50 \lpcode#1`\W=50 \lpcode#1`\X=50 \lpcode#1`\Y=50 + \lpcode#1`\v=50 \lpcode#1`\w=50 \lpcode#1`\x=50 \lpcode#1`\y=0 + % + \mtadjustprotcode#1\relax +} + +\newcount\countC +\def\mtadjustprotcode#1{% + \countC=0 + \loop + \ifcase\lpcode#1\countC\else + \mtadjustcp\lpcode#1\countC + \fi + \ifcase\rpcode#1\countC\else + \mtadjustcp\rpcode#1\countC + \fi + \advance\countC 1 + \ifnum\countC < 256 \repeat +} + +\newcount\countB +\def\mtadjustcp#1#2#3{% + \setbox\boxA=\hbox{% + \ifx#2\font\else#2\fi + \char#3}% + \countB=\wd\boxA + \multiply\countB #1#2#3\relax + \divide\countB \fontdimen6 #2\relax + #1#2#3=\countB\relax +} + +\ifxetex % XeTeX + \mtsetprotcode\textrm + \def\mtfontexpand#1{} +\else + \ifluatex % LuaTeX + \mtsetprotcode\textrm + \def\mtfontexpand#1{\expandglyphsinfont#1 20 20 1\relax} + \else + \ifpdf % pdfTeX + \mtsetprotcode\textrm + \def\mtfontexpand#1{\pdffontexpand#1 20 20 1 autoexpand\relax} + \else % TeX + \def\mtfontexpand#1{} + \fi + \fi +\fi + + +\newif\ifmicrotype + +\def\microtypeON{% + \microtypetrue + % + \ifxetex % XeTeX + \XeTeXprotrudechars=2 + \else + \ifluatex % LuaTeX + \adjustspacing=2 + \protrudechars=2 + \else + \ifpdf % pdfTeX + \pdfadjustspacing=2 + \pdfprotrudechars=2 + \fi + \fi + \fi + % + \mtfontexpand\textrm + \mtfontexpand\textsl + \mtfontexpand\textbf +} + +\def\microtypeOFF{% + \microtypefalse + % + \ifxetex % XeTeX + \XeTeXprotrudechars=0 + \else + \ifluatex % LuaTeX + \adjustspacing=0 + \protrudechars=0 + \else + \ifpdf % pdfTeX + \pdfadjustspacing=0 + \pdfprotrudechars=0 + \fi + \fi + \fi +} + +\microtypeOFF + +\parseargdef\microtype{% + \def\txiarg{#1}% + \ifx\txiarg\onword + \microtypeON + \else\ifx\txiarg\offword + \microtypeOFF + \else + \errhelp = \EMsimple + \errmessage{Unknown @microtype option `\txiarg', must be on|off}% + \fi\fi +} + + \message{and turning on texinfo input format.} +% Make UTF-8 the default encoding. +\documentencodingzzz{UTF-8} + \def^^L{\par} % remove \outer, so ^L can appear in an @comment +\catcode`\^^K = 10 % treat vertical tab as whitespace % DEL is a comment character, in case @c does not suffice. \catcode`\^^? = 14 @@ -11391,23 +12131,6 @@ \catcode`\|=\other \def\normalverticalbar{|} \catcode`\~=\other \def\normaltilde{~} -% This macro is used to make a character print one way in \tt -% (where it can probably be output as-is), and another way in other fonts, -% where something hairier probably needs to be done. -% -% #1 is what to print if we are indeed using \tt; #2 is what to print -% otherwise. Since all the Computer Modern typewriter fonts have zero -% interword stretch (and shrink), and it is reasonable to expect all -% typewriter fonts to have this, we can check that font parameter. -% -\def\ifusingtt#1#2{\ifdim \fontdimen3\font=0pt #1\else #2\fi} - -% Same as above, but check for italic font. Actually this also catches -% non-italic slanted fonts since it is impossible to distinguish them from -% italic fonts. But since this is only used by $ and it uses \sl anyway -% this is not a problem. -\def\ifusingit#1#2{\ifdim \fontdimen1\font>0pt #1\else #2\fi} - % Set catcodes for Texinfo file % Active characters for printing the wanted glyph. @@ -11442,7 +12165,7 @@ \def\texinfochars{% \let< = \activeless \let> = \activegtr - \let~ = \activetilde + \let~ = \activetilde \let^ = \activehat \setregularquotes \let\b = \strong @@ -11453,23 +12176,32 @@ % Used sometimes to turn off (effectively) the active characters even after % parsing them. \def\turnoffactive{% - \normalturnoffactive + \passthroughcharstrue + \let-=\normaldash + \let"=\normaldoublequote + \let$=\normaldollar %$ font-lock fix + \let+=\normalplus + \let<=\normalless + \let>=\normalgreater + \let^=\normalcaret + \let_=\normalunderscore + \let|=\normalverticalbar + \let~=\normaltilde \otherbackslash + \setregularquotes + \unsepspaces } -\catcode`\@=0 +% If a .fmt file is being used, characters that might appear in a file +% name cannot be active until we have parsed the command line. +% So turn them off again, and have \loadconf turn them back on. +\catcode`+=\other \catcode`\_=\other + % \backslashcurfont outputs one backslash character in current font, % as in \char`\\. \global\chardef\backslashcurfont=`\\ -% \realbackslash is an actual character `\' with catcode other. -{\catcode`\\=\other @gdef@realbackslash{\}} - -% In Texinfo, backslash is an active character; it prints the backslash -% in fixed width font. -\catcode`\\=\active % @ for escape char from now on. - % Print a typewriter backslash. For math mode, we can't simply use % \backslashcurfont: the story here is that in math mode, the \char % of \backslashcurfont ends up printing the roman \ from the math symbol @@ -11479,109 +12211,125 @@ % ignored family value; char position "5C). We can't use " for the % usual hex value because it has already been made active. -@def@ttbackslash{{@tt @ifmmode @mathchar29020 @else @backslashcurfont @fi}} -@let@backslashchar = @ttbackslash % @backslashchar{} is for user documents. - -% \otherbackslash defines an active \ to be a literal `\' character with -% catcode other. -@gdef@otherbackslash{@let\=@realbackslash} - -% Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of -% the literal character `\'. -% -{@catcode`- = @active - @gdef@normalturnoffactive{% - @passthroughcharstrue - @let-=@normaldash - @let"=@normaldoublequote - @let$=@normaldollar %$ font-lock fix - @let+=@normalplus - @let<=@normalless - @let>=@normalgreater - @let^=@normalcaret - @let_=@normalunderscore - @let|=@normalverticalbar - @let~=@normaltilde - @let\=@ttbackslash - @setregularquotes - @unsepspaces - } -} +\def\ttbackslash{{\tt \ifmmode \mathchar29020 \else \backslashcurfont \fi}} +\let\backslashchar = \ttbackslash % \backslashchar{} is for user documents. -% If a .fmt file is being used, characters that might appear in a file -% name cannot be active until we have parsed the command line. -% So turn them off again, and have @fixbackslash turn them back on. -@catcode`+=@other @catcode`@_=@other - -% \enablebackslashhack - allow file to begin `\input texinfo' -% -% If a .fmt file is being used, we don't want the `\input texinfo' to show up. -% That is what \eatinput is for; after that, the `\' should revert to printing -% a backslash. -% If the file did not have a `\input texinfo', then it is turned off after -% the first line; otherwise the first `\' in the file would cause an error. -% This is used on the very last line of this file, texinfo.tex. -% We also use @c to call @fixbackslash, in case ends of lines are hidden. -{ -@catcode`@^=7 -@catcode`@^^M=13@gdef@enablebackslashhack{% - @global@let\ = @eatinput% - @catcode`@^^M=13% - @def@c{@fixbackslash@c}% - % Definition for the newline at the end of this file. - @def ^^M{@let^^M@secondlinenl}% - % Definition for a newline in the main Texinfo file. - @gdef @secondlinenl{@fixbackslash}% - % In case the first line has a whole-line command on it - @let@originalparsearg@parsearg - @def@parsearg{@fixbackslash@originalparsearg} +% These are made active for url-breaking, so need +% active definitions as the normal characters. +\def\normaldot{.} +\def\normalquest{?} +\def\normalslash{/} + +% \newlinesloadsconf - call \loadconf as soon as possible in the +% file, e.g. at the first newline. +% +{\catcode`\^=7 +\catcode`\^^M=13 +\gdef\newlineloadsconf{% + \catcode`\^^M=13 % + \newlineloadsconfzz% +} +\gdef\newlineloadsconfzz#1^^M{% + \def\c{\loadconf\c}% + % Definition for the first newline read in the file + \def ^^M{\loadconf}% + % In case the first line has a whole-line or environment command on it + \let\originalparsearg\parsearg% + \def\parsearg{\loadconf\originalparsearg}% + % + % \startenvironment is in the expansion of commands defined with \envdef + \let\originalstartenvironment\startenvironment% + \def\startenvironment{\loadconf\startenvironment}% }} -{@catcode`@^=7 @catcode`@^^M=13% -@gdef@eatinput input texinfo#1^^M{@fixbackslash}} % Emergency active definition of newline, in case an active newline token % appears by mistake. -{@catcode`@^=7 @catcode13=13% -@gdef@enableemergencynewline{% - @gdef^^M{% - @par% - %<warning: active newline>@par% +{\catcode`\^=7 \catcode13=13% +\gdef\enableemergencynewline{% + \gdef^^M{% + \par% + %<warning: active newline>\par% }}} -@gdef@fixbackslash{% - @ifx\@eatinput @let\ = @ttbackslash @fi - @catcode13=5 % regular end of line - @enableemergencynewline - @let@c=@comment - @let@parsearg@originalparsearg +% \loadconf gets called at the beginning of every Texinfo file. +% If texinfo.cnf is present on the system, read it. Useful for site-wide +% @afourpaper, etc. Not opening texinfo.cnf directly in texinfo.tex +% makes it possible to make a format file for Texinfo. +% +\gdef\loadconf{% + \relax % Terminate the filename if running as "tex '&texinfo' FILE.texi". + % + % Turn off the definitions that trigger \loadconf + \everyjobreset + \catcode13=5 % regular end of line + \enableemergencynewline + \let\c=\comment + \let\parsearg\originalparsearg + \let\startenvironment\originalstartenvironment + % % Also turn back on active characters that might appear in the input % file name, in case not using a pre-dumped format. - @catcode`+=@active - @catcode`@_=@active - % - % If texinfo.cnf is present on the system, read it. - % Useful for site-wide @afourpaper, etc. This macro, @fixbackslash, gets - % called at the beginning of every Texinfo file. Not opening texinfo.cnf - % directly in this file, texinfo.tex, makes it possible to make a format - % file for Texinfo. + \catcode`+=\active + \catcode`\_=\active % - @openin 1 texinfo.cnf - @ifeof 1 @else @input texinfo.cnf @fi - @closein 1 + \openin 1 texinfo.cnf + \ifeof 1 \else \input texinfo.cnf \fi + \closein 1 } +% Redefine some control sequences to be controlled by the \ifdummies +% and \ifindexnofonts switches. Do this at the end so that the control +% sequences are all defined. +\definedummies + + + + +\catcode`\@=0 + +% \realbackslash is an actual character `\' with catcode other. +{\catcode`\\=\other @gdef@realbackslash{\}} + +% In Texinfo, backslash is an active character; it prints the backslash +% in fixed width font. +\catcode`\\=\active % @ for escape char from now on. + +@let\ = @ttbackslash + +% If in a .fmt file, print the version number. +% \eatinput stops the `\input texinfo' from showing up. +% After that, `\' should revert to printing a backslash. +% Turn on active characters that we couldn't do earlier because +% they might have appeared in the input file name. +% +@everyjob{@message{[Texinfo version @texinfoversion]}% + @global@let\ = @eatinput + @catcode`+=@active @catcode`@_=@active} + +{@catcode`@^=7 @catcode`@^^M=13% +@gdef@eatinput input texinfo#1^^M{@loadconf}} + +@def@everyjobreset{@ifx\@eatinput @let\ = @ttbackslash @fi} + +% \otherbackslash defines an active \ to be a literal `\' character with +% catcode other. +@gdef@otherbackslash{@let\=@realbackslash} + +% Same as @turnoffactive except outputs \ as {\tt\char`\\} instead of +% the literal character `\'. +% +{@catcode`- = @active + @gdef@normalturnoffactive{% + @turnoffactive + @let\=@ttbackslash + } +} % Say @foo, not \foo, in error messages. @escapechar = `@@ -% These (along with & and #) are made active for url-breaking, so need -% active definitions as the normal characters. -@def@normaldot{.} -@def@normalquest{?} -@def@normalslash{/} - % These look ok in all fonts, so just make them not special. % @hashchar{} gets its own user-level command, because of #line. @catcode`@& = @other @def@normalamp{&} @@ -11596,17 +12344,11 @@ @c Do this last of all since we use ` in the previous @catcode assignments. @catcode`@'=@active @catcode`@`=@active -@setregularquotes @c Local variables: -@c eval: (add-hook 'before-save-hook 'time-stamp) -@c page-delimiter: "^\\\\message\\|emacs-page" -@c time-stamp-start: "def\\\\texinfoversion{" -@c time-stamp-format: "%:y-%02m-%02d.%02H" -@c time-stamp-end: "}" +@c eval: (add-hook 'before-save-hook 'time-stamp nil t) +@c time-stamp-pattern: "texinfoversion{%Y-%02m-%02d.%02H}" +@c page-delimiter: "^\\\\message" @c End: -@c vim:sw=2: - -@enablebackslashhack - +@newlineloadsconf diff --git a/deps/libffi/doc/version.texi b/deps/libffi/doc/version.texi index dc281e38e0f6..c9adde9c03f9 100644 --- a/deps/libffi/doc/version.texi +++ b/deps/libffi/doc/version.texi @@ -1,4 +1,4 @@ -@set UPDATED 8 August 2026 -@set UPDATED-MONTH August 2026 -@set EDITION 3.8.0 -@set VERSION 3.8.0 +@set UPDATED 14 November 2026 +@set UPDATED-MONTH November 2026 +@set EDITION 3.8.1 +@set VERSION 3.8.1 diff --git a/deps/libffi/fficonfig.h.in b/deps/libffi/fficonfig.h.in index 0b35a6be073c..78c52d934035 100644 --- a/deps/libffi/fficonfig.h.in +++ b/deps/libffi/fficonfig.h.in @@ -71,10 +71,10 @@ /* Define if you support more than one size of the long double type */ #undef HAVE_LONG_DOUBLE_VARIANT -/* Define to 1 if you have the `memcpy' function. */ +/* Define to 1 if you have the 'memcpy' function. */ #undef HAVE_MEMCPY -/* Define to 1 if you have the `memfd_create' function. */ +/* Define to 1 if you have the 'memfd_create' function. */ #undef HAVE_MEMFD_CREATE /* Define if .eh_frame sections should be read-only. */ @@ -134,16 +134,16 @@ /* Define to the version of this package. */ #undef PACKAGE_VERSION -/* The size of `double', as computed by sizeof. */ +/* The size of 'double', as computed by sizeof. */ #undef SIZEOF_DOUBLE -/* The size of `long double', as computed by sizeof. */ +/* The size of 'long double', as computed by sizeof. */ #undef SIZEOF_LONG_DOUBLE -/* The size of `size_t', as computed by sizeof. */ +/* The size of 'size_t', as computed by sizeof. */ #undef SIZEOF_SIZE_T -/* Define to 1 if all of the C90 standard headers exist (not just the ones +/* Define to 1 if all of the C89 standard headers exist (not just the ones required in a freestanding environment). This macro is provided for backward compatibility; new code need not use it. */ #undef STDC_HEADERS diff --git a/deps/libffi/generate-headers.py b/deps/libffi/generate-headers.py index fb58edf17b66..b17dadff0801 100644 --- a/deps/libffi/generate-headers.py +++ b/deps/libffi/generate-headers.py @@ -7,8 +7,8 @@ from pathlib import Path -LIBFFI_VERSION = '3.8.0' -LIBFFI_VERSION_NUMBER = '30800' +LIBFFI_VERSION = '3.8.1' +LIBFFI_VERSION_NUMBER = '30801' def normalize_arch(target_arch): aliases = { diff --git a/deps/libffi/include/Makefile.in b/deps/libffi/include/Makefile.in index 8851d33a6f98..fa38efaf444d 100644 --- a/deps/libffi/include/Makefile.in +++ b/deps/libffi/include/Makefile.in @@ -1,7 +1,7 @@ -# Makefile.in generated by automake 1.16.5 from Makefile.am. +# Makefile.in generated by automake 1.18.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2021 Free Software Foundation, Inc. +# Copyright (C) 1994-2025 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -70,6 +70,8 @@ am__make_running_with_option = \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +am__rm_f = rm -f $(am__rm_f_notfound) +am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -155,10 +157,9 @@ am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ - test -z "$$files" \ - || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ - || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ - $(am__cd) "$$dir" && rm -f $$files; }; \ + { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } am__installdirs = "$(DESTDIR)$(includedir)" HEADERS = $(nodist_include_HEADERS) $(noinst_HEADERS) @@ -282,8 +283,10 @@ ac_ct_READELF = @ac_ct_READELF@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ +am__xargs_n = @am__xargs_n@ ax_enable_builddir_sed = @ax_enable_builddir_sed@ bindir = @bindir@ build = @build@ @@ -452,6 +455,7 @@ cscopelist-am: $(am__tagged_files) distclean-tags: -rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags + distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am @@ -516,9 +520,9 @@ mostlyclean-generic: clean-generic: distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) - -test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES) + -$(am__rm_f) $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) + -$(am__rm_f) $(DISTCLEANFILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -611,3 +615,10 @@ uninstall-am: uninstall-nodist_includeHEADERS # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: + +# Tell GNU make to disable its built-in pattern rules. +%:: %,v +%:: RCS/%,v +%:: RCS/% +%:: s.% +%:: SCCS/s.% diff --git a/deps/libffi/install-sh b/deps/libffi/install-sh index ec298b537402..1d8d96696466 100755 --- a/deps/libffi/install-sh +++ b/deps/libffi/install-sh @@ -1,7 +1,7 @@ #!/bin/sh # install - install a program, script, or datafile -scriptversion=2020-11-14.01; # UTC +scriptversion=2025-06-18.21; # UTC # This originates from X11R5 (mit/util/scripts/install.sh), which was # later released in X11R6 (xc/config/util/install.sh) with the @@ -124,9 +124,9 @@ it's up to you to specify -f if you want it. If -S is not specified, no backups are attempted. -Email bug reports to bug-automake@gnu.org. -Automake home page: https://www.gnu.org/software/automake/ -" +Report bugs to <bug-automake@gnu.org>. +GNU Automake home page: <https://www.gnu.org/software/automake/>. +General help using GNU software: <https://www.gnu.org/gethelp/>." while test $# -ne 0; do case $1 in @@ -170,7 +170,7 @@ while test $# -ne 0; do -T) is_target_a_directory=never;; - --version) echo "$0 $scriptversion"; exit $?;; + --version) echo "$0 (GNU Automake) $scriptversion"; exit $?;; --) shift break;; @@ -345,7 +345,7 @@ do ' 0 # Because "mkdir -p" follows existing symlinks and we likely work - # directly in world-writeable /tmp, make sure that the '$tmpdir' + # directly in world-writable /tmp, make sure that the '$tmpdir' # directory is successfully created first before we actually test # 'mkdir -p'. if (umask $mkdir_umask && @@ -353,7 +353,7 @@ do exec $mkdirprog $mkdir_mode -p -- "$tmpdir/a/b") >/dev/null 2>&1 then if test -z "$dir_arg" || { - # Check for POSIX incompatibilities with -m. + # Check for POSIX incompatibility with -m. # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or # other-writable bit of parent directory when it shouldn't. # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. @@ -533,9 +533,9 @@ do done # Local variables: -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/libtool-version b/deps/libffi/libtool-version index 814c6e21d925..5b9d55999538 100644 --- a/deps/libffi/libtool-version +++ b/deps/libffi/libtool-version @@ -26,4 +26,4 @@ # release, then set age to 0. # # CURRENT:REVISION:AGE -13:0:5 +13:1:5 diff --git a/deps/libffi/ltmain.sh b/deps/libffi/ltmain.sh index 977e5237bb01..22edd1403fb4 100755 --- a/deps/libffi/ltmain.sh +++ b/deps/libffi/ltmain.sh @@ -2,11 +2,11 @@ ## DO NOT EDIT - This file generated from ./build-aux/ltmain.in ## by inline-source v2019-02-19.15 -# libtool (GNU libtool) 2.4.7 +# libtool (GNU libtool) 2.5.4 # Provide generalized library-building support services. # Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996 -# Copyright (C) 1996-2019, 2021-2022 Free Software Foundation, Inc. +# Copyright (C) 1996-2019, 2021-2024 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. @@ -31,8 +31,8 @@ PROGRAM=libtool PACKAGE=libtool -VERSION="2.4.7 Debian-2.4.7-7build1" -package_revision=2.4.7 +VERSION="2.5.4 Debian-2.5.4-9" +package_revision=2.5.4 ## ------ ## @@ -64,7 +64,7 @@ package_revision=2.4.7 # libraries, which are installed to $pkgauxdir. # Set a version string for this script. -scriptversion=2019-02-19.15; # UTC +scriptversion=2024-12-01.17; # UTC # General shell script boiler plate, and helper functions. # Written by Gary V. Vaughan, 2004 @@ -72,11 +72,11 @@ scriptversion=2019-02-19.15; # UTC # This is free software. There is NO warranty; not even for # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # -# Copyright (C) 2004-2019, 2021 Bootstrap Authors +# Copyright (C) 2004-2019, 2021, 2023-2024 Bootstrap Authors # # This file is dual licensed under the terms of the MIT license -# <https://opensource.org/license/MIT>, and GPL version 2 or later -# <http://www.gnu.org/licenses/gpl-2.0.html>. You must apply one of +# <https://opensource.org/licenses/MIT>, and GPL version 2 or later +# <https://www.gnu.org/licenses/gpl-2.0.html>. You must apply one of # these licenses when using or redistributing this software or any of # the files within it. See the URLs above, or the file `LICENSE` # included in the Bootstrap distribution for the full license texts. @@ -143,7 +143,7 @@ nl=' ' IFS="$sp $nl" -# There are apparently some retarded systems that use ';' as a PATH separator! +# There are apparently some systems that use ';' as a PATH separator! if test "${PATH_SEPARATOR+set}" != set; then PATH_SEPARATOR=: (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { @@ -572,15 +572,16 @@ func_require_term_colors () # --------------------- # Append VALUE onto the existing contents of VAR. + # _G_HAVE_PLUSEQ_OP # Can be empty, in which case the shell is probed, "yes" if += is - # useable or anything else if it does not work. - if test -z "$_G_HAVE_PLUSEQ_OP" && \ - __PLUSEQ_TEST="a" && \ - __PLUSEQ_TEST+=" b" 2>/dev/null && \ - test "a b" = "$__PLUSEQ_TEST"; then - _G_HAVE_PLUSEQ_OP=yes - fi + # usable or anything else if it does not work. +if test -z "$_G_HAVE_PLUSEQ_OP" && \ + __PLUSEQ_TEST="a" && \ + __PLUSEQ_TEST+=" b" 2>/dev/null && \ + test "a b" = "$__PLUSEQ_TEST"; then + _G_HAVE_PLUSEQ_OP=yes +fi if test yes = "$_G_HAVE_PLUSEQ_OP" then @@ -727,7 +728,7 @@ eval 'func_dirname () # to NONDIR_REPLACEMENT. # value returned in "$func_dirname_result" # basename: Compute filename of FILE. -# value retuned in "$func_basename_result" +# value returned in "$func_basename_result" # For efficiency, we do not delegate to the functions above but instead # duplicate the functionality here. eval 'func_dirname_and_basename () @@ -885,7 +886,7 @@ func_mkdir_p () # While some portion of DIR does not yet exist... while test ! -d "$_G_directory_path"; do # ...make a list in topmost first order. Use a colon delimited - # list incase some portion of path contains whitespace. + # list in case some portion of path contains whitespace. _G_dir_list=$_G_directory_path:$_G_dir_list # If the last portion added has no slash in it, the list is done @@ -1524,11 +1525,11 @@ func_lt_ver () # This is free software. There is NO warranty; not even for # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # -# Copyright (C) 2010-2019, 2021 Bootstrap Authors +# Copyright (C) 2010-2019, 2021, 2023-2024 Bootstrap Authors # # This file is dual licensed under the terms of the MIT license -# <https://opensource.org/license/MIT>, and GPL version 2 or later -# <http://www.gnu.org/licenses/gpl-2.0.html>. You must apply one of +# <https://opensource.org/licenses/MIT>, and GPL version 2 or later +# <https://www.gnu.org/licenses/gpl-2.0.html>. You must apply one of # these licenses when using or redistributing this software or any of # the files within it. See the URLs above, or the file `LICENSE` # included in the Bootstrap distribution for the full license texts. @@ -2205,7 +2206,30 @@ func_version () # End: # Set a version string. -scriptversion='(GNU libtool) 2.4.7' +scriptversion='(GNU libtool) 2.5.4' + +# func_version +# ------------ +# Echo version message to standard output and exit. +func_version () +{ + $debug_cmd + + year=`date +%Y` + + cat <<EOF +$progname $scriptversion Debian-2.5.4-9 +Copyright (C) $year Free Software Foundation, Inc. +License GPLv2+: GNU GPL version 2 or later <https://gnu.org/licenses/gpl.html> +This is free software: you are free to change and redistribute it. +There is NO WARRANTY, to the extent permitted by law. + +Originally written by Gordon Matzigkeit, 1996 +(See AUTHORS for complete contributor listing) +EOF + + exit $? +} # func_echo ARG... @@ -2228,18 +2252,6 @@ func_echo () } -# func_warning ARG... -# ------------------- -# Libtool warnings are not categorized, so override funclib.sh -# func_warning with this simpler definition. -func_warning () -{ - $debug_cmd - - $warning_func ${1+"$@"} -} - - ## ---------------- ## ## Options parsing. ## ## ---------------- ## @@ -2251,19 +2263,23 @@ usage='$progpath [OPTION]... [MODE-ARG]...' # Short help message in response to '-h'. usage_message="Options: - --config show all configuration variables - --debug enable verbose shell tracing - -n, --dry-run display commands without modifying any files - --features display basic configuration information and exit - --mode=MODE use operation mode MODE - --no-warnings equivalent to '-Wnone' - --preserve-dup-deps don't remove duplicate dependency libraries - --quiet, --silent don't print informational messages - --tag=TAG use configuration variables from tag TAG - -v, --verbose print more informational messages than default - --version print version information - -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] - -h, --help, --help-all print short, long, or detailed help message + --config show all configuration variables + --debug enable verbose shell tracing + -n, --dry-run display commands without modifying any files + --features display basic configuration information + --finish use operation '--mode=finish' + --mode=MODE use operation mode MODE + --no-finish don't update shared library cache + --no-quiet, --no-silent print default informational messages + --no-warnings equivalent to '-Wnone' + --preserve-dup-deps don't remove duplicate dependency libraries + --quiet, --silent don't print informational messages + --reorder-cache=DIRS reorder shared library cache for preferred DIRS + --tag=TAG use configuration variables from tag TAG + -v, --verbose print more informational messages than default + --version print version information + -W, --warnings=CATEGORY report the warnings falling in CATEGORY [all] + -h, --help, --help-all print short, long, or detailed help message " # Additional text appended to 'usage_message' in response to '--help'. @@ -2296,13 +2312,13 @@ include the following information: compiler: $LTCC compiler flags: $LTCFLAGS linker: $LD (gnu? $with_gnu_ld) - version: $progname $scriptversion Debian-2.4.7-7build1 + version: $progname $scriptversion Debian-2.5.4-9 automake: `($AUTOMAKE --version) 2>/dev/null |$SED 1q` autoconf: `($AUTOCONF --version) 2>/dev/null |$SED 1q` Report bugs to <bug-libtool@gnu.org>. -GNU libtool home page: <http://www.gnu.org/s/libtool/>. -General help using GNU software: <http://www.gnu.org/gethelp/>." +GNU libtool home page: <https://www.gnu.org/s/libtool/>. +General help using GNU software: <https://www.gnu.org/gethelp/>." exit 0 } @@ -2492,8 +2508,11 @@ libtool_options_prep () opt_dry_run=false opt_help=false opt_mode= + opt_reorder_cache=false opt_preserve_dup_deps=false opt_quiet=false + opt_finishing=true + opt_warning= nonopt= preserve_args= @@ -2585,14 +2604,18 @@ libtool_parse_options () clean|compile|execute|finish|install|link|relink|uninstall) ;; # Catch anything else as an error - *) func_error "invalid argument for $_G_opt" + *) func_error "invalid argument '$1' for $_G_opt" exit_cmd=exit - break ;; esac shift ;; + --no-finish) + opt_finishing=false + func_append preserve_args " $_G_opt" + ;; + --no-silent|--no-quiet) opt_quiet=false func_append preserve_args " $_G_opt" @@ -2608,6 +2631,24 @@ libtool_parse_options () func_append preserve_args " $_G_opt" ;; + --reorder-cache) + opt_reorder_cache=true + shared_lib_dirs=$1 + if test -n "$shared_lib_dirs"; then + case $1 in + # Must begin with /: + /*) ;; + + # Catch anything else as an error (relative paths) + *) func_error "invalid argument '$1' for $_G_opt" + func_error "absolute paths are required for $_G_opt" + exit_cmd=exit + ;; + esac + fi + shift + ;; + --silent|--quiet) opt_quiet=: opt_verbose=false @@ -2644,6 +2685,18 @@ libtool_parse_options () func_add_hook func_parse_options libtool_parse_options +# func_warning ARG... +# ------------------- +# Libtool warnings are not categorized, so override funclib.sh +# func_warning with this simpler definition. +func_warning () +{ + if $opt_warning; then + $debug_cmd + $warning_func ${1+"$@"} + fi +} + # libtool_validate_options [ARG]... # --------------------------------- @@ -2660,10 +2713,10 @@ libtool_validate_options () # preserve --debug test : = "$debug_cmd" || func_append preserve_args " --debug" - case $host in + case $host_os in # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452 # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788 - *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*) + cygwin* | mingw* | windows* | pw32* | cegcc* | solaris2* | os2*) # don't eliminate duplications in $postdeps and $predeps opt_duplicate_compiler_generated_deps=: ;; @@ -2995,7 +3048,7 @@ EOF # func_convert_core_file_wine_to_w32 ARG # Helper function used by file name conversion functions when $build is *nix, -# and $host is mingw, cygwin, or some other w32 environment. Relies on a +# and $host is mingw, windows, cygwin, or some other w32 environment. Relies on a # correctly configured wine environment available, with the winepath program # in $build's $PATH. # @@ -3027,9 +3080,10 @@ func_convert_core_file_wine_to_w32 () # func_convert_core_path_wine_to_w32 ARG # Helper function used by path conversion functions when $build is *nix, and -# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly -# configured wine environment available, with the winepath program in $build's -# $PATH. Assumes ARG has no leading or trailing path separator characters. +# $host is mingw, windows, cygwin, or some other w32 environment. Relies on a +# correctly configured wine environment available, with the winepath program +# in $build's $PATH. Assumes ARG has no leading or trailing path separator +# characters. # # ARG is path to be converted from $build format to win32. # Result is available in $func_convert_core_path_wine_to_w32_result. @@ -3172,6 +3226,15 @@ func_convert_path_front_back_pathsep () # end func_convert_path_front_back_pathsep +# func_convert_delimited_path PATH ORIG_DELIMITER NEW_DELIMITER +# Replaces a delimiter for a given path. +func_convert_delimited_path () +{ + converted_path=`$ECHO "$1" | $SED "s#$2#$3#g"` +} +# end func_convert_delimited_path + + ################################################## # $build to $host FILE NAME CONVERSION FUNCTIONS # ################################################## @@ -3506,6 +3569,65 @@ func_dll_def_p () } +# func_reorder_shared_lib_cache DIRS +# Reorder the shared library cache by unconfiguring previous shared library cache +# and configuring preferred search directories before previous search directories. +# Previous shared library cache: /usr/lib /usr/local/lib +# Preferred search directories: /tmp/testing +# Reordered shared library cache: /tmp/testing /usr/lib /usr/local/lib +func_reorder_shared_lib_cache () +{ + $debug_cmd + + case $host_os in + openbsd*) + get_search_directories=`PATH="$PATH:/sbin" ldconfig -r | $GREP "search directories" | $SED "s#.*search directories:\ ##g"` + func_convert_delimited_path "$get_search_directories" ':' '\ ' + save_search_directories=$converted_path + func_convert_delimited_path "$1" ':' '\ ' + + # Ensure directories exist + for dir in $converted_path; do + # Ensure each directory is an absolute path + case $dir in + /*) ;; + *) func_error "Directory '$dir' is not an absolute path" + exit $EXIT_FAILURE ;; + esac + # Ensure no trailing slashes + func_stripname '' '/' "$dir" + dir=$func_stripname_result + if test -d "$dir"; then + if test -n "$preferred_search_directories"; then + preferred_search_directories="$preferred_search_directories $dir" + else + preferred_search_directories=$dir + fi + else + func_error "Directory '$dir' does not exist" + exit $EXIT_FAILURE + fi + done + + PATH="$PATH:/sbin" ldconfig -U $save_search_directories + PATH="$PATH:/sbin" ldconfig -m $preferred_search_directories $save_search_directories + get_search_directories=`PATH="$PATH:/sbin" ldconfig -r | $GREP "search directories" | $SED "s#.*search directories:\ ##g"` + func_convert_delimited_path "$get_search_directories" ':' '\ ' + reordered_search_directories=$converted_path + + $ECHO "Original: $save_search_directories" + $ECHO "Reordered: $reordered_search_directories" + exit $EXIT_SUCCESS + ;; + *) + func_error "--reorder-cache is not supported for host_os=$host_os." + exit $EXIT_FAILURE + ;; + esac +} +# end func_reorder_shared_lib_cache + + # func_mode_compile arg... func_mode_compile () { @@ -3684,7 +3806,7 @@ func_mode_compile () # On Cygwin there's no "real" PIC flag so we must build both object types case $host_os in - cygwin* | mingw* | pw32* | os2* | cegcc*) + cygwin* | mingw* | windows* | pw32* | os2* | cegcc*) pic_mode=default ;; esac @@ -4078,6 +4200,12 @@ if $opt_help; then fi +# If option '--reorder-cache', reorder the shared library cache and exit. +if $opt_reorder_cache; then + func_reorder_shared_lib_cache $shared_lib_dirs +fi + + # func_mode_execute arg... func_mode_execute () { @@ -4262,7 +4390,7 @@ func_mode_finish () fi fi - if test -n "$finish_cmds$finish_eval" && test -n "$libdirs"; then + if test -n "$finish_cmds$finish_eval" && test -n "$libdirs" && $opt_finishing; then for libdir in $libdirs; do if test -n "$finish_cmds"; then # Do each command in the finish commands. @@ -4287,6 +4415,12 @@ func_mode_finish () for libdir in $libdirs; do $ECHO " $libdir" done + if test "false" = "$opt_finishing"; then + echo + echo "NOTE: finish_cmds were not executed during testing, so you must" + echo "manually run ldconfig to add a given test directory, LIBDIR, to" + echo "the search path for generated executables." + fi echo echo "If you ever happen to want to link against installed libraries" echo "in a given directory, LIBDIR, you must either use libtool, and" @@ -4523,8 +4657,15 @@ func_mode_install () func_append dir "$objdir" if test -n "$relink_command"; then + # Strip any trailing slash from the destination. + func_stripname '' '/' "$libdir" + destlibdir=$func_stripname_result + + func_stripname '' '/' "$destdir" + s_destdir=$func_stripname_result + # Determine the prefix the user has applied to our future dir. - inst_prefix_dir=`$ECHO "$destdir" | $SED -e "s%$libdir\$%%"` + inst_prefix_dir=`$ECHO "X$s_destdir" | $Xsed -e "s%$destlibdir\$%%"` # Don't allow the user to place us outside of our expected # location b/c this prevents finding dependent libraries that @@ -4561,7 +4702,7 @@ func_mode_install () 'exit $?' tstripme=$stripme case $host_os in - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) case $realname in *.dll.a) tstripme= @@ -4674,7 +4815,7 @@ func_mode_install () # Do a test to see if this is really a libtool program. case $host in - *cygwin* | *mingw*) + *cygwin* | *mingw* | *windows*) if func_ltwrapper_executable_p "$file"; then func_ltwrapper_scriptname "$file" wrapper=$func_ltwrapper_scriptname_result @@ -4902,7 +5043,7 @@ extern \"C\" { $RM $export_symbols eval "$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \(.*\)$/\1/p' "'< "$nlist" > "$export_symbols"' case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$export_symbols" >> "$output_objdir/$outputname.def"' ;; @@ -4914,7 +5055,7 @@ extern \"C\" { eval '$GREP -f "$output_objdir/$outputname.exp" < "$nlist" > "$nlist"T' eval '$MV "$nlist"T "$nlist"' case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) eval "echo EXPORTS "'> "$output_objdir/$outputname.def"' eval 'cat "$nlist" >> "$output_objdir/$outputname.def"' ;; @@ -4928,7 +5069,7 @@ extern \"C\" { func_basename "$dlprefile" name=$func_basename_result case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) # if an import library, we need to obtain dlname if func_win32_import_lib_p "$dlprefile"; then func_tr_sh "$dlprefile" @@ -4954,8 +5095,16 @@ extern \"C\" { eval '$ECHO ": $name " >> "$nlist"' fi func_to_tool_file "$dlprefile" func_convert_file_msys_to_w32 - eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | - $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + case $host in + i[3456]86-*-mingw32*) + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'" + ;; + *) + eval "$NM \"$func_to_tool_file_result\" 2>/dev/null | $global_symbol_pipe | + $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/__nm_//' >> '$nlist'" + ;; + esac } else # not an import lib $opt_dry_run || { @@ -5103,7 +5252,7 @@ static const void *lt_preloaded_setup() { # Transform the symbol file into the correct name. symfileobj=$output_objdir/${my_outputname}S.$objext case $host in - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) if test -f "$output_objdir/$my_outputname.def"; then compile_command=`$ECHO "$compile_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` finalize_command=`$ECHO "$finalize_command" | $SED "s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%"` @@ -5179,7 +5328,7 @@ func_win32_libid () *ar\ archive*) # could be an import, or static # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD. if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null | - $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then + $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64|pe-aarch64)' >/dev/null; then case $nm_interface in "MS dumpbin") if func_cygming_ms_implib_p "$1" || @@ -5446,7 +5595,7 @@ func_extract_archives () # # Emit a libtool wrapper script on stdout. # Don't directly open a file because we may want to -# incorporate the script contents within a cygwin/mingw +# incorporate the script contents within a cygwin/mingw/windows # wrapper executable. Must ONLY be called from within # func_mode_link because it depends on a number of variables # set therein. @@ -5454,7 +5603,7 @@ func_extract_archives () # ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR # variable will take. If 'yes', then the emitted script # will assume that the directory where it is stored is -# the $objdir directory. This is a cygwin/mingw-specific +# the $objdir directory. This is a cygwin/mingw/windows-specific # behavior. func_emit_wrapper () { @@ -5579,7 +5728,7 @@ func_exec_program_core () " case $host in # Backslashes separate directories on plain windows - *-*-mingw | *-*-os2* | *-cegcc*) + *-*-mingw* | *-*-windows* | *-*-os2* | *-cegcc*) $ECHO "\ if test -n \"\$lt_option_debug\"; then \$ECHO \"$outputname:$output:\$LINENO: newargv[0]: \$progdir\\\\\$program\" 1>&2 @@ -5647,7 +5796,7 @@ func_exec_program () file=\`ls -ld \"\$thisdir/\$file\" | $SED -n 's/.*-> //p'\` done - # Usually 'no', except on cygwin/mingw when embedded into + # Usually 'no', except on cygwin/mingw/windows when embedded into # the cwrapper. WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1 if test \"\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\" = \"yes\"; then @@ -5779,7 +5928,7 @@ EOF #endif #include <stdio.h> #include <stdlib.h> -#ifdef _MSC_VER +#if defined _WIN32 && !defined __GNUC__ # include <direct.h> # include <process.h> # include <io.h> @@ -5804,7 +5953,7 @@ EOF /* declarations of non-ANSI functions */ #if defined __MINGW32__ # ifdef __STRICT_ANSI__ -int _putenv (const char *); +_CRTIMP int __cdecl _putenv (const char *); # endif #elif defined __CYGWIN__ # ifdef __STRICT_ANSI__ @@ -6002,7 +6151,7 @@ main (int argc, char *argv[]) { EOF case $host in - *mingw* | *cygwin* ) + *mingw* | *windows* | *cygwin* ) # make stdout use "unix" line endings echo " setmode(1,_O_BINARY);" ;; @@ -6021,7 +6170,7 @@ EOF { /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX namespace, but it is not one of the ones we know about and - have already dealt with, above (inluding dump-script), then + have already dealt with, above (including dump-script), then report an error. Otherwise, targets might begin to believe they are allowed to use options in the LTWRAPPER_OPTION_PREFIX namespace. The first time any user complains about this, we'll @@ -6105,7 +6254,7 @@ EOF EOF case $host_os in - mingw*) + mingw* | windows*) cat <<"EOF" { char* p; @@ -6147,7 +6296,7 @@ EOF EOF case $host_os in - mingw*) + mingw* | windows*) cat <<"EOF" /* execv doesn't actually work on mingw as expected on unix */ newargz = prepare_spawn (newargz); @@ -6566,7 +6715,7 @@ lt_update_lib_path (const char *name, const char *value) EOF case $host_os in - mingw*) + mingw* | windows*) cat <<"EOF" /* Prepares an argument vector before calling spawn(). @@ -6741,7 +6890,7 @@ func_mode_link () $debug_cmd case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-cegcc*) # It is impossible to link a dll without this setting, and # we shouldn't force the makefile maintainer to figure out # what system we are compiling for in order to pass an extra @@ -6765,6 +6914,7 @@ func_mode_link () finalize_command=$nonopt compile_rpath= + compile_rpath_tail= finalize_rpath= compile_shlibpath= finalize_shlibpath= @@ -6805,10 +6955,12 @@ func_mode_link () xrpath= perm_rpath= temp_rpath= + temp_rpath_tail= thread_safe=no vinfo= vinfo_number=no weak_libs= + rpath_arg= single_module=$wl-single_module func_infer_tag $base_compile @@ -7071,7 +7223,7 @@ func_mode_link () case $arg in [\\/]* | [A-Za-z]:[\\/]*) ;; *) - func_fatal_error "only absolute run-paths are allowed" + func_fatal_error "argument to -rpath is not absolute: $arg" ;; esac if test rpath = "$prev"; then @@ -7247,7 +7399,7 @@ func_mode_link () ;; esac case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$dir" | $SED 's*/lib$*/bin*'` case :$dllsearchpath: in *":$dir:"*) ;; @@ -7267,7 +7419,7 @@ func_mode_link () -l*) if test X-lc = "X$arg" || test X-lm = "X$arg"; then case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*) # These systems don't actually have a C or math library (as such) continue ;; @@ -7275,7 +7427,7 @@ func_mode_link () # These systems don't actually have a C library (as such) test X-lc = "X$arg" && continue ;; - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*) # Do not include libc due to us having libc/libc_r. test X-lc = "X$arg" && continue ;; @@ -7295,7 +7447,7 @@ func_mode_link () esac elif test X-lc_r = "X$arg"; then case $host in - *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*) + *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*) # Do not include libc_r directly, use -pthread flag. continue ;; @@ -7318,7 +7470,8 @@ func_mode_link () # Tru64 UNIX uses -model [arg] to determine the layout of C++ # classes, name mangling, and exception handling. # Darwin uses the -arch flag to determine output architecture. - -model|-arch|-isysroot|--sysroot) + # -q <option> for IBM XL C/C++ compiler. + -model|-arch|-isysroot|--sysroot|-q) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" @@ -7339,7 +7492,7 @@ func_mode_link () continue ;; -mt|-mthreads|-kthread|-Kthread|-pthreads|--thread-safe \ - |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + |-threads|-fopenmp|-fopenmp=*|-openmp|-mp|-xopenmp|-omp|-qsmp=*) func_append compiler_flags " $arg" func_append compile_command " $arg" func_append finalize_command " $arg" @@ -7362,7 +7515,7 @@ func_mode_link () -no-install) case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*) # The PATH hackery in wrapper scripts is required on Windows # and Darwin in order for the loader to find any dlls it needs. func_warning "'-no-install' is ignored for $host" @@ -7422,7 +7575,7 @@ func_mode_link () dir=$lt_sysroot$func_stripname_result ;; *) - func_fatal_error "only absolute run-paths are allowed" + func_fatal_error "argument ($arg) to '-R' is not an absolute path: $dir" ;; esac case "$xrpath " in @@ -7547,15 +7700,29 @@ func_mode_link () # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization # -specs=* GCC specs files # -stdlib=* select c++ std lib with clang + # -fdiagnostics-color* simply affects output + # -frecord-gcc-switches used to verify flags were respected # -fsanitize=* Clang/GCC memory and address sanitizer + # -fno-sanitize* Clang/GCC memory and address sanitizer + # -shared-libsan Link with shared sanitizer runtimes (Clang) + # -static-libsan Link with static sanitizer runtimes (Clang) + # -no-canonical-prefixes Do not expand any symbolic links # -fuse-ld=* Linker select flags for GCC # -static-* direct GCC to link specific libraries statically # -fcilkplus Cilk Plus language extension features for C/C++ + # -rtlib=* select c runtime lib with clang + # --unwindlib=* select unwinder library with clang + # -f{file|debug|macro|profile}-prefix-map=* needed for lto linking # -Wa,* Pass flags directly to the assembler + # -Werror, -Werror=* Report (specified) warnings as errors -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \ -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \ - -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \ - -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus|-Wa,*) + -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-no-canonical-prefixes| \ + -stdlib=*|-rtlib=*|--unwindlib=*| \ + -specs=*|-fsanitize=*|-fno-sanitize*|-shared-libsan|-static-libsan| \ + -ffile-prefix-map=*|-fdebug-prefix-map=*|-fmacro-prefix-map=*|-fprofile-prefix-map=*| \ + -fdiagnostics-color*|-frecord-gcc-switches| \ + -fuse-ld=*|-static-*|-fcilkplus|-Wa,*|-Werror|-Werror=*) func_quote_arg pretty "$arg" arg=$func_quote_arg_result func_append compile_command " $arg" @@ -7713,8 +7880,20 @@ func_mode_link () # Now actually substitute the argument into the commands. if test -n "$arg"; then - func_append compile_command " $arg" - func_append finalize_command " $arg" + if test -n "$rpath_arg"; then + func_append finalize_rpath " ${arg##*,}" + unset rpath_arg + else + case $arg in + -Wl,-rpath,*) + func_append finalize_rpath " ${arg##*,}";; + -Wl,-rpath) + rpath_arg=1;; + *) + func_append compile_command " $arg" + func_append finalize_command " $arg" + esac + fi fi done # argument parsing loop @@ -7888,7 +8067,7 @@ func_mode_link () found=false case $deplib in -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \ - |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*) + |-threads|-fopenmp|-fopenmp=*|-openmp|-mp|-xopenmp|-omp|-qsmp=*) if test prog,link = "$linkmode,$pass"; then compile_deplibs="$deplib $compile_deplibs" finalize_deplibs="$deplib $finalize_deplibs" @@ -8065,18 +8244,15 @@ func_mode_link () ;; esac if $valid_a_lib; then - echo - $ECHO "*** Warning: Linking the shared library $output against the" - $ECHO "*** static library $deplib is not portable!" + func_warning "Linking the shared library $output against the static library $deplib is not portable!" deplibs="$deplib $deplibs" else - echo - $ECHO "*** Warning: Trying to link with static lib archive $deplib." - echo "*** I have the capability to make that library automatically link in when" - echo "*** you link to this library. But I can only do this if you have a" - echo "*** shared version of the library, which you do not appear to have" - echo "*** because the file extensions .$libext of this argument makes me believe" - echo "*** that it is just a static archive that I should not use here." + func_warning "Trying to link with static lib archive $deplib." + func_warning "I have the capability to make that library automatically link in when" + func_warning "you link to this library. But I can only do this if you have a" + func_warning "shared version of the library, which you do not appear to have" + func_warning "because the file extensions .$libext of this argument makes me believe" + func_warning "that it is just a static archive that I should not use here." fi ;; esac @@ -8271,7 +8447,7 @@ func_mode_link () fi case $host in # special handling for platforms with PE-DLLs. - *cygwin* | *mingw* | *cegcc* ) + *cygwin* | *mingw* | *windows* | *cegcc* ) # Linker will automatically link against shared library if both # static and shared are present. Therefore, ensure we extract # symbols from the import library if a shared library is present @@ -8371,7 +8547,10 @@ func_mode_link () # Make sure the rpath contains only unique directories. case $temp_rpath: in *"$absdir:"*) ;; - *) func_append temp_rpath "$absdir:" ;; + *) case $absdir in + "$progdir/"*) func_append temp_rpath "$absdir:" ;; + *) func_append temp_rpath_tail "$absdir:" ;; + esac esac fi @@ -8381,9 +8560,12 @@ func_mode_link () case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) - case "$compile_rpath " in + case "$compile_rpath$compile_rpath_tail " in *" $absdir "*) ;; - *) func_append compile_rpath " $absdir" ;; + *) case $absdir in + "$progdir/"*) func_append compile_rpath " $absdir" ;; + *) func_append compile_rpath_tail " $absdir" ;; + esac esac ;; esac @@ -8414,8 +8596,8 @@ func_mode_link () fi if test -n "$library_names" && { test no = "$use_static_libs" || test -z "$old_library"; }; then - case $host in - *cygwin* | *mingw* | *cegcc* | *os2*) + case $host_os in + cygwin* | mingw* | windows* | cegcc* | os2*) # No point in relinking DLLs because paths are not encoded func_append notinst_deplibs " $lib" need_relink=no @@ -8441,11 +8623,11 @@ func_mode_link () if test -z "$dlopenmodule" && test yes = "$shouldnotlink" && test link = "$pass"; then echo if test prog = "$linkmode"; then - $ECHO "*** Warning: Linking the executable $output against the loadable module" + func_warning "Linking the executable $output against the loadable module" else - $ECHO "*** Warning: Linking the shared library $output against the loadable module" + func_warning "Linking the shared library $output against the loadable module" fi - $ECHO "*** $linklib is not portable!" + func_warning "$linklib is not portable!" fi if test lib = "$linkmode" && test yes = "$hardcode_into_libs"; then @@ -8455,9 +8637,12 @@ func_mode_link () case " $sys_lib_dlsearch_path " in *" $absdir "*) ;; *) - case "$compile_rpath " in + case "$compile_rpath$compile_rpath_tail " in *" $absdir "*) ;; - *) func_append compile_rpath " $absdir" ;; + *) case $absdir in + "$progdir/"*) func_append compile_rpath " $absdir" ;; + *) func_append compile_rpath_tail " $absdir" ;; + esac esac ;; esac @@ -8484,8 +8669,8 @@ func_mode_link () soname=$dlname elif test -n "$soname_spec"; then # bleh windows - case $host in - *cygwin* | mingw* | *cegcc* | *os2*) + case $host_os in + cygwin* | mingw* | windows* | cegcc* | os2*) func_arith $current - $age major=$func_arith_result versuffix=-$major @@ -8532,6 +8717,7 @@ func_mode_link () case $host in *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;; *-*-sysv4*uw2*) add_dir=-L$dir ;; + *-*-emscripten*) add_dir=-L$dir ;; *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \ *-*-unixware7*) add_dir=-L$dir ;; *-*-darwin* ) @@ -8540,11 +8726,10 @@ func_mode_link () if /usr/bin/file -L $add 2> /dev/null | $GREP ": [^:]* bundle" >/dev/null; then if test "X$dlopenmodule" != "X$lib"; then - $ECHO "*** Warning: lib $linklib is a module, not a shared library" + func_warning "lib $linklib is a module, not a shared library" if test -z "$old_library"; then - echo - echo "*** And there doesn't seem to be a static archive available" - echo "*** The link will probably fail, sorry" + func_warning "And there doesn't seem to be a static archive available" + func_warning "The link will probably fail, sorry" else add=$dir/$old_library fi @@ -8627,7 +8812,7 @@ func_mode_link () test no = "$hardcode_direct_absolute"; then add=$libdir/$linklib elif test yes = "$hardcode_minus_L"; then - add_dir=-L$libdir + add_dir=-L$lt_sysroot$libdir add=-l$name elif test yes = "$hardcode_shlibpath_var"; then case :$finalize_shlibpath: in @@ -8644,7 +8829,7 @@ func_mode_link () fi else # We cannot seem to hardcode it, guess we'll fake it. - add_dir=-L$libdir + add_dir=-L$lt_sysroot$libdir # Try looking first in the location we're being installed to. if test -n "$inst_prefix_dir"; then case $libdir in @@ -8684,21 +8869,19 @@ func_mode_link () # Just print a warning and add the library to dependency_libs so # that the program can be linked against the static library. - echo - $ECHO "*** Warning: This system cannot link to static lib archive $lib." - echo "*** I have the capability to make that library automatically link in when" - echo "*** you link to this library. But I can only do this if you have a" - echo "*** shared version of the library, which you do not appear to have." + func_warning "This system cannot link to static lib archive $lib." + func_warning "I have the capability to make that library automatically link in when" + func_warning "you link to this library. But I can only do this if you have a" + func_warning "shared version of the library, which you do not appear to have." if test yes = "$module"; then - echo "*** But as you try to build a module library, libtool will still create " - echo "*** a static module, that should work as long as the dlopening application" - echo "*** is linked with the -dlopen flag to resolve symbols at runtime." + func_warning "But as you try to build a module library, libtool will still create " + func_warning "a static module, that should work as long as the dlopening application" + func_warning "is linked with the -dlopen flag to resolve symbols at runtime." if test -z "$global_symbol_pipe"; then - echo - echo "*** However, this would only work if libtool was able to extract symbol" - echo "*** lists from a program, using 'nm' or equivalent, but libtool could" - echo "*** not find such a program. So, this module is probably useless." - echo "*** 'nm' from GNU binutils and a full rebuild may help." + func_warning "However, this would only work if libtool was able to extract symbol" + func_warning "lists from a program, using 'nm' or equivalent, but libtool could" + func_warning "not find such a program. So, this module is probably useless." + func_warning "'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then build_libtool_libs=module @@ -8821,6 +9004,10 @@ func_mode_link () fi # link_all_deplibs != no fi # linkmode = lib done # for deplib in $libs + + func_append temp_rpath "$temp_rpath_tail" + func_append compile_rpath "$compile_rpath_tail" + if test link = "$pass"; then if test prog = "$linkmode"; then compile_deplibs="$new_inherited_linker_flags $compile_deplibs" @@ -8858,42 +9045,46 @@ func_mode_link () # Add libraries to $var in reverse order eval tmp_libs=\"\$$var\" new_libs= + # FIXME: Pedantically, this is the right thing to do, so + # that some nasty dependency loop isn't accidentally + # broken: new_libs="$deplib $new_libs" for deplib in $tmp_libs; do - # FIXME: Pedantically, this is the right thing to do, so - # that some nasty dependency loop isn't accidentally - # broken: - #new_libs="$deplib $new_libs" - # Pragmatically, this seems to cause very few problems in - # practice: - case $deplib in - -L*) new_libs="$deplib $new_libs" ;; - -R*) ;; - *) - # And here is the reason: when a library appears more - # than once as an explicit dependence of a library, or - # is implicitly linked in more than once by the - # compiler, it is considered special, and multiple - # occurrences thereof are not removed. Compare this - # with having the same library being listed as a - # dependency of multiple other libraries: in this case, - # we know (pedantically, we assume) the library does not - # need to be listed more than once, so we keep only the - # last copy. This is not always right, but it is rare - # enough that we require users that really mean to play - # such unportable linking tricks to link the library - # using -Wl,-lname, so that libtool does not consider it - # for duplicate removal. - case " $specialdeplibs " in - *" $deplib "*) new_libs="$deplib $new_libs" ;; + if $opt_preserve_dup_deps; then + new_libs="$deplib $new_libs" + else + # Pragmatically, this seems to cause very few problems in + # practice: + case $deplib in + -L*) new_libs="$deplib $new_libs" ;; + -R*) ;; *) - case " $new_libs " in - *" $deplib "*) ;; - *) new_libs="$deplib $new_libs" ;; - esac - ;; + # And here is the reason: when a library appears more + # than once as an explicit dependence of a library, or + # is implicitly linked in more than once by the + # compiler, it is considered special, and multiple + # occurrences thereof are not removed. Compare this + # with having the same library being listed as a + # dependency of multiple other libraries: in this case, + # we know (pedantically, we assume) the library does not + # need to be listed more than once, so we keep only the + # last copy. This is not always right, but it is rare + # enough that we require users that really mean to play + # such unportable linking tricks to link the library + # using -Wl,-lname, so that libtool does not consider it + # for duplicate removal. And if not possible for portability + # reasons, then --preserve-dup-deps should be used. + case " $specialdeplibs " in + *" $deplib "*) new_libs="$deplib $new_libs" ;; + *) + case " $new_libs " in + *" $deplib "*) ;; + *) new_libs="$deplib $new_libs" ;; + esac + ;; + esac + ;; esac - ;; - esac + fi done tmp_libs= for deplib in $new_libs; do @@ -9025,9 +9216,7 @@ func_mode_link () if test pass_all != "$deplibs_check_method"; then func_fatal_error "cannot build libtool library '$output' from non-libtool objects on this host:$objs" else - echo - $ECHO "*** Warning: Linking the shared library $output against the non-libtool" - $ECHO "*** objects $objs is not portable!" + func_warning "Linking the shared library $output against the non-libtool objects $objs is not portable!" func_append libobjs " $objs" fi fi @@ -9088,13 +9277,13 @@ func_mode_link () # case $version_type in # correct linux to gnu/linux during the next big refactor - darwin|freebsd-elf|linux|midnightbsd-elf|osf|windows|none) + darwin|freebsd-elf|linux|midnightbsd-elf|osf|qnx|windows|none) func_arith $number_major + $number_minor current=$func_arith_result age=$number_minor revision=$number_revision ;; - freebsd-aout|qnx|sunos) + freebsd-aout|sco|sunos) current=$number_major revision=$number_minor age=0 @@ -9109,6 +9298,9 @@ func_mode_link () *) func_fatal_configuration "$modename: unknown library version type '$version_type'" ;; + *) + func_fatal_configuration "$modename: unknown library version type '$version_type'" + ;; esac ;; no) @@ -9244,8 +9436,9 @@ func_mode_link () ;; qnx) - major=.$current - versuffix=.$current + func_arith $current - $age + major=.$func_arith_result + versuffix=$major.$age.$revision ;; sco) @@ -9398,7 +9591,7 @@ func_mode_link () if test yes = "$build_libtool_libs"; then if test -n "$rpath"; then case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*) # these systems don't actually have a c library (as such)! ;; *-*-rhapsody* | *-*-darwin1.[012]) @@ -9449,108 +9642,6 @@ func_mode_link () # implementing what was already the behavior. newdeplibs=$deplibs ;; - test_compile) - # This code stresses the "libraries are programs" paradigm to its - # limits. Maybe even breaks it. We compile a program, linking it - # against the deplibs as a proxy for the library. Then we can check - # whether they linked in statically or dynamically with ldd. - $opt_dry_run || $RM conftest.c - cat > conftest.c <<EOF - int main() { return 0; } -EOF - $opt_dry_run || $RM conftest - if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then - ldd_output=`ldd conftest` - for i in $deplibs; do - case $i in - -l*) - func_stripname -l '' "$i" - name=$func_stripname_result - if test yes = "$allow_libtool_libs_with_static_runtimes"; then - case " $predeps $postdeps " in - *" $i "*) - func_append newdeplibs " $i" - i= - ;; - esac - fi - if test -n "$i"; then - libname=`eval "\\$ECHO \"$libname_spec\""` - deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` - set dummy $deplib_matches; shift - deplib_match=$1 - if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0; then - func_append newdeplibs " $i" - else - droppeddeps=yes - echo - $ECHO "*** Warning: dynamic linker does not accept needed library $i." - echo "*** I have the capability to make that library automatically link in when" - echo "*** you link to this library. But I can only do this if you have a" - echo "*** shared version of the library, which I believe you do not have" - echo "*** because a test_compile did reveal that the linker did not use it for" - echo "*** its dynamic dependency list that programs get resolved with at runtime." - fi - fi - ;; - *) - func_append newdeplibs " $i" - ;; - esac - done - else - # Error occurred in the first compile. Let's try to salvage - # the situation: Compile a separate program for each library. - for i in $deplibs; do - case $i in - -l*) - func_stripname -l '' "$i" - name=$func_stripname_result - $opt_dry_run || $RM conftest - if $LTCC $LTCFLAGS -o conftest conftest.c $i; then - ldd_output=`ldd conftest` - if test yes = "$allow_libtool_libs_with_static_runtimes"; then - case " $predeps $postdeps " in - *" $i "*) - func_append newdeplibs " $i" - i= - ;; - esac - fi - if test -n "$i"; then - libname=`eval "\\$ECHO \"$libname_spec\""` - deplib_matches=`eval "\\$ECHO \"$library_names_spec\""` - set dummy $deplib_matches; shift - deplib_match=$1 - if test `expr "$ldd_output" : ".*$deplib_match"` -ne 0; then - func_append newdeplibs " $i" - else - droppeddeps=yes - echo - $ECHO "*** Warning: dynamic linker does not accept needed library $i." - echo "*** I have the capability to make that library automatically link in when" - echo "*** you link to this library. But I can only do this if you have a" - echo "*** shared version of the library, which you do not appear to have" - echo "*** because a test_compile did reveal that the linker did not use this one" - echo "*** as a dynamic dependency that programs can get resolved with at runtime." - fi - fi - else - droppeddeps=yes - echo - $ECHO "*** Warning! Library $i is needed by this library but I was not able to" - echo "*** make it link in! You will probably need to install it or some" - echo "*** library that it depends on before this library will be fully" - echo "*** functional. Installing it before continuing would be even better." - fi - ;; - *) - func_append newdeplibs " $i" - ;; - esac - done - fi - ;; file_magic*) set dummy $deplibs_check_method; shift file_magic_regex=`expr "$deplibs_check_method" : "$1 \(.*\)"` @@ -9614,17 +9705,16 @@ EOF fi if test -n "$a_deplib"; then droppeddeps=yes - echo - $ECHO "*** Warning: linker path does not have real file for library $a_deplib." - echo "*** I have the capability to make that library automatically link in when" - echo "*** you link to this library. But I can only do this if you have a" - echo "*** shared version of the library, which you do not appear to have" - echo "*** because I did check the linker path looking for a file starting" + func_warning "Linker path does not have real file for library $a_deplib." + func_warning "I have the capability to make that library automatically link in when" + func_warning "you link to this library. But I can only do this if you have a" + func_warning "shared version of the library, which you do not appear to have" + func_warning "because I did check the linker path looking for a file starting" if test -z "$potlib"; then - $ECHO "*** with $libname but no candidates were found. (...for file magic test)" + func_warning "with $libname but no candidates were found. (...for file magic test)" else - $ECHO "*** with $libname and none of the candidates passed a file format test" - $ECHO "*** using a file magic. Last file checked: $potlib" + func_warning "with $libname and none of the candidates passed a file format test" + func_warning "using a file magic. Last file checked: $potlib" fi fi ;; @@ -9668,17 +9758,16 @@ EOF fi if test -n "$a_deplib"; then droppeddeps=yes - echo - $ECHO "*** Warning: linker path does not have real file for library $a_deplib." - echo "*** I have the capability to make that library automatically link in when" - echo "*** you link to this library. But I can only do this if you have a" - echo "*** shared version of the library, which you do not appear to have" - echo "*** because I did check the linker path looking for a file starting" + func_warning "Linker path does not have real file for library $a_deplib." + func_warning "I have the capability to make that library automatically link in when" + func_warning "you link to this library. But I can only do this if you have a" + func_warning "shared version of the library, which you do not appear to have" + func_warning "because I did check the linker path looking for a file starting" if test -z "$potlib"; then - $ECHO "*** with $libname but no candidates were found. (...for regex pattern test)" + func_warning "with $libname but no candidates were found. (...for regex pattern test)" else - $ECHO "*** with $libname and none of the candidates passed a file format test" - $ECHO "*** using a regex pattern. Last file checked: $potlib" + func_warning "with $libname and none of the candidates passed a file format test" + func_warning "using a regex pattern. Last file checked: $potlib" fi fi ;; @@ -9702,11 +9791,11 @@ EOF *[!\ \ ]*) echo if test none = "$deplibs_check_method"; then - echo "*** Warning: inter-library dependencies are not supported in this platform." + func_warning "Inter-library dependencies are not supported in this platform." else - echo "*** Warning: inter-library dependencies are not known to be supported." + func_warning "Inter-library dependencies are not known to be supported." fi - echo "*** All declared inter-library dependencies are being dropped." + func_warning "All declared inter-library dependencies are being dropped." droppeddeps=yes ;; esac @@ -9727,17 +9816,15 @@ EOF if test yes = "$droppeddeps"; then if test yes = "$module"; then - echo - echo "*** Warning: libtool could not satisfy all declared inter-library" - $ECHO "*** dependencies of module $libname. Therefore, libtool will create" - echo "*** a static module, that should work as long as the dlopening" - echo "*** application is linked with the -dlopen flag." + func_warning "libtool could not satisfy all declared inter-library" + func_warning "dependencies of module $libname. Therefore, libtool will create" + func_warning "a static module, that should work as long as the dlopening" + func_warning "application is linked with the -dlopen flag." if test -z "$global_symbol_pipe"; then - echo - echo "*** However, this would only work if libtool was able to extract symbol" - echo "*** lists from a program, using 'nm' or equivalent, but libtool could" - echo "*** not find such a program. So, this module is probably useless." - echo "*** 'nm' from GNU binutils and a full rebuild may help." + func_warning "However, this would only work if libtool was able to extract symbol" + func_warning "lists from a program, using 'nm' or equivalent, but libtool could" + func_warning "not find such a program. So, this module is probably useless." + func_warning "'nm' from GNU binutils and a full rebuild may help." fi if test no = "$build_old_libs"; then oldlibs=$output_objdir/$libname.$libext @@ -9912,7 +9999,7 @@ EOF orig_export_symbols= case $host_os in - cygwin* | mingw* | cegcc*) + cygwin* | mingw* | windows* | cegcc*) if test -n "$export_symbols" && test -z "$export_symbols_regex"; then # exporting using user supplied symfile func_dll_def_p "$export_symbols" || { @@ -10110,20 +10197,7 @@ EOF last_robj= k=1 - if test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then - output=$output_objdir/$output_la.lnkscript - func_verbose "creating GNU ld script: $output" - echo 'INPUT (' > $output - for obj in $save_libobjs - do - func_to_tool_file "$obj" - $ECHO "$func_to_tool_file_result" >> $output - done - echo ')' >> $output - func_append delfiles " $output" - func_to_tool_file "$output" - output=$func_to_tool_file_result - elif test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then + if test -n "$save_libobjs" && test : != "$skipped_export" && test -n "$file_list_spec"; then output=$output_objdir/$output_la.lnk func_verbose "creating linker input file list: $output" : > $output @@ -10142,6 +10216,19 @@ EOF func_append delfiles " $output" func_to_tool_file "$output" output=$firstobj\"$file_list_spec$func_to_tool_file_result\" + elif test -n "$save_libobjs" && test : != "$skipped_export" && test yes = "$with_gnu_ld"; then + output=$output_objdir/$output_la.lnkscript + func_verbose "creating GNU ld script: $output" + echo 'INPUT (' > $output + for obj in $save_libobjs + do + func_to_tool_file "$obj" + $ECHO "$func_to_tool_file_result" >> $output + done + echo ')' >> $output + func_append delfiles " $output" + func_to_tool_file "$output" + output=$func_to_tool_file_result else if test -n "$save_libobjs"; then func_verbose "creating reloadable object files..." @@ -10582,7 +10669,7 @@ EOF esac fi case $host in - *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*) + *-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-os2* | *-cegcc*) testbindir=`$ECHO "$libdir" | $SED -e 's*/lib$*/bin*'` case :$dllsearchpath: in *":$libdir:"*) ;; @@ -10660,7 +10747,7 @@ EOF # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway. wrappers_required=false ;; - *cygwin* | *mingw* ) + *cygwin* | *mingw* | *windows* ) test yes = "$build_libtool_libs" || wrappers_required=false ;; *) @@ -10814,7 +10901,7 @@ EOF *) exeext= ;; esac case $host in - *cygwin* | *mingw* ) + *cygwin* | *mingw* | windows* ) func_dirname_and_basename "$output" "" "." output_name=$func_basename_result output_path=$func_dirname_result @@ -11148,7 +11235,7 @@ EOF # tests/bindir.at for full details. tdlname=$dlname case $host,$output,$installed,$module,$dlname in - *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) + *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *windows*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) # If a -bindir argument was supplied, place the dll there. if test -n "$bindir"; then func_relative_path "$install_libdir" "$bindir" diff --git a/deps/libffi/m4/libtool.m4 b/deps/libffi/m4/libtool.m4 index e7b68334557b..4aa8d6e7846b 100755 --- a/deps/libffi/m4/libtool.m4 +++ b/deps/libffi/m4/libtool.m4 @@ -1,6 +1,6 @@ # libtool.m4 - Configure libtool for the host system. -*-Autoconf-*- # -# Copyright (C) 1996-2001, 2003-2019, 2021-2022 Free Software +# Copyright (C) 1996-2001, 2003-2019, 2021-2024 Free Software # Foundation, Inc. # Written by Gordon Matzigkeit, 1996 # @@ -9,13 +9,13 @@ # modifications, as long as this notice is preserved. m4_define([_LT_COPYING], [dnl -# Copyright (C) 2014 Free Software Foundation, Inc. +# Copyright (C) 2024 Free Software Foundation, Inc. # This is free software; see the source for copying conditions. There is NO # warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # GNU Libtool is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of of the License, or +# the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # As a special exception to the GNU General Public License, if you @@ -32,7 +32,7 @@ m4_define([_LT_COPYING], [dnl # along with this program. If not, see <http://www.gnu.org/licenses/>. ]) -# serial 59 LT_INIT +# serial 63 LT_INIT # LT_PREREQ(VERSION) @@ -60,7 +60,7 @@ esac # LT_INIT([OPTIONS]) # ------------------ AC_DEFUN([LT_INIT], -[AC_PREREQ([2.62])dnl We use AC_PATH_PROGS_FEATURE_CHECK +[AC_PREREQ([2.64])dnl We use AC_PATH_PROGS_FEATURE_CHECK AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT])dnl AC_BEFORE([$0], [LT_LANG])dnl AC_BEFORE([$0], [LT_OUTPUT])dnl @@ -616,7 +616,7 @@ m4_popdef([AS_MESSAGE_LOG_FD])])])# _LT_GENERATED_FILE_INIT # LT_OUTPUT # --------- # This macro allows early generation of the libtool script (before -# AC_OUTPUT is called), incase it is used in configure for compilation +# AC_OUTPUT is called), in case it is used in configure for compilation # tests. AC_DEFUN([LT_OUTPUT], [: ${CONFIG_LT=./config.lt} @@ -651,9 +651,9 @@ m4_ifset([AC_PACKAGE_NAME], [AC_PACKAGE_NAME ])config.lt[]dnl m4_ifset([AC_PACKAGE_VERSION], [ AC_PACKAGE_VERSION]) configured by $[0], generated by m4_PACKAGE_STRING. -Copyright (C) 2011 Free Software Foundation, Inc. +Copyright (C) 2024 Free Software Foundation, Inc. This config.lt script is free software; the Free Software Foundation -gives unlimited permision to copy, distribute and modify it." +gives unlimited permission to copy, distribute and modify it." while test 0 != $[#] do @@ -974,6 +974,7 @@ _lt_linker_boilerplate=`cat conftest.err` $RM -r conftest* ])# _LT_LINKER_BOILERPLATE + # _LT_REQUIRED_DARWIN_CHECKS # ------------------------- m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ @@ -1024,6 +1025,21 @@ m4_defun_once([_LT_REQUIRED_DARWIN_CHECKS],[ rm -f conftest.* fi]) + # Feature test to disable chained fixups since it is not + # compatible with '-undefined dynamic_lookup' + AC_CACHE_CHECK([for -no_fixup_chains linker flag], + [lt_cv_support_no_fixup_chains], + [ save_LDFLAGS=$LDFLAGS + LDFLAGS="$LDFLAGS -Wl,-no_fixup_chains" + AC_LINK_IFELSE( + [AC_LANG_PROGRAM([],[])], + lt_cv_support_no_fixup_chains=yes, + lt_cv_support_no_fixup_chains=no + ) + LDFLAGS=$save_LDFLAGS + ] + ) + AC_CACHE_CHECK([for -exported_symbols_list linker flag], [lt_cv_ld_exported_symbols_list], [lt_cv_ld_exported_symbols_list=no @@ -1048,7 +1064,7 @@ _LT_EOF echo "$RANLIB libconftest.a" >&AS_MESSAGE_LOG_FD $RANLIB libconftest.a 2>&AS_MESSAGE_LOG_FD cat > conftest.c << _LT_EOF -int main() { return 0;} +int main(void) { return 0;} _LT_EOF echo "$LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a" >&AS_MESSAGE_LOG_FD $LTCC $LTCFLAGS $LDFLAGS -o conftest conftest.c -Wl,-force_load,./libconftest.a 2>conftest.err @@ -1073,13 +1089,32 @@ _LT_EOF 10.[[012]],*|,*powerpc*-darwin[[5-8]]*) _lt_dar_allow_undefined='$wl-flat_namespace $wl-undefined ${wl}suppress' ;; *) - _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' ;; + _lt_dar_allow_undefined='$wl-undefined ${wl}dynamic_lookup' + if test yes = "$lt_cv_support_no_fixup_chains"; then + AS_VAR_APPEND([_lt_dar_allow_undefined], [' $wl-no_fixup_chains']) + fi + ;; esac ;; esac if test yes = "$lt_cv_apple_cc_single_mod"; then _lt_dar_single_mod='$single_module' fi + _lt_dar_needs_single_mod=no + case $host_os in + rhapsody* | darwin1.*) + _lt_dar_needs_single_mod=yes ;; + darwin*) + # When targeting Mac OS X 10.4 (darwin 8) or later, + # -single_module is the default and -multi_module is unsupported. + # The toolchain on macOS 10.14 (darwin 18) and later cannot + # target any OS version that needs -single_module. + case ${MACOSX_DEPLOYMENT_TARGET-10.0},$host in + 10.0,*-darwin[[567]].*|10.[[0-3]],*-darwin[[5-9]].*|10.[[0-3]],*-darwin1[[0-7]].*) + _lt_dar_needs_single_mod=yes ;; + esac + ;; + esac if test yes = "$lt_cv_ld_exported_symbols_list"; then _lt_dar_export_syms=' $wl-exported_symbols_list,$output_objdir/$libname-symbols.expsym' else @@ -1125,7 +1160,7 @@ m4_defun([_LT_DARWIN_LINKER_FEATURES], _LT_TAGVAR(archive_expsym_cmds, $1)="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$libobjs \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring $_lt_dar_single_mod$_lt_dar_export_syms$_lt_dsymutil" _LT_TAGVAR(module_expsym_cmds, $1)="$SED -e 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC \$allow_undefined_flag -o \$lib -bundle \$libobjs \$deplibs \$compiler_flags$_lt_dar_export_syms$_lt_dsymutil" m4_if([$1], [CXX], -[ if test yes != "$lt_cv_apple_cc_single_mod"; then +[ if test yes = "$_lt_dar_needs_single_mod" -a yes != "$lt_cv_apple_cc_single_mod"; then _LT_TAGVAR(archive_cmds, $1)="\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dsymutil" _LT_TAGVAR(archive_expsym_cmds, $1)="$SED 's|^|_|' < \$export_symbols > \$output_objdir/\$libname-symbols.expsym~\$CC -r -keep_private_externs -nostdlib -o \$lib-master.o \$libobjs~\$CC -dynamiclib \$allow_undefined_flag -o \$lib \$lib-master.o \$deplibs \$compiler_flags -install_name \$rpath/\$soname \$verstring$_lt_dar_export_syms$_lt_dsymutil" fi @@ -1255,7 +1290,9 @@ lt_sysroot= case $with_sysroot in #( yes) if test yes = "$GCC"; then - lt_sysroot=`$CC --print-sysroot 2>/dev/null` + # Trim trailing / since we'll always append absolute paths and we want + # to avoid //, if only for less confusing output for the user. + lt_sysroot=`$CC --print-sysroot 2>/dev/null | $SED 's:/\+$::'` fi ;; #( /*) @@ -1367,7 +1404,7 @@ mips64*-*linux*) ;; x86_64-*kfreebsd*-gnu|x86_64-*linux*|powerpc*-*linux*| \ -s390*-*linux*|s390*-*tpf*|sparc*-*linux*) +s390*-*linux*|s390*-*tpf*|sparc*-*linux*|x86_64-gnu*) # Find out what ABI is being produced by ac_compile, and set linker # options accordingly. Note that the listed cases only cover the # situations where additional linker options are needed (such as when @@ -1382,7 +1419,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_i386_fbsd" ;; - x86_64-*linux*) + x86_64-*linux*|x86_64-gnu*) case `$FILECMD conftest.o` in *x86-64*) LD="${LD-ld} -m elf32_x86_64" @@ -1411,7 +1448,7 @@ s390*-*linux*|s390*-*tpf*|sparc*-*linux*) x86_64-*kfreebsd*-gnu) LD="${LD-ld} -m elf_x86_64_fbsd" ;; - x86_64-*linux*) + x86_64-*linux*|x86_64-gnu*) LD="${LD-ld} -m elf_x86_64" ;; powerpcle-*linux*) @@ -1494,7 +1531,7 @@ _LT_DECL([], [AR], [1], [The archiver]) # Use ARFLAGS variable as AR's operation code to sync the variable naming with # Automake. If both AR_FLAGS and ARFLAGS are specified, AR_FLAGS should have -# higher priority because thats what people were doing historically (setting +# higher priority because that's what people were doing historically (setting # ARFLAGS for automake and AR_FLAGS for libtool). FIXME: Make the AR_FLAGS # variable obsoleted/removed. @@ -1544,7 +1581,7 @@ AC_CHECK_TOOL(STRIP, strip, :) test -z "$STRIP" && STRIP=: _LT_DECL([], [STRIP], [1], [A symbol stripping program]) -AC_CHECK_TOOL(RANLIB, ranlib, :) +AC_REQUIRE([AC_PROG_RANLIB]) test -z "$RANLIB" && RANLIB=: _LT_DECL([], [RANLIB], [1], [Commands used to install an old-style archive]) @@ -1555,15 +1592,8 @@ old_postinstall_cmds='chmod 644 $oldlib' old_postuninstall_cmds= if test -n "$RANLIB"; then - case $host_os in - bitrig* | openbsd*) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB -t \$tool_oldlib" - ;; - *) - old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" - ;; - esac old_archive_cmds="$old_archive_cmds~\$RANLIB \$tool_oldlib" + old_postinstall_cmds="$old_postinstall_cmds~\$RANLIB \$tool_oldlib" fi case $host_os in @@ -1695,14 +1725,14 @@ AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl lt_cv_sys_max_cmd_len=12288; # 12K is about right ;; - gnu*) - # Under GNU Hurd, this test is not required because there is - # no limit to the length of command line arguments. + gnu* | ironclad*) + # Under GNU Hurd and Ironclad, this test is not required because there + # is no limit to the length of command line arguments. # Libtool will interpret -1 as no limit whatsoever lt_cv_sys_max_cmd_len=-1; ;; - cygwin* | mingw* | cegcc*) + cygwin* | mingw* | windows* | cegcc*) # On Win9x/ME, this test blows up -- it succeeds, but takes # about 5 minutes as the teststring grows exponentially. # Worse, since 9x/ME are not pre-emptively multitasking, @@ -1724,7 +1754,7 @@ AC_CACHE_VAL([lt_cv_sys_max_cmd_len], [dnl lt_cv_sys_max_cmd_len=8192; ;; - bitrig* | darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) + darwin* | dragonfly* | freebsd* | midnightbsd* | netbsd* | openbsd*) # This has been around since 386BSD, at least. Likely further. if test -x /sbin/sysctl; then lt_cv_sys_max_cmd_len=`/sbin/sysctl -n kern.argmax` @@ -1884,11 +1914,11 @@ else /* When -fvisibility=hidden is used, assume the code has been annotated correspondingly for the symbols needed. */ #if defined __GNUC__ && (((__GNUC__ == 3) && (__GNUC_MINOR__ >= 3)) || (__GNUC__ > 3)) -int fnord () __attribute__((visibility("default"))); +int fnord (void) __attribute__((visibility("default"))); #endif -int fnord () { return 42; } -int main () +int fnord (void) { return 42; } +int main (void) { void *self = dlopen (0, LT_DLGLOBAL|LT_DLLAZY_OR_NOW); int status = $lt_dlunknown; @@ -1945,7 +1975,7 @@ else lt_cv_dlopen_self=yes ;; - mingw* | pw32* | cegcc*) + mingw* | windows* | pw32* | cegcc*) lt_cv_dlopen=LoadLibrary lt_cv_dlopen_libs= ;; @@ -2313,7 +2343,7 @@ if test yes = "$GCC"; then *) lt_awk_arg='/^libraries:/' ;; esac case $host_os in - mingw* | cegcc*) lt_sed_strip_eq='s|=\([[A-Za-z]]:\)|\1|g' ;; + mingw* | windows* | cegcc*) lt_sed_strip_eq='s|=\([[A-Za-z]]:\)|\1|g' ;; *) lt_sed_strip_eq='s|=/|/|g' ;; esac lt_search_path_spec=`$CC -print-search-dirs | awk $lt_awk_arg | $SED -e "s/^libraries://" -e $lt_sed_strip_eq` @@ -2371,7 +2401,7 @@ BEGIN {RS = " "; FS = "/|\n";} { # AWK program above erroneously prepends '/' to C:/dos/paths # for these hosts. case $host_os in - mingw* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ + mingw* | windows* | cegcc*) lt_search_path_spec=`$ECHO "$lt_search_path_spec" |\ $SED 's|/\([[A-Za-z]]:\)|\1|g'` ;; esac sys_lib_search_path_spec=`$ECHO "$lt_search_path_spec" | $lt_NL2SP` @@ -2446,7 +2476,7 @@ aix[[4-9]]*) # Unfortunately, runtime linking may impact performance, so we do # not want this to be the default eventually. Also, we use the # versioned .so libs for executables only if there is the -brtl - # linker flag in LDFLAGS as well, or --with-aix-soname=svr4 only. + # linker flag in LDFLAGS as well, or --enable-aix-soname=svr4 only. # To allow for filename-based versioning support, we need to create # libNAME.so.V as an archive file, containing: # *) an Import File, referring to the versioned filename of the @@ -2540,7 +2570,7 @@ bsdi[[45]]*) # libtool to hard-code these into programs ;; -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) version_type=windows shrext_cmds=.dll need_version=no @@ -2551,15 +2581,29 @@ cygwin* | mingw* | pw32* | cegcc*) # gcc library_names_spec='$libname.dll.a' # DLL is installed to $(libdir)/../bin by postinstall_cmds - postinstall_cmds='base_file=`basename \$file`~ - dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ - dldir=$destdir/`dirname \$dlpath`~ - test -d \$dldir || mkdir -p \$dldir~ - $install_prog $dir/$dlname \$dldir/$dlname~ - chmod a+x \$dldir/$dlname~ - if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then - eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; - fi' + # If user builds GCC with multilib enabled, + # it should just install on $(libdir) + # not on $(libdir)/../bin or 32 bits dlls would override 64 bit ones. + if test xyes = x"$multilib"; then + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + $install_prog $dir/$dlname $destdir/$dlname~ + chmod a+x $destdir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib $destdir/$dlname'\'' || exit \$?; + fi' + else + postinstall_cmds='base_file=`basename \$file`~ + dlpath=`$SHELL 2>&1 -c '\''. $dir/'\''\$base_file'\''i; echo \$dlname'\''`~ + dldir=$destdir/`dirname \$dlpath`~ + test -d \$dldir || mkdir -p \$dldir~ + $install_prog $dir/$dlname \$dldir/$dlname~ + chmod a+x \$dldir/$dlname~ + if test -n '\''$stripme'\'' && test -n '\''$striplib'\''; then + eval '\''$striplib \$dldir/$dlname'\'' || exit \$?; + fi' + fi postuninstall_cmds='dldll=`$SHELL 2>&1 -c '\''. $file; echo \$dlname'\''`~ dlpath=$dir/\$dldll~ $RM \$dlpath' @@ -2572,7 +2616,7 @@ cygwin* | mingw* | pw32* | cegcc*) m4_if([$1], [],[ sys_lib_search_path_spec="$sys_lib_search_path_spec /usr/lib/w32api"]) ;; - mingw* | cegcc*) + mingw* | windows* | cegcc*) # MinGW DLLs use traditional 'lib' prefix soname_spec='$libname`echo $release | $SED -e 's/[[.]]/-/g'`$versuffix$shared_ext' ;; @@ -2591,7 +2635,7 @@ m4_if([$1], [],[ library_names_spec='$libname.dll.lib' case $build_os in - mingw*) + mingw* | windows*) sys_lib_search_path_spec= lt_save_ifs=$IFS IFS=';' @@ -2698,7 +2742,21 @@ freebsd* | dragonfly* | midnightbsd*) need_version=yes ;; esac - shlibpath_var=LD_LIBRARY_PATH + case $host_cpu in + powerpc64) + # On FreeBSD bi-arch platforms, a different variable is used for 32-bit + # binaries. See <https://man.freebsd.org/cgi/man.cgi?query=ld.so>. + AC_COMPILE_IFELSE( + [AC_LANG_SOURCE( + [[int test_pointer_size[sizeof (void *) - 5]; + ]])], + [shlibpath_var=LD_LIBRARY_PATH], + [shlibpath_var=LD_32_LIBRARY_PATH]) + ;; + *) + shlibpath_var=LD_LIBRARY_PATH + ;; + esac case $host_os in freebsd2.*) shlibpath_overrides_runpath=yes @@ -2728,8 +2786,9 @@ haiku*) soname_spec='$libname$release$shared_ext$major' shlibpath_var=LIBRARY_PATH shlibpath_overrides_runpath=no - sys_lib_dlsearch_path_spec='/boot/home/config/lib /boot/common/lib /boot/system/lib' - hardcode_into_libs=yes + sys_lib_search_path_spec='/boot/system/non-packaged/develop/lib /boot/system/develop/lib' + sys_lib_dlsearch_path_spec='/boot/home/config/non-packaged/lib /boot/home/config/lib /boot/system/non-packaged/lib /boot/system/lib' + hardcode_into_libs=no ;; hpux9* | hpux10* | hpux11*) @@ -2839,7 +2898,7 @@ linux*android*) version_type=none # Android doesn't support versioned libraries. need_lib_prefix=no need_version=no - library_names_spec='$libname$release$shared_ext' + library_names_spec='$libname$release$shared_ext $libname$shared_ext' soname_spec='$libname$release$shared_ext' finish_cmds= shlibpath_var=LD_LIBRARY_PATH @@ -2851,8 +2910,9 @@ linux*android*) hardcode_into_libs=yes dynamic_linker='Android linker' - # Don't embed -rpath directories since the linker doesn't support them. - _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' + # -rpath works at least for libraries that are not overridden by + # libraries installed in system locations. + _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-rpath $wl$libdir' ;; # This must be glibc/ELF. @@ -2886,7 +2946,7 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) # before this can be enabled. hardcode_into_libs=yes - # Ideally, we could use ldconfig to report *all* directores which are + # Ideally, we could use ldconfig to report *all* directories which are # searched for libraries, however this is still not possible. Aside from not # being certain /sbin/ldconfig is available, command # 'ldconfig -N -X -v | grep ^/' on 64bit Fedora does not report /usr/lib64, @@ -2906,6 +2966,18 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) dynamic_linker='GNU/Linux ld.so' ;; +netbsdelf*-gnu) + version_type=linux + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + dynamic_linker='NetBSD ld.elf_so' + ;; + netbsdelf*-gnu) version_type=linux need_lib_prefix=no @@ -2936,6 +3008,18 @@ netbsd*) hardcode_into_libs=yes ;; +*-mlibc) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + dynamic_linker='mlibc ld.so' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + hardcode_into_libs=yes + ;; + newsos6) version_type=linux # correct to gnu/linux during the next big refactor library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' @@ -2955,7 +3039,7 @@ newsos6) dynamic_linker='ldqnx.so' ;; -openbsd* | bitrig*) +openbsd*) version_type=sunos sys_lib_dlsearch_path_spec=/usr/lib need_lib_prefix=no @@ -3015,6 +3099,17 @@ rdos*) dynamic_linker=no ;; +serenity*) + version_type=linux # correct to gnu/linux during the next big refactor + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext$versuffix $libname$release$shared_ext$major $libname$shared_ext' + soname_spec='$libname$release$shared_ext$major' + shlibpath_var=LD_LIBRARY_PATH + shlibpath_overrides_runpath=no + dynamic_linker='SerenityOS LibELF' + ;; + solaris*) version_type=linux # correct to gnu/linux during the next big refactor need_lib_prefix=no @@ -3112,6 +3207,21 @@ uts4*) shlibpath_var=LD_LIBRARY_PATH ;; +emscripten*) + version_type=none + need_lib_prefix=no + need_version=no + library_names_spec='$libname$release$shared_ext' + soname_spec='$libname$release$shared_ext' + finish_cmds= + dynamic_linker="Emscripten linker" + _LT_COMPILER_PIC($1)='-fPIC' + _LT_TAGVAR(archive_cmds, $1)='$CC -sSIDE_MODULE=2 -shared $libobjs $deplibs $compiler_flags -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$SED "s|^|_|" $export_symbols >$output_objdir/$soname.expsym~$CC -sSIDE_MODULE=2 -shared $libobjs $deplibs $compiler_flags -o $lib -s EXPORTED_FUNCTIONS=@$output_objdir/$soname.expsym' + _LT_TAGVAR(archive_cmds_need_lc, $1)=no + _LT_TAGVAR(no_undefined_flag, $1)= + ;; + *) dynamic_linker=no ;; @@ -3287,7 +3397,7 @@ if test yes = "$GCC"; then # Check if gcc -print-prog-name=ld gives a path. AC_MSG_CHECKING([for ld used by $CC]) case $host in - *-*-mingw*) + *-*-mingw* | *-*-windows*) # gcc leaves a trailing carriage return, which upsets mingw ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;; *) @@ -3396,7 +3506,7 @@ case $reload_flag in esac reload_cmds='$LD$reload_flag -o $output$reload_objs' case $host_os in - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) if test yes != "$GCC"; then reload_cmds=false fi @@ -3468,7 +3578,6 @@ lt_cv_deplibs_check_method='unknown' # 'none' -- dependencies not supported. # 'unknown' -- same as none, but documents that we really don't know. # 'pass_all' -- all dependencies passed with no checks. -# 'test_compile' -- check by making test program. # 'file_magic [[regex]]' -- check by looking for files in library path # that responds to the $file_magic_cmd with a given extended regex. # If you have 'file' or equivalent on your system and you're not sure @@ -3495,7 +3604,7 @@ cygwin*) lt_cv_file_magic_cmd='func_win32_libid' ;; -mingw* | pw32*) +mingw* | windows* | pw32*) # Base MSYS/MinGW do not provide the 'file' command needed by # func_win32_libid shell function, so use a weaker test based on 'objdump', # unless we find 'file', for example because we are cross-compiling. @@ -3504,7 +3613,7 @@ mingw* | pw32*) lt_cv_file_magic_cmd='func_win32_libid' else # Keep this pattern in sync with the one in func_win32_libid. - lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' + lt_cv_deplibs_check_method='file_magic file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64|pe-aarch64)' lt_cv_file_magic_cmd='$OBJDUMP -f' fi ;; @@ -3577,6 +3686,10 @@ linux* | k*bsd*-gnu | kopensolaris*-gnu | gnu*) lt_cv_deplibs_check_method=pass_all ;; +*-mlibc) + lt_cv_deplibs_check_method=pass_all + ;; + netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ > /dev/null; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|_pic\.a)$' @@ -3595,7 +3708,7 @@ newos6*) lt_cv_deplibs_check_method=pass_all ;; -openbsd* | bitrig*) +openbsd*) if test -z "`echo __ELF__ | $CC -E - | $GREP __ELF__`"; then lt_cv_deplibs_check_method='match_pattern /lib[[^/]]+(\.so\.[[0-9]]+\.[[0-9]]+|\.so|_pic\.a)$' else @@ -3611,6 +3724,10 @@ rdos*) lt_cv_deplibs_check_method=pass_all ;; +serenity*) + lt_cv_deplibs_check_method=pass_all + ;; + solaris*) lt_cv_deplibs_check_method=pass_all ;; @@ -3659,7 +3776,7 @@ file_magic_glob= want_nocaseglob=no if test "$build" = "$host"; then case $host_os in - mingw* | pw32*) + mingw* | windows* | pw32*) if ( shopt | grep nocaseglob ) >/dev/null 2>&1; then want_nocaseglob=yes else @@ -3711,7 +3828,7 @@ else # Tru64's nm complains that /dev/null is an invalid object file # MSYS converts /dev/null to NUL, MinGW nm treats NUL as empty case $build_os in - mingw*) lt_bad_file=conftest.nm/nofile ;; + mingw* | windows*) lt_bad_file=conftest.nm/nofile ;; *) lt_bad_file=/dev/null ;; esac case `"$tmp_nm" -B $lt_bad_file 2>&1 | $SED '1q'` in @@ -3802,7 +3919,7 @@ lt_cv_sharedlib_from_linklib_cmd, [lt_cv_sharedlib_from_linklib_cmd='unknown' case $host_os in -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) # two different shell functions defined in ltmain.sh; # decide which one to use based on capabilities of $DLLTOOL case `$DLLTOOL --help 2>&1` in @@ -3834,16 +3951,16 @@ _LT_DECL([], [sharedlib_from_linklib_cmd], [1], m4_defun([_LT_PATH_MANIFEST_TOOL], [AC_CHECK_TOOL(MANIFEST_TOOL, mt, :) test -z "$MANIFEST_TOOL" && MANIFEST_TOOL=mt -AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_mainfest_tool], - [lt_cv_path_mainfest_tool=no +AC_CACHE_CHECK([if $MANIFEST_TOOL is a manifest tool], [lt_cv_path_manifest_tool], + [lt_cv_path_manifest_tool=no echo "$as_me:$LINENO: $MANIFEST_TOOL '-?'" >&AS_MESSAGE_LOG_FD $MANIFEST_TOOL '-?' 2>conftest.err > conftest.out cat conftest.err >&AS_MESSAGE_LOG_FD if $GREP 'Manifest Tool' conftest.out > /dev/null; then - lt_cv_path_mainfest_tool=yes + lt_cv_path_manifest_tool=yes fi rm -f conftest*]) -if test yes != "$lt_cv_path_mainfest_tool"; then +if test yes != "$lt_cv_path_manifest_tool"; then MANIFEST_TOOL=: fi _LT_DECL([], [MANIFEST_TOOL], [1], [Manifest tool])dnl @@ -3872,7 +3989,7 @@ AC_DEFUN([LT_LIB_M], [AC_REQUIRE([AC_CANONICAL_HOST])dnl LIBM= case $host in -*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-pw32* | *-*-darwin*) +*-*-beos* | *-*-cegcc* | *-*-cygwin* | *-*-haiku* | *-*-mingw* | *-*-pw32* | *-*-darwin*) # These system don't have libm, or don't need it ;; *-ncr-sysv4.3*) @@ -3947,7 +4064,7 @@ case $host_os in aix*) symcode='[[BCDT]]' ;; -cygwin* | mingw* | pw32* | cegcc*) +cygwin* | mingw* | windows* | pw32* | cegcc*) symcode='[[ABCDGISTW]]' ;; hpux*) @@ -3962,7 +4079,7 @@ osf*) symcode='[[BCDEGQRST]]' ;; solaris*) - symcode='[[BDRT]]' + symcode='[[BCDRT]]' ;; sco3.2v5*) symcode='[[DT]]' @@ -4026,7 +4143,7 @@ $lt_c_name_lib_hook\ # Handle CRLF in mingw tool chain opt_cr= case $build_os in -mingw*) +mingw* | windows*) opt_cr=`$ECHO 'x\{0,1\}' | tr x '\015'` # option cr in regexp ;; esac @@ -4077,7 +4194,7 @@ void nm_test_func(void){} #ifdef __cplusplus } #endif -int main(){nm_test_var='a';nm_test_func();return(0);} +int main(void){nm_test_var='a';nm_test_func();return(0);} _LT_EOF if AC_TRY_EVAL(ac_compile); then @@ -4254,7 +4371,7 @@ m4_if([$1], [CXX], [ beos* | irix5* | irix6* | nonstopux* | osf3* | osf4* | osf5*) # PIC is the default for these OSes. ;; - mingw* | cygwin* | os2* | pw32* | cegcc*) + mingw* | windows* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style @@ -4330,7 +4447,7 @@ m4_if([$1], [CXX], [ ;; esac ;; - mingw* | cygwin* | os2* | pw32* | cegcc*) + mingw* | windows* | cygwin* | os2* | pw32* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], @@ -4458,6 +4575,8 @@ m4_if([$1], [CXX], [ ;; netbsd* | netbsdelf*-gnu) ;; + *-mlibc) + ;; *qnx* | *nto*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. @@ -4486,6 +4605,8 @@ m4_if([$1], [CXX], [ ;; psos*) ;; + serenity*) + ;; solaris*) case $cc_basename in CC* | sunCC*) @@ -4578,7 +4699,7 @@ m4_if([$1], [CXX], [ # PIC is the default for these OSes. ;; - mingw* | cygwin* | pw32* | os2* | cegcc*) + mingw* | windows* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). # Although the cygwin gcc ignores -fPIC, still need this for old-style @@ -4682,7 +4803,7 @@ m4_if([$1], [CXX], [ esac ;; - mingw* | cygwin* | pw32* | os2* | cegcc*) + mingw* | windows* | cygwin* | pw32* | os2* | cegcc*) # This hack is so that the source file can tell whether it is being # built for inclusion in a dll (and should export symbols for example). m4_if([$1], [GCJ], [], @@ -4724,6 +4845,12 @@ m4_if([$1], [CXX], [ _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' ;; + *flang* | ftn | f18* | f95*) + # Flang compiler. + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; # flang / f18. f95 an alias for gfortran or flang on Debian flang* | f18* | f95*) _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' @@ -4812,6 +4939,12 @@ m4_if([$1], [CXX], [ _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' ;; + *-mlibc) + _LT_TAGVAR(lt_prog_compiler_wl, $1)='-Wl,' + _LT_TAGVAR(lt_prog_compiler_pic, $1)='-fPIC' + _LT_TAGVAR(lt_prog_compiler_static, $1)='-static' + ;; + *nto* | *qnx*) # QNX uses GNU C++, but need to define -shared option too, otherwise # it will coredump. @@ -4828,6 +4961,9 @@ m4_if([$1], [CXX], [ _LT_TAGVAR(lt_prog_compiler_static, $1)='-non_shared' ;; + serenity*) + ;; + solaris*) _LT_TAGVAR(lt_prog_compiler_pic, $1)='-KPIC' _LT_TAGVAR(lt_prog_compiler_static, $1)='-Bstatic' @@ -4963,7 +5099,7 @@ m4_if([$1], [CXX], [ pw32*) _LT_TAGVAR(export_symbols_cmds, $1)=$ltdll_cmds ;; - cygwin* | mingw* | cegcc*) + cygwin* | mingw* | windows* | cegcc*) case $cc_basename in cl* | icl*) _LT_TAGVAR(exclude_expsyms, $1)='_NULL_IMPORT_DESCRIPTOR|_IMPORT_DESCRIPTOR_.*' @@ -5024,7 +5160,7 @@ dnl Note also adjust exclude_expsyms for C++ above. extract_expsyms_cmds= case $host_os in - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) # FIXME: the MSVC++ and ICC port hasn't been tested in a loooong time # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. @@ -5036,9 +5172,6 @@ dnl Note also adjust exclude_expsyms for C++ above. # we just hope/assume this is gcc and not c89 (= MSVC++ or ICC) with_gnu_ld=yes ;; - openbsd* | bitrig*) - with_gnu_ld=no - ;; linux* | k*bsd*-gnu | gnu*) _LT_TAGVAR(link_all_deplibs, $1)=no ;; @@ -5142,7 +5275,7 @@ _LT_EOF fi ;; - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) # _LT_TAGVAR(hardcode_libdir_flag_spec, $1) is actually meaningless, # as there is no search path for DLLs. _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='-L$libdir' @@ -5152,6 +5285,7 @@ _LT_EOF _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(export_symbols_cmds, $1)='$NM $libobjs $convenience | $global_symbol_pipe | $SED -e '\''/^[[BCDGRS]][[ ]]/s/.*[[ ]]\([[^ ]]*\)/\1 DATA/;s/^.*[[ ]]__nm__\([[^ ]]*\)[[ ]][[^ ]]*/\1 DATA/;/^I[[ ]]/d;/^[[AITW]][[ ]]/s/.* //'\'' | sort | uniq > $export_symbols' _LT_TAGVAR(exclude_expsyms, $1)=['[_]+GLOBAL_OFFSET_TABLE_|[_]+GLOBAL__[FID]_.*|[_]+head_[A-Za-z0-9_]+_dll|[A-Za-z0-9_]+_dll_iname'] + _LT_TAGVAR(file_list_spec, $1)='@' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' @@ -5171,7 +5305,7 @@ _LT_EOF haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' - _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(link_all_deplibs, $1)=no ;; os2*) @@ -5198,7 +5332,7 @@ _LT_EOF cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' - _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' ;; @@ -5298,6 +5432,11 @@ _LT_EOF fi ;; + *-mlibc) + _LT_TAGVAR(archive_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' + _LT_TAGVAR(archive_expsym_cmds, $1)='$CC -shared $pic_flag $libobjs $deplibs $compiler_flags $wl-soname $wl$soname $wl-retain-symbols-file $wl$export_symbols -o $lib' + ;; + netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable $libobjs $deplibs $linker_flags -o $lib' @@ -5600,7 +5739,7 @@ _LT_EOF _LT_TAGVAR(export_dynamic_flag_spec, $1)=-rdynamic ;; - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) # When not using gcc, we currently assume that we are using # Microsoft Visual C++ or Intel C++ Compiler. # hardcode_libdir_flag_spec is actually meaningless, as there is @@ -5617,14 +5756,14 @@ _LT_EOF # Tell ltmain to make .dll files, not .so files. shrext_cmds=.dll # FIXME: Setting linknames here is a bad hack. - _LT_TAGVAR(archive_cmds, $1)='$CC -o $output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' + _LT_TAGVAR(archive_cmds, $1)='$CC -Fe$output_objdir/$soname $libobjs $compiler_flags $deplibs -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~linknames=' _LT_TAGVAR(archive_expsym_cmds, $1)='if _LT_DLL_DEF_P([$export_symbols]); then cp "$export_symbols" "$output_objdir/$soname.def"; echo "$tool_output_objdir$soname.def" > "$output_objdir/$soname.exp"; else $SED -e '\''s/^/-link -EXPORT:/'\'' < $export_symbols > $output_objdir/$soname.exp; fi~ - $CC -o $tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ + $CC -Fe$tool_output_objdir$soname $libobjs $compiler_flags $deplibs "@$tool_output_objdir$soname.exp" -Wl,-DLL,-IMPLIB:"$tool_output_objdir$libname.dll.lib"~ linknames=' # The linker will not automatically build a static lib if we build a DLL. # _LT_TAGVAR(old_archive_from_new_cmds, $1)='true' @@ -5842,6 +5981,9 @@ _LT_EOF esac ;; + *-mlibc) + ;; + netbsd* | netbsdelf*-gnu) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $libobjs $deplibs $linker_flags' # a.out @@ -5864,7 +6006,7 @@ _LT_EOF *nto* | *qnx*) ;; - openbsd* | bitrig*) + openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no @@ -5907,7 +6049,7 @@ _LT_EOF cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' - _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' ;; @@ -5943,6 +6085,9 @@ _LT_EOF _LT_TAGVAR(hardcode_libdir_separator, $1)=: ;; + serenity*) + ;; + solaris*) _LT_TAGVAR(no_undefined_flag, $1)=' -z defs' if test yes = "$GCC"; then @@ -6201,7 +6346,7 @@ _LT_TAGDECL([], [hardcode_direct], [0], _LT_TAGDECL([], [hardcode_direct_absolute], [0], [Set to "yes" if using DIR/libNAME$shared_ext during linking hardcodes DIR into the resulting binary and the resulting library dependency is - "absolute", i.e impossible to change by setting $shlibpath_var if the + "absolute", i.e. impossible to change by setting $shlibpath_var if the library is relocated]) _LT_TAGDECL([], [hardcode_minus_L], [0], [Set to "yes" if using the -LDIR flag during linking hardcodes DIR @@ -6259,7 +6404,7 @@ _LT_TAGVAR(objext, $1)=$objext lt_simple_compile_test_code="int some_variable = 0;" # Code to be used in simple link tests -lt_simple_link_test_code='int main(){return(0);}' +lt_simple_link_test_code='int main(void){return(0);}' _LT_TAG_COMPILER # Save the default compiler, since it gets overwritten when the other @@ -6448,8 +6593,7 @@ if test yes != "$_lt_caught_CXX_error"; then wlarc='$wl' # ancient GNU ld didn't support --whole-archive et. al. - if eval "`$CC -print-prog-name=ld` --help 2>&1" | - $GREP 'no-whole-archive' > /dev/null; then + if $LD --help 2>&1 | $GREP 'no-whole-archive' > /dev/null; then _LT_TAGVAR(whole_archive_flag_spec, $1)=$wlarc'--whole-archive$convenience '$wlarc'--no-whole-archive' else _LT_TAGVAR(whole_archive_flag_spec, $1)= @@ -6469,7 +6613,7 @@ if test yes != "$_lt_caught_CXX_error"; then # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [[-]]L"' else GXX=no @@ -6678,7 +6822,7 @@ if test yes != "$_lt_caught_CXX_error"; then esac ;; - cygwin* | mingw* | pw32* | cegcc*) + cygwin* | mingw* | windows* | pw32* | cegcc*) case $GXX,$cc_basename in ,cl* | no,cl* | ,icl* | no,icl*) # Native MSVC or ICC @@ -6731,6 +6875,7 @@ if test yes != "$_lt_caught_CXX_error"; then _LT_TAGVAR(allow_undefined_flag, $1)=unsupported _LT_TAGVAR(always_export_symbols, $1)=no _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes + _LT_TAGVAR(file_list_spec, $1)='@' if $LD --help 2>&1 | $GREP 'auto-import' > /dev/null; then _LT_TAGVAR(archive_cmds, $1)='$CC -shared -nostdlib $predep_objects $libobjs $deplibs $postdep_objects $compiler_flags -o $output_objdir/$soname $wl--enable-auto-image-base -Xlinker --out-implib -Xlinker $lib' @@ -6777,7 +6922,7 @@ if test yes != "$_lt_caught_CXX_error"; then cat $export_symbols | $prefix_cmds >> $output_objdir/$libname.def~ $CC -Zdll -Zcrtdll -o $output_objdir/$soname $libobjs $deplibs $compiler_flags $output_objdir/$libname.def~ emximp -o $lib $output_objdir/$libname.def' - _LT_TAGVAR(old_archive_From_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' + _LT_TAGVAR(old_archive_from_new_cmds, $1)='emximp -o $output_objdir/${libname}_dll.a $output_objdir/$libname.def' _LT_TAGVAR(enable_shared_with_static_runtimes, $1)=yes _LT_TAGVAR(file_list_spec, $1)='@' ;; @@ -6818,7 +6963,7 @@ if test yes != "$_lt_caught_CXX_error"; then haiku*) _LT_TAGVAR(archive_cmds, $1)='$CC -shared $libobjs $deplibs $compiler_flags $wl-soname $wl$soname -o $lib' - _LT_TAGVAR(link_all_deplibs, $1)=yes + _LT_TAGVAR(link_all_deplibs, $1)=no ;; hpux9*) @@ -6845,7 +6990,7 @@ if test yes != "$_lt_caught_CXX_error"; then # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. - output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP " \-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $EGREP "[[-]]L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then @@ -6910,7 +7055,7 @@ if test yes != "$_lt_caught_CXX_error"; then # explicitly linking system object files so we need to strip them # from the output so that they don't get included in the library # dependencies. - output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP " \-L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' + output_verbose_link_cmd='templist=`($CC -b $CFLAGS -v conftest.$objext 2>&1) | $GREP " [[-]]L"`; list= ; for z in $templist; do case $z in conftest.$objext) list="$list $z";; *.$objext);; *) list="$list $z";;esac; done; func_echo_all "$list"' ;; *) if test yes = "$GXX"; then @@ -7142,6 +7287,10 @@ if test yes != "$_lt_caught_CXX_error"; then esac ;; + *-mlibc) + _LT_TAGVAR(ld_shlibs, $1)=yes + ;; + netbsd*) if echo __ELF__ | $CC -E - | $GREP __ELF__ >/dev/null; then _LT_TAGVAR(archive_cmds, $1)='$LD -Bshareable -o $lib $predep_objects $libobjs $deplibs $postdep_objects $linker_flags' @@ -7158,7 +7307,7 @@ if test yes != "$_lt_caught_CXX_error"; then _LT_TAGVAR(ld_shlibs, $1)=yes ;; - openbsd* | bitrig*) + openbsd*) if test -f /usr/libexec/ld.so; then _LT_TAGVAR(hardcode_direct, $1)=yes _LT_TAGVAR(hardcode_shlibpath_var, $1)=no @@ -7249,7 +7398,7 @@ if test yes != "$_lt_caught_CXX_error"; then # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [[-]]L"' else # FIXME: insert proper C++ library support @@ -7264,6 +7413,9 @@ if test yes != "$_lt_caught_CXX_error"; then _LT_TAGVAR(ld_shlibs, $1)=no ;; + serenity*) + ;; + sunos4*) case $cc_basename in CC*) @@ -7333,7 +7485,7 @@ if test yes != "$_lt_caught_CXX_error"; then # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -shared $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [[-]]L"' else # g++ 2.7 appears to require '-G' NOT '-shared' on this # platform. @@ -7344,7 +7496,7 @@ if test yes != "$_lt_caught_CXX_error"; then # Commands to make compiler produce verbose output that lists # what "hidden" libraries, object files and flags are used when # linking a shared library. - output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " \-L"' + output_verbose_link_cmd='$CC -G $CFLAGS -v conftest.$objext 2>&1 | $GREP -v "^Configured with:" | $GREP " [[-]]L"' fi _LT_TAGVAR(hardcode_libdir_flag_spec, $1)='$wl-R $wl$libdir' @@ -7582,10 +7734,11 @@ if AC_TRY_EVAL(ac_compile); then case $prev$p in -L* | -R* | -l*) - # Some compilers place space between "-{L,R}" and the path. + # Some compilers place space between "-{L,R,l}" and the path. # Remove the space. - if test x-L = "$p" || - test x-R = "$p"; then + if test x-L = x"$p" || + test x-R = x"$p" || + test x-l = x"$p"; then prev=$p continue fi @@ -8243,7 +8396,7 @@ AC_SUBST([DLLTOOL]) # ---------------- # Check for a file(cmd) program that can be used to detect file type and magic m4_defun([_LT_DECL_FILECMD], -[AC_CHECK_TOOL([FILECMD], [file], [:]) +[AC_CHECK_PROG([FILECMD], [file], [file], [:]) _LT_DECL([], [FILECMD], [1], [A file(cmd) program that detects file types]) ])# _LD_DECL_FILECMD @@ -8259,73 +8412,6 @@ _LT_DECL([], [SED], [1], [A sed program that does not truncate output]) _LT_DECL([], [Xsed], ["\$SED -e 1s/^X//"], [Sed that helps us avoid accidentally triggering echo(1) options like -n]) ])# _LT_DECL_SED - -m4_ifndef([AC_PROG_SED], [ -############################################################ -# NOTE: This macro has been submitted for inclusion into # -# GNU Autoconf as AC_PROG_SED. When it is available in # -# a released version of Autoconf we should remove this # -# macro and use it instead. # -############################################################ - -m4_defun([AC_PROG_SED], -[AC_MSG_CHECKING([for a sed that does not truncate output]) -AC_CACHE_VAL(lt_cv_path_SED, -[# Loop through the user's path and test for sed and gsed. -# Then use that list of sed's as ones to test for truncation. -as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for lt_ac_prog in sed gsed; do - for ac_exec_ext in '' $ac_executable_extensions; do - if $as_executable_p "$as_dir/$lt_ac_prog$ac_exec_ext"; then - lt_ac_sed_list="$lt_ac_sed_list $as_dir/$lt_ac_prog$ac_exec_ext" - fi - done - done -done -IFS=$as_save_IFS -lt_ac_max=0 -lt_ac_count=0 -# Add /usr/xpg4/bin/sed as it is typically found on Solaris -# along with /bin/sed that truncates output. -for lt_ac_sed in $lt_ac_sed_list /usr/xpg4/bin/sed; do - test ! -f "$lt_ac_sed" && continue - cat /dev/null > conftest.in - lt_ac_count=0 - echo $ECHO_N "0123456789$ECHO_C" >conftest.in - # Check for GNU sed and select it if it is found. - if "$lt_ac_sed" --version 2>&1 < /dev/null | grep 'GNU' > /dev/null; then - lt_cv_path_SED=$lt_ac_sed - break - fi - while true; do - cat conftest.in conftest.in >conftest.tmp - mv conftest.tmp conftest.in - cp conftest.in conftest.nl - echo >>conftest.nl - $lt_ac_sed -e 's/a$//' < conftest.nl >conftest.out || break - cmp -s conftest.out conftest.nl || break - # 10000 chars as input seems more than enough - test 10 -lt "$lt_ac_count" && break - lt_ac_count=`expr $lt_ac_count + 1` - if test "$lt_ac_count" -gt "$lt_ac_max"; then - lt_ac_max=$lt_ac_count - lt_cv_path_SED=$lt_ac_sed - fi - done -done -]) -SED=$lt_cv_path_SED -AC_SUBST([SED]) -AC_MSG_RESULT([$SED]) -])#AC_PROG_SED -])#m4_ifndef - -# Old name: -AU_ALIAS([LT_AC_PROG_SED], [AC_PROG_SED]) dnl aclocal-1.4 backwards compatibility: dnl AC_DEFUN([LT_AC_PROG_SED], []) @@ -8372,7 +8458,7 @@ AC_CACHE_VAL(lt_cv_to_host_file_cmd, [case $host in *-*-mingw* ) case $build in - *-*-mingw* ) # actually msys + *-*-mingw* | *-*-windows* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_w32 ;; *-*-cygwin* ) @@ -8385,7 +8471,7 @@ AC_CACHE_VAL(lt_cv_to_host_file_cmd, ;; *-*-cygwin* ) case $build in - *-*-mingw* ) # actually msys + *-*-mingw* | *-*-windows* ) # actually msys lt_cv_to_host_file_cmd=func_convert_file_msys_to_cygwin ;; *-*-cygwin* ) @@ -8411,9 +8497,9 @@ AC_CACHE_VAL(lt_cv_to_tool_file_cmd, [#assume ordinary cross tools, or native build. lt_cv_to_tool_file_cmd=func_convert_file_noop case $host in - *-*-mingw* ) + *-*-mingw* | *-*-windows* ) case $build in - *-*-mingw* ) # actually msys + *-*-mingw* | *-*-windows* ) # actually msys lt_cv_to_tool_file_cmd=func_convert_file_msys_to_w32 ;; esac diff --git a/deps/libffi/m4/ltoptions.m4 b/deps/libffi/m4/ltoptions.m4 index b0b5e9c21260..25caa890298a 100755 --- a/deps/libffi/m4/ltoptions.m4 +++ b/deps/libffi/m4/ltoptions.m4 @@ -1,6 +1,6 @@ # Helper functions for option handling. -*- Autoconf -*- # -# Copyright (C) 2004-2005, 2007-2009, 2011-2019, 2021-2022 Free +# Copyright (C) 2004-2005, 2007-2009, 2011-2019, 2021-2024 Free # Software Foundation, Inc. # Written by Gary V. Vaughan, 2004 # @@ -8,7 +8,7 @@ # unlimited permission to copy and/or distribute it, with or without # modifications, as long as this notice is preserved. -# serial 8 ltoptions.m4 +# serial 10 ltoptions.m4 # This is to help aclocal find these macros, as it can't see m4_define. AC_DEFUN([LTOPTIONS_VERSION], [m4_if([1])]) @@ -128,7 +128,7 @@ LT_OPTION_DEFINE([LT_INIT], [win32-dll], [enable_win32_dll=yes case $host in -*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-cegcc*) +*-*-cygwin* | *-*-mingw* | *-*-windows* | *-*-pw32* | *-*-cegcc*) AC_CHECK_TOOL(AS, as, false) AC_CHECK_TOOL(DLLTOOL, dlltool, false) AC_CHECK_TOOL(OBJDUMP, objdump, false) @@ -323,29 +323,39 @@ dnl AC_DEFUN([AM_DISABLE_FAST_INSTALL], []) # _LT_WITH_AIX_SONAME([DEFAULT]) # ---------------------------------- -# implement the --with-aix-soname flag, and support the `aix-soname=aix' -# and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. DEFAULT -# is either `aix', `both' or `svr4'. If omitted, it defaults to `aix'. +# implement the --enable-aix-soname configure option, and support the +# `aix-soname=aix' and `aix-soname=both' and `aix-soname=svr4' LT_INIT options. +# DEFAULT is either `aix', `both', or `svr4'. If omitted, it defaults to `aix'. m4_define([_LT_WITH_AIX_SONAME], [m4_define([_LT_WITH_AIX_SONAME_DEFAULT], [m4_if($1, svr4, svr4, m4_if($1, both, both, aix))])dnl shared_archive_member_spec= case $host,$enable_shared in power*-*-aix[[5-9]]*,yes) AC_MSG_CHECKING([which variant of shared library versioning to provide]) - AC_ARG_WITH([aix-soname], - [AS_HELP_STRING([--with-aix-soname=aix|svr4|both], + AC_ARG_ENABLE([aix-soname], + [AS_HELP_STRING([--enable-aix-soname=aix|svr4|both], [shared library versioning (aka "SONAME") variant to provide on AIX, @<:@default=]_LT_WITH_AIX_SONAME_DEFAULT[@:>@.])], - [case $withval in - aix|svr4|both) - ;; - *) - AC_MSG_ERROR([Unknown argument to --with-aix-soname]) - ;; - esac - lt_cv_with_aix_soname=$with_aix_soname], - [AC_CACHE_VAL([lt_cv_with_aix_soname], - [lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT) - with_aix_soname=$lt_cv_with_aix_soname]) + [case $enableval in + aix|svr4|both) + ;; + *) + AC_MSG_ERROR([Unknown argument to --enable-aix-soname]) + ;; + esac + lt_cv_with_aix_soname=$enable_aix_soname], + [_AC_ENABLE_IF([with], [aix-soname], + [case $withval in + aix|svr4|both) + ;; + *) + AC_MSG_ERROR([Unknown argument to --with-aix-soname]) + ;; + esac + lt_cv_with_aix_soname=$with_aix_soname], + [AC_CACHE_VAL([lt_cv_with_aix_soname], + [lt_cv_with_aix_soname=]_LT_WITH_AIX_SONAME_DEFAULT)]) + enable_aix_soname=$lt_cv_with_aix_soname]) + with_aix_soname=$enable_aix_soname AC_MSG_RESULT([$with_aix_soname]) if test aix != "$with_aix_soname"; then # For the AIX way of multilib, we name the shared archive member @@ -376,30 +386,50 @@ LT_OPTION_DEFINE([LT_INIT], [aix-soname=svr4], [_LT_WITH_AIX_SONAME([svr4])]) # _LT_WITH_PIC([MODE]) # -------------------- -# implement the --with-pic flag, and support the 'pic-only' and 'no-pic' +# implement the --enable-pic flag, and support the 'pic-only' and 'no-pic' # LT_INIT options. # MODE is either 'yes' or 'no'. If omitted, it defaults to 'both'. m4_define([_LT_WITH_PIC], -[AC_ARG_WITH([pic], - [AS_HELP_STRING([--with-pic@<:@=PKGS@:>@], +[AC_ARG_ENABLE([pic], + [AS_HELP_STRING([--enable-pic@<:@=PKGS@:>@], [try to use only PIC/non-PIC objects @<:@default=use both@:>@])], [lt_p=${PACKAGE-default} - case $withval in - yes|no) pic_mode=$withval ;; - *) - pic_mode=default - # Look at the argument we got. We use all the common list separators. - lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, - for lt_pkg in $withval; do - IFS=$lt_save_ifs - if test "X$lt_pkg" = "X$lt_p"; then - pic_mode=yes - fi - done - IFS=$lt_save_ifs - ;; - esac], - [pic_mode=m4_default([$1], [default])]) + case $enableval in + yes|no) pic_mode=$enableval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for lt_pkg in $enableval; do + IFS=$lt_save_ifs + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS=$lt_save_ifs + ;; + esac], + [dnl Continue to support --with-pic and --without-pic, for backward + dnl compatibility. + _AC_ENABLE_IF([with], [pic], + [lt_p=${PACKAGE-default} + case $withval in + yes|no) pic_mode=$withval ;; + *) + pic_mode=default + # Look at the argument we got. We use all the common list separators. + lt_save_ifs=$IFS; IFS=$IFS$PATH_SEPARATOR, + for lt_pkg in $withval; do + IFS=$lt_save_ifs + if test "X$lt_pkg" = "X$lt_p"; then + pic_mode=yes + fi + done + IFS=$lt_save_ifs + ;; + esac], + [pic_mode=m4_default([$1], [default])])] + ) _LT_DECL([], [pic_mode], [0], [What type of objects to build])dnl ])# _LT_WITH_PIC diff --git a/deps/libffi/m4/ltsugar.m4 b/deps/libffi/m4/ltsugar.m4 index 902508bd93ae..5b5c80a3ad78 100755 --- a/deps/libffi/m4/ltsugar.m4 +++ b/deps/libffi/m4/ltsugar.m4 @@ -1,6 +1,6 @@ # ltsugar.m4 -- libtool m4 base layer. -*-Autoconf-*- # -# Copyright (C) 2004-2005, 2007-2008, 2011-2019, 2021-2022 Free Software +# Copyright (C) 2004-2005, 2007-2008, 2011-2019, 2021-2024 Free Software # Foundation, Inc. # Written by Gary V. Vaughan, 2004 # diff --git a/deps/libffi/m4/ltversion.m4 b/deps/libffi/m4/ltversion.m4 index b155d0aceca3..228df3f39bf9 100755 --- a/deps/libffi/m4/ltversion.m4 +++ b/deps/libffi/m4/ltversion.m4 @@ -1,6 +1,6 @@ # ltversion.m4 -- version numbers -*- Autoconf -*- # -# Copyright (C) 2004, 2011-2019, 2021-2022 Free Software Foundation, +# Copyright (C) 2004, 2011-2019, 2021-2024 Free Software Foundation, # Inc. # Written by Scott James Remnant, 2004 # @@ -10,15 +10,15 @@ # @configure_input@ -# serial 4245 ltversion.m4 +# serial 4441 ltversion.m4 # This file is part of GNU Libtool -m4_define([LT_PACKAGE_VERSION], [2.4.7]) -m4_define([LT_PACKAGE_REVISION], [2.4.7]) +m4_define([LT_PACKAGE_VERSION], [2.5.4]) +m4_define([LT_PACKAGE_REVISION], [2.5.4]) AC_DEFUN([LTVERSION_VERSION], -[macro_version='2.4.7' -macro_revision='2.4.7' +[macro_version='2.5.4' +macro_revision='2.5.4' _LT_DECL(, macro_version, 0, [Which release of libtool.m4 was used?]) _LT_DECL(, macro_revision, 0) ]) diff --git a/deps/libffi/m4/lt~obsolete.m4 b/deps/libffi/m4/lt~obsolete.m4 index 0f7a8759da8d..22b534697357 100755 --- a/deps/libffi/m4/lt~obsolete.m4 +++ b/deps/libffi/m4/lt~obsolete.m4 @@ -1,6 +1,6 @@ # lt~obsolete.m4 -- aclocal satisfying obsolete definitions. -*-Autoconf-*- # -# Copyright (C) 2004-2005, 2007, 2009, 2011-2019, 2021-2022 Free +# Copyright (C) 2004-2005, 2007, 2009, 2011-2019, 2021-2024 Free # Software Foundation, Inc. # Written by Scott James Remnant, 2004. # diff --git a/deps/libffi/man/Makefile.in b/deps/libffi/man/Makefile.in index 0e90b6263043..d0040c90a618 100644 --- a/deps/libffi/man/Makefile.in +++ b/deps/libffi/man/Makefile.in @@ -1,7 +1,7 @@ -# Makefile.in generated by automake 1.16.5 from Makefile.am. +# Makefile.in generated by automake 1.18.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2021 Free Software Foundation, Inc. +# Copyright (C) 1994-2025 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -69,6 +69,8 @@ am__make_running_with_option = \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +am__rm_f = rm -f $(am__rm_f_notfound) +am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -153,10 +155,9 @@ am__base_list = \ sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \ sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g' am__uninstall_files_from_dir = { \ - test -z "$$files" \ - || { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ - || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ - $(am__cd) "$$dir" && rm -f $$files; }; \ + { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \ + || { echo " ( cd '$$dir' && rm -f" $$files ")"; \ + $(am__cd) "$$dir" && echo $$files | $(am__xargs_n) 40 $(am__rm_f); }; \ } man3dir = $(mandir)/man3 am__installdirs = "$(DESTDIR)$(man3dir)" @@ -266,8 +267,10 @@ ac_ct_READELF = @ac_ct_READELF@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ +am__xargs_n = @am__xargs_n@ ax_enable_builddir_sed = @ax_enable_builddir_sed@ bindir = @bindir@ build = @build@ @@ -408,6 +411,7 @@ ctags CTAGS: cscope cscopelist: + distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am @@ -472,8 +476,8 @@ mostlyclean-generic: clean-generic: distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + -$(am__rm_f) $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -567,3 +571,10 @@ uninstall-man: uninstall-man3 # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: + +# Tell GNU make to disable its built-in pattern rules. +%:: %,v +%:: RCS/%,v +%:: RCS/% +%:: s.% +%:: SCCS/s.% diff --git a/deps/libffi/missing b/deps/libffi/missing index 1fe1611f1851..5e450bab3cdf 100755 --- a/deps/libffi/missing +++ b/deps/libffi/missing @@ -1,9 +1,11 @@ #! /bin/sh -# Common wrapper for a few potentially missing GNU programs. +# Common wrapper for a few potentially missing GNU and other programs. -scriptversion=2018-03-07.03; # UTC +scriptversion=2025-06-18.21; # UTC -# Copyright (C) 1996-2021 Free Software Foundation, Inc. +# shellcheck disable=SC2006,SC2268 # we must support pre-POSIX shells + +# Copyright (C) 1996-2025 Free Software Foundation, Inc. # Originally written by Fran,cois Pinard <pinard@iro.umontreal.ca>, 1996. # This program is free software; you can redistribute it and/or modify @@ -54,18 +56,20 @@ Options: -v, --version output version information and exit Supported PROGRAM values: - aclocal autoconf autoheader autom4te automake makeinfo - bison yacc flex lex help2man +aclocal autoconf autogen autoheader autom4te automake autoreconf +bison flex help2man lex makeinfo perl yacc Version suffixes to PROGRAM as well as the prefixes 'gnu-', 'gnu', and 'g' are ignored when checking the name. -Send bug reports to <bug-automake@gnu.org>." +Report bugs to <bug-automake@gnu.org>. +GNU Automake home page: <https://www.gnu.org/software/automake/>. +General help using GNU software: <https://www.gnu.org/gethelp/>." exit $? ;; -v|--v|--ve|--ver|--vers|--versi|--versio|--version) - echo "missing $scriptversion (GNU Automake)" + echo "missing (GNU Automake) $scriptversion" exit $? ;; @@ -108,7 +112,7 @@ gnu_software_URL=https://www.gnu.org/software program_details () { case $1 in - aclocal|automake) + aclocal|automake|autoreconf) echo "The '$1' program is part of the GNU Automake package:" echo "<$gnu_software_URL/automake>" echo "It also requires GNU Autoconf, GNU m4 and Perl in order to run:" @@ -123,6 +127,9 @@ program_details () echo "<$gnu_software_URL/m4/>" echo "<$perl_URL>" ;; + *) + : + ;; esac } @@ -137,48 +144,55 @@ give_advice () printf '%s\n' "'$1' is $msg." configure_deps="'configure.ac' or m4 files included by 'configure.ac'" + autoheader_deps="'acconfig.h'" + automake_deps="'Makefile.am'" + aclocal_deps="'acinclude.m4'" case $normalized_program in + aclocal*) + echo "You should only need it if you modified $aclocal_deps or" + echo "$configure_deps." + ;; autoconf*) - echo "You should only need it if you modified 'configure.ac'," - echo "or m4 files included by it." - program_details 'autoconf' + echo "You should only need it if you modified $configure_deps." + ;; + autogen*) + echo "You should only need it if you modified a '.def' or '.tpl' file." + echo "You may want to install the GNU AutoGen package:" + echo "<$gnu_software_URL/autogen/>" ;; autoheader*) - echo "You should only need it if you modified 'acconfig.h' or" + echo "You should only need it if you modified $autoheader_deps or" echo "$configure_deps." - program_details 'autoheader' ;; automake*) - echo "You should only need it if you modified 'Makefile.am' or" - echo "$configure_deps." - program_details 'automake' - ;; - aclocal*) - echo "You should only need it if you modified 'acinclude.m4' or" + echo "You should only need it if you modified $automake_deps or" echo "$configure_deps." - program_details 'aclocal' ;; - autom4te*) + autom4te*) echo "You might have modified some maintainer files that require" echo "the 'autom4te' program to be rebuilt." - program_details 'autom4te' + ;; + autoreconf*) + echo "You should only need it if you modified $aclocal_deps or" + echo "$automake_deps or $autoheader_deps or $automake_deps or" + echo "$configure_deps." ;; bison*|yacc*) echo "You should only need it if you modified a '.y' file." echo "You may want to install the GNU Bison package:" echo "<$gnu_software_URL/bison/>" ;; - lex*|flex*) - echo "You should only need it if you modified a '.l' file." - echo "You may want to install the Fast Lexical Analyzer package:" - echo "<$flex_URL>" - ;; help2man*) echo "You should only need it if you modified a dependency" \ "of a man page." echo "You may want to install the GNU Help2man package:" echo "<$gnu_software_URL/help2man/>" ;; + lex*|flex*) + echo "You should only need it if you modified a '.l' file." + echo "You may want to install the Fast Lexical Analyzer package:" + echo "<$flex_URL>" + ;; makeinfo*) echo "You should only need it if you modified a '.texi' file, or" echo "any other file indirectly affecting the aspect of the manual." @@ -189,6 +203,12 @@ give_advice () echo "want to install GNU make:" echo "<$gnu_software_URL/make/>" ;; + perl*) + echo "You should only need it to run GNU Autoconf, GNU Automake, " + echo " assorted other tools, or if you modified a Perl source file." + echo "You may want to install the Perl 5 language interpreter:" + echo "<$perl_URL>" + ;; *) echo "You might have modified some files without having the proper" echo "tools for further handling them. Check the 'README' file, it" @@ -197,6 +217,7 @@ give_advice () echo "case some other package contains this missing '$1' program." ;; esac + program_details "$normalized_program" } give_advice "$1" | sed -e '1s/^/WARNING: /' \ @@ -207,9 +228,9 @@ give_advice "$1" | sed -e '1s/^/WARNING: /' \ exit $st # Local variables: -# eval: (add-hook 'before-save-hook 'time-stamp) +# eval: (add-hook 'before-save-hook 'time-stamp nil t) # time-stamp-start: "scriptversion=" -# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-format: "%Y-%02m-%02d.%02H" # time-stamp-time-zone: "UTC0" # time-stamp-end: "; # UTC" # End: diff --git a/deps/libffi/src/aarch64/ffi.c b/deps/libffi/src/aarch64/ffi.c index 1eb90dd565ad..d950e970e93e 100644 --- a/deps/libffi/src/aarch64/ffi.c +++ b/deps/libffi/src/aarch64/ffi.c @@ -105,249 +105,137 @@ intlog2 (int n) return level; } -/* A subroutine of is_vfp_type. Given a structure type, return the type code - of the first non-structure element. Recurse for structure elements. - Return -1 if the structure is in fact empty, i.e. no nested elements. */ +/* A subroutine of is_vfp_type. Recursively flatten the (possibly nested) + aggregate TY and verify it is homogeneous: every leaf must be the same + fundamental type, as AAPCS64 requires of an HFA or HVA. Two short + vectors are the same fundamental type when they have the same size (the + lane type is irrelevant: an integer and a floating-point 16-byte vector + both occupy one Q register). A _Complex counts as two members of its + element type. + + *KIND carries the common leaf type found so far: 0 before the first leaf, + a positive FFI_TYPE_{FLOAT,DOUBLE,LONGDOUBLE} for a floating-point HFA, or + the negated vector size for an HVA. Returns the number of leaf elements, + or -1 if TY is empty or not homogeneous. */ static int -is_hfa0 (const ffi_type *ty) -{ - ffi_type **elements = ty->elements; - int i, ret = -1; - - if (elements != NULL) - for (i = 0; elements[i]; ++i) - { - ret = elements[i]->type; - if (ret == FFI_TYPE_STRUCT || ret == FFI_TYPE_VECTOR - || ret == FFI_TYPE_COMPLEX) - { - ret = is_hfa0 (elements[i]); - if (ret < 0) - continue; - } - break; - } - - return ret; -} - -/* A subroutine of is_vfp_type. Return the size in bytes of the vector (SIMD) - member of TY, i.e. the width of a single Neon register slot, or 0 if TY - neither is nor contains a vector. For a bare vector this is its whole size; - for a homogeneous vector aggregate it is the size of one lane vector. */ - -static size_t -is_simd (const ffi_type *ty) +hfa_flatten (const ffi_type *ty, int *kind) { ffi_type **elements; - int i; - - if (ty->type == FFI_TYPE_VECTOR) - return ty->size; + int i, total, n, k; - elements = ty->elements; - if (elements != NULL) - for (i = 0; elements[i]; ++i) - { - int t = elements[i]->type; - if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX - || t == FFI_TYPE_VECTOR) - return is_simd (elements[i]); - } - - return 0; -} + switch (ty->type) + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + k = (int) ty->type; + if (*kind == 0) + *kind = k; + else if (*kind != k) + return -1; + return 1; -/* A subroutine of is_vfp_type. Given a structure type, return true if all - of the non-structure elements are the same as CANDIDATE. */ + case FFI_TYPE_VECTOR: + /* Only 4-, 8- and 16-byte short vectors have a register class here. */ + if (ty->size != 4 && ty->size != 8 && ty->size != 16) + return -1; + k = -(int) ty->size; + if (*kind == 0) + *kind = k; + else if (*kind != k) + return -1; + return 1; -static int -is_hfa1 (const ffi_type *ty, int candidate) -{ - ffi_type **elements = ty->elements; - int i; + case FFI_TYPE_COMPLEX: + k = ty->elements[0]->type; + if (k != FFI_TYPE_FLOAT && k != FFI_TYPE_DOUBLE && k != FFI_TYPE_LONGDOUBLE) + return -1; + if (*kind == 0) + *kind = k; + else if (*kind != k) + return -1; + return 2; - if (elements != NULL) - for (i = 0; elements[i]; ++i) - { - int t = elements[i]->type; - if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_VECTOR - || t == FFI_TYPE_COMPLEX) - { - if (!is_hfa1 (elements[i], candidate)) - return 0; - } - else if (t != candidate) - return 0; - } + case FFI_TYPE_STRUCT: + elements = ty->elements; + if (elements == NULL) + return -1; + total = 0; + for (i = 0; elements[i]; ++i) + { + n = hfa_flatten (elements[i], kind); + if (n < 0) + return -1; + total += n; + } + return total == 0 ? -1 : total; - return 1; + default: + return -1; + } } -/* Determine if TY may be allocated to the FP registers. This is both an - fp scalar type as well as an homogenous floating point aggregate (HFA). - That is, a structure consisting of 1 to 4 members of all the same type, - where that type is an fp scalar. +/* Determine if TY may be allocated to the FP/SIMD registers. This is an fp + scalar or short vector, or a homogeneous aggregate (HFA or HVA) of 1 to 4 + members all of the same fundamental type. - Returns non-zero iff TY is an HFA. The result is the AARCH64_RET_* - constant for the type. */ + Returns non-zero iff TY is such a type. The result is the AARCH64_RET_* + constant for it. */ static int is_vfp_type (const ffi_type *ty) { - ffi_type **elements; - int candidate, i; - size_t size, ele_count, simd_size; + int candidate, count, kind; + size_t size; /* Quickest tests first. */ - candidate = ty->type; - switch (candidate) + switch (ty->type) { default: return 0; case FFI_TYPE_FLOAT: case FFI_TYPE_DOUBLE: case FFI_TYPE_LONGDOUBLE: - ele_count = 1; - goto done; + return (int) ty->type * 4 + (4 - 1); case FFI_TYPE_COMPLEX: candidate = ty->elements[0]->type; switch (candidate) - { - case FFI_TYPE_FLOAT: - case FFI_TYPE_DOUBLE: - case FFI_TYPE_LONGDOUBLE: - ele_count = 2; - goto done; - } + { + case FFI_TYPE_FLOAT: + case FFI_TYPE_DOUBLE: + case FFI_TYPE_LONGDOUBLE: + return candidate * 4 + (4 - 2); + } return 0; case FFI_TYPE_STRUCT: case FFI_TYPE_VECTOR: break; } - /* No HFA/HVA types are smaller than 4 bytes, or larger than 64 bytes. */ + /* No HFA/HVA is smaller than 4 bytes or larger than 64 bytes (4 Q regs). */ size = ty->size; if (size < 4 || size > 64) return 0; - /* Determine the width of the vector (SIMD) member, if any: 0 for a plain - floating-point HFA, else the size in bytes of one Neon register slot. */ - simd_size = is_simd (ty); - - /* Find the type of the first non-aggregate member. */ - elements = ty->elements; - candidate = elements[0]->type; - if (candidate == FFI_TYPE_STRUCT || candidate == FFI_TYPE_VECTOR - || candidate == FFI_TYPE_COMPLEX) - { - for (i = 0; ; ++i) - { - candidate = is_hfa0 (elements[i]); - if (candidate >= 0) - break; - } - } - - if (simd_size) - { - /* Vector or homogeneous vector aggregate (HVA). A single Neon slot is - at most 16 bytes (a Q register). A bare vector wider than 16 bytes - (e.g. a 32-byte double4) has no short-vector register class under - AAPCS64, so bail and let the generic composite path pass it by - reference / return it in memory -- matching what current compilers do. - The scalar lane type does not affect register selection (an integer - and a floating-point 16-byte vector both occupy one Q register), so, - unlike the floating-point HFA path below, CANDIDATE is used only to - confirm the lanes are homogeneous. */ - size_t reg_size = simd_size; - int num_registers; - int first_level_element_type; - - /* A Neon register slot is an S (4B), D (8B) or Q (16B). A lane narrower - than 4 bytes has no short-vector register class under AAPCS64 and would - map below AARCH64_RET_S4, making extend_hfa_type() branch before its - jump table; reject it and let the generic aggregate path handle it. */ - if (reg_size < 4 || reg_size > 16 || size % reg_size != 0) - return 0; - num_registers = (int) (size / reg_size); - if (num_registers > 4) - return 0; - - /* For an aggregate, every member must itself be a vector (or nested - vector aggregate) of the same register width: this rejects a struct - that mixes a bare scalar with a vector even when the scalar's type - matches the vector's lane type. A bare vector needs no such check -- - its lanes were validated when its layout was computed. */ - if (ty->type != FFI_TYPE_VECTOR) - for (i = 0; elements[i]; ++i) - if (is_simd (elements[i]) != reg_size) - return 0; - - /* Every lane must be the identical scalar type across the whole HVA - (this rejects, e.g., an aggregate mixing float and integer vectors). */ - for (i = 0; elements[i]; ++i) - { - int t = elements[i]->type; - if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_VECTOR - || t == FFI_TYPE_COMPLEX) - { - if (!is_hfa1 (elements[i], candidate)) - return 0; - } - else if (t != candidate) - return 0; - } - - /* Reuse the AARCH64_RET_{S,D,Q}* codes, which are laid out as - (type * 4) + (4 - count) with FLOAT->S(4B), DOUBLE->D(8B), - LONGDOUBLE->Q(16B). Map the register width onto that type axis. */ - first_level_element_type = FFI_TYPE_FLOAT + intlog2 ((int) reg_size) - 2; - return first_level_element_type * 4 + (4 - num_registers); - } - - /* If the first member is not a floating point type, it's not an HFA. - Also quickly re-check the size of the structure. */ - switch (candidate) - { - case FFI_TYPE_FLOAT: - ele_count = size / sizeof(float); - if (size != ele_count * sizeof(float)) - return 0; - break; - case FFI_TYPE_DOUBLE: - ele_count = size / sizeof(double); - if (size != ele_count * sizeof(double)) - return 0; - break; - case FFI_TYPE_LONGDOUBLE: - ele_count = size / sizeof(long double); - if (size != ele_count * sizeof(long double)) - return 0; - break; - default: - return 0; - } - if (ele_count > 4) + /* Flatten the aggregate; every leaf must share one fundamental type, and + there must be 1 to 4 of them. */ + kind = 0; + count = hfa_flatten (ty, &kind); + if (count < 1 || count > 4) return 0; - /* Finally, make sure that all scalar elements are the same type. */ - for (i = 0; elements[i]; ++i) + if (kind < 0) { - int t = elements[i]->type; - if (t == FFI_TYPE_STRUCT || t == FFI_TYPE_COMPLEX) - { - if (!is_hfa1 (elements[i], candidate)) - return 0; - } - else if (t != candidate) - return 0; + /* HVA: KIND is the negated vector register width (4, 8 or 16 bytes). + Map it onto the S/D/Q axis of the AARCH64_RET_* encoding. */ + candidate = FFI_TYPE_FLOAT + intlog2 (-kind) - 2; } + else + /* Floating-point HFA: KIND is the common scalar type. */ + candidate = kind; - /* All tests succeeded. Encode the result. */ - done: - return candidate * 4 + (4 - (int)ele_count); + return candidate * 4 + (4 - count); } /* Representation of the procedure call argument marshalling @@ -408,6 +296,28 @@ allocate_to_stack (struct arg_state *state, void *stack, return (char *)stack + nsaa; } +/* Darwin packs only scalars to their natural alignment; a non-HFA + composite of up to 16 bytes still takes whole register-sized slots. */ +static void * +allocate_composite_to_stack (struct arg_state *state, void *stack, + const ffi_type *ty) +{ + size_t alignment = ty->alignment; + size_t size = ty->size; + +/* Apple's ABI gives these composites full pointer-sized slots. The + experimental GCC Darwin port instead packs them to their natural size; + match the compiler ABI used to build libffi so calls and closures remain + self-consistent. */ +#if defined (__APPLE__) \ + && (!defined (__GNUC__) || defined (__clang__)) + alignment = FFI_ALIGN (alignment, sizeof (void *)); + size = FFI_ALIGN (size, sizeof (void *)); +#endif + + return allocate_to_stack (state, stack, alignment, size); +} + /* Allocate and copy a structure that is passed by value on the stack and return a pointer to it. */ static void * @@ -564,13 +474,9 @@ compress_hfa_type (void *dest, void *reg, int h) { case AARCH64_RET_S1: if (dest == reg) - { -#ifdef __AARCH64EB__ - dest += 12; -#endif - } + return (char *)dest + BE (12); else - *(float *)dest = *(float *)reg; + *(float *)dest = *(float *)((char *)reg + BE (12)); break; case AARCH64_RET_S2: __asm__ ("ldp q16, q17, [%1]\n\t" @@ -592,13 +498,9 @@ compress_hfa_type (void *dest, void *reg, int h) case AARCH64_RET_D1: if (dest == reg) - { -#ifdef __AARCH64EB__ - dest += 8; -#endif - } + return (char *)dest + BE (8); else - *(double *)dest = *(double *)reg; + *(double *)dest = *(double *)((char *)reg + BE (8)); break; case AARCH64_RET_D2: __asm__ ("ldp q16, q17, [%1]\n\t" @@ -637,10 +539,11 @@ allocate_int_to_reg_or_stack (struct call_context *context, void *stack, size_t size) { if (state->ngrn < N_X_ARG_REG) - return &context->x[state->ngrn++]; + return (char *)&context->x[state->ngrn++] + BE (sizeof (UINT64) - size); state->ngrn = N_X_ARG_REG; - return allocate_to_stack (state, stack, size, size); + return (char *)allocate_to_stack (state, stack, size, size) + + BE (sizeof (UINT64) - size); } static void * @@ -937,7 +840,8 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue, break; } state.nsrn = N_V_ARG_REG; - dest = allocate_to_stack (&state, stack, ty->alignment, s); + dest = (char *)allocate_to_stack (&state, stack, ty->alignment, s) + + (t == FFI_TYPE_FLOAT ? BE (sizeof (UINT64) - s) : 0); } } else if (s > 16) @@ -951,6 +855,13 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue, a = &dest; t = FFI_TYPE_POINTER; s = sizeof (void *); + /* The argument is now the pointer, which takes a plain 8-byte, + 8-aligned stack slot (AAPCS64 B.4). Re-point `ty' so + do_pointer aligns the slot by 8 and not by the composite's + own alignment (up to 16), which would place the pointer at + the wrong offset -- where the callee, and libffi's own + closure path, do not look (GHSA-h52h-3759-xqm4). */ + ty = &ffi_type_pointer; goto do_pointer; } else @@ -972,7 +883,7 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *orig_rvalue, adjusted and the argument is copied to memory at the adjusted NSAA. */ state.ngrn = N_X_ARG_REG; - dest = allocate_to_stack (&state, stack, ty->alignment, s); + dest = allocate_composite_to_stack (&state, stack, ty); } } memcpy (dest, a, s); @@ -1222,8 +1133,9 @@ ffi_closure_SYSV_inner (ffi_cif *cif, { state.ngrn = N_X_ARG_REG; state.nsrn = N_V_ARG_REG; - avalue[i] = allocate_to_stack(&state, stack, - ty->alignment, s); + avalue[i] = (char *)allocate_to_stack (&state, stack, + ty->alignment, s) + + (t == FFI_TYPE_FLOAT ? BE (sizeof (UINT64) - s) : 0); } } else @@ -1237,8 +1149,9 @@ ffi_closure_SYSV_inner (ffi_cif *cif, else { state.nsrn = N_V_ARG_REG; - avalue[i] = allocate_to_stack(&state, stack, - ty->alignment, s); + avalue[i] = (char *)allocate_to_stack (&state, stack, + ty->alignment, s) + + (t == FFI_TYPE_FLOAT ? BE (sizeof (UINT64) - s) : 0); } } } @@ -1270,8 +1183,7 @@ ffi_closure_SYSV_inner (ffi_cif *cif, else { state.ngrn = N_X_ARG_REG; - avalue[i] = allocate_to_stack(&state, stack, - ty->alignment, s); + avalue[i] = allocate_composite_to_stack (&state, stack, ty); } } break; diff --git a/deps/libffi/src/aarch64/internal.h b/deps/libffi/src/aarch64/internal.h index 2f76eb370194..c58fd33a3584 100644 --- a/deps/libffi/src/aarch64/internal.h +++ b/deps/libffi/src/aarch64/internal.h @@ -78,6 +78,11 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endif +#ifdef __AARCH64EB__ +# define BE(X) X +#else +# define BE(X) 0 +#endif /* Helpers for writing assembly compatible with arm ptr auth */ #ifdef LIBFFI_ASM diff --git a/deps/libffi/src/aarch64/sysv.S b/deps/libffi/src/aarch64/sysv.S index ccf2a3d41582..10ed111ca8bc 100644 --- a/deps/libffi/src/aarch64/sysv.S +++ b/deps/libffi/src/aarch64/sysv.S @@ -728,3 +728,7 @@ CNAME(ffi_go_closure_SYSV): .section .note.GNU-stack,"",%progbits FEATURE_1_AND_MARK(AARCH64_BTI | AARCH64_POINTER_AUTH | AARCH64_GCS) #endif + +#ifdef __APPLE__ + .subsections_via_symbols +#endif diff --git a/deps/libffi/src/arm/ffi.c b/deps/libffi/src/arm/ffi.c index cfd3e9d19ebd..b4195b336576 100644 --- a/deps/libffi/src/arm/ffi.c +++ b/deps/libffi/src/arm/ffi.c @@ -309,8 +309,20 @@ ffi_prep_cif_machdep (ffi_cif *cif) flags = ARM_TYPE_INT; else { + /* The address of the return value goes in r0, ahead of the + arguments, which can then need more padding than cif->bytes + includes. Lay them out again behind it. */ + unsigned i; + flags = ARM_TYPE_STRUCT; - bytes += 4; + bytes = 4; + for (i = 0; i < cif->nargs; i++) + { + ffi_type *ty = cif->arg_types[i]; + + bytes = (size_t) ffi_align (ty, (void *) bytes); + bytes += FFI_ALIGN (ty->size, 4); + } } break; @@ -467,6 +479,11 @@ ffi_prep_incoming_args_SYSV (ffi_cif *cif, void *rvalue, size_t z = ty->size; argp = ffi_align (ty, argp); +#ifdef __ARMEB__ + if (z < 4 && ty->type != FFI_TYPE_STRUCT && ty->type != FFI_TYPE_COMPLEX) + avalue[i] = (void *) (argp + 4 - z); + else +#endif avalue[i] = (void *) argp; argp += z; } @@ -515,6 +532,11 @@ ffi_prep_incoming_args_VFP (ffi_cif *cif, void *rvalue, char *stack, if (tregp + z <= eo_regp || !stack_used) { /* Because we're little endian, this is what it turns into. */ +#ifdef __ARMEB__ + if (z < 4 && ty->type != FFI_TYPE_STRUCT && ty->type != FFI_TYPE_COMPLEX) + avalue[i] = (void *) (tregp + 4 - z); + else +#endif avalue[i] = (void *) tregp; regp = tregp + z; @@ -537,6 +559,11 @@ ffi_prep_incoming_args_VFP (ffi_cif *cif, void *rvalue, char *stack, stack_used = 1; argp = ffi_align (ty, argp); +#ifdef __ARMEB__ + if (z < 4 && ty->type != FFI_TYPE_STRUCT && ty->type != FFI_TYPE_COMPLEX) + avalue[i] = (void *) (argp + 4 - z); + else +#endif avalue[i] = (void *) argp; argp += z; } diff --git a/deps/libffi/src/closures.c b/deps/libffi/src/closures.c index c1fbcf87ce29..5261c789e209 100644 --- a/deps/libffi/src/closures.c +++ b/deps/libffi/src/closures.c @@ -65,6 +65,7 @@ ffi_closure_alloc (size_t size, void **code) static size_t page_size; size_t rounded_size; void *codeseg, *dataseg; + long ps; int prot; /* Expect that PAX mprotect is active and a separate code mapping is necessary. */ @@ -73,7 +74,12 @@ ffi_closure_alloc (size_t size, void **code) /* Obtain system page size. */ if (!page_size) - page_size = sysconf(_SC_PAGESIZE); + { + ps = sysconf(_SC_PAGESIZE); + if (ps <= 0) + return NULL; + page_size = (size_t) ps; + } /* Round allocation size up to the next page, keeping in mind the size field and pointer to code map. */ rounded_size = (size + overhead + page_size - 1) & ~(page_size - 1); @@ -256,12 +262,23 @@ ffi_trampoline_table_alloc (void) /* We have valid trampoline and config pages */ table = calloc (1, sizeof (ffi_trampoline_table)); + if (table == NULL) + { + vm_deallocate (mach_task_self (), config_page, PAGE_MAX_SIZE * 2); + return NULL; + } table->free_count = FFI_TRAMPOLINE_COUNT; table->config_page = config_page; /* Create and initialize the free list */ table->free_list_pool = calloc (FFI_TRAMPOLINE_COUNT, sizeof (ffi_trampoline_table_entry)); + if (table->free_list_pool == NULL) + { + vm_deallocate (mach_task_self (), config_page, PAGE_MAX_SIZE * 2); + free (table); + return NULL; + } for (i = 0; i < table->free_count; i++) { @@ -370,7 +387,13 @@ ffi_closure_free (void *ptr) } else if (ffi_trampoline_tables != table) { - /* Otherwise, bump this table to the top of the list */ + /* Otherwise, bump this table to the top of the list. Unlink it + from its current position first, so the old neighbours do not + keep pointing at it and corrupt the list (CWE-416). */ + if (table->prev != NULL) + table->prev->next = table->next; + if (table->next != NULL) + table->next->prev = table->prev; table->prev = NULL; table->next = ffi_trampoline_tables; if (ffi_trampoline_tables != NULL) @@ -546,13 +569,18 @@ static void *dlmalloc(size_t); static void dlfree(void*); static void *dlcalloc(size_t, size_t) MAYBE_UNUSED; static void *dlrealloc(void *, size_t) MAYBE_UNUSED; +static void *dlrealloc_in_place(void *, size_t) MAYBE_UNUSED; static void *dlmemalign(size_t, size_t) MAYBE_UNUSED; +static int dlposix_memalign(void **, size_t, size_t) MAYBE_UNUSED; static void *dlvalloc(size_t) MAYBE_UNUSED; static int dlmallopt(int, int) MAYBE_UNUSED; static size_t dlmalloc_footprint(void) MAYBE_UNUSED; static size_t dlmalloc_max_footprint(void) MAYBE_UNUSED; +static size_t dlmalloc_footprint_limit(void) MAYBE_UNUSED; +static size_t dlmalloc_set_footprint_limit(size_t) MAYBE_UNUSED; static void** dlindependent_calloc(size_t, size_t, void**) MAYBE_UNUSED; static void** dlindependent_comalloc(size_t, size_t*, void**) MAYBE_UNUSED; +static size_t dlbulk_free(void**, size_t) MAYBE_UNUSED; static void *dlpvalloc(size_t) MAYBE_UNUSED; static int dlmalloc_trim(size_t) MAYBE_UNUSED; static size_t dlmalloc_usable_size(void*) MAYBE_UNUSED; @@ -737,12 +765,14 @@ static struct #endif /* HAVE_MNTENT */ }; +#define OPEN_TEMP_EXEC_FILE_OPTS_COUNT \ + (sizeof (open_temp_exec_file_opts) / sizeof (*open_temp_exec_file_opts)) + /* Current index into open_temp_exec_file_opts. */ -static int open_temp_exec_file_opts_idx = 0; +static size_t open_temp_exec_file_opts_idx = 0; /* Reset a current multi-call func, then advances to the next entry. - If we're at the last, go back to the first and return nonzero, - otherwise return zero. */ + Return nonzero after advancing past the last entry. */ static int open_temp_exec_file_opts_next (void) { @@ -750,15 +780,7 @@ open_temp_exec_file_opts_next (void) open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func (NULL); open_temp_exec_file_opts_idx++; - if (open_temp_exec_file_opts_idx - == (sizeof (open_temp_exec_file_opts) - / sizeof (*open_temp_exec_file_opts))) - { - open_temp_exec_file_opts_idx = 0; - return 1; - } - - return 0; + return open_temp_exec_file_opts_idx == OPEN_TEMP_EXEC_FILE_OPTS_COUNT; } /* Return a file descriptor of a temporary zero-sized file in a @@ -768,6 +790,9 @@ open_temp_exec_file (void) { int fd; + if (open_temp_exec_file_opts_idx == OPEN_TEMP_EXEC_FILE_OPTS_COUNT) + return -1; + do { fd = open_temp_exec_file_opts[open_temp_exec_file_opts_idx].func @@ -800,6 +825,8 @@ allocate_space (int fd, off_t len) /* Obtain system page size. */ if (!page_size) page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0) + return -1; unsigned char buf[page_size]; memset (buf, 0, page_size); @@ -849,6 +876,7 @@ dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset) if (!offset) { close (execfd); + execfd = -1; goto retry_open; } if (ftruncate (execfd, offset) != 0) @@ -861,6 +889,7 @@ dlmmap_locked (void *start, size_t length, int prot, int flags, off_t offset) return MFAIL; } else if (!offset + && open_temp_exec_file_opts_idx < OPEN_TEMP_EXEC_FILE_OPTS_COUNT && open_temp_exec_file_opts[open_temp_exec_file_opts_idx].repeat) open_temp_exec_file_opts_next (); diff --git a/deps/libffi/src/java_raw_api.c b/deps/libffi/src/java_raw_api.c index e0a02ef27432..455888a0e115 100644 --- a/deps/libffi/src/java_raw_api.c +++ b/deps/libffi/src/java_raw_api.c @@ -343,10 +343,14 @@ ffi_prep_java_raw_closure_loc (ffi_java_raw_closure* cl, { ffi_status status; + /* Pass the closure itself as user_data, not codeloc: with static + trampolines codeloc points into the read-only trampoline code table, + so ffi_java_translate_args would read cl->fun/cl->user_data from the + wrong memory and make a wild indirect call (GHSA-w6j9-w53f-2857). */ status = ffi_prep_closure_loc ((ffi_closure*) cl, cif, &ffi_java_translate_args, - codeloc, + cl, codeloc); if (status == FFI_OK) { diff --git a/deps/libffi/src/loongarch/ffi.c b/deps/libffi/src/loongarch/ffi.c index e81842b85192..ab0d929f81f5 100644 --- a/deps/libffi/src/loongarch/ffi.c +++ b/deps/libffi/src/loongarch/ffi.c @@ -92,6 +92,9 @@ typedef struct float_struct_info char type2; } float_struct_info; +#define IS_AGGREGATE(type) \ + ((type) == FFI_TYPE_STRUCT || (type) == FFI_TYPE_COMPLEX) + #if ABI_FRLEN >= 64 # define IS_FLOAT(type) ((type) >= FFI_TYPE_FLOAT && (type) <= FFI_TYPE_DOUBLE) #else @@ -105,7 +108,15 @@ flatten_struct (ffi_type *in, ffi_type **out, ffi_type **out_end) if (out == out_end) return out; - if (in->type != FFI_TYPE_STRUCT) + if (in->type == FFI_TYPE_COMPLEX) + { + /* The psABI passes a complex number like a struct of two reals. */ + *(out++) = in->elements[0]; + if (out == out_end) + return out; + *(out++) = in->elements[0]; + } + else if (in->type != FFI_TYPE_STRUCT) *(out++) = in; else for (i = 0; in->elements[i]; i++) @@ -113,9 +124,9 @@ flatten_struct (ffi_type *in, ffi_type **out, ffi_type **out_end) return out; } -/* Structs with at most two fields after flattening, one of which is of - floating point type, are passed in multiple registers if sufficient - registers are available. */ +/* Structs and complex numbers with at most two fields after flattening, + one of which is of floating point type, are passed in multiple registers + if sufficient registers are available. */ static float_struct_info struct_passed_as_elements (call_builder *cb, ffi_type *top) { @@ -278,7 +289,7 @@ marshal (call_builder *cb, ffi_type *type, int var, void *data) size_t realign[2]; #if ABI_FRLEN - if (!var && type->type == FFI_TYPE_STRUCT) + if (!var && IS_AGGREGATE (type->type)) { float_struct_info fsi = struct_passed_as_elements (cb, type); if (fsi.as_elements) @@ -347,7 +358,7 @@ unmarshal (call_builder *cb, ffi_type *type, int var, void *data) void *pointer; #if ABI_FRLEN - if (!var && type->type == FFI_TYPE_STRUCT) + if (!var && IS_AGGREGATE (type->type)) { float_struct_info fsi = struct_passed_as_elements (cb, type); if (fsi.as_elements) @@ -413,7 +424,7 @@ static int passed_by_ref (call_builder *cb, ffi_type *type, int var) { #if ABI_FRLEN - if (!var && type->type == FFI_TYPE_STRUCT) + if (!var && IS_AGGREGATE (type->type)) { float_struct_info fsi = struct_passed_as_elements (cb, type); if (fsi.as_elements) diff --git a/deps/libffi/src/loongarch/ffitarget.h b/deps/libffi/src/loongarch/ffitarget.h index 242b8f0ff256..c3d78764e444 100644 --- a/deps/libffi/src/loongarch/ffitarget.h +++ b/deps/libffi/src/loongarch/ffitarget.h @@ -83,6 +83,7 @@ typedef enum ffi_abi #endif /* LIBFFI_ASM */ #define FFI_TARGET_HAS_INT128 +#define FFI_TARGET_HAS_COMPLEX_TYPE /* ---- Definitions for closures ----------------------------------------- */ diff --git a/deps/libffi/src/metag/sysv.S b/deps/libffi/src/metag/sysv.S index b4b2a3b26bbf..f7d4bbe575d6 100644 --- a/deps/libffi/src/metag/sysv.S +++ b/deps/libffi/src/metag/sysv.S @@ -65,7 +65,7 @@ setl [A0StP++], D0Ar2, D1Ar1 .endm -! Save retrun, frame pointer and other regs +! Save return, frame pointer and other regs .macro SAVE_REGS regs= .text .balign 4 diff --git a/deps/libffi/src/mips/ffi.c b/deps/libffi/src/mips/ffi.c index 5c8c6bc5d447..dc5507926a43 100644 --- a/deps/libffi/src/mips/ffi.c +++ b/deps/libffi/src/mips/ffi.c @@ -402,7 +402,7 @@ static ffi_status ffi_prep_cif_machdep_int(ffi_cif *cif, unsigned nfixedargs) * does not have special handling for floating point args. */ - if (cif->rtype->type != FFI_TYPE_STRUCT && cif->rtype->type != FFI_TYPE_COMPLEX && cif->abi == FFI_O32) + if (cif->rtype->type != FFI_TYPE_STRUCT && cif->abi == FFI_O32) { if (cif->nargs > 0 && cif->nargs == nfixedargs) { @@ -455,6 +455,24 @@ static ffi_status ffi_prep_cif_machdep_int(ffi_cif *cif, unsigned nfixedargs) cif->flags += FFI_TYPE_UINT64 << (FFI_FLAG_BITS * 2); break; + case FFI_TYPE_COMPLEX: + /* Complex values are returned in GPRs like integer complex + values of the same size. */ + cif->flags += FFI_TYPE_COMPLEX << (FFI_FLAG_BITS * 2); + switch (cif->rtype->elements[0]->type) + { + case FFI_TYPE_FLOAT: + cif->flags += FFI_TYPE_UINT32 << (FFI_FLAG_BITS * 4); + break; + case FFI_TYPE_DOUBLE: + cif->flags += FFI_TYPE_UINT64 << (FFI_FLAG_BITS * 4); + break; + default: + cif->flags += cif->rtype->elements[0]->type << (FFI_FLAG_BITS * 4); + break; + } + break; + case FFI_TYPE_FLOAT: default: cif->flags += FFI_TYPE_INT << (FFI_FLAG_BITS * 2); @@ -798,6 +816,18 @@ void ffi_call_int(ffi_cif *cif, void (*fn)(void), void *rvalue, rvalue_copy = alloca(16); copy_rvalue = 1; } + else if (cif->rtype->type == FFI_TYPE_COMPLEX && cif->rtype->size < 16) + { + /* The assembly stores complex GPR returns in 8-byte chunks. + Bounce them through a suitably sized and aligned buffer so a + smaller user result cannot be overrun. */ + rvalue_copy = alloca (16); + copy_rvalue = 1; +#if defined(__MIPSEB__) || defined(_MIPSEB) + if (cif->rtype->size < 8) + copy_offset = 8 - cif->rtype->size; +#endif + } else if (cif->rtype->type == FFI_TYPE_FLOAT && (cif->abi == FFI_N64_SOFT_FLOAT || cif->abi == FFI_N32_SOFT_FLOAT)) @@ -978,11 +1008,19 @@ ffi_closure_mips_inner_O32 (ffi_cif *cif, argn = 1; seen_int = 1; } - if ((cif->flags >> (FFI_FLAG_BITS * 2)) == FFI_TYPE_COMPLEX) + if (cif->rtype->type == FFI_TYPE_COMPLEX + && (cif->rtype->elements[0]->type == FFI_TYPE_FLOAT + || cif->rtype->elements[0]->type == FFI_TYPE_DOUBLE + || cif->rtype->elements[0]->type == FFI_TYPE_LONGDOUBLE)) { rvalue = fpr; - argn = 1; } + /* With soft float, complex values are returned in up to four GPRs, + which does not fit into the space for v0 and v1. ffi_closure_O32 + does not use the space for the FP argument registers in that case, + so return the value there. */ + if (cif->abi == FFI_O32_SOFT_FLOAT && cif->rtype->type == FFI_TYPE_COMPLEX) + rvalue = fpr; i = 0; avn = cif->nargs; @@ -1041,6 +1079,15 @@ ffi_closure_mips_inner_O32 (ffi_cif *cif, /* Invoke the closure. */ fun(cif, rvalue, avaluep, user_data); + if (cif->rtype->type == FFI_TYPE_COMPLEX && cif->rtype->size == 2) + { + /* A _Complex char is returned right-justified in v0. */ + UINT16 value; + + memcpy (&value, rvalue, sizeof (value)); + *(UINT32 *) rvalue = value; + } + if (cif->abi == FFI_O32_SOFT_FLOAT) { switch (cif->rtype->type) @@ -1049,15 +1096,18 @@ ffi_closure_mips_inner_O32 (ffi_cif *cif, return FFI_TYPE_INT; case FFI_TYPE_DOUBLE: return FFI_TYPE_UINT64; + case FFI_TYPE_COMPLEX: + return (FFI_TYPE_COMPLEX + | (cif->rtype->size << (FFI_FLAG_BITS * 2))); default: return cif->rtype->type; } } else { - if (cif->rtype->type == FFI_TYPE_COMPLEX) { - __asm__ volatile ("move $v1, %0" : : "r"(cif->rtype->size)); - } + if (cif->rtype->type == FFI_TYPE_COMPLEX) + return (FFI_TYPE_COMPLEX + | (cif->rtype->size << (FFI_FLAG_BITS * 2))); return cif->rtype->type; } } @@ -1271,6 +1321,29 @@ ffi_closure_mips_inner_N32 (ffi_cif *cif, /* Invoke the closure. */ fun (cif, rvalue, avaluep, user_data); +#if defined(__MIPSEB__) || defined(_MIPSEB) + /* ffi_closure_N32 loads a 32-bit integer return value from the end of + an ffi_arg on big-endian. A float with soft float and a pointer on + N32 are returned the same way, but the closure stores them at the + start, so widen them. */ + if ((cif->rtype->type == FFI_TYPE_FLOAT && soft_float) +#if _MIPS_SIM == _ABIN32 + || cif->rtype->type == FFI_TYPE_POINTER +#endif + ) + *(ffi_arg *) rvalue = (SINT32) *(UINT32 *) rvalue; + + /* Complex values smaller than 8 bytes are returned right-justified in + v0, which ffi_closure_N32 loads as a whole. */ + if (cif->rtype->type == FFI_TYPE_COMPLEX && cif->rtype->size < 8) + { + size_t size = cif->rtype->size; + + memmove ((char *) rvalue + 8 - size, rvalue, size); + memset (rvalue, 0, 8 - size); + } +#endif + return cif->flags >> (FFI_FLAG_BITS * 8); } diff --git a/deps/libffi/src/mips/n32.S b/deps/libffi/src/mips/n32.S index 08cbb956667e..29612a493359 100644 --- a/deps/libffi/src/mips/n32.S +++ b/deps/libffi/src/mips/n32.S @@ -27,6 +27,7 @@ #define LIBFFI_ASM #include <fficonfig.h> #include <ffi.h> +#include <ffi_cfi.h> /* Only build this code if we are compiling for n32 */ @@ -56,6 +57,7 @@ .ent ffi_call_N32 ffi_call_N32: .LFB0: + cfi_startproc .frame $fp, SIZEOF_FRAME, ra .mask 0xc0000000,-FFI_SIZEOF_ARG .fmask 0x00000000,0 @@ -63,11 +65,15 @@ ffi_call_N32: # Prologue SUBU $sp, SIZEOF_FRAME # Frame size .LCFI00: + cfi_def_cfa_offset(SIZEOF_FRAME) REG_S $fp, SIZEOF_FRAME - 2*FFI_SIZEOF_ARG($sp) # Save frame pointer REG_S ra, SIZEOF_FRAME - 1*FFI_SIZEOF_ARG($sp) # Save return address .LCFI01: + cfi_offset($fp, -2*FFI_SIZEOF_ARG) + cfi_offset(ra, -1*FFI_SIZEOF_ARG) move $fp, $sp .LCFI02: + cfi_def_cfa_register($fp) move t9, callback # callback function pointer REG_S bytes, 2*FFI_SIZEOF_ARG($fp) # bytes REG_S flags, 3*FFI_SIZEOF_ARG($fp) # flags @@ -396,7 +402,7 @@ retstruct_f_f_soft: jal t9 REG_L t4, 4*FFI_SIZEOF_ARG($fp) sw v0, 0(t4) - sw v1, 4(t4) + sw a0, 4(t4) b epilogue retstruct_d_f_soft: @@ -404,7 +410,7 @@ retstruct_d_f_soft: jal t9 REG_L t4, 4*FFI_SIZEOF_ARG($fp) sd v0, 0(t4) - sw v1, 8(t4) + sw a0, 8(t4) b epilogue retstruct_f_d_soft: @@ -466,6 +472,7 @@ epilogue: j ra .LFE0: + cfi_endproc .end ffi_call_N32 /* ffi_closure_N32. Expects address of the passed-in ffi_closure in t0 @@ -521,6 +528,14 @@ epilogue: #define V1_OFF2 (3 * FFI_SIZEOF_ARG) #define V0_OFF2 (2 * FFI_SIZEOF_ARG) +/* Integer return values narrower than ffi_arg are stored widened to an + ffi_arg, so on big-endian their bytes are at its end. */ +#if defined(__MIPSEB__) || defined(_MIPSEB) +#define V0_OFF2_N(n) (V0_OFF2 + FFI_SIZEOF_ARG - (n)) +#else +#define V0_OFF2_N(n) V0_OFF2 +#endif + #define RA_OFF2 (1 * FFI_SIZEOF_ARG) #define GP_OFF2 (0 * FFI_SIZEOF_ARG) @@ -529,14 +544,18 @@ epilogue: .ent ffi_go_closure_N32 ffi_go_closure_N32: .LFB1: + cfi_startproc .frame $sp, SIZEOF_FRAME2, ra .mask 0x90000000,-(SIZEOF_FRAME2 - RA_OFF2) .fmask 0x00000000,0 SUBU $sp, SIZEOF_FRAME2 .LCFI10: + cfi_def_cfa_offset(SIZEOF_FRAME2) .cpsetup t9, GP_OFF2, ffi_go_closure_N32 REG_S ra, RA_OFF2($sp) # Save return address .LCFI11: + cfi_offset($gp, GP_OFF2 - SIZEOF_FRAME2) + cfi_offset(ra, RA_OFF2 - SIZEOF_FRAME2) REG_S a0, A0_OFF2($sp) REG_S a1, A1_OFF2($sp) @@ -562,6 +581,7 @@ ffi_go_closure_N32: b $do_closure .LFE1: + cfi_endproc .end ffi_go_closure_N32 .align 2 @@ -569,14 +589,18 @@ ffi_go_closure_N32: .ent ffi_closure_N32 ffi_closure_N32: .LFB2: + cfi_startproc .frame $sp, SIZEOF_FRAME2, ra .mask 0x90000000,-(SIZEOF_FRAME2 - RA_OFF2) .fmask 0x00000000,0 SUBU $sp, SIZEOF_FRAME2 .LCFI20: + cfi_def_cfa_offset(SIZEOF_FRAME2) .cpsetup t9, GP_OFF2, ffi_closure_N32 REG_S ra, RA_OFF2($sp) # Save return address .LCFI21: + cfi_offset($gp, GP_OFF2 - SIZEOF_FRAME2) + cfi_offset(ra, RA_OFF2 - SIZEOF_FRAME2) REG_S a0, A0_OFF2($sp) REG_S a1, A1_OFF2($sp) REG_S a2, A2_OFF2($sp) @@ -628,27 +652,27 @@ cls_retuint64: cls_retsint32: bne v0, FFI_TYPE_SINT32, cls_retsint16 - lw v0, V0_OFF2($sp) + lw v0, V0_OFF2_N(4)($sp) b cls_epilogue cls_retsint16: bne v0, FFI_TYPE_SINT16, cls_retuint16 - lh v0, V0_OFF2($sp) + lh v0, V0_OFF2_N(2)($sp) b cls_epilogue cls_retuint16: bne v0, FFI_TYPE_UINT16, cls_retsint8 - lhu v0, V0_OFF2($sp) + lhu v0, V0_OFF2_N(2)($sp) b cls_epilogue cls_retsint8: bne v0, FFI_TYPE_SINT8, cls_retuint8 - lb v0, V0_OFF2($sp) + lb v0, V0_OFF2_N(1)($sp) b cls_epilogue cls_retuint8: bne v0, FFI_TYPE_UINT8, cls_retfloat - lbu v0, V0_OFF2($sp) + lbu v0, V0_OFF2_N(1)($sp) b cls_epilogue cls_retfloat: @@ -703,18 +727,55 @@ cls_retstruct_d_f: b cls_epilogue cls_retstruct_f_d: - bne v0, FFI_TYPE_STRUCT_FD, cls_retcomplex_ld_ld + bne v0, FFI_TYPE_STRUCT_FD, cls_retstruct_f_soft l.s $f0, V0_OFF2($sp) l.d $f2, V1_OFF2($sp) b cls_epilogue #else cls_longdouble_soft: - bne v0, FFI_TYPE_LONGDOUBLE, cls_retcomplex_ld_ld + bne v0, FFI_TYPE_LONGDOUBLE, cls_retstruct_f_soft REG_L v0, V0_OFF2($sp) REG_L a0, V1_OFF2($sp) # not typo, it is a0, I have no idea, gcc does do it b cls_epilogue #endif + # With soft float, a struct of one or two floating-point fields is + # returned with the first field in v0 and the second in a0, each + # like a scalar of its type. +cls_retstruct_f_soft: + bne v0, FFI_TYPE_STRUCT_F_SOFT, cls_retstruct_d_soft + lw v0, V0_OFF2($sp) + b cls_epilogue + +cls_retstruct_d_soft: + bne v0, FFI_TYPE_STRUCT_D_SOFT, cls_retstruct_f_f_soft + ld v0, V0_OFF2($sp) + b cls_epilogue + +cls_retstruct_f_f_soft: + bne v0, FFI_TYPE_STRUCT_FF_SOFT, cls_retstruct_d_d_soft + lw v0, V0_OFF2($sp) + lw a0, (V0_OFF2+4)($sp) + b cls_epilogue + +cls_retstruct_d_d_soft: + bne v0, FFI_TYPE_STRUCT_DD_SOFT, cls_retstruct_f_d_soft + ld v0, V0_OFF2($sp) + ld a0, (V0_OFF2+8)($sp) + b cls_epilogue + +cls_retstruct_f_d_soft: + bne v0, FFI_TYPE_STRUCT_FD_SOFT, cls_retstruct_d_f_soft + lw v0, V0_OFF2($sp) + ld a0, (V0_OFF2+8)($sp) + b cls_epilogue + +cls_retstruct_d_f_soft: + bne v0, FFI_TYPE_STRUCT_DF_SOFT, cls_retcomplex_ld_ld + ld v0, V0_OFF2($sp) + lw a0, (V0_OFF2+8)($sp) + b cls_epilogue + cls_retcomplex_ld_ld: bne v0, FFI_TYPE_COMPLEX_LDLD, cls_retstruct_small2 REG_L t8, A0_OFF2($sp) @@ -739,9 +800,10 @@ cls_epilogue: ADDU $sp, SIZEOF_FRAME2 j ra .LFE2: + cfi_endproc .end ffi_closure_N32 -#ifdef __GNUC__ +#if defined(__GNUC__) && !defined(HAVE_AS_CFI_PSEUDO_OP) .section .eh_frame,EH_FRAME_FLAGS,@progbits .Lframe1: .4byte .LECIE1-.LSCIE1 # length @@ -818,7 +880,7 @@ cls_epilogue: .uleb128 (SIZEOF_FRAME2 - RA_OFF2)/4 .align EH_FRAME_ALIGN .LEFDE2: -#endif /* __GNUC__ */ +#endif /* __GNUC__ && !HAVE_AS_CFI_PSEUDO_OP */ #endif diff --git a/deps/libffi/src/mips/o32.S b/deps/libffi/src/mips/o32.S index 03ceed5dc452..5c884a959792 100644 --- a/deps/libffi/src/mips/o32.S +++ b/deps/libffi/src/mips/o32.S @@ -224,7 +224,24 @@ retcomplex: b epilogue 5: + # Integer complex values: a _Complex char is returned right-justified + # in v0, a _Complex short in v0, a _Complex int in v0/v1 and a + # _Complex long long in v0/v1/a0/a1. + slti t3, t1, FFI_TYPE_UINT16 + bnez t3, 6f + slti t3, t1, FFI_TYPE_UINT32 + bnez t3, 7f REG_S v1, 4(t0) + REG_S v0, 0(t0) + slti t3, t1, FFI_TYPE_UINT64 + bnez t3, epilogue + REG_S a1, 12(t0) + REG_S a0, 8(t0) + b epilogue +6: + sh v0, 0(t0) + b epilogue +7: REG_S v0, 0(t0) b epilogue @@ -408,11 +425,13 @@ $do_closure: # Load the return value into the appropriate register. move $8, $2 + SRL $3, $8, (FFI_FLAG_BITS * 2) + and $8, ((1 << (FFI_FLAG_BITS * 2)) - 1) li $9, FFI_TYPE_VOID beq $8, $9, closure_done li $13, 1 # FFI_O32 - bne $16, $13, 1f # Skip fp restore if FFI_O32_SOFT_FLOAT + bne $16, $13, 2f # Skip fp restore if FFI_O32_SOFT_FLOAT #ifndef __mips_soft_float li $9, FFI_TYPE_FLOAT @@ -427,15 +446,31 @@ $do_closure: bne $8, $9, 1f li $9, 8 - l.s $f0, V0_OFF2($fp) - l.s $f2, V1_OFF2($fp) + REG_L $2, FA_0_0_OFF2($fp) + mtc1 $2, $f0 + REG_L $2, FA_0_1_OFF2($fp) + mtc1 $2, $f2 beq $3, $9, closure_done li $9, 16 - l.d $f0, V0_OFF2($fp) - l.d $f2, (V0_OFF2+8)($fp) + l.d $f0, FA_0_0_OFF2($fp) + l.d $f2, FA_1_0_OFF2($fp) beq $3, $9, closure_done #endif + b 1f + +2: + # FFI_O32_SOFT_FLOAT returns complex values in up to four GPRs. + # ffi_closure_mips_inner_O32 stored them in the space for the + # FP argument registers. + li $9, FFI_TYPE_COMPLEX + bne $8, $9, 1f + REG_L $2, FA_0_0_OFF2($fp) + REG_L $3, FA_0_1_OFF2($fp) + REG_L $4, FA_1_0_OFF2($fp) + REG_L $5, FA_1_1_OFF2($fp) + b closure_done + 1: REG_L $3, V1_OFF2($fp) REG_L $2, V0_OFF2($fp) diff --git a/deps/libffi/src/powerpc/ffi.c b/deps/libffi/src/powerpc/ffi.c index 69725242344c..37c99bc1261d 100644 --- a/deps/libffi/src/powerpc/ffi.c +++ b/deps/libffi/src/powerpc/ffi.c @@ -114,7 +114,7 @@ ffi_call_int (ffi_cif *cif, if (rvalue && ecif.rvalue == smst_buffer) { unsigned int rsize = cif->rtype->size; -#ifdef FFI_TARGET_HAS_COMPLEX_TYPE +#if defined (FFI_TARGET_HAS_COMPLEX_TYPE) && defined (POWERPC64) /* Integer-typed _Complex: the .Lsmall_struct return path stored r3 at buffer offset 0 and r4 at offset 8. Extract one inner- sized half from each slot — right-justified on BE, low-address diff --git a/deps/libffi/src/powerpc/ffi_linux64.c b/deps/libffi/src/powerpc/ffi_linux64.c index e92f88c46973..c0ca42cab9af 100644 --- a/deps/libffi/src/powerpc/ffi_linux64.c +++ b/deps/libffi/src/powerpc/ffi_linux64.c @@ -61,6 +61,17 @@ ffi_prep_types_linux64 (ffi_abi abi) ffi_type_longdouble.size = 16; ffi_type_longdouble.alignment = 16; } +#ifdef FFI_TARGET_HAS_COMPLEX_TYPE + /* _Complex long double is two halves of whatever long double just became. + Its size comes from sizeof(_Complex long double) at build time, which is + only right for the ABI libffi itself was built for, so keep it in step. + Leaving it behind makes the type disagree with its own element: a caller + that asks for the other long double width would get a return value copied + at cif->rtype->size (wrong by 16 bytes either way) and structs containing + the type laid out to the build-time size. */ + ffi_type_complex_longdouble.size = 2 * ffi_type_longdouble.size; + ffi_type_complex_longdouble.alignment = ffi_type_longdouble.alignment; +#endif } #endif @@ -393,6 +404,12 @@ ffi_prep_cif_linux64_core (ffi_cif *cif) under ELFv2, and is what differentiates _Complex from a same-sized struct{T;T;} which uses fewer GPR shadow slots. */ elt = (*ptr)->elements[0]->type; +#if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* A 64-bit long double is passed exactly like a double. */ + if (elt == FFI_TYPE_LONGDOUBLE + && (cif->abi & FFI_LINUX_LONG_DOUBLE_128) == 0) + elt = FFI_TYPE_DOUBLE; +#endif switch (elt) { case FFI_TYPE_FLOAT: @@ -776,6 +793,10 @@ ffi_prep_args64 (extended_cif *ecif, unsigned long *const stack) case FFI_TYPE_COMPLEX: elt = (*ptr)->elements[0]->type; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* A 64-bit long double is passed exactly like a double. */ + if (elt == FFI_TYPE_LONGDOUBLE + && (ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_128) == 0) + elt = FFI_TYPE_DOUBLE; if (elt == FFI_TYPE_LONGDOUBLE && (ecif->cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) { @@ -1398,6 +1419,10 @@ ffi_closure_helper_LINUX64 (ffi_cif *cif, unsigned int j; elt = arg_types[i]->elements[0]->type; #if FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE + /* A 64-bit long double arrives exactly like a double. */ + if (elt == FFI_TYPE_LONGDOUBLE + && (cif->abi & FFI_LINUX_LONG_DOUBLE_128) == 0) + elt = FFI_TYPE_DOUBLE; if (elt == FFI_TYPE_LONGDOUBLE && (cif->abi & FFI_LINUX_LONG_DOUBLE_IEEE128) != 0) { @@ -1624,13 +1649,13 @@ ffi_closure_helper_LINUX64 (ffi_cif *cif, case 0: return PPC_LD_NONE; case 1: - return PPC_LD_U8; + return PPC64_LD_STRUCT_1; case 2: - return PPC_LD_U16; + return PPC64_LD_STRUCT_2; case 3: return PPC64_LD_STRUCT_3; case 4: - return PPC_LD_U32; + return PPC64_LD_STRUCT_4; case 5: return PPC64_LD_STRUCT_5; case 6: diff --git a/deps/libffi/src/powerpc/ffi_powerpc.h b/deps/libffi/src/powerpc/ffi_powerpc.h index bad33efe3b8c..8147c3a91dbe 100644 --- a/deps/libffi/src/powerpc/ffi_powerpc.h +++ b/deps/libffi/src/powerpc/ffi_powerpc.h @@ -54,17 +54,24 @@ /* Needed for soft-float long-double. */ #define PPC32_LD_R3R6 10 +/* Needed for _Complex long double with a 128-bit long double. */ +#define PPC32_LD_R3R10 11 + /* Needed for FFI_SYSV small structure returns. */ #ifdef __LITTLE_ENDIAN__ #define PPC32_SYSV_LD_STRUCT_3 PPC32_LD_R3 #define PPC32_SYSV_LD_STRUCT_5 PPC32_LD_R3R4 #define PPC32_SYSV_LD_STRUCT_6 PPC32_LD_R3R4 #define PPC32_SYSV_LD_STRUCT_7 PPC32_LD_R3R4 +#define PPC32_SYSV_LD_STRUCT_1 PPC_LD_U8 +#define PPC32_SYSV_LD_STRUCT_2 PPC_LD_U16 #else -#define PPC32_SYSV_LD_STRUCT_3 11 -#define PPC32_SYSV_LD_STRUCT_5 12 -#define PPC32_SYSV_LD_STRUCT_6 13 -#define PPC32_SYSV_LD_STRUCT_7 14 +#define PPC32_SYSV_LD_STRUCT_3 12 +#define PPC32_SYSV_LD_STRUCT_5 13 +#define PPC32_SYSV_LD_STRUCT_6 14 +#define PPC32_SYSV_LD_STRUCT_7 15 +#define PPC32_SYSV_LD_STRUCT_1 16 +#define PPC32_SYSV_LD_STRUCT_2 17 #endif #else /* POWERPC64 */ @@ -84,11 +91,17 @@ #define PPC64_LD_STRUCT_5 PPC_LD_I64 #define PPC64_LD_STRUCT_6 PPC_LD_I64 #define PPC64_LD_STRUCT_7 PPC_LD_I64 +#define PPC64_LD_STRUCT_1 PPC_LD_U8 +#define PPC64_LD_STRUCT_2 PPC_LD_U16 +#define PPC64_LD_STRUCT_4 PPC_LD_U32 #else #define PPC64_LD_STRUCT_3 16 #define PPC64_LD_STRUCT_5 17 #define PPC64_LD_STRUCT_6 18 #define PPC64_LD_STRUCT_7 19 +#define PPC64_LD_STRUCT_1 20 +#define PPC64_LD_STRUCT_2 21 +#define PPC64_LD_STRUCT_4 22 #endif #endif /* POWERPC64 */ @@ -106,6 +119,7 @@ enum { /* These go in cr6 */ FLAG_RETURNS_64BITS = 1 << (31-27), FLAG_RETURNS_128BITS = 1 << (31-26), + FLAG_RETURNS_256BITS = 1 << (31-25), /* Used by sysv code */ FLAG_COMPAT = 1 << (31- 8), /* Not used by assembly */ diff --git a/deps/libffi/src/powerpc/ffi_sysv.c b/deps/libffi/src/powerpc/ffi_sysv.c index a33039e3dbdb..d9f0fdde6d4b 100644 --- a/deps/libffi/src/powerpc/ffi_sysv.c +++ b/deps/libffi/src/powerpc/ffi_sysv.c @@ -42,6 +42,10 @@ #define NUM_GPR_ARG_REGISTERS 8 #define NUM_FPR_ARG_REGISTERS 8 +/* Internal type for an eight-word complex value, i.e. _Complex long double + with a 128-bit long double. */ +#define FFI_TYPE_UINT256 (FFI_TYPE_LAST + 1) + #if HAVE_LONG_DOUBLE_VARIANT && FFI_TYPE_LONGDOUBLE != FFI_TYPE_DOUBLE /* Adjust size of ffi_type_longdouble. */ @@ -58,6 +62,12 @@ ffi_prep_types_sysv (ffi_abi abi) ffi_type_longdouble.size = 16; ffi_type_longdouble.alignment = 16; } +#ifdef FFI_TARGET_HAS_COMPLEX_TYPE + /* _Complex long double is two halves of whatever long double just + became, so keep its size and alignment in step. */ + ffi_type_complex_longdouble.size = 2 * ffi_type_longdouble.size; + ffi_type_complex_longdouble.alignment = ffi_type_longdouble.alignment; +#endif } #endif @@ -89,6 +99,39 @@ translate_float (int abi, int type) return type; } +/* Transform a type to the type that is passed and returned the same way. + Complex values always go in GPRs, never in FPRs, even with hard float: + GCC does not split them for this ABI but passes each one as a single + item of as many words as it needs, just like an integer of that size. */ +static int +translate_type (int abi, const ffi_type *t) +{ + if (t->type != FFI_TYPE_COMPLEX) + return translate_float (abi, t->type); + + switch (t->size) + { + case 2: + /* _Complex char. */ + return FFI_TYPE_UINT16; + case 4: + /* _Complex short. */ + return FFI_TYPE_UINT32; + case 8: + /* float and int _Complex: two words, like long long. */ + return FFI_TYPE_UINT64; + case 16: + /* double, long long and 64-bit long double _Complex. */ + return FFI_TYPE_UINT128; + case 32: + /* 128-bit long double _Complex. */ + return FFI_TYPE_UINT256; + default: + FFI_ASSERT (0); + return FFI_TYPE_STRUCT; + } +} + /* Perform machine dependent cif processing */ static ffi_status ffi_prep_cif_sysv_core (ffi_cif *cif) @@ -121,7 +164,7 @@ ffi_prep_cif_sysv_core (ffi_cif *cif) - long doubles (if not equivalent to double) are returned in fpr1,fpr2 for Linux and as for large structs for SysV. */ - type = translate_float (cif->abi, type); + type = translate_type (cif->abi, cif->rtype); switch (type) { @@ -140,6 +183,9 @@ ffi_prep_cif_sysv_core (ffi_cif *cif) #endif break; + case FFI_TYPE_UINT256: + flags |= FLAG_RETURNS_256BITS; + /* Fall through. */ case FFI_TYPE_UINT128: flags |= FLAG_RETURNS_128BITS; /* Fall through. */ @@ -148,6 +194,13 @@ ffi_prep_cif_sysv_core (ffi_cif *cif) flags |= FLAG_RETURNS_64BITS; break; + case FFI_TYPE_UINT16: + /* A _Complex char is returned right-justified in r3, like a small + struct. Use the small struct bounce buffer to extract it. */ + if (cif->rtype->type == FFI_TYPE_COMPLEX) + flags |= FLAG_RETURNS_SMST; + break; + case FFI_TYPE_STRUCT: /* The final SYSV ABI says that structures smaller or equal 8 bytes are returned in r3/r4. A draft ABI used by linux instead @@ -176,9 +229,8 @@ ffi_prep_cif_sysv_core (ffi_cif *cif) Stuff on the stack needs to keep proper alignment. */ for (ptr = cif->arg_types, i = cif->nargs; i > 0; i--, ptr++) { - unsigned short typenum = (*ptr)->type; - - typenum = translate_float (cif->abi, typenum); + unsigned short typenum = translate_type (cif->abi, *ptr); + unsigned nwords; switch (typenum) { @@ -224,16 +276,19 @@ ffi_prep_cif_sysv_core (ffi_cif *cif) #endif break; + case FFI_TYPE_UINT256: case FFI_TYPE_UINT128: /* A long double in FFI_LINUX_SOFT_FLOAT can use only a set of four consecutive gprs. If we do not have enough, we - have to adjust the gpr_count value. */ - if (gpr_count >= NUM_GPR_ARG_REGISTERS - 3) + have to adjust the gpr_count value. Complex values of four + or eight words are passed the same way. */ + nwords = typenum == FFI_TYPE_UINT256 ? 8 : 4; + if (gpr_count > NUM_GPR_ARG_REGISTERS - nwords) gpr_count = NUM_GPR_ARG_REGISTERS; if (gpr_count >= NUM_GPR_ARG_REGISTERS) - stack_count += 4; + stack_count += nwords; else - gpr_count += 4; + gpr_count += nwords; break; case FFI_TYPE_UINT64: @@ -458,9 +513,8 @@ ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack) i > 0; i--, ptr++, p_argv.v++) { - unsigned int typenum = (*ptr)->type; - - typenum = translate_float (ecif->cif->abi, typenum); + unsigned int typenum = translate_type (ecif->cif->abi, *ptr); + unsigned int ii, nwords; /* Now test the translated value */ switch (typenum) @@ -518,16 +572,18 @@ ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack) break; #endif /* have FPRs */ + case FFI_TYPE_UINT256: case FFI_TYPE_UINT128: /* The soft float ABI for long doubles works like this, a long double is passed in four consecutive GPRs if available. A maximum of 2 long doubles can be passed in gprs. If we do not have 4 GPRs - left, the long double is passed on the stack, 4-byte aligned. */ - if (gpr_base.u >= gpr_end.u - 3) + left, the long double is passed on the stack, 4-byte aligned. + Complex values of four or eight words are passed the same way. */ + nwords = typenum == FFI_TYPE_UINT256 ? 8 : 4; + if (gpr_base.u > gpr_end.u - nwords) { - unsigned int ii; gpr_base.u = gpr_end.u; - for (ii = 0; ii < 4; ii++) + for (ii = 0; ii < nwords; ii++) { unsigned int int_tmp = (*p_argv.ui)[ii]; *next_arg.u++ = int_tmp; @@ -535,8 +591,7 @@ ffi_prep_args_SYSV (extended_cif *ecif, unsigned *const stack) } else { - unsigned int ii; - for (ii = 0; ii < 4; ii++) + for (ii = 0; ii < nwords; ii++) { unsigned int int_tmp = (*p_argv.ui)[ii]; *gpr_base.u++ = int_tmp; @@ -709,7 +764,7 @@ ffi_closure_helper_SYSV (ffi_cif *cif, avalue = alloca (cif->nargs * sizeof (void *)); /* First translate for softfloat/nonlinux */ - rtypenum = translate_float (cif->abi, rtypenum); + rtypenum = translate_type (cif->abi, cif->rtype); /* Copy the caller's structure return value address so that the closure returns the data directly to the caller. @@ -729,10 +784,9 @@ ffi_closure_helper_SYSV (ffi_cif *cif, /* Grab the addresses of the arguments from the stack frame. */ while (i < avn) { - unsigned short typenum = arg_types[i]->type; - /* We may need to handle some values depending on ABI. */ - typenum = translate_float (cif->abi, typenum); + unsigned short typenum = translate_type (cif->abi, arg_types[i]); + long nwords; switch (typenum) { @@ -796,20 +850,23 @@ ffi_closure_helper_SYSV (ffi_cif *cif, # endif #endif + case FFI_TYPE_UINT256: case FFI_TYPE_UINT128: /* Test if for the whole long double, 4 gprs are available. - otherwise the stuff ends up on the stack. */ - if (ng < NUM_GPR_ARG_REGISTERS - 3) + otherwise the stuff ends up on the stack. The same holds + for complex values of four or eight words. */ + nwords = typenum == FFI_TYPE_UINT256 ? 8 : 4; + if (ng <= NUM_GPR_ARG_REGISTERS - nwords) { avalue[i] = pgr; - pgr += 4; - ng += 4; + pgr += nwords; + ng += nwords; } else { avalue[i] = pst; - pst += 4; - ng = 8+4; + pst += nwords; + ng = NUM_GPR_ARG_REGISTERS; } break; @@ -940,6 +997,18 @@ ffi_closure_helper_SYSV (ffi_cif *cif, case FFI_TYPE_SINT8: return PPC_LD_S8; case FFI_TYPE_UINT16: + if (cif->rtype->type == FFI_TYPE_COMPLEX) + { + /* A _Complex char is returned right-justified in r3. */ + unsigned int word = 0; +#ifdef __LITTLE_ENDIAN__ + memcpy (&word, rvalue, 2); +#else + memcpy ((char *) &word + 2, rvalue, 2); +#endif + *(unsigned int *) rvalue = word; + return PPC_LD_U32; + } return PPC_LD_U16; case FFI_TYPE_SINT16: return PPC_LD_S16; @@ -955,14 +1024,16 @@ ffi_closure_helper_SYSV (ffi_cif *cif, return PPC_LD_I64; case FFI_TYPE_UINT128: return PPC32_LD_R3R6; + case FFI_TYPE_UINT256: + return PPC32_LD_R3R10; case FFI_TYPE_STRUCT: if (cif->abi & FFI_SYSV_STRUCT_RET) switch (size) { case 1: - return PPC_LD_U8; + return PPC32_SYSV_LD_STRUCT_1; case 2: - return PPC_LD_U16; + return PPC32_SYSV_LD_STRUCT_2; case 3: return PPC32_SYSV_LD_STRUCT_3; case 4: diff --git a/deps/libffi/src/powerpc/ffitarget.h b/deps/libffi/src/powerpc/ffitarget.h index 7ffe36b682e4..ad65fa16aa04 100644 --- a/deps/libffi/src/powerpc/ffitarget.h +++ b/deps/libffi/src/powerpc/ffitarget.h @@ -155,8 +155,15 @@ typedef enum ffi_abi { ELFv2, float/double _Complex are passed and returned as a 2-element homogeneous floating-point aggregate, but each scalar half consumes a GPR shadow slot of its own — i.e. the same way the underlying C ABI - handles them, which is what GCC's split_complex_arg emits. */ -#if defined(POWERPC64) && _CALL_ELF == 2 + handles them, which is what GCC's split_complex_arg emits. + + They are also supported on 32-bit SYSV, where complex values are passed + and returned in GPRs like integers of the same size. */ +#if defined(POWERPC64) +# if _CALL_ELF == 2 +# define FFI_TARGET_HAS_COMPLEX_TYPE +# endif +#elif defined (POWERPC) || defined (POWERPC_FREEBSD) # define FFI_TARGET_HAS_COMPLEX_TYPE #endif diff --git a/deps/libffi/src/powerpc/linux64_closure.S b/deps/libffi/src/powerpc/linux64_closure.S index 3071bec0d22a..62de845bf673 100644 --- a/deps/libffi/src/powerpc/linux64_closure.S +++ b/deps/libffi/src/powerpc/linux64_closure.S @@ -342,8 +342,8 @@ E PPC64_LD_DOUBLE_HOMOG #ifndef __LITTLE_ENDIAN__ E PPC64_LD_STRUCT_3 - lwz %r3, RETVAL+4(%r1) - srd %r3, %r3, 8 + ld %r3, RETVAL+0(%r1) + srdi %r3, %r3, 40 epilogue E PPC64_LD_STRUCT_5 @@ -360,6 +360,21 @@ E PPC64_LD_STRUCT_7 ld %r3, RETVAL+0(%r1) srdi %r3, %r3, 8 epilogue + +E PPC64_LD_STRUCT_1 + ld %r3, RETVAL+0(%r1) + srdi %r3, %r3, 56 + epilogue + +E PPC64_LD_STRUCT_2 + ld %r3, RETVAL+0(%r1) + srdi %r3, %r3, 48 + epilogue + +E PPC64_LD_STRUCT_4 + ld %r3, RETVAL+0(%r1) + srdi %r3, %r3, 32 + epilogue #endif .Lmoredouble: diff --git a/deps/libffi/src/powerpc/ppc_closure.S b/deps/libffi/src/powerpc/ppc_closure.S index 92949b164f56..ad31fb6fde09 100644 --- a/deps/libffi/src/powerpc/ppc_closure.S +++ b/deps/libffi/src/powerpc/ppc_closure.S @@ -202,10 +202,17 @@ E PPC_LD_S16 epilogue E PPC32_LD_R3R6 +.Lr3r6: lwz %r5,112+8(%r1) lwz %r6,112+12(%r1) b .Lr3r4 +E PPC32_LD_R3R10 + lwz %r7,112+16(%r1) + lwz %r8,112+20(%r1) + lwz %r9,112+24(%r1) + b .Lr3r10 + #ifndef __LITTLE_ENDIAN__ E PPC32_SYSV_LD_STRUCT_3 lwz %r3,112+0(%r1) @@ -228,7 +235,15 @@ E PPC32_SYSV_LD_STRUCT_7 lwz %r3,112+0(%r1) lwz %r4,112+4(%r1) li %r5,8 - nop + b .Lstruct567 + +E PPC32_SYSV_LD_STRUCT_1 + lbz %r3,112+0(%r1) + epilogue + +E PPC32_SYSV_LD_STRUCT_2 + lhz %r3,112+0(%r1) + epilogue .Lstruct567: subfic %r6,%r5,32 @@ -239,6 +254,10 @@ E PPC32_SYSV_LD_STRUCT_7 epilogue #endif +.Lr3r10: + lwz %r10,112+28(%r1) + b .Lr3r6 + .cfi_endproc END(ffi_closure_SYSV) diff --git a/deps/libffi/src/powerpc/sysv.S b/deps/libffi/src/powerpc/sysv.S index df9773427cba..b569f1ec8be1 100644 --- a/deps/libffi/src/powerpc/sysv.S +++ b/deps/libffi/src/powerpc/sysv.S @@ -116,6 +116,11 @@ ENTRY(ffi_call_SYSV) bf 26,L(done_return_value) stw %r5,8(%r30) stw %r6,12(%r30) + bf 25,L(done_return_value) + stw %r7,16(%r30) + stw %r8,20(%r30) + stw %r9,24(%r30) + stw %r10,28(%r30) /* Fall through... */ L(done_return_value): diff --git a/deps/libffi/src/raw_api.c b/deps/libffi/src/raw_api.c index 670d56d948a3..2194a8962d42 100644 --- a/deps/libffi/src/raw_api.c +++ b/deps/libffi/src/raw_api.c @@ -232,10 +232,15 @@ ffi_prep_raw_closure_loc (ffi_raw_closure* cl, { ffi_status status; + /* Pass the closure itself as the user_data that ffi_translate_args + receives, not codeloc. The two aliased before static trampolines, but + with FFI_EXEC_STATIC_TRAMP codeloc points into the read-only trampoline + code table, so reading cl->fun/cl->user_data through it would load + garbage and make a wild indirect call (GHSA-w6j9-w53f-2857). */ status = ffi_prep_closure_loc ((ffi_closure*) cl, cif, &ffi_translate_args, - codeloc, + cl, codeloc); if (status == FFI_OK) { diff --git a/deps/libffi/src/riscv/ffi.c b/deps/libffi/src/riscv/ffi.c index 5aca74665a5c..53c41db60a66 100644 --- a/deps/libffi/src/riscv/ffi.c +++ b/deps/libffi/src/riscv/ffi.c @@ -84,6 +84,8 @@ typedef struct { char as_elements, type1, offset2, type2; } float_struct_info; +#define IS_AGGREGATE(type) ((type) == FFI_TYPE_STRUCT || (type) == FFI_TYPE_COMPLEX) + #if ABI_FLEN >= 64 #define IS_FLOAT(type) ((type) >= FFI_TYPE_FLOAT && (type) <= FFI_TYPE_DOUBLE) #else @@ -93,7 +95,12 @@ typedef struct { static ffi_type **flatten_struct(ffi_type *in, ffi_type **out, ffi_type **out_end) { int i; if (out == out_end) return out; - if (in->type != FFI_TYPE_STRUCT) { + if (in->type == FFI_TYPE_COMPLEX) { + /* the psABI passes a complex number like a struct of two reals */ + *(out++) = in->elements[0]; + if (out == out_end) return out; + *(out++) = in->elements[0]; + } else if (in->type != FFI_TYPE_STRUCT) { *(out++) = in; } else { for (i = 0; in->elements[i]; i++) @@ -102,9 +109,9 @@ static ffi_type **flatten_struct(ffi_type *in, ffi_type **out, ffi_type **out_en return out; } -/* Structs with at most two fields after flattening, one of which is of - floating point type, are passed in multiple registers if sufficient - registers are available. */ +/* Structs and complex numbers with at most two fields after flattening, + one of which is of floating point type, are passed in multiple registers + if sufficient registers are available. */ static float_struct_info struct_passed_as_elements(call_builder *cb, ffi_type *top) { float_struct_info ret = {0, 0, 0, 0}; ffi_type *fields[3]; @@ -247,7 +254,7 @@ static void marshal(call_builder *cb, ffi_type *type, int var, void *data) { size_t realign[2]; #if ABI_FLEN - if (!var && type->type == FFI_TYPE_STRUCT) { + if (!var && IS_AGGREGATE(type->type)) { float_struct_info fsi = struct_passed_as_elements(cb, type); if (fsi.as_elements) { marshal_atom(cb, fsi.type1, data); @@ -295,7 +302,7 @@ static void *unmarshal(call_builder *cb, ffi_type *type, int var, void *data) { void *pointer; #if ABI_FLEN - if (!var && type->type == FFI_TYPE_STRUCT) { + if (!var && IS_AGGREGATE(type->type)) { float_struct_info fsi = struct_passed_as_elements(cb, type); if (fsi.as_elements) { unmarshal_atom(cb, fsi.type1, data); @@ -340,7 +347,7 @@ static void *unmarshal(call_builder *cb, ffi_type *type, int var, void *data) { static int passed_by_ref(call_builder *cb, ffi_type *type, int var) { #if ABI_FLEN - if (!var && type->type == FFI_TYPE_STRUCT) { + if (!var && IS_AGGREGATE(type->type)) { float_struct_info fsi = struct_passed_as_elements(cb, type); if (fsi.as_elements) return 0; } @@ -414,7 +421,7 @@ ffi_call_int (ffi_cif *cif, void (*fn) (void), void *rvalue, void **avalue, ffi_call_asm ((void *) alloc_base, cb.aregs, fn, closure); cb.used_float = cb.used_integer = 0; - if (!return_by_ref && rvalue) + if (!return_by_ref && rvalue && cif->rtype->type != FFI_TYPE_VOID) { if (IS_INT(cif->rtype->type) && cif->rtype->size < sizeof (ffi_arg)) diff --git a/deps/libffi/src/riscv/ffitarget.h b/deps/libffi/src/riscv/ffitarget.h index 06010027bd48..8e4d65bf97d0 100644 --- a/deps/libffi/src/riscv/ffitarget.h +++ b/deps/libffi/src/riscv/ffitarget.h @@ -65,6 +65,7 @@ typedef enum ffi_abi { #define FFI_EXTRA_CIF_FIELDS unsigned riscv_nfixedargs; unsigned riscv_unused #define FFI_TARGET_SPECIFIC_VARIADIC #define FFI_TARGET_HAS_INT128 +#define FFI_TARGET_HAS_COMPLEX_TYPE #endif diff --git a/deps/libffi/src/s390/ffi.c b/deps/libffi/src/s390/ffi.c index 7ec2a877ce43..d9b6d0c9dcaa 100644 --- a/deps/libffi/src/s390/ffi.c +++ b/deps/libffi/src/s390/ffi.c @@ -546,9 +546,16 @@ ffi_closure_helper_SYSV (ffi_cif *cif, #endif /* Check how a structure type is passed. */ - if (type == FFI_TYPE_STRUCT || type == FFI_TYPE_COMPLEX) + if (type == FFI_TYPE_STRUCT || type == FFI_TYPE_COMPLEX + || type == FFI_TYPE_SINT128 || type == FFI_TYPE_UINT128) { - if (type == FFI_TYPE_COMPLEX) + if (type == FFI_TYPE_COMPLEX + || type == FFI_TYPE_SINT128 || type == FFI_TYPE_UINT128) + /* Complex and 128-bit integer types are passed by reference: one + GPR slot holds a pointer to the value. The call side already + does this; without it here the closure left avalue[] for such + an argument uninitialised and shifted every later argument + (GHSA-wf8m-qr3x-cch4). */ type = FFI_TYPE_POINTER; else type = ffi_check_struct_type (*ptr); diff --git a/deps/libffi/src/sparc/ffi64.c b/deps/libffi/src/sparc/ffi64.c index 5eec1499e170..80cad6604606 100644 --- a/deps/libffi/src/sparc/ffi64.c +++ b/deps/libffi/src/sparc/ffi64.c @@ -135,12 +135,18 @@ ffi_struct_float_merge (int size_mask, void *vi, void *vf) /* Similar, but place the data into VD in the end. */ void FFI_HIDDEN -ffi_struct_float_copy (int size_mask, void *vd, void *vi, void *vf) +ffi_struct_float_copy (int flags, void *vd, void *vi, void *vf) { + int size_mask = flags >> SPARC_SIZEMASK_SHIFT; int size = size_mask & 0xff; int mask = size_mask >> 8; int n = size >> 2; + if (flags & SP_V9_FLAG_RET_COMPLEX_SMALL) + { + FFI_ASSERT (mask == 0 && size < 8); + vi = (char *) vi + 8 - size; + } if (mask == 0) ; else if (mask == (1 << n) - 1) @@ -199,6 +205,9 @@ ffi_prep_cif_machdep_core(ffi_cif *cif) flags = (size_mask << SPARC_SIZEMASK_SHIFT) | SPARC_RET_STRUCT; + if (rtt == FFI_TYPE_COMPLEX && rtype->size < 8 && fp_mask == 0) + flags |= SP_V9_FLAG_RET_COMPLEX_SMALL; + /* For special cases of all-int or all-fp, we can return the value directly without popping through a struct copy. */ if (fp_mask == 0) @@ -398,8 +407,17 @@ ffi_prep_args_v9(ffi_cif *cif, unsigned long *argp, void *rvalue, void **avalue) *argp++ = *(UINT64 *)a; break; - case FFI_TYPE_LONGDOUBLE: case FFI_TYPE_COMPLEX: + z = ty->size; + if (z < 8) + { + *argp = 0; + memcpy ((char *) argp + 8 - z, a, z); + argp++; + break; + } + /* FALLTHRU */ + case FFI_TYPE_LONGDOUBLE: case FFI_TYPE_STRUCT: z = ty->size; if (z > 16) @@ -573,6 +591,11 @@ ffi_closure_sparc_inner_v9(ffi_cif *cif, case FFI_TYPE_COMPLEX: case FFI_TYPE_STRUCT: z = ty->size; + if (ty->type == FFI_TYPE_COMPLEX && z < 8) + { + a = (char *) a + 8 - z; + break; + } if (z > 16) a = *(void **)a; else diff --git a/deps/libffi/src/sparc/internal.h b/deps/libffi/src/sparc/internal.h index 0a66472bade8..5cac3332c008 100644 --- a/deps/libffi/src/sparc/internal.h +++ b/deps/libffi/src/sparc/internal.h @@ -22,5 +22,6 @@ #define SPARC_FLAG_RET_MASK 15 #define SPARC_FLAG_RET_IN_MEM 32 #define SPARC_FLAG_FP_ARGS 64 +#define SP_V9_FLAG_RET_COMPLEX_SMALL 128 /* v9 only */ #define SPARC_SIZEMASK_SHIFT 8 diff --git a/deps/libffi/src/sparc/v9.S b/deps/libffi/src/sparc/v9.S index 55f8f4324cfe..dee17df48ef0 100644 --- a/deps/libffi/src/sparc/v9.S +++ b/deps/libffi/src/sparc/v9.S @@ -186,7 +186,7 @@ E(SPARC_RET_F_1) std %f6, [%l2+56] ! Copy the structure into place. - srl %l0, SPARC_SIZEMASK_SHIFT, %o0 ! load size_mask + mov %l0, %o0 ! load flags and size_mask mov %i2, %o1 ! load dst mov %l2, %o2 ! load src_gp call C(ffi_struct_float_copy) @@ -270,6 +270,7 @@ C(ffi_closure_v9): add %fp, STACK_BIAS+128, %o4 call C(ffi_closure_sparc_inner_v9) add %fp, STACK_BIAS-128, %o5 + mov %o0, %l0 ! preserve full return flags 0: call 1f ! load pc in %o7 and %o0, SPARC_FLAG_RET_MASK, %o0 @@ -287,10 +288,10 @@ E(SPARC_RET_VOID) return %i7+8 nop E(SPARC_RET_STRUCT) - ldx [FP-160], %i0 - ldd [FP-160], %f0 - b 8f - ldx [FP-152], %i1 + b .Lclosure_ret_struct + nop + nop + nop E(SPARC_RET_UINT8) ldub [FP-160+7], %i0 return %i7+8 @@ -354,6 +355,31 @@ E(SPARC_RET_F_1) nop ! Finish the SPARC_RET_STRUCT sequence. + ! Small integer complex values are scalar-like in the v9 ABI and + ! occupy the low end of %i0, unlike small structures. + .align 8 +.Lclosure_ret_struct: + andcc %l0, SP_V9_FLAG_RET_COMPLEX_SMALL, %g0 + bne,pn %xcc, .Lclosure_ret_complex_small + srl %l0, SPARC_SIZEMASK_SHIFT, %l1 + ldx [FP-160], %i0 + ldd [FP-160], %f0 + b 8f + ldx [FP-152], %i1 + +.Lclosure_ret_complex_small: + and %l1, 0xff, %l1 + cmp %l1, 2 + be,pn %xcc, .Lclosure_ret_complex_2 + nop + lduw [FP-160], %i0 + return %i7+8 + nop +.Lclosure_ret_complex_2: + lduh [FP-160], %i0 + return %i7+8 + nop + .align 8 8: ldd [FP-152], %f2 ldx [FP-144], %i2 diff --git a/deps/libffi/src/tramp.c b/deps/libffi/src/tramp.c index a04188858af6..5b2b2cfd36ba 100644 --- a/deps/libffi/src/tramp.c +++ b/deps/libffi/src/tramp.c @@ -44,12 +44,14 @@ #include <ffi_common.h> #include <stdio.h> +#include <string.h> #include <unistd.h> #include <stdlib.h> #include <stdint.h> #include <fcntl.h> #include <pthread.h> #include <sys/mman.h> +#include <sys/stat.h> #include <tramp.h> #ifdef __linux__ #include <linux/limits.h> @@ -209,13 +211,14 @@ static int ffi_tramp_get_libffi (void) { FILE *fp; - /* `file' is sized PATH_MAX+1 so a scanf field width of PATH_MAX - (which permits PATH_MAX characters plus the terminating NUL) cannot - overflow. */ + /* `line' holds one /proc/<pid>/maps line; its path field can be up to + PATH_MAX bytes. `file' holds the /proc/<pid>/maps path opened first. */ char file[PATH_MAX+1], line[PATH_MAX+100], perm[10], dev[10]; unsigned long start, end, offset, inode; uintptr_t addr = (uintptr_t) tramp_globals.text; - int nfields, found; + int nfields, found, path_off; + char *path = NULL, *nl; + struct stat st; int open_flags = O_RDONLY; #ifdef O_CLOEXEC @@ -228,33 +231,64 @@ ffi_tramp_get_libffi (void) return 0; found = 0; + inode = 0; while (feof (fp) == 0) { if (fgets (line, sizeof (line), fp) == 0) break; - /* Bound the path field width so a long mapping name cannot overflow - the fixed-size `file' buffer. */ - nfields = sscanf (line, - "%lx-%lx %9s %lx %9s %ld %" FFI_TRAMP_STR(PATH_MAX) "s", - &start, &end, perm, &offset, dev, &inode, file); - if (nfields != 7) + /* + * Parse the six fixed fields and record where the path begins with %n. + * The path is taken as the rest of the line rather than with a "%s" + * field because the kernel does not escape spaces in the maps name + * field, so "%s" would truncate a path that contains a space and libffi + * could open and map the wrong file (GHSA-fq46-69xf-x5gf). + */ + path_off = 0; + nfields = sscanf (line, "%lx-%lx %9s %lx %9s %lu %n", + &start, &end, perm, &offset, dev, &inode, &path_off); + if (nfields != 6 || path_off == 0) continue; if (addr >= start && addr < end) { tramp_globals.offset = offset + (addr - start); + path = line + path_off; found = 1; break; } } fclose (fp); - if (!found) + if (!found || path == NULL || *path == '\0' || *path == '\n') return 0; - tramp_globals.fd = open (file, open_flags); + /* Drop the trailing newline so the path can be opened. */ + nl = strchr (path, '\n'); + if (nl != NULL) + *nl = '\0'; + + tramp_globals.fd = open (path, open_flags); if (tramp_globals.fd == -1) return 0; + /* + * Verify that the file just opened is the file that backs the mapping we + * selected, by comparing its inode with the one from the maps line. + * Without this the path could have been replaced, or be a symlink to + * another file, between reading the maps line and the open, letting an + * attacker substitute the bytes libffi maps as executable trampoline code + * (GHSA-fq46-69xf-x5gf). Only the inode is compared: the device number in + * /proc/<pid>/maps does not match stat(2)'s st_dev on btrfs, overlayfs and + * some other filesystems, so comparing st_dev would reject the real file + * there. On any mismatch, fall back to the temp-file trampoline. + */ + if (fstat (tramp_globals.fd, &st) != 0 + || (unsigned long) st.st_ino != inode) + { + close (tramp_globals.fd); + tramp_globals.fd = -1; + return 0; + } + /* * Allocate a trampoline table just to make sure that the trampoline code * table can be mapped. diff --git a/deps/libffi/src/wasm/ffi.c b/deps/libffi/src/wasm/ffi.c index b631b1b2bef9..1da9d418f83c 100644 --- a/deps/libffi/src/wasm/ffi.c +++ b/deps/libffi/src/wasm/ffi.c @@ -42,18 +42,18 @@ #define EM_JS_MACROS(ret, name, args, body...) EM_JS(ret, name, args, body) -EM_JS_DEPS(libffi, "$getWasmTableEntry,$setWasmTableEntry,$getEmptyTableSlot,$convertJsFunctionToWasm"); +EM_JS_DEPS(libffi, "$getWasmTableEntry,$setWasmTableEntry,$getEmptyTableSlot,$wasmTable,$stackSave,$stackAlloc,$stackRestore"); #define DEREF_U8(addr, offset) HEAPU8[addr + offset] #define DEREF_S8(addr, offset) HEAP8[addr + offset] -#define DEREF_U16(addr, offset) HEAPU16[(addr >> 1) + offset] -#define DEREF_S16(addr, offset) HEAP16[(addr >> 1) + offset] -#define DEREF_U32(addr, offset) HEAPU32[(addr >> 2) + offset] -#define DEREF_S32(addr, offset) HEAP32[(addr >> 2) + offset] +#define DEREF_U16(addr, offset) HEAPU16[HEAP_INDEX_16(addr) + offset] +#define DEREF_S16(addr, offset) HEAP16[HEAP_INDEX_16(addr) + offset] +#define DEREF_U32(addr, offset) HEAPU32[HEAP_INDEX_32(addr) + offset] +#define DEREF_S32(addr, offset) HEAP32[HEAP_INDEX_32(addr) + offset] -#define DEREF_F32(addr, offset) HEAPF32[(addr >> 2) + offset] -#define DEREF_F64(addr, offset) HEAPF64[(addr >> 3) + offset] -#define DEREF_U64(addr, offset) HEAPU64[(addr >> 3) + offset] +#define DEREF_F32(addr, offset) HEAPF32[HEAP_INDEX_32(addr) + offset] +#define DEREF_F64(addr, offset) HEAPF64[HEAP_INDEX_64(addr) + offset] +#define DEREF_U64(addr, offset) HEAPU64[HEAP_INDEX_64(addr) + offset] #define CHECK_FIELD_OFFSET(struct, field, offset) \ _Static_assert( \ @@ -64,10 +64,17 @@ EM_JS_DEPS(libffi, "$getWasmTableEntry,$setWasmTableEntry,$getEmptyTableSlot,$co #define FFI_EMSCRIPTEN_ABI FFI_WASM32_EMSCRIPTEN #define PTR_SIG 'i' +#define PTR_WASM_TYPE 0x7f #define DEC_PTR(p) p #define ENC_PTR(p) p +// Pointers reach JS as signed 32-bit Numbers, so an address at or above 2 GiB +// is negative and needs an unsigned shift to become a heap view index. +#define HEAP_INDEX_16(addr) ((addr) >>> 1) +#define HEAP_INDEX_32(addr) ((addr) >>> 2) +#define HEAP_INDEX_64(addr) ((addr) >>> 3) + #define DEREF_PTR(addr, offset) DEREF_U32(addr, offset) #define DEREF_PTR_NUMBER(addr, offset) DEREF_PTR(addr, offset) @@ -106,14 +113,21 @@ CHECK_FIELD_OFFSET(ffi_type, elements, 8); #define FFI_EMSCRIPTEN_ABI FFI_WASM64_EMSCRIPTEN #define PTR_SIG 'j' +#define PTR_WASM_TYPE 0x7e -// DEC_PTR casts a pointer value (comming from Wasm) represented as BigInt (i64) to Number (i53). +// DEC_PTR casts a pointer value (coming from Wasm) represented as BigInt (i64) to Number (i53). // This should be used for a pointer that is expected to be within the i53 range. If the pointer // value is outside the Number's range, the value will become NaN. #define DEC_PTR(p) bigintToI53Checked(p) // ENC_PTR casts a pointer value represented as Number to BigInt (i64) #define ENC_PTR(p) BigInt(p) +// JS shifts truncate their operand to 32 bits, so divide to keep addresses +// at or above 4 GiB intact. +#define HEAP_INDEX_16(addr) ((addr) / 2) +#define HEAP_INDEX_32(addr) ((addr) / 4) +#define HEAP_INDEX_64(addr) ((addr) / 8) + #define DEREF_PTR(addr, offset) DEREF_U64(addr, offset) #define DEREF_PTR_NUMBER(addr, offset) DEC_PTR(DEREF_PTR(addr, offset)) @@ -590,6 +604,34 @@ ffi_closure_free(void *closure) { return ffi_closure_free_js(closure); } + + +/** + * A closure has to appear to its caller as an ordinary wasm function with the + * signature of the cif. In order for it to work with JSPI, the trampoline has + * to be implemented in WebAssembly -- otherwise attempting to suspend inside of + * the closure will trap with "trying to suspend JS frames". + * + * It's a bit annoying to do things in generated WebAssembly so we put most of + * the logic in JS prelude/epilogue. + * + * call prelude(... all closure arguments) + * call_indirect closure->fun(cif, ret_ptr, args_ptr, user_data) + * call epilogue(ret_ptr, orig_stack_ptr) + * + * prelude() which copies the closure arguments into the appropriate places on + * the C stack, builds the argument pointer array, and returns 7 values: The + * closure->fun pointer and its four arguments, and the two arguments for epilogue. + + * epilogue() is a JavaScript helper that restores the stack pointer and loads + * the return value from ret_ptr. Doing the load in JavaScript rather than in + * the trampoline avoids needing to specify the memory size in the imports + * section. + * + * The module bytes are a pure function of the signature string. We cache the + * compiled WebAssembly.Module per signature and instantiate it once per closure + * with that closure's prelude. + */ EM_JS_MACROS( ffi_status, ffi_prep_closure_loc_js, @@ -600,6 +642,35 @@ ffi_prep_closure_loc_js, fun = DEC_PTR(fun); user_data = DEC_PTR(user_data); codeloc = DEC_PTR(codeloc); + var { sig, call_info } = ffi_cif_to_call_info(cif); + + LOG_DEBUG("CREATE_CLOSURE", "sig:", sig); + try { + var instance = new WebAssembly.Instance( + ffi_closure_trampoline_module(sig), + { + e: { + p: ffi_closure_prelude(closure, call_info), + e: ffi_closure_epilogue(sig), + t: wasmTable, + }, + }, + ); + } catch (e) { + LOG_DEBUG("CREATE_CLOSURE_FAILED", e); + return FFI_BAD_TYPEDEF_MACRO; + } + var wasm_trampoline = instance.exports["f"]; + setWasmTableEntry(codeloc, wasm_trampoline); + CLOSURE__cif(closure) = ENC_PTR(cif); + CLOSURE__fun(closure) = ENC_PTR(fun); + CLOSURE__user_data(closure) = ENC_PTR(user_data); + return FFI_OK_MACRO; +} + +// Walk the CIF and compute the metadata we need for ffi_closure_prelude +// and ffi_closure_trampoline_module. +function ffi_cif_to_call_info(cif) { var abi = CIF__ABI(cif); var nargs = CIF__NARGS(cif); var nfixedargs = CIF__NFIXEDARGS(cif); @@ -696,10 +767,33 @@ ffi_prep_closure_loc_js, // extra pointer to varargs stack sig += PTR_SIG; } - LOG_DEBUG("CREATE_CLOSURE", "sig:", sig); - function trampoline() { - var args = Array.prototype.slice.call(arguments); - var size = 0; + return { + sig, + call_info: { + nfixedargs, + nargs, + ret_by_arg, + unboxed_arg_type_info_list, + unboxed_arg_type_id_list, + }, + }; +} + +// The prelude() function is called by the wasm trampoline with the closure's +// arguments. It marshals them onto the C stack and returns what the trampoline +// needs to make the onward call. +function ffi_closure_prelude( + closure, + { + nfixedargs, + nargs, + ret_by_arg, + unboxed_arg_type_info_list, + unboxed_arg_type_id_list, + }, +) { + return function prelude() { + var args = arguments; var orig_stack_ptr = stackSave(); var cur_ptr = orig_stack_ptr; var ret_ptr; @@ -707,7 +801,7 @@ ffi_prep_closure_loc_js, // Should we return by argument or not? The onwards call returns by argument // no matter what. (Warning: ret_by_arg means the opposite in ffi_call) if (ret_by_arg) { - ret_ptr = args[jsarg_idx++]; + ret_ptr = DEC_PTR(args[jsarg_idx++]); } else { // We might return 4 bytes or 8 bytes, allocate 8 just in case. STACK_ALLOC(cur_ptr, 8, 8); @@ -817,37 +911,138 @@ ffi_prep_closure_loc_js, stackRestore(cur_ptr); stackAlloc(0); // stackAlloc enforces alignment invariants on the stack pointer LOG_DEBUG("CALL_CLOSURE", "closure:", closure, "fptr", CLOSURE__fun(closure), "cif", CLOSURE__cif(closure)); - getWasmTableEntry(CLOSURE__fun(closure))( - CLOSURE__cif(closure), ENC_PTR(ret_ptr), ENC_PTR(args_ptr), - CLOSURE__user_data(closure) - ); - stackRestore(orig_stack_ptr); - - // If we aren't supposed to return by argument, figure out what to return. - if (!ret_by_arg) { - switch (sig[0]) { - case 'i': - return DEREF_U32(ret_ptr, 0); - case 'j': - return DEREF_U64(ret_ptr, 0); - case 'd': - return DEREF_F64(ret_ptr, 0); - case 'f': - return DEREF_F32(ret_ptr, 0); + // The trampoline now does + // fun(cif, ret_ptr, args_ptr, user_data); + // return epilogue(ret_ptr, orig_stack_ptr); + // + // We return these arguments in reverse order because stack is LIFO. + return [ + ENC_PTR(ret_ptr), // epilogue args (in correct order) + ENC_PTR(orig_stack_ptr), + + CLOSURE__cif(closure), // call_indirect args (in correct order) + ENC_PTR(ret_ptr), + ENC_PTR(args_ptr), + CLOSURE__user_data(closure), + + CLOSURE__fun(closure), // ...and the table index for call_indirect + ]; + } +} + +// Returns function which restores the stack pointer and loads the closure's +// return value from ret_ptr. +function ffi_closure_epilogue(sig) { + var load; + switch (sig[0]) { + case 'i': load = (ptr) => DEREF_S32(ptr, 0); break; + case 'j': load = (ptr) => DEREF_U64(ptr, 0); break; + case 'f': load = (ptr) => DEREF_F32(ptr, 0); break; + case 'd': load = (ptr) => DEREF_F64(ptr, 0); break; + default: load = (ptr) => undefined; break; + } + return function epilogue(ret_ptr, orig_stack_ptr) { + stackRestore(DEC_PTR(orig_stack_ptr)); + return load(DEC_PTR(ret_ptr)); + }; +} + +var ffi_closure_trampoline_module_cache = new Map(); +function ffi_closure_trampoline_module(sig) { + var cache = ffi_closure_trampoline_module_cache; + var module = cache.get(sig); + if (module) { + return module; + } + + function uleb128(n) { + var result = []; + do { + var byte = n & 0x7f; + n >>>= 7; + if (n) { + byte |= 0x80; } - } + result.push(byte); + } while (n); + return result; } - try { - var wasm_trampoline = convertJsFunctionToWasm(trampoline, sig); - } catch(e) { - return FFI_BAD_TYPEDEF_MACRO; + // A vector of single-byte items + function vec(bytes) { + return [...uleb128(bytes.length), ...bytes]; } - setWasmTableEntry(codeloc, wasm_trampoline); - CLOSURE__cif(closure) = ENC_PTR(cif); - CLOSURE__fun(closure) = ENC_PTR(fun); - CLOSURE__user_data(closure) = ENC_PTR(user_data); - return FFI_OK_MACRO; -}) + function section(id, bytes) { + return [id, ...vec(bytes)]; + } + function funcType(params, results) { + return [0x60, ...vec(params), ...vec(results)]; + } + + var typeCodes = { 'i': 0x7f, 'j': 0x7e, 'f': 0x7d, 'd': 0x7c }; + var P = PTR_WASM_TYPE; + var params = Array.from(sig.slice(1), (c) => typeCodes[c]); + var results = sig[0] === 'v' ? [] : [typeCodes[sig[0]]]; + var nparams = params.length; + + // Is the function table 64-bit indexed? + // -sMEMORY64=2 compiles with 64-bit pointers but uses a 32-bit memory and + // table, so we have to i32.wrap_i64 pointers. + var idx64 = typeof wasmTable.length === 'bigint'; + var idxFlag = idx64 ? 0x04 : 0x00; + // Pointers are wrapped to i32 to be used as a table index. + var wrapPtr = (P === 0x7e && !idx64) ? [0xa7] : []; // i32.wrap_i64 + + var typeSection = section(0x01, [ + ...uleb128(4), + ...funcType(params, results), // type 0: the trampoline itself + ...funcType(params, [P, P, P, P, P, P, P]), // type 1: prelude + ...funcType([P, P, P, P], []), // type 2: closure->fun(cif, ret, args, user_data) + ...funcType([P, P], results), // type 3: epilogue(ret_ptr, orig_sp) + ]); + var importSection = section(0x02, [ + ...uleb128(3), + // prelude: (import "e" "p" (func (type 1))) + 0x01, 0x65, 0x01, 0x70, 0x00, 0x01, + // epilogue: (import "e" "e" (func (type 3))) + 0x01, 0x65, 0x01, 0x65, 0x00, 0x03, + // (import "e" "t" (table 0 funcref)) + 0x01, 0x65, 0x01, 0x74, 0x01, 0x70, 0x00 | idxFlag, 0x00, + ]); + // One function, of type 0. + var functionSection = section(0x03, [0x01, 0x00]); + // (export "f" (func 2)) -- funcs 0 and 1 are the imports. + var exportSection = section(0x07, [0x01, 0x01, 0x66, 0x00, 0x02]); + + // Function body + var body = [0x00]; // no locals + for (var i = 0; i < nparams; i++) { + body.push(0x20, ...uleb128(i)); // local.get i + } + body.push(0x10, 0x00); // call prelude + // Operand stack is now: ret_ptr, orig_sp, cif, ret_ptr, args_ptr, user_data, fun + body.push(...wrapPtr); // fun is used as a table index + body.push(0x11, 0x02, 0x00); // call_indirect (type 2) (table 0), consumes the top 5 + // Operand stack: ret_ptr, orig_sp + body.push(0x10, 0x01); // call epilogue, consumes both and leaves the result (if any) + body.push(0x0b); // end + var codeSection = section(0x0a, [...uleb128(1), ...vec(body)]); + + var bytes = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, // magic + 0x01, 0x00, 0x00, 0x00, // version + ...typeSection, + ...importSection, + ...functionSection, + ...exportSection, + ...codeSection, + ]); + LOG_DEBUG("CLOSURE_MODULE", "sig:", sig, "bytes:", bytes); + // The module is tiny so compiling synchronously is fine. + module = new WebAssembly.Module(bytes); + cache.set(sig, module); + return module; +} +) // EM_JS does not correctly handle function pointer arguments, so we need a // helper diff --git a/deps/libffi/src/x86/ffi.c b/deps/libffi/src/x86/ffi.c index a953891362d5..f2beecf53989 100644 --- a/deps/libffi/src/x86/ffi.c +++ b/deps/libffi/src/x86/ffi.c @@ -348,7 +348,7 @@ ffi_call_int (ffi_cif *cif, void (*fn)(void), void *rvalue, size_t z = ty->size; int t = ty->type; - if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT) + if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT && t != FFI_TYPE_COMPLEX) { ffi_arg val = extend_basic_type (valp, t); @@ -495,7 +495,7 @@ ffi_closure_inner (struct closure_frame *frame, char *stack) int t = ty->type; void *valp; - if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT) + if (z <= FFI_SIZEOF_ARG && t != FFI_TYPE_STRUCT && t != FFI_TYPE_COMPLEX) { if (t != FFI_TYPE_FLOAT && narg_reg < pabi->nregs) valp = &frame->regs[pabi->regs[narg_reg++]]; @@ -681,6 +681,10 @@ ffi_prep_go_closure (ffi_go_closure* closure, ffi_cif* cif, void FFI_HIDDEN ffi_closure_raw_SYSV(void); void FFI_HIDDEN ffi_closure_raw_THISCALL(void); +#if defined(FFI_EXEC_STATIC_TRAMP) +void FFI_HIDDEN ffi_closure_raw_SYSV_alt(void); +void FFI_HIDDEN ffi_closure_raw_THISCALL_alt(void); +#endif ffi_status ffi_prep_raw_closure_loc (ffi_raw_closure *closure, @@ -717,6 +721,24 @@ ffi_prep_raw_closure_loc (ffi_raw_closure *closure, return FFI_BAD_ABI; } +#if defined(FFI_EXEC_STATIC_TRAMP) + if (ffi_tramp_is_present (closure)) + { + /* With a static trampoline, set its parameters instead of writing a + dynamic trampoline into closure->tramp. The _alt entry loads the + closure pointer the trampoline passes into %eax, where + ffi_closure_raw_* expect it. Writing the dynamic trampoline here + would instead clobber the ftramp pointer ffi_closure_alloc stored at + offset 0 and leave the static trampoline with no parameters + (GHSA-w6j9-w53f-2857). ftramp is read through ffi_closure, exactly + as ffi_closure_alloc/ffi_closure_free do. */ + dest = (dest == ffi_closure_raw_SYSV) + ? ffi_closure_raw_SYSV_alt : ffi_closure_raw_THISCALL_alt; + ffi_tramp_set_parms (((ffi_closure *) closure)->ftramp, dest, closure); + goto out; + } +#endif + /* movl imm, %eax. */ tramp[0] = 0xb8; *(void **)(tramp + 1) = codeloc; @@ -725,6 +747,9 @@ ffi_prep_raw_closure_loc (ffi_raw_closure *closure, tramp[5] = 0xe9; *(unsigned *)(tramp + 6) = (unsigned)dest - ((unsigned)codeloc + 10); +#if defined(FFI_EXEC_STATIC_TRAMP) +out: +#endif closure->cif = cif; closure->fun = fun; closure->user_data = user_data; diff --git a/deps/libffi/src/x86/ffi64.c b/deps/libffi/src/x86/ffi64.c index c2c78f3fbbfb..6bb2b9639c77 100644 --- a/deps/libffi/src/x86/ffi64.c +++ b/deps/libffi/src/x86/ffi64.c @@ -442,6 +442,41 @@ examine_argument (ffi_type *type, enum x86_64_reg_class classes[MAX_CLASSES], return n; } +/* Recursively test whether TY is, or contains, a short vector whose x86-64 + System V calling convention is undefined, so that libffi must refuse it + rather than marshal it the wrong way. + + The psABI only defines the convention for vectors that map to __m64/__m128 + (8 and 16 bytes). Narrower vectors (<1 x float>, <4 x uint8>, ...) are + unspecified, and GCC and Clang disagree on them. Among the 8-byte vectors + the two also disagree on the single-element <1 x double>: GCC returns and + passes it in memory, Clang in %xmm0. libffi cannot tell which convention + the target function was compiled for, so it accepts only the shapes both + compilers agree on and this port implements: 16-byte vectors, and 8-byte + vectors other than <1 x double>. Everything else is FFI_BAD_TYPEDEF. */ + +static int +vector_type_unsupported (ffi_type *ty) +{ + ffi_type **p; + + if (ty == NULL) + return 0; + if (ty->type == FFI_TYPE_VECTOR) + { + if (ty->size == 16) + return 0; + if (ty->size == 8 && ty->elements[0]->type != FFI_TYPE_DOUBLE) + return 0; + return 1; + } + if (ty->type == FFI_TYPE_STRUCT && ty->elements != NULL) + for (p = ty->elements; *p != NULL; p++) + if (vector_type_unsupported (*p)) + return 1; + return 0; +} + /* Perform machine dependent cif processing. */ #ifndef __ILP32__ @@ -469,6 +504,18 @@ ffi_prep_cif_machdep (ffi_cif *cif) rtype = cif->rtype; rtype_size = rtype->size; + + /* Reject return and argument types that are, or contain, a vector whose + x86-64 System V convention is undefined (see vector_type_unsupported). + Doing it here, before any classification, keeps libffi from silently + marshalling such a value the wrong way -- which for <1 x double> turns a + caller's integer argument into the store address of the result. */ + if (vector_type_unsupported (rtype)) + return FFI_BAD_TYPEDEF; + for (i = 0, avn = cif->nargs; i < avn; i++) + if (vector_type_unsupported (cif->arg_types[i])) + return FFI_BAD_TYPEDEF; + switch (rtype->type) { case FFI_TYPE_VOID: @@ -533,7 +580,9 @@ ffi_prep_cif_machdep (ffi_cif *cif) { _Bool sse0 = SSE_CLASS_P (classes[0]); - if (rtype_size == 4 && sse0) + if (classes[0] == X86_64_X87_CLASS) + flags = UNIX64_RET_X87; + else if (rtype_size == 4 && sse0) flags = UNIX64_RET_XMM32; else if (rtype_size == 8) flags = sse0 ? UNIX64_RET_XMM64 : UNIX64_RET_INT64; @@ -553,8 +602,9 @@ ffi_prep_cif_machdep (ffi_cif *cif) } break; case FFI_TYPE_VECTOR: - /* An 8-byte vector returns in the low half of %xmm0; a 16-byte vector - fills %xmm0 (SSE + SSEUP). Wider vectors are unsupported here. */ + /* Only supported vectors reach here (vector_type_unsupported rejected + the rest above): an 8-byte vector returns in the low half of %xmm0, + a 16-byte vector fills %xmm0 (SSE + SSEUP). */ if (rtype_size == 8) flags = UNIX64_RET_XMM64; else if (rtype_size == 16) @@ -606,15 +656,6 @@ ffi_prep_cif_machdep (ffi_cif *cif) return FFI_BAD_TYPEDEF; } - /* Reject vectors wider than 16 bytes as arguments: correct %ymm/%zmm - passing needs unix64.S register-save changes that are out of scope for - this port, and classify_argument would otherwise silently treat them as - an in-memory aggregate. */ - for (i = 0, avn = cif->nargs; i < avn; i++) - if (cif->arg_types[i]->type == FFI_TYPE_VECTOR - && cif->arg_types[i]->size > 16) - return FFI_BAD_TYPEDEF; - /* Go over all arguments and determine the way they should be passed. If it's in a register and there is space for it, let that be so. If not, add it's size to the stack byte count. */ @@ -934,8 +975,14 @@ build_plan (ffi_cif *cif) switch (classes[j]) { case X86_64_NO_CLASS: - case X86_64_SSEUP_CLASS: continue; /* nothing placed for this 8-byte */ + case X86_64_SSEUP_CLASS: + /* Upper half of the preceding SSE class's %xmm slot. */ + m.dst_off = (unsigned) (offsetof (struct register_args, sse) + + (ssecount - 1) + * sizeof (union big_int_union) + 8); + m.op = FFI_MOVE_SSE64; + break; case X86_64_INTEGER_CLASS: case X86_64_INTEGERSI_CLASS: m.dst_off = gprcount * 8; /* offsetof(register_args,gpr) == 0 */ diff --git a/deps/libffi/src/x86/sysv.S b/deps/libffi/src/x86/sysv.S index dac841421d9b..b6070f0151c0 100644 --- a/deps/libffi/src/x86/sysv.S +++ b/deps/libffi/src/x86/sysv.S @@ -351,7 +351,7 @@ L(UW13): FFI_CLOSURE_SAVE_REGS FFI_CLOSURE_COPY_TRAMP_DATA - /* Entry point from preceeding Go closures. */ + /* Entry point from preceding Go closures. */ L(do_closure_i386): FFI_CLOSURE_PREP_CALL @@ -486,7 +486,7 @@ L(do_closure_REGISTER): FFI_CLOSURE_COPY_TRAMP_DATA - /* Entry point from preceeding Go closure. */ + /* Entry point from preceding Go closure. */ L(do_closure_STDCALL): FFI_CLOSURE_PREP_CALL @@ -883,6 +883,32 @@ L(UW52): /* cfi_endproc */ ENDF(C(ffi_closure_raw_THISCALL)) +#if defined(FFI_EXEC_STATIC_TRAMP) +/* Static-trampoline entry points for the raw closures. The static + trampoline leaves the closure pointer at 4(%esp); load it into %eax + (where ffi_closure_raw_* expect it), restore the stack, and jump to the + normal body. Mirrors ffi_closure_i386_alt. */ + .balign 16 + .globl C(ffi_closure_raw_SYSV_alt) + FFI_HIDDEN(C(ffi_closure_raw_SYSV_alt)) +C(ffi_closure_raw_SYSV_alt): + _CET_ENDBR + movl 4(%esp), %eax /* Load closure in eax */ + add $8, %esp /* Restore the stack */ + jmp C(ffi_closure_raw_SYSV) +ENDF(C(ffi_closure_raw_SYSV_alt)) + + .balign 16 + .globl C(ffi_closure_raw_THISCALL_alt) + FFI_HIDDEN(C(ffi_closure_raw_THISCALL_alt)) +C(ffi_closure_raw_THISCALL_alt): + _CET_ENDBR + movl 4(%esp), %eax /* Load closure in eax */ + add $8, %esp /* Restore the stack */ + jmp C(ffi_closure_raw_THISCALL) +ENDF(C(ffi_closure_raw_THISCALL_alt)) +#endif /* FFI_EXEC_STATIC_TRAMP */ + #endif /* !FFI_NO_RAW_API */ #ifdef X86_DARWIN diff --git a/deps/libffi/src/x86/sysv_intel.S b/deps/libffi/src/x86/sysv_intel.S index c7de159916ac..7de706a90d2e 100644 --- a/deps/libffi/src/x86/sysv_intel.S +++ b/deps/libffi/src/x86/sysv_intel.S @@ -291,7 +291,7 @@ L(UW13): FFI_CLOSURE_SAVE_REGS FFI_CLOSURE_COPY_TRAMP_DATA - /* Entry point from preceeding Go closures. */ + /* Entry point from preceding Go closures. */ L(do_closure_i386):: FFI_CLOSURE_PREP_CALL @@ -420,7 +420,7 @@ L(do_closure_REGISTER):: FFI_CLOSURE_COPY_TRAMP_DATA - /* Entry point from preceeding Go closure. */ + /* Entry point from preceding Go closure. */ L(do_closure_STDCALL):: FFI_CLOSURE_PREP_CALL diff --git a/deps/libffi/src/x86/unix64.S b/deps/libffi/src/x86/unix64.S index 61983ef3bcf5..6520f815cb8f 100644 --- a/deps/libffi/src/x86/unix64.S +++ b/deps/libffi/src/x86/unix64.S @@ -31,6 +31,7 @@ #define LIBFFI_ASM #include <fficonfig.h> #include <ffi.h> +#include <ffi_cfi.h> #include "internal64.h" #include "asmnames.h" @@ -256,7 +257,7 @@ ENDF(C(ffi_call_unix64)) .globl C(ffi_plan_fast_call) FFI_HIDDEN(C(ffi_plan_fast_call)) C(ffi_plan_fast_call): - .cfi_startproc + cfi_startproc _CET_ENDBR movq %rsi, %r11 /* fn */ movq %rdi, %rax /* img */ @@ -280,12 +281,12 @@ C(ffi_plan_fast_call): movq 0x28(%rax), %r9 movl %r10d, %eax /* %al = ssecount */ subq $8, %rsp /* realign to 16 across the call */ - .cfi_adjust_cfa_offset 8 + cfi_adjust_cfa_offset(8) call *%r11 addq $8, %rsp - .cfi_adjust_cfa_offset -8 + cfi_adjust_cfa_offset(-8) ret /* rax + xmm0 carry the callee's return */ - .cfi_endproc + cfi_endproc ENDF(C(ffi_plan_fast_call)) /* Count-based direct thunks for the pure-GP64 fast path: load avalue[0..N-1] @@ -297,7 +298,7 @@ C(ffi_plan_fast_call): rax/xmm0 flow out as the {UINT64,double} return; C stores per return code. */ #define FFI_GP_HEAD \ - .cfi_startproc; \ + cfi_startproc; \ _CET_ENDBR; \ movq %rsi, %r11; \ movq %rdi, %rax @@ -307,12 +308,12 @@ C(ffi_plan_fast_call): #define FFI_GP_TAIL \ xorl %eax, %eax; \ subq $8, %rsp; \ - .cfi_adjust_cfa_offset 8; \ + cfi_adjust_cfa_offset(8); \ call *%r11; \ addq $8, %rsp; \ - .cfi_adjust_cfa_offset -8; \ + cfi_adjust_cfa_offset(-8); \ ret; \ - .cfi_endproc + cfi_endproc .balign 8 .globl C(ffi_plan_gp0) diff --git a/deps/libffi/testsuite/Makefile.am b/deps/libffi/testsuite/Makefile.am index 702461d02418..4fab507d1e97 100644 --- a/deps/libffi/testsuite/Makefile.am +++ b/deps/libffi/testsuite/Makefile.am @@ -13,6 +13,7 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.bhaible/alignof.h libffi.bhaible/bhaible.exp libffi.bhaible/test-call.c \ libffi.bhaible/test-callback.c libffi.bhaible/testcases.c libffi.call/align_mixed.c \ libffi.call/align_stdcall.c libffi.call/bpo_38748.c libffi.call/call.exp \ + libffi.call/closure_raw.c \ libffi.call/closure_thiscall_fastcall_pop.c \ libffi.call/err_bad_typedef.c libffi.call/ffitest.h libffi.call/float.c \ libffi.call/float1.c libffi.call/float2.c libffi.call/float3.c \ @@ -29,7 +30,7 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.call/return_fl1.c libffi.call/return_fl2.c libffi.call/return_fl3.c \ libffi.call/return_ldl.c libffi.call/return_ll.c libffi.call/return_ll1.c \ libffi.call/return_sc.c libffi.call/return_sl.c libffi.call/return_uc.c \ - libffi.call/return_ul.c libffi.call/s55.c libffi.call/strlen.c \ + libffi.call/return_ul.c libffi.call/return_void.c libffi.call/s55.c libffi.call/strlen.c \ libffi.call/strlen2.c libffi.call/strlen3.c libffi.call/strlen4.c \ libffi.call/struct1.c libffi.call/struct10.c libffi.call/struct2.c \ libffi.call/struct3.c libffi.call/struct4.c libffi.call/struct5.c \ @@ -37,12 +38,14 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.call/struct9.c libffi.call/struct_by_value_2.c libffi.call/struct_by_value_3.c \ libffi.call/struct_by_value_3f.c libffi.call/struct_by_value_4.c libffi.call/struct_by_value_4f.c \ libffi.call/struct_by_value_big.c libffi.call/struct_by_value_small.c libffi.call/struct_return_2H.c \ - libffi.call/struct_int_float.c libffi.call/longjmp.c \ + libffi.call/struct_int_float.c libffi.call/struct_stack_small.c libffi.call/longjmp.c \ libffi.call/struct_return_8H.c libffi.call/uninitialized.c libffi.call/va_1.c \ libffi.call/va_2.c libffi.call/va_3.c libffi.call/va_struct1.c \ libffi.call/va_struct2.c libffi.call/va_struct3.c libffi.call/callback.c \ libffi.call/callback2.c libffi.call/callback3.c libffi.call/callback4.c libffi.call/x32.c \ - libffi.closures/closure.exp libffi.closures/closure_fn0.c libffi.closures/closure_fn1.c \ + libffi.closures/closure.exp libffi.closures/closure_int128.c \ + libffi.closures/closure_mmap_failure.c libffi.closures/closure_trampoline_table.c \ + libffi.closures/closure_fn0.c libffi.closures/closure_fn1.c \ libffi.closures/closure_fn2.c libffi.closures/closure_fn3.c libffi.closures/closure_fn4.c \ libffi.closures/closure_fn5.c libffi.closures/closure_fn6.c libffi.closures/closure_loc_fn0.c \ libffi.closures/closure_simple.c libffi.closures/cls_12byte.c libffi.closures/cls_16byte.c \ @@ -64,7 +67,7 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.closures/cls_multi_sshortchar.c libffi.closures/cls_multi_uchar.c libffi.closures/cls_multi_ushort.c \ libffi.closures/cls_multi_ushortchar.c libffi.closures/cls_pointer.c libffi.closures/cls_pointer_stack.c \ libffi.closures/cls_schar.c libffi.closures/cls_sint.c libffi.closures/cls_sshort.c \ - libffi.closures/cls_struct_va1.c libffi.closures/cls_uchar.c libffi.closures/cls_uint.c \ + libffi.closures/cls_struct_fp_return.c libffi.closures/cls_struct_ld_return.c libffi.closures/cls_struct_va1.c libffi.closures/cls_uchar.c libffi.closures/cls_uint.c \ libffi.closures/cls_uint_va.c libffi.closures/cls_ulong_va.c libffi.closures/cls_ulonglong.c \ libffi.closures/cls_ushort.c libffi.closures/err_bad_abi.c libffi.closures/ffitest.h \ libffi.closures/huge_struct.c libffi.closures/nested_struct.c libffi.closures/nested_struct1.c \ @@ -83,7 +86,9 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.complex/cls_complex_va_double.c libffi.complex/cls_complex_va_float.c libffi.complex/cls_complex_va_longdouble.c \ libffi.complex/complex.exp libffi.complex/complex.inc libffi.complex/complex_defs_double.inc \ libffi.complex/complex_defs_float.inc libffi.complex/complex_defs_longdouble.inc libffi.complex/complex_double.c \ - libffi.complex/complex_float.c libffi.complex/complex_i128.c libffi.complex/complex_int.c libffi.complex/complex_longdouble.c \ + libffi.complex/complex_float.c libffi.complex/complex_i128.c libffi.complex/complex_int.c libffi.complex/complex_int_small.c libffi.complex/complex_longdouble.c \ + libffi.complex/complex_longdouble_abi.c libffi.complex/complex_regs.inc libffi.complex/complex_regs_double.c \ + libffi.complex/complex_regs_float.c libffi.complex/complex_regs_longdouble.c \ libffi.complex/ffitest.h libffi.complex/many_complex.inc libffi.complex/many_complex_double.c \ libffi.complex/many_complex_float.c libffi.complex/many_complex_longdouble.c libffi.complex/return_complex.inc \ libffi.complex/return_complex1.inc libffi.complex/return_complex1_double.c libffi.complex/return_complex1_float.c \ @@ -92,10 +97,13 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.complex/return_complex_float.c libffi.complex/return_complex_longdouble.c libffi.go/aa-direct.c \ libffi.go/closure1.c libffi.go/ffitest.h libffi.go/go.exp \ libffi.go/static-chain.h Makefile.am Makefile.in \ + libffi.jspi/cls_jspi.c libffi.jspi/ffitest.h libffi.jspi/jspi.exp \ libffi.threads/ffitest.h libffi.threads/threads.exp libffi.threads/tsan.c \ libffi.vector/vector.exp libffi.vector/ffitest.h libffi.vector/vector.h \ libffi.vector/vector_float32x4.c libffi.vector/vector_float32x2.c \ libffi.vector/vector_double2.c libffi.vector/vector_int32x4.c \ libffi.vector/vector_args_spill.c libffi.vector/vector_vec3.c \ libffi.vector/vector_double4.c libffi.vector/vector_hva.c \ - libffi.vector/cls_vector.c libffi.vector/vector_validate.c + libffi.vector/cls_vector.c libffi.vector/vector_validate.c \ + libffi.vector/vector_unsupported_abi.c \ + libffi.configure/libdir.sh diff --git a/deps/libffi/testsuite/Makefile.in b/deps/libffi/testsuite/Makefile.in index 30b417735d5e..62c61d5132c7 100644 --- a/deps/libffi/testsuite/Makefile.in +++ b/deps/libffi/testsuite/Makefile.in @@ -1,7 +1,7 @@ -# Makefile.in generated by automake 1.16.5 from Makefile.am. +# Makefile.in generated by automake 1.18.1 from Makefile.am. # @configure_input@ -# Copyright (C) 1994-2021 Free Software Foundation, Inc. +# Copyright (C) 1994-2025 Free Software Foundation, Inc. # This Makefile.in is free software; the Free Software Foundation # gives unlimited permission to copy and/or distribute it, @@ -69,6 +69,8 @@ am__make_running_with_option = \ test $$has_opt = yes am__make_dryrun = (target_option=n; $(am__make_running_with_option)) am__make_keepgoing = (target_option=k; $(am__make_running_with_option)) +am__rm_f = rm -f $(am__rm_f_notfound) +am__rm_rf = rm -rf $(am__rm_f_notfound) pkgdatadir = $(datadir)/@PACKAGE@ pkgincludedir = $(includedir)/@PACKAGE@ pkglibdir = $(libdir)/@PACKAGE@ @@ -239,8 +241,10 @@ ac_ct_READELF = @ac_ct_READELF@ am__include = @am__include@ am__leading_dot = @am__leading_dot@ am__quote = @am__quote@ +am__rm_f_notfound = @am__rm_f_notfound@ am__tar = @am__tar@ am__untar = @am__untar@ +am__xargs_n = @am__xargs_n@ ax_enable_builddir_sed = @ax_enable_builddir_sed@ bindir = @bindir@ build = @build@ @@ -301,6 +305,7 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.bhaible/alignof.h libffi.bhaible/bhaible.exp libffi.bhaible/test-call.c \ libffi.bhaible/test-callback.c libffi.bhaible/testcases.c libffi.call/align_mixed.c \ libffi.call/align_stdcall.c libffi.call/bpo_38748.c libffi.call/call.exp \ + libffi.call/closure_raw.c \ libffi.call/closure_thiscall_fastcall_pop.c \ libffi.call/err_bad_typedef.c libffi.call/ffitest.h libffi.call/float.c \ libffi.call/float1.c libffi.call/float2.c libffi.call/float3.c \ @@ -317,7 +322,7 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.call/return_fl1.c libffi.call/return_fl2.c libffi.call/return_fl3.c \ libffi.call/return_ldl.c libffi.call/return_ll.c libffi.call/return_ll1.c \ libffi.call/return_sc.c libffi.call/return_sl.c libffi.call/return_uc.c \ - libffi.call/return_ul.c libffi.call/s55.c libffi.call/strlen.c \ + libffi.call/return_ul.c libffi.call/return_void.c libffi.call/s55.c libffi.call/strlen.c \ libffi.call/strlen2.c libffi.call/strlen3.c libffi.call/strlen4.c \ libffi.call/struct1.c libffi.call/struct10.c libffi.call/struct2.c \ libffi.call/struct3.c libffi.call/struct4.c libffi.call/struct5.c \ @@ -325,12 +330,14 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.call/struct9.c libffi.call/struct_by_value_2.c libffi.call/struct_by_value_3.c \ libffi.call/struct_by_value_3f.c libffi.call/struct_by_value_4.c libffi.call/struct_by_value_4f.c \ libffi.call/struct_by_value_big.c libffi.call/struct_by_value_small.c libffi.call/struct_return_2H.c \ - libffi.call/struct_int_float.c libffi.call/longjmp.c \ + libffi.call/struct_int_float.c libffi.call/struct_stack_small.c libffi.call/longjmp.c \ libffi.call/struct_return_8H.c libffi.call/uninitialized.c libffi.call/va_1.c \ libffi.call/va_2.c libffi.call/va_3.c libffi.call/va_struct1.c \ libffi.call/va_struct2.c libffi.call/va_struct3.c libffi.call/callback.c \ libffi.call/callback2.c libffi.call/callback3.c libffi.call/callback4.c libffi.call/x32.c \ - libffi.closures/closure.exp libffi.closures/closure_fn0.c libffi.closures/closure_fn1.c \ + libffi.closures/closure.exp libffi.closures/closure_int128.c \ + libffi.closures/closure_mmap_failure.c libffi.closures/closure_trampoline_table.c \ + libffi.closures/closure_fn0.c libffi.closures/closure_fn1.c \ libffi.closures/closure_fn2.c libffi.closures/closure_fn3.c libffi.closures/closure_fn4.c \ libffi.closures/closure_fn5.c libffi.closures/closure_fn6.c libffi.closures/closure_loc_fn0.c \ libffi.closures/closure_simple.c libffi.closures/cls_12byte.c libffi.closures/cls_16byte.c \ @@ -352,7 +359,7 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.closures/cls_multi_sshortchar.c libffi.closures/cls_multi_uchar.c libffi.closures/cls_multi_ushort.c \ libffi.closures/cls_multi_ushortchar.c libffi.closures/cls_pointer.c libffi.closures/cls_pointer_stack.c \ libffi.closures/cls_schar.c libffi.closures/cls_sint.c libffi.closures/cls_sshort.c \ - libffi.closures/cls_struct_va1.c libffi.closures/cls_uchar.c libffi.closures/cls_uint.c \ + libffi.closures/cls_struct_fp_return.c libffi.closures/cls_struct_ld_return.c libffi.closures/cls_struct_va1.c libffi.closures/cls_uchar.c libffi.closures/cls_uint.c \ libffi.closures/cls_uint_va.c libffi.closures/cls_ulong_va.c libffi.closures/cls_ulonglong.c \ libffi.closures/cls_ushort.c libffi.closures/err_bad_abi.c libffi.closures/ffitest.h \ libffi.closures/huge_struct.c libffi.closures/nested_struct.c libffi.closures/nested_struct1.c \ @@ -371,7 +378,9 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.complex/cls_complex_va_double.c libffi.complex/cls_complex_va_float.c libffi.complex/cls_complex_va_longdouble.c \ libffi.complex/complex.exp libffi.complex/complex.inc libffi.complex/complex_defs_double.inc \ libffi.complex/complex_defs_float.inc libffi.complex/complex_defs_longdouble.inc libffi.complex/complex_double.c \ - libffi.complex/complex_float.c libffi.complex/complex_i128.c libffi.complex/complex_int.c libffi.complex/complex_longdouble.c \ + libffi.complex/complex_float.c libffi.complex/complex_i128.c libffi.complex/complex_int.c libffi.complex/complex_int_small.c libffi.complex/complex_longdouble.c \ + libffi.complex/complex_longdouble_abi.c libffi.complex/complex_regs.inc libffi.complex/complex_regs_double.c \ + libffi.complex/complex_regs_float.c libffi.complex/complex_regs_longdouble.c \ libffi.complex/ffitest.h libffi.complex/many_complex.inc libffi.complex/many_complex_double.c \ libffi.complex/many_complex_float.c libffi.complex/many_complex_longdouble.c libffi.complex/return_complex.inc \ libffi.complex/return_complex1.inc libffi.complex/return_complex1_double.c libffi.complex/return_complex1_float.c \ @@ -380,13 +389,16 @@ EXTRA_DIST = config/default.exp emscripten/build.sh emscripten/conftest.py \ libffi.complex/return_complex_float.c libffi.complex/return_complex_longdouble.c libffi.go/aa-direct.c \ libffi.go/closure1.c libffi.go/ffitest.h libffi.go/go.exp \ libffi.go/static-chain.h Makefile.am Makefile.in \ + libffi.jspi/cls_jspi.c libffi.jspi/ffitest.h libffi.jspi/jspi.exp \ libffi.threads/ffitest.h libffi.threads/threads.exp libffi.threads/tsan.c \ libffi.vector/vector.exp libffi.vector/ffitest.h libffi.vector/vector.h \ libffi.vector/vector_float32x4.c libffi.vector/vector_float32x2.c \ libffi.vector/vector_double2.c libffi.vector/vector_int32x4.c \ libffi.vector/vector_args_spill.c libffi.vector/vector_vec3.c \ libffi.vector/vector_double4.c libffi.vector/vector_hva.c \ - libffi.vector/cls_vector.c libffi.vector/vector_validate.c + libffi.vector/cls_vector.c libffi.vector/vector_validate.c \ + libffi.vector/vector_unsupported_abi.c \ + libffi.configure/libdir.sh all: all-am @@ -445,37 +457,39 @@ check-DEJAGNU: site.exp fi; \ exit $$exit_status site.exp: Makefile $(EXTRA_DEJAGNU_SITE_CONFIG) - @echo 'Making a new site.exp file ...' - @echo '## these variables are automatically generated by make ##' >site.tmp - @echo '# Do not edit here. If you wish to override these values' >>site.tmp - @echo '# edit the last section' >>site.tmp - @echo 'set srcdir "$(srcdir)"' >>site.tmp - @echo "set objdir \"`pwd`\"" >>site.tmp - @echo 'set build_alias "$(build_alias)"' >>site.tmp - @echo 'set build_triplet $(build_triplet)' >>site.tmp - @echo 'set host_alias "$(host_alias)"' >>site.tmp - @echo 'set host_triplet $(host_triplet)' >>site.tmp - @echo 'set target_alias "$(target_alias)"' >>site.tmp - @echo 'set target_triplet $(target_triplet)' >>site.tmp - @list='$(EXTRA_DEJAGNU_SITE_CONFIG)'; for f in $$list; do \ - echo "## Begin content included from file $$f. Do not modify. ##" \ - && cat `test -f "$$f" || echo '$(srcdir)/'`$$f \ - && echo "## End content included from file $$f. ##" \ - || exit 1; \ - done >> site.tmp - @echo "## End of auto-generated content; you can edit from here. ##" >> site.tmp - @if test -f site.exp; then \ - sed -e '1,/^## End of auto-generated content.*##/d' site.exp >> site.tmp; \ - fi - @-rm -f site.bak - @test ! -f site.exp || mv site.exp site.bak - @mv site.tmp site.exp + $(AM_V_GEN)set -e; ( \ + echo '## these variables are automatically generated by make ##'; \ + echo '# Do not edit here. If you wish to override these values'; \ + echo '# edit the last section'; \ + echo 'set srcdir "$(srcdir)"'; \ + echo "set objdir \"`pwd`\""; \ + echo 'set build_alias "$(build_alias)"'; \ + echo 'set build_triplet $(build_triplet)'; \ + echo 'set host_alias "$(host_alias)"'; \ + echo 'set host_triplet $(host_triplet)'; \ + echo 'set target_alias "$(target_alias)"'; \ + echo 'set target_triplet $(target_triplet)'; \ + list='$(EXTRA_DEJAGNU_SITE_CONFIG)'; \ + for f in $$list; do \ + echo "## Begin content included from file $$f. Do not modify. ##"; \ + cat `test -f "$$f" || echo '$(srcdir)/'`$$f; \ + echo "## End content included from file $$f. ##"; \ + done; \ + echo "## End of auto-generated content; you can edit from here. ##"; \ + if test -f site.exp; then \ + sed -e '1,/^## End of auto-generated content.*##/d' site.exp; \ + fi; \ + ) >site.tmp; \ + rm -f site.bak; \ + test ! -f site.exp || mv site.exp site.bak; \ + mv site.tmp site.exp distclean-DEJAGNU: -rm -f site.exp site.bak -l='$(DEJATOOL)'; for tool in $$l; do \ rm -f $$tool.sum $$tool.log; \ done + distdir: $(BUILT_SOURCES) $(MAKE) $(AM_MAKEFLAGS) distdir-am @@ -536,11 +550,11 @@ install-strip: mostlyclean-generic: clean-generic: - -test -z "$(CLEANFILES)" || rm -f $(CLEANFILES) + -$(am__rm_f) $(CLEANFILES) distclean-generic: - -test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES) - -test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES) + -$(am__rm_f) $(CONFIG_CLEAN_FILES) + -test . = "$(srcdir)" || $(am__rm_f) $(CONFIG_CLEAN_VPATH_FILES) maintainer-clean-generic: @echo "This command is intended for maintainers to use" @@ -632,3 +646,10 @@ uninstall-am: # Tell versions [3.59,3.63) of GNU make to not export all variables. # Otherwise a system limit (for SysV at least) may be exceeded. .NOEXPORT: + +# Tell GNU make to disable its built-in pattern rules. +%:: %,v +%:: RCS/%,v +%:: RCS/% +%:: s.% +%:: SCCS/s.% diff --git a/deps/libffi/testsuite/check-dlmalloc-static.sh b/deps/libffi/testsuite/check-dlmalloc-static.sh new file mode 100755 index 000000000000..708cc2125d7d --- /dev/null +++ b/deps/libffi/testsuite/check-dlmalloc-static.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# Check that closures.c keeps the bundled dlmalloc private. +# +# closures.c declares each dl* function static before it includes +# dlmalloc.c. A dl* function missing from that list gets dlmalloc's +# default extern linkage. The version script hides it in libffi.so. +# libffi.a has no version script, so a program that links libffi.a +# exports it. +# +# Usage: check-dlmalloc-static.sh NM LIBTOOL-OBJECT + +nm_cmd=$1 +lo=$2 + +case $nm_cmd in + *dumpbin*) + echo "SKIP: $nm_cmd does not print nm-style output" + exit 0 + ;; +esac + +pic_object=none +non_pic_object=none +. "./$lo" +dir=`dirname "$lo"` + +status=0 +checked=0 +for obj in "$pic_object" "$non_pic_object"; do + test "$obj" = none && continue + checked=1 + leaked=`$nm_cmd "$dir/$obj" | awk 'NF >= 3 && $2 ~ /^[A-TV-Z]$/ { print $3 }' | grep '^_*dl'` + if test -n "$leaked"; then + echo "FAIL: $dir/$obj defines these dlmalloc functions as external symbols:" + echo "$leaked" | sed 's/^/ /' + echo "Declare them static in src/closures.c, before it includes dlmalloc.c." + status=1 + fi +done + +if test $checked = 0; then + echo "FAIL: $lo names no object to check" + exit 1 +fi +test $status = 0 && echo "PASS: no dlmalloc function in $lo is external" +exit $status diff --git a/deps/libffi/testsuite/emscripten/build-tests.sh b/deps/libffi/testsuite/emscripten/build-tests.sh index 2f1dd8d769fa..b73cb79fa982 100755 --- a/deps/libffi/testsuite/emscripten/build-tests.sh +++ b/deps/libffi/testsuite/emscripten/build-tests.sh @@ -18,7 +18,6 @@ export LDFLAGS=" \ -sMODULARIZE \ -sMAIN_MODULE \ -sNO_DISABLE_EXCEPTION_CATCHING \ - -sWASM_BIGINT \ $EXTRA_LD_FLAGS \ " diff --git a/deps/libffi/testsuite/emscripten/node-tests.sh b/deps/libffi/testsuite/emscripten/node-tests.sh index 2710947c069c..273d60b5abba 100755 --- a/deps/libffi/testsuite/emscripten/node-tests.sh +++ b/deps/libffi/testsuite/emscripten/node-tests.sh @@ -7,8 +7,8 @@ fi # Common compiler flags export CFLAGS="-fPIC $EXTRA_CFLAGS" -export CXXFLAGS="$CFLAGS -sNO_DISABLE_EXCEPTION_CATCHING $EXTRA_CXXFLAGS" -export LDFLAGS="-sEXPORTED_FUNCTIONS=_main,_malloc,_free -sALLOW_TABLE_GROWTH -sASSERTIONS -sNO_DISABLE_EXCEPTION_CATCHING -sWASM_BIGINT -Wno-main" +export CXXFLAGS="$CFLAGS -fexceptions $EXTRA_CXXFLAGS" +export LDFLAGS="-sEXPORTED_FUNCTIONS=_main,_malloc,_free -sALLOW_TABLE_GROWTH -sASSERTIONS -Wno-main" # Specific variables for cross-compilation export CHOST="${TARGET_HOST}-unknown-linux" # wasm32-unknown-emscripten diff --git a/deps/libffi/testsuite/lib/libffi.exp b/deps/libffi/testsuite/lib/libffi.exp index 55afb8f094a0..6cb40f8703b7 100644 --- a/deps/libffi/testsuite/lib/libffi.exp +++ b/deps/libffi/testsuite/lib/libffi.exp @@ -29,6 +29,20 @@ proc check_effective_target_gccbug { } { return $has_gccbug } +# True when this is a powerpc64 linux target whose compiler makes long double +# 128 bits wide. A few tests pin -mlong-double-128 to exercise the IBM-128 +# paths, but they may only do so when the library they link against was built +# the same way: the powerpc linker refuses to merge objects that disagree about +# the long double ABI. Probe the compiler rather than the target triplet, so a +# -mlong-double-64 build (musl's choice on ppc64le) drops the option and tests +# the 64-bit long double instead. +proc check_effective_target_ppc64_longdouble128 { } { + if { ![istarget powerpc64*-*-linux-gnu*] } { + return 0 + } + return [libffi_feature_test "#if defined(__LONG_DOUBLE_128__)"] +} + # Return 1 if the target matches the effective target 'arg', 0 otherwise. # This can be used with any check_* proc that takes no argument and # returns only 1 or 0. It could be used with check_* procs that take @@ -432,6 +446,8 @@ proc libffi_target_compile { source dest type options } { } } elseif { [string match "*android*" $target_triplet] } { lappend options "libs= -lc++" + } elseif { [string match "wasm*-*" $target_triplet] } { + lappend options "additional_flags=-fexceptions" } } @@ -447,10 +463,39 @@ proc libffi_target_compile { source dest type options } { lappend options "libs= -lpthread" } + # Newer clang warns about file-scope variables that are assigned + # but never read. Several tests do this deliberately. + if { [libffi_compiler_accepts_flag "-Wno-unused-but-set-global"] } { + lappend options "additional_flags=-Wno-unused-but-set-global" + } + verbose "options: $options" return [target_compile $source $dest $type $options] } +# Returns true if the compiler accepts FLAG without complaint. The +# result is cached, so the probe only runs once per flag. +proc libffi_compiler_accepts_flag { flag } { + global libffi_accepted_flags + + if { [info exists libffi_accepted_flags($flag)] } { + return $libffi_accepted_flags($flag) + } + + set src "ffiflag[pid].c" + set f [open $src "w"] + puts $f "int main() {return 0;}" + close $f + + set lines [target_compile $src $src.i preprocess "additional_flags=$flag"] + file delete $src + file delete $src.i + + set libffi_accepted_flags($flag) [string match "" $lines] + verbose "compiler accepts $flag: $libffi_accepted_flags($flag)" + return $libffi_accepted_flags($flag) +} + # TEST should be a preprocessor condition. Returns true if it holds. proc libffi_feature_test { test } { set src "ffitest[pid].c" diff --git a/deps/libffi/testsuite/libffi.call/callback.c b/deps/libffi/testsuite/libffi.call/callback.c index 70248cbb5e16..98d552cd816a 100644 --- a/deps/libffi/testsuite/libffi.call/callback.c +++ b/deps/libffi/testsuite/libffi.call/callback.c @@ -5,6 +5,9 @@ Originator: David Tenty <daltenty@ibm.com> */ /* { dg-do run } */ +/* SPARC64 classifies array members differently from nested structures, + but libffi's documented array emulation has no distinct array tag. */ +/* { dg-skip-if "array members are not representable in the SPARC64 ABI" { sparc64-*-* } } */ #include "ffitest.h" static int i=5; diff --git a/deps/libffi/testsuite/libffi.call/callback2.c b/deps/libffi/testsuite/libffi.call/callback2.c index 0fcc614977b6..bf989b817739 100644 --- a/deps/libffi/testsuite/libffi.call/callback2.c +++ b/deps/libffi/testsuite/libffi.call/callback2.c @@ -5,6 +5,9 @@ Originator: David Tenty <daltenty@ibm.com> */ /* { dg-do run } */ +/* SPARC64 classifies array members differently from nested structures, + but libffi's documented array emulation has no distinct array tag. */ +/* { dg-skip-if "array members are not representable in the SPARC64 ABI" { sparc64-*-* } } */ #include "ffitest.h" static int i=5; diff --git a/deps/libffi/testsuite/libffi.call/closure_raw.c b/deps/libffi/testsuite/libffi.call/closure_raw.c new file mode 100644 index 000000000000..84c32a445445 --- /dev/null +++ b/deps/libffi/testsuite/libffi.call/closure_raw.c @@ -0,0 +1,56 @@ +/* Area: ffi_prep_raw_closure_loc + Purpose: Check that a raw-API closure allocated with ffi_closure_alloc + is invoked correctly. With static trampolines the executable + code address differs from the closure data, and the raw API + passed the wrong one as the handler's user_data, so the handler + was read from read-only trampoline bytes and the closure made a + wild indirect call (GHSA-w6j9-w53f-2857). There was previously + no test for ffi_prep_raw_closure*. + Limitations: none. + PR: GHSA-w6j9-w53f-2857. */ + +/* { dg-do run { xfail i686-pc-cygwin } } */ +/* XFAIL: the i686 MSVC native raw-closure path fails at execution; see + libffi issue #1074. */ +#include "ffitest.h" + +/* The raw API can be configured out (e.g. Emscripten builds with + --disable-raw-api), which drops ffi_prep_raw_closure_loc from the + library. Match raw_api.c's own guard so the test links there too. */ +#if FFI_CLOSURES && !FFI_NO_RAW_API + +static void +raw_handler (ffi_cif *cif, void *ret, ffi_raw *args, void *ud) +{ + (void) cif; + *(ffi_arg *) ret = (ffi_arg) (args[0].sint + args[1].sint + (intptr_t) ud); +} + +int +main (void) +{ + ffi_cif cif; + ffi_type *args[2] = { &ffi_type_sint, &ffi_type_sint }; + ffi_raw_closure *cl; + void *code; + int (*f) (int, int); + + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 2, &ffi_type_sint, args) + == FFI_OK); + + cl = ffi_closure_alloc (sizeof (ffi_raw_closure), &code); + CHECK (cl != NULL); + CHECK (ffi_prep_raw_closure_loc (cl, &cif, raw_handler, (void *) 100, code) + == FFI_OK); + + f = (int (*) (int, int)) code; + CHECK (f (20, 3) == 123); + + ffi_closure_free (cl); + printf ("raw closure ok\n"); + exit (0); +} + +#else +int main (void) { return 0; } +#endif diff --git a/deps/libffi/testsuite/libffi.call/return_void.c b/deps/libffi/testsuite/libffi.call/return_void.c new file mode 100644 index 000000000000..abc3c198e568 --- /dev/null +++ b/deps/libffi/testsuite/libffi.call/return_void.c @@ -0,0 +1,37 @@ +/* Area: ffi_call + Purpose: Check that a void call ignores its return buffer. + Limitations: none. */ + +/* { dg-do run } */ +#include "ffitest.h" + +static unsigned int called; + +static void +return_void (unsigned int value) +{ + called = value; +} + +int +main (void) +{ + ffi_cif cif; + ffi_type *args[1] = { &ffi_type_uint }; + unsigned int value = 42; + void *values[1] = { &value }; + ffi_arg result = ~(ffi_arg)0; + + CHECK(ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_void, args) == FFI_OK); + + ffi_call (&cif, FFI_FN(return_void), &result, values); + CHECK(called == value); + CHECK(result == ~(ffi_arg)0); + + value = 43; + ffi_call (&cif, FFI_FN(return_void), NULL, values); + CHECK(called == value); + + exit (0); +} diff --git a/deps/libffi/testsuite/libffi.call/struct_stack_small.c b/deps/libffi/testsuite/libffi.call/struct_stack_small.c new file mode 100644 index 000000000000..e55646adae7f --- /dev/null +++ b/deps/libffi/testsuite/libffi.call/struct_stack_small.c @@ -0,0 +1,96 @@ +/* Area: ffi_call, closure_call + Purpose: Check a small struct passed on the stack and the argument + following it. + Limitations: none. + PR: none. */ + +/* { dg-do run } */ +#include "ffitest.h" + +/* A two-byte struct after eight ints goes to the stack on targets with + eight argument registers, followed by a short that must land in the slot + the ABI assigns after the struct. */ + +typedef struct +{ + unsigned char a; + unsigned char b; +} small_struct; + +static int ABI_ATTR +f_stack (int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, + small_struct s, short t) +{ + return i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8 + + s.a * 10 + s.b * 100 + t * 1000; +} + +#if FFI_CLOSURES +static void +cls_stack (ffi_cif *cif __UNUSED__, void *resp, void **args, + void *userdata __UNUSED__) +{ + *(ffi_arg *) resp = f_stack (*(int *) args[0], *(int *) args[1], + *(int *) args[2], *(int *) args[3], + *(int *) args[4], *(int *) args[5], + *(int *) args[6], *(int *) args[7], + *(small_struct *) args[8], + *(short *) args[9]); +} +#endif + +int +main (void) +{ + ffi_cif cif; + ffi_type small_struct_type; + ffi_type *small_struct_elements[3]; + ffi_type *types[10]; + void *values[10]; +#if FFI_CLOSURES + ffi_closure *pcl; + void *code; +#endif + int ints[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + small_struct s = { 3, 5 }; + short t = 7; + ffi_arg result; + int i; + + small_struct_elements[0] = &ffi_type_uchar; + small_struct_elements[1] = &ffi_type_uchar; + small_struct_elements[2] = NULL; + small_struct_type.size = 0; + small_struct_type.alignment = 0; + small_struct_type.type = FFI_TYPE_STRUCT; + small_struct_type.elements = small_struct_elements; + + for (i = 0; i < 8; i++) + { + types[i] = &ffi_type_sint; + values[i] = &ints[i]; + } + types[8] = &small_struct_type; + values[8] = &s; + types[9] = &ffi_type_sshort; + values[9] = &t; + + CHECK (ffi_prep_cif (&cif, ABI_NUM, 10, &ffi_type_sint, types) == FFI_OK); + ffi_call (&cif, FFI_FN (f_stack), &result, values); + printf ("stack: %d\n", (int) result); + CHECK ((int) result == 7566); + +#if FFI_CLOSURES + pcl = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (pcl != NULL); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_stack, NULL, code) == FFI_OK); + result = ((int (ABI_ATTR *) (int, int, int, int, int, int, int, int, + small_struct, short)) code) + (1, 2, 3, 4, 5, 6, 7, 8, s, t); + printf ("closure stack: %d\n", (int) result); + CHECK ((int) result == 7566); + ffi_closure_free (pcl); +#endif + + exit (0); +} diff --git a/deps/libffi/testsuite/libffi.closures/closure_int128.c b/deps/libffi/testsuite/libffi.closures/closure_int128.c new file mode 100644 index 000000000000..a1c8ea155c37 --- /dev/null +++ b/deps/libffi/testsuite/libffi.closures/closure_int128.c @@ -0,0 +1,79 @@ +/* Area: ffi_closure + Purpose: Check that a closure receives a 128-bit integer argument, and + the argument after it, correctly. On s390x the closure path + had no SINT128/UINT128 case, so it left the argument's avalue[] + slot uninitialised and shifted every later argument + (GHSA-wf8m-qr3x-cch4). + Limitations: none. + PR: GHSA-wf8m-qr3x-cch4. */ + +/* { dg-do run } */ +#include "ffitest.h" + +#if defined(FFI_TARGET_HAS_INT128) && defined(__SIZEOF_INT128__) + +typedef __int128_t i128; + +static const i128 VAL = + ((i128)0x0102030405060708ull << 64) | 0x090a0b0c0d0e0f10ull; +#define TAIL 0x5a5a5a5aL + +/* long f(i128 x, long b) => low64(x) + b */ +static void h_xb (ffi_cif *cif, void *ret, void **args, void *ud) +{ + i128 x = *(i128 *) args[0]; + long b = *(long *) args[1]; + (void) cif; (void) ud; + *(ffi_arg *) ret = (ffi_arg) ((long) x + b); +} + +/* long g(long a, i128 x, long b) => a + low64(x) + b */ +static void h_axb (ffi_cif *cif, void *ret, void **args, void *ud) +{ + long a = *(long *) args[0]; + i128 x = *(i128 *) args[1]; + long b = *(long *) args[2]; + (void) cif; (void) ud; + *(ffi_arg *) ret = (ffi_arg) (a + (long) x + b); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *cl; + + { + ffi_type *args[2] = { &ffi_type_sint128, &ffi_type_sint64 }; + long (*f) (i128, long); + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 2, &ffi_type_sint64, args) + == FFI_OK); + cl = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (cl != NULL); + CHECK (ffi_prep_closure_loc (cl, &cif, h_xb, NULL, code) == FFI_OK); + f = (long (*) (i128, long)) code; + CHECK (f (VAL, TAIL) == (long) ((long) VAL + TAIL)); + ffi_closure_free (cl); + } + + { + ffi_type *args[3] = + { &ffi_type_sint64, &ffi_type_sint128, &ffi_type_sint64 }; + long (*g) (long, i128, long); + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 3, &ffi_type_sint64, args) + == FFI_OK); + cl = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (cl != NULL); + CHECK (ffi_prep_closure_loc (cl, &cif, h_axb, NULL, code) == FFI_OK); + g = (long (*) (long, i128, long)) code; + CHECK (g (11, VAL, TAIL) == (long) (11 + (long) VAL + TAIL)); + ffi_closure_free (cl); + } + + printf ("closure int128 ok\n"); + exit (0); +} + +#else +int main (void) { return 0; } +#endif diff --git a/deps/libffi/testsuite/libffi.closures/closure_mmap_failure.c b/deps/libffi/testsuite/libffi.closures/closure_mmap_failure.c new file mode 100644 index 000000000000..143174708601 --- /dev/null +++ b/deps/libffi/testsuite/libffi.closures/closure_mmap_failure.c @@ -0,0 +1,62 @@ +/* Area: closures */ +/* { dg-do run { target x86_64-*-linux-gnu* } } */ +/* { dg-options "-Wl,--export-dynamic" { target x86_64-*-linux-gnu* } } */ + +#define _GNU_SOURCE 1 +#include "ffitest.h" + +/* The Emscripten browser harness compiles every testcase and ignores the + dg-do target above. This test interposes mmap through RTLD_NEXT and needs + dlsym on a glibc/ELF system; on wasm, dlsym from an unopened handle aborts. + Guard the body so it is a harmless no-op anywhere it cannot run. */ +#if defined(__GLIBC__) + +#include <dlfcn.h> +#include <errno.h> +#include <sys/mman.h> +#include <unistd.h> + +typedef void *(*mmap_fn) (void *, size_t, int, int, int, off_t); + +static mmap_fn real_mmap; +static int reject_exec_mappings; + +/* Model a hardened runtime that rejects every executable mapping. */ +void * +mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset) +{ + if (reject_exec_mappings && (prot & PROT_EXEC)) + { + errno = EPERM; + return MAP_FAILED; + } + + return real_mmap (addr, length, prot, flags, fd, offset); +} + +int +main (void) +{ + ffi_closure *closure; + void *code = NULL; + + real_mmap = (mmap_fn) dlsym (RTLD_NEXT, "mmap"); + CHECK (real_mmap != NULL); + + reject_exec_mappings = 1; + + /* The failure path must terminate instead of cycling through temporary + backing files forever. */ + alarm (5); + closure = ffi_closure_alloc (sizeof (ffi_closure), &code); + alarm (0); + + CHECK (closure == NULL); + CHECK (code == NULL); + + exit (0); +} + +#else +int main (void) { return 0; } +#endif diff --git a/deps/libffi/testsuite/libffi.closures/closure_trampoline_table.c b/deps/libffi/testsuite/libffi.closures/closure_trampoline_table.c new file mode 100644 index 000000000000..c293ba78ba70 --- /dev/null +++ b/deps/libffi/testsuite/libffi.closures/closure_trampoline_table.c @@ -0,0 +1,62 @@ +/* Area: ffi_closure_alloc, ffi_closure_free + Purpose: Churn the closure allocator across many live closures. + On targets that use the Darwin trampoline-table allocator + this spans several trampoline tables and exercises the + allocator's internal table list. Freeing a partially used + non-head table moved it to the head of the list without + unlinking it first, corrupting the doubly-linked list; a + later free then wrote through the stale links into freed + table memory, a heap use-after-free (GHSA-23hx-9rxv-9qfp). + The sequence is harmless on every other allocator. + Limitations: Only the Darwin trampoline-table allocator keeps such a + list, so elsewhere this is just an allocator stress test. + PR: GHSA-23hx-9rxv-9qfp */ + +/* { dg-do run } */ + +#include "ffitest.h" + +/* Enough closures to span several trampoline tables on the Darwin + allocator (at most 1024 entries per table), so that the interleaved + free order below forces non-head tables to be bumped to the front of + the list and later emptied and freed. */ +#define N 4096 + +int +main (void) +{ + ffi_closure **closures; + void *code; + int round, i; + + closures = malloc (N * sizeof (*closures)); + CHECK (closures != NULL); + + for (round = 0; round < 3; round++) + { + for (i = 0; i < N; i++) + { + code = NULL; + closures[i] = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (closures[i] != NULL); + CHECK (code != NULL); + } + + /* Interleave the frees: the first pass returns one entry from + many different tables, bumping partially used non-head tables + to the head of the list; the second pass then empties and frees + tables while the list is in that state. Before the fix this + walked stale prev/next links and wrote into freed memory. */ + for (i = 0; i < N; i += 2) + ffi_closure_free (closures[i]); + for (i = 1; i < N; i += 2) + ffi_closure_free (closures[i]); + } + + free (closures); + + printf ("closure trampoline table ok\n"); + exit (0); +} + +/* { dg-output "closure trampoline table ok" } */ diff --git a/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c b/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c index 128d6e1b4039..8988b5d6197e 100644 --- a/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c +++ b/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split.c @@ -5,7 +5,7 @@ Originator: <hos@tamanegi.org> 20031203 */ /* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ -/* { dg-options -mlong-double-128 { target powerpc64*-*-linux-gnu* } } */ +/* { dg-options -mlong-double-128 { target ppc64_longdouble128 } } */ #include "ffitest.h" diff --git a/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c b/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c index 3562a57fabda..edf21b7f9267 100644 --- a/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c +++ b/deps/libffi/testsuite/libffi.closures/cls_align_longdouble_split2.c @@ -6,7 +6,7 @@ */ /* { dg-do run { xfail strongarm*-*-* } } */ -/* { dg-options -mlong-double-128 { target powerpc64*-*-linux-gnu* } } */ +/* { dg-options -mlong-double-128 { target ppc64_longdouble128 } } */ #include "ffitest.h" diff --git a/deps/libffi/testsuite/libffi.closures/cls_longdouble.c b/deps/libffi/testsuite/libffi.closures/cls_longdouble.c index 2cfac4bafef9..ea2985f6f497 100644 --- a/deps/libffi/testsuite/libffi.closures/cls_longdouble.c +++ b/deps/libffi/testsuite/libffi.closures/cls_longdouble.c @@ -7,7 +7,7 @@ /* This test is known to PASS on armv7l-unknown-linux-gnueabihf, so I have remove the xfail for arm*-*-* below, until we know more. */ /* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ -/* { dg-options -mlong-double-128 { target powerpc64*-*-linux-gnu* } } */ +/* { dg-options -mlong-double-128 { target ppc64_longdouble128 } } */ #include "ffitest.h" diff --git a/deps/libffi/testsuite/libffi.closures/cls_struct_fp_return.c b/deps/libffi/testsuite/libffi.closures/cls_struct_fp_return.c new file mode 100644 index 000000000000..35583b6ed180 --- /dev/null +++ b/deps/libffi/testsuite/libffi.closures/cls_struct_fp_return.c @@ -0,0 +1,102 @@ +/* Area: ffi_call, closure_call + Purpose: Check return values of structs with one or two floating-point + fields. + Limitations: none. + PR: none. */ + +/* { dg-do run { xfail mips64*-*-* } } */ +/* XFAIL: mips N64 ABI bug in complex-float/longdouble args and fp-struct + returns; see libffi issue #1071. */ + +#include "ffitest.h" + +/* Several ABIs return these structs in floating-point registers, or with + soft float in pairs of GPRs that differ from those used for other small + structs, so they need their own return paths in ffi_call and in + closures. */ + +typedef struct { float a; } s_f; +typedef struct { double a; } s_d; +typedef struct { float a; float b; } s_ff; +typedef struct { double a; double b; } s_dd; +typedef struct { float a; double b; } s_fd; +typedef struct { double a; float b; } s_df; + +#define DEFINE(name, eq, ...) \ +static name ABI_ATTR \ +fn_##name (int k) \ +{ \ + name r = { __VA_ARGS__ }; \ + return r; \ +} \ + \ +static void \ +cls_##name (ffi_cif *cif __UNUSED__, void *resp, void **argv, \ + void *userdata __UNUSED__) \ +{ \ + *(name *) resp = fn_##name (*(int *) argv[0]); \ +} \ + \ +static int \ +eq_##name (name x, name y) \ +{ \ + return eq; \ +} + +#define EQ1 (x.a == y.a) +#define EQ2 (x.a == y.a && x.b == y.b) + +DEFINE (s_f, EQ1, 1.5f * k) +DEFINE (s_d, EQ1, 2.5 * k) +DEFINE (s_ff, EQ2, 1.5f * k, -0.25f * k) +DEFINE (s_dd, EQ2, 2.5 * k, -0.75 * k) +DEFINE (s_fd, EQ2, 1.5f * k, -0.75 * k) +DEFINE (s_df, EQ2, 2.5 * k, -0.25f * k) + +#define CHECK_ONE(name, type1, type2) \ + do { \ + ffi_type *elements[3] = { type1, type2, NULL }; \ + ffi_type type; \ + ffi_type *args[1] = { &ffi_type_sint }; \ + void *values[1] = { &k }; \ + ffi_cif cif; \ + ffi_closure *pcl; \ + void *code; \ + union { ffi_arg align; name value; } result; \ + name want = fn_##name (k), got; \ + \ + type.size = 0; \ + type.alignment = 0; \ + type.type = FFI_TYPE_STRUCT; \ + type.elements = elements; \ + CHECK (ffi_prep_cif (&cif, ABI_NUM, 1, &type, args) == FFI_OK); \ + \ + memset (&result, 0, sizeof (result)); \ + ffi_call (&cif, FFI_FN (fn_##name), &result, values); \ + CHECK (eq_##name (result.value, want)); \ + \ + pcl = ffi_closure_alloc (sizeof (ffi_closure), &code); \ + CHECK (pcl != NULL); \ + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_##name, NULL, code) \ + == FFI_OK); \ + memset (&got, 0, sizeof (got)); \ + got = ((name (ABI_ATTR *)(int)) code) (k); \ + CHECK (eq_##name (got, want)); \ + ffi_closure_free (pcl); \ + printf ("%s: ok\n", #name); \ + } while (0) + +int +main (void) +{ + int k = 3; + + CHECK_ONE (s_f, &ffi_type_float, NULL); + CHECK_ONE (s_d, &ffi_type_double, NULL); + CHECK_ONE (s_ff, &ffi_type_float, &ffi_type_float); + CHECK_ONE (s_dd, &ffi_type_double, &ffi_type_double); + CHECK_ONE (s_fd, &ffi_type_float, &ffi_type_double); + CHECK_ONE (s_df, &ffi_type_double, &ffi_type_float); + + exit (0); +} diff --git a/deps/libffi/testsuite/libffi.closures/cls_struct_ld_return.c b/deps/libffi/testsuite/libffi.closures/cls_struct_ld_return.c new file mode 100644 index 000000000000..cb831d65b692 --- /dev/null +++ b/deps/libffi/testsuite/libffi.closures/cls_struct_ld_return.c @@ -0,0 +1,66 @@ +/* Area: ffi_call, closure_call + Purpose: Check the return value of a struct with one long double field. + Limitations: none. + PR: none. */ + +/* { dg-do run { xfail mips64*-*-* x86_64-*-linux-android* } } */ +/* XFAIL: mips N64 mishandles long-double struct returns (libffi issue + #1071). x86_64 Android mishandles the long-double struct return where + x86_64-linux-gnu does not (libffi issue #1076). */ +/* { dg-options -mlong-double-128 { target ppc64_longdouble128 } } */ + +#include "ffitest.h" + +/* x86-64 returns this struct in %st(0), like a plain long double. */ + +typedef struct { long double a; } s_ld; + +static s_ld ABI_ATTR +fn_s_ld (int k) +{ + s_ld r = { 1.5L * k }; + return r; +} + +static void +cls_s_ld (ffi_cif *cif __UNUSED__, void *resp, void **argv, + void *userdata __UNUSED__) +{ + *(s_ld *) resp = fn_s_ld (*(int *) argv[0]); +} + +int +main (void) +{ + ffi_type *elements[2] = { &ffi_type_longdouble, NULL }; + ffi_type type; + ffi_type *args[1] = { &ffi_type_sint }; + int k = 3; + void *values[1] = { &k }; + ffi_cif cif; + ffi_closure *pcl; + void *code; + s_ld got; + + type.size = 0; + type.alignment = 0; + type.type = FFI_TYPE_STRUCT; + type.elements = elements; + CHECK (ffi_prep_cif (&cif, ABI_NUM, 1, &type, args) == FFI_OK); + + memset (&got, 0, sizeof (got)); + ffi_call (&cif, FFI_FN (fn_s_ld), &got, values); + printf ("ffi_call: %Lg\n", got.a); + CHECK (got.a == 4.5L); + + pcl = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (pcl != NULL); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_s_ld, NULL, code) == FFI_OK); + memset (&got, 0, sizeof (got)); + got = ((s_ld (ABI_ATTR *)(int)) code) (k + 1); + printf ("closure: %Lg\n", got.a); + CHECK (got.a == 6.0L); + ffi_closure_free (pcl); + + exit (0); +} diff --git a/deps/libffi/testsuite/libffi.closures/huge_struct.c b/deps/libffi/testsuite/libffi.closures/huge_struct.c index b3488304c1a6..040973d37ea1 100644 --- a/deps/libffi/testsuite/libffi.closures/huge_struct.c +++ b/deps/libffi/testsuite/libffi.closures/huge_struct.c @@ -6,7 +6,7 @@ */ /* { dg-do run { xfail strongarm*-*-* xscale*-*-* } } */ -/* { dg-options -mlong-double-128 { target powerpc64*-*-linux-gnu* } } */ +/* { dg-options -mlong-double-128 { target ppc64_longdouble128 } } */ /* { dg-options -Wformat=0 { target moxie*-*-elf or1k-*-* } } */ #include <inttypes.h> diff --git a/deps/libffi/testsuite/libffi.complex/complex_int_small.c b/deps/libffi/testsuite/libffi.complex/complex_int_small.c new file mode 100644 index 000000000000..29bc46d61c00 --- /dev/null +++ b/deps/libffi/testsuite/libffi.complex/complex_int_small.c @@ -0,0 +1,170 @@ +/* Area: ffi_call, closure_call + Purpose: Check integer complex types smaller than a register. + Limitations: none. + PR: none. */ + +/* { dg-do run } */ + +#include "ffitest.h" +#include <complex.h> + +/* _Complex signed char and _Complex short are passed and returned in a + single register or stack slot on most targets, which for complex values + is a different code path from the larger types. The last function + passes both after eight ints, so that they go to the stack on targets + with eight argument registers. */ + +#define FFI_COMPLEX_TYPEDEF(name, type, ffitype) \ + static ffi_type *ffi_elements_complex_##name [2] = { \ + (ffi_type *)(&ffitype), NULL \ + }; \ + struct struct_align_complex_##name { \ + char c; \ + _Complex type x; \ + }; \ + static ffi_type ffi_type_complex_##name = { \ + sizeof(_Complex type), \ + offsetof(struct struct_align_complex_##name, x), \ + FFI_TYPE_COMPLEX, \ + (ffi_type **)ffi_elements_complex_##name \ + } + +FFI_COMPLEX_TYPEDEF(schar, signed char, ffi_type_schar); +FFI_COMPLEX_TYPEDEF(sshort, short, ffi_type_sshort); + +typedef _Complex signed char cc; +typedef _Complex short cs; + +/* ffi_call requires its return storage to be at least register-sized and + suitably aligned, even when the declared return type is smaller. */ +typedef union +{ + ffi_arg align; + cc cchar; + cs cshort; +} complex_result; + +static cc +f_cc (cc a, int k) +{ + __real__ a = __real__ a * k; + __imag__ a = __imag__ a - k; + return a; +} + +static cs +f_cs (cs a, int k) +{ + __real__ a = __real__ a * k; + __imag__ a = __imag__ a - k; + return a; +} + +static cs +f_stack (int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8, + cc a, cs b) +{ + __real__ b = __real__ b + __real__ a + i1 + i2 + i3 + i4; + __imag__ b = __imag__ b + __imag__ a + i5 + i6 + i7 + i8; + return b; +} + +static void +cls_cc (ffi_cif *cif __UNUSED__, void *resp, void **args, + void *userdata __UNUSED__) +{ + *(cc *) resp = f_cc (*(cc *) args[0], *(int *) args[1]); +} + +static void +cls_cs (ffi_cif *cif __UNUSED__, void *resp, void **args, + void *userdata __UNUSED__) +{ + *(cs *) resp = f_cs (*(cs *) args[0], *(int *) args[1]); +} + +static void +cls_stack (ffi_cif *cif __UNUSED__, void *resp, void **args, + void *userdata __UNUSED__) +{ + *(cs *) resp = f_stack (*(int *) args[0], *(int *) args[1], + *(int *) args[2], *(int *) args[3], + *(int *) args[4], *(int *) args[5], + *(int *) args[6], *(int *) args[7], + *(cc *) args[8], *(cs *) args[9]); +} + +int +main (void) +{ + ffi_cif cif; + ffi_type *types[10]; + void *values[10]; + ffi_closure *pcl; + void *code; + int ints[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + cc a, ra; + cs b, rb; + complex_result result; + int k = 3, i; + + pcl = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (pcl != NULL); + + __real__ a = 5; + __imag__ a = -7; + __real__ b = 300; + __imag__ b = -400; + + types[0] = &ffi_type_complex_schar; + types[1] = &ffi_type_sint; + values[0] = &a; + values[1] = &k; + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 2, &ffi_type_complex_schar, + types) == FFI_OK); + ffi_call (&cif, FFI_FN (f_cc), &result, values); + ra = result.cchar; + printf ("cc: %d,%di\n", (int) __real__ ra, (int) __imag__ ra); + CHECK (__real__ ra == 15 && __imag__ ra == -10); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_cc, NULL, code) == FFI_OK); + ra = ((cc (*)(cc, int)) code) (a, k); + printf ("closure cc: %d,%di\n", (int) __real__ ra, (int) __imag__ ra); + CHECK (__real__ ra == 15 && __imag__ ra == -10); + + types[0] = &ffi_type_complex_sshort; + values[0] = &b; + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 2, &ffi_type_complex_sshort, + types) == FFI_OK); + ffi_call (&cif, FFI_FN (f_cs), &result, values); + rb = result.cshort; + printf ("cs: %d,%di\n", (int) __real__ rb, (int) __imag__ rb); + CHECK (__real__ rb == 900 && __imag__ rb == -403); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_cs, NULL, code) == FFI_OK); + rb = ((cs (*)(cs, int)) code) (b, k); + printf ("closure cs: %d,%di\n", (int) __real__ rb, (int) __imag__ rb); + CHECK (__real__ rb == 900 && __imag__ rb == -403); + + for (i = 0; i < 8; i++) + { + types[i] = &ffi_type_sint; + values[i] = &ints[i]; + } + types[8] = &ffi_type_complex_schar; + values[8] = &a; + types[9] = &ffi_type_complex_sshort; + values[9] = &b; + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, 10, &ffi_type_complex_sshort, + types) == FFI_OK); + ffi_call (&cif, FFI_FN (f_stack), &result, values); + rb = result.cshort; + printf ("stack: %d,%di\n", (int) __real__ rb, (int) __imag__ rb); + CHECK (__real__ rb == 315 && __imag__ rb == -381); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_stack, NULL, code) == FFI_OK); + rb = ((cs (*)(int, int, int, int, int, int, int, int, cc, cs)) code) + (1, 2, 3, 4, 5, 6, 7, 8, a, b); + printf ("closure stack: %d,%di\n", (int) __real__ rb, (int) __imag__ rb); + CHECK (__real__ rb == 315 && __imag__ rb == -381); + + ffi_closure_free (pcl); + exit (0); +} diff --git a/deps/libffi/testsuite/libffi.complex/complex_longdouble_abi.c b/deps/libffi/testsuite/libffi.complex/complex_longdouble_abi.c new file mode 100644 index 000000000000..5a2ef2436b8b --- /dev/null +++ b/deps/libffi/testsuite/libffi.complex/complex_longdouble_abi.c @@ -0,0 +1,68 @@ +/* Area: ffi_prep_types + Purpose: Check that _Complex long double follows the abi's long double width. + Limitations: powerpc64 only -- the one target where long double has more + than one width at run time. + PR: none. + Originator: Anthony Green 20260916 */ + +/* { dg-do run { target powerpc64*-*-linux-gnu* } } */ + +#include "ffitest.h" + +/* ffi_prep_cif() and ffi_get_struct_offsets() resize ffi_type_longdouble to + match the FFI_LINUX_LONG_DOUBLE_128 bit of the abi they are handed, so that + one libffi can describe calls into libraries built with either width. That + is also why these two types, alone among the ffi_type objects, are not + const. ffi_type_complex_longdouble has to keep up: two halves of whatever + long double currently is. */ + +static void +check_width (ffi_abi abi, size_t ld_size, unsigned short ld_align) +{ + ffi_cif cif; + ffi_type *args[1]; + ffi_type *elements[2]; + ffi_type s; + size_t offsets[1]; + + args[0] = &ffi_type_complex_longdouble; + CHECK (ffi_prep_cif (&cif, abi, 1, &ffi_type_complex_longdouble, args) + == FFI_OK); + + CHECK (ffi_type_longdouble.size == ld_size); + CHECK (ffi_type_longdouble.alignment == ld_align); + + CHECK (ffi_type_complex_longdouble.size == 2 * ld_size); + CHECK (ffi_type_complex_longdouble.alignment == ld_align); + CHECK (ffi_type_complex_longdouble.elements[0]->size == ld_size); + + /* A struct built out of that type has to come out the same size, which is + what ffi_get_struct_offsets() and every struct-passing path rely on. */ + elements[0] = &ffi_type_complex_longdouble; + elements[1] = NULL; + s.size = 0; + s.alignment = 0; + s.type = FFI_TYPE_STRUCT; + s.elements = elements; + CHECK (ffi_get_struct_offsets (abi, &s, offsets) == FFI_OK); + CHECK (s.size == 2 * ld_size); + CHECK (offsets[0] == 0); +} + +int +main (void) +{ + size_t native = (FFI_DEFAULT_ABI & FFI_LINUX_LONG_DOUBLE_128) ? 16 : 8; + + /* A 64-bit long double, as musl selects on ppc64le. */ + check_width ((ffi_abi) FFI_LINUX, 8, 8); + /* A 128-bit long double, either IBM-128 or IEEE-128. */ + check_width ((ffi_abi) (FFI_LINUX | FFI_LINUX_LONG_DOUBLE_128), 16, 16); + /* Leave the globals as this build's default abi found them. */ + check_width (FFI_DEFAULT_ABI, native, (unsigned short) native); + + printf ("success\n"); + exit (0); +} + +/* { dg-output "success" } */ diff --git a/deps/libffi/testsuite/libffi.complex/complex_regs.inc b/deps/libffi/testsuite/libffi.complex/complex_regs.inc new file mode 100644 index 000000000000..f2d2bbf8e369 --- /dev/null +++ b/deps/libffi/testsuite/libffi.complex/complex_regs.inc @@ -0,0 +1,142 @@ +/* -*-c-*- */ +#include "ffitest.h" +#include <complex.h> + +/* A complex argument that arrives when the argument registers are nearly + used up. Seven doubles leave one floating-point argument register on + RISC-V and LoongArch, so the complex value has to move to integer + registers as a whole. Five ints leave an odd number of GPRs on 32-bit + PowerPC, where a two-word complex skips to the next even register pair + and a larger one goes to the stack, followed by every later argument. + Eight doubles and eight ints push the complex value onto the stack on + every target. */ + +typedef _Complex T_C_TYPE C; + +static C +fn_d7 (double d1, double d2, double d3, double d4, double d5, double d6, + double d7, C c, int k) +{ + return c * k + (d1 + d2 + d3 + d4 + d5 + d6 + d7); +} + +static C +fn_i5 (int i1, int i2, int i3, int i4, int i5, C c, int k) +{ + return c * k + (i1 + i2 + i3 + i4 + i5); +} + +static C +fn_d8i8 (double d1, double d2, double d3, double d4, double d5, double d6, + double d7, double d8, int i1, int i2, int i3, int i4, int i5, int i6, + int i7, int i8, C c, int k) +{ + return c * k + (d1 + d2 + d3 + d4 + d5 + d6 + d7 + d8 + + i1 + i2 + i3 + i4 + i5 + i6 + i7 + i8); +} + +/* SHAPE[0] doubles, SHAPE[1] ints, then the complex value and an int. */ +static void +cls_fn (ffi_cif *cif __UNUSED__, void *resp, void **args, void *userdata) +{ + const int *shape = (const int *) userdata; + T_C_TYPE s = 0; + int i, n = 0; + + for (i = 0; i < shape[0]; i++) + s += *(double *) args[n++]; + for (i = 0; i < shape[1]; i++) + s += *(int *) args[n++]; + *(C *) resp = *(C *) args[n] * *(int *) args[n + 1] + s; +} + +static void +check (const char *name, C got, C want) +{ + printf ("%s: %.3f,%.3fi (want %.3f,%.3fi)\n", name, + T_CONV creal (got), T_CONV cimag (got), + T_CONV creal (want), T_CONV cimag (want)); + CHECK (creal (got) == creal (want)); + CHECK (cimag (got) == cimag (want)); +} + +static void +prep (ffi_cif *cif, ffi_type **types, void **values, int nd, int ni, + double *d, int *i, C *c, int *k) +{ + int j, n = 0; + + for (j = 0; j < nd; j++, n++) + { + types[n] = &ffi_type_double; + values[n] = &d[j]; + } + for (j = 0; j < ni; j++, n++) + { + types[n] = &ffi_type_sint; + values[n] = &i[j]; + } + types[n] = &T_FFI_TYPE; + values[n++] = c; + types[n] = &ffi_type_sint; + values[n++] = k; + CHECK (ffi_prep_cif (cif, FFI_DEFAULT_ABI, n, &T_FFI_TYPE, types) == FFI_OK); +} + +int +main (void) +{ + static const int shape_d7[2] = { 7, 0 }; + static const int shape_i5[2] = { 0, 5 }; + static const int shape_d8i8[2] = { 8, 8 }; + double d[8] = { 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5 }; + int i[8] = { 10, 20, 30, 40, 50, 60, 70, 80 }; + C c = 1.25 + 2.5 * I; + int k = 77; + ffi_type *types[18]; + void *values[18]; + ffi_cif cif; + ffi_closure *pcl; + void *code; + C r; + + pcl = ffi_closure_alloc (sizeof (ffi_closure), &code); + CHECK (pcl != NULL); + + prep (&cif, types, values, 7, 0, d, i, &c, &k); + ffi_call (&cif, FFI_FN (fn_d7), &r, values); + check ("call d7", r, fn_d7 (d[0], d[1], d[2], d[3], d[4], d[5], d[6], c, k)); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_fn, (void *) shape_d7, code) + == FFI_OK); + r = ((C (*)(double, double, double, double, double, double, double, C, + int)) code) (d[0], d[1], d[2], d[3], d[4], d[5], d[6], c, k); + check ("closure d7", r, + fn_d7 (d[0], d[1], d[2], d[3], d[4], d[5], d[6], c, k)); + + prep (&cif, types, values, 0, 5, d, i, &c, &k); + ffi_call (&cif, FFI_FN (fn_i5), &r, values); + check ("call i5", r, fn_i5 (i[0], i[1], i[2], i[3], i[4], c, k)); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_fn, (void *) shape_i5, code) + == FFI_OK); + r = ((C (*)(int, int, int, int, int, C, int)) code) + (i[0], i[1], i[2], i[3], i[4], c, k); + check ("closure i5", r, fn_i5 (i[0], i[1], i[2], i[3], i[4], c, k)); + + prep (&cif, types, values, 8, 8, d, i, &c, &k); + ffi_call (&cif, FFI_FN (fn_d8i8), &r, values); + check ("call d8i8", r, + fn_d8i8 (d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], + i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], c, k)); + CHECK (ffi_prep_closure_loc (pcl, &cif, cls_fn, (void *) shape_d8i8, code) + == FFI_OK); + r = ((C (*)(double, double, double, double, double, double, double, double, + int, int, int, int, int, int, int, int, C, int)) code) + (d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], + i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], c, k); + check ("closure d8i8", r, + fn_d8i8 (d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], + i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], c, k)); + + ffi_closure_free (pcl); + exit (0); +} diff --git a/deps/libffi/testsuite/libffi.complex/complex_regs_double.c b/deps/libffi/testsuite/libffi.complex/complex_regs_double.c new file mode 100644 index 000000000000..6c1cb7e025af --- /dev/null +++ b/deps/libffi/testsuite/libffi.complex/complex_regs_double.c @@ -0,0 +1,11 @@ +/* Area: ffi_call, closure_call + Purpose: Check complex arguments after the argument registers run low. + Limitations: none. + PR: none. */ + +/* { dg-do run { xfail mips64*-*-* } } */ +/* XFAIL: mips N64 complex-argument ABI bug; the little-endian variant + fails the complex-double case too. See libffi issue #1071. */ + +#include "complex_defs_double.inc" +#include "complex_regs.inc" diff --git a/deps/libffi/testsuite/libffi.complex/complex_regs_float.c b/deps/libffi/testsuite/libffi.complex/complex_regs_float.c new file mode 100644 index 000000000000..a7015c41d21b --- /dev/null +++ b/deps/libffi/testsuite/libffi.complex/complex_regs_float.c @@ -0,0 +1,11 @@ +/* Area: ffi_call, closure_call + Purpose: Check complex arguments after the argument registers run low. + Limitations: none. + PR: none. */ + +/* { dg-do run { xfail mips64*-*-* } } */ +/* XFAIL: mips N64 ABI bug in complex-float/longdouble args and fp-struct + returns; see libffi issue #1071. */ + +#include "complex_defs_float.inc" +#include "complex_regs.inc" diff --git a/deps/libffi/testsuite/libffi.complex/complex_regs_longdouble.c b/deps/libffi/testsuite/libffi.complex/complex_regs_longdouble.c new file mode 100644 index 000000000000..b5e3082c7e9c --- /dev/null +++ b/deps/libffi/testsuite/libffi.complex/complex_regs_longdouble.c @@ -0,0 +1,11 @@ +/* Area: ffi_call, closure_call + Purpose: Check complex arguments after the argument registers run low. + Limitations: none. + PR: none. */ + +/* { dg-do run { xfail mips64*-*-* } } */ +/* XFAIL: mips N64 ABI bug in complex-float/longdouble args and fp-struct + returns; see libffi issue #1071. */ + +#include "complex_defs_longdouble.inc" +#include "complex_regs.inc" diff --git a/deps/libffi/testsuite/libffi.configure/libdir.sh b/deps/libffi/testsuite/libffi.configure/libdir.sh new file mode 100755 index 000000000000..0232593539f2 --- /dev/null +++ b/deps/libffi/testsuite/libffi.configure/libdir.sh @@ -0,0 +1,61 @@ +#!/bin/sh + +set -eu + +srcdir=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd) +test_root=$(mktemp -d "${TMPDIR:-/tmp}/libffi-libdir.XXXXXX") +trap 'rm -rf "$test_root"' EXIT HUP INT TERM + +cat > "$test_root/cc" <<'EOF' +#!/bin/sh +for arg do + if test "$arg" = -print-multi-os-directory; then + echo ../lib64 + exit 0 + fi +done +exec gcc "$@" +EOF +chmod +x "$test_root/cc" + +mkdir "$test_root/default" "$test_root/disabled" + +( + cd "$test_root/default" + CC="$test_root/cc" "$srcdir/configure" --disable-builddir >/dev/null +) +grep -Fqx 'toolexeclibdir = ${libdir}/../lib64' \ + "$test_root/default/Makefile" + +( + cd "$test_root/disabled" + CC="$test_root/cc" "$srcdir/configure" --disable-builddir \ + --disable-multi-os-directory >/dev/null +) +grep -Fqx 'toolexeclibdir = ${libdir}' "$test_root/disabled/Makefile" + +check_explicit_libdir() +{ + name=$1 + shift + builddir="$test_root/$name" + mkdir "$builddir" + ( + cd "$builddir" + CC="$test_root/cc" "$srcdir/configure" --disable-builddir "$@" \ + >/dev/null + ) + grep -Fqx 'libdir = /test/custom lib' "$builddir/Makefile" + grep -Fqx 'toolexeclibdir = ${libdir}' "$builddir/Makefile" +} + +# Keep this list synchronized with the libdir spellings accepted by the +# generated configure option parser. +check_explicit_libdir long-equals '--libdir=/test/custom lib' +check_explicit_libdir long-separate --libdir '/test/custom lib' +check_explicit_libdir libdi-equals '--libdi=/test/custom lib' +check_explicit_libdir libdi-separate --libdi '/test/custom lib' +check_explicit_libdir libd-equals '--libd=/test/custom lib' +check_explicit_libdir libd-separate --libd '/test/custom lib' +check_explicit_libdir single-equals '-libdir=/test/custom lib' +check_explicit_libdir single-separate -libdir '/test/custom lib' diff --git a/deps/libffi/testsuite/libffi.jspi/cls_jspi.c b/deps/libffi/testsuite/libffi.jspi/cls_jspi.c new file mode 100644 index 000000000000..518297dfe9fb --- /dev/null +++ b/deps/libffi/testsuite/libffi.jspi/cls_jspi.c @@ -0,0 +1,175 @@ +/* Area: closure_call + Purpose: Check that a closure handler can suspend with JSPI. + Limitations: Emscripten only, needs -sJSPI and a JSPI-enabled engine. + PR: none. + Originator: Hood Chatham 20260912 */ + +/* { dg-do run { target wasm*-*-* } } */ +#include "ffitest.h" +#include <emscripten.h> + +/* JSPI suspends the whole wasm stack while the promise is pending. That + only works if every frame between the JSPI entry point (main) and the + suspending import is a wasm frame, so the closure trampoline must not + be a JS function. Exercise each kind of trampoline epilogue: void, + return-by-pointer (struct), i32, i64, f32, f64. */ + +EM_ASYNC_JS(int, async_add_one, (int x), { + await new Promise(resolve => setTimeout(resolve, 1)); + return x + 1; +}); + +static int n_calls = 0; + +typedef struct { double a; int b; long long c; } big_t; + +static void int_fn(ffi_cif *cif __UNUSED__, void *ret, void **args, + void *userdata) +{ + int x = *(int *)args[0]; + short y = *(short *)args[1]; + n_calls++; + *(ffi_arg *)ret = async_add_one(x) * 10 + y + *(int *)userdata; +} + +static void double_fn(ffi_cif *cif __UNUSED__, void *ret, void **args, + void *userdata __UNUSED__) +{ + n_calls++; + *(double *)ret = async_add_one((int)*(double *)args[0]) + 0.5; +} + +static void float_fn(ffi_cif *cif __UNUSED__, void *ret, void **args, + void *userdata __UNUSED__) +{ + n_calls++; + *(float *)ret = async_add_one((int)*(float *)args[0]) + 0.25f; +} + +static void i64_fn(ffi_cif *cif __UNUSED__, void *ret, void **args, + void *userdata __UNUSED__) +{ + long long x = *(long long *)args[0]; + n_calls++; + *(long long *)ret = ((long long)async_add_one((int)x) << 40) | 7; +} + +static void struct_fn(ffi_cif *cif __UNUSED__, void *ret, void **args, + void *userdata __UNUSED__) +{ + big_t in = *(big_t *)args[0]; + big_t *out = ret; + n_calls++; + out->a = in.a * 2; + out->b = async_add_one(in.b); + out->c = in.c + 1; +} + +static void void_fn(ffi_cif *cif __UNUSED__, void *ret __UNUSED__, + void **args, void *userdata) +{ + n_calls++; + *(int *)userdata = async_add_one(*(int *)args[0]); +} + +int main (void) +{ + ffi_cif cif; + void *code; + ffi_closure *pcl; + int ud = 1000; + + /* int f(int, short) */ + { + ffi_type *cl_arg_types[] = { &ffi_type_sint, &ffi_type_sshort }; + int (*f)(int, short); + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, + &ffi_type_sint, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, int_fn, &ud, code) == FFI_OK); + f = code; + CHECK(f(4, 3) == 50 + 3 + 1000); + CHECK(f(-2, -1) == -10 - 1 + 1000); + /* Nested: a suspending closure call inside the arguments of another. */ + CHECK(f(f(0, 0) - 1000, 1) == 110 + 1 + 1000); + ffi_closure_free(pcl); + } + + /* double f(double) */ + { + ffi_type *cl_arg_types[] = { &ffi_type_double }; + double (*f)(double); + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_double, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, double_fn, NULL, code) == FFI_OK); + f = code; + CHECK(f(2.0) == 3.5); + ffi_closure_free(pcl); + } + + /* float f(float) */ + { + ffi_type *cl_arg_types[] = { &ffi_type_float }; + float (*f)(float); + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_float, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, float_fn, NULL, code) == FFI_OK); + f = code; + CHECK(f(2.0f) == 3.25f); + ffi_closure_free(pcl); + } + + /* long long f(long long) */ + { + ffi_type *cl_arg_types[] = { &ffi_type_sint64 }; + long long (*f)(long long); + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_sint64, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, i64_fn, NULL, code) == FFI_OK); + f = code; + CHECK(f(5) == ((6LL << 40) | 7)); + ffi_closure_free(pcl); + } + + /* big_t f(big_t): returned through a pointer argument. */ + { + ffi_type *elements[] = { &ffi_type_double, &ffi_type_sint, + &ffi_type_sint64, NULL }; + ffi_type big = { 0, 0, FFI_TYPE_STRUCT, elements }; + ffi_type *cl_arg_types[] = { &big }; + big_t (*f)(big_t); + big_t in = { 1.5, 10, 1LL << 33 }; + big_t out; + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, &big, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, struct_fn, NULL, code) == FFI_OK); + f = code; + out = f(in); + CHECK(out.a == 3.0); + CHECK(out.b == 11); + CHECK(out.c == (1LL << 33) + 1); + ffi_closure_free(pcl); + } + + /* void f(int) */ + { + ffi_type *cl_arg_types[] = { &ffi_type_sint }; + void (*f)(int); + int result = 0; + pcl = ffi_closure_alloc(sizeof(ffi_closure), &code); + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 1, + &ffi_type_void, cl_arg_types) == FFI_OK); + CHECK(ffi_prep_closure_loc(pcl, &cif, void_fn, &result, code) == FFI_OK); + f = code; + f(41); + CHECK(result == 42); + ffi_closure_free(pcl); + } + + printf("%d closure calls\n", n_calls); + /* { dg-output "9 closure calls" } */ + exit(0); +} diff --git a/deps/libffi/testsuite/libffi.jspi/ffitest.h b/deps/libffi/testsuite/libffi.jspi/ffitest.h new file mode 100644 index 000000000000..d27d362d6a6e --- /dev/null +++ b/deps/libffi/testsuite/libffi.jspi/ffitest.h @@ -0,0 +1 @@ +#include "../libffi.call/ffitest.h" diff --git a/deps/libffi/testsuite/libffi.jspi/jspi.exp b/deps/libffi/testsuite/libffi.jspi/jspi.exp new file mode 100644 index 000000000000..f298e98c1531 --- /dev/null +++ b/deps/libffi/testsuite/libffi.jspi/jspi.exp @@ -0,0 +1,42 @@ +# Copyright (C) 2003, 2006, 2009, 2010, 2014, 2019 Free Software Foundation, Inc. +# Copyright (C) 2019 Anthony Green + +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; see the file COPYING3. If not see +# <http://www.gnu.org/licenses/>. + +# Tests for Emscripten's JavaScript Promise Integration (JSPI). These +# build with -sJSPI and need a JS engine with JSPI enabled to run. + +dg-init +libffi-init + +global srcdir subdir + +set tlist [lsort [glob -nocomplain -- $srcdir/$subdir/*.c]] + +# JSPI only exists on Emscripten. emcc warns that -sJSPI is experimental, +# which would otherwise count as an excess error. +if { [istarget "wasm*-*-*"] } { + run-many-tests $tlist "-sJSPI -Wno-experimental" +} else { + foreach test $tlist { + unsupported "$test" + } +} + +dg-finish + +# Local Variables: +# tcl-indent-level:4 +# End: diff --git a/deps/libffi/testsuite/libffi.threads/tsan.c b/deps/libffi/testsuite/libffi.threads/tsan.c index 168b2f84ba80..52b5204ce17b 100644 --- a/deps/libffi/testsuite/libffi.threads/tsan.c +++ b/deps/libffi/testsuite/libffi.threads/tsan.c @@ -8,6 +8,8 @@ #define NUM_THREADS 20 +static char thread_failure; + #if defined(_POSIX_BARRIERS) && _POSIX_BARRIERS > 0 pthread_barrier_t barrier; #endif @@ -30,14 +32,14 @@ void *thread_func(void *arg) { if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &ffi_type_float, args) != FFI_OK) { fprintf(stderr, "ffi_prep_cif failed\n"); - return NULL; + return &thread_failure; } ffi_closure *closure = ffi_closure_alloc(sizeof(ffi_closure), (void **)&arg); if (ffi_prep_closure_loc(closure, &cif, callback, NULL, arg) != FFI_OK) { fprintf(stderr, "ffi_prep_closure_loc failed\n"); - return NULL; + return &thread_failure; } callback_fn fn = (callback_fn)arg; @@ -62,7 +64,13 @@ int main() { } for (int i = 0; i < NUM_THREADS; ++i) { - pthread_join(threads[i], NULL); + void *result; + if (pthread_join(threads[i], &result) != 0) { + fprintf(stderr, "pthread_join failed\n"); + exit(EXIT_FAILURE); + } + if (result == &thread_failure) + exit(EXIT_FAILURE); } #if defined(_POSIX_BARRIERS) && _POSIX_BARRIERS > 0 diff --git a/deps/libffi/testsuite/libffi.vector/vector_float32x4.c b/deps/libffi/testsuite/libffi.vector/vector_float32x4.c index 971814aaf66c..c7b026671170 100644 --- a/deps/libffi/testsuite/libffi.vector/vector_float32x4.c +++ b/deps/libffi/testsuite/libffi.vector/vector_float32x4.c @@ -27,7 +27,8 @@ main (void) void *values[2]; f32x4 a = { 1, 2, 3, 4 }; f32x4 b = { 10, 20, 30, 40 }; - f32x4 r, ref; + f32x4 r, rp, ref; + ffi_call_plan *plan; int i; make_vector_type (&vec_type, vec_elems, &ffi_type_float, 4); @@ -43,11 +44,17 @@ main (void) ffi_call (&cif, FFI_FN (add_f32x4), &r, values); + plan = ffi_call_plan_alloc (&cif); + CHECK (plan != NULL); + ffi_call_plan_invoke (plan, FFI_FN (add_f32x4), &rp, values); + ffi_call_plan_free (plan); + ref = add_f32x4 (a, b); for (i = 0; i < 4; i++) { printf ("r[%d] = %g (want %g)\n", i, (double) r[i], (double) ref[i]); CHECK (r[i] == ref[i]); + CHECK (rp[i] == ref[i]); } exit (0); diff --git a/deps/libffi/testsuite/libffi.vector/vector_unsupported_abi.c b/deps/libffi/testsuite/libffi.vector/vector_unsupported_abi.c new file mode 100644 index 000000000000..d6e17910e152 --- /dev/null +++ b/deps/libffi/testsuite/libffi.vector/vector_unsupported_abi.c @@ -0,0 +1,105 @@ +/* Area: ffi_prep_cif + Purpose: On x86-64 System V, reject vector types whose calling + convention is undefined (so GCC and Clang disagree) with + FFI_BAD_TYPEDEF, while still accepting the shapes both + compilers agree on. Rejecting <1 x double> closes a + type-confusion that turned a caller's integer argument into + the store address of the return value (GHSA-5pc3-hr6f-q3mm). + Limitations: The classification is x86-64 System V specific, so the + assertions only run there; the test passes trivially on + other targets and ABIs. + PR: GHSA-5pc3-hr6f-q3mm. + Originator: libffi vector support. */ + +/* { dg-do run } */ + +#include "vector.h" + +#if defined(__x86_64__) && !defined(_WIN64) && !defined(__CYGWIN__) + +/* Expect ffi_prep_cif for RET f(ARG) to return STATUS. Either type may be + NULL to mean "no argument" / void return as appropriate. */ +static void +check_cif (ffi_type *ret, ffi_type *arg, ffi_status expected) +{ + ffi_cif cif; + ffi_type *args[1]; + unsigned nargs = 0; + + if (arg != NULL) + { + args[0] = arg; + nargs = 1; + } + CHECK (ffi_prep_cif (&cif, FFI_DEFAULT_ABI, nargs, + ret ? ret : &ffi_type_void, args) == expected); +} + +int +main (void) +{ + ffi_type vt, vt2; + ffi_type *elems[17], *elems2[17]; + ffi_type *selems[2]; + ffi_type st; + + /* --- Shapes with an undefined ABI: must be rejected. --- */ + + /* <1 x double> (8 bytes): GCC returns/passes it in memory, Clang in %xmm0. + This is the one that produced the out-of-bounds write. */ + make_vector_type (&vt, elems, &ffi_type_double, 1); + check_cif (&vt, NULL, FFI_BAD_TYPEDEF); /* as return value */ + check_cif (NULL, &vt, FFI_BAD_TYPEDEF); /* as argument */ + + /* <1 x float> (4 bytes): GCC memory, Clang INTEGER (%eax). */ + make_vector_type (&vt, elems, &ffi_type_float, 1); + check_cif (NULL, &vt, FFI_BAD_TYPEDEF); + + /* <4 x uint8> (4 bytes): sub-8-byte, unspecified. */ + make_vector_type (&vt, elems, &ffi_type_uint8, 4); + check_cif (NULL, &vt, FFI_BAD_TYPEDEF); + + /* A struct that contains <1 x double> must be rejected recursively. */ + make_vector_type (&vt, elems, &ffi_type_double, 1); + selems[0] = &vt; + selems[1] = NULL; + st.size = 0; + st.alignment = 0; + st.type = FFI_TYPE_STRUCT; + st.elements = selems; + check_cif (&st, NULL, FFI_BAD_TYPEDEF); + check_cif (NULL, &st, FFI_BAD_TYPEDEF); + + /* --- Shapes both compilers agree on: must still be accepted. --- */ + + /* <2 x float> (8 bytes, not <1 x double>) -> SSE on GCC and Clang. */ + make_vector_type (&vt, elems, &ffi_type_float, 2); + check_cif (&vt, NULL, FFI_OK); + check_cif (NULL, &vt, FFI_OK); + + /* <8 x uint8> (8 bytes) -> SSE on both. */ + make_vector_type (&vt, elems, &ffi_type_uint8, 8); + check_cif (NULL, &vt, FFI_OK); + + /* <4 x float> (16 bytes) -> SSE + SSEUP on both. */ + make_vector_type (&vt2, elems2, &ffi_type_float, 4); + check_cif (&vt2, NULL, FFI_OK); + check_cif (NULL, &vt2, FFI_OK); + + /* <2 x double> (16 bytes) -> SSE + SSEUP on both. */ + make_vector_type (&vt2, elems2, &ffi_type_double, 2); + check_cif (&vt2, NULL, FFI_OK); + + printf ("unsupported vector abi ok\n"); + exit (0); +} + +#else + +int +main (void) +{ + exit (0); +} + +#endif /* x86-64 System V */ diff --git a/deps/nbytes/.release-please-manifest.json b/deps/nbytes/.release-please-manifest.json index 88f7c73eadc7..18e45d5e23b5 100644 --- a/deps/nbytes/.release-please-manifest.json +++ b/deps/nbytes/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "0.1.4" + ".": "0.1.5" } diff --git a/deps/nbytes/CHANGELOG.md b/deps/nbytes/CHANGELOG.md index 5a740eb23506..f73416d574a9 100644 --- a/deps/nbytes/CHANGELOG.md +++ b/deps/nbytes/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## [0.1.5](https://github.com/nodejs/nbytes/compare/v0.1.4...v0.1.5) (2026-11-16) + + +### Bug Fixes + +* **base64, hex:** enhance decoding to ignore non-Latin1 characters ([#17](https://github.com/nodejs/nbytes/issues/17)) ([c0328e6](https://github.com/nodejs/nbytes/commit/c0328e6cc55b1aaae982d626c2f5a01f51cd2134)) + ## [0.1.4](https://github.com/nodejs/nbytes/compare/v0.1.3...v0.1.4) (2026-04-09) diff --git a/deps/nbytes/CMakeLists.txt b/deps/nbytes/CMakeLists.txt index b3d7c897b91e..9f71ba26d1c6 100644 --- a/deps/nbytes/CMakeLists.txt +++ b/deps/nbytes/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.28) -project(nbytes VERSION 0.1.4) # x-release-please-version +project(nbytes VERSION 0.1.5) # x-release-please-version set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED True) diff --git a/deps/nbytes/include/nbytes.h b/deps/nbytes/include/nbytes.h index 27f1449c6201..8a4260f97c43 100644 --- a/deps/nbytes/include/nbytes.h +++ b/deps/nbytes/include/nbytes.h @@ -109,6 +109,15 @@ bool SwapBytes64(char *data, size_t nbytes); extern const int8_t unbase64_table[256]; +// Code units above 0xFF are never base64 digits; do not truncate them. +template <typename TypeName> +inline int8_t Unbase64(TypeName c) { + if constexpr (sizeof(TypeName) > 1) { + if (c > 0xFF) return -1; + } + return unbase64_table[static_cast<uint8_t>(c)]; +} + template <typename TypeName> bool Base64DecodeGroupSlow(char *const dst, const size_t dstlen, const TypeName *const src, const size_t srclen, @@ -117,8 +126,8 @@ bool Base64DecodeGroupSlow(char *const dst, const size_t dstlen, uint8_t lo; #define V(expr) \ for (;;) { \ - const uint8_t c = static_cast<uint8_t>(src[*i]); \ - lo = unbase64_table[c]; \ + const TypeName c = src[*i]; \ + lo = Unbase64(c); \ *i += 1; \ if (lo < 64) break; /* Legal character. */ \ if (c == '=' || *i >= srclen) return false; /* Stop decoding. */ \ @@ -179,14 +188,10 @@ size_t Base64DecodeFast(char *const dst, const size_t dstlen, size_t k = 0; while (i < max_i && k < max_k) { const unsigned char txt[] = { - static_cast<unsigned char>( - unbase64_table[static_cast<uint8_t>(src[i + 0])]), - static_cast<unsigned char>( - unbase64_table[static_cast<uint8_t>(src[i + 1])]), - static_cast<unsigned char>( - unbase64_table[static_cast<uint8_t>(src[i + 2])]), - static_cast<unsigned char>( - unbase64_table[static_cast<uint8_t>(src[i + 3])]), + static_cast<unsigned char>(Unbase64(src[i + 0])), + static_cast<unsigned char>(Unbase64(src[i + 1])), + static_cast<unsigned char>(Unbase64(src[i + 2])), + static_cast<unsigned char>(Unbase64(src[i + 3])), }; const uint32_t v = ReadUint32BE(txt); @@ -224,13 +229,22 @@ size_t Base64Decode(char *const dst, const size_t dstlen, extern const int8_t unhex_table[256]; +// Code units above 0xFF are never hex digits; do not truncate them. +template <typename TypeName> +inline int8_t Unhex(TypeName c) { + if constexpr (sizeof(TypeName) > 1) { + if (c > 0xFF) return -1; + } + return unhex_table[static_cast<uint8_t>(c)]; +} + template <typename TypeName> static size_t HexDecode(char *buf, size_t len, const TypeName *src, const size_t srcLen) { size_t i; for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = unhex_table[static_cast<uint8_t>(src[i * 2 + 0])]; - unsigned b = unhex_table[static_cast<uint8_t>(src[i * 2 + 1])]; + unsigned a = Unhex(src[i * 2 + 0]); + unsigned b = Unhex(src[i * 2 + 1]); if (!~a || !~b) return i; buf[i] = (a << 4) | b; } @@ -836,12 +850,12 @@ size_t SearchString(const char *haystack, size_t haystack_length, // ============================================================================ // Version metadata -#define NBYTES_VERSION "0.1.4" // x-release-please-version +#define NBYTES_VERSION "0.1.5" // x-release-please-version enum { NBYTES_VERSION_MAJOR = 0, // x-release-please-major NBYTES_VERSION_MINOR = 1, // x-release-please-minor - NBYTES_VERSION_REVISION = 4, // x-release-please-patch + NBYTES_VERSION_REVISION = 5, // x-release-please-patch }; } // namespace nbytes diff --git a/deps/nbytes/tests/basic.cpp b/deps/nbytes/tests/basic.cpp index f0ed0a9f0014..a81b94d6b1aa 100644 --- a/deps/nbytes/tests/basic.cpp +++ b/deps/nbytes/tests/basic.cpp @@ -27,3 +27,36 @@ TEST(basic, swap_bytes64) { EXPECT_EQ(input, expected); SUCCEED(); } + +TEST(base64, decode_two_byte_ignores_non_latin1) { + // U+4E2D has the low byte 0x2D ('-'); it must not decode as a base64 digit. + const char16_t input[] = u"QUJD\u4E2DREVG"; + char out[16] = {}; + size_t n = nbytes::Base64Decode(out, sizeof(out), input, 9); + EXPECT_EQ(std::string(out, n), "ABCDEF"); +} + +TEST(base64, decode_two_byte_does_not_stop_on_low_byte_padding) { + // U+013D has the low byte 0x3D ('='); it must not end the decoding. + const char16_t input[] = u"QUJD\u013DREVG"; + char out[16] = {}; + size_t n = nbytes::Base64Decode(out, sizeof(out), input, 9); + EXPECT_EQ(std::string(out, n), "ABCDEF"); +} + +TEST(base64, decode_two_byte_all_non_latin1_is_empty) { + // Four U+4E2D units form a full group in the fast path; the output must + // still be empty rather than the bytes of "----". + const char16_t input[] = u"\u4E2D\u4E2D\u4E2D\u4E2D"; + char out[16] = {}; + size_t n = nbytes::Base64Decode(out, sizeof(out), input, 4); + EXPECT_EQ(n, 0u); +} + +TEST(hex, decode_two_byte_rejects_non_latin1) { + // U+0141 has the low byte 0x41 ('A'); it is not a hex digit. + const char16_t input[] = u"\u0141\u0141"; + char out[4] = {}; + size_t n = nbytes::HexDecode(out, sizeof(out), input, 2); + EXPECT_EQ(n, 0u); +} diff --git a/deps/ncrypto/ncrypto.cc b/deps/ncrypto/ncrypto.cc index ba800fa816c4..55fe562cfd5e 100644 --- a/deps/ncrypto/ncrypto.cc +++ b/deps/ncrypto/ncrypto.cc @@ -3607,6 +3607,8 @@ const BoringSSLKeyAlgorithm kBoringSSLKeyAlgorithms[] = { {KeyAlgorithm::ML_DSA_87.name(), EVP_PKEY_ML_DSA_87, EVP_pkey_ml_dsa_87}, {KeyAlgorithm::ML_KEM_768.name(), EVP_PKEY_ML_KEM_768, EVP_pkey_ml_kem_768}, {KeyAlgorithm::ML_KEM_1024.name(), EVP_PKEY_ML_KEM_1024, EVP_pkey_ml_kem_1024}, + {KeyAlgorithm::SLH_DSA_SHA2_128S.name(), EVP_PKEY_SLH_DSA_SHA2_128S, EVP_pkey_slh_dsa_sha2_128s}, + {KeyAlgorithm::SLH_DSA_SHAKE_256F.name(), EVP_PKEY_SLH_DSA_SHAKE_256F, EVP_pkey_slh_dsa_shake_256f}, }; // NOLINTEND(whitespace/line_length) // clang-format on @@ -5194,7 +5196,7 @@ SSLPointer SSLPointer::New(const SSLCtxPointer& ctx) { void SSLPointer::getCiphers(std::function<void(const char*)> cb) const { if (!ssl_) return; - STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(get()); + const STACK_OF(SSL_CIPHER)* ciphers = SSL_get_ciphers(get()); // TLSv1.3 ciphers aren't listed by EVP. There are only 5, we could just // document them, but since there are only 5, easier to just add them manually diff --git a/deps/npm/docs/content/commands/npm-ci.md b/deps/npm/docs/content/commands/npm-ci.md index af76af434cba..a4b260b5a6f6 100644 --- a/deps/npm/docs/content/commands/npm-ci.md +++ b/deps/npm/docs/content/commands/npm-ci.md @@ -324,6 +324,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm-exec.md b/deps/npm/docs/content/commands/npm-exec.md index 95789626f283..fd17f3852067 100644 --- a/deps/npm/docs/content/commands/npm-exec.md +++ b/deps/npm/docs/content/commands/npm-exec.md @@ -199,6 +199,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm-install-ci-test.md b/deps/npm/docs/content/commands/npm-install-ci-test.md index 0103ca86ac5c..d65fe2dca1aa 100644 --- a/deps/npm/docs/content/commands/npm-install-ci-test.md +++ b/deps/npm/docs/content/commands/npm-install-ci-test.md @@ -278,6 +278,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm-install-scripts.md b/deps/npm/docs/content/commands/npm-install-scripts.md index 4182392c9a3d..1dbfa4ecc4df 100644 --- a/deps/npm/docs/content/commands/npm-install-scripts.md +++ b/deps/npm/docs/content/commands/npm-install-scripts.md @@ -28,6 +28,9 @@ Dependency install scripts are blocked by default. Install commands silently skip lifecycle scripts for any dependency that does not have a matching entry in `allowScripts`, and end with a list of the packages whose scripts were skipped so you can review them here. +These warnings omit disconnected unused entries that installation cannot +build. Local link targets that can still be rebuilt remain subject to the +policy. This command only works inside a project that has a `package.json`. Running it with `--global` (`-g`) fails with an `EGLOBAL` error, since global @@ -62,6 +65,9 @@ unreviewed install scripts. `ls` is read-only: it lists every package whose install scripts are not yet covered by `allowScripts`, without modifying `package.json`. +This includes unreviewed extraneous packages, which are installed but not +required by any dependency. These packages can still cause +`npm rebuild --strict-allow-scripts` to fail. `prune` removes `allowScripts` entries that no longer match an installed package with an install script, either because the package is no longer diff --git a/deps/npm/docs/content/commands/npm-install-test.md b/deps/npm/docs/content/commands/npm-install-test.md index ed5ed2bd03f5..175bb7c4544c 100644 --- a/deps/npm/docs/content/commands/npm-install-test.md +++ b/deps/npm/docs/content/commands/npm-install-test.md @@ -355,6 +355,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm-install.md b/deps/npm/docs/content/commands/npm-install.md index 19efd10b7112..2aaa1697d762 100644 --- a/deps/npm/docs/content/commands/npm-install.md +++ b/deps/npm/docs/content/commands/npm-install.md @@ -696,6 +696,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm-ls.md b/deps/npm/docs/content/commands/npm-ls.md index 7a0a37f855b2..ca18270b8139 100644 --- a/deps/npm/docs/content/commands/npm-ls.md +++ b/deps/npm/docs/content/commands/npm-ls.md @@ -23,7 +23,7 @@ Note that nested packages will *also* show the paths to the specified packages. For example, running `npm ls promzard` in npm's source tree will show: ```bash -npm@12.2.2 /path/to/npm +npm@12.2.3 /path/to/npm └─┬ init-package-json@0.0.4 └── promzard@0.1.5 ``` diff --git a/deps/npm/docs/content/commands/npm-rebuild.md b/deps/npm/docs/content/commands/npm-rebuild.md index f3107c605672..b6e71568f51b 100644 --- a/deps/npm/docs/content/commands/npm-rebuild.md +++ b/deps/npm/docs/content/commands/npm-rebuild.md @@ -144,6 +144,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm-update.md b/deps/npm/docs/content/commands/npm-update.md index 1dd224318f98..3eeb3e0559b1 100644 --- a/deps/npm/docs/content/commands/npm-update.md +++ b/deps/npm/docs/content/commands/npm-update.md @@ -353,6 +353,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `dangerously-allow-all-scripts` diff --git a/deps/npm/docs/content/commands/npm.md b/deps/npm/docs/content/commands/npm.md index a8717a3a14d1..2aab25113cf8 100644 --- a/deps/npm/docs/content/commands/npm.md +++ b/deps/npm/docs/content/commands/npm.md @@ -14,7 +14,7 @@ Note: This command is unaware of workspaces. ### Version -12.2.2 +12.2.3 ### Description diff --git a/deps/npm/docs/content/using-npm/config.md b/deps/npm/docs/content/using-npm/config.md index 8d8d0af983de..49ba469ff2da 100644 --- a/deps/npm/docs/content/using-npm/config.md +++ b/deps/npm/docs/content/using-npm/config.md @@ -2040,6 +2040,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching `os`, `cpu`, or `libc`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. `npm rebuild` and `npm install-scripts ls` still check unused +packages on disk. + #### `strict-npmrc` diff --git a/deps/npm/docs/output/commands/npm-access.html b/deps/npm/docs/output/commands/npm-access.html index e8bc244d780f..5449a6f811f4 100644 --- a/deps/npm/docs/output/commands/npm-access.html +++ b/deps/npm/docs/output/commands/npm-access.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-access----1222"> +<h1 id="----npm-access----1223"> <span>npm-access</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Set access level on published packages</span> </header> diff --git a/deps/npm/docs/output/commands/npm-approve-scripts.html b/deps/npm/docs/output/commands/npm-approve-scripts.html index 25de4b91fc2f..731b6b2d64c9 100644 --- a/deps/npm/docs/output/commands/npm-approve-scripts.html +++ b/deps/npm/docs/output/commands/npm-approve-scripts.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-approve-scripts----1222"> +<h1 id="----npm-approve-scripts----1223"> <span>npm-approve-scripts</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Approve install scripts for specific dependencies</span> </header> diff --git a/deps/npm/docs/output/commands/npm-audit.html b/deps/npm/docs/output/commands/npm-audit.html index af1a3c82a9a5..1fbc29d4b723 100644 --- a/deps/npm/docs/output/commands/npm-audit.html +++ b/deps/npm/docs/output/commands/npm-audit.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-audit----1222"> +<h1 id="----npm-audit----1223"> <span>npm-audit</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Run a security audit</span> </header> diff --git a/deps/npm/docs/output/commands/npm-bugs.html b/deps/npm/docs/output/commands/npm-bugs.html index b51e7d05a905..5cf5136b11c1 100644 --- a/deps/npm/docs/output/commands/npm-bugs.html +++ b/deps/npm/docs/output/commands/npm-bugs.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-bugs----1222"> +<h1 id="----npm-bugs----1223"> <span>npm-bugs</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Report bugs for a package in a web browser</span> </header> diff --git a/deps/npm/docs/output/commands/npm-cache.html b/deps/npm/docs/output/commands/npm-cache.html index 1e786028ba5f..e7d0c0151939 100644 --- a/deps/npm/docs/output/commands/npm-cache.html +++ b/deps/npm/docs/output/commands/npm-cache.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-cache----1222"> +<h1 id="----npm-cache----1223"> <span>npm-cache</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manipulates packages cache</span> </header> diff --git a/deps/npm/docs/output/commands/npm-ci.html b/deps/npm/docs/output/commands/npm-ci.html index 5ad424ab03c9..3f66ba2b770e 100644 --- a/deps/npm/docs/output/commands/npm-ci.html +++ b/deps/npm/docs/output/commands/npm-ci.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-ci----1222"> +<h1 id="----npm-ci----1223"> <span>npm-ci</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Clean install a project</span> </header> @@ -441,6 +441,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-completion.html b/deps/npm/docs/output/commands/npm-completion.html index 1cf6ffa7c6f1..ee8f2e3df4fd 100644 --- a/deps/npm/docs/output/commands/npm-completion.html +++ b/deps/npm/docs/output/commands/npm-completion.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-completion----1222"> +<h1 id="----npm-completion----1223"> <span>npm-completion</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Tab Completion for npm</span> </header> diff --git a/deps/npm/docs/output/commands/npm-config.html b/deps/npm/docs/output/commands/npm-config.html index 6cb35feff113..4b08a07ca6b2 100644 --- a/deps/npm/docs/output/commands/npm-config.html +++ b/deps/npm/docs/output/commands/npm-config.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-config----1222"> +<h1 id="----npm-config----1223"> <span>npm-config</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage the npm configuration files</span> </header> diff --git a/deps/npm/docs/output/commands/npm-dedupe.html b/deps/npm/docs/output/commands/npm-dedupe.html index f7e29d2ba60e..64ff03a22f82 100644 --- a/deps/npm/docs/output/commands/npm-dedupe.html +++ b/deps/npm/docs/output/commands/npm-dedupe.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-dedupe----1222"> +<h1 id="----npm-dedupe----1223"> <span>npm-dedupe</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Reduce duplication in the package tree</span> </header> diff --git a/deps/npm/docs/output/commands/npm-deny-scripts.html b/deps/npm/docs/output/commands/npm-deny-scripts.html index deb3085d2e1c..40856fa1c7a7 100644 --- a/deps/npm/docs/output/commands/npm-deny-scripts.html +++ b/deps/npm/docs/output/commands/npm-deny-scripts.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-deny-scripts----1222"> +<h1 id="----npm-deny-scripts----1223"> <span>npm-deny-scripts</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Deny install scripts for specific dependencies</span> </header> diff --git a/deps/npm/docs/output/commands/npm-deprecate.html b/deps/npm/docs/output/commands/npm-deprecate.html index abd3039a41ce..73a217b27300 100644 --- a/deps/npm/docs/output/commands/npm-deprecate.html +++ b/deps/npm/docs/output/commands/npm-deprecate.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-deprecate----1222"> +<h1 id="----npm-deprecate----1223"> <span>npm-deprecate</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Deprecate a version of a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-diff.html b/deps/npm/docs/output/commands/npm-diff.html index 801877eecd9c..1f617c050ba5 100644 --- a/deps/npm/docs/output/commands/npm-diff.html +++ b/deps/npm/docs/output/commands/npm-diff.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-diff----1222"> +<h1 id="----npm-diff----1223"> <span>npm-diff</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">The registry diff command</span> </header> diff --git a/deps/npm/docs/output/commands/npm-dist-tag.html b/deps/npm/docs/output/commands/npm-dist-tag.html index 066ade7afb76..c45107e237e5 100644 --- a/deps/npm/docs/output/commands/npm-dist-tag.html +++ b/deps/npm/docs/output/commands/npm-dist-tag.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-dist-tag----1222"> +<h1 id="----npm-dist-tag----1223"> <span>npm-dist-tag</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Modify package distribution tags</span> </header> diff --git a/deps/npm/docs/output/commands/npm-docs.html b/deps/npm/docs/output/commands/npm-docs.html index a799607fc296..46d0e731a598 100644 --- a/deps/npm/docs/output/commands/npm-docs.html +++ b/deps/npm/docs/output/commands/npm-docs.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-docs----1222"> +<h1 id="----npm-docs----1223"> <span>npm-docs</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Open documentation for a package in a web browser</span> </header> diff --git a/deps/npm/docs/output/commands/npm-doctor.html b/deps/npm/docs/output/commands/npm-doctor.html index 6c8a259191ce..e3aa4d8a0224 100644 --- a/deps/npm/docs/output/commands/npm-doctor.html +++ b/deps/npm/docs/output/commands/npm-doctor.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-doctor----1222"> +<h1 id="----npm-doctor----1223"> <span>npm-doctor</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Check the health of your npm environment</span> </header> diff --git a/deps/npm/docs/output/commands/npm-edit.html b/deps/npm/docs/output/commands/npm-edit.html index d1d51c0425f5..fe7c2b05f442 100644 --- a/deps/npm/docs/output/commands/npm-edit.html +++ b/deps/npm/docs/output/commands/npm-edit.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-edit----1222"> +<h1 id="----npm-edit----1223"> <span>npm-edit</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Edit an installed package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-exec.html b/deps/npm/docs/output/commands/npm-exec.html index 6aed95ce18e7..67d6d7700d06 100644 --- a/deps/npm/docs/output/commands/npm-exec.html +++ b/deps/npm/docs/output/commands/npm-exec.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-exec----1222"> +<h1 id="----npm-exec----1223"> <span>npm-exec</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Run a command from a local or remote npm package</span> </header> @@ -341,6 +341,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-explain.html b/deps/npm/docs/output/commands/npm-explain.html index 602b4ecd715d..70f25234b631 100644 --- a/deps/npm/docs/output/commands/npm-explain.html +++ b/deps/npm/docs/output/commands/npm-explain.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-explain----1222"> +<h1 id="----npm-explain----1223"> <span>npm-explain</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Explain installed packages</span> </header> diff --git a/deps/npm/docs/output/commands/npm-explore.html b/deps/npm/docs/output/commands/npm-explore.html index e0aed4e1fa53..444fc436b27f 100644 --- a/deps/npm/docs/output/commands/npm-explore.html +++ b/deps/npm/docs/output/commands/npm-explore.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-explore----1222"> +<h1 id="----npm-explore----1223"> <span>npm-explore</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Browse an installed package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-find-dupes.html b/deps/npm/docs/output/commands/npm-find-dupes.html index 1544c271508f..5b9582bd8dee 100644 --- a/deps/npm/docs/output/commands/npm-find-dupes.html +++ b/deps/npm/docs/output/commands/npm-find-dupes.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-find-dupes----1222"> +<h1 id="----npm-find-dupes----1223"> <span>npm-find-dupes</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Find duplication in the package tree</span> </header> diff --git a/deps/npm/docs/output/commands/npm-fund.html b/deps/npm/docs/output/commands/npm-fund.html index 78b38fd33cba..9380eeff9d00 100644 --- a/deps/npm/docs/output/commands/npm-fund.html +++ b/deps/npm/docs/output/commands/npm-fund.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-fund----1222"> +<h1 id="----npm-fund----1223"> <span>npm-fund</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Retrieve funding information</span> </header> diff --git a/deps/npm/docs/output/commands/npm-get.html b/deps/npm/docs/output/commands/npm-get.html index a56684a1b2ce..726a51b9686f 100644 --- a/deps/npm/docs/output/commands/npm-get.html +++ b/deps/npm/docs/output/commands/npm-get.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-get----1222"> +<h1 id="----npm-get----1223"> <span>npm-get</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Get a value from the npm configuration</span> </header> diff --git a/deps/npm/docs/output/commands/npm-help-search.html b/deps/npm/docs/output/commands/npm-help-search.html index 7b8dc4930ad2..73fb370269e2 100644 --- a/deps/npm/docs/output/commands/npm-help-search.html +++ b/deps/npm/docs/output/commands/npm-help-search.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-help-search----1222"> +<h1 id="----npm-help-search----1223"> <span>npm-help-search</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Search npm help documentation</span> </header> diff --git a/deps/npm/docs/output/commands/npm-help.html b/deps/npm/docs/output/commands/npm-help.html index 63a2f3a65ac8..d9b14b25204f 100644 --- a/deps/npm/docs/output/commands/npm-help.html +++ b/deps/npm/docs/output/commands/npm-help.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-help----1222"> +<h1 id="----npm-help----1223"> <span>npm-help</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Get help on npm</span> </header> diff --git a/deps/npm/docs/output/commands/npm-init.html b/deps/npm/docs/output/commands/npm-init.html index 592eef7a233a..ab0313407855 100644 --- a/deps/npm/docs/output/commands/npm-init.html +++ b/deps/npm/docs/output/commands/npm-init.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-init----1222"> +<h1 id="----npm-init----1223"> <span>npm-init</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Create a package.json file</span> </header> diff --git a/deps/npm/docs/output/commands/npm-install-ci-test.html b/deps/npm/docs/output/commands/npm-install-ci-test.html index 7cfe3a02120c..b21f8198128c 100644 --- a/deps/npm/docs/output/commands/npm-install-ci-test.html +++ b/deps/npm/docs/output/commands/npm-install-ci-test.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-install-ci-test----1222"> +<h1 id="----npm-install-ci-test----1223"> <span>npm-install-ci-test</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Install a project with a clean slate and run tests</span> </header> @@ -406,6 +406,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-install-scripts.html b/deps/npm/docs/output/commands/npm-install-scripts.html index 03e65461f592..28936dc329b3 100644 --- a/deps/npm/docs/output/commands/npm-install-scripts.html +++ b/deps/npm/docs/output/commands/npm-install-scripts.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-install-scripts----1222"> +<h1 id="----npm-install-scripts----1223"> <span>npm-install-scripts</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage install-script approvals for dependencies</span> </header> @@ -215,7 +215,10 @@ <h3 id="description">Description</h3> <p>Dependency install scripts are blocked by default. Install commands silently skip lifecycle scripts for any dependency that does not have a matching entry in <code>allowScripts</code>, and end with a list of the packages -whose scripts were skipped so you can review them here.</p> +whose scripts were skipped so you can review them here. +These warnings omit disconnected unused entries that installation cannot +build. Local link targets that can still be rebuilt remain subject to the +policy.</p> <p>This command only works inside a project that has a <code>package.json</code>. Running it with <code>--global</code> (<code>-g</code>) fails with an <code>EGLOBAL</code> error, since global installs (<code>npm install -g</code>) and one-off executions (<code>npm exec</code> / <code>npx</code>) have @@ -242,7 +245,10 @@ <h3 id="description">Description</h3> package from any future blanket approval. <code>--all</code> denies every package with unreviewed install scripts.</p> <p><code>ls</code> is read-only: it lists every package whose install scripts are not yet -covered by <code>allowScripts</code>, without modifying <code>package.json</code>.</p> +covered by <code>allowScripts</code>, without modifying <code>package.json</code>. +This includes unreviewed extraneous packages, which are installed but not +required by any dependency. These packages can still cause +<code>npm rebuild --strict-allow-scripts</code> to fail.</p> <p><code>prune</code> removes <code>allowScripts</code> entries that no longer match an installed package with an install script, either because the package is no longer installed (a transitive dependency changed, or a pinned <code>pkg@1.2.3</code> was diff --git a/deps/npm/docs/output/commands/npm-install-test.html b/deps/npm/docs/output/commands/npm-install-test.html index 81f401fb63ec..0618f671e81d 100644 --- a/deps/npm/docs/output/commands/npm-install-test.html +++ b/deps/npm/docs/output/commands/npm-install-test.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-install-test----1222"> +<h1 id="----npm-install-test----1223"> <span>npm-install-test</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Install package(s) and run tests</span> </header> @@ -462,6 +462,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-install.html b/deps/npm/docs/output/commands/npm-install.html index f8debaf29c7e..86e1ef481f94 100644 --- a/deps/npm/docs/output/commands/npm-install.html +++ b/deps/npm/docs/output/commands/npm-install.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-install----1222"> +<h1 id="----npm-install----1223"> <span>npm-install</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Install a package</span> </header> @@ -736,6 +736,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-link.html b/deps/npm/docs/output/commands/npm-link.html index bd5868e09b5e..350c6eddb76b 100644 --- a/deps/npm/docs/output/commands/npm-link.html +++ b/deps/npm/docs/output/commands/npm-link.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-link----1222"> +<h1 id="----npm-link----1223"> <span>npm-link</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Symlink a package folder</span> </header> diff --git a/deps/npm/docs/output/commands/npm-ll.html b/deps/npm/docs/output/commands/npm-ll.html index f52019a5dd19..7f1321fb6d7e 100644 --- a/deps/npm/docs/output/commands/npm-ll.html +++ b/deps/npm/docs/output/commands/npm-ll.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-ll----1222"> +<h1 id="----npm-ll----1223"> <span>npm-ll</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">List installed packages</span> </header> diff --git a/deps/npm/docs/output/commands/npm-login.html b/deps/npm/docs/output/commands/npm-login.html index 11acf310b47a..9a7157c06250 100644 --- a/deps/npm/docs/output/commands/npm-login.html +++ b/deps/npm/docs/output/commands/npm-login.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-login----1222"> +<h1 id="----npm-login----1223"> <span>npm-login</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Login to a registry user account</span> </header> diff --git a/deps/npm/docs/output/commands/npm-logout.html b/deps/npm/docs/output/commands/npm-logout.html index 464313e2adbf..b2af9df0946b 100644 --- a/deps/npm/docs/output/commands/npm-logout.html +++ b/deps/npm/docs/output/commands/npm-logout.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-logout----1222"> +<h1 id="----npm-logout----1223"> <span>npm-logout</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Log out of the registry</span> </header> diff --git a/deps/npm/docs/output/commands/npm-ls.html b/deps/npm/docs/output/commands/npm-ls.html index a8a8831640ca..483b3fd8eb14 100644 --- a/deps/npm/docs/output/commands/npm-ls.html +++ b/deps/npm/docs/output/commands/npm-ls.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-ls----1222"> +<h1 id="----npm-ls----1223"> <span>npm-ls</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">List installed packages</span> </header> @@ -209,7 +209,7 @@ <h3 id="description">Description</h3> <p>Positional arguments are <code>name@version-range</code> identifiers, which will limit the results to only the paths to the packages named. Note that nested packages will <em>also</em> show the paths to the specified packages. For example, running <code>npm ls promzard</code> in npm's source tree will show:</p> -<pre><code class="language-bash">npm@12.2.2 /path/to/npm +<pre><code class="language-bash">npm@12.2.3 /path/to/npm └─┬ init-package-json@0.0.4 └── promzard@0.1.5 </code></pre> diff --git a/deps/npm/docs/output/commands/npm-org.html b/deps/npm/docs/output/commands/npm-org.html index 99cb4339b164..338253f5711b 100644 --- a/deps/npm/docs/output/commands/npm-org.html +++ b/deps/npm/docs/output/commands/npm-org.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-org----1222"> +<h1 id="----npm-org----1223"> <span>npm-org</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage orgs</span> </header> diff --git a/deps/npm/docs/output/commands/npm-outdated.html b/deps/npm/docs/output/commands/npm-outdated.html index 613b24e8bd64..acbd60ea2010 100644 --- a/deps/npm/docs/output/commands/npm-outdated.html +++ b/deps/npm/docs/output/commands/npm-outdated.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-outdated----1222"> +<h1 id="----npm-outdated----1223"> <span>npm-outdated</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Check for outdated packages</span> </header> diff --git a/deps/npm/docs/output/commands/npm-owner.html b/deps/npm/docs/output/commands/npm-owner.html index 9af22b69a867..e4afeb4a153c 100644 --- a/deps/npm/docs/output/commands/npm-owner.html +++ b/deps/npm/docs/output/commands/npm-owner.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-owner----1222"> +<h1 id="----npm-owner----1223"> <span>npm-owner</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage package owners</span> </header> diff --git a/deps/npm/docs/output/commands/npm-pack.html b/deps/npm/docs/output/commands/npm-pack.html index c970b43b5bb3..fb1d5f3bc765 100644 --- a/deps/npm/docs/output/commands/npm-pack.html +++ b/deps/npm/docs/output/commands/npm-pack.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-pack----1222"> +<h1 id="----npm-pack----1223"> <span>npm-pack</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Create a tarball from a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-patch.html b/deps/npm/docs/output/commands/npm-patch.html index 95f8ca03ed3f..7fd6f8d0667f 100644 --- a/deps/npm/docs/output/commands/npm-patch.html +++ b/deps/npm/docs/output/commands/npm-patch.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-patch----1222"> +<h1 id="----npm-patch----1223"> <span>npm-patch</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Apply local patches to installed dependencies</span> </header> diff --git a/deps/npm/docs/output/commands/npm-ping.html b/deps/npm/docs/output/commands/npm-ping.html index 2eb84b187218..505bcd8cdce4 100644 --- a/deps/npm/docs/output/commands/npm-ping.html +++ b/deps/npm/docs/output/commands/npm-ping.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-ping----1222"> +<h1 id="----npm-ping----1223"> <span>npm-ping</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Ping npm registry</span> </header> diff --git a/deps/npm/docs/output/commands/npm-pkg.html b/deps/npm/docs/output/commands/npm-pkg.html index 4e0e78e8a0d4..5b0dfe5c1500 100644 --- a/deps/npm/docs/output/commands/npm-pkg.html +++ b/deps/npm/docs/output/commands/npm-pkg.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-pkg----1222"> +<h1 id="----npm-pkg----1223"> <span>npm-pkg</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manages your package.json</span> </header> diff --git a/deps/npm/docs/output/commands/npm-prefix.html b/deps/npm/docs/output/commands/npm-prefix.html index 4754a80148cd..ed8434fc7c60 100644 --- a/deps/npm/docs/output/commands/npm-prefix.html +++ b/deps/npm/docs/output/commands/npm-prefix.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-prefix----1222"> +<h1 id="----npm-prefix----1223"> <span>npm-prefix</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Display prefix</span> </header> diff --git a/deps/npm/docs/output/commands/npm-profile.html b/deps/npm/docs/output/commands/npm-profile.html index a04049fa44be..803a00f2cec1 100644 --- a/deps/npm/docs/output/commands/npm-profile.html +++ b/deps/npm/docs/output/commands/npm-profile.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-profile----1222"> +<h1 id="----npm-profile----1223"> <span>npm-profile</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Change settings on your registry profile</span> </header> diff --git a/deps/npm/docs/output/commands/npm-prune.html b/deps/npm/docs/output/commands/npm-prune.html index 8a5965e94fe9..d1c86a59a6a3 100644 --- a/deps/npm/docs/output/commands/npm-prune.html +++ b/deps/npm/docs/output/commands/npm-prune.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-prune----1222"> +<h1 id="----npm-prune----1223"> <span>npm-prune</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Remove extraneous packages</span> </header> diff --git a/deps/npm/docs/output/commands/npm-publish.html b/deps/npm/docs/output/commands/npm-publish.html index 850f8ea16f88..d67876a8139e 100644 --- a/deps/npm/docs/output/commands/npm-publish.html +++ b/deps/npm/docs/output/commands/npm-publish.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-publish----1222"> +<h1 id="----npm-publish----1223"> <span>npm-publish</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Publish a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-query.html b/deps/npm/docs/output/commands/npm-query.html index fc702828c7d3..00318a3fc045 100644 --- a/deps/npm/docs/output/commands/npm-query.html +++ b/deps/npm/docs/output/commands/npm-query.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-query----1222"> +<h1 id="----npm-query----1223"> <span>npm-query</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Dependency selector query</span> </header> diff --git a/deps/npm/docs/output/commands/npm-rebuild.html b/deps/npm/docs/output/commands/npm-rebuild.html index a37087eee829..6356652a0291 100644 --- a/deps/npm/docs/output/commands/npm-rebuild.html +++ b/deps/npm/docs/output/commands/npm-rebuild.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-rebuild----1222"> +<h1 id="----npm-rebuild----1223"> <span>npm-rebuild</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Rebuild a package</span> </header> @@ -305,6 +305,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-repo.html b/deps/npm/docs/output/commands/npm-repo.html index 02f51b1f96a7..546c2177fe8d 100644 --- a/deps/npm/docs/output/commands/npm-repo.html +++ b/deps/npm/docs/output/commands/npm-repo.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-repo----1222"> +<h1 id="----npm-repo----1223"> <span>npm-repo</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Open package repository page in the browser</span> </header> diff --git a/deps/npm/docs/output/commands/npm-restart.html b/deps/npm/docs/output/commands/npm-restart.html index 62d66243bb62..12e975bc5fe2 100644 --- a/deps/npm/docs/output/commands/npm-restart.html +++ b/deps/npm/docs/output/commands/npm-restart.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-restart----1222"> +<h1 id="----npm-restart----1223"> <span>npm-restart</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Restart a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-root.html b/deps/npm/docs/output/commands/npm-root.html index 791f77c7a1dc..dc0871e017c6 100644 --- a/deps/npm/docs/output/commands/npm-root.html +++ b/deps/npm/docs/output/commands/npm-root.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-root----1222"> +<h1 id="----npm-root----1223"> <span>npm-root</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Display npm root</span> </header> diff --git a/deps/npm/docs/output/commands/npm-run.html b/deps/npm/docs/output/commands/npm-run.html index 4a893229f5f9..f82a68c59daa 100644 --- a/deps/npm/docs/output/commands/npm-run.html +++ b/deps/npm/docs/output/commands/npm-run.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-run----1222"> +<h1 id="----npm-run----1223"> <span>npm-run</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Run arbitrary package scripts</span> </header> diff --git a/deps/npm/docs/output/commands/npm-sbom.html b/deps/npm/docs/output/commands/npm-sbom.html index 4b740785316d..bd8df6437980 100644 --- a/deps/npm/docs/output/commands/npm-sbom.html +++ b/deps/npm/docs/output/commands/npm-sbom.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-sbom----1222"> +<h1 id="----npm-sbom----1223"> <span>npm-sbom</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Generate a Software Bill of Materials (SBOM)</span> </header> diff --git a/deps/npm/docs/output/commands/npm-search.html b/deps/npm/docs/output/commands/npm-search.html index e812a0e6287b..909fc5b7ac48 100644 --- a/deps/npm/docs/output/commands/npm-search.html +++ b/deps/npm/docs/output/commands/npm-search.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-search----1222"> +<h1 id="----npm-search----1223"> <span>npm-search</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Search for packages</span> </header> diff --git a/deps/npm/docs/output/commands/npm-set.html b/deps/npm/docs/output/commands/npm-set.html index d980e7d7bd17..f905da0f2e97 100644 --- a/deps/npm/docs/output/commands/npm-set.html +++ b/deps/npm/docs/output/commands/npm-set.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-set----1222"> +<h1 id="----npm-set----1223"> <span>npm-set</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Set a value in the npm configuration</span> </header> diff --git a/deps/npm/docs/output/commands/npm-stage.html b/deps/npm/docs/output/commands/npm-stage.html index af9b075b5299..626706f938ab 100644 --- a/deps/npm/docs/output/commands/npm-stage.html +++ b/deps/npm/docs/output/commands/npm-stage.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-stage----1222"> +<h1 id="----npm-stage----1223"> <span>npm-stage</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Stage packages for publishing</span> </header> diff --git a/deps/npm/docs/output/commands/npm-start.html b/deps/npm/docs/output/commands/npm-start.html index 77de290c4995..53c34d28a1b3 100644 --- a/deps/npm/docs/output/commands/npm-start.html +++ b/deps/npm/docs/output/commands/npm-start.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-start----1222"> +<h1 id="----npm-start----1223"> <span>npm-start</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Start a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-stop.html b/deps/npm/docs/output/commands/npm-stop.html index 3054cf5502c6..bacf3f6253c6 100644 --- a/deps/npm/docs/output/commands/npm-stop.html +++ b/deps/npm/docs/output/commands/npm-stop.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-stop----1222"> +<h1 id="----npm-stop----1223"> <span>npm-stop</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Stop a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-team.html b/deps/npm/docs/output/commands/npm-team.html index 8b2f9e77434c..92dd6c677ca5 100644 --- a/deps/npm/docs/output/commands/npm-team.html +++ b/deps/npm/docs/output/commands/npm-team.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-team----1222"> +<h1 id="----npm-team----1223"> <span>npm-team</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage organization teams and team memberships</span> </header> diff --git a/deps/npm/docs/output/commands/npm-test.html b/deps/npm/docs/output/commands/npm-test.html index 88b28fc373cb..becc549d00b9 100644 --- a/deps/npm/docs/output/commands/npm-test.html +++ b/deps/npm/docs/output/commands/npm-test.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-test----1222"> +<h1 id="----npm-test----1223"> <span>npm-test</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Test a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-token.html b/deps/npm/docs/output/commands/npm-token.html index 7b939a21559d..59993536dfa8 100644 --- a/deps/npm/docs/output/commands/npm-token.html +++ b/deps/npm/docs/output/commands/npm-token.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-token----1222"> +<h1 id="----npm-token----1223"> <span>npm-token</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage your authentication tokens</span> </header> diff --git a/deps/npm/docs/output/commands/npm-trust.html b/deps/npm/docs/output/commands/npm-trust.html index 707ed794b10f..c859f06d6c56 100644 --- a/deps/npm/docs/output/commands/npm-trust.html +++ b/deps/npm/docs/output/commands/npm-trust.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-trust----1222"> +<h1 id="----npm-trust----1223"> <span>npm-trust</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Manage trusted publishing relationships between packages and CI/CD providers</span> </header> diff --git a/deps/npm/docs/output/commands/npm-undeprecate.html b/deps/npm/docs/output/commands/npm-undeprecate.html index 1b35b155ec13..e6b97323eb48 100644 --- a/deps/npm/docs/output/commands/npm-undeprecate.html +++ b/deps/npm/docs/output/commands/npm-undeprecate.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-undeprecate----1222"> +<h1 id="----npm-undeprecate----1223"> <span>npm-undeprecate</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Undeprecate a version of a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-uninstall.html b/deps/npm/docs/output/commands/npm-uninstall.html index dcb9c30a4d75..89083df0db82 100644 --- a/deps/npm/docs/output/commands/npm-uninstall.html +++ b/deps/npm/docs/output/commands/npm-uninstall.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-uninstall----1222"> +<h1 id="----npm-uninstall----1223"> <span>npm-uninstall</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Remove a package</span> </header> diff --git a/deps/npm/docs/output/commands/npm-unpublish.html b/deps/npm/docs/output/commands/npm-unpublish.html index 52fc59ffb7aa..46cc2487ea66 100644 --- a/deps/npm/docs/output/commands/npm-unpublish.html +++ b/deps/npm/docs/output/commands/npm-unpublish.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-unpublish----1222"> +<h1 id="----npm-unpublish----1223"> <span>npm-unpublish</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Remove a package from the registry</span> </header> diff --git a/deps/npm/docs/output/commands/npm-update.html b/deps/npm/docs/output/commands/npm-update.html index 43c331216205..469e8820b9e1 100644 --- a/deps/npm/docs/output/commands/npm-update.html +++ b/deps/npm/docs/output/commands/npm-update.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-update----1222"> +<h1 id="----npm-update----1223"> <span>npm-update</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Update packages</span> </header> @@ -448,6 +448,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="dangerously-allow-all-scripts"><code>dangerously-allow-all-scripts</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/commands/npm-version.html b/deps/npm/docs/output/commands/npm-version.html index 6062c22b56ef..93cb28ab1367 100644 --- a/deps/npm/docs/output/commands/npm-version.html +++ b/deps/npm/docs/output/commands/npm-version.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-version----1222"> +<h1 id="----npm-version----1223"> <span>npm-version</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Bump a package version</span> </header> diff --git a/deps/npm/docs/output/commands/npm-view.html b/deps/npm/docs/output/commands/npm-view.html index 1d80c87ab452..77328a4e9d03 100644 --- a/deps/npm/docs/output/commands/npm-view.html +++ b/deps/npm/docs/output/commands/npm-view.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-view----1222"> +<h1 id="----npm-view----1223"> <span>npm-view</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">View registry info</span> </header> diff --git a/deps/npm/docs/output/commands/npm-whoami.html b/deps/npm/docs/output/commands/npm-whoami.html index 03727c5291dc..73e89e7b96a5 100644 --- a/deps/npm/docs/output/commands/npm-whoami.html +++ b/deps/npm/docs/output/commands/npm-whoami.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-whoami----1222"> +<h1 id="----npm-whoami----1223"> <span>npm-whoami</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Display npm username</span> </header> diff --git a/deps/npm/docs/output/commands/npm.html b/deps/npm/docs/output/commands/npm.html index 798e831ae48f..fa2a5b2b599f 100644 --- a/deps/npm/docs/output/commands/npm.html +++ b/deps/npm/docs/output/commands/npm.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm----1222"> +<h1 id="----npm----1223"> <span>npm</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">javascript package manager</span> </header> @@ -203,7 +203,7 @@ <h2 id="table-of-contents">Table of contents</h2> </code></pre> <p>Note: This command is unaware of workspaces.</p> <h3 id="version">Version</h3> -<p>12.2.2</p> +<p>12.2.3</p> <h3 id="description">Description</h3> <p>npm is the package manager for the Node JavaScript platform. It puts modules in place so that node can find them, and manages dependency conflicts intelligently.</p> diff --git a/deps/npm/docs/output/commands/npx.html b/deps/npm/docs/output/commands/npx.html index d72a03612b88..e13f289c4aed 100644 --- a/deps/npm/docs/output/commands/npx.html +++ b/deps/npm/docs/output/commands/npx.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npx----1222"> +<h1 id="----npx----1223"> <span>npx</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Run a command from a local or remote npm package</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/folders.html b/deps/npm/docs/output/configuring-npm/folders.html index 322360279966..12f64f3dd84b 100644 --- a/deps/npm/docs/output/configuring-npm/folders.html +++ b/deps/npm/docs/output/configuring-npm/folders.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----folders----1222"> +<h1 id="----folders----1223"> <span>Folders</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Folder structures used by npm</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/install.html b/deps/npm/docs/output/configuring-npm/install.html index fda1dbc96d4e..8e38c1837a3c 100644 --- a/deps/npm/docs/output/configuring-npm/install.html +++ b/deps/npm/docs/output/configuring-npm/install.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----install----1222"> +<h1 id="----install----1223"> <span>Install</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Download and install node and npm</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/npm-extension.html b/deps/npm/docs/output/configuring-npm/npm-extension.html index 7de5b85b5626..c1669ac1ae9f 100644 --- a/deps/npm/docs/output/configuring-npm/npm-extension.html +++ b/deps/npm/docs/output/configuring-npm/npm-extension.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npm-extension----1222"> +<h1 id="----npm-extension----1223"> <span>.npm-extension</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Imperative, root-owned manifest repairs</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/npm-global.html b/deps/npm/docs/output/configuring-npm/npm-global.html index 322360279966..12f64f3dd84b 100644 --- a/deps/npm/docs/output/configuring-npm/npm-global.html +++ b/deps/npm/docs/output/configuring-npm/npm-global.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----folders----1222"> +<h1 id="----folders----1223"> <span>Folders</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Folder structures used by npm</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/npm-json.html b/deps/npm/docs/output/configuring-npm/npm-json.html index bd54796a9869..1d00841fab73 100644 --- a/deps/npm/docs/output/configuring-npm/npm-json.html +++ b/deps/npm/docs/output/configuring-npm/npm-json.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----packagejson----1222"> +<h1 id="----packagejson----1223"> <span>package.json</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Specifics of npm's package.json handling</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/npmrc.html b/deps/npm/docs/output/configuring-npm/npmrc.html index 7a8494a8e2b8..7779ca39c9e0 100644 --- a/deps/npm/docs/output/configuring-npm/npmrc.html +++ b/deps/npm/docs/output/configuring-npm/npmrc.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----npmrc----1222"> +<h1 id="----npmrc----1223"> <span>.npmrc</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">The npm config files</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/package-json.html b/deps/npm/docs/output/configuring-npm/package-json.html index bd54796a9869..1d00841fab73 100644 --- a/deps/npm/docs/output/configuring-npm/package-json.html +++ b/deps/npm/docs/output/configuring-npm/package-json.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----packagejson----1222"> +<h1 id="----packagejson----1223"> <span>package.json</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Specifics of npm's package.json handling</span> </header> diff --git a/deps/npm/docs/output/configuring-npm/package-lock-json.html b/deps/npm/docs/output/configuring-npm/package-lock-json.html index d5464d7c276e..f5800c82280f 100644 --- a/deps/npm/docs/output/configuring-npm/package-lock-json.html +++ b/deps/npm/docs/output/configuring-npm/package-lock-json.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----package-lockjson----1222"> +<h1 id="----package-lockjson----1223"> <span>package-lock.json</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">A manifestation of the manifest</span> </header> diff --git a/deps/npm/docs/output/using-npm/config.html b/deps/npm/docs/output/using-npm/config.html index df5cf69f13b9..a0e934084564 100644 --- a/deps/npm/docs/output/using-npm/config.html +++ b/deps/npm/docs/output/using-npm/config.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----config----1222"> +<h1 id="----config----1223"> <span>Config</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">About npm configuration</span> </header> @@ -1674,6 +1674,10 @@ <h4 id="strict-allow-scripts"><code>strict-allow-scripts</code></h4> <p>Optional dependencies that cannot be installed on the current platform or engine (a non-matching <code>os</code>, <code>cpu</code>, or <code>libc</code>) are not flagged, because their install scripts never run.</p> +<p>Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. <code>npm rebuild</code> and <code>npm install-scripts ls</code> still check unused +packages on disk.</p> <h4 id="strict-npmrc"><code>strict-npmrc</code></h4> <ul> <li>Default: false</li> diff --git a/deps/npm/docs/output/using-npm/dependency-selectors.html b/deps/npm/docs/output/using-npm/dependency-selectors.html index 7dc55a54dae1..a22be2193a83 100644 --- a/deps/npm/docs/output/using-npm/dependency-selectors.html +++ b/deps/npm/docs/output/using-npm/dependency-selectors.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----dependency-selectors----1222"> +<h1 id="----dependency-selectors----1223"> <span>Dependency Selectors</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Dependency Selector Syntax & Querying</span> </header> diff --git a/deps/npm/docs/output/using-npm/developers.html b/deps/npm/docs/output/using-npm/developers.html index c89c0dcbf936..87bcdfc6b9e1 100644 --- a/deps/npm/docs/output/using-npm/developers.html +++ b/deps/npm/docs/output/using-npm/developers.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----developers----1222"> +<h1 id="----developers----1223"> <span>Developers</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Developer guide</span> </header> diff --git a/deps/npm/docs/output/using-npm/logging.html b/deps/npm/docs/output/using-npm/logging.html index 352752b2507a..2b7c37803e98 100644 --- a/deps/npm/docs/output/using-npm/logging.html +++ b/deps/npm/docs/output/using-npm/logging.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----logging----1222"> +<h1 id="----logging----1223"> <span>Logging</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Why, What & How we Log</span> </header> diff --git a/deps/npm/docs/output/using-npm/orgs.html b/deps/npm/docs/output/using-npm/orgs.html index 26ee0603d670..fc91b4656b65 100644 --- a/deps/npm/docs/output/using-npm/orgs.html +++ b/deps/npm/docs/output/using-npm/orgs.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----organizations----1222"> +<h1 id="----organizations----1223"> <span>Organizations</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Working with teams & organizations</span> </header> diff --git a/deps/npm/docs/output/using-npm/package-spec.html b/deps/npm/docs/output/using-npm/package-spec.html index e25f71a8e1e8..001cec2b026a 100644 --- a/deps/npm/docs/output/using-npm/package-spec.html +++ b/deps/npm/docs/output/using-npm/package-spec.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----package-spec----1222"> +<h1 id="----package-spec----1223"> <span>Package spec</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Package name specifier</span> </header> diff --git a/deps/npm/docs/output/using-npm/registry.html b/deps/npm/docs/output/using-npm/registry.html index 3139f4ea3059..4fc393eae3f8 100644 --- a/deps/npm/docs/output/using-npm/registry.html +++ b/deps/npm/docs/output/using-npm/registry.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----registry----1222"> +<h1 id="----registry----1223"> <span>Registry</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">The JavaScript Package Registry</span> </header> diff --git a/deps/npm/docs/output/using-npm/removal.html b/deps/npm/docs/output/using-npm/removal.html index b11487ded282..f06ef2503931 100644 --- a/deps/npm/docs/output/using-npm/removal.html +++ b/deps/npm/docs/output/using-npm/removal.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----removal----1222"> +<h1 id="----removal----1223"> <span>Removal</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Cleaning the slate</span> </header> diff --git a/deps/npm/docs/output/using-npm/scope.html b/deps/npm/docs/output/using-npm/scope.html index 684642f50a73..049267b82058 100644 --- a/deps/npm/docs/output/using-npm/scope.html +++ b/deps/npm/docs/output/using-npm/scope.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----scope----1222"> +<h1 id="----scope----1223"> <span>Scope</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Scoped packages</span> </header> diff --git a/deps/npm/docs/output/using-npm/scripts.html b/deps/npm/docs/output/using-npm/scripts.html index cb78e8f079c6..eba70755f764 100644 --- a/deps/npm/docs/output/using-npm/scripts.html +++ b/deps/npm/docs/output/using-npm/scripts.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----scripts----1222"> +<h1 id="----scripts----1223"> <span>Scripts</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">How npm handles the "scripts" field</span> </header> diff --git a/deps/npm/docs/output/using-npm/workspaces.html b/deps/npm/docs/output/using-npm/workspaces.html index b34d4b7e98a6..184b3d22a78d 100644 --- a/deps/npm/docs/output/using-npm/workspaces.html +++ b/deps/npm/docs/output/using-npm/workspaces.html @@ -186,9 +186,9 @@ <section id="content"> <header class="title"> -<h1 id="----workspaces----1222"> +<h1 id="----workspaces----1223"> <span>Workspaces</span> - <span class="version">@12.2.2</span> + <span class="version">@12.2.3</span> </h1> <span class="description">Working with workspaces</span> </header> diff --git a/deps/npm/lib/commands/exec.js b/deps/npm/lib/commands/exec.js index 7b7d8ad30fcd..930a68de0baa 100644 --- a/deps/npm/lib/commands/exec.js +++ b/deps/npm/lib/commands/exec.js @@ -88,8 +88,6 @@ class Exec extends BaseCommand { return libexec({ ...flatOptions, allowScripts: allowScriptsPolicy, - // we explicitly set packageLockOnly to false because if it's true when we try to install a missing package, we won't actually install it - packageLockOnly: false, // what the user asked to run args[0] is run by default args: [...args], // copy args so they don't get mutated // specify a custom command to be run instead of args[0] diff --git a/deps/npm/lib/commands/unpublish.js b/deps/npm/lib/commands/unpublish.js index fc390a2b9edf..8b55ef9476d6 100644 --- a/deps/npm/lib/commands/unpublish.js +++ b/deps/npm/lib/commands/unpublish.js @@ -26,7 +26,7 @@ class Unpublish extends BaseCommand { query: { write: true }, _isRoot: true, }) - return Object.keys(packument.versions) + return Object.keys(packument.versions || {}) } static async completion (args, npm) { @@ -136,6 +136,9 @@ class Unpublish extends BaseCommand { } const versions = await Unpublish.getKeysOfVersions(spec.name, opts) + if (versions.length === 0 && spec.type === 'version') { + throw this.usageError(`Refusing to delete ${spec.name}@${spec.rawSpec}: the registry returned no versions for ${spec.name}.`) + } if (versions.length === 1 && spec.rawSpec === versions[0] && !force) { throw this.usageError(LAST_REMAINING_VERSION_ERROR) } diff --git a/deps/npm/lib/utils/check-allow-scripts.js b/deps/npm/lib/utils/check-allow-scripts.js index 47984803cde7..352f8e7cb9bc 100644 --- a/deps/npm/lib/utils/check-allow-scripts.js +++ b/deps/npm/lib/utils/check-allow-scripts.js @@ -15,13 +15,20 @@ const { collectUnreviewedScripts } = require('@npmcli/arborist/lib/unreviewed-sc // `includeWhenIgnored` keeps listing unreviewed packages even when // ignore-scripts is set, so approve/deny can show what you'd move from a // blanket ignore-scripts to an allowlist. Execution callers leave it false. -const checkAllowScripts = async ({ arb, npm, tree, includeWhenIgnored = false }) => +const checkAllowScripts = async ({ + arb, + npm, + tree, + includeWhenIgnored = false, + skipExtraneous = false, +}) => collectUnreviewedScripts({ tree: tree || arb.actualTree, policy: arb.options?.allowScripts || null, ignoreScripts: !!arb.options?.ignoreScripts, dangerouslyAllowAllScripts: !!npm?.flatOptions?.dangerouslyAllowAllScripts, includeWhenIgnored, + skipExtraneous, }) module.exports = checkAllowScripts diff --git a/deps/npm/lib/utils/is-windows.js b/deps/npm/lib/utils/is-windows.js index 63c5671d8400..d4513e3e98e6 100644 --- a/deps/npm/lib/utils/is-windows.js +++ b/deps/npm/lib/utils/is-windows.js @@ -1,4 +1,8 @@ +const isGitBashMsystem = (msystem) => + /^(MINGW(32|64)|UCRT64|CLANG(32|64|ARM64))$/.test(msystem || '') + const isWindowsShell = (process.platform === 'win32') && - !/^MINGW(32|64)$/.test(process.env.MSYSTEM) && process.env.TERM !== 'cygwin' + !isGitBashMsystem(process.env.MSYSTEM) && process.env.TERM !== 'cygwin' exports.isWindowsShell = isWindowsShell +exports.isGitBashMsystem = isGitBashMsystem diff --git a/deps/npm/lib/utils/reify-finish.js b/deps/npm/lib/utils/reify-finish.js index 1041c53fdb93..0278f9b59191 100644 --- a/deps/npm/lib/utils/reify-finish.js +++ b/deps/npm/lib/utils/reify-finish.js @@ -18,7 +18,7 @@ const reifyFinish = async (npm, arb) => { } } warnWorkspaceAllowScripts(arb.actualTree) - const unreviewedScripts = await checkAllowScripts({ arb, npm }) + const unreviewedScripts = await checkAllowScripts({ arb, npm, skipExtraneous: true }) reifyOutput(npm, arb, { unreviewedScripts }) } diff --git a/deps/npm/lib/utils/strict-allow-scripts-preflight.js b/deps/npm/lib/utils/strict-allow-scripts-preflight.js index 0c500018184c..2bb5ceb6d9d4 100644 --- a/deps/npm/lib/utils/strict-allow-scripts-preflight.js +++ b/deps/npm/lib/utils/strict-allow-scripts-preflight.js @@ -33,7 +33,12 @@ const strictAllowScriptsPreflight = async ({ arb, npm, idealTreeOpts }) => { tree = arb.actualTree } - const unreviewed = await checkAllowScripts({ arb, npm, tree }) + const unreviewed = await checkAllowScripts({ + arb, + npm, + tree, + skipExtraneous: idealTreeOpts !== undefined, + }) if (unreviewed.length === 0) { return } diff --git a/deps/npm/man/man1/npm-access.1 b/deps/npm/man/man1/npm-access.1 index 324c220e5f95..67ab96393546 100644 --- a/deps/npm/man/man1/npm-access.1 +++ b/deps/npm/man/man1/npm-access.1 @@ -1,4 +1,4 @@ -.TH "NPM-ACCESS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-ACCESS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-access\fR - Set access level on published packages .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-approve-scripts.1 b/deps/npm/man/man1/npm-approve-scripts.1 index afd31482a639..c1bd7a0791bf 100644 --- a/deps/npm/man/man1/npm-approve-scripts.1 +++ b/deps/npm/man/man1/npm-approve-scripts.1 @@ -1,4 +1,4 @@ -.TH "NPM-APPROVE-SCRIPTS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-APPROVE-SCRIPTS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-approve-scripts\fR - Approve install scripts for specific dependencies .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-audit.1 b/deps/npm/man/man1/npm-audit.1 index 1f1e65aca70b..91e51aee7a16 100644 --- a/deps/npm/man/man1/npm-audit.1 +++ b/deps/npm/man/man1/npm-audit.1 @@ -1,4 +1,4 @@ -.TH "NPM-AUDIT" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-AUDIT" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-audit\fR - Run a security audit .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-bugs.1 b/deps/npm/man/man1/npm-bugs.1 index ce79290f6031..497415d7b840 100644 --- a/deps/npm/man/man1/npm-bugs.1 +++ b/deps/npm/man/man1/npm-bugs.1 @@ -1,4 +1,4 @@ -.TH "NPM-BUGS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-BUGS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-bugs\fR - Report bugs for a package in a web browser .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-cache.1 b/deps/npm/man/man1/npm-cache.1 index b0b872ea8883..04b0dc35acd5 100644 --- a/deps/npm/man/man1/npm-cache.1 +++ b/deps/npm/man/man1/npm-cache.1 @@ -1,4 +1,4 @@ -.TH "NPM-CACHE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-CACHE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-cache\fR - Manipulates packages cache .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-ci.1 b/deps/npm/man/man1/npm-ci.1 index 602bac82785f..b0f4716c197b 100644 --- a/deps/npm/man/man1/npm-ci.1 +++ b/deps/npm/man/man1/npm-ci.1 @@ -1,4 +1,4 @@ -.TH "NPM-CI" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-CI" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-ci\fR - Clean install a project .SS "Synopsis" @@ -254,6 +254,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-completion.1 b/deps/npm/man/man1/npm-completion.1 index a1d2038a9fc9..4cc53229bf1e 100644 --- a/deps/npm/man/man1/npm-completion.1 +++ b/deps/npm/man/man1/npm-completion.1 @@ -1,4 +1,4 @@ -.TH "NPM-COMPLETION" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-COMPLETION" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-completion\fR - Tab Completion for npm .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-config.1 b/deps/npm/man/man1/npm-config.1 index 442a17aca7fc..1feffc654e02 100644 --- a/deps/npm/man/man1/npm-config.1 +++ b/deps/npm/man/man1/npm-config.1 @@ -1,4 +1,4 @@ -.TH "NPM-CONFIG" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-CONFIG" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-config\fR - Manage the npm configuration files .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-dedupe.1 b/deps/npm/man/man1/npm-dedupe.1 index 861a94c86574..b1d269486660 100644 --- a/deps/npm/man/man1/npm-dedupe.1 +++ b/deps/npm/man/man1/npm-dedupe.1 @@ -1,4 +1,4 @@ -.TH "NPM-DEDUPE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DEDUPE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-dedupe\fR - Reduce duplication in the package tree .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-deny-scripts.1 b/deps/npm/man/man1/npm-deny-scripts.1 index 7250da8e247b..47cf11778eb1 100644 --- a/deps/npm/man/man1/npm-deny-scripts.1 +++ b/deps/npm/man/man1/npm-deny-scripts.1 @@ -1,4 +1,4 @@ -.TH "NPM-DENY-SCRIPTS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DENY-SCRIPTS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-deny-scripts\fR - Deny install scripts for specific dependencies .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-deprecate.1 b/deps/npm/man/man1/npm-deprecate.1 index 781c3119b7b6..ce1eb5dc4664 100644 --- a/deps/npm/man/man1/npm-deprecate.1 +++ b/deps/npm/man/man1/npm-deprecate.1 @@ -1,4 +1,4 @@ -.TH "NPM-DEPRECATE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DEPRECATE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-deprecate\fR - Deprecate a version of a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-diff.1 b/deps/npm/man/man1/npm-diff.1 index b9a9edc62851..bd4339affa6c 100644 --- a/deps/npm/man/man1/npm-diff.1 +++ b/deps/npm/man/man1/npm-diff.1 @@ -1,4 +1,4 @@ -.TH "NPM-DIFF" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DIFF" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-diff\fR - The registry diff command .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-dist-tag.1 b/deps/npm/man/man1/npm-dist-tag.1 index 0e22a5cdf8c0..749532eaf721 100644 --- a/deps/npm/man/man1/npm-dist-tag.1 +++ b/deps/npm/man/man1/npm-dist-tag.1 @@ -1,4 +1,4 @@ -.TH "NPM-DIST-TAG" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DIST-TAG" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-dist-tag\fR - Modify package distribution tags .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-docs.1 b/deps/npm/man/man1/npm-docs.1 index bd38207633fe..d04c5baa2bc4 100644 --- a/deps/npm/man/man1/npm-docs.1 +++ b/deps/npm/man/man1/npm-docs.1 @@ -1,4 +1,4 @@ -.TH "NPM-DOCS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DOCS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-docs\fR - Open documentation for a package in a web browser .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-doctor.1 b/deps/npm/man/man1/npm-doctor.1 index 730593799c1f..b358f187a921 100644 --- a/deps/npm/man/man1/npm-doctor.1 +++ b/deps/npm/man/man1/npm-doctor.1 @@ -1,4 +1,4 @@ -.TH "NPM-DOCTOR" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-DOCTOR" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-doctor\fR - Check the health of your npm environment .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-edit.1 b/deps/npm/man/man1/npm-edit.1 index 85c48dd18060..909c4dfa2122 100644 --- a/deps/npm/man/man1/npm-edit.1 +++ b/deps/npm/man/man1/npm-edit.1 @@ -1,4 +1,4 @@ -.TH "NPM-EDIT" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-EDIT" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-edit\fR - Edit an installed package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-exec.1 b/deps/npm/man/man1/npm-exec.1 index 5ef7665a12f6..6089a5464306 100644 --- a/deps/npm/man/man1/npm-exec.1 +++ b/deps/npm/man/man1/npm-exec.1 @@ -1,4 +1,4 @@ -.TH "NPM-EXEC" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-EXEC" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-exec\fR - Run a command from a local or remote npm package .SS "Synopsis" @@ -197,6 +197,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-explain.1 b/deps/npm/man/man1/npm-explain.1 index c915dd81707d..a843006b09b9 100644 --- a/deps/npm/man/man1/npm-explain.1 +++ b/deps/npm/man/man1/npm-explain.1 @@ -1,4 +1,4 @@ -.TH "NPM-EXPLAIN" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-EXPLAIN" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-explain\fR - Explain installed packages .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-explore.1 b/deps/npm/man/man1/npm-explore.1 index 2b76b1d5520b..753c290857a0 100644 --- a/deps/npm/man/man1/npm-explore.1 +++ b/deps/npm/man/man1/npm-explore.1 @@ -1,4 +1,4 @@ -.TH "NPM-EXPLORE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-EXPLORE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-explore\fR - Browse an installed package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-find-dupes.1 b/deps/npm/man/man1/npm-find-dupes.1 index 16718ee79367..5273ad159580 100644 --- a/deps/npm/man/man1/npm-find-dupes.1 +++ b/deps/npm/man/man1/npm-find-dupes.1 @@ -1,4 +1,4 @@ -.TH "NPM-FIND-DUPES" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-FIND-DUPES" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-find-dupes\fR - Find duplication in the package tree .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-fund.1 b/deps/npm/man/man1/npm-fund.1 index 74f81a6636c0..4281acfd4149 100644 --- a/deps/npm/man/man1/npm-fund.1 +++ b/deps/npm/man/man1/npm-fund.1 @@ -1,4 +1,4 @@ -.TH "NPM-FUND" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-FUND" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-fund\fR - Retrieve funding information .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-get.1 b/deps/npm/man/man1/npm-get.1 index 46f9e70e1745..4e8cc7ec69ae 100644 --- a/deps/npm/man/man1/npm-get.1 +++ b/deps/npm/man/man1/npm-get.1 @@ -1,4 +1,4 @@ -.TH "NPM-GET" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-GET" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-get\fR - Get a value from the npm configuration .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-help-search.1 b/deps/npm/man/man1/npm-help-search.1 index d38714cdda44..6ea5d6292185 100644 --- a/deps/npm/man/man1/npm-help-search.1 +++ b/deps/npm/man/man1/npm-help-search.1 @@ -1,4 +1,4 @@ -.TH "NPM-HELP-SEARCH" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-HELP-SEARCH" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-help-search\fR - Search npm help documentation .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-help.1 b/deps/npm/man/man1/npm-help.1 index 6e3e7d450fe3..ff1ef84a9e94 100644 --- a/deps/npm/man/man1/npm-help.1 +++ b/deps/npm/man/man1/npm-help.1 @@ -1,4 +1,4 @@ -.TH "NPM-HELP" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-HELP" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-help\fR - Get help on npm .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-init.1 b/deps/npm/man/man1/npm-init.1 index 48a63eb4bca4..3aa9f47d0cdd 100644 --- a/deps/npm/man/man1/npm-init.1 +++ b/deps/npm/man/man1/npm-init.1 @@ -1,4 +1,4 @@ -.TH "NPM-INIT" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-INIT" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-init\fR - Create a package.json file .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-install-ci-test.1 b/deps/npm/man/man1/npm-install-ci-test.1 index db3b60c1fff7..b5d9983dc876 100644 --- a/deps/npm/man/man1/npm-install-ci-test.1 +++ b/deps/npm/man/man1/npm-install-ci-test.1 @@ -1,4 +1,4 @@ -.TH "NPM-INSTALL-CI-TEST" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-INSTALL-CI-TEST" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-install-ci-test\fR - Install a project with a clean slate and run tests .SS "Synopsis" @@ -202,6 +202,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-install-scripts.1 b/deps/npm/man/man1/npm-install-scripts.1 index c91c2f66d452..e6d173e981e1 100644 --- a/deps/npm/man/man1/npm-install-scripts.1 +++ b/deps/npm/man/man1/npm-install-scripts.1 @@ -1,4 +1,4 @@ -.TH "NPM-INSTALL-SCRIPTS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-INSTALL-SCRIPTS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-install-scripts\fR - Manage install-script approvals for dependencies .SS "Synopsis" @@ -19,7 +19,7 @@ Note: This command is unaware of workspaces. .P Manages the \fBallowScripts\fR field in your project's \fBpackage.json\fR, which records which of your dependencies are permitted to run install scripts (\fBpreinstall\fR, \fBinstall\fR, \fBpostinstall\fR, and \fBprepare\fR for non-registry sources). This is the recommended way to maintain that field. .P -Dependency install scripts are blocked by default. Install commands silently skip lifecycle scripts for any dependency that does not have a matching entry in \fBallowScripts\fR, and end with a list of the packages whose scripts were skipped so you can review them here. +Dependency install scripts are blocked by default. Install commands silently skip lifecycle scripts for any dependency that does not have a matching entry in \fBallowScripts\fR, and end with a list of the packages whose scripts were skipped so you can review them here. These warnings omit disconnected unused entries that installation cannot build. Local link targets that can still be rebuilt remain subject to the policy. .P This command only works inside a project that has a \fBpackage.json\fR. Running it with \fB--global\fR (\fB-g\fR) fails with an \fBEGLOBAL\fR error, since global installs (\fBnpm install -g\fR) and one-off executions (\fBnpm exec\fR / \fBnpx\fR) have no project \fBpackage.json\fR to write to. To allow install scripts in those contexts, use the \fB--allow-scripts\fR flag at install time (for example \fBnpm install -g --allow-scripts=canvas,sharp\fR) or persist the setting with \fBnpm config set allow-scripts=canvas,sharp --location=user\fR. .P @@ -40,7 +40,7 @@ npm install-scripts prune .P \fBdeny\fR records an explicit denial for the named packages (a name-only \fBfalse\fR entry), which survives \fBnpm install-scripts approve --all\fR and excludes the package from any future blanket approval. \fB--all\fR denies every package with unreviewed install scripts. .P -\fBls\fR is read-only: it lists every package whose install scripts are not yet covered by \fBallowScripts\fR, without modifying \fBpackage.json\fR. +\fBls\fR is read-only: it lists every package whose install scripts are not yet covered by \fBallowScripts\fR, without modifying \fBpackage.json\fR. This includes unreviewed extraneous packages, which are installed but not required by any dependency. These packages can still cause \fBnpm rebuild --strict-allow-scripts\fR to fail. .P \fBprune\fR removes \fBallowScripts\fR entries that no longer match an installed package with an install script, either because the package is no longer installed (a transitive dependency changed, or a pinned \fBpkg@1.2.3\fR was upgraded) or because it no longer has an install script. Both approvals (\fBtrue\fR) and denials (\fBfalse\fR) are removed. It edits only the \fBallowScripts\fR field in \fBpackage.json\fR, never \fB.npmrc\fR or \fB--allow-scripts\fR. Pass \fB--dry-run\fR to preview without writing. Unparseable keys are left alone. .P diff --git a/deps/npm/man/man1/npm-install-test.1 b/deps/npm/man/man1/npm-install-test.1 index 00e1adced341..6d0ae8a3b899 100644 --- a/deps/npm/man/man1/npm-install-test.1 +++ b/deps/npm/man/man1/npm-install-test.1 @@ -1,4 +1,4 @@ -.TH "NPM-INSTALL-TEST" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-INSTALL-TEST" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-install-test\fR - Install package(s) and run tests .SS "Synopsis" @@ -279,6 +279,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-install.1 b/deps/npm/man/man1/npm-install.1 index ebcdf8f33fc5..5b52babce553 100644 --- a/deps/npm/man/man1/npm-install.1 +++ b/deps/npm/man/man1/npm-install.1 @@ -1,4 +1,4 @@ -.TH "NPM-INSTALL" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-INSTALL" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-install\fR - Install a package .SS "Synopsis" @@ -667,6 +667,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-link.1 b/deps/npm/man/man1/npm-link.1 index 6e01fa12f7a8..9cdd1865a969 100644 --- a/deps/npm/man/man1/npm-link.1 +++ b/deps/npm/man/man1/npm-link.1 @@ -1,4 +1,4 @@ -.TH "NPM-LINK" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-LINK" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-link\fR - Symlink a package folder .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-ll.1 b/deps/npm/man/man1/npm-ll.1 index 9a4c9dd4d96a..259de7410be4 100644 --- a/deps/npm/man/man1/npm-ll.1 +++ b/deps/npm/man/man1/npm-ll.1 @@ -1,4 +1,4 @@ -.TH "NPM-LL" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-LL" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-ll\fR - List installed packages .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-login.1 b/deps/npm/man/man1/npm-login.1 index 528cbd6bd783..65667ad6e930 100644 --- a/deps/npm/man/man1/npm-login.1 +++ b/deps/npm/man/man1/npm-login.1 @@ -1,4 +1,4 @@ -.TH "NPM-LOGIN" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-LOGIN" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-login\fR - Login to a registry user account .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-logout.1 b/deps/npm/man/man1/npm-logout.1 index 9615a4d06279..d6a861954cc1 100644 --- a/deps/npm/man/man1/npm-logout.1 +++ b/deps/npm/man/man1/npm-logout.1 @@ -1,4 +1,4 @@ -.TH "NPM-LOGOUT" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-LOGOUT" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-logout\fR - Log out of the registry .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-ls.1 b/deps/npm/man/man1/npm-ls.1 index 8e3cbf0f6cd6..0827655ae5f8 100644 --- a/deps/npm/man/man1/npm-ls.1 +++ b/deps/npm/man/man1/npm-ls.1 @@ -1,4 +1,4 @@ -.TH "NPM-LS" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-LS" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-ls\fR - List installed packages .SS "Synopsis" @@ -20,7 +20,7 @@ Positional arguments are \fBname@version-range\fR identifiers, which will limit .P .RS 2 .nf -npm@12.2.2 /path/to/npm +npm@12.2.3 /path/to/npm └─┬ init-package-json@0.0.4 └── promzard@0.1.5 .fi diff --git a/deps/npm/man/man1/npm-org.1 b/deps/npm/man/man1/npm-org.1 index 43a33b5a80d6..9eafb981a110 100644 --- a/deps/npm/man/man1/npm-org.1 +++ b/deps/npm/man/man1/npm-org.1 @@ -1,4 +1,4 @@ -.TH "NPM-ORG" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-ORG" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-org\fR - Manage orgs .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-outdated.1 b/deps/npm/man/man1/npm-outdated.1 index 088147b68dab..0266323a48ab 100644 --- a/deps/npm/man/man1/npm-outdated.1 +++ b/deps/npm/man/man1/npm-outdated.1 @@ -1,4 +1,4 @@ -.TH "NPM-OUTDATED" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-OUTDATED" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-outdated\fR - Check for outdated packages .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-owner.1 b/deps/npm/man/man1/npm-owner.1 index 341f0d86ff00..3d6818245620 100644 --- a/deps/npm/man/man1/npm-owner.1 +++ b/deps/npm/man/man1/npm-owner.1 @@ -1,4 +1,4 @@ -.TH "NPM-OWNER" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-OWNER" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-owner\fR - Manage package owners .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-pack.1 b/deps/npm/man/man1/npm-pack.1 index efd0fe7e891b..7ad5fce0f22b 100644 --- a/deps/npm/man/man1/npm-pack.1 +++ b/deps/npm/man/man1/npm-pack.1 @@ -1,4 +1,4 @@ -.TH "NPM-PACK" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PACK" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-pack\fR - Create a tarball from a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-patch.1 b/deps/npm/man/man1/npm-patch.1 index 8566db4005ff..e20b2d65fbab 100644 --- a/deps/npm/man/man1/npm-patch.1 +++ b/deps/npm/man/man1/npm-patch.1 @@ -1,4 +1,4 @@ -.TH "NPM-PATCH" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PATCH" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-patch\fR - Apply local patches to installed dependencies .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-ping.1 b/deps/npm/man/man1/npm-ping.1 index d7ea10b46e9b..1d0ce6e6afdf 100644 --- a/deps/npm/man/man1/npm-ping.1 +++ b/deps/npm/man/man1/npm-ping.1 @@ -1,4 +1,4 @@ -.TH "NPM-PING" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PING" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-ping\fR - Ping npm registry .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-pkg.1 b/deps/npm/man/man1/npm-pkg.1 index a4ba9cff71d7..a341de8306e0 100644 --- a/deps/npm/man/man1/npm-pkg.1 +++ b/deps/npm/man/man1/npm-pkg.1 @@ -1,4 +1,4 @@ -.TH "NPM-PKG" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PKG" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-pkg\fR - Manages your package.json .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-prefix.1 b/deps/npm/man/man1/npm-prefix.1 index b040821494d5..c42f9205955f 100644 --- a/deps/npm/man/man1/npm-prefix.1 +++ b/deps/npm/man/man1/npm-prefix.1 @@ -1,4 +1,4 @@ -.TH "NPM-PREFIX" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PREFIX" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-prefix\fR - Display prefix .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-profile.1 b/deps/npm/man/man1/npm-profile.1 index 8676592d547e..d4962477a9b9 100644 --- a/deps/npm/man/man1/npm-profile.1 +++ b/deps/npm/man/man1/npm-profile.1 @@ -1,4 +1,4 @@ -.TH "NPM-PROFILE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PROFILE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-profile\fR - Change settings on your registry profile .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-prune.1 b/deps/npm/man/man1/npm-prune.1 index 3403426106df..55f72cb1dcf4 100644 --- a/deps/npm/man/man1/npm-prune.1 +++ b/deps/npm/man/man1/npm-prune.1 @@ -1,4 +1,4 @@ -.TH "NPM-PRUNE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PRUNE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-prune\fR - Remove extraneous packages .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-publish.1 b/deps/npm/man/man1/npm-publish.1 index 96fc7285c8dc..60b4f2fe2664 100644 --- a/deps/npm/man/man1/npm-publish.1 +++ b/deps/npm/man/man1/npm-publish.1 @@ -1,4 +1,4 @@ -.TH "NPM-PUBLISH" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-PUBLISH" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-publish\fR - Publish a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-query.1 b/deps/npm/man/man1/npm-query.1 index a21a449797d2..e5e242d14b7d 100644 --- a/deps/npm/man/man1/npm-query.1 +++ b/deps/npm/man/man1/npm-query.1 @@ -1,4 +1,4 @@ -.TH "NPM-QUERY" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-QUERY" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-query\fR - Dependency selector query .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-rebuild.1 b/deps/npm/man/man1/npm-rebuild.1 index af397b47dd0d..94562c4e1584 100644 --- a/deps/npm/man/man1/npm-rebuild.1 +++ b/deps/npm/man/man1/npm-rebuild.1 @@ -1,4 +1,4 @@ -.TH "NPM-REBUILD" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-REBUILD" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-rebuild\fR - Rebuild a package .SS "Synopsis" @@ -133,6 +133,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-repo.1 b/deps/npm/man/man1/npm-repo.1 index 2c9762dfaa15..f13e406ee475 100644 --- a/deps/npm/man/man1/npm-repo.1 +++ b/deps/npm/man/man1/npm-repo.1 @@ -1,4 +1,4 @@ -.TH "NPM-REPO" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-REPO" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-repo\fR - Open package repository page in the browser .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-restart.1 b/deps/npm/man/man1/npm-restart.1 index 60db8303f54f..e83b55eb79c8 100644 --- a/deps/npm/man/man1/npm-restart.1 +++ b/deps/npm/man/man1/npm-restart.1 @@ -1,4 +1,4 @@ -.TH "NPM-RESTART" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-RESTART" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-restart\fR - Restart a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-root.1 b/deps/npm/man/man1/npm-root.1 index a9992453f1bc..f73b06cfa334 100644 --- a/deps/npm/man/man1/npm-root.1 +++ b/deps/npm/man/man1/npm-root.1 @@ -1,4 +1,4 @@ -.TH "NPM-ROOT" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-ROOT" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-root\fR - Display npm root .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-run.1 b/deps/npm/man/man1/npm-run.1 index f47f81e3b7bf..7c521dfcd7e1 100644 --- a/deps/npm/man/man1/npm-run.1 +++ b/deps/npm/man/man1/npm-run.1 @@ -1,4 +1,4 @@ -.TH "NPM-RUN" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-RUN" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-run\fR - Run arbitrary package scripts .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-sbom.1 b/deps/npm/man/man1/npm-sbom.1 index 7f0126d347ec..def290bba9a7 100644 --- a/deps/npm/man/man1/npm-sbom.1 +++ b/deps/npm/man/man1/npm-sbom.1 @@ -1,4 +1,4 @@ -.TH "NPM-SBOM" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-SBOM" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-sbom\fR - Generate a Software Bill of Materials (SBOM) .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-search.1 b/deps/npm/man/man1/npm-search.1 index 08e58b7eba72..5ac93a662651 100644 --- a/deps/npm/man/man1/npm-search.1 +++ b/deps/npm/man/man1/npm-search.1 @@ -1,4 +1,4 @@ -.TH "NPM-SEARCH" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-SEARCH" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-search\fR - Search for packages .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-set.1 b/deps/npm/man/man1/npm-set.1 index 00f7d9362e6c..a31c8cc5a23c 100644 --- a/deps/npm/man/man1/npm-set.1 +++ b/deps/npm/man/man1/npm-set.1 @@ -1,4 +1,4 @@ -.TH "NPM-SET" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-SET" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-set\fR - Set a value in the npm configuration .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-stage.1 b/deps/npm/man/man1/npm-stage.1 index 2485744883f6..bdb617b8d39d 100644 --- a/deps/npm/man/man1/npm-stage.1 +++ b/deps/npm/man/man1/npm-stage.1 @@ -1,4 +1,4 @@ -.TH "NPM-STAGE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-STAGE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-stage\fR - Stage packages for publishing .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-start.1 b/deps/npm/man/man1/npm-start.1 index 95ca202bc957..c98b0c6d4d03 100644 --- a/deps/npm/man/man1/npm-start.1 +++ b/deps/npm/man/man1/npm-start.1 @@ -1,4 +1,4 @@ -.TH "NPM-START" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-START" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-start\fR - Start a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-stop.1 b/deps/npm/man/man1/npm-stop.1 index 1bb7818e1f5a..681a4209fdc5 100644 --- a/deps/npm/man/man1/npm-stop.1 +++ b/deps/npm/man/man1/npm-stop.1 @@ -1,4 +1,4 @@ -.TH "NPM-STOP" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-STOP" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-stop\fR - Stop a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-team.1 b/deps/npm/man/man1/npm-team.1 index 52a32be20f8b..8362186067eb 100644 --- a/deps/npm/man/man1/npm-team.1 +++ b/deps/npm/man/man1/npm-team.1 @@ -1,4 +1,4 @@ -.TH "NPM-TEAM" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-TEAM" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-team\fR - Manage organization teams and team memberships .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-test.1 b/deps/npm/man/man1/npm-test.1 index 5dcb59e605b7..13e09089094c 100644 --- a/deps/npm/man/man1/npm-test.1 +++ b/deps/npm/man/man1/npm-test.1 @@ -1,4 +1,4 @@ -.TH "NPM-TEST" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-TEST" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-test\fR - Test a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-token.1 b/deps/npm/man/man1/npm-token.1 index c93b80fd6f16..8aa9c57463dd 100644 --- a/deps/npm/man/man1/npm-token.1 +++ b/deps/npm/man/man1/npm-token.1 @@ -1,4 +1,4 @@ -.TH "NPM-TOKEN" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-TOKEN" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-token\fR - Manage your authentication tokens .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-trust.1 b/deps/npm/man/man1/npm-trust.1 index 3db7dc8b88b2..a37b1cec1032 100644 --- a/deps/npm/man/man1/npm-trust.1 +++ b/deps/npm/man/man1/npm-trust.1 @@ -1,4 +1,4 @@ -.TH "NPM-TRUST" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-TRUST" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-trust\fR - Manage trusted publishing relationships between packages and CI/CD providers .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-undeprecate.1 b/deps/npm/man/man1/npm-undeprecate.1 index 4b9722986873..788cc169b96e 100644 --- a/deps/npm/man/man1/npm-undeprecate.1 +++ b/deps/npm/man/man1/npm-undeprecate.1 @@ -1,4 +1,4 @@ -.TH "NPM-UNDEPRECATE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-UNDEPRECATE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-undeprecate\fR - Undeprecate a version of a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-uninstall.1 b/deps/npm/man/man1/npm-uninstall.1 index d02c219f6a48..e785121fafee 100644 --- a/deps/npm/man/man1/npm-uninstall.1 +++ b/deps/npm/man/man1/npm-uninstall.1 @@ -1,4 +1,4 @@ -.TH "NPM-UNINSTALL" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-UNINSTALL" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-uninstall\fR - Remove a package .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-unpublish.1 b/deps/npm/man/man1/npm-unpublish.1 index c11c5de96e5e..e41e23559fb5 100644 --- a/deps/npm/man/man1/npm-unpublish.1 +++ b/deps/npm/man/man1/npm-unpublish.1 @@ -1,4 +1,4 @@ -.TH "NPM-UNPUBLISH" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-UNPUBLISH" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-unpublish\fR - Remove a package from the registry .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-update.1 b/deps/npm/man/man1/npm-update.1 index fb6a41bfb1ce..e7f258b122b6 100644 --- a/deps/npm/man/man1/npm-update.1 +++ b/deps/npm/man/man1/npm-update.1 @@ -1,4 +1,4 @@ -.TH "NPM-UPDATE" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-UPDATE" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-update\fR - Update packages .SS "Synopsis" @@ -311,6 +311,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBdangerously-allow-all-scripts\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man1/npm-version.1 b/deps/npm/man/man1/npm-version.1 index 76ae63781843..a7e15d48013a 100644 --- a/deps/npm/man/man1/npm-version.1 +++ b/deps/npm/man/man1/npm-version.1 @@ -1,4 +1,4 @@ -.TH "NPM-VERSION" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-VERSION" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-version\fR - Bump a package version .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-view.1 b/deps/npm/man/man1/npm-view.1 index 49c3895db180..5ad0e7913361 100644 --- a/deps/npm/man/man1/npm-view.1 +++ b/deps/npm/man/man1/npm-view.1 @@ -1,4 +1,4 @@ -.TH "NPM-VIEW" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-VIEW" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-view\fR - View registry info .SS "Synopsis" diff --git a/deps/npm/man/man1/npm-whoami.1 b/deps/npm/man/man1/npm-whoami.1 index 00999cc8dbdc..149ee0eab23e 100644 --- a/deps/npm/man/man1/npm-whoami.1 +++ b/deps/npm/man/man1/npm-whoami.1 @@ -1,4 +1,4 @@ -.TH "NPM-WHOAMI" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM-WHOAMI" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm-whoami\fR - Display npm username .SS "Synopsis" diff --git a/deps/npm/man/man1/npm.1 b/deps/npm/man/man1/npm.1 index 471b53d9a73b..9fbc8f7fd09b 100644 --- a/deps/npm/man/man1/npm.1 +++ b/deps/npm/man/man1/npm.1 @@ -1,4 +1,4 @@ -.TH "NPM" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPM" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpm\fR - javascript package manager .SS "Synopsis" @@ -12,7 +12,7 @@ npm Note: This command is unaware of workspaces. .SS "Version" .P -12.2.2 +12.2.3 .SS "Description" .P npm is the package manager for the Node JavaScript platform. It puts modules in place so that node can find them, and manages dependency conflicts intelligently. diff --git a/deps/npm/man/man1/npx.1 b/deps/npm/man/man1/npx.1 index b578ba8b11bc..3f137e15df68 100644 --- a/deps/npm/man/man1/npx.1 +++ b/deps/npm/man/man1/npx.1 @@ -1,4 +1,4 @@ -.TH "NPX" "1" "November 2026" "NPM@12.2.2" "" +.TH "NPX" "1" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBnpx\fR - Run a command from a local or remote npm package .SS "Synopsis" diff --git a/deps/npm/man/man5/folders.5 b/deps/npm/man/man5/folders.5 index 5d4d531fa779..aa65b394cc25 100644 --- a/deps/npm/man/man5/folders.5 +++ b/deps/npm/man/man5/folders.5 @@ -1,4 +1,4 @@ -.TH "FOLDERS" "5" "November 2026" "NPM@12.2.2" "" +.TH "FOLDERS" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBFolders\fR - Folder structures used by npm .SS "Description" diff --git a/deps/npm/man/man5/install.5 b/deps/npm/man/man5/install.5 index 746f0448b745..46a008083c52 100644 --- a/deps/npm/man/man5/install.5 +++ b/deps/npm/man/man5/install.5 @@ -1,4 +1,4 @@ -.TH "INSTALL" "5" "November 2026" "NPM@12.2.2" "" +.TH "INSTALL" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBInstall\fR - Download and install node and npm .SS "Description" diff --git a/deps/npm/man/man5/npm-extension.5 b/deps/npm/man/man5/npm-extension.5 index c8db8a2645b2..cbbf6971e9e9 100644 --- a/deps/npm/man/man5/npm-extension.5 +++ b/deps/npm/man/man5/npm-extension.5 @@ -1,4 +1,4 @@ -.TH ".NPM-EXTENSION" "5" "November 2026" "NPM@12.2.2" "" +.TH ".NPM-EXTENSION" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fB.npm-extension\fR - Imperative, root-owned manifest repairs .SS "Description" diff --git a/deps/npm/man/man5/npm-global.5 b/deps/npm/man/man5/npm-global.5 index 5d4d531fa779..aa65b394cc25 100644 --- a/deps/npm/man/man5/npm-global.5 +++ b/deps/npm/man/man5/npm-global.5 @@ -1,4 +1,4 @@ -.TH "FOLDERS" "5" "November 2026" "NPM@12.2.2" "" +.TH "FOLDERS" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBFolders\fR - Folder structures used by npm .SS "Description" diff --git a/deps/npm/man/man5/npm-json.5 b/deps/npm/man/man5/npm-json.5 index 85af518d6ed6..2fb979e91394 100644 --- a/deps/npm/man/man5/npm-json.5 +++ b/deps/npm/man/man5/npm-json.5 @@ -1,4 +1,4 @@ -.TH "PACKAGE.JSON" "5" "November 2026" "NPM@12.2.2" "" +.TH "PACKAGE.JSON" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBpackage.json\fR - Specifics of npm's package.json handling .SS "Description" diff --git a/deps/npm/man/man5/npmrc.5 b/deps/npm/man/man5/npmrc.5 index 333864f013de..313cb5639cfe 100644 --- a/deps/npm/man/man5/npmrc.5 +++ b/deps/npm/man/man5/npmrc.5 @@ -1,4 +1,4 @@ -.TH ".NPMRC" "5" "November 2026" "NPM@12.2.2" "" +.TH ".NPMRC" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fB.npmrc\fR - The npm config files .SS "Description" diff --git a/deps/npm/man/man5/package-json.5 b/deps/npm/man/man5/package-json.5 index 85af518d6ed6..2fb979e91394 100644 --- a/deps/npm/man/man5/package-json.5 +++ b/deps/npm/man/man5/package-json.5 @@ -1,4 +1,4 @@ -.TH "PACKAGE.JSON" "5" "November 2026" "NPM@12.2.2" "" +.TH "PACKAGE.JSON" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBpackage.json\fR - Specifics of npm's package.json handling .SS "Description" diff --git a/deps/npm/man/man5/package-lock-json.5 b/deps/npm/man/man5/package-lock-json.5 index 050024e3e143..f4d26a535196 100644 --- a/deps/npm/man/man5/package-lock-json.5 +++ b/deps/npm/man/man5/package-lock-json.5 @@ -1,4 +1,4 @@ -.TH "PACKAGE-LOCK.JSON" "5" "November 2026" "NPM@12.2.2" "" +.TH "PACKAGE-LOCK.JSON" "5" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBpackage-lock.json\fR - A manifestation of the manifest .SS "Description" diff --git a/deps/npm/man/man7/config.7 b/deps/npm/man/man7/config.7 index c67a71ae67e4..25c9b76e0b8f 100644 --- a/deps/npm/man/man7/config.7 +++ b/deps/npm/man/man7/config.7 @@ -1,4 +1,4 @@ -.TH "CONFIG" "7" "November 2026" "NPM@12.2.2" "" +.TH "CONFIG" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBConfig\fR - About npm configuration .SS "Description" @@ -1966,6 +1966,8 @@ If \fBtrue\fR, turn the install-script policy from a warning into a hard error: Dependencies explicitly denied with \fBfalse\fR in \fBallowScripts\fR are always silently skipped; this setting only affects unreviewed entries (packages with install scripts that are neither approved nor denied). \fB--ignore-scripts\fR and \fB--dangerously-allow-all-scripts\fR both override this setting. .P Optional dependencies that cannot be installed on the current platform or engine (a non-matching \fBos\fR, \fBcpu\fR, or \fBlibc\fR) are not flagged, because their install scripts never run. +.P +Installation checks skip unused entries with no package parent or incoming links. Local link targets that installation can still rebuild remain subject to this check. \fBnpm rebuild\fR and \fBnpm install-scripts ls\fR still check unused packages on disk. .SS "\fBstrict-npmrc\fR" .RS 0 .IP \(bu 4 diff --git a/deps/npm/man/man7/dependency-selectors.7 b/deps/npm/man/man7/dependency-selectors.7 index c074d387c2e6..e67a6f9ce52d 100644 --- a/deps/npm/man/man7/dependency-selectors.7 +++ b/deps/npm/man/man7/dependency-selectors.7 @@ -1,4 +1,4 @@ -.TH "SELECTORS" "7" "November 2026" "NPM@12.2.2" "" +.TH "SELECTORS" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBSelectors\fR - Dependency Selector Syntax & Querying .SS "Description" diff --git a/deps/npm/man/man7/developers.7 b/deps/npm/man/man7/developers.7 index d559d9c8888d..540b5a82c41a 100644 --- a/deps/npm/man/man7/developers.7 +++ b/deps/npm/man/man7/developers.7 @@ -1,4 +1,4 @@ -.TH "DEVELOPERS" "7" "November 2026" "NPM@12.2.2" "" +.TH "DEVELOPERS" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBDevelopers\fR - Developer guide .SS "Description" diff --git a/deps/npm/man/man7/logging.7 b/deps/npm/man/man7/logging.7 index ec1ee7e6f3a0..da33fef66a09 100644 --- a/deps/npm/man/man7/logging.7 +++ b/deps/npm/man/man7/logging.7 @@ -1,4 +1,4 @@ -.TH "LOGGING" "7" "November 2026" "NPM@12.2.2" "" +.TH "LOGGING" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBLogging\fR - Why, What & How we Log .SS "Description" diff --git a/deps/npm/man/man7/orgs.7 b/deps/npm/man/man7/orgs.7 index fed16a661cf9..858ef9d7addb 100644 --- a/deps/npm/man/man7/orgs.7 +++ b/deps/npm/man/man7/orgs.7 @@ -1,4 +1,4 @@ -.TH "ORGANIZATIONS" "7" "November 2026" "NPM@12.2.2" "" +.TH "ORGANIZATIONS" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBOrganizations\fR - Working with teams & organizations .SS "Description" diff --git a/deps/npm/man/man7/package-spec.7 b/deps/npm/man/man7/package-spec.7 index e3dc2e778a11..5474f67a1dae 100644 --- a/deps/npm/man/man7/package-spec.7 +++ b/deps/npm/man/man7/package-spec.7 @@ -1,4 +1,4 @@ -.TH "SPEC" "7" "November 2026" "NPM@12.2.2" "" +.TH "SPEC" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBspec\fR - Package name specifier .SS "Description" diff --git a/deps/npm/man/man7/registry.7 b/deps/npm/man/man7/registry.7 index 63a92998e30f..a4655281691c 100644 --- a/deps/npm/man/man7/registry.7 +++ b/deps/npm/man/man7/registry.7 @@ -1,4 +1,4 @@ -.TH "REGISTRY" "7" "November 2026" "NPM@12.2.2" "" +.TH "REGISTRY" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBRegistry\fR - The JavaScript Package Registry .SS "Description" diff --git a/deps/npm/man/man7/removal.7 b/deps/npm/man/man7/removal.7 index 15f712cf886f..199e6538f558 100644 --- a/deps/npm/man/man7/removal.7 +++ b/deps/npm/man/man7/removal.7 @@ -1,4 +1,4 @@ -.TH "REMOVAL" "7" "November 2026" "NPM@12.2.2" "" +.TH "REMOVAL" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBRemoval\fR - Cleaning the slate .SS "Synopsis" diff --git a/deps/npm/man/man7/scope.7 b/deps/npm/man/man7/scope.7 index 222a2057d82c..cbd4de516a4e 100644 --- a/deps/npm/man/man7/scope.7 +++ b/deps/npm/man/man7/scope.7 @@ -1,4 +1,4 @@ -.TH "SCOPE" "7" "November 2026" "NPM@12.2.2" "" +.TH "SCOPE" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBScope\fR - Scoped packages .SS "Description" diff --git a/deps/npm/man/man7/scripts.7 b/deps/npm/man/man7/scripts.7 index 22825120fef3..9ee1a348a298 100644 --- a/deps/npm/man/man7/scripts.7 +++ b/deps/npm/man/man7/scripts.7 @@ -1,4 +1,4 @@ -.TH "SCRIPTS" "7" "November 2026" "NPM@12.2.2" "" +.TH "SCRIPTS" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBScripts\fR - How npm handles the "scripts" field .SS "Description" diff --git a/deps/npm/man/man7/workspaces.7 b/deps/npm/man/man7/workspaces.7 index 4f34d4ffb3dd..3dbbf14834ab 100644 --- a/deps/npm/man/man7/workspaces.7 +++ b/deps/npm/man/man7/workspaces.7 @@ -1,4 +1,4 @@ -.TH "WORKSPACES" "7" "November 2026" "NPM@12.2.2" "" +.TH "WORKSPACES" "7" "November 2026" "NPM@12.2.3" "" .SH "NAME" \fBWorkspaces\fR - Working with workspaces .SS "Description" diff --git a/deps/npm/node_modules/@npmcli/arborist/lib/arborist/isolated-reifier.js b/deps/npm/node_modules/@npmcli/arborist/lib/arborist/isolated-reifier.js index 784c389c4375..13415b07fc32 100644 --- a/deps/npm/node_modules/@npmcli/arborist/lib/arborist/isolated-reifier.js +++ b/deps/npm/node_modules/@npmcli/arborist/lib/arborist/isolated-reifier.js @@ -1,5 +1,6 @@ const { join } = require('node:path') const { depth } = require('treeverse') +const { getPaths: getBinPaths } = require('bin-links') const crypto = require('node:crypto') const { IsolatedNode, IsolatedLink } = require('../isolated-classes.js') const nameFromFolder = require('@npmcli/name-from-folder') @@ -435,11 +436,12 @@ module.exports = cls => class IsolatedReifier extends cls { return } - if (dep.package.bin) { - for (const bn in dep.package.bin) { - target.binPaths.push(join(dep.root.localPath, nmFolder, '.bin', bn)) - } - } + target.binPaths.push(...getBinPaths({ + pkg: dep.package, + path: join(dep.root.localPath, nmFolder, dep.name), + global: false, + top: false, + })) const pkg = { _id: dep.package._id, diff --git a/deps/npm/node_modules/@npmcli/arborist/lib/case-insensitive-map.js b/deps/npm/node_modules/@npmcli/arborist/lib/case-insensitive-map.js index afc6afbe0f98..63badcecd867 100644 --- a/deps/npm/node_modules/@npmcli/arborist/lib/case-insensitive-map.js +++ b/deps/npm/node_modules/@npmcli/arborist/lib/case-insensitive-map.js @@ -2,6 +2,9 @@ // are case-insensitive and unicode-normalizing, so we need to treat // node.children.get('FOO') and node.children.get('foo') as the same thing. +// ASCII keys without uppercase letters are already normalized. +const needsNormalization = /[A-Z\u0080-\uffff]/ + module.exports = class CIMap extends Map { #keys = new Map() @@ -13,7 +16,7 @@ module.exports = class CIMap extends Map { } #normKey (key) { - if (typeof key !== 'string') { + if (typeof key !== 'string' || !needsNormalization.test(key)) { return key } return key.normalize('NFKD').toLowerCase() diff --git a/deps/npm/node_modules/@npmcli/arborist/lib/edge.js b/deps/npm/node_modules/@npmcli/arborist/lib/edge.js index 1ed2446c8090..b563e8ca4c38 100644 --- a/deps/npm/node_modules/@npmcli/arborist/lib/edge.js +++ b/deps/npm/node_modules/@npmcli/arborist/lib/edge.js @@ -108,16 +108,16 @@ class Edge { return false } + // If there's no override we just use the spec. + if (!this.overrides?.keySpec) { + return depValid(node, this.spec, this.#accept, this.#from) + } + // NOTE: this condition means we explicitly do not support overriding // bundled dependencies if (node.inDepBundle) { return depValid(node, this.rawSpec, this.#accept, this.#from) } - - // If there's no override we just use the spec. - if (!this.overrides?.keySpec) { - return depValid(node, this.spec, this.#accept, this.#from) - } // There's some override. If the target node satisfies the overriding spec // then it's okay. if (depValid(node, this.spec, this.#accept, this.#from)) { diff --git a/deps/npm/node_modules/@npmcli/arborist/lib/node.js b/deps/npm/node_modules/@npmcli/arborist/lib/node.js index 13370a50ab47..4f555f2ef939 100644 --- a/deps/npm/node_modules/@npmcli/arborist/lib/node.js +++ b/deps/npm/node_modules/@npmcli/arborist/lib/node.js @@ -523,20 +523,25 @@ class Node { ) } - getBundler (path = []) { + getBundler (seen = new Set()) { + const isArray = Array.isArray(seen) // made a cycle, definitely not bundled! - if (path.includes(this)) { + if (isArray ? seen.includes(this) : seen.has(this)) { return null } - path.push(this) + if (isArray) { + seen.push(this) + } else { + seen.add(this) + } const parent = this[_parent] if (!parent) { return null } - const pBundler = parent.getBundler(path) + const pBundler = parent.getBundler(seen) if (pBundler) { return pBundler } @@ -553,7 +558,7 @@ class Node { // then they are not bundled. Ie, installing a package with // unmet bundled deps will not cause your deps to be bundled. for (const edge of this.edgesIn) { - const eBundler = edge.from.getBundler(path) + const eBundler = edge.from.getBundler(seen) if (!eBundler) { continue } @@ -1505,6 +1510,11 @@ class Node { } [_reloadNamedEdges] (name, rootLoc = this.location) { + if (!this.edgesOut.size && !this.children.size && !this.fsChildren.size) { + // With no outgoing edges or descendants, there is nothing to refresh or traverse. + return + } + const edge = this.edgesOut.get(name) // if we don't have an edge, do nothing, but keep descending const rootLocResolved = edge && edge.to && diff --git a/deps/npm/node_modules/@npmcli/arborist/lib/unreviewed-scripts.js b/deps/npm/node_modules/@npmcli/arborist/lib/unreviewed-scripts.js index f7bed387845e..e30a4540834f 100644 --- a/deps/npm/node_modules/@npmcli/arborist/lib/unreviewed-scripts.js +++ b/deps/npm/node_modules/@npmcli/arborist/lib/unreviewed-scripts.js @@ -18,6 +18,7 @@ const collectUnreviewedScripts = async ({ ignoreScripts = false, dangerouslyAllowAllScripts = false, includeWhenIgnored = false, + skipExtraneous = false, } = {}) => { // With ignore-scripts set, no scripts run, so execution callers bail out // here. approve/deny pass includeWhenIgnored so they keep listing @@ -57,6 +58,10 @@ const collectUnreviewedScripts = async ({ // must not be flagged (npm/cli#9562). continue } + if (skipExtraneous && node.extraneous && !node.parent && node.linksIn?.size === 0) { + // Reify never installs disconnected extraneous nodes, so their scripts cannot run. + continue + } const verdict = isScriptAllowed(node, resolvedPolicy) if (verdict === true || verdict === false) { diff --git a/deps/npm/node_modules/@npmcli/arborist/package.json b/deps/npm/node_modules/@npmcli/arborist/package.json index de1c6c973694..74efe09cb866 100644 --- a/deps/npm/node_modules/@npmcli/arborist/package.json +++ b/deps/npm/node_modules/@npmcli/arborist/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/arborist", - "version": "10.0.4", + "version": "10.0.5", "description": "Manage node_modules trees", "dependencies": { "@gar/promise-retry": "^1.0.0", diff --git a/deps/npm/node_modules/@npmcli/config/lib/definitions/definitions.js b/deps/npm/node_modules/@npmcli/config/lib/definitions/definitions.js index bd5c82363937..08b30b232b37 100644 --- a/deps/npm/node_modules/@npmcli/config/lib/definitions/definitions.js +++ b/deps/npm/node_modules/@npmcli/config/lib/definitions/definitions.js @@ -2512,6 +2512,11 @@ const definitions = { Optional dependencies that cannot be installed on the current platform or engine (a non-matching \`os\`, \`cpu\`, or \`libc\`) are not flagged, because their install scripts never run. + + Installation checks skip unused entries with no package parent or + incoming links. Local link targets that installation can still rebuild + remain subject to this check. \`npm rebuild\` and \`npm install-scripts ls\` + still check unused packages on disk. `, flatten, }), diff --git a/deps/npm/node_modules/@npmcli/config/package.json b/deps/npm/node_modules/@npmcli/config/package.json index 06f9020a7e64..fdc1924fe1a0 100644 --- a/deps/npm/node_modules/@npmcli/config/package.json +++ b/deps/npm/node_modules/@npmcli/config/package.json @@ -1,6 +1,6 @@ { "name": "@npmcli/config", - "version": "11.2.0", + "version": "11.2.1", "files": [ "bin/", "lib/" diff --git a/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/lib/index.js b/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/lib/index.js index dafc874463f6..e0ad5f13b203 100644 --- a/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/lib/index.js +++ b/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/lib/index.js @@ -24,7 +24,7 @@ const extractPathFromCmd = cmdshimContents => { } const extractPathFromCygwin = cmdshimContents => { - const matches = cmdshimContents.match(/"[$]basedir[/]([^"]+?)"\s+"[$]@"/) + const matches = cmdshimContents.match(/"[$]basedir(?:_win)?[/]([^"]+?)"\s+"[$]@"/) return matches && matches[1] } diff --git a/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/package.json b/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/package.json index cfd11bfe148b..213c0b16b724 100644 --- a/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/package.json +++ b/deps/npm/node_modules/bin-links/node_modules/read-cmd-shim/package.json @@ -1,12 +1,12 @@ { "name": "read-cmd-shim", - "version": "7.0.0", + "version": "7.0.1", "description": "Figure out what a cmd-shim is pointing at. This acts as the equivalent of fs.readlink.", "main": "lib/index.js", "devDependencies": { - "@npmcli/eslint-config": "^6.0.0", - "@npmcli/template-oss": "5.0.0", - "cmd-shim": "^8.0.0" + "@npmcli/eslint-config": "^7.0.0", + "@npmcli/template-oss": "5.1.1", + "cmd-shim": "^9.0.0" }, "scripts": { "test": "node --test './test/**/*.js'", @@ -36,7 +36,7 @@ }, "templateOSS": { "//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.", - "version": "5.0.0", + "version": "5.1.1", "publish": true, "testRunner": "node:test", "latestCiVersion": 24 diff --git a/deps/npm/node_modules/libnpmdiff/package.json b/deps/npm/node_modules/libnpmdiff/package.json index 8f6c89c9bd56..21b31e10290d 100644 --- a/deps/npm/node_modules/libnpmdiff/package.json +++ b/deps/npm/node_modules/libnpmdiff/package.json @@ -1,6 +1,6 @@ { "name": "libnpmdiff", - "version": "9.0.4", + "version": "9.0.5", "description": "The registry diff", "repository": { "type": "git", @@ -47,7 +47,7 @@ "tap": "^16.3.8" }, "dependencies": { - "@npmcli/arborist": "^10.0.4", + "@npmcli/arborist": "^10.0.5", "@npmcli/installed-package-contents": "^5.0.0", "binary-extensions": "^3.0.0", "diff": "^8.0.2", diff --git a/deps/npm/node_modules/libnpmexec/lib/index.js b/deps/npm/node_modules/libnpmexec/lib/index.js index 56dcf7c73694..ac63f5ba7702 100644 --- a/deps/npm/node_modules/libnpmexec/lib/index.js +++ b/deps/npm/node_modules/libnpmexec/lib/index.js @@ -263,6 +263,10 @@ const exec = async (opts) => { await mkdir(installDir, { recursive: true }) const npxArb = new Arborist({ ...flatOptions, + // a missing package must actually be installed to the npx cache, so it can be run, + // even when these are set: eg, a lifecycle script inherits npm_config_dry_run from `npm publish --dry-run` + dryRun: false, + packageLockOnly: false, path: installDir, }) const lockPath = join(installDir, 'concurrency.lock') diff --git a/deps/npm/node_modules/libnpmexec/lib/strict-allow-scripts-preflight.js b/deps/npm/node_modules/libnpmexec/lib/strict-allow-scripts-preflight.js index 579fd0c0fddf..383521fab8fa 100644 --- a/deps/npm/node_modules/libnpmexec/lib/strict-allow-scripts-preflight.js +++ b/deps/npm/node_modules/libnpmexec/lib/strict-allow-scripts-preflight.js @@ -24,6 +24,7 @@ const strictAllowScriptsPreflight = async (arb, opts) => { policy: opts.allowScripts || null, ignoreScripts: opts.ignoreScripts, dangerouslyAllowAllScripts: opts.dangerouslyAllowAllScripts, + skipExtraneous: true, }) if (unreviewed.length === 0) { diff --git a/deps/npm/node_modules/libnpmexec/package.json b/deps/npm/node_modules/libnpmexec/package.json index 0479de86500d..3e8bb37447bb 100644 --- a/deps/npm/node_modules/libnpmexec/package.json +++ b/deps/npm/node_modules/libnpmexec/package.json @@ -1,6 +1,6 @@ { "name": "libnpmexec", - "version": "11.0.5", + "version": "11.0.6", "files": [ "bin/", "lib/" @@ -65,7 +65,7 @@ }, "dependencies": { "@gar/promise-retry": "^1.0.0", - "@npmcli/arborist": "^10.0.4", + "@npmcli/arborist": "^10.0.5", "@npmcli/package-json": "^8.0.0", "@npmcli/run-script": "^11.0.0", "ci-info": "^4.0.0", diff --git a/deps/npm/node_modules/libnpmfund/package.json b/deps/npm/node_modules/libnpmfund/package.json index 1019a8a788ab..b9af7edc6d6f 100644 --- a/deps/npm/node_modules/libnpmfund/package.json +++ b/deps/npm/node_modules/libnpmfund/package.json @@ -1,6 +1,6 @@ { "name": "libnpmfund", - "version": "8.0.4", + "version": "8.0.5", "main": "lib/index.js", "files": [ "bin/", @@ -46,7 +46,7 @@ "tap": "^16.3.8" }, "dependencies": { - "@npmcli/arborist": "^10.0.4" + "@npmcli/arborist": "^10.0.5" }, "engines": { "node": "^22.22.2 || ^24.15.0 || >=26.0.0" diff --git a/deps/npm/node_modules/libnpmpack/package.json b/deps/npm/node_modules/libnpmpack/package.json index 5a33b697646c..2c5452b85da5 100644 --- a/deps/npm/node_modules/libnpmpack/package.json +++ b/deps/npm/node_modules/libnpmpack/package.json @@ -1,6 +1,6 @@ { "name": "libnpmpack", - "version": "10.0.4", + "version": "10.0.5", "description": "Programmatic API for the bits behind npm pack", "author": "GitHub Inc.", "main": "lib/index.js", @@ -37,7 +37,7 @@ "bugs": "https://github.com/npm/libnpmpack/issues", "homepage": "https://npmjs.com/package/libnpmpack", "dependencies": { - "@npmcli/arborist": "^10.0.4", + "@npmcli/arborist": "^10.0.5", "@npmcli/run-script": "^11.0.0", "npm-package-arg": "^14.0.0", "pacote": "^22.0.0" diff --git a/deps/npm/package.json b/deps/npm/package.json index b1e37e484a13..cc70defc03a6 100644 --- a/deps/npm/package.json +++ b/deps/npm/package.json @@ -1,5 +1,5 @@ { - "version": "12.2.2", + "version": "12.2.3", "name": "npm", "description": "a package manager for JavaScript", "workspaces": [ @@ -48,8 +48,8 @@ }, "dependencies": { "@isaacs/string-locale-compare": "^1.1.0", - "@npmcli/arborist": "^10.0.4", - "@npmcli/config": "^11.2.0", + "@npmcli/arborist": "^10.0.5", + "@npmcli/config": "^11.2.1", "@npmcli/fs": "^6.0.0", "@npmcli/git": "^8.0.0", "@npmcli/map-workspaces": "^6.0.0", @@ -76,11 +76,11 @@ "is-cidr": "^7.0.0", "json-parse-even-better-errors": "^6.0.0", "libnpmaccess": "^11.0.0", - "libnpmdiff": "^9.0.4", - "libnpmexec": "^11.0.5", - "libnpmfund": "^8.0.4", + "libnpmdiff": "^9.0.5", + "libnpmexec": "^11.0.6", + "libnpmfund": "^8.0.5", "libnpmorg": "^9.0.0", - "libnpmpack": "^10.0.4", + "libnpmpack": "^10.0.5", "libnpmpublish": "^12.0.1", "libnpmsearch": "^10.0.0", "libnpmteam": "^9.0.0", diff --git a/deps/npm/tap-snapshots/test/lib/docs.js.test.cjs b/deps/npm/tap-snapshots/test/lib/docs.js.test.cjs index 6e34b0832ea7..cb191c647766 100644 --- a/deps/npm/tap-snapshots/test/lib/docs.js.test.cjs +++ b/deps/npm/tap-snapshots/test/lib/docs.js.test.cjs @@ -2091,6 +2091,11 @@ Optional dependencies that cannot be installed on the current platform or engine (a non-matching \`os\`, \`cpu\`, or \`libc\`) are not flagged, because their install scripts never run. +Installation checks skip unused entries with no package parent or incoming +links. Local link targets that installation can still rebuild remain subject +to this check. \`npm rebuild\` and \`npm install-scripts ls\` still check unused +packages on disk. + #### \`strict-npmrc\` diff --git a/deps/npm/test/bin/windows-shims.js b/deps/npm/test/bin/windows-shims.js index d785fbe7b1c5..8dbdf6359bc8 100644 --- a/deps/npm/test/bin/windows-shims.js +++ b/deps/npm/test/bin/windows-shims.js @@ -177,7 +177,9 @@ t.test('run shims', t => { chmodSync(join(path, shim), 0o755) } - const { ProgramFiles = '/', SystemRoot = '/', NYC_CONFIG, WINDOWS_SHIMS_TEST } = process.env + const { + ProgramFiles = '/', SystemRoot = '/', NYC_CONFIG, WINDOWS_SHIMS_TEST, CYGWIN_ROOT, + } = process.env const skipDefault = WINDOWS_SHIMS_TEST || process.platform === 'win32' ? null : 'test not relevant on platform' @@ -188,13 +190,17 @@ t.test('run shims', t => { git: join(ProgramFiles, 'Git', 'bin', 'bash.exe'), 'user git': join(ProgramFiles, 'Git', 'usr', 'bin', 'bash.exe'), wsl: join(SystemRoot, 'System32', 'bash.exe'), - cygwin: resolve(SystemRoot, '/', 'cygwin64', 'bin', 'bash.exe'), + cygwin: CYGWIN_ROOT && join(CYGWIN_ROOT, 'bin', 'bash.exe'), }).map(([name, cmd]) => { let match = {} const skip = { reason: skipDefault, fail: WINDOWS_SHIMS_TEST } - const isBash = cmd.endsWith('bash.exe') + const isBash = name === 'cygwin' || cmd.endsWith('bash.exe') const testName = `${name} ${isBash ? 'bash' : ''}`.trim() + if (!skip.reason && name === 'cygwin' && !CYGWIN_ROOT) { + skip.reason = 'CYGWIN_ROOT is not set' + } + if (!skip.reason) { if (isBash) { try { diff --git a/deps/npm/test/fixtures/allow-scripts-orphan.js b/deps/npm/test/fixtures/allow-scripts-orphan.js new file mode 100644 index 000000000000..9276c573f4ec --- /dev/null +++ b/deps/npm/test/fixtures/allow-scripts-orphan.js @@ -0,0 +1,32 @@ +const { workspaceMock } = require('./mock-npm.js') + +module.exports = (t, { workspace = true, allowScripts, requiredScripts = false } = {}) => { + const fixture = workspaceMock(t, { + workspaces: { app: { 'abbrev@1.0.0': {} } }, + }) + const pkg = JSON.parse(fixture['package.json']) + const lock = JSON.parse(fixture['package-lock.json']) + + if (!workspace) { + delete pkg.workspaces + pkg.dependencies = { app: 'file:app' } + lock.packages[''] = { ...pkg } + } + pkg.allowScripts = allowScripts + + // The missing intermediate directory leaves this orphan in the ideal-tree inventory. + lock.packages['app/node_modules/abbrev/node_modules/orphan'] = { + version: '1.0.0', + resolved: 'https://registry.npmjs.org/orphan/-/orphan-1.0.0.tgz', + hasInstallScript: true, + extraneous: true, + } + if (requiredScripts) { + lock.packages['node_modules/abbrev'].hasInstallScript = true + } + + delete fixture.node_modules + fixture['package.json'] = JSON.stringify(pkg) + fixture['package-lock.json'] = JSON.stringify(lock) + return fixture +} diff --git a/deps/npm/test/lib/commands/ci.js b/deps/npm/test/lib/commands/ci.js index a90ca4b0cffe..53d49fbb9e82 100644 --- a/deps/npm/test/lib/commands/ci.js +++ b/deps/npm/test/lib/commands/ci.js @@ -6,6 +6,8 @@ const { loadNpmWithRegistry: loadMockNpm, workspaceMock, } = require('../../fixtures/mock-npm') +const orphanFixture = require('../../fixtures/allow-scripts-orphan.js') +const tspawk = require('../../fixtures/tspawk.js') // t.cleanSnapshot = str => str.replace(/ in [0-9ms]+/g, ' in {TIME}') @@ -413,6 +415,69 @@ t.test('should throw error when ideal inventory mismatches virtual', async t => t.equal(fs.existsSync(nmTestFile), true, 'does not remove node_modules') }) +t.test('ci with lockfile-only orphans', async t => { + tspawk(t) + const testOrphan = async (t, { + workspace = true, + allowScripts, + strict = true, + json = false, + } = {}) => { + const prefixDir = orphanFixture(t, { workspace, allowScripts }) + const { npm, registry, assert, logs, clearOutput, joinedOutput } = await loadMockNpm(t, { + config: { audit: false, fund: false, 'strict-allow-scripts': strict, json }, + prefixDir, + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'tarballs/abbrev@1.0.0'), + }) + + await npm.exec('ci', []) + + assert.packageInstalled('node_modules/abbrev@1.0.0') + assert.fileShouldNotExist('app/node_modules/abbrev/node_modules/orphan') + t.equal( + fs.readFileSync(path.join(npm.prefix, 'package-lock.json'), 'utf8'), + prefixDir['package-lock.json'], + 'does not change the lockfile' + ) + t.strictSame(logs.warn.byTitle('install-scripts'), [], 'no orphan warning') + if (json) { + t.notOk(Object.hasOwn(JSON.parse(joinedOutput()), 'unreviewedScripts'), 'no orphan entry') + } else { + clearOutput() + await npm.exec('install-scripts', ['ls']) + t.match(joinedOutput(), /No packages with unreviewed install scripts/) + } + } + + for (const workspace of [true, false]) { + for (const allowScripts of [undefined, { orphan: false }]) { + const source = workspace ? 'workspace' : 'file link' + const policy = allowScripts ? 'denied' : 'unreviewed' + for (const strict of [false, true]) { + await t.test(`${source}, ${policy} orphan, strict=${strict}`, + t => testOrphan(t, { workspace, allowScripts, strict })) + } + } + } + + await t.test('JSON excludes the orphan', t => testOrphan(t, { json: true })) + + await t.test('still rejects a required unreviewed package', async t => { + const { npm } = await loadMockNpm(t, { + config: { audit: false, 'strict-allow-scripts': true }, + prefixDir: orphanFixture(t, { requiredScripts: true }), + }) + await t.rejects(npm.exec('ci', []), { + code: 'ESTRICTALLOWSCRIPTS', + message: /1 package\(s\) have install scripts not covered by allowScripts:\n {2}abbrev@1\.0\.0/, + }) + }) +}) + t.test('should remove dirty node_modules with unhoisted workspace module', async t => { const { npm, registry, assert } = await loadMockNpm(t, { prefixDir: workspaceMock(t, { diff --git a/deps/npm/test/lib/commands/exec.js b/deps/npm/test/lib/commands/exec.js index 87422d1519a4..7abd17e31a8e 100644 --- a/deps/npm/test/lib/commands/exec.js +++ b/deps/npm/test/lib/commands/exec.js @@ -52,6 +52,42 @@ t.test('registry package', async t => { t.ok(exists.isFile(), 'bin ran, creating file') }) +t.test('registry package with dry-run set', async t => { + const registry = new MockRegistry({ + tap: t, + registry: 'https://registry.npmjs.org/', + }) + + const manifest = registry.manifest({ name: '@npmcli/npx-dry-run-test' }) + manifest.versions['1.0.0'].bin = { 'npx-dry-run-test': 'index.js' } + + const { npm } = await loadMockNpm(t, { + config: { + audit: false, + yes: true, + 'dry-run': true, + }, + prefixDir: { + 'npm-exec-test': { + 'package.json': JSON.stringify(manifest), + 'index.js': `#!/usr/bin/env node + require('fs').writeFileSync('npm-exec-test-success', '')`, + }, + }, + }) + + await registry.package({ + times: 2, + manifest, + tarballs: { + '1.0.0': path.join(npm.prefix, 'npm-exec-test'), + } }) + + await npm.exec('exec', ['@npmcli/npx-dry-run-test']) + const exists = await fs.stat(path.join(npm.prefix, 'npm-exec-test-success')) + t.ok(exists.isFile(), 'package was installed and bin ran, creating file') +}) + t.test('--prefix', async t => { const registry = new MockRegistry({ tap: t, diff --git a/deps/npm/test/lib/commands/install-scripts.js b/deps/npm/test/lib/commands/install-scripts.js index fd7051c7e441..9a7c20591445 100644 --- a/deps/npm/test/lib/commands/install-scripts.js +++ b/deps/npm/test/lib/commands/install-scripts.js @@ -8,11 +8,17 @@ const mockNpm = async (t, opts = {}) => { return _mockNpm(t, opts) } -const setupProject = ({ allowScripts, withScripts = ['canvas'], noScripts = [] } = {}) => { +const setupProject = ({ + allowScripts, + withScripts = ['canvas'], + noScripts = [], + extraneous = false, +} = {}) => { const pkg = { name: 'host', version: '1.0.0', - dependencies: Object.fromEntries([...withScripts, ...noScripts].map((n) => [n, '*'])), + dependencies: extraneous ? {} + : Object.fromEntries([...withScripts, ...noScripts].map((n) => [n, '*'])), } if (allowScripts !== undefined) { pkg.allowScripts = allowScripts @@ -140,6 +146,29 @@ t.test('install-scripts ls lists unreviewed packages', async t => { t.match(out, /sharp@1\.0\.0/) }) +t.test('install-scripts ls lists extraneous packages on disk', async t => { + for (const json of [false, true]) { + await t.test(json ? 'json' : 'text', async t => { + const { npm, joinedOutput } = await mockNpm(t, { + prefixDir: setupProject({ extraneous: true }), + config: { json }, + }) + await npm.exec('install-scripts', ['ls']) + if (json) { + t.strictSame(JSON.parse(joinedOutput()), { + allowScripts: [{ + name: 'canvas', + changes: [{ key: 'canvas@1.0.0', change: 'pending' }], + }], + }) + } else { + t.match(joinedOutput(), /1 package has install scripts blocked/) + t.match(joinedOutput(), /canvas@1\.0\.0/) + } + }) + } +}) + t.test('install-scripts ls with no unreviewed says so', async t => { const { npm, joinedOutput } = await mockNpm(t, { prefixDir: setupProject({ allowScripts: { canvas: true }, withScripts: ['canvas'] }), diff --git a/deps/npm/test/lib/commands/install.js b/deps/npm/test/lib/commands/install.js index 3961b7f02e0c..f1d6a21efcd0 100644 --- a/deps/npm/test/lib/commands/install.js +++ b/deps/npm/test/lib/commands/install.js @@ -16,6 +16,7 @@ const { loadNpmWithRegistry: loadMockNpm, workspaceMock, } = require('../../fixtures/mock-npm') +const orphanFixture = require('../../fixtures/allow-scripts-orphan.js') // tspawk calls preventUnmatched which assures that no scripts run if we don't mock any const spawk = tspawk(t) @@ -597,6 +598,132 @@ t.test('completion', async t => { }) }) +t.test('install with an extraneous local link', async t => { + const setup = (t, config = {}) => loadMockNpm(t, { + config: { audit: false, fund: false, 'package-lock': false, ...config }, + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + foo: { + 'package.json': JSON.stringify({ + name: 'foo', + version: '1.0.0', + scripts: { install: 'echo linked-install' }, + }), + }, + node_modules: { foo: t.fixture('symlink', '../foo') }, + }, + }) + + await t.test('strict mode rejects a retained link target', async t => { + const { npm, assert } = await setup(t, { 'strict-allow-scripts': true }) + await t.rejects(npm.exec('install', []), { + code: 'ESTRICTALLOWSCRIPTS', + message: /foo@1\.0\.0/, + }) + assert.fileShouldExist('node_modules/foo/package.json') + }) + + await t.test('normal mode keeps the blocked-script warning', async t => { + const { npm, logs } = await setup(t) + await npm.exec('install', []) + const warnings = logs.warn.byTitle('install-scripts').join('\n') + t.match(warnings, /1 package had install scripts blocked/) + t.match(warnings, /foo@1\.0\.0/) + }) + + await t.test('JSON keeps the blocked-script entry', async t => { + const { npm, joinedOutput } = await setup(t, { json: true }) + await npm.exec('install', []) + t.strictSame(JSON.parse(joinedOutput()).unreviewedScripts, [{ + name: 'foo', + version: '1.0.0', + path: path.join(npm.prefix, 'foo'), + scripts: { install: 'echo linked-install' }, + }]) + }) + + await t.test('the bypass still rebuilds the retained link', async t => { + const { npm } = await setup(t, { + 'strict-allow-scripts': true, + 'dangerously-allow-all-scripts': true, + }) + let calls = 0 + spawk.spawn(/.*/, args => { + calls++ + return args.includes('echo linked-install') + }) + await npm.exec('install', []) + t.equal(calls, 1, 'ran the linked package install script') + }) + + await t.test('pruning the link does not reject or warn about its detached target', async t => { + const { npm, logs, assert } = await setup(t, { + 'strict-allow-scripts': true, + 'package-lock': true, + }) + await npm.exec('install', []) + assert.fileShouldNotExist('node_modules/foo') + assert.fileShouldExist('foo/package.json') + t.strictSame(logs.warn.byTitle('install-scripts'), []) + }) +}) + +t.test('install with lockfile-only orphans', async t => { + const testOrphan = async (t, { + workspace = true, + allowScripts, + strict = true, + json = false, + } = {}) => { + const { npm, registry, assert, logs, clearOutput, joinedOutput } = await loadMockNpm(t, { + config: { audit: false, fund: false, 'strict-allow-scripts': strict, json }, + prefixDir: orphanFixture(t, { workspace, allowScripts }), + }) + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: path.join(npm.prefix, 'tarballs/abbrev@1.0.0'), + }) + + await npm.exec('install', []) + + assert.packageInstalled('node_modules/abbrev@1.0.0') + assert.fileShouldNotExist('app/node_modules/abbrev/node_modules/orphan') + t.strictSame(logs.warn.byTitle('install-scripts'), [], 'no orphan warning') + if (json) { + t.notOk(Object.hasOwn(JSON.parse(joinedOutput()), 'unreviewedScripts'), 'no orphan entry') + } else { + clearOutput() + await npm.exec('install-scripts', ['ls']) + t.match(joinedOutput(), /No packages with unreviewed install scripts/) + } + } + + for (const workspace of [true, false]) { + for (const allowScripts of [undefined, { orphan: false }]) { + const source = workspace ? 'workspace' : 'file link' + const policy = allowScripts ? 'denied' : 'unreviewed' + for (const strict of [false, true]) { + await t.test(`${source}, ${policy} orphan, strict=${strict}`, + t => testOrphan(t, { workspace, allowScripts, strict })) + } + } + } + + await t.test('JSON excludes the orphan', t => testOrphan(t, { json: true })) + + await t.test('still rejects a required unreviewed package', async t => { + const { npm } = await loadMockNpm(t, { + config: { audit: false, 'strict-allow-scripts': true }, + prefixDir: orphanFixture(t, { requiredScripts: true }), + }) + await t.rejects(npm.exec('install', []), { + code: 'ESTRICTALLOWSCRIPTS', + message: /1 package\(s\) have install scripts not covered by allowScripts:\n {2}abbrev@1\.0\.0/, + }) + }) +}) + t.test('should install in workspace with unhoisted module', async t => { const { npm, registry, assert } = await loadMockNpm(t, { prefixDir: workspaceMock(t, { diff --git a/deps/npm/test/lib/commands/rebuild.js b/deps/npm/test/lib/commands/rebuild.js index cfd2d2511e19..5bd2295f6477 100644 --- a/deps/npm/test/lib/commands/rebuild.js +++ b/deps/npm/test/lib/commands/rebuild.js @@ -244,6 +244,33 @@ t.test('emits blocked warning for unreviewed install scripts', async t => { ) }) +t.test('strict rebuild rejects extraneous packages on disk', async t => { + for (const args of [[], ['canvas']]) { + await t.test(args.length ? 'named package' : 'all packages', async t => { + const { npm, prefix } = await setupMockNpm(t, { + config: { 'strict-allow-scripts': true }, + prefixDir: { + 'package.json': JSON.stringify({ name: 'host', version: '1.0.0' }), + node_modules: { + canvas: { + 'package.json': JSON.stringify({ + name: 'canvas', + version: '1.0.0', + scripts: { install: "node -e \"require('fs').writeFileSync('ran', '')\"" }, + }), + }, + }, + }, + }) + await t.rejects(npm.exec('rebuild', args), { + code: 'ESTRICTALLOWSCRIPTS', + message: /canvas@1\.0\.0/, + }) + t.notOk(fs.existsSync(resolve(prefix, 'node_modules/canvas/ran')), 'script did not run') + }) + } +}) + t.test('global advisory warning points at npm config set, not approve-scripts', async t => { const { npm, logs } = await setupMockNpm(t, { config: { diff --git a/deps/npm/test/lib/commands/unpublish.js b/deps/npm/test/lib/commands/unpublish.js index 4c8bc5e058af..26520ea2119b 100644 --- a/deps/npm/test/lib/commands/unpublish.js +++ b/deps/npm/test/lib/commands/unpublish.js @@ -166,6 +166,49 @@ t.test('unpublish <pkg>@version last version', async t => { ) }) +t.test('unpublish <pkg>@version of a packument with no versions', async t => { + const { npm } = await loadMockNpm(t, { + config: { + ...auth, + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + const manifest = registry.manifest({ name: pkg }) + delete manifest.versions + await registry.package({ manifest, query: { write: true } }) + + await t.rejects( + npm.exec('unpublish', ['test-package@1.0.0']), + /the registry returned no versions for test-package/ + ) +}) + +t.test('unpublish <pkg>@version of a packument with no versions with --force', async t => { + const { npm } = await loadMockNpm(t, { + config: { + force: true, + ...auth, + }, + }) + const registry = new MockRegistry({ + tap: t, + registry: npm.config.get('registry'), + authorization: 'test-auth-token', + }) + const manifest = registry.manifest({ name: pkg }) + manifest.versions = {} + await registry.package({ manifest, query: { write: true } }) + + await t.rejects( + npm.exec('unpublish', ['test-package@1.0.0']), + /the registry returned no versions for test-package/ + ) +}) + t.test('no version found in package.json no force', async t => { const { npm } = await loadMockNpm(t, { config: { diff --git a/deps/npm/test/lib/utils/check-allow-scripts.js b/deps/npm/test/lib/utils/check-allow-scripts.js index c67ec2a7cd70..f7fe9c6367c1 100644 --- a/deps/npm/test/lib/utils/check-allow-scripts.js +++ b/deps/npm/test/lib/utils/check-allow-scripts.js @@ -95,6 +95,29 @@ t.test('skips project root, workspace, and linked nodes', async t => { t.strictSame(result, []) }) +t.test('only skips extraneous nodes when requested', async t => { + const checkAllowScripts = mockCheck(t) + const orphan = { + ...node({ name: 'orphan', scripts: { install: 'x' }, isRegistryDependency: false }), + extraneous: true, + edgesIn: new Set(), + parent: null, + linksIn: new Set(), + } + for (const skipExtraneous of [undefined, false, true]) { + const result = await checkAllowScripts({ + arb: arb({ nodes: [orphan], allowScripts: { orphan: false } }), + npm: { flatOptions: {} }, + skipExtraneous, + }) + t.strictSame( + result.map(({ node: entry }) => entry), + skipExtraneous ? [] : [orphan], + `skipExtraneous=${skipExtraneous}` + ) + } +}) + t.test('skips nodes with no install-relevant scripts', async t => { const checkAllowScripts = mockCheck(t) const result = await checkAllowScripts({ diff --git a/deps/npm/test/lib/utils/is-windows.js b/deps/npm/test/lib/utils/is-windows.js new file mode 100644 index 000000000000..a8606da3a781 --- /dev/null +++ b/deps/npm/test/lib/utils/is-windows.js @@ -0,0 +1,65 @@ +const t = require('tap') +const { isGitBashMsystem } = require('../../../lib/utils/is-windows.js') + +t.test('isGitBashMsystem recognizes Git Bash / MSYS2 shells', t => { + t.equal(isGitBashMsystem('MINGW64'), true) + t.equal(isGitBashMsystem('MINGW32'), true) + t.equal(isGitBashMsystem('UCRT64'), true, 'Git for Windows 2.56+ default') + t.equal(isGitBashMsystem('CLANG64'), true) + t.equal(isGitBashMsystem('CLANG32'), true) + t.equal(isGitBashMsystem('CLANGARM64'), true) + t.equal(isGitBashMsystem('MSYS'), false) + t.equal(isGitBashMsystem('nogmingw'), false) + t.equal(isGitBashMsystem(undefined), false) + t.equal(isGitBashMsystem(''), false) + t.end() +}) + +t.test('isWindowsShell respects UCRT64 via fresh require', t => { + const path = require.resolve('../../../lib/utils/is-windows.js') + const origPlatform = Object.getOwnPropertyDescriptor(process, 'platform') + const origMsystem = process.env.MSYSTEM + const origTerm = process.env.TERM + + const load = (platform, msystem, term) => { + delete require.cache[path] + Object.defineProperty(process, 'platform', { value: platform, configurable: true }) + if (msystem === undefined) { + delete process.env.MSYSTEM + } else { + process.env.MSYSTEM = msystem + } + if (term === undefined) { + delete process.env.TERM + } else { + process.env.TERM = term + } + return require(path).isWindowsShell + } + + t.teardown(() => { + delete require.cache[path] + if (origPlatform) { + Object.defineProperty(process, 'platform', origPlatform) + } + if (origMsystem === undefined) { + delete process.env.MSYSTEM + } else { + process.env.MSYSTEM = origMsystem + } + if (origTerm === undefined) { + delete process.env.TERM + } else { + process.env.TERM = origTerm + } + }) + + t.equal(load('linux', undefined, undefined), false) + t.equal(load('win32', undefined, undefined), true) + t.equal(load('win32', 'MINGW64', undefined), false) + t.equal(load('win32', 'UCRT64', undefined), false, 'UCRT64 Git Bash is not cmd.exe') + t.equal(load('win32', 'CLANG64', undefined), false) + t.equal(load('win32', undefined, 'cygwin'), false) + t.equal(load('win32', 'nogmingw', undefined), true) + t.end() +}) diff --git a/deps/npm/test/lib/utils/reify-finish.js b/deps/npm/test/lib/utils/reify-finish.js index a1dd165034a4..56ef51d75abf 100644 --- a/deps/npm/test/lib/utils/reify-finish.js +++ b/deps/npm/test/lib/utils/reify-finish.js @@ -23,8 +23,11 @@ const mockReififyFinish = async (t, { actualTree = {}, otherDirs = {}, ...config config, }) + let reportedScripts const reifyFinish = tmock(t, '{LIB}/utils/reify-finish.js', { - '{LIB}/utils/reify-output.js': () => {}, + '{LIB}/utils/reify-output.js': (_npm, _arb, { unreviewedScripts }) => { + reportedScripts = unreviewedScripts + }, }) await reifyFinish(mock.npm, { @@ -39,6 +42,7 @@ const mockReififyFinish = async (t, { actualTree = {}, otherDirs = {}, ...config return { builtinRc, + reportedScripts, ...mock, } } @@ -51,6 +55,31 @@ t.test('ok by default', async t => { t.strictSame(mock.builtinRc.data, { key: 'value' }) }) +t.test('only omits disconnected orphans from post-install reporting', async t => { + for (const strict of [false, true]) { + await t.test(`strict=${strict}`, async t => { + const candidate = (name, properties = {}) => ({ + name, + package: { name, version: '1.0.0', scripts: { install: `echo ${name}` } }, + extraneous: true, + parent: null, + linksIn: new Set(), + ...properties, + }) + const orphan = candidate('orphan') + const attached = candidate('attached', { parent: {} }) + const linked = candidate('linked', { linksIn: new Set([{}]) }) + const { reportedScripts } = await mockReififyFinish(t, { + 'strict-allow-scripts': strict, + actualTree: { + inventory: new Map([orphan, attached, linked].map(n => [n.name, n])), + }, + }) + t.strictSame(reportedScripts.map(({ node }) => node), [attached, linked]) + }) + } +}) + t.test('should not write if no global npm module', async t => { const mock = await mockReififyFinish(t, { global: true, diff --git a/deps/npm/test/lib/utils/strict-allow-scripts-preflight.js b/deps/npm/test/lib/utils/strict-allow-scripts-preflight.js index c67a6e4853a1..d8115857b64f 100644 --- a/deps/npm/test/lib/utils/strict-allow-scripts-preflight.js +++ b/deps/npm/test/lib/utils/strict-allow-scripts-preflight.js @@ -1,4 +1,8 @@ const t = require('tap') +const { join } = require('node:path') +const Arborist = require('@npmcli/arborist') +const { loadNpmWithRegistry } = require('../../fixtures/mock-npm.js') +const orphanFixture = require('../../fixtures/allow-scripts-orphan.js') const preflight = require('../../../lib/utils/strict-allow-scripts-preflight.js') @@ -24,9 +28,18 @@ const tree = (nodes) => ({ inventory: new Map(nodes.map((n, i) => [`node_modules/${n.name}-${i}`, n])), }) -const makeArb = ({ ideal, actual, allowScripts = null } = {}) => { +const orphan = () => ({ + ...node({ name: 'orphan' }), + extraneous: true, + isRegistryDependency: false, + edgesIn: new Set(), + parent: null, + linksIn: new Set(), +}) + +const makeArb = ({ ideal, actual, allowScripts = null, options = {} } = {}) => { const arb = { - options: { allowScripts, ignoreScripts: false }, + options: { allowScripts, ignoreScripts: false, ...options }, idealTree: ideal ?? null, actualTree: actual ?? null, } @@ -89,6 +102,99 @@ t.test('passes when the only unreviewed node is inert (platform-incompatible opt t.pass('no error thrown for inert node') }) +t.test('skips disconnected orphans when pruning is disabled', async t => { + for (const installStrategy of ['hoisted', 'linked']) { + await t.test(installStrategy, async t => { + const { npm, prefix, registry, assert } = await loadNpmWithRegistry(t, { + config: { + audit: false, + 'strict-allow-scripts': true, + 'install-strategy': installStrategy, + }, + prefixDir: orphanFixture(t, { allowScripts: { orphan: false } }), + }) + const opts = { + ...npm.flatOptions, + path: prefix, + prune: false, + allowScripts: { orphan: false }, + } + const arb = new Arborist(opts) + await arb.buildIdealTree(opts) + const location = 'app/node_modules/abbrev/node_modules/orphan' + const unused = arb.idealTree.inventory.get(location) + t.match(unused, { extraneous: true, parent: null }) + t.equal(unused.linksIn.size, 0, 'the orphan has no incoming links') + + await preflight({ arb, npm, idealTreeOpts: opts }) + + const manifest = registry.manifest({ name: 'abbrev' }) + await registry.tarball({ + manifest: manifest.versions['1.0.0'], + tarball: join(prefix, 'tarballs/abbrev@1.0.0'), + }) + await arb.reify(opts) + const installedPath = installStrategy === 'linked' ? 'app/node_modules' : 'node_modules' + assert.packageInstalled(`${installedPath}/abbrev@1.0.0`) + assert.fileShouldNotExist(location) + t.equal(arb.scriptsRun.size, 0, 'no install scripts ran') + const actual = await new Arborist(opts).loadActual() + t.notOk([...actual.inventory.values()].some(n => n.name === 'orphan'), + 'the installed tree has no orphan') + }) + } +}) + +t.test('skips orphans in a newly built ideal tree', async t => { + const arb = makeArb() + arb.buildIdealTree = async () => { + arb.idealTree = tree([orphan()]) + } + await t.resolves(preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + })) + t.ok(arb.idealTree, 'built the ideal tree') +}) + +t.test('does not skip an extraneous target with an incoming link', async t => { + const target = { ...orphan(), linksIn: new Set([{}]) } + const arb = makeArb({ + ideal: tree([target]), + allowScripts: { orphan: false }, + options: { prune: false }, + }) + await t.rejects(preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: { prune: false }, + }), { code: 'ESTRICTALLOWSCRIPTS', message: /orphan@1\.0\.0/ }) +}) + +t.test('skipping an orphan does not skip a required unreviewed package', async t => { + const arb = makeArb({ ideal: tree([orphan(), node({ name: 'required' })]) }) + await t.rejects(preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + idealTreeOpts: {}, + }), { + code: 'ESTRICTALLOWSCRIPTS', + message: /1 package\(s\) have install scripts not covered by allowScripts:\n {2}required@1\.0\.0/, + }) +}) + +t.test('does not skip actual-tree orphans even with an ideal tree', async t => { + const arb = makeArb({ + ideal: tree([]), + actual: tree([orphan()]), + }) + await t.rejects(preflight({ + arb, + npm: { flatOptions: { strictAllowScripts: true } }, + }), { code: 'ESTRICTALLOWSCRIPTS', message: /orphan@1\.0\.0/ }) +}) + t.test('passes when all install-script nodes are explicitly approved', async t => { const arb = makeArb({ ideal: tree([node({ name: 'canvas' })]), diff --git a/deps/simdjson/simdjson.cpp b/deps/simdjson/simdjson.cpp index 6db84f295573..537a7ab6a9a5 100644 --- a/deps/simdjson/simdjson.cpp +++ b/deps/simdjson/simdjson.cpp @@ -1,4 +1,4 @@ -/* auto-generated on 2026-10-31 19:14:12 -0400. version 5.1.1 Do not edit! */ +/* auto-generated on 2026-11-14 18:54:03 -0500. version 5.2.0 Do not edit! */ /* including simdjson.cpp: */ /* begin file simdjson.cpp */ #define SIMDJSON_SRC_SIMDJSON_CPP @@ -185,6 +185,24 @@ #endif #endif // !defined(SIMDJSON_SUPPORTS_CHAR8_T) +// std::string::resize_and_overwrite (C++23) is available. +#if !defined(SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE) +#if defined(__cpp_lib_string_resize_and_overwrite) && __cpp_lib_string_resize_and_overwrite >= 202110L +#define SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE 1 +#else +#define SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE 0 +#endif +#endif // !defined(SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE) + +// std::string can be used in constant expressions (C++20, e.g., libstdc++ 12 or better). +#if !defined(SIMDJSON_SUPPORTS_CONSTEXPR_STRING) +#if defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#define SIMDJSON_SUPPORTS_CONSTEXPR_STRING 1 +#else +#define SIMDJSON_SUPPORTS_CONSTEXPR_STRING 0 +#endif +#endif // !defined(SIMDJSON_SUPPORTS_CONSTEXPR_STRING) + // The C++23 fixed-width floating-point types std::float32_t and std::float64_t // (<stdfloat>) are available. They are optional even in C++23: a compiler that // provides them predefines __STDCPP_FLOAT32_T__ and __STDCPP_FLOAT64_T__. @@ -217,11 +235,11 @@ #if !defined(SIMDJSON_CONSTEVAL) -#if defined(__cpp_consteval) && __cpp_consteval >= 201811L && defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#if defined(__cpp_consteval) && __cpp_consteval >= 201811L && SIMDJSON_SUPPORTS_CONSTEXPR_STRING #define SIMDJSON_CONSTEVAL 1 #else #define SIMDJSON_CONSTEVAL 0 -#endif // defined(__cpp_consteval) && __cpp_consteval >= 201811L && defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#endif // defined(__cpp_consteval) && __cpp_consteval >= 201811L && SIMDJSON_SUPPORTS_CONSTEXPR_STRING #endif // !defined(SIMDJSON_CONSTEVAL) // SIMDJSON_CONSTEXPR_STRING is 'constexpr' when the standard library supports @@ -229,11 +247,11 @@ // lets functions that build a std::string be constant expressions when possible // while still compiling against older standard libraries. #if !defined(SIMDJSON_CONSTEXPR_STRING) -#if defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#if SIMDJSON_SUPPORTS_CONSTEXPR_STRING #define SIMDJSON_CONSTEXPR_STRING constexpr #else #define SIMDJSON_CONSTEXPR_STRING -#endif // defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#endif // SIMDJSON_SUPPORTS_CONSTEXPR_STRING #endif // !defined(SIMDJSON_CONSTEXPR_STRING) #endif // SIMDJSON_COMPILER_CHECK_H /* end file simdjson/compiler_check.h */ @@ -309,7 +327,25 @@ using std::size_t; #define SIMDJSON_IS_LSX 1 // Adjust for runtime dispatching support. -#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__NVCOMPILER) +// +// LASX runtime dispatching is deliberately disabled by default, so that the +// LSX kernel is used even when the processor supports LASX. On a Loongson +// 3A6000, our LASX kernel parses about 5% slower overall than our LSX +// kernel (stage 1 about 14% slower), with both GCC 15 and LLVM. The 256-bit +// registers do not help: stage 1 is limited by moving bitmasks from vector +// registers to general-purpose registers, and with LASX each bitmask needs +// a cross-lane permutation (3 cycles) and a slower vector-to-GPR move +// (xvpickve2gr is 2 cycles slower than vpickve2gr). +// +// Define SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH to 0 to enable LASX runtime +// dispatching (GCC 15+ or LLVM). Compiling with -mlasx selects the LASX +// kernel regardless of this macro. See doc/implementation-selection.md. +#ifndef SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH + #define SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH 1 +#endif +#if SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH + #define SIMDJSON_IMPLEMENTATION_LASX 0 +#elif defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__NVCOMPILER) #if __GNUC__ > 15 || (__GNUC__ == 15 && __GNUC_MINOR__ >= 0) // We are ok, we will support runtime dispatch for LASX. #else @@ -318,14 +354,15 @@ using std::size_t; // Loongson users should update to GCC 15 or better. #define SIMDJSON_IMPLEMENTATION_LASX 0 #endif +#elif defined(__clang__) + // LLVM supports runtime dispatch for LASX through the target attribute. + // See simdjson/lasx/intrinsics.h. #else - // We are not using GCC, so we assume that we can support runtime dispatch for LASX. + // We are not using GCC or LLVM, so we do not support runtime dispatch for LASX. // https://godbolt.org/z/jcMnrjYhs #define SIMDJSON_IMPLEMENTATION_LASX 0 #endif - - #endif #elif defined(__PPC64__) || defined(_M_PPC64) #define SIMDJSON_IS_PPC64 1 @@ -3139,10 +3176,25 @@ template <typename T> concept string_view_like = std::is_convertible_v<T, std::string_view> && !std::is_convertible_v<T, const char*>; +template <typename T> +concept optional_type = requires(std::remove_cvref_t<T> obj) { + typename std::remove_cvref_t<T>::value_type; + { obj.value() } -> std::same_as<typename std::remove_cvref_t<T>::value_type&>; + requires requires(typename std::remove_cvref_t<T>::value_type &&val) { + obj.emplace(std::move(val)); + { + obj.value_or(val) + } -> std::convertible_to<typename std::remove_cvref_t<T>::value_type>; + }; + { static_cast<bool>(obj) } -> std::same_as<bool>; // convertible to bool + { obj.reset() } noexcept -> std::same_as<void>; +}; + template<typename T> concept constructible_from_string_view = std::is_constructible_v<T, std::string_view> && !std::is_same_v<T, std::string_view> - && std::is_default_constructible_v<T>; + && std::is_default_constructible_v<T> + && !optional_type<T>; #if SIMDJSON_SUPPORTS_CHAR8_T /** @@ -3154,7 +3206,8 @@ template<typename T> concept constructible_from_u8string_view = std::is_constructible_v<T, std::u8string_view> && !std::is_same_v<T, std::u8string_view> && !std::is_constructible_v<T, std::string_view> - && std::is_default_constructible_v<T>; + && std::is_default_constructible_v<T> + && !optional_type<T>; #endif // SIMDJSON_SUPPORTS_CHAR8_T template<typename M> @@ -3224,22 +3277,6 @@ concept smart_pointer = requires(std::remove_cvref_t<T> ptr) { { *ptr } -> std::same_as<typename std::remove_cvref_t<T>::element_type &>; }; -template <typename T> -concept optional_type = requires(std::remove_cvref_t<T> obj) { - typename std::remove_cvref_t<T>::value_type; - { obj.value() } -> std::same_as<typename std::remove_cvref_t<T>::value_type&>; - requires requires(typename std::remove_cvref_t<T>::value_type &&val) { - obj.emplace(std::move(val)); - { - obj.value_or(val) - } -> std::convertible_to<typename std::remove_cvref_t<T>::value_type>; - }; - { static_cast<bool>(obj) } -> std::same_as<bool>; // convertible to bool - { obj.reset() } noexcept -> std::same_as<void>; -}; - - - // Types we serialize as JSON strings (not as containers) template <typename T> concept string_like = @@ -13013,7 +13050,7 @@ class document { * * The parser will allocate capacity as needed. */ - document() noexcept = default; + simdjson_inline document() noexcept {} ~document() noexcept = default; /** @@ -14543,6 +14580,9 @@ namespace { simdjson_inline simd8() : simd8(vdupq_n_u8(0)) {} // Splat constructor simdjson_inline simd8(bool _value) : simd8(splat(_value)) {} + // base_u8's operator~ xors with 0xFFu, which simd8<bool> only accepts by + // narrowing it to bool (MSVC C4305). Every other kernel overrides it too. + simdjson_inline simd8<bool> operator~() const { return *this ^ true; } // We return uint32_t instead of uint16_t because that seems to be more efficient for most // purposes (cutting it down to uint16_t costs performance in some compilers). @@ -14642,9 +14682,15 @@ namespace { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return ~any_bits_set(bits); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return vtstq_u8(*this, bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return vmaxvq_u32(vreinterpretq_u32_u8(*this)) != 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return vshrq_n_u8(*this, N); } template<int N> @@ -15408,8 +15454,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -15419,11 +15470,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -15474,7 +15528,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -16687,6 +16741,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -16779,6 +16836,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -17061,6 +17121,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -17157,6 +17220,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -17842,6 +17908,9 @@ namespace { simdjson_inline simd8() : simd8(vdupq_n_u8(0)) {} // Splat constructor simdjson_inline simd8(bool _value) : simd8(splat(_value)) {} + // base_u8's operator~ xors with 0xFFu, which simd8<bool> only accepts by + // narrowing it to bool (MSVC C4305). Every other kernel overrides it too. + simdjson_inline simd8<bool> operator~() const { return *this ^ true; } // We return uint32_t instead of uint16_t because that seems to be more efficient for most // purposes (cutting it down to uint16_t costs performance in some compilers). @@ -17941,9 +18010,15 @@ namespace { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return ~any_bits_set(bits); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return vtstq_u8(*this, bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return vmaxvq_u32(vreinterpretq_u32_u8(*this)) != 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return vshrq_n_u8(*this, N); } template<int N> @@ -19706,6 +19781,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for arm64 */ +/* including generic/stage1/utf8_validator.h for arm64: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for arm64 */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace arm64 { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace arm64 +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for arm64 */ /* including generic/stage1/json_structural_indexer.h for arm64: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for arm64 */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -19719,6 +19842,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -20008,7 +20132,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -20161,54 +20295,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for arm64 */ -/* including generic/stage1/utf8_validator.h for arm64: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for arm64 */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace arm64 { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace arm64 -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for arm64 */ /* end file generic/stage1/amalgamated.h for arm64 */ /* including generic/stage2/amalgamated.h for arm64: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for arm64 */ @@ -22973,8 +23059,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -22984,11 +23075,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -23039,7 +23133,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -24252,6 +24346,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -24344,6 +24441,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -24626,6 +24726,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -24722,6 +24825,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -27119,6 +27225,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for haswell */ +/* including generic/stage1/utf8_validator.h for haswell: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for haswell */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace haswell { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace haswell +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for haswell */ /* including generic/stage1/json_structural_indexer.h for haswell: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for haswell */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -27132,6 +27286,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -27421,7 +27576,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -27574,54 +27739,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for haswell */ -/* including generic/stage1/utf8_validator.h for haswell: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for haswell */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace haswell { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace haswell -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for haswell */ /* end file generic/stage1/amalgamated.h for haswell */ /* including generic/stage2/amalgamated.h for haswell: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for haswell */ @@ -30362,8 +30479,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -30373,11 +30495,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -30428,7 +30553,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -31641,6 +31766,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -31733,6 +31861,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -32015,6 +32146,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -32111,6 +32245,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -34503,6 +34640,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for icelake */ +/* including generic/stage1/utf8_validator.h for icelake: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for icelake */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace icelake { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace icelake +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for icelake */ /* including generic/stage1/json_structural_indexer.h for icelake: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for icelake */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -34516,6 +34701,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -34805,7 +34991,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -34958,54 +35154,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for icelake */ -/* including generic/stage1/utf8_validator.h for icelake: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for icelake */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace icelake { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace icelake -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for icelake */ /* end file generic/stage1/amalgamated.h for icelake */ /* including generic/stage2/amalgamated.h for icelake: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for icelake */ @@ -37303,7 +37451,7 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { - return this->gt_bits(other).any_bits_set(); + return this->lt_bits(other).any_bits_set(); } // Bit-specific operations @@ -37332,6 +37480,9 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return !bits_not_set_anywhere(bits); } + simdjson_inline bool is_ascii() const { + return this->bits_not_set_anywhere(uint8_t(0x80)); + } template <int N> simdjson_inline simd8<uint8_t> shr() const { return simd8<uint8_t>( (__m128i)vec_sr(this->value, (__m128i)vec_splat_u8(N))); @@ -37907,8 +38058,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -37918,11 +38074,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -37973,7 +38132,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -39186,6 +39345,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -39278,6 +39440,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -39560,6 +39725,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -39656,6 +39824,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -40561,7 +40732,7 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { - return this->gt_bits(other).any_bits_set(); + return this->lt_bits(other).any_bits_set(); } // Bit-specific operations @@ -40590,6 +40761,9 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return !bits_not_set_anywhere(bits); } + simdjson_inline bool is_ascii() const { + return this->bits_not_set_anywhere(uint8_t(0x80)); + } template <int N> simdjson_inline simd8<uint8_t> shr() const { return simd8<uint8_t>( (__m128i)vec_sr(this->value, (__m128i)vec_splat_u8(N))); @@ -42164,6 +42338,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for ppc64 */ +/* including generic/stage1/utf8_validator.h for ppc64: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for ppc64 */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace ppc64 { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace ppc64 +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for ppc64 */ /* including generic/stage1/json_structural_indexer.h for ppc64: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for ppc64 */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -42177,6 +42399,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -42466,7 +42689,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -42619,54 +42852,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for ppc64 */ -/* including generic/stage1/utf8_validator.h for ppc64: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for ppc64 */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace ppc64 { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace ppc64 -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for ppc64 */ /* end file generic/stage1/amalgamated.h for ppc64 */ /* including generic/stage2/amalgamated.h for ppc64: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for ppc64 */ @@ -44829,7 +45014,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -45248,7 +45433,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -45806,8 +45991,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -45817,11 +46007,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -45872,7 +46065,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -47085,6 +47278,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -47177,6 +47373,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -47459,6 +47658,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -47555,6 +47757,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -48393,7 +48598,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -48812,7 +49017,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -50369,6 +50574,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for westmere */ +/* including generic/stage1/utf8_validator.h for westmere: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for westmere */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace westmere { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace westmere +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for westmere */ /* including generic/stage1/json_structural_indexer.h for westmere: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for westmere */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -50382,6 +50635,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -50671,7 +50925,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -50824,54 +51088,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for westmere */ -/* including generic/stage1/utf8_validator.h for westmere: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for westmere */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace westmere { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace westmere -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for westmere */ /* end file generic/stage1/amalgamated.h for westmere */ /* including generic/stage2/amalgamated.h for westmere: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for westmere */ @@ -52570,7 +52786,18 @@ template <typename T> struct simd8x64; /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include <lsxintrin.h> +#if defined(__clang__) && !defined(__loongarch_asx) +// LLVM's lasxintrin.h only declares the LASX types and functions when +// __loongarch_asx is defined, that is, when the code is compiled with -mlasx. +// For runtime dispatching, we include it inside a target("lasx") region +// (see simdjson/lasx/begin.h) where the LASX builtins are available, so we +// define __loongarch_asx while including the header. +#define __loongarch_asx 1 #include <lasxintrin.h> +#undef __loongarch_asx +#else +#include <lasxintrin.h> +#endif static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX"); @@ -52789,10 +53016,7 @@ namespace simd { __m256i mask = __lasx_xvmskltz_b(*this); return (__lasx_xvpickve2gr_w(mask, 4) << 16) | (__lasx_xvpickve2gr_w(mask, 0)); } - simdjson_inline bool any() const { - __m256i v = __lasx_xvmsknz_b(*this); - return (0 == __lasx_xvpickve2gr_w(v, 0)) && (0 == __lasx_xvpickve2gr_w(v, 4)); - } + simdjson_inline bool any() const { return !__lasx_xbz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -53558,8 +53782,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -53569,11 +53798,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -53624,7 +53856,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -54837,6 +55069,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -54929,6 +55164,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -55211,6 +55449,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -55307,6 +55548,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -55650,7 +55894,18 @@ template <typename T> struct simd8x64; /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include <lsxintrin.h> +#if defined(__clang__) && !defined(__loongarch_asx) +// LLVM's lasxintrin.h only declares the LASX types and functions when +// __loongarch_asx is defined, that is, when the code is compiled with -mlasx. +// For runtime dispatching, we include it inside a target("lasx") region +// (see simdjson/lasx/begin.h) where the LASX builtins are available, so we +// define __loongarch_asx while including the header. +#define __loongarch_asx 1 #include <lasxintrin.h> +#undef __loongarch_asx +#else +#include <lasxintrin.h> +#endif static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX"); @@ -55869,10 +56124,7 @@ namespace simd { __m256i mask = __lasx_xvmskltz_b(*this); return (__lasx_xvpickve2gr_w(mask, 4) << 16) | (__lasx_xvpickve2gr_w(mask, 0)); } - simdjson_inline bool any() const { - __m256i v = __lasx_xvmsknz_b(*this); - return (0 == __lasx_xvpickve2gr_w(v, 0)) && (0 == __lasx_xvpickve2gr_w(v, 4)); - } + simdjson_inline bool any() const { return !__lasx_xbz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -57637,6 +57889,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for lasx */ +/* including generic/stage1/utf8_validator.h for lasx: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for lasx */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace lasx { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace lasx +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for lasx */ /* including generic/stage1/json_structural_indexer.h for lasx: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for lasx */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -57650,6 +57950,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -57939,7 +58240,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -58092,54 +58403,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for lasx */ -/* including generic/stage1/utf8_validator.h for lasx: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for lasx */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace lasx { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace lasx -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for lasx */ /* end file generic/stage1/amalgamated.h for lasx */ /* including generic/stage2/amalgamated.h for lasx: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for lasx */ @@ -60015,7 +60278,7 @@ namespace simd { simdjson_inline simd8(bool _value) : base8<bool>(splat(_value)) {} simdjson_inline int to_bitmask() const { return __lsx_vpickve2gr_w(__lsx_vmskltz_b(*this), 0); } - simdjson_inline bool any() const { return 0 == __lsx_vpickve2gr_hu(__lsx_vmsknz_b(*this), 0); } + simdjson_inline bool any() const { return !__lsx_bz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -60771,8 +61034,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -60782,11 +61050,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -60837,7 +61108,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -62050,6 +62321,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -62142,6 +62416,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -62424,6 +62701,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -62520,6 +62800,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -63062,7 +63345,7 @@ namespace simd { simdjson_inline simd8(bool _value) : base8<bool>(splat(_value)) {} simdjson_inline int to_bitmask() const { return __lsx_vpickve2gr_w(__lsx_vmskltz_b(*this), 0); } - simdjson_inline bool any() const { return 0 == __lsx_vpickve2gr_hu(__lsx_vmsknz_b(*this), 0); } + simdjson_inline bool any() const { return !__lsx_bz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -64817,6 +65100,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for lsx */ +/* including generic/stage1/utf8_validator.h for lsx: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for lsx */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace lsx { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace lsx +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for lsx */ /* including generic/stage1/json_structural_indexer.h for lsx: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for lsx */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -64830,6 +65161,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -65119,7 +65451,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -65272,54 +65614,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for lsx */ -/* including generic/stage1/utf8_validator.h for lsx: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for lsx */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace lsx { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace lsx -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for lsx */ /* end file generic/stage1/amalgamated.h for lsx */ /* including generic/stage2/amalgamated.h for lsx: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for lsx */ @@ -67166,7 +67460,9 @@ namespace simd { simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); } simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); } simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); } - simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); } + simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(*this, other, VL8); } + simdjson_inline simd8<bool> operator==(const simd8<bool> other) const { return __riscv_vmxnor(*this, other, VL8); } + simdjson_inline bool any() const { return __riscv_vfirst(value, VL8) >= 0; } simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); } simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; } simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; } @@ -67218,9 +67514,9 @@ namespace simd { simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); } simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); } #if __riscv_zvbb - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(value, other, VL8); } #else - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return *this & ~other; } #endif simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; } simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; } @@ -67248,6 +67544,8 @@ namespace simd { simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; } // Order-specific operations + simdjson_inline simd8<uint8_t> max_val(const simd8<uint8_t> other) const { return __riscv_vmaxu(value, other, VL8); } + simdjson_inline simd8<uint8_t> min_val(const simd8<uint8_t> other) const { return __riscv_vminu(value, other, VL8); } simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); } @@ -67259,10 +67557,17 @@ namespace simd { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return (*this & bits).bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return ~this->bits_not_set(bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); } template<int N> @@ -67978,8 +68283,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -67989,11 +68299,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -68044,7 +68357,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -69257,6 +69570,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -69349,6 +69665,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -69631,6 +69950,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -69727,6 +70049,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -70244,7 +70569,9 @@ namespace simd { simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); } simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); } simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); } - simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); } + simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(*this, other, VL8); } + simdjson_inline simd8<bool> operator==(const simd8<bool> other) const { return __riscv_vmxnor(*this, other, VL8); } + simdjson_inline bool any() const { return __riscv_vfirst(value, VL8) >= 0; } simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); } simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; } simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; } @@ -70296,9 +70623,9 @@ namespace simd { simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); } simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); } #if __riscv_zvbb - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(value, other, VL8); } #else - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return *this & ~other; } #endif simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; } simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; } @@ -70326,6 +70653,8 @@ namespace simd { simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; } // Order-specific operations + simdjson_inline simd8<uint8_t> max_val(const simd8<uint8_t> other) const { return __riscv_vmaxu(value, other, VL8); } + simdjson_inline simd8<uint8_t> min_val(const simd8<uint8_t> other) const { return __riscv_vminu(value, other, VL8); } simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); } @@ -70337,10 +70666,17 @@ namespace simd { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return (*this & bits).bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return ~this->bits_not_set(bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); } template<int N> @@ -70723,7 +71059,9 @@ namespace simd { simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); } simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); } simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); } - simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); } + simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(*this, other, VL8); } + simdjson_inline simd8<bool> operator==(const simd8<bool> other) const { return __riscv_vmxnor(*this, other, VL8); } + simdjson_inline bool any() const { return __riscv_vfirst(value, VL8) >= 0; } simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); } simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; } simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; } @@ -70775,9 +71113,9 @@ namespace simd { simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); } simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); } #if __riscv_zvbb - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(value, other, VL8); } #else - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return *this & ~other; } #endif simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; } simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; } @@ -70805,6 +71143,8 @@ namespace simd { simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; } // Order-specific operations + simdjson_inline simd8<uint8_t> max_val(const simd8<uint8_t> other) const { return __riscv_vmaxu(value, other, VL8); } + simdjson_inline simd8<uint8_t> min_val(const simd8<uint8_t> other) const { return __riscv_vminu(value, other, VL8); } simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); } @@ -70816,10 +71156,17 @@ namespace simd { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return (*this & bits).bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return ~this->bits_not_set(bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); } template<int N> @@ -72428,6 +72775,54 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_MINIFIER_H /* end file generic/stage1/json_minifier.h for rvv_vls */ +/* including generic/stage1/utf8_validator.h for rvv_vls: #include <generic/stage1/utf8_validator.h> */ +/* begin file generic/stage1/utf8_validator.h for rvv_vls */ +#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H + +/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ +/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ +/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ +/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ + +namespace simdjson { +namespace rvv_vls { +namespace { +namespace stage1 { + +/** + * Validates that the string is actual UTF-8. + */ +template<class checker> +bool generic_validate_utf8(const uint8_t * input, size_t length) { + checker c{}; + buf_block_reader<64> reader(input, length); + while (reader.has_full_block()) { + simd::simd8x64<uint8_t> in(reader.full_block()); + c.check_next_input(in); + reader.advance(); + } + uint8_t block[64]{}; + reader.get_remainder(block); + simd::simd8x64<uint8_t> in(block); + c.check_next_input(in); + reader.advance(); + c.check_eof(); + return c.errors() == error_code::SUCCESS; +} + +bool generic_validate_utf8(const char * input, size_t length) { + return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); +} + +} // namespace stage1 +} // unnamed namespace +} // namespace rvv_vls +} // namespace simdjson + +#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H +/* end file generic/stage1/utf8_validator.h for rvv_vls */ /* including generic/stage1/json_structural_indexer.h for rvv_vls: #include <generic/stage1/json_structural_indexer.h> */ /* begin file generic/stage1/json_structural_indexer.h for rvv_vls */ #ifndef SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H @@ -72441,6 +72836,7 @@ error_code json_minifier::minify(const uint8_t *buf, size_t len, uint8_t *dst, s /* amalgamation skipped (editor-only): #include <generic/stage1/json_scanner.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/json_minifier.h> */ /* amalgamation skipped (editor-only): #include <generic/stage1/find_next_document_index.h> */ +/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_validator.h> */ /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ // This file contains the common code every implementation uses in stage1 @@ -72730,7 +73126,17 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa // Bail out only once the count and sentinels above are set: // document_stream::truncated_bytes() reads them even on error. - if (simdjson_unlikely(should_we_exit)) { return error; } + if (simdjson_unlikely(should_we_exit)) { + // The error is UNCLOSED_STRING, which iterate_allow_incomplete_json() + // accepts: it must not hide an invalid input. A character cut by the end + // of the input belongs to the unclosed string, as when streaming. + if (unescaped_chars_error) { return UNESCAPED_CHARS; } + if (checker.errors() != SUCCESS && + !generic_validate_utf8<utf8_checker>(parser.buf, trim_partial_utf8(parser.buf, len))) { + return UTF8_ERROR; + } + return error; + } if (unescaped_chars_error) { return UNESCAPED_CHARS; } // a valid JSON file cannot have zero structural indexes - we should have found something @@ -72883,54 +73289,6 @@ simdjson_inline error_code json_structural_indexer::finish(dom_parser_implementa #endif // SIMDJSON_SRC_GENERIC_STAGE1_JSON_STRUCTURAL_INDEXER_H /* end file generic/stage1/json_structural_indexer.h for rvv_vls */ -/* including generic/stage1/utf8_validator.h for rvv_vls: #include <generic/stage1/utf8_validator.h> */ -/* begin file generic/stage1/utf8_validator.h for rvv_vls */ -#ifndef SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H - -/* amalgamation skipped (editor-only): #ifndef SIMDJSON_CONDITIONAL_INCLUDE */ -/* amalgamation skipped (editor-only): #define SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H */ -/* amalgamation skipped (editor-only): #include <generic/stage1/base.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/buf_block_reader.h> */ -/* amalgamation skipped (editor-only): #include <generic/stage1/utf8_lookup4_algorithm.h> */ -/* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ - -namespace simdjson { -namespace rvv_vls { -namespace { -namespace stage1 { - -/** - * Validates that the string is actual UTF-8. - */ -template<class checker> -bool generic_validate_utf8(const uint8_t * input, size_t length) { - checker c{}; - buf_block_reader<64> reader(input, length); - while (reader.has_full_block()) { - simd::simd8x64<uint8_t> in(reader.full_block()); - c.check_next_input(in); - reader.advance(); - } - uint8_t block[64]{}; - reader.get_remainder(block); - simd::simd8x64<uint8_t> in(block); - c.check_next_input(in); - reader.advance(); - c.check_eof(); - return c.errors() == error_code::SUCCESS; -} - -bool generic_validate_utf8(const char * input, size_t length) { - return generic_validate_utf8<utf8_checker>(reinterpret_cast<const uint8_t *>(input),length); -} - -} // namespace stage1 -} // unnamed namespace -} // namespace rvv_vls -} // namespace simdjson - -#endif // SIMDJSON_SRC_GENERIC_STAGE1_UTF8_VALIDATOR_H -/* end file generic/stage1/utf8_validator.h for rvv_vls */ /* end file generic/stage1/amalgamated.h for rvv_vls */ /* including generic/stage2/amalgamated.h for rvv_vls: #include <generic/stage2/amalgamated.h> */ /* begin file generic/stage2/amalgamated.h for rvv_vls */ @@ -75173,8 +75531,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -75184,11 +75547,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -75239,7 +75605,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -76452,6 +76818,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -76544,6 +76913,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -76826,6 +77198,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -76922,6 +77297,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -79325,6 +79703,17 @@ simdjson_inline bool is_continuation(uint8_t c) { return (c & 0xc0) == 0x80; } +// The input ends inside the n-byte character at idx: the bytes after it, as +// far as they go, are continuation bytes. Such a character belongs to a string +// that does not close: it is not an error, as with streaming. +simdjson_inline bool is_cut_by_end(size_t n) { + for (size_t i = size_t(idx) + 1; i < size_t(idx) + n; i++) { + if (i >= len) { return true; } + if (!is_continuation(buf[i])) { return false; } + } + return false; +} + simdjson_inline void validate_utf8_character() { // Continuation if (simdjson_unlikely((buf[idx] & 0x40) == 0)) { @@ -79338,7 +79727,7 @@ simdjson_inline void validate_utf8_character() { if ((buf[idx] & 0x20) == 0) { // missing continuation if (simdjson_unlikely(idx+1 >= len || !is_continuation(buf[idx+1]))) { - if (idx+1 >= len && is_streaming(partial)) { idx = len; return; } + if (idx+1 >= len && (is_streaming(partial) || is_cut_by_end(2))) { idx = len; return; } error = UTF8_ERROR; idx++; return; @@ -79353,7 +79742,7 @@ simdjson_inline void validate_utf8_character() { if ((buf[idx] & 0x10) == 0) { // missing continuation if (simdjson_unlikely(idx+2 >= len || !is_continuation(buf[idx+1]) || !is_continuation(buf[idx+2]))) { - if (idx+2 >= len && is_streaming(partial)) { idx = len; return; } + if (idx+2 >= len && (is_streaming(partial) || is_cut_by_end(3))) { idx = len; return; } error = UTF8_ERROR; idx++; return; @@ -79369,7 +79758,7 @@ simdjson_inline void validate_utf8_character() { // 4-byte // missing continuation if (simdjson_unlikely(idx+3 >= len || !is_continuation(buf[idx+1]) || !is_continuation(buf[idx+2]) || !is_continuation(buf[idx+3]))) { - if (idx+3 >= len && is_streaming(partial)) { idx = len; return; } + if (idx+3 >= len && (is_streaming(partial) || is_cut_by_end(4))) { idx = len; return; } error = UTF8_ERROR; idx++; return; @@ -79485,7 +79874,7 @@ simdjson_warn_unused simdjson_inline error_code scan() { // String if (buf[idx] == '"') { add_structural(); - unclosed_string |= validate_string(); + if (validate_string()) { unclosed_string = true; break; } // Operator } else if (char_is_operator(buf[idx])) { add_structural(); @@ -79632,7 +80021,11 @@ simdjson_warn_unused simdjson_inline error_code scan() { parser.structural_indexes[parser.n_structural_indexes + 1] = parser.structural_indexes[parser.n_structural_indexes]; parser.structural_indexes[parser.n_structural_indexes] = uint32_t(len); if (simdjson_unlikely(parser.n_structural_indexes == 0)) { return EMPTY; } - } else if(unclosed_string) { error = UNCLOSED_STRING; } + } else if(unclosed_string && error == SUCCESS) { + // Keep an earlier UTF8_ERROR or UNESCAPED_CHARS: iterate_allow_incomplete_json() + // accepts UNCLOSED_STRING. + error = UNCLOSED_STRING; + } return error; } diff --git a/deps/simdjson/simdjson.h b/deps/simdjson/simdjson.h index 04dbe98eb574..49f66b687dcf 100644 --- a/deps/simdjson/simdjson.h +++ b/deps/simdjson/simdjson.h @@ -1,4 +1,4 @@ -/* auto-generated on 2026-10-31 19:14:12 -0400. version 5.1.1 Do not edit! */ +/* auto-generated on 2026-11-14 18:54:03 -0500. version 5.2.0 Do not edit! */ /* including simdjson.h: */ /* begin file simdjson.h */ #ifndef SIMDJSON_H @@ -205,6 +205,24 @@ #endif #endif // !defined(SIMDJSON_SUPPORTS_CHAR8_T) +// std::string::resize_and_overwrite (C++23) is available. +#if !defined(SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE) +#if defined(__cpp_lib_string_resize_and_overwrite) && __cpp_lib_string_resize_and_overwrite >= 202110L +#define SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE 1 +#else +#define SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE 0 +#endif +#endif // !defined(SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE) + +// std::string can be used in constant expressions (C++20, e.g., libstdc++ 12 or better). +#if !defined(SIMDJSON_SUPPORTS_CONSTEXPR_STRING) +#if defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#define SIMDJSON_SUPPORTS_CONSTEXPR_STRING 1 +#else +#define SIMDJSON_SUPPORTS_CONSTEXPR_STRING 0 +#endif +#endif // !defined(SIMDJSON_SUPPORTS_CONSTEXPR_STRING) + // The C++23 fixed-width floating-point types std::float32_t and std::float64_t // (<stdfloat>) are available. They are optional even in C++23: a compiler that // provides them predefines __STDCPP_FLOAT32_T__ and __STDCPP_FLOAT64_T__. @@ -237,11 +255,11 @@ #if !defined(SIMDJSON_CONSTEVAL) -#if defined(__cpp_consteval) && __cpp_consteval >= 201811L && defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#if defined(__cpp_consteval) && __cpp_consteval >= 201811L && SIMDJSON_SUPPORTS_CONSTEXPR_STRING #define SIMDJSON_CONSTEVAL 1 #else #define SIMDJSON_CONSTEVAL 0 -#endif // defined(__cpp_consteval) && __cpp_consteval >= 201811L && defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#endif // defined(__cpp_consteval) && __cpp_consteval >= 201811L && SIMDJSON_SUPPORTS_CONSTEXPR_STRING #endif // !defined(SIMDJSON_CONSTEVAL) // SIMDJSON_CONSTEXPR_STRING is 'constexpr' when the standard library supports @@ -249,11 +267,11 @@ // lets functions that build a std::string be constant expressions when possible // while still compiling against older standard libraries. #if !defined(SIMDJSON_CONSTEXPR_STRING) -#if defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#if SIMDJSON_SUPPORTS_CONSTEXPR_STRING #define SIMDJSON_CONSTEXPR_STRING constexpr #else #define SIMDJSON_CONSTEXPR_STRING -#endif // defined(__cpp_lib_constexpr_string) && __cpp_lib_constexpr_string >= 201907L +#endif // SIMDJSON_SUPPORTS_CONSTEXPR_STRING #endif // !defined(SIMDJSON_CONSTEXPR_STRING) #endif // SIMDJSON_COMPILER_CHECK_H /* end file simdjson/compiler_check.h */ @@ -329,7 +347,25 @@ using std::size_t; #define SIMDJSON_IS_LSX 1 // Adjust for runtime dispatching support. -#if defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__NVCOMPILER) +// +// LASX runtime dispatching is deliberately disabled by default, so that the +// LSX kernel is used even when the processor supports LASX. On a Loongson +// 3A6000, our LASX kernel parses about 5% slower overall than our LSX +// kernel (stage 1 about 14% slower), with both GCC 15 and LLVM. The 256-bit +// registers do not help: stage 1 is limited by moving bitmasks from vector +// registers to general-purpose registers, and with LASX each bitmask needs +// a cross-lane permutation (3 cycles) and a slower vector-to-GPR move +// (xvpickve2gr is 2 cycles slower than vpickve2gr). +// +// Define SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH to 0 to enable LASX runtime +// dispatching (GCC 15+ or LLVM). Compiling with -mlasx selects the LASX +// kernel regardless of this macro. See doc/implementation-selection.md. +#ifndef SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH + #define SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH 1 +#endif +#if SIMDJSON_DISABLE_LASX_RUNTIME_DISPATCH + #define SIMDJSON_IMPLEMENTATION_LASX 0 +#elif defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER) && !defined(__NVCOMPILER) #if __GNUC__ > 15 || (__GNUC__ == 15 && __GNUC_MINOR__ >= 0) // We are ok, we will support runtime dispatch for LASX. #else @@ -338,14 +374,15 @@ using std::size_t; // Loongson users should update to GCC 15 or better. #define SIMDJSON_IMPLEMENTATION_LASX 0 #endif +#elif defined(__clang__) + // LLVM supports runtime dispatch for LASX through the target attribute. + // See simdjson/lasx/intrinsics.h. #else - // We are not using GCC, so we assume that we can support runtime dispatch for LASX. + // We are not using GCC or LLVM, so we do not support runtime dispatch for LASX. // https://godbolt.org/z/jcMnrjYhs #define SIMDJSON_IMPLEMENTATION_LASX 0 #endif - - #endif #elif defined(__PPC64__) || defined(_M_PPC64) #define SIMDJSON_IS_PPC64 1 @@ -2715,7 +2752,7 @@ namespace std { #define SIMDJSON_SIMDJSON_VERSION_H /** The version of simdjson being used (major.minor.revision) */ -#define SIMDJSON_VERSION "5.1.1" +#define SIMDJSON_VERSION "5.2.0" namespace simdjson { enum { @@ -2726,11 +2763,11 @@ enum { /** * The minor version (major.MINOR.revision) of simdjson being used. */ - SIMDJSON_VERSION_MINOR = 1, + SIMDJSON_VERSION_MINOR = 2, /** * The revision (major.minor.REVISION) of simdjson being used. */ - SIMDJSON_VERSION_REVISION = 1 + SIMDJSON_VERSION_REVISION = 0 }; } // namespace simdjson @@ -3202,10 +3239,25 @@ template <typename T> concept string_view_like = std::is_convertible_v<T, std::string_view> && !std::is_convertible_v<T, const char*>; +template <typename T> +concept optional_type = requires(std::remove_cvref_t<T> obj) { + typename std::remove_cvref_t<T>::value_type; + { obj.value() } -> std::same_as<typename std::remove_cvref_t<T>::value_type&>; + requires requires(typename std::remove_cvref_t<T>::value_type &&val) { + obj.emplace(std::move(val)); + { + obj.value_or(val) + } -> std::convertible_to<typename std::remove_cvref_t<T>::value_type>; + }; + { static_cast<bool>(obj) } -> std::same_as<bool>; // convertible to bool + { obj.reset() } noexcept -> std::same_as<void>; +}; + template<typename T> concept constructible_from_string_view = std::is_constructible_v<T, std::string_view> && !std::is_same_v<T, std::string_view> - && std::is_default_constructible_v<T>; + && std::is_default_constructible_v<T> + && !optional_type<T>; #if SIMDJSON_SUPPORTS_CHAR8_T /** @@ -3217,7 +3269,8 @@ template<typename T> concept constructible_from_u8string_view = std::is_constructible_v<T, std::u8string_view> && !std::is_same_v<T, std::u8string_view> && !std::is_constructible_v<T, std::string_view> - && std::is_default_constructible_v<T>; + && std::is_default_constructible_v<T> + && !optional_type<T>; #endif // SIMDJSON_SUPPORTS_CHAR8_T template<typename M> @@ -3287,22 +3340,6 @@ concept smart_pointer = requires(std::remove_cvref_t<T> ptr) { { *ptr } -> std::same_as<typename std::remove_cvref_t<T>::element_type &>; }; -template <typename T> -concept optional_type = requires(std::remove_cvref_t<T> obj) { - typename std::remove_cvref_t<T>::value_type; - { obj.value() } -> std::same_as<typename std::remove_cvref_t<T>::value_type&>; - requires requires(typename std::remove_cvref_t<T>::value_type &&val) { - obj.emplace(std::move(val)); - { - obj.value_or(val) - } -> std::convertible_to<typename std::remove_cvref_t<T>::value_type>; - }; - { static_cast<bool>(obj) } -> std::same_as<bool>; // convertible to bool - { obj.reset() } noexcept -> std::same_as<void>; -}; - - - // Types we serialize as JSON strings (not as containers) template <typename T> concept string_like = @@ -5052,6 +5089,11 @@ inline padded_string_view pad_with_reserve(std::string& s) noexcept; * is longer than block_size; skip it and continue. With block_size larger than * the longest document, no slice is ever empty. * + * Cost: a slice searches its own block for its start, and then from the end of + * its block to the next delimiter. An empty slice returns after searching its + * block alone. Cutting the whole input therefore scans each byte about twice, + * whatever the document lengths. + * * @param data The padded input. * @param delimiter The byte that separates documents. * @param block_size The nominal slice size, before snapping. @@ -5266,14 +5308,30 @@ inline padded_string_view slice_at(padded_string_view data, char delimiter, const size_t raw_begin = index * block_size; if (raw_begin >= data.size()) { return {}; } - auto snap = [&](size_t want) -> size_t { - if (want >= data.size()) { return data.size(); } - const void *p = std::memchr(data.data() + want, delimiter, data.size() - want); - return p ? size_t(static_cast<const char *>(p) - data.data()) + 1 : data.size(); + auto find = [&](size_t from, size_t to) -> const char * { + return static_cast<const char *>( + std::memchr(data.data() + from, delimiter, to - from)); }; - const size_t begin = (raw_begin == 0) ? 0 : snap(raw_begin); - const size_t end = snap(raw_begin + block_size); + // The slice begins just past the first delimiter in its own block. If the + // block holds no delimiter, it lies inside a document that an earlier slice + // owns, and the slice is empty. Searching past the block would give the same + // answer, but would make every block inside a long document scan to that + // document's end: quadratic time in the document's length. + size_t begin = 0; + if (raw_begin != 0) { + const size_t block_end = (data.size() - raw_begin > block_size) + ? raw_begin + block_size : data.size(); + const char *p = find(raw_begin, block_end); + if (p == nullptr) { return {}; } + begin = size_t(p - data.data()) + 1; + } + // Only the slice that owns a document scans to its end. + size_t end = data.size(); + if (data.size() - raw_begin > block_size) { + const char *p = find(raw_begin + block_size, data.size()); + if (p != nullptr) { end = size_t(p - data.data()) + 1; } + } if (begin >= end) { return {}; } return padded_string_view(data.data() + begin, end - begin, data.capacity() - begin); @@ -6037,7 +6095,7 @@ class array { inline bool operator>=(const iterator& other) const noexcept; inline bool operator>(const iterator& other) const noexcept; - iterator() noexcept = default; + simdjson_inline iterator() noexcept {} iterator(const iterator&) noexcept = default; iterator& operator=(const iterator&) noexcept = default; private: @@ -6065,7 +6123,7 @@ class array { inline bool operator==(const reverse_iterator& other) const noexcept; inline bool operator!=(const reverse_iterator& other) const noexcept; - reverse_iterator() noexcept = default; + simdjson_inline reverse_iterator() noexcept {} reverse_iterator(const reverse_iterator&) noexcept = default; reverse_iterator& operator=(const reverse_iterator&) noexcept = default; private: @@ -6283,7 +6341,7 @@ class document { * * The parser will allocate capacity as needed. */ - document() noexcept = default; + simdjson_inline document() noexcept {} ~document() noexcept = default; /** @@ -7135,7 +7193,7 @@ namespace dom { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -7858,7 +7916,7 @@ class element { * - NO_SUCH_FIELD if the field does not exist in the object * - INCORRECT_TYPE if this is not an object */ - inline simdjson_result<element> operator[](std::string_view key) const noexcept; + simdjson_inline simdjson_result<element> operator[](std::string_view key) const noexcept; /** * Get the value associated with the given key. @@ -7873,7 +7931,7 @@ class element { * - NO_SUCH_FIELD if the field does not exist in the object * - INCORRECT_TYPE if this is not an object */ - inline simdjson_result<element> operator[](const char *key) const noexcept; + simdjson_inline simdjson_result<element> operator[](const char *key) const noexcept; simdjson_result<element> operator[](int) const noexcept = delete; @@ -7963,7 +8021,7 @@ class element { * @return The value associated with this field, or: * - NO_SUCH_FIELD if the field does not exist in the object */ - inline simdjson_result<element> at_key(std::string_view key) const noexcept; + simdjson_inline simdjson_result<element> at_key(std::string_view key) const noexcept; /** * Get the value associated with the given key in a case-insensitive manner. @@ -8153,7 +8211,7 @@ class object { * Returns true if the key in this key/value pair is equal * to the provided string_view. */ - inline bool key_equals(std::string_view o) const noexcept; + simdjson_inline bool key_equals(std::string_view o) const noexcept; /** * Returns true if the key in this key/value pair is equal * to the provided string_view in a case-insensitive manner. @@ -8169,7 +8227,7 @@ class object { */ inline element value() const noexcept; - iterator() noexcept = default; + simdjson_inline iterator() noexcept {} iterator(const iterator&) noexcept = default; iterator& operator=(const iterator&) noexcept = default; private: @@ -8213,7 +8271,7 @@ class object { * - NO_SUCH_FIELD if the field does not exist in the object * - INCORRECT_TYPE if this is not an object */ - inline simdjson_result<element> operator[](std::string_view key) const noexcept; + simdjson_inline simdjson_result<element> operator[](std::string_view key) const noexcept; /** * Get the value associated with the given key. @@ -8230,7 +8288,7 @@ class object { * - NO_SUCH_FIELD if the field does not exist in the object * - INCORRECT_TYPE if this is not an object */ - inline simdjson_result<element> operator[](const char *key) const noexcept; + simdjson_inline simdjson_result<element> operator[](const char *key) const noexcept; simdjson_result<element> operator[](int) const noexcept = delete; /** @@ -8297,7 +8355,7 @@ class object { * @return The value associated with this field, or: * - NO_SUCH_FIELD if the field does not exist in the object */ - inline simdjson_result<element> at_key(std::string_view key) const noexcept; + simdjson_inline simdjson_result<element> at_key(std::string_view key) const noexcept; /** * Gets the values associated with keys of an object @@ -8361,13 +8419,13 @@ struct simdjson_result<dom::object> : public internal::simdjson_result_base<dom: simdjson_inline simdjson_result(dom::object value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - inline simdjson_result<dom::element> operator[](std::string_view key) const noexcept; - inline simdjson_result<dom::element> operator[](const char *key) const noexcept; + simdjson_inline simdjson_result<dom::element> operator[](std::string_view key) const noexcept; + simdjson_inline simdjson_result<dom::element> operator[](const char *key) const noexcept; simdjson_result<dom::element> operator[](int) const noexcept = delete; inline simdjson_result<dom::element> at_pointer(std::string_view json_pointer) const noexcept; inline simdjson_result<std::vector<dom::element>> at_path_with_wildcard(std::string_view json_path_new) const noexcept; inline simdjson_result<dom::element> at_path(std::string_view json_path) const noexcept; - inline simdjson_result<dom::element> at_key(std::string_view key) const noexcept; + simdjson_inline simdjson_result<dom::element> at_key(std::string_view key) const noexcept; inline std::vector<dom::element>& get_values(std::vector<dom::element>& out) const noexcept; inline simdjson_result<dom::element> at_key_case_insensitive(std::string_view key) const noexcept; @@ -8474,7 +8532,7 @@ template <class formatter> class base_formatter { // implementation details (subject to change) /** Backing buffer **/ struct vector_with_small_buffer { - vector_with_small_buffer() = default; + vector_with_small_buffer() {} ~vector_with_small_buffer() { free_buffer(); } vector_with_small_buffer(const vector_with_small_buffer &) = delete; @@ -8559,6 +8617,8 @@ template <class formatter> class base_formatter { */ class mini_formatter : public base_formatter<mini_formatter> { public: + /** User-provided so that value-initialization does not zero the buffer. **/ + mini_formatter() {} simdjson_inline void print_newline(); simdjson_inline void print_indents(size_t depth); @@ -8593,7 +8653,7 @@ class pretty_formatter : public base_formatter<pretty_formatter> { template <class formatter = mini_formatter> class string_builder { public: /** Construct an initially empty builder, would print the empty string **/ - string_builder() = default; + string_builder() {} /** Construct a builder whose formatter uses the given indentation step **/ explicit string_builder(int indent_step) : format(indent_step) {} @@ -9043,6 +9103,7 @@ simdjson_inline bool is_matching_failure_error(error_code error) noexcept { * @return A string containing the equivalent JSON Pointer. */ inline std::string json_path_to_pointer_conversion(std::string_view json_path) { + if (json_path == "$") { return {}; } size_t i = 0; // if JSONPath starts with $, skip it // json_path.starts_with('$') requires C++20. @@ -9065,7 +9126,16 @@ inline std::string json_path_to_pointer_conversion(std::string_view json_path) { } else if (json_path[i] == '[') { result += '/'; ++i; // Move past the '[' - while (i < json_path.length() && json_path[i] != ']') { + // A bracket-quoted key (['key'] or ["key"]) is the key without its quotes, + // as in get_next_key_and_json_path(). It runs up to the matching quote, + // which the ']' must follow. + char quote = '\0'; + if (i < json_path.length() && (json_path[i] == '\'' || json_path[i] == '"')) { + quote = json_path[i]; + ++i; + } + const char key_end = quote ? quote : ']'; + while (i < json_path.length() && json_path[i] != key_end) { if (json_path[i] == '~') { result += "~0"; } else if (json_path[i] == '/') { @@ -9075,6 +9145,12 @@ inline std::string json_path_to_pointer_conversion(std::string_view json_path) { } ++i; } + if (quote) { + if (i == json_path.length()) { + return "-1"; // missing closing quote + } + ++i; // Move past the closing quote + } if (i == json_path.length() || json_path[i] != ']') { return "-1"; // Using sentinel value that will be handled as an error by the caller. } @@ -9614,7 +9690,8 @@ inline array::iterator array::begin() const noexcept { } inline array::iterator array::end() const noexcept { SIMDJSON_DEVELOPMENT_ASSERT(tape.usable()); // https://github.com/simdjson/simdjson/issues/1914 - return internal::tape_ref(tape.doc, tape.after_element() - 1); + SIMDJSON_DEVELOPMENT_ASSERT(tape.tape_ref_type() == internal::tape_type::START_ARRAY); + return internal::tape_ref(tape.doc, tape.matching_brace_index() - 1); } inline size_t array::size() const noexcept { SIMDJSON_DEVELOPMENT_ASSERT(tape.usable()); // https://github.com/simdjson/simdjson/issues/1914 @@ -9650,14 +9727,12 @@ inline simdjson_result<element> array::at_pointer(std::string_view json_pointer) SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = array(tape).at(array_index); + element child; // If there is an error, it ends here - if(child.error()) { - return child; - } + SIMDJSON_TRY(array(tape).at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -9818,11 +9893,11 @@ simdjson_inline simdjson_result<dom::object>::simdjson_result(dom::object value) simdjson_inline simdjson_result<dom::object>::simdjson_result(error_code error) noexcept : internal::simdjson_result_base<dom::object>(error) {} -inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](std::string_view key) const noexcept { +simdjson_inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](std::string_view key) const noexcept { if (error()) { return error(); } return first[key]; } -inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](const char *key) const noexcept { +simdjson_inline simdjson_result<dom::element> simdjson_result<dom::object>::operator[](const char *key) const noexcept { if (error()) { return error(); } return first[key]; } @@ -9842,7 +9917,7 @@ inline simdjson_result<std::vector<dom::element>> simdjson_result<dom::object>:: } return first.at_path_with_wildcard(json_path); } -inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key(std::string_view key) const noexcept { +simdjson_inline simdjson_result<dom::element> simdjson_result<dom::object>::at_key(std::string_view key) const noexcept { if (error()) { return error(); } return first.at_key(key); } @@ -9885,17 +9960,18 @@ inline object::iterator object::begin() const noexcept { } inline object::iterator object::end() const noexcept { SIMDJSON_DEVELOPMENT_ASSERT(tape.usable()); // https://github.com/simdjson/simdjson/issues/1914 - return internal::tape_ref(tape.doc, tape.after_element() - 1); + SIMDJSON_DEVELOPMENT_ASSERT(tape.tape_ref_type() == internal::tape_type::START_OBJECT); + return internal::tape_ref(tape.doc, tape.matching_brace_index() - 1); } inline size_t object::size() const noexcept { SIMDJSON_DEVELOPMENT_ASSERT(tape.usable()); // https://github.com/simdjson/simdjson/issues/1914 return tape.scope_count(); } -inline simdjson_result<element> object::operator[](std::string_view key) const noexcept { +simdjson_inline simdjson_result<element> object::operator[](std::string_view key) const noexcept { return at_key(key); } -inline simdjson_result<element> object::operator[](const char *key) const noexcept { +simdjson_inline simdjson_result<element> object::operator[](const char *key) const noexcept { return at_key(key); } inline simdjson_result<element> object::at_pointer(std::string_view json_pointer) const noexcept { @@ -9909,7 +9985,8 @@ inline simdjson_result<element> object::at_pointer(std::string_view json_pointer size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<element> child; + element child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -9929,16 +10006,16 @@ inline simdjson_result<element> object::at_pointer(std::string_view json_pointer } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = at_key(unescaped); + error = at_key(unescaped).get(child); } else { - child = at_key(key); + error = at_key(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -9973,7 +10050,7 @@ inline simdjson_result<std::vector<element>> object::at_path_with_wildcard(std:: return element(*this).at_path_with_wildcard(json_path); } -inline simdjson_result<element> object::at_key(std::string_view key) const noexcept { +simdjson_inline simdjson_result<element> object::at_key(std::string_view key) const noexcept { iterator end_field = end(); for (iterator field = begin(); field != end_field; ++field) { if (field.key_equals(key)) { @@ -10072,7 +10149,7 @@ inline element object::iterator::value() const noexcept { * on the long run. */ -inline bool object::iterator::key_equals(std::string_view o) const noexcept { +simdjson_inline bool object::iterator::key_equals(std::string_view o) const noexcept { // We use the fact that the key length can be computed quickly // without access to the string buffer. const uint32_t len = key_length(); @@ -10600,10 +10677,10 @@ inline array::iterator element::end() const noexcept(false) { #endif // SIMDJSON_EXCEPTIONS -inline simdjson_result<element> element::operator[](std::string_view key) const noexcept { +simdjson_inline simdjson_result<element> element::operator[](std::string_view key) const noexcept { return at_key(key); } -inline simdjson_result<element> element::operator[](const char *key) const noexcept { +simdjson_inline simdjson_result<element> element::operator[](const char *key) const noexcept { return at_key(key); } @@ -10647,6 +10724,7 @@ inline simdjson_result<element> element::at_pointer(std::string_view json_pointe inline simdjson_result<std::vector<element>> element::at_path_with_wildcard(std::string_view json_path) const noexcept { SIMDJSON_DEVELOPMENT_ASSERT(tape.usable()); // https://github.com/simdjson/simdjson/issues/1914 + if (json_path == "$") { return std::vector<element>{*this}; } const internal::wildcard_json_path path = internal::parse_wildcard_json_path(json_path); // A path that cannot be parsed matches nothing, whatever the document: say @@ -10680,7 +10758,7 @@ inline simdjson_result<element> element::at(std::string_view json_pointer) const inline simdjson_result<element> element::at(size_t index) const noexcept { return get<array>().at(index); } -inline simdjson_result<element> element::at_key(std::string_view key) const noexcept { +simdjson_inline simdjson_result<element> element::at_key(std::string_view key) const noexcept { return get<object>().at_key(key); } inline simdjson_result<element> element::at_key_case_insensitive(std::string_view key) const noexcept { @@ -11041,6 +11119,7 @@ inline error_code parser::allocate(size_t capacity, size_t max_depth) noexcept { err = implementation->allocate(capacity, max_depth); } else { err = simdjson::get_active_implementation()->create_dom_parser_implementation(capacity, max_depth, implementation); + if (err) { implementation.reset(); } } if (err) { return err; } return SUCCESS; @@ -12145,6 +12224,9 @@ find_next_json_quotable_character_scalar(const std::string_view view, template <typename Finder> inline size_t write_string_escaped_with(const std::string_view input, char *out) { size_t mysize = input.size(); + if (mysize == 0) { + return 0; + } // Use SIMD position finder directly - it returns mysize if no escape needed size_t location = Finder::find(input, 0); @@ -16838,6 +16920,9 @@ namespace { simdjson_inline simd8() : simd8(vdupq_n_u8(0)) {} // Splat constructor simdjson_inline simd8(bool _value) : simd8(splat(_value)) {} + // base_u8's operator~ xors with 0xFFu, which simd8<bool> only accepts by + // narrowing it to bool (MSVC C4305). Every other kernel overrides it too. + simdjson_inline simd8<bool> operator~() const { return *this ^ true; } // We return uint32_t instead of uint16_t because that seems to be more efficient for most // purposes (cutting it down to uint16_t costs performance in some compilers). @@ -16937,9 +17022,15 @@ namespace { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return ~any_bits_set(bits); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return vtstq_u8(*this, bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return vmaxvq_u32(vreinterpretq_u32_u8(*this)) != 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return vshrq_n_u8(*this, N); } template<int N> @@ -17703,8 +17794,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -17714,11 +17810,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -17769,7 +17868,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -18982,6 +19081,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -19074,6 +19176,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -19356,6 +19461,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -19452,6 +19560,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -20342,8 +20453,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -20353,11 +20469,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -20408,7 +20527,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -21621,6 +21740,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -21713,6 +21835,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -21995,6 +22120,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -22091,6 +22219,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -23451,8 +23582,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -23462,11 +23598,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -23517,7 +23656,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -24730,6 +24869,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -24822,6 +24964,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -25104,6 +25249,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -25200,6 +25348,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -26556,8 +26707,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -26567,11 +26723,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -26622,7 +26781,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -27835,6 +27994,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -27927,6 +28089,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -28209,6 +28374,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -28305,6 +28473,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -29175,7 +29346,7 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { - return this->gt_bits(other).any_bits_set(); + return this->lt_bits(other).any_bits_set(); } // Bit-specific operations @@ -29204,6 +29375,9 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return !bits_not_set_anywhere(bits); } + simdjson_inline bool is_ascii() const { + return this->bits_not_set_anywhere(uint8_t(0x80)); + } template <int N> simdjson_inline simd8<uint8_t> shr() const { return simd8<uint8_t>( (__m128i)vec_sr(this->value, (__m128i)vec_splat_u8(N))); @@ -29779,8 +29953,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -29790,11 +29969,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -29845,7 +30027,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -31058,6 +31240,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -31150,6 +31335,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -31432,6 +31620,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -31528,6 +31719,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -32333,7 +32527,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -32752,7 +32946,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -33310,8 +33504,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -33321,11 +33520,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -33376,7 +33578,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -34589,6 +34791,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -34681,6 +34886,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -34963,6 +35171,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -35059,6 +35270,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -35369,7 +35583,18 @@ template <typename T> struct simd8x64; /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include <lsxintrin.h> +#if defined(__clang__) && !defined(__loongarch_asx) +// LLVM's lasxintrin.h only declares the LASX types and functions when +// __loongarch_asx is defined, that is, when the code is compiled with -mlasx. +// For runtime dispatching, we include it inside a target("lasx") region +// (see simdjson/lasx/begin.h) where the LASX builtins are available, so we +// define __loongarch_asx while including the header. +#define __loongarch_asx 1 #include <lasxintrin.h> +#undef __loongarch_asx +#else +#include <lasxintrin.h> +#endif static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX"); @@ -35588,10 +35813,7 @@ namespace simd { __m256i mask = __lasx_xvmskltz_b(*this); return (__lasx_xvpickve2gr_w(mask, 4) << 16) | (__lasx_xvpickve2gr_w(mask, 0)); } - simdjson_inline bool any() const { - __m256i v = __lasx_xvmsknz_b(*this); - return (0 == __lasx_xvpickve2gr_w(v, 0)) && (0 == __lasx_xvpickve2gr_w(v, 4)); - } + simdjson_inline bool any() const { return !__lasx_xbz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -36357,8 +36579,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -36368,11 +36595,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -36423,7 +36653,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -37636,6 +37866,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -37728,6 +37961,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -38010,6 +38246,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -38106,6 +38345,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -38626,7 +38868,7 @@ namespace simd { simdjson_inline simd8(bool _value) : base8<bool>(splat(_value)) {} simdjson_inline int to_bitmask() const { return __lsx_vpickve2gr_w(__lsx_vmskltz_b(*this), 0); } - simdjson_inline bool any() const { return 0 == __lsx_vpickve2gr_hu(__lsx_vmsknz_b(*this), 0); } + simdjson_inline bool any() const { return !__lsx_bz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -39382,8 +39624,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -39393,11 +39640,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -39448,7 +39698,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -40661,6 +40911,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -40753,6 +41006,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -41035,6 +41291,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -41131,6 +41390,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -41618,7 +41880,9 @@ namespace simd { simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); } simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); } simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); } - simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); } + simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(*this, other, VL8); } + simdjson_inline simd8<bool> operator==(const simd8<bool> other) const { return __riscv_vmxnor(*this, other, VL8); } + simdjson_inline bool any() const { return __riscv_vfirst(value, VL8) >= 0; } simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); } simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; } simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; } @@ -41670,9 +41934,9 @@ namespace simd { simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); } simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); } #if __riscv_zvbb - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(value, other, VL8); } #else - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return *this & ~other; } #endif simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; } simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; } @@ -41700,6 +41964,8 @@ namespace simd { simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; } // Order-specific operations + simdjson_inline simd8<uint8_t> max_val(const simd8<uint8_t> other) const { return __riscv_vmaxu(value, other, VL8); } + simdjson_inline simd8<uint8_t> min_val(const simd8<uint8_t> other) const { return __riscv_vminu(value, other, VL8); } simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); } @@ -41711,10 +41977,17 @@ namespace simd { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return (*this & bits).bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return ~this->bits_not_set(bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); } template<int N> @@ -42430,8 +42703,13 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s } size_t max_structures = rounded_capacity + 9; if(max_structures > SIZE_MAX / sizeof(uint32_t)) { return CAPACITY; } - structural_indexes.reset( new (std::nothrow) uint32_t[max_structures] ); - if (!structural_indexes) { _capacity = 0; return MEMALLOC; } + // Allocate before releasing the current buffer so that, on failure, the + // implementation keeps its previous buffer and capacity. Otherwise a parser + // that still believes it has room skips reallocation and stage 1 rejects + // every document with CAPACITY. + std::unique_ptr<uint32_t[]> new_structural_indexes(new (std::nothrow) uint32_t[max_structures]); + if (!new_structural_indexes) { return MEMALLOC; } + structural_indexes = std::move(new_structural_indexes); structural_indexes[0] = 0; n_structural_indexes = 0; @@ -42441,11 +42719,14 @@ inline simdjson_warn_unused error_code dom_parser_implementation::set_capacity(s inline simdjson_warn_unused error_code dom_parser_implementation::set_max_depth(size_t max_depth) noexcept { if(max_depth == 0 || max_depth > SIMDJSON_MAX_DEPTH || max_depth > SIZE_MAX / sizeof(open_container)) { return CAPACITY; } - // Stage 2 stacks - open_containers.reset(new (std::nothrow) open_container[max_depth]); - is_array.reset(new (std::nothrow) bool[max_depth]); - if (!is_array || !open_containers) { _max_depth = 0; return MEMALLOC; } - + // Stage 2 stacks. Allocate both before touching the parser so that, on + // failure, it keeps its previous stacks and depth: a parser whose depth does + // not match its stacks would crash in stage 2. + std::unique_ptr<open_container[]> new_open_containers(new (std::nothrow) open_container[max_depth]); + std::unique_ptr<bool[]> new_is_array(new (std::nothrow) bool[max_depth]); + if (!new_is_array || !new_open_containers) { return MEMALLOC; } + open_containers = std::move(new_open_containers); + is_array = std::move(new_is_array); _max_depth = max_depth; return SUCCESS; } @@ -42496,7 +42777,7 @@ struct implementation_simdjson_result_base { /** * Create a new empty result with error = UNINITIALIZED. */ - simdjson_inline implementation_simdjson_result_base() noexcept = default; + simdjson_inline implementation_simdjson_result_base() noexcept {} /** * Create a new error result. @@ -43709,6 +43990,9 @@ simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned(const u } // Parse any number from 0 to 18,446,744,073,709,551,615 simdjson_unused simdjson_inline simdjson_result<uint64_t> parse_unsigned_in_string(const uint8_t * const src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } const uint8_t *p = src + 1; // // Parse the integer part. @@ -43801,6 +44085,9 @@ simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer(const uin // Parse any number from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 simdjson_unused simdjson_inline simdjson_result<int64_t> parse_integer_in_string(const uint8_t *src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -44083,6 +44370,9 @@ simdjson_unused simdjson_inline simdjson_result<number_type> get_number_type(con } simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -44179,6 +44469,9 @@ simdjson_unused simdjson_inline simdjson_result<double> parse_double_in_string(c // Parse a JSON number held inside a JSON string into a binary32 (float) value. // See parse_float for why we do not simply round parse_double_in_string. simdjson_unused simdjson_inline simdjson_result<float> parse_float_in_string(const uint8_t * src) noexcept { + // The number must be inside a string: anything else (a bare number, an + // array, an object...) is not the requested type. + if (*src != '"') { return INCORRECT_TYPE; } // // Check for minus sign // @@ -45235,6 +45528,9 @@ namespace { simdjson_inline simd8() : simd8(vdupq_n_u8(0)) {} // Splat constructor simdjson_inline simd8(bool _value) : simd8(splat(_value)) {} + // base_u8's operator~ xors with 0xFFu, which simd8<bool> only accepts by + // narrowing it to bool (MSVC C4305). Every other kernel overrides it too. + simdjson_inline simd8<bool> operator~() const { return *this ^ true; } // We return uint32_t instead of uint16_t because that seems to be more efficient for most // purposes (cutting it down to uint16_t costs performance in some compilers). @@ -45334,9 +45630,15 @@ namespace { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return ~any_bits_set(bits); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return vtstq_u8(*this, bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return vmaxvq_u32(vreinterpretq_u32_u8(*this)) != 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return vshrq_n_u8(*this, N); } template<int N> @@ -45927,7 +46229,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -47447,14 +47765,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -47553,10 +47871,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -48220,7 +48545,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -49740,14 +50081,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -49846,10 +50187,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -50983,7 +51331,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -52503,14 +52867,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -52609,10 +52973,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -53742,7 +54113,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -55262,14 +55649,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -55368,10 +55755,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -56188,7 +56582,7 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { - return this->gt_bits(other).any_bits_set(); + return this->lt_bits(other).any_bits_set(); } // Bit-specific operations @@ -56217,6 +56611,9 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return !bits_not_set_anywhere(bits); } + simdjson_inline bool is_ascii() const { + return this->bits_not_set_anywhere(uint8_t(0x80)); + } template <int N> simdjson_inline simd8<uint8_t> shr() const { return simd8<uint8_t>( (__m128i)vec_sr(this->value, (__m128i)vec_splat_u8(N))); @@ -56619,7 +57016,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -58139,14 +58552,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -58245,10 +58658,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -59000,7 +59420,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -59419,7 +59839,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -59804,7 +60224,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -61324,14 +61760,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -61430,10 +61866,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -61896,7 +62339,7 @@ namespace simd { simdjson_inline simd8(bool _value) : base8<bool>(splat(_value)) {} simdjson_inline int to_bitmask() const { return __lsx_vpickve2gr_w(__lsx_vmskltz_b(*this), 0); } - simdjson_inline bool any() const { return 0 == __lsx_vpickve2gr_hu(__lsx_vmsknz_b(*this), 0); } + simdjson_inline bool any() const { return !__lsx_bz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -62479,7 +62922,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -63999,14 +64458,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -64105,10 +64564,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -64362,7 +64828,18 @@ template <typename T> struct simd8x64; /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include <lsxintrin.h> +#if defined(__clang__) && !defined(__loongarch_asx) +// LLVM's lasxintrin.h only declares the LASX types and functions when +// __loongarch_asx is defined, that is, when the code is compiled with -mlasx. +// For runtime dispatching, we include it inside a target("lasx") region +// (see simdjson/lasx/begin.h) where the LASX builtins are available, so we +// define __loongarch_asx while including the header. +#define __loongarch_asx 1 #include <lasxintrin.h> +#undef __loongarch_asx +#else +#include <lasxintrin.h> +#endif static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX"); @@ -64581,10 +65058,7 @@ namespace simd { __m256i mask = __lasx_xvmskltz_b(*this); return (__lasx_xvpickve2gr_w(mask, 4) << 16) | (__lasx_xvpickve2gr_w(mask, 0)); } - simdjson_inline bool any() const { - __m256i v = __lasx_xvmsknz_b(*this); - return (0 == __lasx_xvpickve2gr_w(v, 0)) && (0 == __lasx_xvpickve2gr_w(v, 4)); - } + simdjson_inline bool any() const { return !__lasx_xbz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -65177,7 +65651,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -66697,14 +67187,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -66803,10 +67293,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -67246,7 +67743,9 @@ namespace simd { simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); } simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); } simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); } - simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); } + simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(*this, other, VL8); } + simdjson_inline simd8<bool> operator==(const simd8<bool> other) const { return __riscv_vmxnor(*this, other, VL8); } + simdjson_inline bool any() const { return __riscv_vfirst(value, VL8) >= 0; } simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); } simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; } simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; } @@ -67298,9 +67797,9 @@ namespace simd { simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); } simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); } #if __riscv_zvbb - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(value, other, VL8); } #else - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return *this & ~other; } #endif simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; } simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; } @@ -67328,6 +67827,8 @@ namespace simd { simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; } // Order-specific operations + simdjson_inline simd8<uint8_t> max_val(const simd8<uint8_t> other) const { return __riscv_vmaxu(value, other, VL8); } + simdjson_inline simd8<uint8_t> min_val(const simd8<uint8_t> other) const { return __riscv_vminu(value, other, VL8); } simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); } @@ -67339,10 +67840,17 @@ namespace simd { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return (*this & bits).bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return ~this->bits_not_set(bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); } template<int N> @@ -67885,7 +68393,23 @@ requires (!std::is_convertible<R, std::string_view>::value && !concepts::optiona * The result may not be valid UTF-8 if some of your content was not valid UTF-8. * Use validate_unicode() to check the content if needed. */ - simdjson_inline operator std::string() const noexcept(false); + simdjson_inline operator std::string() const & noexcept(false); + + /** + * Moves the written JSON buffer out of the builder into an std::string, + * see move_to(). The builder is left empty and can be reused. + * Throws if memory allocation failed. + * + * Used for copy-initialization from an rvalue, e.g. + * `std::string s = std::move(builder);`, and for `return builder;` from a + * function returning std::string (implicit move, C++20 or as an extension). + * Direct-initialization, `std::string s(std::move(builder));`, may copy + * through operator std::string_view() instead, depending on the compiler. + * + * The result may not be valid UTF-8 if some of your content was not valid UTF-8. + * Use validate_unicode() to check the content if needed. + */ + inline operator std::string() && noexcept(false); /** * Creates an std::string_view from the written JSON buffer. @@ -69405,14 +69929,14 @@ simdjson_inline void string_builder::append_raw(const char *c) noexcept { simdjson_inline void string_builder::append_raw(std::string_view input) noexcept { - if (capacity_check(input.size())) { - std::memcpy(buffer_data() + position, input.data(), input.size()); - position += input.size(); - } + append_raw(input.data(), input.size()); } simdjson_inline void string_builder::append_raw(const char *str, size_t len) noexcept { + if (len == 0) { + return; + } if (capacity_check(len)) { std::memcpy(buffer_data() + position, str, len); position += len; @@ -69511,10 +70035,17 @@ simdjson_inline void string_builder::append(const R &range) noexcept { #endif #if SIMDJSON_EXCEPTIONS -simdjson_inline string_builder::operator std::string() const noexcept(false) { +simdjson_inline string_builder::operator std::string() const & noexcept(false) { return std::string(operator std::string_view()); } +inline string_builder::operator std::string() && noexcept(false) { + std::string out; + error_code error = move_to(out); + if (error) { throw simdjson_error(error); } + return out; +} + simdjson_inline string_builder::operator std::string_view() const noexcept(false) simdjson_lifetime_bound { return view(); @@ -70182,6 +70713,9 @@ namespace { simdjson_inline simd8() : simd8(vdupq_n_u8(0)) {} // Splat constructor simdjson_inline simd8(bool _value) : simd8(splat(_value)) {} + // base_u8's operator~ xors with 0xFFu, which simd8<bool> only accepts by + // narrowing it to bool (MSVC C4305). Every other kernel overrides it too. + simdjson_inline simd8<bool> operator~() const { return *this ^ true; } // We return uint32_t instead of uint16_t because that seems to be more efficient for most // purposes (cutting it down to uint16_t costs performance in some compilers). @@ -70281,9 +70815,15 @@ namespace { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return ~any_bits_set(bits); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return vtstq_u8(*this, bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return vmaxvq_u32(vreinterpretq_u32_u8(*this)) != 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return vshrq_n_u8(*this, N); } template<int N> @@ -70834,7 +71374,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -70842,6 +71390,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -71159,6 +71716,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -71303,7 +71866,7 @@ struct simdjson_result<arm64::ondemand::value_iterator> : public arm64::implemen public: simdjson_inline simdjson_result(arm64::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -72211,7 +72774,7 @@ struct simdjson_result<arm64::ondemand::value> : public arm64::implementation_si public: simdjson_inline simdjson_result(arm64::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<arm64::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<arm64::ondemand::object> get_object() noexcept; @@ -72484,7 +73047,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -72610,7 +73173,7 @@ struct simdjson_result<arm64::ondemand::token_iterator> : public arm64::implemen public: simdjson_inline simdjson_result(arm64::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -72687,7 +73250,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -72696,6 +73259,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -72712,6 +73291,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -72891,6 +73476,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -72963,7 +73554,7 @@ struct simdjson_result<arm64::ondemand::json_iterator> : public arm64::implement simdjson_inline simdjson_result(arm64::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -73126,7 +73717,7 @@ struct simdjson_result<arm64::ondemand::json_type> : public arm64::implementatio public: simdjson_inline simdjson_result(arm64::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -73178,7 +73769,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -73294,6 +73885,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -73333,6 +73938,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -73359,7 +73965,7 @@ struct simdjson_result<arm64::ondemand::raw_json_string> : public arm64::impleme public: simdjson_inline simdjson_result(arm64::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -73821,6 +74427,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -73828,6 +74438,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -73848,7 +74462,7 @@ struct simdjson_result<arm64::ondemand::parser> : public arm64::implementation_s public: simdjson_inline simdjson_result(arm64::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -73884,7 +74498,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -74131,7 +74745,7 @@ struct simdjson_result<arm64::ondemand::array> : public arm64::implementation_si public: simdjson_inline simdjson_result(arm64::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<arm64::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<arm64::ondemand::array_iterator> begin() && noexcept; @@ -74212,7 +74826,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -74270,6 +74884,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -74294,7 +74909,7 @@ struct simdjson_result<arm64::ondemand::array_iterator> : public arm64::implemen simdjson_inline simdjson_result(arm64::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -74344,7 +74959,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -75467,7 +76082,7 @@ struct simdjson_result<arm64::ondemand::document> : public arm64::implementation public: simdjson_inline simdjson_result(arm64::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<arm64::ondemand::array> get_array() & noexcept; @@ -75597,7 +76212,7 @@ template<> struct simdjson_result<arm64::ondemand::document_reference> : public arm64::implementation_simdjson_result_base<arm64::ondemand::document_reference> { public: simdjson_inline simdjson_result(arm64::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<arm64::ondemand::array> get_array() & noexcept; @@ -75744,7 +76359,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -76094,7 +76709,7 @@ struct simdjson_result<arm64::ondemand::document_stream> : public arm64::impleme public: simdjson_inline simdjson_result(arm64::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -76222,7 +76837,7 @@ struct simdjson_result<arm64::ondemand::field> : public arm64::implementation_si public: simdjson_inline simdjson_result(arm64::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -77766,7 +78381,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -77788,7 +78403,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -78236,7 +78851,7 @@ struct simdjson_result<arm64::ondemand::object> : public arm64::implementation_s public: simdjson_inline simdjson_result(arm64::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<arm64::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<arm64::ondemand::object_iterator> begin() && noexcept; @@ -78355,7 +78970,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -78396,6 +79011,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -78413,7 +79029,7 @@ struct simdjson_result<arm64::ondemand::object_iterator> : public arm64::impleme public: simdjson_inline simdjson_result(arm64::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -78472,7 +79088,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -78516,7 +79132,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -78544,7 +79160,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -78572,7 +79188,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -78834,6 +79450,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -78887,6 +79507,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -78904,7 +79534,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); arm64::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, arm64::ondemand::array>) { arr = val; @@ -78984,35 +79614,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, arm64::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - arm64::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, arm64::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + arm64::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, arm64::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -79029,27 +79646,6 @@ error_code tag_invoke(deserialize_tag, arm64::ondemand::object &obj, T &out) noe return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, arm64::ondemand::value &val, T &out) noexcept(false) { - arm64::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, arm64::ondemand::document &doc, T &out) noexcept(false) { - arm64::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, arm64::ondemand::document_reference &doc, T &out) noexcept(false) { - arm64::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -79072,7 +79668,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -79095,10 +79691,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -79107,10 +79711,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -79132,6 +79748,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -79900,15 +80518,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -80088,12 +80703,12 @@ namespace arm64 { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -80106,7 +80721,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -80119,6 +80735,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -80128,7 +80745,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -80139,6 +80757,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -80166,8 +80785,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -80622,6 +81242,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -80641,6 +81262,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -81436,6 +82062,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -81463,7 +82097,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -81491,6 +82125,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -82821,6 +83461,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -82839,7 +83550,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -82853,7 +83565,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -83070,10 +83783,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -83305,14 +84018,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -83340,7 +84147,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -83350,6 +84157,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -83360,53 +84175,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -83432,6 +84248,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -83452,6 +84282,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -83609,6 +84445,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -84208,7 +85084,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -84366,7 +85242,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -84386,16 +85263,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -84755,7 +85632,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -84768,6 +85646,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -84777,7 +85656,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -84788,6 +85668,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -84802,6 +85683,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -84827,7 +85709,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -85087,25 +85969,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -85152,7 +86046,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -85422,7 +86349,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -85442,7 +86369,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -85474,6 +86401,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -85775,13 +86736,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -85841,10 +86811,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -85894,7 +86878,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -85903,8 +86887,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -85912,14 +86894,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -85927,9 +86902,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -86009,7 +86984,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -86036,8 +87011,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -86046,14 +87019,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -86061,9 +87027,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -86086,8 +87052,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -86096,14 +87060,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -86111,9 +87068,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -86158,6 +87115,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -86248,6 +87213,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -86271,15 +87241,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -86290,8 +87254,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -86440,15 +87403,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -86650,6 +87607,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -86709,6 +87683,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -86772,6 +87753,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -86888,7 +87875,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -88327,7 +89319,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -88335,6 +89335,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -88652,6 +89661,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -88796,7 +89811,7 @@ struct simdjson_result<fallback::ondemand::value_iterator> : public fallback::im public: simdjson_inline simdjson_result(fallback::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -89704,7 +90719,7 @@ struct simdjson_result<fallback::ondemand::value> : public fallback::implementat public: simdjson_inline simdjson_result(fallback::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<fallback::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<fallback::ondemand::object> get_object() noexcept; @@ -89977,7 +90992,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -90103,7 +91118,7 @@ struct simdjson_result<fallback::ondemand::token_iterator> : public fallback::im public: simdjson_inline simdjson_result(fallback::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -90180,7 +91195,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -90189,6 +91204,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -90205,6 +91236,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -90384,6 +91421,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -90456,7 +91499,7 @@ struct simdjson_result<fallback::ondemand::json_iterator> : public fallback::imp simdjson_inline simdjson_result(fallback::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -90619,7 +91662,7 @@ struct simdjson_result<fallback::ondemand::json_type> : public fallback::impleme public: simdjson_inline simdjson_result(fallback::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -90671,7 +91714,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -90787,6 +91830,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -90826,6 +91883,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -90852,7 +91910,7 @@ struct simdjson_result<fallback::ondemand::raw_json_string> : public fallback::i public: simdjson_inline simdjson_result(fallback::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -91314,6 +92372,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -91321,6 +92383,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -91341,7 +92407,7 @@ struct simdjson_result<fallback::ondemand::parser> : public fallback::implementa public: simdjson_inline simdjson_result(fallback::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -91377,7 +92443,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -91624,7 +92690,7 @@ struct simdjson_result<fallback::ondemand::array> : public fallback::implementat public: simdjson_inline simdjson_result(fallback::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<fallback::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<fallback::ondemand::array_iterator> begin() && noexcept; @@ -91705,7 +92771,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -91763,6 +92829,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -91787,7 +92854,7 @@ struct simdjson_result<fallback::ondemand::array_iterator> : public fallback::im simdjson_inline simdjson_result(fallback::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -91837,7 +92904,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -92960,7 +94027,7 @@ struct simdjson_result<fallback::ondemand::document> : public fallback::implemen public: simdjson_inline simdjson_result(fallback::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<fallback::ondemand::array> get_array() & noexcept; @@ -93090,7 +94157,7 @@ template<> struct simdjson_result<fallback::ondemand::document_reference> : public fallback::implementation_simdjson_result_base<fallback::ondemand::document_reference> { public: simdjson_inline simdjson_result(fallback::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<fallback::ondemand::array> get_array() & noexcept; @@ -93237,7 +94304,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -93587,7 +94654,7 @@ struct simdjson_result<fallback::ondemand::document_stream> : public fallback::i public: simdjson_inline simdjson_result(fallback::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -93715,7 +94782,7 @@ struct simdjson_result<fallback::ondemand::field> : public fallback::implementat public: simdjson_inline simdjson_result(fallback::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -95259,7 +96326,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -95281,7 +96348,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -95729,7 +96796,7 @@ struct simdjson_result<fallback::ondemand::object> : public fallback::implementa public: simdjson_inline simdjson_result(fallback::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<fallback::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<fallback::ondemand::object_iterator> begin() && noexcept; @@ -95848,7 +96915,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -95889,6 +96956,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -95906,7 +96974,7 @@ struct simdjson_result<fallback::ondemand::object_iterator> : public fallback::i public: simdjson_inline simdjson_result(fallback::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -95965,7 +97033,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -96009,7 +97077,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -96037,7 +97105,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -96065,7 +97133,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -96327,6 +97395,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -96380,6 +97452,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -96397,7 +97479,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); fallback::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, fallback::ondemand::array>) { arr = val; @@ -96477,35 +97559,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, fallback::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - fallback::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, fallback::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + fallback::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, fallback::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -96522,27 +97591,6 @@ error_code tag_invoke(deserialize_tag, fallback::ondemand::object &obj, T &out) return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, fallback::ondemand::value &val, T &out) noexcept(false) { - fallback::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, fallback::ondemand::document &doc, T &out) noexcept(false) { - fallback::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, fallback::ondemand::document_reference &doc, T &out) noexcept(false) { - fallback::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -96565,7 +97613,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -96588,10 +97636,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -96600,10 +97656,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -96625,6 +97693,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -97393,15 +98463,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -97581,12 +98648,12 @@ namespace fallback { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -97599,7 +98666,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -97612,6 +98680,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -97621,7 +98690,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -97632,6 +98702,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -97659,8 +98730,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -98115,6 +99187,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -98134,6 +99207,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -98929,6 +100007,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -98956,7 +100042,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -98984,6 +100070,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -100314,6 +101406,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -100332,7 +101495,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -100346,7 +101510,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -100563,10 +101728,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -100798,14 +101963,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -100833,7 +102092,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -100843,6 +102102,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -100853,53 +102120,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -100925,6 +102193,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -100945,6 +102227,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -101102,6 +102390,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -101701,7 +103029,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -101859,7 +103187,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -101879,16 +103208,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -102248,7 +103577,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -102261,6 +103591,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -102270,7 +103601,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -102281,6 +103613,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -102295,6 +103628,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -102320,7 +103654,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -102580,25 +103914,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -102645,7 +103991,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -102915,7 +104294,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -102935,7 +104314,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -102967,6 +104346,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -103268,13 +104681,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -103334,10 +104756,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -103387,7 +104823,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -103396,8 +104832,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -103405,14 +104839,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -103420,9 +104847,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -103502,7 +104929,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -103529,8 +104956,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -103539,14 +104964,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -103554,9 +104972,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -103579,8 +104997,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -103589,14 +105005,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -103604,9 +105013,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -103651,6 +105060,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -103741,6 +105158,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -103764,15 +105186,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -103783,8 +105199,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -103933,15 +105348,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -104143,6 +105552,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -104202,6 +105628,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -104265,6 +105698,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -104381,7 +105820,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -106290,7 +107734,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -106298,6 +107750,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -106615,6 +108076,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -106759,7 +108226,7 @@ struct simdjson_result<haswell::ondemand::value_iterator> : public haswell::impl public: simdjson_inline simdjson_result(haswell::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -107667,7 +109134,7 @@ struct simdjson_result<haswell::ondemand::value> : public haswell::implementatio public: simdjson_inline simdjson_result(haswell::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<haswell::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<haswell::ondemand::object> get_object() noexcept; @@ -107940,7 +109407,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -108066,7 +109533,7 @@ struct simdjson_result<haswell::ondemand::token_iterator> : public haswell::impl public: simdjson_inline simdjson_result(haswell::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -108143,7 +109610,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -108152,6 +109619,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -108168,6 +109651,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -108347,6 +109836,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -108419,7 +109914,7 @@ struct simdjson_result<haswell::ondemand::json_iterator> : public haswell::imple simdjson_inline simdjson_result(haswell::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -108582,7 +110077,7 @@ struct simdjson_result<haswell::ondemand::json_type> : public haswell::implement public: simdjson_inline simdjson_result(haswell::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -108634,7 +110129,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -108750,6 +110245,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -108789,6 +110298,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -108815,7 +110325,7 @@ struct simdjson_result<haswell::ondemand::raw_json_string> : public haswell::imp public: simdjson_inline simdjson_result(haswell::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -109277,6 +110787,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -109284,6 +110798,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -109304,7 +110822,7 @@ struct simdjson_result<haswell::ondemand::parser> : public haswell::implementati public: simdjson_inline simdjson_result(haswell::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -109340,7 +110858,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -109587,7 +111105,7 @@ struct simdjson_result<haswell::ondemand::array> : public haswell::implementatio public: simdjson_inline simdjson_result(haswell::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<haswell::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<haswell::ondemand::array_iterator> begin() && noexcept; @@ -109668,7 +111186,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -109726,6 +111244,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -109750,7 +111269,7 @@ struct simdjson_result<haswell::ondemand::array_iterator> : public haswell::impl simdjson_inline simdjson_result(haswell::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -109800,7 +111319,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -110923,7 +112442,7 @@ struct simdjson_result<haswell::ondemand::document> : public haswell::implementa public: simdjson_inline simdjson_result(haswell::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<haswell::ondemand::array> get_array() & noexcept; @@ -111053,7 +112572,7 @@ template<> struct simdjson_result<haswell::ondemand::document_reference> : public haswell::implementation_simdjson_result_base<haswell::ondemand::document_reference> { public: simdjson_inline simdjson_result(haswell::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<haswell::ondemand::array> get_array() & noexcept; @@ -111200,7 +112719,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -111550,7 +113069,7 @@ struct simdjson_result<haswell::ondemand::document_stream> : public haswell::imp public: simdjson_inline simdjson_result(haswell::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -111678,7 +113197,7 @@ struct simdjson_result<haswell::ondemand::field> : public haswell::implementatio public: simdjson_inline simdjson_result(haswell::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -113222,7 +114741,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -113244,7 +114763,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -113692,7 +115211,7 @@ struct simdjson_result<haswell::ondemand::object> : public haswell::implementati public: simdjson_inline simdjson_result(haswell::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<haswell::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<haswell::ondemand::object_iterator> begin() && noexcept; @@ -113811,7 +115330,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -113852,6 +115371,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -113869,7 +115389,7 @@ struct simdjson_result<haswell::ondemand::object_iterator> : public haswell::imp public: simdjson_inline simdjson_result(haswell::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -113928,7 +115448,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -113972,7 +115492,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -114000,7 +115520,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -114028,7 +115548,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -114290,6 +115810,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -114343,6 +115867,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -114360,7 +115894,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); haswell::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, haswell::ondemand::array>) { arr = val; @@ -114440,35 +115974,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, haswell::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - haswell::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, haswell::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + haswell::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, haswell::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -114485,27 +116006,6 @@ error_code tag_invoke(deserialize_tag, haswell::ondemand::object &obj, T &out) n return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, haswell::ondemand::value &val, T &out) noexcept(false) { - haswell::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, haswell::ondemand::document &doc, T &out) noexcept(false) { - haswell::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, haswell::ondemand::document_reference &doc, T &out) noexcept(false) { - haswell::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -114528,7 +116028,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -114551,10 +116051,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -114563,10 +116071,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -114588,6 +116108,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -115356,15 +116878,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -115544,12 +117063,12 @@ namespace haswell { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -115562,7 +117081,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -115575,6 +117095,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -115584,7 +117105,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -115595,6 +117117,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -115622,8 +117145,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -116078,6 +117602,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -116097,6 +117622,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -116892,6 +118422,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -116919,7 +118457,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -116947,6 +118485,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -118277,6 +119821,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -118295,7 +119910,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -118309,7 +119925,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -118526,10 +120143,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -118761,14 +120378,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -118796,7 +120507,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -118806,6 +120517,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -118816,53 +120535,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -118888,6 +120608,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -118908,6 +120642,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -119065,6 +120805,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -119664,7 +121444,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -119822,7 +121602,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -119842,16 +121623,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -120211,7 +121992,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -120224,6 +122006,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -120233,7 +122016,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -120244,6 +122028,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -120258,6 +122043,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -120283,7 +122069,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -120543,25 +122329,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -120608,7 +122406,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -120878,7 +122709,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -120898,7 +122729,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -120930,6 +122761,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -121231,13 +123096,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -121297,10 +123171,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -121350,7 +123238,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -121359,8 +123247,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -121368,14 +123254,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -121383,9 +123262,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -121465,7 +123344,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -121492,8 +123371,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -121502,14 +123379,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -121517,9 +123387,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -121542,8 +123412,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -121552,14 +123420,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -121567,9 +123428,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -121614,6 +123475,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -121704,6 +123573,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -121727,15 +123601,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -121746,8 +123614,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -121896,15 +123763,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -122106,6 +123967,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -122165,6 +124043,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -122228,6 +124113,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -122344,7 +124235,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -124249,7 +126145,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -124257,6 +126161,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -124574,6 +126487,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -124718,7 +126637,7 @@ struct simdjson_result<icelake::ondemand::value_iterator> : public icelake::impl public: simdjson_inline simdjson_result(icelake::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -125626,7 +127545,7 @@ struct simdjson_result<icelake::ondemand::value> : public icelake::implementatio public: simdjson_inline simdjson_result(icelake::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<icelake::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<icelake::ondemand::object> get_object() noexcept; @@ -125899,7 +127818,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -126025,7 +127944,7 @@ struct simdjson_result<icelake::ondemand::token_iterator> : public icelake::impl public: simdjson_inline simdjson_result(icelake::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -126102,7 +128021,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -126111,6 +128030,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -126127,6 +128062,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -126306,6 +128247,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -126378,7 +128325,7 @@ struct simdjson_result<icelake::ondemand::json_iterator> : public icelake::imple simdjson_inline simdjson_result(icelake::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -126541,7 +128488,7 @@ struct simdjson_result<icelake::ondemand::json_type> : public icelake::implement public: simdjson_inline simdjson_result(icelake::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -126593,7 +128540,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -126709,6 +128656,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -126748,6 +128709,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -126774,7 +128736,7 @@ struct simdjson_result<icelake::ondemand::raw_json_string> : public icelake::imp public: simdjson_inline simdjson_result(icelake::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -127236,6 +129198,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -127243,6 +129209,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -127263,7 +129233,7 @@ struct simdjson_result<icelake::ondemand::parser> : public icelake::implementati public: simdjson_inline simdjson_result(icelake::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -127299,7 +129269,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -127546,7 +129516,7 @@ struct simdjson_result<icelake::ondemand::array> : public icelake::implementatio public: simdjson_inline simdjson_result(icelake::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<icelake::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<icelake::ondemand::array_iterator> begin() && noexcept; @@ -127627,7 +129597,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -127685,6 +129655,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -127709,7 +129680,7 @@ struct simdjson_result<icelake::ondemand::array_iterator> : public icelake::impl simdjson_inline simdjson_result(icelake::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -127759,7 +129730,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -128882,7 +130853,7 @@ struct simdjson_result<icelake::ondemand::document> : public icelake::implementa public: simdjson_inline simdjson_result(icelake::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<icelake::ondemand::array> get_array() & noexcept; @@ -129012,7 +130983,7 @@ template<> struct simdjson_result<icelake::ondemand::document_reference> : public icelake::implementation_simdjson_result_base<icelake::ondemand::document_reference> { public: simdjson_inline simdjson_result(icelake::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<icelake::ondemand::array> get_array() & noexcept; @@ -129159,7 +131130,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -129509,7 +131480,7 @@ struct simdjson_result<icelake::ondemand::document_stream> : public icelake::imp public: simdjson_inline simdjson_result(icelake::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -129637,7 +131608,7 @@ struct simdjson_result<icelake::ondemand::field> : public icelake::implementatio public: simdjson_inline simdjson_result(icelake::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -131181,7 +133152,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -131203,7 +133174,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -131651,7 +133622,7 @@ struct simdjson_result<icelake::ondemand::object> : public icelake::implementati public: simdjson_inline simdjson_result(icelake::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<icelake::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<icelake::ondemand::object_iterator> begin() && noexcept; @@ -131770,7 +133741,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -131811,6 +133782,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -131828,7 +133800,7 @@ struct simdjson_result<icelake::ondemand::object_iterator> : public icelake::imp public: simdjson_inline simdjson_result(icelake::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -131887,7 +133859,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -131931,7 +133903,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -131959,7 +133931,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -131987,7 +133959,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -132249,6 +134221,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -132302,6 +134278,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -132319,7 +134305,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); icelake::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, icelake::ondemand::array>) { arr = val; @@ -132399,35 +134385,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, icelake::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - icelake::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, icelake::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + icelake::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, icelake::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -132444,27 +134417,6 @@ error_code tag_invoke(deserialize_tag, icelake::ondemand::object &obj, T &out) n return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, icelake::ondemand::value &val, T &out) noexcept(false) { - icelake::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, icelake::ondemand::document &doc, T &out) noexcept(false) { - icelake::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, icelake::ondemand::document_reference &doc, T &out) noexcept(false) { - icelake::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -132487,7 +134439,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -132510,10 +134462,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -132522,10 +134482,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -132547,6 +134519,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -133315,15 +135289,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -133503,12 +135474,12 @@ namespace icelake { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -133521,7 +135492,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -133534,6 +135506,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -133543,7 +135516,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -133554,6 +135528,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -133581,8 +135556,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -134037,6 +136013,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -134056,6 +136033,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -134851,6 +136833,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -134878,7 +136868,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -134906,6 +136896,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -136236,6 +138232,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -136254,7 +138321,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -136268,7 +138336,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -136485,10 +138554,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -136720,14 +138789,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -136755,7 +138918,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -136765,6 +138928,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -136775,53 +138946,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -136847,6 +139019,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -136867,6 +139053,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -137024,6 +139216,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -137623,7 +139855,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -137781,7 +140013,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -137801,16 +140034,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -138170,7 +140403,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -138183,6 +140417,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -138192,7 +140427,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -138203,6 +140439,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -138217,6 +140454,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -138242,7 +140480,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -138502,25 +140740,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -138567,7 +140817,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -138837,7 +141120,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -138857,7 +141140,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -138889,6 +141172,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -139190,13 +141507,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -139256,10 +141582,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -139309,7 +141649,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -139318,8 +141658,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -139327,14 +141665,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -139342,9 +141673,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -139424,7 +141755,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -139451,8 +141782,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -139461,14 +141790,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -139476,9 +141798,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -139501,8 +141823,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -139511,14 +141831,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -139526,9 +141839,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -139573,6 +141886,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -139663,6 +141984,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -139686,15 +142012,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -139705,8 +142025,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -139855,15 +142174,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -140065,6 +142378,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -140124,6 +142454,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -140187,6 +142524,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -140303,7 +142646,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -141935,7 +144283,7 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { - return this->gt_bits(other).any_bits_set(); + return this->lt_bits(other).any_bits_set(); } // Bit-specific operations @@ -141964,6 +144312,9 @@ template <> struct simd8<uint8_t> : base8_numeric<uint8_t> { simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return !bits_not_set_anywhere(bits); } + simdjson_inline bool is_ascii() const { + return this->bits_not_set_anywhere(uint8_t(0x80)); + } template <int N> simdjson_inline simd8<uint8_t> shr() const { return simd8<uint8_t>( (__m128i)vec_sr(this->value, (__m128i)vec_splat_u8(N))); @@ -142326,7 +144677,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -142334,6 +144693,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -142651,6 +145019,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -142795,7 +145169,7 @@ struct simdjson_result<ppc64::ondemand::value_iterator> : public ppc64::implemen public: simdjson_inline simdjson_result(ppc64::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -143703,7 +146077,7 @@ struct simdjson_result<ppc64::ondemand::value> : public ppc64::implementation_si public: simdjson_inline simdjson_result(ppc64::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<ppc64::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<ppc64::ondemand::object> get_object() noexcept; @@ -143976,7 +146350,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -144102,7 +146476,7 @@ struct simdjson_result<ppc64::ondemand::token_iterator> : public ppc64::implemen public: simdjson_inline simdjson_result(ppc64::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -144179,7 +146553,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -144188,6 +146562,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -144204,6 +146594,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -144383,6 +146779,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -144455,7 +146857,7 @@ struct simdjson_result<ppc64::ondemand::json_iterator> : public ppc64::implement simdjson_inline simdjson_result(ppc64::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -144618,7 +147020,7 @@ struct simdjson_result<ppc64::ondemand::json_type> : public ppc64::implementatio public: simdjson_inline simdjson_result(ppc64::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -144670,7 +147072,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -144786,6 +147188,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -144825,6 +147241,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -144851,7 +147268,7 @@ struct simdjson_result<ppc64::ondemand::raw_json_string> : public ppc64::impleme public: simdjson_inline simdjson_result(ppc64::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -145313,6 +147730,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -145320,6 +147741,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -145340,7 +147765,7 @@ struct simdjson_result<ppc64::ondemand::parser> : public ppc64::implementation_s public: simdjson_inline simdjson_result(ppc64::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -145376,7 +147801,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -145623,7 +148048,7 @@ struct simdjson_result<ppc64::ondemand::array> : public ppc64::implementation_si public: simdjson_inline simdjson_result(ppc64::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<ppc64::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<ppc64::ondemand::array_iterator> begin() && noexcept; @@ -145704,7 +148129,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -145762,6 +148187,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -145786,7 +148212,7 @@ struct simdjson_result<ppc64::ondemand::array_iterator> : public ppc64::implemen simdjson_inline simdjson_result(ppc64::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -145836,7 +148262,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -146959,7 +149385,7 @@ struct simdjson_result<ppc64::ondemand::document> : public ppc64::implementation public: simdjson_inline simdjson_result(ppc64::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<ppc64::ondemand::array> get_array() & noexcept; @@ -147089,7 +149515,7 @@ template<> struct simdjson_result<ppc64::ondemand::document_reference> : public ppc64::implementation_simdjson_result_base<ppc64::ondemand::document_reference> { public: simdjson_inline simdjson_result(ppc64::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<ppc64::ondemand::array> get_array() & noexcept; @@ -147236,7 +149662,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -147586,7 +150012,7 @@ struct simdjson_result<ppc64::ondemand::document_stream> : public ppc64::impleme public: simdjson_inline simdjson_result(ppc64::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -147714,7 +150140,7 @@ struct simdjson_result<ppc64::ondemand::field> : public ppc64::implementation_si public: simdjson_inline simdjson_result(ppc64::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -149258,7 +151684,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -149280,7 +151706,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -149728,7 +152154,7 @@ struct simdjson_result<ppc64::ondemand::object> : public ppc64::implementation_s public: simdjson_inline simdjson_result(ppc64::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<ppc64::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<ppc64::ondemand::object_iterator> begin() && noexcept; @@ -149847,7 +152273,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -149888,6 +152314,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -149905,7 +152332,7 @@ struct simdjson_result<ppc64::ondemand::object_iterator> : public ppc64::impleme public: simdjson_inline simdjson_result(ppc64::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -149964,7 +152391,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -150008,7 +152435,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -150036,7 +152463,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -150064,7 +152491,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -150326,6 +152753,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -150379,6 +152810,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -150396,7 +152837,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); ppc64::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, ppc64::ondemand::array>) { arr = val; @@ -150476,35 +152917,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, ppc64::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - ppc64::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, ppc64::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + ppc64::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, ppc64::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -150521,27 +152949,6 @@ error_code tag_invoke(deserialize_tag, ppc64::ondemand::object &obj, T &out) noe return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, ppc64::ondemand::value &val, T &out) noexcept(false) { - ppc64::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, ppc64::ondemand::document &doc, T &out) noexcept(false) { - ppc64::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, ppc64::ondemand::document_reference &doc, T &out) noexcept(false) { - ppc64::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -150564,7 +152971,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -150587,10 +152994,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -150599,10 +153014,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -150624,6 +153051,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -151392,15 +153821,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -151580,12 +154006,12 @@ namespace ppc64 { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -151598,7 +154024,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -151611,6 +154038,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -151620,7 +154048,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -151631,6 +154060,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -151658,8 +154088,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -152114,6 +154545,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -152133,6 +154565,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -152928,6 +155365,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -152955,7 +155400,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -152983,6 +155428,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -154313,6 +156764,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -154331,7 +156853,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -154345,7 +156868,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -154562,10 +157086,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -154797,14 +157321,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -154832,7 +157450,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -154842,6 +157460,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -154852,53 +157478,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -154924,6 +157551,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -154944,6 +157585,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -155101,6 +157748,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -155700,7 +158387,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -155858,7 +158545,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -155878,16 +158566,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -156247,7 +158935,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -156260,6 +158949,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -156269,7 +158959,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -156280,6 +158971,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -156294,6 +158986,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -156319,7 +159012,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -156579,25 +159272,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -156644,7 +159349,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -156914,7 +159652,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -156934,7 +159672,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -156966,6 +159704,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -157267,13 +160039,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -157333,10 +160114,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -157386,7 +160181,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -157395,8 +160190,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -157404,14 +160197,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -157419,9 +160205,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -157501,7 +160287,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -157528,8 +160314,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -157538,14 +160322,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -157553,9 +160330,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -157578,8 +160355,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -157588,14 +160363,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -157603,9 +160371,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -157650,6 +160418,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -157740,6 +160516,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -157763,15 +160544,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -157782,8 +160557,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -157932,15 +160706,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -158142,6 +160910,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -158201,6 +160986,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -158264,6 +161056,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -158380,7 +161178,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -159947,7 +162750,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -160366,7 +163169,7 @@ namespace simd { simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return other.max_val(*this) == other; } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return other.min_val(*this) == other; } simdjson_inline simd8<bool> operator>(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } - simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->gt_bits(other).any_bits_set(); } + simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return this->lt_bits(other).any_bits_set(); } // Bit-specific operations simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } @@ -160711,7 +163514,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -160719,6 +163530,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -161036,6 +163856,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -161180,7 +164006,7 @@ struct simdjson_result<westmere::ondemand::value_iterator> : public westmere::im public: simdjson_inline simdjson_result(westmere::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -162088,7 +164914,7 @@ struct simdjson_result<westmere::ondemand::value> : public westmere::implementat public: simdjson_inline simdjson_result(westmere::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<westmere::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<westmere::ondemand::object> get_object() noexcept; @@ -162361,7 +165187,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -162487,7 +165313,7 @@ struct simdjson_result<westmere::ondemand::token_iterator> : public westmere::im public: simdjson_inline simdjson_result(westmere::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -162564,7 +165390,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -162573,6 +165399,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -162589,6 +165431,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -162768,6 +165616,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -162840,7 +165694,7 @@ struct simdjson_result<westmere::ondemand::json_iterator> : public westmere::imp simdjson_inline simdjson_result(westmere::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -163003,7 +165857,7 @@ struct simdjson_result<westmere::ondemand::json_type> : public westmere::impleme public: simdjson_inline simdjson_result(westmere::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -163055,7 +165909,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -163171,6 +166025,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -163210,6 +166078,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -163236,7 +166105,7 @@ struct simdjson_result<westmere::ondemand::raw_json_string> : public westmere::i public: simdjson_inline simdjson_result(westmere::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -163698,6 +166567,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -163705,6 +166578,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -163725,7 +166602,7 @@ struct simdjson_result<westmere::ondemand::parser> : public westmere::implementa public: simdjson_inline simdjson_result(westmere::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -163761,7 +166638,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -164008,7 +166885,7 @@ struct simdjson_result<westmere::ondemand::array> : public westmere::implementat public: simdjson_inline simdjson_result(westmere::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<westmere::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<westmere::ondemand::array_iterator> begin() && noexcept; @@ -164089,7 +166966,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -164147,6 +167024,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -164171,7 +167049,7 @@ struct simdjson_result<westmere::ondemand::array_iterator> : public westmere::im simdjson_inline simdjson_result(westmere::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -164221,7 +167099,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -165344,7 +168222,7 @@ struct simdjson_result<westmere::ondemand::document> : public westmere::implemen public: simdjson_inline simdjson_result(westmere::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<westmere::ondemand::array> get_array() & noexcept; @@ -165474,7 +168352,7 @@ template<> struct simdjson_result<westmere::ondemand::document_reference> : public westmere::implementation_simdjson_result_base<westmere::ondemand::document_reference> { public: simdjson_inline simdjson_result(westmere::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<westmere::ondemand::array> get_array() & noexcept; @@ -165621,7 +168499,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -165971,7 +168849,7 @@ struct simdjson_result<westmere::ondemand::document_stream> : public westmere::i public: simdjson_inline simdjson_result(westmere::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -166099,7 +168977,7 @@ struct simdjson_result<westmere::ondemand::field> : public westmere::implementat public: simdjson_inline simdjson_result(westmere::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -167643,7 +170521,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -167665,7 +170543,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -168113,7 +170991,7 @@ struct simdjson_result<westmere::ondemand::object> : public westmere::implementa public: simdjson_inline simdjson_result(westmere::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<westmere::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<westmere::ondemand::object_iterator> begin() && noexcept; @@ -168232,7 +171110,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -168273,6 +171151,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -168290,7 +171169,7 @@ struct simdjson_result<westmere::ondemand::object_iterator> : public westmere::i public: simdjson_inline simdjson_result(westmere::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -168349,7 +171228,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -168393,7 +171272,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -168421,7 +171300,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -168449,7 +171328,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -168711,6 +171590,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -168764,6 +171647,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -168781,7 +171674,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); westmere::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, westmere::ondemand::array>) { arr = val; @@ -168861,35 +171754,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, westmere::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - westmere::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, westmere::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + westmere::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, westmere::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -168906,27 +171786,6 @@ error_code tag_invoke(deserialize_tag, westmere::ondemand::object &obj, T &out) return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, westmere::ondemand::value &val, T &out) noexcept(false) { - westmere::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, westmere::ondemand::document &doc, T &out) noexcept(false) { - westmere::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, westmere::ondemand::document_reference &doc, T &out) noexcept(false) { - westmere::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -168949,7 +171808,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -168972,10 +171831,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -168984,10 +171851,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -169009,6 +171888,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -169777,15 +172658,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -169965,12 +172843,12 @@ namespace westmere { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -169983,7 +172861,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -169996,6 +172875,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -170005,7 +172885,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -170016,6 +172897,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -170043,8 +172925,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -170499,6 +173382,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -170518,6 +173402,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -171313,6 +174202,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -171340,7 +174237,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -171368,6 +174265,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -172698,6 +175601,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -172716,7 +175690,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -172730,7 +175705,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -172947,10 +175923,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -173182,14 +176158,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -173217,7 +176287,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -173227,6 +176297,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -173237,53 +176315,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -173309,6 +176388,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -173329,6 +176422,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -173486,6 +176585,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -174085,7 +177224,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -174243,7 +177382,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -174263,16 +177403,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -174632,7 +177772,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -174645,6 +177786,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -174654,7 +177796,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -174665,6 +177808,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -174679,6 +177823,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -174704,7 +177849,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -174964,25 +178109,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -175029,7 +178186,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -175299,7 +178489,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -175319,7 +178509,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -175351,6 +178541,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -175652,13 +178876,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -175718,10 +178951,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -175771,7 +179018,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -175780,8 +179027,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -175789,14 +179034,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -175804,9 +179042,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -175886,7 +179124,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -175913,8 +179151,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -175923,14 +179159,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -175938,9 +179167,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -175963,8 +179192,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -175973,14 +179200,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -175988,9 +179208,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -176035,6 +179255,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -176125,6 +179353,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -176148,15 +179381,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -176167,8 +179394,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -176317,15 +179543,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -176527,6 +179747,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -176586,6 +179823,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -176649,6 +179893,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -176765,7 +180015,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -178043,7 +181298,7 @@ namespace simd { simdjson_inline simd8(bool _value) : base8<bool>(splat(_value)) {} simdjson_inline int to_bitmask() const { return __lsx_vpickve2gr_w(__lsx_vmskltz_b(*this), 0); } - simdjson_inline bool any() const { return 0 == __lsx_vpickve2gr_hu(__lsx_vmsknz_b(*this), 0); } + simdjson_inline bool any() const { return !__lsx_bz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -178586,7 +181841,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -178594,6 +181857,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -178911,6 +182183,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -179055,7 +182333,7 @@ struct simdjson_result<lsx::ondemand::value_iterator> : public lsx::implementati public: simdjson_inline simdjson_result(lsx::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -179963,7 +183241,7 @@ struct simdjson_result<lsx::ondemand::value> : public lsx::implementation_simdjs public: simdjson_inline simdjson_result(lsx::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<lsx::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<lsx::ondemand::object> get_object() noexcept; @@ -180236,7 +183514,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -180362,7 +183640,7 @@ struct simdjson_result<lsx::ondemand::token_iterator> : public lsx::implementati public: simdjson_inline simdjson_result(lsx::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -180439,7 +183717,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -180448,6 +183726,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -180464,6 +183758,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -180643,6 +183943,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -180715,7 +184021,7 @@ struct simdjson_result<lsx::ondemand::json_iterator> : public lsx::implementatio simdjson_inline simdjson_result(lsx::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -180878,7 +184184,7 @@ struct simdjson_result<lsx::ondemand::json_type> : public lsx::implementation_si public: simdjson_inline simdjson_result(lsx::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -180930,7 +184236,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -181046,6 +184352,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -181085,6 +184405,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -181111,7 +184432,7 @@ struct simdjson_result<lsx::ondemand::raw_json_string> : public lsx::implementat public: simdjson_inline simdjson_result(lsx::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -181573,6 +184894,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -181580,6 +184905,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -181600,7 +184929,7 @@ struct simdjson_result<lsx::ondemand::parser> : public lsx::implementation_simdj public: simdjson_inline simdjson_result(lsx::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -181636,7 +184965,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -181883,7 +185212,7 @@ struct simdjson_result<lsx::ondemand::array> : public lsx::implementation_simdjs public: simdjson_inline simdjson_result(lsx::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<lsx::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<lsx::ondemand::array_iterator> begin() && noexcept; @@ -181964,7 +185293,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -182022,6 +185351,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -182046,7 +185376,7 @@ struct simdjson_result<lsx::ondemand::array_iterator> : public lsx::implementati simdjson_inline simdjson_result(lsx::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -182096,7 +185426,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -183219,7 +186549,7 @@ struct simdjson_result<lsx::ondemand::document> : public lsx::implementation_sim public: simdjson_inline simdjson_result(lsx::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<lsx::ondemand::array> get_array() & noexcept; @@ -183349,7 +186679,7 @@ template<> struct simdjson_result<lsx::ondemand::document_reference> : public lsx::implementation_simdjson_result_base<lsx::ondemand::document_reference> { public: simdjson_inline simdjson_result(lsx::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<lsx::ondemand::array> get_array() & noexcept; @@ -183496,7 +186826,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -183846,7 +187176,7 @@ struct simdjson_result<lsx::ondemand::document_stream> : public lsx::implementat public: simdjson_inline simdjson_result(lsx::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -183974,7 +187304,7 @@ struct simdjson_result<lsx::ondemand::field> : public lsx::implementation_simdjs public: simdjson_inline simdjson_result(lsx::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -185518,7 +188848,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -185540,7 +188870,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -185988,7 +189318,7 @@ struct simdjson_result<lsx::ondemand::object> : public lsx::implementation_simdj public: simdjson_inline simdjson_result(lsx::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<lsx::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<lsx::ondemand::object_iterator> begin() && noexcept; @@ -186107,7 +189437,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -186148,6 +189478,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -186165,7 +189496,7 @@ struct simdjson_result<lsx::ondemand::object_iterator> : public lsx::implementat public: simdjson_inline simdjson_result(lsx::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -186224,7 +189555,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -186268,7 +189599,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -186296,7 +189627,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -186324,7 +189655,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -186586,6 +189917,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -186639,6 +189974,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -186656,7 +190001,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); lsx::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, lsx::ondemand::array>) { arr = val; @@ -186736,35 +190081,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, lsx::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - lsx::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lsx::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + lsx::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, lsx::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -186781,27 +190113,6 @@ error_code tag_invoke(deserialize_tag, lsx::ondemand::object &obj, T &out) noexc return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lsx::ondemand::value &val, T &out) noexcept(false) { - lsx::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lsx::ondemand::document &doc, T &out) noexcept(false) { - lsx::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lsx::ondemand::document_reference &doc, T &out) noexcept(false) { - lsx::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -186824,7 +190135,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -186847,10 +190158,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -186859,10 +190178,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -186884,6 +190215,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -187652,15 +190985,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -187840,12 +191170,12 @@ namespace lsx { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -187858,7 +191188,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -187871,6 +191202,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -187880,7 +191212,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -187891,6 +191224,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -187918,8 +191252,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -188374,6 +191709,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -188393,6 +191729,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -189188,6 +192529,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -189215,7 +192564,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -189243,6 +192592,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -190573,6 +193928,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -190591,7 +194017,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -190605,7 +194032,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -190822,10 +194250,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -191057,14 +194485,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -191092,7 +194614,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -191102,6 +194624,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -191112,53 +194642,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -191184,6 +194715,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -191204,6 +194749,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -191361,6 +194912,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -191960,7 +195551,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -192118,7 +195709,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -192138,16 +195730,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -192507,7 +196099,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -192520,6 +196113,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -192529,7 +196123,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -192540,6 +196135,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -192554,6 +196150,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -192579,7 +196176,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -192839,25 +196436,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -192904,7 +196513,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -193174,7 +196816,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -193194,7 +196836,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -193226,6 +196868,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -193527,13 +197203,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -193593,10 +197278,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -193646,7 +197345,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -193655,8 +197354,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -193664,14 +197361,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -193679,9 +197369,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -193761,7 +197451,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -193788,8 +197478,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -193798,14 +197486,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -193813,9 +197494,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -193838,8 +197519,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -193848,14 +197527,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -193863,9 +197535,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -193910,6 +197582,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -194000,6 +197680,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -194023,15 +197708,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -194042,8 +197721,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -194192,15 +197870,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -194402,6 +198074,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -194461,6 +198150,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -194524,6 +198220,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -194640,7 +198342,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -195709,7 +199416,18 @@ template <typename T> struct simd8x64; /* amalgamation skipped (editor-only): #endif // SIMDJSON_CONDITIONAL_INCLUDE */ #include <lsxintrin.h> +#if defined(__clang__) && !defined(__loongarch_asx) +// LLVM's lasxintrin.h only declares the LASX types and functions when +// __loongarch_asx is defined, that is, when the code is compiled with -mlasx. +// For runtime dispatching, we include it inside a target("lasx") region +// (see simdjson/lasx/begin.h) where the LASX builtins are available, so we +// define __loongarch_asx while including the header. +#define __loongarch_asx 1 #include <lasxintrin.h> +#undef __loongarch_asx +#else +#include <lasxintrin.h> +#endif static_assert(sizeof(__m256i) <= simdjson::SIMDJSON_PADDING, "insufficient padding for LoongArch ASX"); @@ -195928,10 +199646,7 @@ namespace simd { __m256i mask = __lasx_xvmskltz_b(*this); return (__lasx_xvpickve2gr_w(mask, 4) << 16) | (__lasx_xvpickve2gr_w(mask, 0)); } - simdjson_inline bool any() const { - __m256i v = __lasx_xvmsknz_b(*this); - return (0 == __lasx_xvpickve2gr_w(v, 0)) && (0 == __lasx_xvpickve2gr_w(v, 4)); - } + simdjson_inline bool any() const { return !__lasx_xbz_v(this->value); } simdjson_inline simd8<bool> operator~() const { return *this ^ true; } }; @@ -196484,7 +200199,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -196492,6 +200215,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -196809,6 +200541,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -196953,7 +200691,7 @@ struct simdjson_result<lasx::ondemand::value_iterator> : public lasx::implementa public: simdjson_inline simdjson_result(lasx::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -197861,7 +201599,7 @@ struct simdjson_result<lasx::ondemand::value> : public lasx::implementation_simd public: simdjson_inline simdjson_result(lasx::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<lasx::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<lasx::ondemand::object> get_object() noexcept; @@ -198134,7 +201872,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -198260,7 +201998,7 @@ struct simdjson_result<lasx::ondemand::token_iterator> : public lasx::implementa public: simdjson_inline simdjson_result(lasx::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -198337,7 +202075,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -198346,6 +202084,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -198362,6 +202116,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -198541,6 +202301,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -198613,7 +202379,7 @@ struct simdjson_result<lasx::ondemand::json_iterator> : public lasx::implementat simdjson_inline simdjson_result(lasx::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -198776,7 +202542,7 @@ struct simdjson_result<lasx::ondemand::json_type> : public lasx::implementation_ public: simdjson_inline simdjson_result(lasx::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -198828,7 +202594,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -198944,6 +202710,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -198983,6 +202763,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -199009,7 +202790,7 @@ struct simdjson_result<lasx::ondemand::raw_json_string> : public lasx::implement public: simdjson_inline simdjson_result(lasx::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -199471,6 +203252,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -199478,6 +203263,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -199498,7 +203287,7 @@ struct simdjson_result<lasx::ondemand::parser> : public lasx::implementation_sim public: simdjson_inline simdjson_result(lasx::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -199534,7 +203323,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -199781,7 +203570,7 @@ struct simdjson_result<lasx::ondemand::array> : public lasx::implementation_simd public: simdjson_inline simdjson_result(lasx::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<lasx::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<lasx::ondemand::array_iterator> begin() && noexcept; @@ -199862,7 +203651,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -199920,6 +203709,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -199944,7 +203734,7 @@ struct simdjson_result<lasx::ondemand::array_iterator> : public lasx::implementa simdjson_inline simdjson_result(lasx::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -199994,7 +203784,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -201117,7 +204907,7 @@ struct simdjson_result<lasx::ondemand::document> : public lasx::implementation_s public: simdjson_inline simdjson_result(lasx::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<lasx::ondemand::array> get_array() & noexcept; @@ -201247,7 +205037,7 @@ template<> struct simdjson_result<lasx::ondemand::document_reference> : public lasx::implementation_simdjson_result_base<lasx::ondemand::document_reference> { public: simdjson_inline simdjson_result(lasx::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<lasx::ondemand::array> get_array() & noexcept; @@ -201394,7 +205184,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -201744,7 +205534,7 @@ struct simdjson_result<lasx::ondemand::document_stream> : public lasx::implement public: simdjson_inline simdjson_result(lasx::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -201872,7 +205662,7 @@ struct simdjson_result<lasx::ondemand::field> : public lasx::implementation_simd public: simdjson_inline simdjson_result(lasx::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -203416,7 +207206,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -203438,7 +207228,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -203886,7 +207676,7 @@ struct simdjson_result<lasx::ondemand::object> : public lasx::implementation_sim public: simdjson_inline simdjson_result(lasx::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<lasx::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<lasx::ondemand::object_iterator> begin() && noexcept; @@ -204005,7 +207795,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -204046,6 +207836,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -204063,7 +207854,7 @@ struct simdjson_result<lasx::ondemand::object_iterator> : public lasx::implement public: simdjson_inline simdjson_result(lasx::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -204122,7 +207913,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -204166,7 +207957,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -204194,7 +207985,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -204222,7 +208013,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -204484,6 +208275,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -204537,6 +208332,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -204554,7 +208359,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); lasx::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, lasx::ondemand::array>) { arr = val; @@ -204634,35 +208439,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, lasx::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - lasx::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lasx::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + lasx::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, lasx::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -204679,27 +208471,6 @@ error_code tag_invoke(deserialize_tag, lasx::ondemand::object &obj, T &out) noex return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lasx::ondemand::value &val, T &out) noexcept(false) { - lasx::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lasx::ondemand::document &doc, T &out) noexcept(false) { - lasx::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, lasx::ondemand::document_reference &doc, T &out) noexcept(false) { - lasx::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -204722,7 +208493,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -204745,10 +208516,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -204757,10 +208536,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -204782,6 +208573,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -205550,15 +209343,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -205738,12 +209528,12 @@ namespace lasx { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -205756,7 +209546,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -205769,6 +209560,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -205778,7 +209570,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -205789,6 +209582,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -205816,8 +209610,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -206272,6 +210067,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -206291,6 +210087,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -207086,6 +210887,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -207113,7 +210922,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -207141,6 +210950,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -208471,6 +212286,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -208489,7 +212375,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -208503,7 +212390,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -208720,10 +212608,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -208955,14 +212843,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -208990,7 +212972,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -209000,6 +212982,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -209010,53 +213000,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -209082,6 +213073,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -209102,6 +213107,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -209259,6 +213270,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -209858,7 +213909,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -210016,7 +214067,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -210036,16 +214088,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -210405,7 +214457,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -210418,6 +214471,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -210427,7 +214481,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -210438,6 +214493,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -210452,6 +214508,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -210477,7 +214534,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -210737,25 +214794,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -210802,7 +214871,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -211072,7 +215174,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -211092,7 +215194,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -211124,6 +215226,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -211425,13 +215561,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -211491,10 +215636,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -211544,7 +215703,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -211553,8 +215712,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -211562,14 +215719,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -211577,9 +215727,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -211659,7 +215809,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -211686,8 +215836,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -211696,14 +215844,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -211711,9 +215852,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -211736,8 +215877,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -211746,14 +215885,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -211761,9 +215893,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -211808,6 +215940,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -211898,6 +216038,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -211921,15 +216066,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -211940,8 +216079,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -212090,15 +216228,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -212300,6 +216432,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -212359,6 +216508,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -212422,6 +216578,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -212538,7 +216700,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { @@ -213793,7 +217960,9 @@ namespace simd { simdjson_inline simd8<bool> operator|(const simd8<bool> other) const { return __riscv_vmor(*this, other, VL8); } simdjson_inline simd8<bool> operator&(const simd8<bool> other) const { return __riscv_vmand(*this, other, VL8); } simdjson_inline simd8<bool> operator^(const simd8<bool> other) const { return __riscv_vmxor(*this, other, VL8); } - simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(other, *this, VL8); } + simdjson_inline simd8<bool> bit_andnot(const simd8<bool> other) const { return __riscv_vmandn(*this, other, VL8); } + simdjson_inline simd8<bool> operator==(const simd8<bool> other) const { return __riscv_vmxnor(*this, other, VL8); } + simdjson_inline bool any() const { return __riscv_vfirst(value, VL8) >= 0; } simdjson_inline simd8<bool> operator~() const { return __riscv_vmnot(*this, VL8); } simdjson_inline simd8<bool>& operator|=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast | other; return *this_cast; } simdjson_inline simd8<bool>& operator&=(const simd8<bool> other) { auto this_cast = static_cast<simd8<bool>*>(this); *this_cast = *this_cast & other; return *this_cast; } @@ -213845,9 +218014,9 @@ namespace simd { simdjson_inline simd8<uint8_t> operator^(const simd8<uint8_t> other) const { return __riscv_vxor_vv_u8m1( value, other, VL8); } simdjson_inline simd8<uint8_t> operator~() const { return __riscv_vnot_v_u8m1(value, VL8); } #if __riscv_zvbb - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(other, value, VL8); } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return __riscv_vandn_vv_u8m1(value, other, VL8); } #else - simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return other & ~*this; } + simdjson_inline simd8<uint8_t> bit_andnot(const simd8<uint8_t> other) const { return *this & ~other; } #endif simdjson_inline simd8<uint8_t>& operator|=(const simd8<uint8_t> other) { value = *this | other; return *this; } simdjson_inline simd8<uint8_t>& operator&=(const simd8<uint8_t> other) { value = *this & other; return *this; } @@ -213875,6 +218044,8 @@ namespace simd { simdjson_inline simd8<uint8_t>& operator-=(const simd8<uint8_t> other) { value = *this - other; return *this; } // Order-specific operations + simdjson_inline simd8<uint8_t> max_val(const simd8<uint8_t> other) const { return __riscv_vmaxu(value, other, VL8); } + simdjson_inline simd8<uint8_t> min_val(const simd8<uint8_t> other) const { return __riscv_vminu(value, other, VL8); } simdjson_inline simd8<bool> operator<=(const simd8<uint8_t> other) const { return __riscv_vmsleu(value, other, VL8); } simdjson_inline simd8<bool> operator>=(const simd8<uint8_t> other) const { return __riscv_vmsgeu(value, other, VL8); } simdjson_inline simd8<bool> operator<(const simd8<uint8_t> other) const { return __riscv_vmsltu(value, other, VL8); } @@ -213886,10 +218057,17 @@ namespace simd { simdjson_inline simd8<uint8_t> lt_bits(const simd8<uint8_t> other) const { return simd8<uint8_t>(*this < other); } // Bit-specific operations + simdjson_inline simd8<bool> bits_not_set() const { return *this == uint8_t(0); } + simdjson_inline simd8<bool> bits_not_set(simd8<uint8_t> bits) const { return (*this & bits).bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set() const { return ~this->bits_not_set(); } + simdjson_inline simd8<bool> any_bits_set(simd8<uint8_t> bits) const { return ~this->bits_not_set(bits); } + simdjson_inline bool bits_not_set_anywhere() const { return !any_bits_set_anywhere(); } simdjson_inline bool any_bits_set_anywhere() const { return __riscv_vfirst(__riscv_vmsne(value, 0, VL8), VL8) >= 0; } + simdjson_inline bool bits_not_set_anywhere(simd8<uint8_t> bits) const { return !any_bits_set_anywhere(bits); } simdjson_inline bool any_bits_set_anywhere(simd8<uint8_t> bits) const { return (*this & bits).any_bits_set_anywhere(); } + simdjson_inline bool is_ascii() const { return bits_not_set_anywhere(uint8_t(0x80)); } template<int N> simdjson_inline simd8<uint8_t> shr() const { return __riscv_vsrl(value, N, VL8); } template<int N> @@ -214392,7 +218570,15 @@ class value_iterator { token_position _start_position{}; public: - simdjson_inline value_iterator() noexcept = default; + simdjson_inline value_iterator() noexcept {} + simdjson_inline value_iterator(const value_iterator &other) noexcept + : _json_iter{other._json_iter}, _depth{other._depth}, _start_position{other._start_position} {} + simdjson_inline value_iterator &operator=(const value_iterator &other) noexcept { + _json_iter = other._json_iter; + _depth = other._depth; + _start_position = other._start_position; + return *this; + } /** * Skips a non-iterated or partially-iterated JSON value, whether it is a scalar, array or object. @@ -214400,6 +218586,15 @@ class value_iterator { * Optimized for scalars. */ simdjson_warn_unused simdjson_inline error_code skip_child() noexcept; + /** + * Skips the current child, knowing where it starts: if the iterator is still there, the child + * was not read. + */ + simdjson_warn_unused simdjson_inline error_code skip_child(token_position child_start) noexcept; + /** Skips the value of the current field, if it was not read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_child() noexcept; + /** Skips the value of a field whose colon was just read. */ + simdjson_warn_unused simdjson_inline error_code skip_field_value() noexcept; /** * Tell whether the iterator is at the EOF mark @@ -214717,6 +218912,12 @@ class value_iterator { /** @} */ protected: + /** + * Whether actual_key, the key we just read along with its colon, equals key. + * Unlike raw_json_string::unsafe_is_equal, key may hold unescaped quotes. + */ + simdjson_inline bool key_matches(raw_json_string actual_key, std::string_view key) const noexcept; + /** * Restarts an array iteration. * @returns Whether the array has any elements (returns false for empty). @@ -214861,7 +219062,7 @@ struct simdjson_result<rvv_vls::ondemand::value_iterator> : public rvv_vls::impl public: simdjson_inline simdjson_result(rvv_vls::ondemand::value_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -215769,7 +219970,7 @@ struct simdjson_result<rvv_vls::ondemand::value> : public rvv_vls::implementatio public: simdjson_inline simdjson_result(rvv_vls::ondemand::value &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<rvv_vls::ondemand::array> get_array() noexcept; simdjson_inline simdjson_result<rvv_vls::ondemand::object> get_object() noexcept; @@ -216042,7 +220243,7 @@ class token_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline token_iterator() noexcept = default; + simdjson_inline token_iterator() noexcept {} simdjson_inline token_iterator(token_iterator &&other) noexcept = default; simdjson_inline token_iterator &operator=(token_iterator &&other) noexcept = default; simdjson_inline token_iterator(const token_iterator &other) noexcept = default; @@ -216168,7 +220369,7 @@ struct simdjson_result<rvv_vls::ondemand::token_iterator> : public rvv_vls::impl public: simdjson_inline simdjson_result(rvv_vls::ondemand::token_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -216245,7 +220446,7 @@ class json_iterator { #endif public: - simdjson_inline json_iterator() noexcept = default; + simdjson_inline json_iterator() noexcept {} simdjson_inline json_iterator(json_iterator &&other) noexcept; simdjson_inline json_iterator &operator=(json_iterator &&other) noexcept; simdjson_inline explicit json_iterator(const json_iterator &other) noexcept = default; @@ -216254,6 +220455,22 @@ class json_iterator { * Skips a JSON value, whether it is a scalar, array or object. */ simdjson_warn_unused simdjson_inline error_code skip_child(depth_t parent_depth) noexcept; + /** + * Skips the value of a field whose colon was just read. + */ + simdjson_warn_unused simdjson_inline error_code skip_value(depth_t parent_depth) noexcept; + /** + * Skips what is left of a child that was entered or read in part: the iterator is past the + * start of the child. + */ + simdjson_warn_unused simdjson_inline error_code skip_partial(depth_t parent_depth) noexcept; + /** Skips the tokens of a container that was entered until the depth returns to parent_depth. */ + simdjson_warn_unused simdjson_inline error_code skip_rest(depth_t parent_depth) noexcept; + /** Tells whether the token just consumed cannot follow the token before it. */ + simdjson_inline bool out_of_place(uint8_t current) const noexcept; + simdjson_inline error_code out_of_place_error() noexcept; + /** Tells whether the string before pos, followed by a colon, is a key. */ + static bool string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept; /** * Tell whether the iterator is still at the start @@ -216270,6 +220487,12 @@ class json_iterator { #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline bool allow_incomplete_json() const noexcept; simdjson_inline size_t remaining_input_length(const uint8_t *json) const noexcept; + /** + * The last scalar of an incomplete document may be cut by the end of the input, and the number + * and atom parsers would read on into the bytes past it. Returns a copy of such a scalar padded + * with spaces, and json itself for any other scalar. + */ + simdjson_inline const uint8_t *scalar_within_input(const uint8_t *json) noexcept; #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @@ -216449,6 +220672,12 @@ class json_iterator { * overflow. */ simdjson_inline simdjson_result<std::string_view> unescape(raw_json_string in, bool allow_replacement) noexcept; + /** + * Unescape the raw_json_string into receiver. Unlike unescape(), this doesn't leave the string in + * the parser's string buffer. + */ + template <typename string_type> + simdjson_warn_unused simdjson_inline error_code unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept; simdjson_inline simdjson_result<std::string_view> unescape_wobbly(raw_json_string in) noexcept; simdjson_inline void reenter_child(token_position position, depth_t child_depth) noexcept; @@ -216521,7 +220750,7 @@ struct simdjson_result<rvv_vls::ondemand::json_iterator> : public rvv_vls::imple simdjson_inline simdjson_result(rvv_vls::ondemand::json_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -216684,7 +220913,7 @@ struct simdjson_result<rvv_vls::ondemand::json_type> : public rvv_vls::implement public: simdjson_inline simdjson_result(rvv_vls::ondemand::json_type &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private }; @@ -216736,7 +220965,7 @@ class raw_json_string { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline raw_json_string() noexcept = default; + simdjson_inline raw_json_string() noexcept {} /** * Create a new invalid raw_json_string pointed at the given location in the JSON. @@ -216852,6 +221081,20 @@ class raw_json_string { && ends_with_unpaired_backslash(target); } + /** + * True when target is a compile-time constant that holds no quote character. + * Always false with compilers lacking __builtin_constant_p. + */ + static simdjson_inline bool is_known_free_from_quote(std::string_view target) noexcept; + + /** + * Compares the current instance, a key, to the std::string_view target: returns + * true if they are byte-by-byte equal (no escaping is done). Unlike + * unsafe_is_equal, target may hold unescaped quote characters: it then never + * matches. The key must be followed by the colon at `colon`. + */ + simdjson_inline bool unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept; + /** * This will set the inner pointer to zero, effectively making * this instance unusable. @@ -216891,6 +221134,7 @@ class raw_json_string { friend class object; friend class field; friend class parser; + friend class value_iterator; friend struct simdjson_result<raw_json_string>; }; @@ -216917,7 +221161,7 @@ struct simdjson_result<rvv_vls::ondemand::raw_json_string> : public rvv_vls::imp public: simdjson_inline simdjson_result(rvv_vls::ondemand::raw_json_string &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline ~simdjson_result() noexcept = default; ///< @private simdjson_inline simdjson_result<const char *> raw() const noexcept; @@ -217379,6 +221623,10 @@ class parser { static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_parser_instance(); /** Get the thread-local parser instance, it might be null */ static simdjson_inline simdjson_warn_unused std::unique_ptr<ondemand::parser>& get_threadlocal_parser_if_exists(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + static simdjson_inline bool can_end_incomplete_json(uint8_t c) noexcept; + simdjson_warn_unused simdjson_inline error_code end_incomplete_json(padded_string_view json) noexcept; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON /** @private [for benchmarking access] The implementation to use */ std::unique_ptr<simdjson::internal::dom_parser_implementation> implementation{}; size_t _capacity{0}; @@ -217386,6 +221634,10 @@ class parser { size_t _max_depth{DEFAULT_MAX_DEPTH}; size_t _document_len{0}; std::unique_ptr<uint8_t[]> string_buf{}; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + /** Copy of a scalar cut by the end of an incomplete document, see json_iterator::scalar_within_input(). */ + uint8_t incomplete_scalar_buf[1074+8+1+SIMDJSON_PADDING]{}; +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON #if SIMDJSON_DEVELOPMENT_CHECKS std::unique_ptr<token_position[]> start_positions{}; @@ -217406,7 +221658,7 @@ struct simdjson_result<rvv_vls::ondemand::parser> : public rvv_vls::implementati public: simdjson_inline simdjson_result(rvv_vls::ondemand::parser &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -217442,7 +221694,7 @@ class array { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline array() noexcept = default; + simdjson_inline array() noexcept {} /** * Begin array iteration. @@ -217689,7 +221941,7 @@ struct simdjson_result<rvv_vls::ondemand::array> : public rvv_vls::implementatio public: simdjson_inline simdjson_result(rvv_vls::ondemand::array &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<rvv_vls::ondemand::array_iterator> begin() & noexcept; simdjson_inline simdjson_result<rvv_vls::ondemand::array_iterator> begin() && noexcept; @@ -217770,7 +222022,7 @@ class array_iterator { using reference = value_type; /** Create a new, invalid array iterator. */ - simdjson_inline array_iterator() noexcept = default; + simdjson_inline array_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~array_iterator() noexcept; @@ -217828,6 +222080,7 @@ class array_iterator { simdjson_inline array_iterator(const value_iterator &_iter, array* _parent) noexcept; #endif value_iterator iter{}; + token_position element_start{}; simdjson_inline array_iterator(const value_iterator &iter) noexcept; @@ -217852,7 +222105,7 @@ struct simdjson_result<rvv_vls::ondemand::array_iterator> : public rvv_vls::impl simdjson_inline simdjson_result(rvv_vls::ondemand::array_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -217902,7 +222155,7 @@ class document { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline document() noexcept = default; + simdjson_inline document() noexcept {} simdjson_inline document(const document &other) noexcept = delete; // pass your documents by reference, not by copy simdjson_inline document(document &&other) noexcept = default; simdjson_inline document &operator=(const document &other) noexcept = delete; @@ -219025,7 +223278,7 @@ struct simdjson_result<rvv_vls::ondemand::document> : public rvv_vls::implementa public: simdjson_inline simdjson_result(rvv_vls::ondemand::document &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<rvv_vls::ondemand::array> get_array() & noexcept; @@ -219155,7 +223408,7 @@ template<> struct simdjson_result<rvv_vls::ondemand::document_reference> : public rvv_vls::implementation_simdjson_result_base<rvv_vls::ondemand::document_reference> { public: simdjson_inline simdjson_result(rvv_vls::ondemand::document_reference value, error_code error) noexcept; - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline error_code rewind() noexcept; simdjson_inline simdjson_result<rvv_vls::ondemand::array> get_array() & noexcept; @@ -219302,7 +223555,7 @@ namespace ondemand { #ifdef SIMDJSON_THREADS_ENABLED /** @private Custom worker class **/ struct stage1_worker { - stage1_worker() noexcept = default; + stage1_worker() noexcept {} stage1_worker(const stage1_worker&) = delete; stage1_worker(stage1_worker&&) = delete; stage1_worker operator=(const stage1_worker&) = delete; @@ -219652,7 +223905,7 @@ struct simdjson_result<rvv_vls::ondemand::document_stream> : public rvv_vls::imp public: simdjson_inline simdjson_result(rvv_vls::ondemand::document_stream &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} }; } // namespace simdjson @@ -219780,7 +224033,7 @@ struct simdjson_result<rvv_vls::ondemand::field> : public rvv_vls::implementatio public: simdjson_inline simdjson_result(rvv_vls::ondemand::field &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<std::string_view> unescaped_key(bool allow_replacement = false) noexcept; #if SIMDJSON_SUPPORTS_CHAR8_T @@ -221324,7 +225577,7 @@ struct object_position { * Default-constructed so a variable can be declared and assigned later, * matching e.g. document()/object(). Not a valid position to revert to. */ - simdjson_inline object_position() noexcept = default; + simdjson_inline object_position() noexcept {} private: token_position position{}; @@ -221346,7 +225599,7 @@ class object { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object() noexcept = default; + simdjson_inline object() noexcept {} /** * Get an iterator to the start of the object. We recommend using a range-based for loop. @@ -221794,7 +226047,7 @@ struct simdjson_result<rvv_vls::ondemand::object> : public rvv_vls::implementati public: simdjson_inline simdjson_result(rvv_vls::ondemand::object &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} simdjson_inline simdjson_result<rvv_vls::ondemand::object_iterator> begin() & noexcept; simdjson_inline simdjson_result<rvv_vls::ondemand::object_iterator> begin() && noexcept; @@ -221913,7 +226166,7 @@ class object_iterator { * * Exists so you can declare a variable and later assign to it before use. */ - simdjson_inline object_iterator() noexcept = default; + simdjson_inline object_iterator() noexcept {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline ~object_iterator() noexcept; @@ -221954,6 +226207,7 @@ class object_iterator { * is first used, and never changes afterwards. */ value_iterator iter{}; + token_position value_start{}; simdjson_inline object_iterator(const value_iterator &iter) noexcept; friend struct simdjson_result<object_iterator>; @@ -221971,7 +226225,7 @@ struct simdjson_result<rvv_vls::ondemand::object_iterator> : public rvv_vls::imp public: simdjson_inline simdjson_result(rvv_vls::ondemand::object_iterator &&value) noexcept; ///< @private simdjson_inline simdjson_result(error_code error) noexcept; ///< @private - simdjson_inline simdjson_result() noexcept = default; + simdjson_inline simdjson_result() noexcept {} // // Iterator interface @@ -222030,7 +226284,7 @@ class array_range_iterator { using reference = simdjson_result<value>; using difference_type = std::ptrdiff_t; - simdjson_inline array_range_iterator() noexcept = default; + simdjson_inline array_range_iterator() noexcept {} simdjson_inline explicit array_range_iterator(array_iterator iter) noexcept; /** @@ -222074,7 +226328,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class array_range { public: - simdjson_inline array_range() noexcept = default; + simdjson_inline array_range() noexcept {} simdjson_inline explicit array_range(array& arr) noexcept; simdjson_inline array_range_iterator begin() noexcept; @@ -222102,7 +226356,7 @@ class object_range_iterator { using reference = simdjson_result<field>; using difference_type = std::ptrdiff_t; - simdjson_inline object_range_iterator() noexcept = default; + simdjson_inline object_range_iterator() noexcept {} simdjson_inline explicit object_range_iterator(object_iterator iter) noexcept; simdjson_inline simdjson_result<field> operator*() const noexcept; @@ -222130,7 +226384,7 @@ SIMDJSON_POP_DISABLE_WARNINGS */ class object_range { public: - simdjson_inline object_range() noexcept = default; + simdjson_inline object_range() noexcept {} simdjson_inline explicit object_range(object& obj) noexcept; simdjson_inline object_range_iterator begin() noexcept; @@ -222392,6 +226646,10 @@ error_code tag_invoke(deserialize_tag, auto &val, char &out) noexcept { // any string-like type (can be constructed from std::string_view) template <concepts::constructible_from_string_view T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(std::is_nothrow_constructible_v<T, std::string_view>) { + if constexpr (std::is_same_v<T, std::string>) { + // get_string(std::string&) has a faster path for short strings. + return val.get_string(out); + } std::string_view str; SIMDJSON_TRY(val.get_string().get(str)); if constexpr (requires { out.assign(str.data(), str.size()); }) { @@ -222445,6 +226703,16 @@ struct pop_back_guard { if (armed) { container.pop_back(); } } }; + +// Empties the optional on destruction while armed. +template <typename T> +struct reset_guard { + T &optional; + bool armed{true}; + ~reset_guard() { + if (armed) { optional.reset(); } + } +}; } // namespace details /** @@ -222462,7 +226730,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified type inside the container must default constructible."); + "The specified type inside the container must be default constructible."); rvv_vls::ondemand::array arr; if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, rvv_vls::ondemand::array>) { arr = val; @@ -222542,35 +226810,22 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { * We want to support std::map and std::unordered_map but only for * string-keyed types. */ - template <concepts::string_view_keyed_map T, typename ValT> +template <concepts::string_view_keyed_map T, typename ValT> error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { using value_type = typename std::remove_cvref_t<T>::mapped_type; static_assert( - deserializable<value_type, ValT>, - "The specified value type inside the container must itself be deserializable"); + deserializable<value_type, rvv_vls::ondemand::value>, + "The specified value type inside the container must itself be deserializable"); static_assert( std::is_default_constructible_v<value_type>, - "The specified value type inside the container must default constructible."); - rvv_vls::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - for (auto field : obj) { - std::string_view key; - SIMDJSON_TRY(field.unescaped_key().get(key)); - value_type this_value; - SIMDJSON_TRY(field.value().get<value_type>().get(this_value)); - [[maybe_unused]] std::pair<typename T::iterator, bool> result = out.emplace(key, this_value); - // unclear what to do if the key already exists - // if (result.second == false) { - // // key already exists - // } - } - (void)out; - return SUCCESS; -} + "The specified value type inside the container must be default constructible."); -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, rvv_vls::ondemand::object &obj, T &out) noexcept(false) { - using value_type = typename std::remove_cvref_t<T>::mapped_type; + rvv_vls::ondemand::object obj; + if constexpr (std::is_same_v<std::remove_cvref_t<ValT>, rvv_vls::ondemand::object>) { + obj = val; + } else { + SIMDJSON_TRY(val.get_object().get(obj)); + } out.clear(); for (auto field : obj) { @@ -222587,27 +226842,6 @@ error_code tag_invoke(deserialize_tag, rvv_vls::ondemand::object &obj, T &out) n return SUCCESS; } -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, rvv_vls::ondemand::value &val, T &out) noexcept(false) { - rvv_vls::ondemand::object obj; - SIMDJSON_TRY(val.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, rvv_vls::ondemand::document &doc, T &out) noexcept(false) { - rvv_vls::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - -template <concepts::string_view_keyed_map T> -error_code tag_invoke(deserialize_tag, rvv_vls::ondemand::document_reference &doc, T &out) noexcept(false) { - rvv_vls::ondemand::object obj; - SIMDJSON_TRY(doc.get_object().get(obj)); - return simdjson::deserialize(obj, out); -} - /** * This CPO (Customization Point Object) will help deserialize into @@ -222630,7 +226864,7 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { "The specified type inside the unique_ptr must itself be deserializable"); static_assert( std::is_default_constructible_v<element_type>, - "The specified type inside the unique_ptr must default constructible."); + "The specified type inside the unique_ptr must be default constructible."); // A null pointer is serialized as null. bool is_null_value; @@ -222653,10 +226887,18 @@ error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept(false) { /** * This CPO (Customization Point Object) will help deserialize into optional types. */ -template <concepts::optional_type T> -error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, decltype(val)>) { +template <concepts::optional_type T, typename ValT> +error_code tag_invoke(deserialize_tag, ValT &val, T &out) noexcept( + nothrow_deserializable<typename std::remove_cvref_t<T>::value_type, std::remove_cvref_t<ValT>>) { using value_type = typename std::remove_cvref_t<T>::value_type; + static_assert( + deserializable<value_type, ValT>, + "The specified type inside the optional must itself be deserializable"); + static_assert( + std::is_default_constructible_v<value_type>, + "The specified type inside the optional must be default constructible."); + // Check if the value is null bool is_null_value; SIMDJSON_TRY( val.is_null().get(is_null_value) ); @@ -222665,10 +226907,22 @@ error_code tag_invoke(deserialize_tag, auto &val, T &out) noexcept(nothrow_deser return SUCCESS; } + // On an error or an exception (a user tag_invoke may throw), out is left as + // it was: empty, or holding its previous value. if (!out) { + // Deserialize in place (no temporary to move, which matters for large + // types), and empty out again if that fails. out.emplace(); + details::reset_guard<std::remove_cvref_t<T>> guard{out}; + SIMDJSON_TRY(val.template get<value_type>(*out)); + guard.armed = false; + } else { + // out holds a value: deserialize into a fresh value and replace it on + // success. (A container is thus replaced rather than appended to.) + value_type temp; + SIMDJSON_TRY(val.template get<value_type>(temp)); + out.emplace(std::move(temp)); } - SIMDJSON_TRY(val.template get<value_type>(out.value())); return SUCCESS; } @@ -222690,6 +226944,8 @@ constexpr bool user_defined_type = (std::is_class_v<T> !concepts::appendable_containers<T> // Smart pointers are handled by the generic smart-pointer tag_invoke. && !concepts::smart_pointer<T> +// String-keyed maps are handled by the generic string_view_keyed_map tag_invoke. +&& !concepts::string_view_keyed_map<T> // simdjson's own types (array, object, value, raw_json_string, number, // document, document_reference) have dedicated get<T>() specializations and // must never go through reflection. @@ -223458,15 +227714,12 @@ inline simdjson_result<value> array::at_pointer(std::string_view json_pointer) n size_t i; SIMDJSON_TRY(internal::parse_json_pointer_array_index(json_pointer, array_index, i)); // Get the child - auto child = at(array_index); + value child; // If there is an error, it ends here - if(child.error()) { - return child; - } - + SIMDJSON_TRY(at(array_index).get(child)); // If there is a /, we're not done yet, call recursively. if (i < json_pointer.length()) { - child = child.at_pointer(json_pointer.substr(i)); + return child.at_pointer(json_pointer.substr(i)); } return child; } @@ -223646,12 +227899,12 @@ namespace rvv_vls { namespace ondemand { simdjson_inline array_iterator::array_iterator(const value_iterator &_iter) noexcept - : iter{_iter} + : iter{_iter}, element_start{_iter.json_iter().position()} {} #if SIMDJSON_DEVELOPMENT_CHECKS simdjson_inline array_iterator::array_iterator(const value_iterator &_iter, array* _parent) noexcept - : parent{_parent}, iter{_iter} + : parent{_parent}, iter{_iter}, element_start{_iter.json_iter().position()} { if (parent) parent->set_locked(true); } @@ -223664,7 +227917,8 @@ simdjson_inline array_iterator::~array_iterator() noexcept simdjson_inline array_iterator::array_iterator(array_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + element_start{other.element_start} { other.parent = nullptr; } @@ -223677,6 +227931,7 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + element_start = other.element_start; other.parent = nullptr; } @@ -223686,7 +227941,8 @@ simdjson_inline array_iterator& array_iterator::operator=(array_iterator&& other simdjson_inline array_iterator::array_iterator(const array_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + element_start{other.element_start} {} simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& other) noexcept { @@ -223697,6 +227953,7 @@ simdjson_inline array_iterator& array_iterator::operator=(const array_iterator& has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + element_start = other.element_start; } return *this; } @@ -223724,8 +227981,9 @@ simdjson_inline array_iterator &array_iterator::operator++() noexcept { // PERF NOTE this is a safety rail ... users should exit loops as soon as they receive an error, so we'll never get here. // However, it does not seem to make a perf difference, so we add it out of an abundance of caution. if (( error = iter.error() )) { return *this; } - if (( error = iter.skip_child() )) { return *this; } + if (( error = iter.skip_child(element_start) )) { return *this; } if (( error = iter.has_next_element().error() )) { return *this; } + element_start = iter.json_iter().position(); return *this; } @@ -224180,6 +228438,7 @@ simdjson_inline simdjson_result<value> value::at_pointer(std::string_view json_p } simdjson_inline simdjson_result<value> value::at_path(std::string_view json_path) noexcept { + if (json_path == "$") { return value(iter); } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -224199,6 +228458,11 @@ template <typename Func> template <typename Func> #endif inline error_code value::for_each_at_path_with_wildcard(std::string_view json_path, Func&& callback) noexcept { + if (json_path == "$") { + value self(iter); + callback(self); + return SUCCESS; + } // The path is split once: every value reached by a wildcard sees the same // remaining path, so re-parsing it at each one would be quadratic. const std::vector<internal::json_path_segment> path = internal::split_json_path(json_path); @@ -224994,6 +229258,14 @@ simdjson_inline simdjson_result<number> document::get_number() noexcept { simdjson_inline simdjson_result<std::string_view> document::raw_json_token() noexcept { auto _iter = get_root_value_iterator(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (iter.allow_incomplete_json()) { + const uint32_t length = _iter.peek_root_length(); + const size_t remaining_input_length = iter.remaining_input_length(_iter.peek_start()); + return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), + remaining_input_length < length ? uint32_t(remaining_input_length) : length); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return std::string_view(reinterpret_cast<const char*>(_iter.peek_start()), _iter.peek_root_length()); } @@ -225021,7 +229293,7 @@ simdjson_inline simdjson_result<value> document::at_path(std::string_view json_p // Rewind the document each time at_path is called. After a fatal error, // the document cannot be walked again: we report the error instead. SIMDJSON_TRY(iter.rewind()); - if (json_path.empty()) { + if (json_path.empty() || json_path == "$") { return this->get_value(); } json_type t; @@ -225049,6 +229321,12 @@ simdjson_inline error_code document::for_each_at_path_with_wildcard(std::string_ if (json_path.empty()) { return INVALID_JSON_POINTER; } + if (json_path == "$") { + value root; + SIMDJSON_TRY(get_value().get(root)); + callback(root); + return SUCCESS; + } json_type t; SIMDJSON_TRY(type().get(t)); switch (t) { @@ -226379,6 +230657,77 @@ inline size_t document_stream::next_batch_start() const noexcept { return batch_start + parser->implementation->structural_indexes[parser->implementation->n_structural_indexes]; } +// Whether the documents in [pos, end) are well formed. Balanced brackets are not +// enough: On-Demand may skip the ] in `[1,]` as a value. +inline bool stream_documents_are_well_formed(const uint8_t *batch, const uint32_t *pos, const uint32_t *end) noexcept { + uint64_t is_object[16]{}; // one bit per open container, up to depth 1024 + size_t depth = 0; + enum { value, first_value, key, first_key, colon, comma_or_close } expected = value; + for (; pos < end; pos++) { + const uint8_t c = batch[*pos]; + if (expected == comma_or_close && depth == 0) { expected = value; } // next document + const bool in_object = depth > 0 && ((is_object[(depth - 1) / 64] >> ((depth - 1) % 64)) & 1); + switch (expected) { + case value: case first_value: + if (c == ']' && expected == first_value) { depth--; expected = comma_or_close; break; } + if (c == ',' || c == ':' || c == ']' || c == '}') { return false; } + expected = comma_or_close; + if (c == '[' || c == '{') { + if (depth == 1024) { return false; } + const uint64_t bit = uint64_t(1) << (depth % 64); + is_object[depth / 64] = (c == '{') ? (is_object[depth / 64] | bit) : (is_object[depth / 64] & ~bit); + depth++; + expected = (c == '{') ? first_key : first_value; + } + break; + case key: case first_key: + if (c == '}' && expected == first_key) { depth--; expected = comma_or_close; break; } + if (c != '"') { return false; } + expected = colon; + break; + case colon: + if (c != ':') { return false; } + expected = value; + break; + case comma_or_close: + if (c == ',') { expected = in_object ? key : value; break; } + if (c != (in_object ? '}' : ']')) { return false; } + depth--; + break; + } + } + return depth == 0 && expected == comma_or_close; +} + +// If the byte past the batch could continue its last document, end the batch +// before an invalid tail, so that On-Demand cannot read past it. Once per batch. +simdjson_never_inline error_code end_batch_before_invalid_tail(internal::dom_parser_implementation &impl, const uint8_t *batch) noexcept { + const uint32_t n = impl.n_structural_indexes; + if (n == 0) { return SUCCESS; } + const uint32_t *const first = impl.structural_indexes.get(); + const uint32_t *const end = first + n; + const uint8_t next = batch[*end]; + const uint8_t last = batch[*(end - 1)]; + if (!(next == ',' || next == ':' || next == ']' || next == '}' || + last == ',' || last == ':' || last == '[' || last == '{')) { + return SUCCESS; + } + const uint32_t *start = end - 1; + for (; start > first; start--) { + const uint8_t c = batch[*start]; + const uint8_t previous = batch[*(start - 1)]; + if (c != ',' && c != ':' && c != ']' && c != '}' && + previous != '[' && previous != '{' && previous != ',' && previous != ':') { + break; + } + } + if (stream_documents_are_well_formed(batch, start, end)) { return SUCCESS; } + if (start == first) { return TAPE_ERROR; } + impl.n_structural_indexes = uint32_t(start - first); + impl.structural_indexes[impl.n_structural_indexes + 1] = *start; // for truncated_bytes() + return SUCCESS; +} + inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch_start) noexcept { // This code only updates the structural index in the parser, it does not update any json_iterator // instance. @@ -226397,7 +230746,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_final; break; } - return p.implementation->stage1(&buf[_batch_start], remaining, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], remaining, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } else { // Partial batch switch (format) { @@ -226411,7 +230761,8 @@ inline error_code document_stream::run_stage1(ondemand::parser &p, size_t _batch mode = stage1_mode::streaming_partial; break; } - return p.implementation->stage1(&buf[_batch_start], batch_size, mode); + error_code err = p.implementation->stage1(&buf[_batch_start], batch_size, mode); + return err ? err : end_batch_before_invalid_tail(*p.implementation, &buf[_batch_start]); } } @@ -226628,10 +230979,10 @@ simdjson_inline simdjson_warn_unused simdjson_result<std::u8string_view> field:: template <typename string_type> simdjson_inline simdjson_warn_unused error_code field::unescaped_key(string_type& receiver, bool allow_replacement) noexcept { - std::string_view key; - SIMDJSON_TRY( unescaped_key(allow_replacement).get(key) ); - internal::assign_utf8(receiver, key); - return SUCCESS; + SIMDJSON_ASSUME(first.buf != nullptr); // We would like to call .alive() but Visual Studio won't let us. + error_code key_error = second.iter.json_iter().unescape(first, receiver, allow_replacement); + first.consume(); + return key_error; } simdjson_inline raw_json_string field::key() const noexcept { @@ -226863,14 +231214,108 @@ static constexpr int8_t skip_depth_delta[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; +// Class of the first token of a value: 0 for a scalar, 1 for an array or an object, 2 for a +// token that cannot start a value. +static constexpr uint8_t value_start_class[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,2,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, +}; + +simdjson_inline bool json_iterator::out_of_place(uint8_t current) const noexcept { + // A value or a key follows a colon, a comma or an opening bracket; nothing else does. + if (_depth <= 1) { return false; } + const uint8_t before = *peek(-2) | 0x20; + const bool after_start = before == ':' || before == ',' || before == '{'; + current |= 0x20; + const bool ends = current == ':' || current == ',' || current == '}'; + return after_start == ends; +} + +simdjson_inline error_code json_iterator::out_of_place_error() noexcept { + return report_error(TAPE_ERROR, "Missing comma, colon or value"); +} + +simdjson_never_inline bool json_iterator::string_is_key(const uint8_t *json, token_position pos, token_position root, token_position end) noexcept { + // The string before pos is followed by a colon. After a colon or a bracket, it is a value; + // after a comma, it is a key if its container is an object. + const uint8_t before = pos - 2 >= root ? json[pos[-2]] : ':'; + if (before == '{') { return true; } + if (before == ':' || before == '[') { return false; } + int32_t depth = 0; + while (pos < end) { + const uint8_t c = json[*pos++]; + depth += skip_depth_delta[c]; + if (depth < 0) { return c == '}'; } + } + return true; +} + // GCC 7 warns when the first line of this function is inlined away into oblivion due to the caller // relating depth and parent_depth, which is a desired effect. The warning does not show up if the // skip_child() function is not marked inline). SIMDJSON_PUSH_DISABLE_WARNINGS SIMDJSON_DISABLE_STRICT_OVERFLOW_WARNING +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_rest(depth_t parent_depth) noexcept { + // Now that we've considered the first value, we only increment/decrement for arrays/objects. + // + // Without logging, look up the depth change of each token in a table instead of branching + // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps + // the position and depth in locals, because the byte loads are char loads that may alias + // token._position and _depth, which would force a store of both on every token. + if (!logger::LOG_ENABLED) { + token_position pos = token.position(); + const token_position end = end_position(); + const uint8_t *const json = token.buf; + depth_t depth = _depth; + while (pos < end) { + depth += skip_depth_delta[json[*pos++]]; + if (depth <= parent_depth) { + token.set_position(pos); + _depth = depth; + return SUCCESS; + } + } + token.set_position(pos); + _depth = depth; + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); + } + + while (position() < end_position()) { + switch (*return_current_and_advance()) { + case '[': case '{': + logger::log_start_value(*this, "skip"); + _depth++; + break; + // TODO consider whether matching braces is a requirement: if non-matching braces indicates + // *missing* braces, then future lookups are not in the object/arrays they think they are, + // violating the rule "validate enough structure that the user can be confident they are + // looking at the right values." + // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + if (depth() <= parent_depth) { return SUCCESS; } + break; + default: + logger::log_value(*this, "skip", ""); + break; + } + } + + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +} + simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_t parent_depth) noexcept { if (depth() <= parent_depth) { return SUCCESS; } - switch (*return_current_and_advance()) { + const uint8_t current = *return_current_and_advance(); + if (simdjson_unlikely(out_of_place(current))) { return out_of_place_error(); } + switch (current) { // TODO consider whether matching braces is a requirement: if non-matching braces indicates // *missing* braces, then future lookups are not in the object/arrays they think they are, // violating the rule "validate enough structure that the user can be confident they are @@ -226898,7 +231343,7 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; case '"': // At the end, peek() would read the sentinel, which points into the padding. - if(!at_end() && *peek() == ':') { + if(!at_end() && *peek() == ':' && string_is_key(token.buf, token.position(), _root, end_position())) { // We are at a key!!! // This might happen if you just started an object and you skip it immediately. // Performance note: it would be nice to get rid of this check as it is somewhat @@ -226908,6 +231353,14 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ return_current_and_advance(); // eat up the ':' break; // important!!! } + if (_depth > 1 && *peek(-2) == '{') { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } simdjson_fallthrough; // Anything else must be a scalar value default: @@ -226918,53 +231371,54 @@ simdjson_warn_unused simdjson_inline error_code json_iterator::skip_child(depth_ break; } - // Now that we've considered the first value, we only increment/decrement for arrays/objects. - // - // Without logging, look up the depth change of each token in a table instead of branching - // on it: the next byte is hard to predict, so a switch mispredicts often. The loop also keeps - // the position and depth in locals, because the byte loads are char loads that may alias - // token._position and _depth, which would force a store of both on every token. - if (!logger::LOG_ENABLED) { - token_position pos = token.position(); - const token_position end = end_position(); - const uint8_t *const json = token.buf; - depth_t depth = _depth; - while (pos < end) { - depth += skip_depth_delta[json[*pos++]]; - if (depth <= parent_depth) { - token.set_position(pos); - _depth = depth; - return SUCCESS; - } - } - token.set_position(pos); - _depth = depth; - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); - } + return skip_rest(parent_depth); +} - while (position() < end_position()) { - switch (*return_current_and_advance()) { - case '[': case '{': - logger::log_start_value(*this, "skip"); - _depth++; - break; - // TODO consider whether matching braces is a requirement: if non-matching braces indicates - // *missing* braces, then future lookups are not in the object/arrays they think they are, - // violating the rule "validate enough structure that the user can be confident they are - // looking at the right values." - // PERF TODO we can eliminate the switch here with a lookup of how much to add to depth - case ']': case '}': - logger::log_end_value(*this, "skip"); - _depth--; - if (depth() <= parent_depth) { return SUCCESS; } - break; - default: - logger::log_value(*this, "skip", ""); - break; - } +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_value(depth_t parent_depth) noexcept { + const uint8_t value_class = value_start_class[*return_current_and_advance()]; + if (value_class == 0) { + logger::log_value(*this, "skip"); + _depth--; + return SUCCESS; } + if (value_class == 2) { return out_of_place_error(); } + logger::log_start_value(*this, "skip"); + return skip_rest(parent_depth); +} - return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "not enough close braces"); +simdjson_warn_unused simdjson_inline error_code json_iterator::skip_partial(depth_t parent_depth) noexcept { + if (depth() <= parent_depth) { return SUCCESS; } + if (depth() != parent_depth + 1) { return skip_child(parent_depth); } + // We are in the child container, past its start: at a key, a colon, a comma or the closing + // bracket. Another value can only follow a missing comma. + switch (*return_current_and_advance()) { + case ',': case ':': + logger::log_value(*this, "skip"); + return skip_rest(parent_depth); + case ']': case '}': + logger::log_end_value(*this, "skip"); + _depth--; + return SUCCESS; + case '"': + if (!at_end() && *peek() == ':') { + logger::log_value(*this, "key"); + return_current_and_advance(); + return skip_rest(parent_depth); + } +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json() && at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object key cut before its colon"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + simdjson_fallthrough; + default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (simdjson_unlikely(allow_incomplete_json() && position() > end_position())) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Value cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + return out_of_place_error(); + } } SIMDJSON_POP_DISABLE_WARNINGS @@ -226990,6 +231444,20 @@ simdjson_inline size_t json_iterator::remaining_input_length(const uint8_t *json const uint8_t *end = token.buf + parser->_document_len; return json < end ? size_t(end - json) : 0; } + +simdjson_inline const uint8_t *json_iterator::scalar_within_input(const uint8_t *json) noexcept { + // Only the last token can run to the end of the input. + const uint32_t n = parser->implementation->n_structural_indexes; + if (simdjson_likely(json != token.buf + parser->implementation->structural_indexes[n - 1])) { return json; } + uint8_t *tmpbuf = parser->incomplete_scalar_buf; + constexpr size_t capacity = sizeof(parser->incomplete_scalar_buf) - SIMDJSON_PADDING; + const size_t length = remaining_input_length(json); + // A scalar too long for the buffer is left out entirely, so that it does not parse. + const size_t copied = length <= capacity ? length : 0; + std::memcpy(tmpbuf, json, copied); + std::memset(tmpbuf + copied, ' ', sizeof(parser->incomplete_scalar_buf) - copied); + return tmpbuf; +} #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON simdjson_inline token_position json_iterator::root_position() const noexcept { @@ -227010,6 +231478,12 @@ simdjson_inline void json_iterator::assert_at_root() const noexcept { } simdjson_inline void json_iterator::assert_more_tokens(uint32_t required_tokens) const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (allow_incomplete_json()) { + SIMDJSON_ASSUME( token._position + required_tokens - 1 <= end_position() ); + return; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON assert_valid_position(token._position + required_tokens - 1); } @@ -227167,6 +231641,46 @@ simdjson_inline simdjson_result<std::string_view> json_iterator::unescape(raw_js #endif } +template <typename string_type> +simdjson_warn_unused simdjson_inline error_code json_iterator::unescape(raw_json_string in, string_type& receiver, bool allow_replacement) noexcept { +// The inline capacity of std::string must be known at compile time, hence constexpr std::string. +#if SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + if constexpr (std::is_same_v<string_type, std::string>) { + // Short strings without escapes go into the string's inline (SSO) buffer with two overlapping + // copies of fixed size. A memcpy of the exact length is much slower here, because its branches + // on the length mispredict. Like parse_string, this reads past the closing quote into the padding. + constexpr size_t sso_capacity = std::string().capacity(); // 22 with libc++, 15 with libstdc++ and MSVC + constexpr size_t chunk = sso_capacity >= 16 ? 16 : 8; + if constexpr (sso_capacity >= chunk && sso_capacity <= 2 * chunk) { + const uint8_t *const start = reinterpret_cast<const uint8_t *>(in.raw()); + uint8_t scratch[backslash_and_quote::BYTES_PROCESSED]; + for (size_t offset = 0; offset <= sso_capacity; offset += backslash_and_quote::BYTES_PROCESSED) { + auto bs_quote = backslash_and_quote{}.copy_and_find(start + offset, scratch); + if (bs_quote.has_quote_first()) { + const size_t length = offset + size_t(bs_quote.quote_index()); + if (length > sso_capacity) { break; } + receiver.resize_and_overwrite(sso_capacity, [&](char *dst, size_t) noexcept { + std::memcpy(dst, start, chunk); + std::memcpy(dst + sso_capacity - chunk, start + sso_capacity - chunk, chunk); + return length; + }); + return SUCCESS; + } + if (bs_quote.has_backslash()) { break; } + } + } + } +#endif // SIMDJSON_SUPPORTS_RESIZE_AND_OVERWRITE && SIMDJSON_SUPPORTS_CONSTEXPR_STRING + + // Anything else: unescape into the string buffer, copy it out, then give the buffer space back. + auto saved_string_buf_loc = _string_buf_loc; + std::string_view content; + SIMDJSON_TRY( unescape(in, allow_replacement).get(content) ); + internal::assign_utf8(receiver, content); + _string_buf_loc = saved_string_buf_loc; + return SUCCESS; +} + simdjson_inline simdjson_result<std::string_view> json_iterator::unescape_wobbly(raw_json_string in) noexcept { #if SIMDJSON_DEVELOPMENT_CHECKS auto result = parser->unescape_wobbly(in, _string_buf_loc); @@ -227766,7 +232280,7 @@ simdjson_flatten simdjson_inline for_each_result object::for_each(Func&& on_matc if (!it.is_open()) { break; } // Skip the value (a no-op if the callback consumed it) and step to the next // field; has_next_field() ends the container on '}', which closes the loop. - if ((error = it.skip_child())) { it.abandon(); return {error, matched}; } + if ((error = it.skip_field_child())) { it.abandon(); return {error, matched}; } if ((error = it.has_next_field().error())) { return {error, matched}; } } return {SUCCESS, matched}; @@ -227924,7 +232438,8 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) size_t slash = json_pointer.find('/'); std::string_view key = json_pointer.substr(0, slash); // Grab the child with the given key - simdjson_result<value> child; + value child; + error_code error; // If there is an escape character in the key, unescape it and then get the child. size_t escape = key.find('~'); @@ -227944,16 +232459,16 @@ inline simdjson_result<value> object::at_pointer(std::string_view json_pointer) } escape = unescaped.find('~', escape+1); } while (escape != std::string::npos); - child = find_field(unescaped); // Take note find_field does not unescape keys when matching + error = find_field(unescaped).get(child); // Take note find_field does not unescape keys when matching } else { - child = find_field(key); + error = find_field(key).get(child); } - if(child.error()) { - return child; // we do not continue if there was an error + if(error) { + return error; // we do not continue if there was an error } // If there is a /, we have to recurse and look up more of the path if (slash != std::string_view::npos) { - child = child.at_pointer(json_pointer.substr(slash)); + return child.at_pointer(json_pointer.substr(slash)); } return child; } @@ -228313,7 +232828,8 @@ simdjson_inline object_iterator::~object_iterator() noexcept simdjson_inline object_iterator::object_iterator(object_iterator&& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{other.parent}, - iter{std::move(other.iter)} + iter{std::move(other.iter)}, + value_start{other.value_start} { other.parent = nullptr; } @@ -228326,6 +232842,7 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot has_been_referenced = other.has_been_referenced; parent = other.parent; iter = std::move(other.iter); + value_start = other.value_start; other.parent = nullptr; } @@ -228335,7 +232852,8 @@ simdjson_inline object_iterator& object_iterator::operator=(object_iterator&& ot simdjson_inline object_iterator::object_iterator(const object_iterator& other) noexcept : has_been_referenced{other.has_been_referenced}, parent{nullptr}, - iter{other.iter} + iter{other.iter}, + value_start{other.value_start} {} simdjson_inline object_iterator& object_iterator::operator=(const object_iterator& other) noexcept { @@ -228346,6 +232864,7 @@ simdjson_inline object_iterator& object_iterator::operator=(const object_iterato has_been_referenced = other.has_been_referenced; parent = nullptr; iter = other.iter; + value_start = other.value_start; } return *this; } @@ -228360,6 +232879,7 @@ simdjson_inline simdjson_result<field> object_iterator::operator*() noexcept { error_code error = iter.error(); if (error) { iter.abandon(); return error; } auto result = field::start(iter); + value_start = iter.json_iter().position(); // TODO this is a safety rail ... users should exit loops as soon as they receive an error. // Nonetheless, let's see if performance is OK with this if statement--the compiler may give it to us for free. if (result.error()) { iter.abandon(); } @@ -228385,7 +232905,7 @@ simdjson_inline object_iterator &object_iterator::operator++() noexcept { if (!iter.is_open()) { return *this; } // Iterator will be released if there is an error simdjson_unused error_code error; - if ((error = iter.skip_child() )) { return *this; } + if ((error = iter.skip_child(value_start) )) { return *this; } simdjson_unused bool has_value; if ((error = iter.has_next_field().get(has_value) )) { return *this; }; @@ -228645,25 +233165,37 @@ simdjson_inline parser::parser(size_t max_capacity) noexcept } simdjson_warn_unused simdjson_inline error_code parser::allocate(size_t new_capacity, size_t new_max_depth) noexcept { + // Reject an invalid depth before touching anything, as the implementation + // would: a failed allocate() leaves the parser as it was. + if (new_max_depth == 0 || new_max_depth > SIMDJSON_MAX_DEPTH) { return CAPACITY; } if (new_capacity > max_capacity()) { return CAPACITY; } if (string_buf && new_capacity <= capacity() && new_max_depth <= max_depth()) { return SUCCESS; } // string_capacity copied from document::allocate - _capacity = 0; - if(5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { + if (5 * (new_capacity / 3) + SIMDJSON_PADDING < SIMDJSON_PADDING) { return CAPACITY; // overflow, only happen on legacy 32-bit systems with very large capacity } size_t string_capacity = SIMDJSON_ROUNDUP_N(5 * (new_capacity / 3) + SIMDJSON_PADDING, 64); - string_buf.reset(new (std::nothrow) uint8_t[string_capacity]); + std::unique_ptr<uint8_t[]> new_string_buf(new (std::nothrow) uint8_t[string_capacity]); + if (!new_string_buf) { return MEMALLOC; } #if SIMDJSON_DEVELOPMENT_CHECKS - start_positions.reset(new (std::nothrow) token_position[new_max_depth]); + std::unique_ptr<token_position[]> new_start_positions(new (std::nothrow) token_position[new_max_depth]); + if (!new_start_positions) { return MEMALLOC; } #endif if (implementation) { - SIMDJSON_TRY( implementation->set_capacity(new_capacity) ); - SIMDJSON_TRY( implementation->set_max_depth(new_max_depth) ); + error_code err = implementation->allocate(new_capacity, new_max_depth); + if (err) { return err; } } else { - SIMDJSON_TRY( simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation) ); + error_code err = simdjson::get_active_implementation()->create_dom_parser_implementation(new_capacity, new_max_depth, implementation); + if (err) { + implementation.reset(); + return err; + } } + string_buf = std::move(new_string_buf); +#if SIMDJSON_DEVELOPMENT_CHECKS + start_positions = std::move(new_start_positions); +#endif _capacity = new_capacity; _max_depth = new_max_depth; return SUCCESS; @@ -228710,7 +233242,40 @@ simdjson_warn_unused simdjson_inline simdjson_result<document> parser::iterate_a if (err != UNCLOSED_STRING) return err; } - return document::start({ reinterpret_cast<const uint8_t *>(json.data()), this, true }); + SIMDJSON_TRY( end_incomplete_json(json) ); + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const uint8_t first = buf[implementation->structural_indexes[0]]; + const bool lone_container = implementation->n_structural_indexes == 1 && (first == '{' || first == '['); + return document::start({ buf, this, !lone_container }); +} + +simdjson_inline bool parser::can_end_incomplete_json(uint8_t c) noexcept { + return c != '"' && c != ',' && c != ']' && c != '}'; +} + +simdjson_warn_unused simdjson_inline error_code parser::end_incomplete_json(padded_string_view json) noexcept { + const uint8_t *buf = reinterpret_cast<const uint8_t *>(json.data()); + const size_t len = json.length(); + uint32_t *indexes = implementation->structural_indexes.get(); + uint32_t n = implementation->n_structural_indexes; + while (n > 1) { + const uint8_t last = buf[indexes[n - 1]]; + if (last != ',' && last != ':' && last != '[' && last != '{') { break; } + n--; + } + implementation->n_structural_indexes = n; + indexes[n] = uint32_t(len); + indexes[n + 1] = uint32_t(len); + indexes[n + 2] = 0; + const uint8_t first = buf[indexes[0]]; + if (n == 1 && first != '{' && first != '[') { return SUCCESS; } + if (simdjson_likely(can_end_incomplete_json(buf[len]))) { return SUCCESS; } + size_t end = len + 1; + while (end < len + SIMDJSON_PADDING && !can_end_incomplete_json(buf[end])) { end++; } + if (end == len + SIMDJSON_PADDING) { return INSUFFICIENT_PADDING; } + indexes[n] = uint32_t(end); + indexes[n + 1] = uint32_t(end); + return SUCCESS; } #endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON @@ -228980,7 +233545,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(std::string_v while(pos < target.size()) { pos = target.find('"', pos); if(pos == std::string_view::npos) { return true; } - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -229000,7 +233565,7 @@ simdjson_inline bool raw_json_string::is_free_from_unescaped_quote(const char* t const char * result = strchr(target+pos, '"'); if(result == nullptr) { return true; } pos = result - target; - if(pos != 0 && target[pos-1] != '\\') { return false; } + if(pos == 0 || target[pos-1] != '\\') { return false; } if(pos > 1 && target[pos-2] == '\\') { size_t backslash_count{2}; for(size_t i = 3; i <= pos; i++) { @@ -229032,6 +233597,40 @@ simdjson_inline bool raw_json_string::unsafe_is_equal(std::string_view target) c return is_equal(target); } +simdjson_inline bool raw_json_string::is_known_free_from_quote(std::string_view target) noexcept { +#if defined(__GNUC__) || defined(__clang__) + // Copy the size first: GCC folds __builtin_constant_p of an expression + // holding a function call to false before inlining. When target is a + // compile-time constant, the size is a constant and the scan below folds + // away. Otherwise we return false, and the scan is never emitted. + const size_t size{target.size()}; + if(!__builtin_constant_p(size)) { return false; } + bool has_quote{false}; + for(char c : target) { has_quote |= (c == '"'); } + return !has_quote; +#else + (void)target; + return false; +#endif +} + +simdjson_inline bool raw_json_string::unsafe_is_equal_key(std::string_view target, const uint8_t *colon) const noexcept { + // Past SIMDJSON_PADDING, is_equal stops at the quote terminating the key. + if(target.size() > SIMDJSON_PADDING) { return is_equal(target); } + const char * quote{raw() + target.size()}; + if((*quote != '"') || memcmp(raw(), target.data(), target.size())) { return false; } + // The bytes of target are followed by a quote. Only whitespace separates the + // quote closing the key from the colon: a quote right before the colon + // therefore closes the key, and target is the key. + const char * c{reinterpret_cast<const char *>(colon)}; + if(simdjson_likely(quote + 1 == c)) { return true; } + // Otherwise there is whitespace before the colon, or the quote is escaped + // (target ends with an unpaired backslash), or target holds an unescaped + // quote: its bytes then run past the quote closing the key, and so past + // the colon, which can only be followed by whitespace before a quote. + return (quote < c) && !escapes_trailing_quote(target); +} + simdjson_inline bool raw_json_string::is_equal(std::string_view target) const noexcept { const char * r{raw()}; size_t pos{0}; @@ -229333,13 +233932,22 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::start if (size_t(_depth) >= _json_iter->parser->max_depth()) { return report_error(DEPTH_ERROR, "Exceeded max depth!"); } _json_iter->set_start_position(_depth, start_position()); #endif - if (*_json_iter->peek() == '}') { + // skip_child() relies on a started object beginning with a key. + const uint8_t *first = _json_iter->peek(); + if (simdjson_likely(*first == '"')) { return true; } + if (*first == '}') { logger::log_value(*_json_iter, "empty object"); _json_iter->return_current_and_advance(); SIMDJSON_TRY(end_container()); return false; } - return true; +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->end_position() - _json_iter->position() <= 1) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Object cut before its first key"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + abandon(); + return report_error(TAPE_ERROR, "Object does not start with a key"); } simdjson_warn_unused simdjson_inline error_code value_iterator::check_root_object() noexcept { @@ -229399,10 +234007,24 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n case ',': return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between object fields"); } } +simdjson_inline bool value_iterator::key_matches(raw_json_string actual_key, std::string_view key) const noexcept { + // A key known at compile time to hold no quote cannot run past actual_key: + // the usual comparison is then exact, and the cheapest. + if (raw_json_string::is_known_free_from_quote(key)) { return actual_key.unsafe_is_equal(key); } + // Otherwise, the colon we just checked bounds actual_key, so that a key + // holding an unescaped quote cannot match the JSON after it. + return actual_key.unsafe_is_equal_key(key, _json_iter->peek(-1)); +} + simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_field_raw(const std::string_view key) noexcept { error_code error; bool has_value; @@ -229452,7 +234074,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // ``` // } else { - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS if (_json_iter->start_position(_depth) != start_position()) { return OUT_OF_ORDER_ITERATION; } @@ -229461,8 +234083,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ while (has_value) { // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -229470,14 +234090,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // key and the value. It will also increment the depth by one. if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - //if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -229485,9 +234098,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); // Skip the value entirely + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -229567,7 +234180,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // If someone queried a key but they not did access the value, then we are left pointing // at the ':' and we need to move forward through the value... If the value was // processed then skip_child() does not move the iterator (but may adjust the depth). - if ((error = skip_child() )) { abandon(); return error; } + if ((error = skip_field_child() )) { abandon(); return error; } search_start = _json_iter->position(); if ((error = has_next_field().get(has_value) )) { abandon(); return error; } #if SIMDJSON_DEVELOPMENT_CHECKS @@ -229594,8 +234207,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). if ((error = field_key().get(actual_key) )) { abandon(); return error; }; @@ -229604,14 +234215,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ if ((error = field_value() )) { abandon(); return error; } // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -229619,9 +234223,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // The has_next_field() advances the pointer and check that either ',' or '}' is found. // It returns true if ',' is found, false otherwise. If anything other than ',' or '}' is found, // then we are in error and we abort. @@ -229644,8 +234248,6 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // Get the key and colon, stopping at the value. raw_json_string actual_key; - // size_t max_key_length = _json_iter->peek_length() - 2; // -2 for the two quotes - // Note: _json_iter->peek_length() - 2 might overflow if _json_iter->peek_length() < 2. // field_key() advances the pointer and checks that '"' is found (corresponding to a key). // The depth is left unchanged by field_key(). error = field_key().get(actual_key); SIMDJSON_ASSUME(!error); @@ -229654,14 +234256,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ error = field_value(); SIMDJSON_ASSUME(!error); // If it matches, stop and return - // We could do it this way if we wanted to allow arbitrary - // key content (including escaped quotes). - // if (actual_key.unsafe_is_equal(max_key_length, key)) { - // Instead we do the following which may trigger buffer overruns if the - // user provides an adversarial key (containing a well placed unescaped quote - // character and being longer than the number of bytes remaining in the JSON - // input). - if (actual_key.unsafe_is_equal(key)) { + if (key_matches(actual_key, key)) { logger::log_event(*this, "match", key, -2); // If we return here, then we return while pointing at the ':' that we just checked. return true; @@ -229669,9 +234264,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::find_ // No match: skip the value and see if , or } is next logger::log_event(*this, "no match", key, -2); - // The call to skip_child is meant to skip over the value corresponding to the key. - // After skip_child(), we are right before the next comma (',') or the final brace ('}'). - SIMDJSON_TRY( skip_child() ); + // The call to skip_field_value is meant to skip over the value corresponding to the key. + // After skip_field_value(), we are right before the next comma (',') or the final brace ('}'). + if ((error = skip_field_value() )) { _json_iter->_depth = 0; return error; } // If we reached the end of the key-value pair we started from, then we know // that the key is not there so we return false. We are either right before // the next comma or the final brace. @@ -229716,6 +234311,14 @@ simdjson_warn_unused simdjson_inline error_code value_iterator::field_key_with_l simdjson_warn_unused simdjson_inline error_code value_iterator::field_value() noexcept { assert_at_next(); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + // An incomplete document may end with a key, possibly cut before its closing + // quote. The next token is then the end-of-input sentinel, which points at the + // byte past the input: it must not be taken for the colon. + if (_json_iter->allow_incomplete_json() && _json_iter->at_end()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Missing colon at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (*_json_iter->return_current_and_advance() != ':') { return report_error(TAPE_ERROR, "Missing colon in object field"); } _json_iter->descend_to(depth()+1); return SUCCESS; @@ -229806,6 +234409,11 @@ simdjson_warn_unused simdjson_inline simdjson_result<bool> value_iterator::has_n _json_iter->descend_to(depth()+1); return true; default: +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json() && _json_iter->position() > _json_iter->end_position()) { + return report_error(INCOMPLETE_ARRAY_OR_OBJECT, "Container cut at the end of an incomplete document"); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return report_error(TAPE_ERROR, "Missing comma between array elements"); } } @@ -229829,15 +234437,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_string(string_type& receiver, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_string(allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_raw_json_string().get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_wobbly_string() noexcept { return get_raw_json_string().unescape_wobbly(json_iter()); @@ -229848,8 +234450,7 @@ simdjson_warn_unused simdjson_inline simdjson_result<raw_json_string> value_iter #ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (_json_iter->allow_incomplete_json()) { const size_t remaining_input_length = _json_iter->remaining_input_length(json); - const uint32_t max_len = remaining_input_length < peek_start_length() ? uint32_t(remaining_input_length) : peek_start_length(); - if (!raw_json_string_is_quote_terminated(json, max_len)) { + if (!raw_json_string_is_quote_terminated(json, uint32_t(remaining_input_length))) { return STRING_ERROR; } } @@ -229998,15 +234599,9 @@ simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_ite } template <typename string_type> simdjson_warn_unused simdjson_inline error_code value_iterator::get_root_string(string_type& receiver, bool check_trailing, bool allow_replacement) noexcept { - std::string_view content; - // Save the string buffer location so that we can restore it after get_string - auto saved_string_buf_loc = _json_iter->string_buf_loc(); - auto err = get_root_string(check_trailing, allow_replacement).get(content); - if (err) { return err; } - internal::assign_utf8(receiver, content); - // Restore the string buffer location, effectively discarding any temporary string storage - _json_iter->string_buf_loc() = saved_string_buf_loc; - return SUCCESS; + raw_json_string raw; + SIMDJSON_TRY( get_root_raw_json_string(check_trailing).get(raw) ); + return _json_iter->unescape(raw, receiver, allow_replacement); } simdjson_warn_unused simdjson_inline simdjson_result<std::string_view> value_iterator::get_root_wobbly_string(bool check_trailing) noexcept { return get_root_raw_json_string(check_trailing).unescape_wobbly(json_iter()); @@ -230208,6 +234803,23 @@ simdjson_inline simdjson_result<bool> value_iterator::is_root_null(bool check_tr return result; } +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child(token_position child_start) noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->position() == child_start) { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_child() noexcept { + if (_json_iter->depth() <= depth()) { return SUCCESS; } + if (_json_iter->depth() == depth() + 1 && *_json_iter->peek(-1) == ':') { return _json_iter->skip_value(depth()); } + return _json_iter->skip_partial(depth()); +} + +simdjson_warn_unused simdjson_inline error_code value_iterator::skip_field_value() noexcept { + SIMDJSON_ASSUME( _json_iter->_depth == _depth + 1 ); + return _json_iter->skip_value(depth()); +} + simdjson_warn_unused simdjson_inline error_code value_iterator::skip_child() noexcept { SIMDJSON_ASSUME( _json_iter->token._position > _start_position ); SIMDJSON_ASSUME( _json_iter->_depth >= _depth ); @@ -230267,6 +234879,13 @@ simdjson_inline const uint8_t *value_iterator::peek_start() const noexcept { return _json_iter->peek(start_position()); } simdjson_inline uint32_t value_iterator::peek_start_length() const noexcept { +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + const uint32_t length = _json_iter->peek_length(start_position()); + const size_t remaining_input_length = _json_iter->remaining_input_length(peek_start()); + return remaining_input_length < length ? uint32_t(remaining_input_length) : length; + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON return _json_iter->peek_length(start_position()); } simdjson_inline uint32_t value_iterator::peek_root_length() const noexcept { @@ -230330,6 +234949,12 @@ simdjson_inline const uint8_t *value_iterator::peek_root_scalar(const char *type } simdjson_inline const uint8_t *value_iterator::peek_non_root_scalar(const char *type) noexcept { logger::log_value(*_json_iter, start_position(), depth(), type); +#ifdef SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON + if (_json_iter->allow_incomplete_json()) { + if (is_at_start()) { assert_at_non_root_start(); } + return _json_iter->scalar_within_input(peek_start()); + } +#endif // SIMDJSON_EXPERIMENTAL_ALLOW_INCOMPLETE_JSON if (!is_at_start()) { return peek_start(); } assert_at_non_root_start(); @@ -230446,7 +235071,12 @@ inline void value_iterator::assert_at_root() const noexcept { inline void value_iterator::assert_at_non_root_start() const noexcept { assert_at_start(); - SIMDJSON_ASSUME( _depth > 1 ); + // The value is usually inside an array or object (depth > 1), but a root + // array or object obtained with document::get_value() is a value at depth 1. + // Scalar getters may be called on it: they see the leading '[' or '{' and + // fail (INCORRECT_TYPE, or NUMBER_ERROR for get_number() and friends) + // without advancing the iterator. + SIMDJSON_ASSUME( _depth > 0 ); } inline void value_iterator::assert_is_valid() const noexcept { diff --git a/deps/undici/src/SECURITY.md b/deps/undici/src/SECURITY.md index 6fed3847fba6..2f9e4ea37fbe 100644 --- a/deps/undici/src/SECURITY.md +++ b/deps/undici/src/SECURITY.md @@ -36,6 +36,29 @@ issue. Undici is an HTTP client library for Node.js. Its threat model is derived from and aligned with the [Node.js threat model](https://github.com/nodejs/node/blob/HEAD/SECURITY.md#the-nodejs-threat-model). +The Node.js policy is authoritative for the copy of undici bundled with +Node.js. This section applies the same boundaries to the standalone undici +package. + +### Security triage dispositions + +Security reports are classified using the same dispositions as Node.js: + +* **Vulnerability**: An undici defect that is exploitable across an + undici-owned security boundary and meets the criteria under + [What constitutes a vulnerability](#what-constitutes-a-vulnerability), + including any applicable DoS criteria. +* **Security-interest bug**: A real undici defect, or an API behavior likely to + cause security bugs in applications, that is not itself a vulnerability + under this threat model. These are fixed as regular bugs and do not + automatically receive a CVE, but should still be reported privately first + when they affect a common security control such as protocol interpretation, + certificate validation, or TLS decisions. +* **Common bug**: A correctness, robustness, or crash issue without an + undici-owned security boundary or a realistic cross-boundary attacker + benefit. +* **Invalid / out of scope**: A report that cannot be reproduced, is not an + undici defect, or concerns behavior excluded by this policy. ### What constitutes a vulnerability @@ -53,27 +76,40 @@ For a behavior to be considered a DoS vulnerability, the proof of concept must meet the following criteria: * The API is being correctly used. -* The API is public and documented. -* The behavior is significant enough to cause a denial of service quickly - or in a context not controlled by the application developer (for example, - HTTP parsing). +* The API does not have a warning against its use in production. +* The API is public and documented. For standards-based APIs, the behavior + must be well-defined by the applicable specification. +* The API is stable. For APIs bundled in Node.js, it must have stable (2.0) + status. +* The behavior is significant enough to cause a denial of service quickly or + in a context not controlled by the application developer, such as protocol + parsing. * The behavior is directly exploitable by an untrusted source without requiring application mistakes. * The behavior cannot be reasonably mitigated through standard operational - practices (like process recycling). + practices, such as process recycling. +* The behavior occurs deterministically under normal usage patterns rather than + only in edge cases. +* The behavior occurs at a rate that would cause practical resource exhaustion + within a practical timeframe under typical workloads. * The attack demonstrates [asymmetric resource consumption](https://cwe.mitre.org/data/definitions/405.html), - where the attacker expends significantly fewer resources than what is required - by the client to process the attack. + where the attacker expends significantly fewer resources than the client + must expend to process the attack. Attacks requiring comparable resources on + the attacker's side, which can be mitigated through practices such as rate + limiting, may not qualify. **Undici does NOT trust**: -* Data received from the remote end of HTTP connections (both inbound responses - and server-sent data) that is parsed or transformed by undici before being - passed to the application. This includes: +* Data received from the remote end of outbound network connections created + through undici APIs and transformed or validated by undici before being + passed to the application, **except with respect to payload length**. Undici + trusts applications to make connections and requests that avoid payload + sizes that would result in a denial of service. Subject to that exception, + untrusted data includes: * HTTP response headers and status lines. - * HTTP response bodies when processed by undici (e.g., chunked transfer - decoding, content-encoding). + * HTTP response bodies processed by undici, such as chunked transfer decoding + and content-encoding. * WebSocket frames received from a server. * Server-Sent Events (EventSource) data received from a server. * TLS certificate validation performed by undici on behalf of the application. @@ -81,7 +117,8 @@ meet the following criteria: **Undici trusts**: * The application code that uses its APIs, including all configuration, - options, callbacks, and decisions about which body-consuming APIs to call. + options, callbacks, connection and request decisions, and decisions about + which body-consuming APIs to call. * The operating system and its network stack. * The Node.js runtime undici is running on. * Dependencies installed by the application. @@ -99,19 +136,19 @@ meet the following criteria: bypass organizational, regulatory, or legal controls. Untrusted proxies are outside the supported threat model. -In other words, if untrusted data passing through undici to the application -can trigger actions other than those documented for the APIs, there is likely -a security vulnerability. Examples of unwanted actions are polluting globals, -causing an unrecoverable crash, or any other unexpected side effects that can -lead to a loss of confidentiality, integrity, or availability. +In other words, if untrusted data passing through undici to the application can +trigger actions other than those documented for the APIs, there is likely a +security vulnerability. Examples include polluting globals, causing an +unrecoverable crash, or other unexpected side effects that can lead to a loss +of confidentiality, integrity, or availability. ### Examples of vulnerabilities #### Improper Certificate Validation (CWE-295) * Undici provides TLS connections to HTTPS endpoints. If certificates can be - crafted that result in incorrect validation by undici, that is considered - a vulnerability. + crafted that result in incorrect validation by undici, that is considered a + vulnerability. #### Inconsistent Interpretation of HTTP Responses (CWE-444) @@ -127,12 +164,19 @@ lead to a loss of confidentiality, integrity, or availability. #### CRLF Injection in Request Headers (CWE-93) -* If untrusted input passed to undici APIs (such as header values or URLs) - can inject additional headers or corrupt the HTTP request stream, that is +* If untrusted input passed to undici APIs, such as header values or URLs, can + inject additional headers or corrupt the HTTP request stream, that is considered a vulnerability. ### Examples of non-vulnerabilities +#### Defense-in-depth issues + +* Bugs whose fixes only improve resilience after another security boundary has + already failed, or reduce the impact of behavior outside this threat model, + are defense-in-depth issues. They are fixed as regular bugs and do not + receive CVEs. + #### Malicious Third-Party Modules (CWE-1357) * Application code and its dependencies are trusted by undici. Any scenario @@ -141,17 +185,17 @@ lead to a loss of confidentiality, integrity, or availability. #### Prototype Pollution Attacks (CWE-1321) -* Undici trusts the inputs provided to it by application code. It is up to the - application to sanitize appropriately. Any scenario that requires control - over user input passed directly by the application is not considered a - vulnerability in undici. +* Undici trusts inputs provided by application code. The application must + sanitize them appropriately. A scenario that requires control over user input + passed directly by the application is not a vulnerability in undici. #### Uncontrolled Resource Consumption on Outbound Connections (CWE-400) -* If undici is asked to connect to a remote site and the response payload is - large enough to impact performance or cause the runtime to run out of - resources, that is not considered a vulnerability. Applications are - responsible for setting appropriate limits on response sizes. +* If undici is asked to connect to a remote site and return an artifact, it is + not a vulnerability if the size of that artifact is large enough to impact + performance or cause the runtime to run out of resources. Applications are + responsible for choosing suitable response-processing APIs and enforcing + limits appropriate for their workloads. #### Calling body-consuming methods on untrusted responses @@ -188,9 +232,9 @@ lead to a loss of confidentiality, integrity, or availability. #### Application Misconfiguration -* Issues arising from incorrect or insecure use of undici APIs (such as +* Issues arising from incorrect or insecure use of undici APIs, such as disabling TLS verification, ignoring errors, or passing unsanitized user - input to request options) are the application's responsibility, not + input to request options, are the application's responsibility and not vulnerabilities in undici. #### Unauthorized or untrusted proxy use diff --git a/deps/undici/src/docs/docs/api/CacheStore.md b/deps/undici/src/docs/docs/api/CacheStore.md index 45c202d89872..dd4facac2f0e 100644 --- a/deps/undici/src/docs/docs/api/CacheStore.md +++ b/deps/undici/src/docs/docs/api/CacheStore.md @@ -203,6 +203,16 @@ added: v7.0.0 integers; a `TypeError` is thrown otherwise, or if `maxEntrySize` is greater than 2 GB. +The database is not encrypted, and nothing in it is hashed. The request URL +(including the query string), the response headers and body, and the values of +any request headers named in the response's `Vary` header (for example +`Authorization` or `Cookie`) are written as plain text to `location`. Protect +that file like any other sensitive data, or use `':memory:'`. A response to a +request that carries `Authorization` is only stored when the response allows it +with `public`, `s-maxage`, or `must-revalidate` (see [RFC 9111, Section 3.5][]); +servers can send `Cache-Control: no-store` to keep a response out of the cache +entirely. + ### `sqliteCacheStore.close()` <!-- YAML @@ -372,4 +382,5 @@ The value returned by `get`. It contains every field of body. (optional) [RFC 9111]: https://www.rfc-editor.org/rfc/rfc9111.html +[RFC 9111, Section 3.5]: https://www.rfc-editor.org/rfc/rfc9111.html#section-3.5 [`node:sqlite`]: https://nodejs.org/api/sqlite.html diff --git a/deps/undici/src/docs/docs/api/Client.md b/deps/undici/src/docs/docs/api/Client.md index b81aef5559bb..402e050351dc 100644 --- a/deps/undici/src/docs/docs/api/Client.md +++ b/deps/undici/src/docs/docs/api/Client.md @@ -137,7 +137,9 @@ added: v1.0.0 positive integer. **Default:** `524288`. * `pingInterval` {number} The time interval, in milliseconds, between HTTP/2 PING frames. Set to `0` to disable PING frames. Applies only to HTTP/2 - connections and emits a `ping` event on the client. **Default:** `60e3`. + connections and emits a `ping` event on the client. A connection whose + PING is still unacknowledged when the next one is due is closed, and new + requests go to a new connection. **Default:** `60e3`. * `settings` {object} `SETTINGS` frame options. For full reference, take a look to [HTTP/2#Settings Object](https://nodejs.org/api/http2.html#settings-object) * `webSocket` {Object} (optional) WebSocket-specific configuration. @@ -217,7 +219,7 @@ import { Client, buildConnector } from 'undici' const connector = buildConnector({ rejectUnauthorized: false }) const client = new Client('https://localhost:3000', { connect (opts, cb) { - connector(opts, (err, socket) => { + return connector(opts, (err, socket) => { if (err) { cb(err) } else { diff --git a/deps/undici/src/docs/docs/api/Connector.md b/deps/undici/src/docs/docs/api/Connector.md index 8e21f1713f0e..724c480b7ed7 100644 --- a/deps/undici/src/docs/docs/api/Connector.md +++ b/deps/undici/src/docs/docs/api/Connector.md @@ -78,7 +78,7 @@ const connector = buildConnector({ rejectUnauthorized: false }) const client = new Client('https://localhost:3000', { connect (opts, cb) { - connector(opts, (err, socket) => { + return connector(opts, (err, socket) => { if (err) { cb(err) } else if (/* assertion */ false) { @@ -124,6 +124,13 @@ targets or a [`tls.TLSSocket`][] for `https:` targets, applies TCP keep-alive an the connect timeout, and invokes `callback` once the socket connects or errors. The socket is also returned synchronously. +undici uses the returned socket to cancel a connection attempt that no request +needs any more: once every request waiting for it is aborted, the socket is +destroyed and the next request opens a new connection instead of waiting for +it. A connector that wraps another one should return the socket it gets back, +as the examples on this page do. If it returns nothing, the attempt runs until +it connects or fails. + When connecting over TLS, established sessions are cached (subject to `maxCachedSessions`) and reused for subsequent connections to the same `servername` or `hostname`. @@ -141,7 +148,7 @@ const connector = buildConnector({ rejectUnauthorized: false }) const client = new Client('https://localhost:3000', { connect (opts, cb) { - connector(opts, (err, socket) => { + return connector(opts, (err, socket) => { if (err) { cb(err) } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { diff --git a/deps/undici/src/docs/docs/api/Dispatcher.md b/deps/undici/src/docs/docs/api/Dispatcher.md index 61c0d64f53d0..8265bee52d6b 100644 --- a/deps/undici/src/docs/docs/api/Dispatcher.md +++ b/deps/undici/src/docs/docs/api/Dispatcher.md @@ -705,6 +705,26 @@ The order of the interceptors matters: the last interceptor in the chain is the first to be called. Forking the chain of interceptors can lead to unexpected results. +Because interceptors wrap each other, ordering is the end-user's responsibility. +Certain built-in interceptors are order-sensitive and will throw an +`InvalidArgumentError` if composed in an unsafe order. In particular, the +`cache` interceptor must be composed **after** the `redirect` interceptor. When +`cache` is composed before `redirect`, the cache handler is wrapped *above* the +redirect handler, so it never observes the redirect history and its +cross-origin / credential-bearing redirect guards are silently disabled. +This allows an attacker-controlled or cross-principal redirect response to be +stored under the trusted origin's cache key and replayed to unrelated callers +(see GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26 and +GHSA-7XG3-FPHP-28HG). + +```js +// Correct: cache is composed after redirect. +new Agent().compose(interceptors.redirect({ maxRedirections: 5 }), interceptors.cache({})) + +// Throws an InvalidArgumentError: cache composed before redirect. +new Agent().compose(interceptors.cache({}), interceptors.redirect({ maxRedirections: 5 })) +``` + ```text compose([interceptor1, interceptor2, interceptor3]) diff --git a/deps/undici/src/docs/docs/api/Interceptors.md b/deps/undici/src/docs/docs/api/Interceptors.md index fd4b8d59aa13..3d3ae902fb0e 100644 --- a/deps/undici/src/docs/docs/api/Interceptors.md +++ b/deps/undici/src/docs/docs/api/Interceptors.md @@ -204,9 +204,6 @@ and `x-compress`, is left untouched, matching `fetch()`. As required by [RFC 9659](https://www.rfc-editor.org/rfc/rfc9659.html), a `zstd` frame that requires a window size larger than 8 MB fails to decode. -> **Experimental:** This interceptor is experimental and subject to change. -> A one-time `ExperimentalWarning` is emitted on first use. - **Parameters** * `opts` {Object} (optional) @@ -359,12 +356,25 @@ backing store. **Returns:** {Dispatcher.DispatcherComposeInterceptor} +> **Ordering:** the `cache` interceptor must be composed **after** the +> `redirect` interceptor. When `cache` is composed before `redirect`, the cache +> handler is wrapped above the redirect handler, so it never observes the +> redirect history and its cross-origin / credential-bearing redirect guards are +> silently disabled, which lets an attacker-controlled or cross-principal +> redirect response be stored under the trusted origin's cache key and replayed +> to unrelated callers (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, +> GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG). `compose()` throws an +> `InvalidArgumentError` for this unsafe order. The `deduplicate` interceptor +> participates in the same redirect-history contract and may be placed before or +> after `redirect`, as long as `cache` follows `redirect`. + **Example** ```js import { Agent, interceptors, cacheStores } from 'undici' const agent = new Agent().compose( + interceptors.redirect({ maxRedirections: 5 }), interceptors.cache({ store: new cacheStores.MemoryCacheStore() }) ) ``` diff --git a/deps/undici/src/docs/docs/best-practices/mocking-request.md b/deps/undici/src/docs/docs/best-practices/mocking-request.md index 86ebca94f7a5..d097ce682723 100644 --- a/deps/undici/src/docs/docs/best-practices/mocking-request.md +++ b/deps/undici/src/docs/docs/best-practices/mocking-request.md @@ -61,7 +61,7 @@ const success = await bankTransfer('1234567890', '100') assert.deepEqual(success, { message: 'transaction processed' }) -// if you dont want to check whether the body or the headers contain the same value +// if you don't want to check whether the body or the headers contain the same value // just remove it from interceptor mockPool.intercept({ path: '/bank-transfer', diff --git a/deps/undici/src/lib/api/abort-signal.js b/deps/undici/src/lib/api/abort-signal.js index 608170b43165..d4c1c93c7a28 100644 --- a/deps/undici/src/lib/api/abort-signal.js +++ b/deps/undici/src/lib/api/abort-signal.js @@ -2,15 +2,17 @@ const { addAbortListener } = require('../core/util') const { RequestAbortedError } = require('../core/errors') +const { kQueuedAbort } = require('../core/symbols') const kListener = Symbol('kListener') const kSignal = Symbol('kSignal') function abort (self) { + // Keep the reason even when abort is set: a queued request that cannot be + // taken out of its queue is aborted once it starts. + self.reason = self[kSignal]?.reason ?? new RequestAbortedError() if (self.abort) { - self.abort(self[kSignal]?.reason) - } else { - self.reason = self[kSignal]?.reason ?? new RequestAbortedError() + self.abort(self.reason) } removeSignal(self) } @@ -26,7 +28,7 @@ function addSignal (self, signal) { } if (signal.aborted) { - abort(self) + self.reason = signal.reason ?? new RequestAbortedError() return } @@ -53,7 +55,55 @@ function removeSignal (self) { self[kListener] = null } +// Dispatchers call the kQueuedAbort hook while a request waits for a +// connection, with a function that takes it out of their queue. Until the +// request starts, the handler's abort calls that function. +// +// A retry or a redirect dispatches the same handler again after an earlier +// attempt started. The handler's abort then also calls the controller of that +// attempt: it does nothing once the attempt is over, and still reaches a +// response that a retry resumes. +function queuedAbortHook (handler) { + // The abort set by onRequestStart, and the one this hook installed last. + let started = null + let installed = null + return (cancel) => { + if (handler.reason) { + cancel(handler.reason) + return + } + + if (handler.abort !== installed) { + started = handler.abort + } + + if (started === null) { + installed = cancel + } else { + const abortStarted = started + installed = (reason) => { + abortStarted(reason) + cancel(reason) + } + } + handler.abort = installed + } +} + +// Dispatches a request whose options carry a signal. Requests without a signal +// are dispatched directly and never reach this function. +function dispatchWithSignal (dispatcher, opts, handler) { + if (handler.reason) { + // Already aborted: fail without dispatching, so no connection is opened. + handler.onResponseError(null, handler.reason) + return + } + + dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler) +} + module.exports = { addSignal, - removeSignal + removeSignal, + dispatchWithSignal } diff --git a/deps/undici/src/lib/api/api-connect.js b/deps/undici/src/lib/api/api-connect.js index f449c787d617..9811b076cb90 100644 --- a/deps/undici/src/lib/api/api-connect.js +++ b/deps/undici/src/lib/api/api-connect.js @@ -4,7 +4,7 @@ const assert = require('node:assert') const { AsyncResource } = require('node:async_hooks') const { InvalidArgumentError, SocketError } = require('../core/errors') const util = require('../core/util') -const { addSignal, removeSignal } = require('./abort-signal') +const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal') class ConnectHandler extends AsyncResource { constructor (opts, callback) { @@ -99,7 +99,11 @@ function connect (opts, callback) { try { const connectHandler = new ConnectHandler(opts, callback) const connectOptions = { ...opts, method: 'CONNECT' } - this.dispatch(connectOptions, connectHandler) + if (opts.signal == null) { + this.dispatch(connectOptions, connectHandler) + } else { + dispatchWithSignal(this, connectOptions, connectHandler) + } } catch (err) { if (typeof callback !== 'function') { throw err diff --git a/deps/undici/src/lib/api/api-pipeline.js b/deps/undici/src/lib/api/api-pipeline.js index 6af3913440a4..fe7c729413af 100644 --- a/deps/undici/src/lib/api/api-pipeline.js +++ b/deps/undici/src/lib/api/api-pipeline.js @@ -14,7 +14,7 @@ const { } = require('../core/errors') const util = require('../core/util') const { kBodyUsed } = require('../core/symbols') -const { addSignal, removeSignal } = require('./abort-signal') +const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal') function noop () {} @@ -126,7 +126,7 @@ class PipelineHandler extends AsyncResource { err = new RequestAbortedError() } - if (abort && err) { + if (abort && (err || !res?.readableEnded)) { abort() } @@ -255,7 +255,12 @@ class PipelineHandler extends AsyncResource { function pipeline (opts, handler) { try { const pipelineHandler = new PipelineHandler(opts, handler) - this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + const pipelineOpts = { ...opts, body: pipelineHandler.req } + if (opts.signal == null) { + this.dispatch(pipelineOpts, pipelineHandler) + } else { + dispatchWithSignal(this, pipelineOpts, pipelineHandler) + } return pipelineHandler.ret } catch (err) { return new PassThrough().destroy(err) diff --git a/deps/undici/src/lib/api/api-request.js b/deps/undici/src/lib/api/api-request.js index e9f72a428b23..c857e213d3f9 100644 --- a/deps/undici/src/lib/api/api-request.js +++ b/deps/undici/src/lib/api/api-request.js @@ -5,6 +5,7 @@ const { AsyncResource } = require('node:async_hooks') const { Readable } = require('./readable') const { InvalidArgumentError, RequestAbortedError } = require('../core/errors') const util = require('../core/util') +const { dispatchWithSignal } = require('./abort-signal') function noop () {} @@ -37,6 +38,11 @@ class RequestHandler extends AsyncResource { throw new InvalidArgumentError('invalid onInfo callback') } + // Reject before dispatching: onRequestStart only runs once a connection is established. + if (signal?.aborted) { + throw signal.reason ?? new RequestAbortedError() + } + super('UNDICI_REQUEST') } catch (err) { if (util.isStream(body)) { @@ -60,9 +66,7 @@ class RequestHandler extends AsyncResource { this.reason = null this.removeAbortListener = null - if (signal?.aborted) { - this.reason = signal.reason ?? new RequestAbortedError() - } else if (signal) { + if (signal) { this.removeAbortListener = util.addAbortListener(signal, () => { this.reason = signal.reason ?? new RequestAbortedError() if (this.res) { @@ -103,7 +107,7 @@ class RequestHandler extends AsyncResource { if (statusCode < 200) { if (this.onInfo) { - this.onInfo({ statusCode, headers: responseHeaderData }) + this.runInAsyncScope(this.onInfo, null, { statusCode, headers: responseHeaderData }) } return } @@ -230,7 +234,11 @@ function request (opts, callback) { try { const handler = new RequestHandler(opts, callback) - this.dispatch(opts, handler) + if (opts.signal == null) { + this.dispatch(opts, handler) + } else { + dispatchWithSignal(this, opts, handler) + } } catch (err) { if (typeof callback !== 'function') { throw err diff --git a/deps/undici/src/lib/api/api-stream.js b/deps/undici/src/lib/api/api-stream.js index f111d70efc17..a5e1b3ef4727 100644 --- a/deps/undici/src/lib/api/api-stream.js +++ b/deps/undici/src/lib/api/api-stream.js @@ -4,7 +4,7 @@ const assert = require('node:assert') const { AsyncResource } = require('node:async_hooks') const { InvalidArgumentError, InvalidReturnValueError } = require('../core/errors') const util = require('../core/util') -const { addSignal, removeSignal } = require('./abort-signal') +const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal') function noop () {} @@ -257,7 +257,11 @@ function stream (opts, factory, callback) { try { const handler = new StreamHandler(opts, factory, callback) - this.dispatch(opts, handler) + if (opts.signal == null) { + this.dispatch(opts, handler) + } else { + dispatchWithSignal(this, opts, handler) + } } catch (err) { if (typeof callback !== 'function') { throw err diff --git a/deps/undici/src/lib/api/api-upgrade.js b/deps/undici/src/lib/api/api-upgrade.js index 42cb29ed3ce1..29eece8d0be9 100644 --- a/deps/undici/src/lib/api/api-upgrade.js +++ b/deps/undici/src/lib/api/api-upgrade.js @@ -5,7 +5,7 @@ const { AsyncResource } = require('node:async_hooks') const assert = require('node:assert') const util = require('../core/util') const { kHTTP2Stream } = require('../core/symbols') -const { addSignal, removeSignal } = require('./abort-signal') +const { addSignal, removeSignal, dispatchWithSignal } = require('./abort-signal') class UpgradeHandler extends AsyncResource { constructor (opts, callback) { @@ -108,7 +108,11 @@ function upgrade (opts, callback) { method: opts.method || 'GET', upgrade: opts.protocol || 'Websocket' } - this.dispatch(upgradeOpts, upgradeHandler) + if (opts.signal == null) { + this.dispatch(upgradeOpts, upgradeHandler) + } else { + dispatchWithSignal(this, upgradeOpts, upgradeHandler) + } } catch (err) { if (typeof callback !== 'function') { throw err diff --git a/deps/undici/src/lib/core/request.js b/deps/undici/src/lib/core/request.js index efa391b8edf8..039dbd7a08e0 100644 --- a/deps/undici/src/lib/core/request.js +++ b/deps/undici/src/lib/core/request.js @@ -47,6 +47,8 @@ const kHandler = Symbol('handler') const kController = Symbol('controller') const kResume = Symbol('resume') +function noop () {} + class RequestController { #paused = false #reason = null @@ -463,12 +465,26 @@ class Request { } } + // Fails a request that was aborted before it reached a connection. The + // handler gets an aborted controller, so wrappers such as RetryHandler can + // tell a caller abort apart from a retryable connection failure. + onQueuedAbort (reason) { + this[kController] = createAbortedController(reason) + return this.onResponseError(reason) + } + addHeader (key, value) { processHeader(this, key, value) return this } } +function createAbortedController (reason) { + const controller = new RequestController(noop) + controller.abort(reason) + return controller +} + function processHeader (request, key, val) { if (val && (typeof val === 'object' && !Array.isArray(val))) { throw new InvalidArgumentError(`invalid ${key} header`) @@ -580,3 +596,4 @@ function isUndiciFormData (body) { } module.exports = Request +module.exports.createAbortedController = createAbortedController diff --git a/deps/undici/src/lib/core/symbols.js b/deps/undici/src/lib/core/symbols.js index 62163ebe2d6a..842669bc6d77 100644 --- a/deps/undici/src/lib/core/symbols.js +++ b/deps/undici/src/lib/core/symbols.js @@ -60,6 +60,7 @@ module.exports = { kMaxResponseSize: Symbol('max response size'), kHTTP2Session: Symbol('http2Session'), kHTTP2Options: Symbol('http2 options'), + kQueuedAbort: Symbol('queued abort'), kHTTP2SessionState: Symbol('http2Session state'), kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), kConstruct: Symbol('constructable'), @@ -77,5 +78,6 @@ module.exports = { kNoProxyAgent: Symbol('no proxy agent'), kHttpProxyAgent: Symbol('http proxy agent'), kHttpsProxyAgent: Symbol('https proxy agent'), - kSocks5ProxyAgent: Symbol('socks5 proxy agent') + kSocks5ProxyAgent: Symbol('socks5 proxy agent'), + kInterceptorKind: Symbol('interceptor kind') } diff --git a/deps/undici/src/lib/dispatcher/agent.js b/deps/undici/src/lib/dispatcher/agent.js index 7f95e308700a..a73ba2e05413 100644 --- a/deps/undici/src/lib/dispatcher/agent.js +++ b/deps/undici/src/lib/dispatcher/agent.js @@ -96,7 +96,7 @@ class Agent extends DispatcherBase { ? { ...this[kOptions], allowH2: false } : this[kOptions]) - const closeClientIfUnused = () => { + const closeClientIfUnused = (deferred = false) => { if (this[kClients].get(key) !== dispatcher) { return } @@ -106,7 +106,16 @@ class Agent extends DispatcherBase { // no connected clients and is not busy, but it still has pending work. // Closing it here lets the replacement Client finish those requests // and then destroys that new connection with ClientDestroyedError. - if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) { + if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) { + return + } + + if (dispatcher[kPending] > 0) { + if (!deferred) { + queueMicrotask(() => { + closeClientIfUnused(true) + }) + } return } diff --git a/deps/undici/src/lib/dispatcher/client-h1.js b/deps/undici/src/lib/dispatcher/client-h1.js index a26b9c014e87..13bc66f9372d 100644 --- a/deps/undici/src/lib/dispatcher/client-h1.js +++ b/deps/undici/src/lib/dispatcher/client-h1.js @@ -67,6 +67,7 @@ const removeAllListeners = util.removeAllListeners const kIdleSocketValidation = Symbol('kIdleSocketValidation') const kIdleSocketValidationTimeout = Symbol('kIdleSocketValidationTimeout') const kSocketUsed = Symbol('kSocketUsed') +const kIdleSince = Symbol('kIdleSince') const kTypeOfService = Symbol('kTypeOfService') let extractBody @@ -1107,6 +1108,19 @@ function scheduleIdleSocketValidation (client, socket) { }) } +/** + * kIdleSince is recorded when the keep-alive timer is armed, so this never + * expires a socket before that timer is due. + * @param {import('net').Socket} socket + * @returns {boolean} + */ +function isIdleSocketExpired (socket) { + const parser = socket[kParser] + return parser.timeoutType === TIMEOUT_KEEP_ALIVE && + parser.timeoutValue > 0 && + performance.now() - socket[kIdleSince] >= parser.timeoutValue +} + /** * @param {import('./client.js')} client */ @@ -1124,6 +1138,15 @@ function resumeH1 (client) { socket[kNoRef] = false } + // The keep-alive timer cannot fire while the event loop is blocked, and a + // request dispatched from the poll phase passes the idle socket validation + // below before that timer or a FIN received during the block is processed. + // Check the clock so that an expired socket is not reused. + if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) { + util.destroy(socket, new InformationalError('socket idle timeout')) + return + } + if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { if (socket[kIdleSocketValidation] === 0) { scheduleIdleSocketValidation(client, socket) @@ -1152,6 +1175,7 @@ function resumeH1 (client) { if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { + socket[kIdleSince] = performance.now() socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE) } } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { diff --git a/deps/undici/src/lib/dispatcher/client-h2.js b/deps/undici/src/lib/dispatcher/client-h2.js index 9857b80b1e23..418ef37e922b 100644 --- a/deps/undici/src/lib/dispatcher/client-h2.js +++ b/deps/undici/src/lib/dispatcher/client-h2.js @@ -91,6 +91,7 @@ const { HTTP2_HEADER_STATUS, HTTP2_HEADER_PROTOCOL, NGHTTP2_NO_ERROR, + NGHTTP2_PROTOCOL_ERROR, NGHTTP2_REFUSED_STREAM } } = http2 @@ -300,7 +301,9 @@ function connectH2 (client, socket) { // refH2Session/unrefH2Session. refed: true, ping: { - interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref() + interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref(), + // Set while a periodic PING waits for its ack. + pending: false } } session[kReceivedGoAway] = false @@ -565,6 +568,10 @@ function onHttp2ProbeTimeout (session) { return } + resetUnresponsiveHttp2Session(session) +} + +function resetUnresponsiveHttp2Session (session) { const err = new SocketError('HTTP/2: connection unresponsive', util.getSocketInfo(session[kSocket])) session[kError] = err resetHttp2Session(session, err) @@ -658,16 +665,27 @@ function onHttp2SendPing (session) { return } - // If no ping sent, do nothing + // An unacked PING never calls back, so a connection that silently died + // (dropped by a NAT or load balancer, a hung peer) would be kept forever when + // no stream times out on it, e.g. when every request is aborted first. + if (state.ping.pending) { + resetUnresponsiveHttp2Session(session) + return + } + + state.ping.pending = true session.ping(onPing.bind(session)) function onPing (err, duration) { + state.ping.pending = false + const client = this[kClient] const socket = this[kSocket] if (err != null) { const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`) - socket[kError] = error + // Keep the reason the session was torn down if that is what cancelled the PING. + socket[kError] ??= error client[kOnError](error) } else { client.emit('ping', duration) @@ -1684,11 +1702,16 @@ function onError (err) { // noop error sink so that re-delivery cannot go unhandled. stream.on('error', noop) - // Node's HTTP/2 implementation can turn an incomplete Content-Length body - // into a protocol stream error instead of emitting 'end'. Prefer the - // content-length mismatch error when the received byte count proves it. - if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) { - err = new ResponseContentLengthMismatchError() + // Node may report Content-Length violations as protocol errors. + if ( + (err.code === 'ERR_HTTP2_ERROR' || + (err.code === 'ERR_HTTP2_STREAM_ERROR' && stream.rstCode === NGHTTP2_PROTOCOL_ERROR)) && + state.responseContentLength != null && + state.bytesRead !== state.responseContentLength + ) { + const mismatch = new ResponseContentLengthMismatchError() + mismatch.cause = err + err = mismatch } if (typeof stream.rstCode === 'number' && stream.rstCode !== NGHTTP2_NO_ERROR) { diff --git a/deps/undici/src/lib/dispatcher/client.js b/deps/undici/src/lib/dispatcher/client.js index 05288a5991b2..bc55e15bd318 100644 --- a/deps/undici/src/lib/dispatcher/client.js +++ b/deps/undici/src/lib/dispatcher/client.js @@ -55,12 +55,14 @@ const { kHostAuthority, kResume, kHTTP2Options, - kUseMilo + kUseMilo, + kQueuedAbort } = require('../core/symbols.js') const connectH1 = require('./client-h1.js') const connectH2 = require('./client-h2.js') const kClosedResolve = Symbol('kClosedResolve') +const kCancelConnect = Symbol('kCancelConnect') const getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && @@ -322,6 +324,7 @@ class Client extends DispatcherBase { this[kClosedResolve] = null this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 this[kHTTPContext] = null + this[kCancelConnect] = null // h2 this[kHTTP2Options] = { pingInterval: h2Options?.pingInterval ?? pingInterval ?? 60e3, @@ -402,6 +405,8 @@ class Client extends DispatcherBase { [kConnect] (cb) { connect(this) + // Asked for explicitly: keep it even if no request waits for it. + this[kCancelConnect] = null this.once('connect', cb) } @@ -419,6 +424,15 @@ class Client extends DispatcherBase { this[kResume](true) } + if (request.abort === null && !request.aborted) { + // The request is still waiting for a connection: if its handler listens + // to a signal, give it a way to take the request out of the queue. + const onQueued = opts[kQueuedAbort] + if (onQueued !== undefined) { + onQueued((reason) => abortPendingRequest(this, request, reason)) + } + } + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { this[kNeedDrain] = 2 } @@ -469,6 +483,56 @@ class Client extends DispatcherBase { } } +function failQueuedRequest (client, request, reason) { + try { + request.onQueuedAbort(reason) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +function abortPendingRequest (client, request, reason) { + // The request already settled, or it started and its handler owns the abort. + if (request.aborted || request.abort !== null) { + return + } + + const queue = client[kQueue] + const idx = queue.indexOf(request, client[kPendingIdx]) + if (idx === -1) { + return + } + + // _resume() may be handing this request to the connection right now, before + // onRequestStart runs. Leave it there: the handler aborts it once it starts. + if (idx === client[kPendingIdx] && client[kResuming] === 2) { + return + } + + queue.splice(idx, 1) + failQueuedRequest(client, request, reason) + + // The client may no longer be busy: emit 'drain' so a Pool can use it again. + client[kResume](true) + + if (client[kCancelConnect] !== null && client[kSize] === 0) { + // The drain is emitted in a microtask: check once a Pool had the chance to + // hand this client the requests it queued. + queueMicrotask(() => cancelUnusedConnect(client)) + } +} + +// A connection attempt that no request waits for only holds a connection slot, +// until it connects or times out. Destroy it, so the next request starts a new +// one instead of waiting for it. +function cancelUnusedConnect (client) { + const cancel = client[kCancelConnect] + if (cancel !== null && client[kSize] === 0) { + cancel(new InformationalError('no request waits for this connection')) + } +} + function onError (client, err) { if ( client[kRunning] === 0 && @@ -515,6 +579,38 @@ function connect (client) { client[kConnecting] = true + // The name this attempt verifies the server's certificate for. While it + // connects, its requests can be aborted and _resume() can switch + // client[kServerName] to the name of the next queued request. + const servername = client[kServerName] + + let calledBack = false + let cancelled = false + + // Ends this attempt without a 'connectionError': no request failed, and a + // Pool would retire this client. + const abandon = (socket, err) => { + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername, + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + util.destroy(socket.on('error', noop), err) + } + if (channels.beforeConnect.hasSubscribers) { channels.beforeConnect.publish({ connectParams: { @@ -523,7 +619,7 @@ function connect (client) { protocol, port, version: client[kHTTPContext]?.version, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, connector: client[kConnector] @@ -531,16 +627,27 @@ function connect (client) { } try { - client[kConnector]({ + const connecting = client[kConnector]({ host, hostname, protocol, port, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, (err, socket) => { + calledBack = true + + if (cancelled) { + if (socket) { + util.destroy(socket.on('error', noop)) + } + return + } + + client[kCancelConnect] = null + if (err) { - handleConnectError(client, err, { host, hostname, protocol, port }) + handleConnectError(client, err, { host, hostname, protocol, port, servername }) client[kResume]() return } @@ -553,13 +660,21 @@ function connect (client) { assert(socket) + if (client[kServerName] !== servername) { + // The server proved its identity for another name than the one the + // queued requests are for: never send them on this connection. + abandon(socket, new InformationalError('servername changed')) + client[kResume]() + return + } + try { client[kHTTPContext] = socket.alpnProtocol === 'h2' ? connectH2(client, socket) : connectH1(client, socket) } catch (err) { socket.destroy().on('error', noop) - handleConnectError(client, err, { host, hostname, protocol, port }) + handleConnectError(client, err, { host, hostname, protocol, port, servername }) client[kResume]() return } @@ -579,7 +694,7 @@ function connect (client) { protocol, port, version: client[kHTTPContext]?.version, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, connector: client[kConnector], @@ -590,13 +705,23 @@ function connect (client) { client.emit('connect', client[kUrl], [client]) client[kResume]() }) + + // The attempt can only be cancelled through the socket the connector + // returns. The built-in connector returns it; custom connectors may not. + if (!calledBack && util.isStream(connecting)) { + client[kCancelConnect] = (err) => { + cancelled = true + client[kCancelConnect] = null + abandon(connecting, err) + } + } } catch (err) { - handleConnectError(client, err, { host, hostname, protocol, port }) + handleConnectError(client, err, { host, hostname, protocol, port, servername }) client[kResume]() } } -function handleConnectError (client, err, { host, hostname, protocol, port }) { +function handleConnectError (client, err, { host, hostname, protocol, port, servername }) { if (client.destroyed) { return } @@ -611,7 +736,7 @@ function handleConnectError (client, err, { host, hostname, protocol, port }) { protocol, port, version: client[kHTTPContext]?.version, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, connector: client[kConnector], @@ -627,7 +752,8 @@ function handleConnectError (client, err, { host, hostname, protocol, port }) { util.errorRequest(client, running[i], err) } - while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + // Only the requests for the name the certificate failed for. + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === servername) { const request = client[kQueue].splice(client[kPendingIdx], 1)[0] util.errorRequest(client, request, err) } @@ -718,6 +844,9 @@ function _resume (client, sync) { client[kHTTPContext] = null resume(client) }) + // A pending attempt verifies the server for the previous name, and its + // connection is discarded once it connects: do not wait for it. + client[kCancelConnect]?.(new InformationalError('servername changed')) } if (client[kConnecting]) { diff --git a/deps/undici/src/lib/dispatcher/dispatcher-base.js b/deps/undici/src/lib/dispatcher/dispatcher-base.js index 97a4db6e3219..7261fd17a905 100644 --- a/deps/undici/src/lib/dispatcher/dispatcher-base.js +++ b/deps/undici/src/lib/dispatcher/dispatcher-base.js @@ -190,7 +190,12 @@ class DispatcherBase extends Dispatcher { handler.onResponseError(null, err) - return false + // The request failed synchronously: no work was queued on this + // dispatcher, no capacity was consumed and no 'drain' event will + // ever follow. Returning false would make callers (e.g. Pool) + // mark this dispatcher as busy waiting for a drain that never + // comes, permanently taking it out of rotation. + return true } } } diff --git a/deps/undici/src/lib/dispatcher/dispatcher.js b/deps/undici/src/lib/dispatcher/dispatcher.js index 11a7ab2b4476..ed45263b27c2 100644 --- a/deps/undici/src/lib/dispatcher/dispatcher.js +++ b/deps/undici/src/lib/dispatcher/dispatcher.js @@ -1,6 +1,7 @@ 'use strict' const EventEmitter = require('node:events') -const { kOriginless, kUrl } = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') +const { kOriginless, kUrl, kInterceptorKind } = require('../core/symbols') class Dispatcher extends EventEmitter { dispatch () { @@ -24,6 +25,8 @@ class Dispatcher extends EventEmitter { : this[kUrl]?.origin let dispatch = this.dispatch.bind(this) + const orderSensitiveKinds = [] + for (const interceptor of interceptors) { if (interceptor == null) { continue @@ -33,6 +36,10 @@ class Dispatcher extends EventEmitter { throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`) } + if (interceptor[kInterceptorKind] != null) { + orderSensitiveKinds.push(interceptor[kInterceptorKind]) + } + dispatch = interceptor(dispatch, interceptorOrigin) if (dispatch == null || typeof dispatch !== 'function' || dispatch.length !== 2) { @@ -40,6 +47,20 @@ class Dispatcher extends EventEmitter { } } + // Several shipped interceptors are order-sensitive: they cooperate through + // the redirect history threaded on the request context, and the cache + // handler only receives it when the redirect interceptor is composed before + // the cache interceptor. Composing `cache` before `redirect` silently + // disables the cache's redirect-origin guards (cross-origin cache + // poisoning, credential-bearing redirect replay), so fail fast instead of + // storing an attacker-controlled or cross-principal response under a key + // the application trusts. + const cacheIndex = orderSensitiveKinds.indexOf('cache') + const redirectIndex = orderSensitiveKinds.indexOf('redirect') + if (cacheIndex !== -1 && redirectIndex !== -1 && cacheIndex < redirectIndex) { + throw new InvalidArgumentError('the cache interceptor must be composed after the redirect interceptor; composing the cache before the redirect disables the cache\'s cross-origin and credential redirect guards (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG)') + } + const originalDispatch = dispatch const self = this dispatch = function (opts, handler) { diff --git a/deps/undici/src/lib/dispatcher/pool-base.js b/deps/undici/src/lib/dispatcher/pool-base.js index ebd3a52784be..5453fd29c332 100644 --- a/deps/undici/src/lib/dispatcher/pool-base.js +++ b/deps/undici/src/lib/dispatcher/pool-base.js @@ -4,7 +4,8 @@ const { AsyncResource } = require('node:async_hooks') const { PoolStats } = require('../util/stats.js') const DispatcherBase = require('./dispatcher-base') const FixedQueue = require('./fixed-queue') -const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('../core/symbols') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require('../core/symbols') +const { createAbortedController } = require('../core/request') const kClients = Symbol('clients') const kNeedDrain = Symbol('needDrain') @@ -23,6 +24,8 @@ const kAddClient = Symbol('add client') const kRemoveClient = Symbol('remove client') const kRetireClient = Symbol('retire client') const kRetiring = Symbol('retiring clients') +const kShiftQueue = Symbol('shift queue') +const kAbortQueued = Symbol('abort queued') // Closes every live client, including clients that have been // taken out of rotation but are still finishing their own @@ -36,6 +39,8 @@ class QueuedRequest extends AsyncResource { super('UNDICI_POOL_QUEUED_REQUEST') this.opts = opts this.handler = handler + // Cleared once the request leaves the queue, so a late abort is ignored. + this.queued = true } dispatch (dispatcher) { @@ -75,17 +80,15 @@ class PoolBase extends DispatcherBase { return } - const queue = this[kQueue] let needDrain = false this[kOnClientDrain](client) while (!needDrain) { - const item = queue.shift() + const item = this[kShiftQueue]() if (!item) { break } - this[kQueued]-- needDrain = !item.dispatch(client) } @@ -98,7 +101,7 @@ class PoolBase extends DispatcherBase { // negotiated and hit maxConcurrentStreams. Hand the rest to other // clients, creating new ones up to the connection limit, instead of // leaving them for this client to drain one batch at a time. - if (!queue.isEmpty()) { + if (this[kQueued] > 0) { return this[kDrainQueue](origin, targets) } } @@ -108,7 +111,7 @@ class PoolBase extends DispatcherBase { this.emit('drain', origin, [this, ...targets]) } - if (this[kClosedResolve] && queue.isEmpty()) { + if (this[kClosedResolve] && this[kQueued] === 0) { return closeClients(this).then(this[kClosedResolve]) } } @@ -118,23 +121,31 @@ class PoolBase extends DispatcherBase { [kOnClientDrain] () {} [kDrainQueue] (origin, targets) { - const queue = this[kQueue] let hasDispatcher = true - while (!queue.isEmpty()) { - const dispatcher = this[kGetDispatcher]() + while (this[kQueued] > 0) { + let dispatcher + try { + dispatcher = this[kGetDispatcher]() + } catch (err) { + // Selection failed before a dispatcher took ownership of this item. + const item = this[kShiftQueue]() + item.runInAsyncScope(item.handler.onResponseError, item.handler, null, err) + // The error handler may synchronously dispatch and consume capacity. + hasDispatcher = !this.destroyed && this[kHasDispatcher](false) + continue + } if (!dispatcher) { hasDispatcher = false break } - const item = queue.shift() - this[kQueued]-- + const item = this[kShiftQueue]() if (!item.dispatch(dispatcher)) { dispatcher[kNeedDrain] = true this[kOnClientBusy](dispatcher) - hasDispatcher = this[kHasDispatcher]() + hasDispatcher = this[kHasDispatcher](false) if (!hasDispatcher) { break } @@ -146,11 +157,48 @@ class PoolBase extends DispatcherBase { this.emit('drain', origin, [this, ...targets]) } - if (this[kClosedResolve] && queue.isEmpty()) { + if (this[kClosedResolve] && this[kQueued] === 0) { return closeClients(this).then(this[kClosedResolve]) } } + // Aborted requests stay in the queue as tombstones (queued === false) and + // are skipped here; kQueued only counts the live ones. + [kShiftQueue] () { + const queue = this[kQueue] + let item = queue.shift() + while (item !== null && item.queued === false) { + item = queue.shift() + } + + if (item !== null) { + this[kQueued]-- + item.queued = false + } + + return item + } + + // Called through the handler's kQueuedAbort hook when a queued request is + // aborted. + [kAbortQueued] (item, reason) { + if (!item.queued) { + return + } + + const { handler } = item + item.queued = false + item.opts = null + item.handler = null + this[kQueued]-- + + item.runInAsyncScope(handler.onResponseError, handler, createAbortedController(reason), reason) + + if (this[kClosedResolve] && this[kQueued] === 0) { + closeClients(this).then(this[kClosedResolve]) + } + } + [kOnConnect] = (origin, targets) => { this.emit('connect', origin, [this, ...targets]) }; @@ -212,7 +260,7 @@ class PoolBase extends DispatcherBase { } [kClose] () { - if (this[kQueue].isEmpty()) { + if (this[kQueued] === 0) { return closeClients(this) } else { return new Promise((resolve) => { @@ -223,7 +271,7 @@ class PoolBase extends DispatcherBase { [kDestroy] (err) { while (true) { - const item = this[kQueue].shift() + const item = this[kShiftQueue]() if (!item) { break } @@ -244,9 +292,17 @@ class PoolBase extends DispatcherBase { const dispatcher = this[kGetDispatcher]() if (!dispatcher) { + const item = new QueuedRequest(opts, handler) this[kNeedDrain] = true - this[kQueue].push(new QueuedRequest(opts, handler)) + this[kQueue].push(item) this[kQueued]++ + + const onQueued = opts[kQueuedAbort] + if (onQueued !== undefined) { + // Give the handler a way to remove the request from the queue as soon + // as it is aborted. + onQueued((reason) => this[kAbortQueued](item, reason)) + } } else if (!dispatcher.dispatch(opts, handler)) { dispatcher[kNeedDrain] = true this[kOnClientBusy](dispatcher) diff --git a/deps/undici/src/lib/dispatcher/pool.js b/deps/undici/src/lib/dispatcher/pool.js index e44ac84b94fa..3e731b6bea40 100644 --- a/deps/undici/src/lib/dispatcher/pool.js +++ b/deps/undici/src/lib/dispatcher/pool.js @@ -18,7 +18,7 @@ const { InvalidArgumentError } = require('../core/errors') const util = require('../core/util') -const { kConnecting, kHTTPContext, kUrl, kQueued } = require('../core/symbols') +const { kConnecting, kHTTPContext, kHTTP2Session, kRemoteSettings, kUrl, kQueued } = require('../core/symbols') const buildConnector = require('../core/connect') const kOptions = Symbol('options') @@ -116,12 +116,25 @@ class Pool extends PoolBase { } if (client === this[kProtocolProbe]) { - // An h2 Client's drain event releases the requests accumulated during - // negotiation onto that Client. If ALPN selected h1, release the probe - // immediately and restore normal Pool fan-out instead. - if (this[kProtocol] !== 'h2') { - this[kProtocolProbe] = null - this[kDrainQueue](origin, targets.slice(1)) + const releaseProbe = () => { + if (client === this[kProtocolProbe]) { + this[kProtocolProbe] = null + // An empty queue must not release backpressure when this client + // is still saturated and the connection limit prevents fan-out. + // Check capacity without invoking a factory for unused capacity. + if (!this.destroyed && (this[kQueued] > 0 || (!this.closed && this[kHasDispatcher](false)))) { + this[kDrainQueue](origin, targets.slice(1)) + } + } + } + const session = client[kHTTP2Session] + // A peer's stream limit can keep the probe busy indefinitely. Once + // SETTINGS arrive, queued work may need another connection without + // waiting for this client's drain event. + if (this[kProtocol] !== 'h2' || session[kRemoteSettings]) { + releaseProbe() + } else { + session.once('remoteSettings', releaseProbe) } } }) @@ -200,7 +213,7 @@ class Pool extends PoolBase { } } - [kHasDispatcher] () { + [kHasDispatcher] (create = true) { const clientTtlOption = this[kOptions].clientTtl for (let i = 0; i < this[kClients].length; i++) { const client = this[kClients][i] @@ -218,7 +231,7 @@ class Pool extends PoolBase { } if (!this[kConnections] || this[kClients].length < this[kConnections]) { - createClient(this) + if (create) createClient(this) return true } diff --git a/deps/undici/src/lib/dispatcher/proxy-agent.js b/deps/undici/src/lib/dispatcher/proxy-agent.js index 19319ff8d10b..d90ff5930c1c 100644 --- a/deps/undici/src/lib/dispatcher/proxy-agent.js +++ b/deps/undici/src/lib/dispatcher/proxy-agent.js @@ -159,8 +159,10 @@ class ProxyAgent extends DispatcherBase { headers: this[kProxyHeaders], connect, factory: agentFactory, - username: opts.username || username, - password: opts.password || password, + // Socks5ProxyAgent decodes the credentials embedded in the URI; + // the URL getters return them still percent-encoded. + username: opts.username, + password: opts.password, connectTimeout, proxyTls: opts.proxyTls, requestTls: opts.requestTls diff --git a/deps/undici/src/lib/handler/cache-handler.js b/deps/undici/src/lib/handler/cache-handler.js index 20c96def2670..d139853ec59d 100644 --- a/deps/undici/src/lib/handler/cache-handler.js +++ b/deps/undici/src/lib/handler/cache-handler.js @@ -412,7 +412,7 @@ class CacheHandler { deleteCachedValue(this.#store, this.#cacheKey) } - // Don't have anything to tell us this response is cachable and we're not + // Don't have anything to tell us this response is cacheable and we're not // caching by default return downstreamOnHeaders() } diff --git a/deps/undici/src/lib/handler/retry-handler.js b/deps/undici/src/lib/handler/retry-handler.js index b7c458b0ea58..19d2585f5192 100644 --- a/deps/undici/src/lib/handler/retry-handler.js +++ b/deps/undici/src/lib/handler/retry-handler.js @@ -1,7 +1,7 @@ 'use strict' const assert = require('node:assert') -const { kRetryHandlerDefaultRetry } = require('../core/symbols') +const { kRetryHandlerDefaultRetry, kQueuedAbort } = require('../core/symbols') const { RequestRetryError, RequestAbortedError } = require('../core/errors') const { hasSafeIterator, @@ -98,6 +98,11 @@ class RetryController { } class RetryHandler { + // Takes the retry that waits for a connection out of its queue. + #queuedCancel = null + // Whether retries are dispatched with a hook that sets #queuedCancel. + #tracksQueuedRetry = false + constructor (opts, { dispatch, handler }) { const { retryOptions, ...dispatchOpts } = opts const { @@ -561,6 +566,18 @@ class RetryHandler { } } + if (!this.#tracksQueuedRetry) { + // The consumer's controller still targets the earlier attempt, so an + // abort would not reach a retry that waits for a connection. Keep the + // function that takes it out of its queue; the caller's hook still runs. + this.#tracksQueuedRetry = true + const onQueued = this.opts[kQueuedAbort] + this.opts[kQueuedAbort] = (cancel) => { + this.#queuedCancel = cancel + onQueued?.(cancel) + } + } + try { this.retryCountCheckpoint = this.retryCount this.dispatch(this.opts, this) @@ -622,6 +639,15 @@ class RetryHandler { } #onAbort (reason) { + // A retry that waits for a connection is taken out of its queue: its + // dispatcher fails it with an aborted controller, so onResponseError passes + // the abort on instead of retrying. Once the retry started, this does nothing. + const cancel = this.#queuedCancel + if (cancel !== null) { + this.#queuedCancel = null + cancel(reason ?? new RequestAbortedError()) + } + // A consumer abort lands on the controller proxy. If the retry policy is // still deciding (typically holding a backoff timer), cancel the wait and // surface the abort immediately instead of letting the request hang until diff --git a/deps/undici/src/lib/interceptor/cache.js b/deps/undici/src/lib/interceptor/cache.js index 60d2522d1ffe..eb71c531c57c 100644 --- a/deps/undici/src/lib/interceptor/cache.js +++ b/deps/undici/src/lib/interceptor/cache.js @@ -18,7 +18,9 @@ const { isEtagUsable } = require('../util/cache.js') const { AbortError } = require('../core/errors.js') +const { kQueuedAbort } = require('../core/symbols.js') const { parseHttpDate } = require('../util/date.js') +const { kInterceptorKind } = require('../core/symbols.js') /** * @param {(string | RegExp)[] | undefined} origins @@ -541,7 +543,10 @@ function handleResult ( dispatch( { ...opts, - headers + headers, + // The revalidation is not the caller's request: aborting the + // caller must not cancel it while it waits for a connection. + [kQueuedAbort]: undefined }, new CacheHandler(globalOpts, cacheKey, { // Silent handler that just updates the cache @@ -665,7 +670,7 @@ module.exports = (opts = {}) => { } } - return (dispatch, interceptorOrigin) => { + const interceptor = (dispatch, interceptorOrigin) => { return (opts, handler) => { const requestOrigin = getInterceptorOrigin(opts, interceptorOrigin) if (!requestOrigin || arrayIncludes(safeMethodsToNotCache, opts.method)) { @@ -768,4 +773,6 @@ module.exports = (opts = {}) => { } } } + interceptor[kInterceptorKind] = 'cache' + return interceptor } diff --git a/deps/undici/src/lib/interceptor/decompress.js b/deps/undici/src/lib/interceptor/decompress.js index 0b6d2bcc0cf9..835c9fa7794f 100644 --- a/deps/undici/src/lib/interceptor/decompress.js +++ b/deps/undici/src/lib/interceptor/decompress.js @@ -105,8 +105,6 @@ function createMaxSizeLimiter (maxSize) { }) } -let warningEmitted = /** @type {boolean} */ (false) - /** * @typedef {Object} DecompressHandlerOptions * @property {number[]|Readonly<number[]>} [skipStatusCodes=[204, 304]] - List of status codes to skip decompression for @@ -550,15 +548,6 @@ class DecompressHandler extends DecoratorHandler { * @returns {Function} - Interceptor function */ function createDecompressInterceptor (options = {}) { - // Emit experimental warning only once - if (!warningEmitted) { - process.emitWarning( - 'DecompressInterceptor is experimental and subject to change', - 'ExperimentalWarning' - ) - warningEmitted = true - } - return (dispatch) => { return (opts, handler) => { if (opts.method === 'HEAD') { diff --git a/deps/undici/src/lib/interceptor/deduplicate.js b/deps/undici/src/lib/interceptor/deduplicate.js index 12598130e8f9..c8e5b934c5a6 100644 --- a/deps/undici/src/lib/interceptor/deduplicate.js +++ b/deps/undici/src/lib/interceptor/deduplicate.js @@ -4,6 +4,7 @@ const diagnosticsChannel = require('node:diagnostics_channel') const util = require('../core/util') const DeduplicationHandler = require('../handler/deduplication-handler') const { getInterceptorOrigin, normalizeHeaders, makeCacheKey, makeDeduplicationKey } = require('../util/cache.js') +const { kInterceptorKind } = require('../core/symbols.js') const pendingRequestsChannel = diagnosticsChannel.channel('undici:request:pending-requests') @@ -57,7 +58,7 @@ module.exports = (opts = {}) => { */ const pendingRequests = new Map() - return (dispatch, interceptorOrigin) => { + const interceptor = (dispatch, interceptorOrigin) => { return (opts, handler) => { const requestOrigin = getInterceptorOrigin(opts, interceptorOrigin) if (!requestOrigin || opts.upgrade || methods.includes(opts.method) === false) { @@ -115,4 +116,6 @@ module.exports = (opts = {}) => { return dispatch(opts, deduplicationHandler) } } + interceptor[kInterceptorKind] = 'deduplicate' + return interceptor } diff --git a/deps/undici/src/lib/interceptor/redirect.js b/deps/undici/src/lib/interceptor/redirect.js index 34e9b3211978..d772100be9aa 100644 --- a/deps/undici/src/lib/interceptor/redirect.js +++ b/deps/undici/src/lib/interceptor/redirect.js @@ -1,9 +1,10 @@ 'use strict' const RedirectHandler = require('../handler/redirect-handler') +const { kInterceptorKind } = require('../core/symbols.js') function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, throwOnMaxRedirect: defaultThrowOnMaxRedirect, stripHeadersOnRedirect: defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect: defaultStripHeadersOnCrossOriginRedirect } = {}) { - return (dispatch) => { + const interceptor = (dispatch) => { return function Intercept (opts, handler) { const { maxRedirections = defaultMaxRedirections, throwOnMaxRedirect = defaultThrowOnMaxRedirect, stripHeadersOnRedirect = defaultStripHeadersOnRedirect, stripHeadersOnCrossOriginRedirect = defaultStripHeadersOnCrossOriginRedirect, ...rest } = opts @@ -16,6 +17,8 @@ function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections, t return dispatch(dispatchOpts, redirectHandler) } } + interceptor[kInterceptorKind] = 'redirect' + return interceptor } module.exports = createRedirectInterceptor diff --git a/deps/undici/src/lib/util/cache.js b/deps/undici/src/lib/util/cache.js index 12f29e9181fe..9aabf188d558 100644 --- a/deps/undici/src/lib/util/cache.js +++ b/deps/undici/src/lib/util/cache.js @@ -650,7 +650,7 @@ function isInvalidOrWildcardVaryHeader (varyHeader) { /** * Note: this deviates from the spec a little. Empty etags ("", W/"") are valid, - * however, including them in cached resposnes serves little to no purpose. + * however, including them in cached responses serves little to no purpose. * * @see https://www.rfc-editor.org/rfc/rfc9110.html#name-etag * diff --git a/deps/undici/src/lib/util/timers.js b/deps/undici/src/lib/util/timers.js index 14984d42ef29..11ac022995d0 100644 --- a/deps/undici/src/lib/util/timers.js +++ b/deps/undici/src/lib/util/timers.js @@ -194,7 +194,7 @@ function refreshTimeout () { // method (e.g. mocked timers in tests). if (fastNowTimeout?.refresh) { fastNowTimeout.refresh() - // fastNowTimeout is not instantiated yet or refresh is not availabe, + // fastNowTimeout is not instantiated yet or refresh is not available, // create a new Timer. } else { clearTimeout(fastNowTimeout) diff --git a/deps/undici/src/lib/web/fetch/formdata.js b/deps/undici/src/lib/web/fetch/formdata.js index e7b8c4c3fb21..c42deafe2d75 100644 --- a/deps/undici/src/lib/web/fetch/formdata.js +++ b/deps/undici/src/lib/web/fetch/formdata.js @@ -163,19 +163,12 @@ class FormData { } [nodeUtil.inspect.custom] (depth, options) { - const state = this.#state.reduce((a, b) => { - if (a[b.name]) { - if (Array.isArray(a[b.name])) { - a[b.name].push(b.value) - } else { - a[b.name] = [a[b.name], b.value] - } - } else { - a[b.name] = b.value - } - - return a - }, { __proto__: null }) + const state = Object.groupBy(this.#state, ({ name }) => name) + for (const [name, entries] of Object.entries(state)) { + state[name] = entries.length === 1 + ? entries[0].value + : entries.map(({ value }) => value) + } options.depth ??= depth options.colors ??= true diff --git a/deps/undici/src/lib/web/fetch/index.js b/deps/undici/src/lib/web/fetch/index.js index b90f6c8d866d..f65afa1f9cb2 100644 --- a/deps/undici/src/lib/web/fetch/index.js +++ b/deps/undici/src/lib/web/fetch/index.js @@ -59,7 +59,7 @@ const { const EE = require('node:events') const { Readable, pipeline, finished, isErrored, isReadable } = require('node:stream') const { addAbortListener, bufferToLowerCasedHeaderName } = require('../../core/util') -const { SocketError } = require('../../core/errors') +const { SocketError, InformationalError } = require('../../core/errors') const { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require('./data-url') const { getGlobalDispatcher } = require('../../global') const { webidl } = require('../webidl') @@ -2333,6 +2333,10 @@ async function httpNetworkFetch ( } } + // The response will be exposed without a body, so any content the + // server sends is disregarded (see main fetch step 19). + this.nullBodyStatus = nullBodyStatus.includes(status) + this.body = new Readable({ read: () => controller.resume() }) const onError = (err) => this.onResponseError(controller, err) @@ -2352,6 +2356,14 @@ async function httpNetworkFetch ( }, onResponseData (controller, chunk) { + if (this.nullBodyStatus) { + // The server sent content in a response that must not have any. + // Nobody can read it, so close the connection instead of waiting + // for the server to finish sending it. + controller.abort(new InformationalError('response with null body status has content')) + return + } + if (fetchParams.controller.dump) { return } @@ -2391,6 +2403,13 @@ async function httpNetworkFetch ( fetchParams.controller.off('terminated', this.abort) } + if (this.nullBodyStatus) { + // The response has no body, so a failure while receiving the + // disregarded content must not turn it into a network error. + this.body?.destroy() + return + } + if ( request.mode === 'websocket' && allowH2 !== false && diff --git a/deps/undici/src/lib/web/fetch/util.js b/deps/undici/src/lib/web/fetch/util.js index c51c89d2fb40..46c50d439392 100644 --- a/deps/undici/src/lib/web/fetch/util.js +++ b/deps/undici/src/lib/web/fetch/util.js @@ -560,7 +560,7 @@ function stripURLForReferrer (url, originOnly = false) { return url } -const isPotentialleTrustworthyIPv4 = RegExp.prototype.test +const isPotentiallyTrustworthyIPv4 = RegExp.prototype.test .bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/) const isPotentiallyTrustworthyIPv6 = RegExp.prototype.test @@ -583,7 +583,7 @@ function isOriginIPPotentiallyTrustworthy (origin) { } // IPv4 - return isPotentialleTrustworthyIPv4(origin) + return isPotentiallyTrustworthyIPv4(origin) } /** diff --git a/deps/undici/src/package-lock.json b/deps/undici/src/package-lock.json index 63b2cd1746ad..f2c4547fb1aa 100644 --- a/deps/undici/src/package-lock.json +++ b/deps/undici/src/package-lock.json @@ -1,15 +1,15 @@ { "name": "undici", - "version": "8.12.4", + "version": "8.13.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "undici", - "version": "8.12.4", + "version": "8.13.1", "license": "MIT", "devDependencies": { - "@fastify/busboy": "3.2.4", + "@fastify/busboy": "3.2.5", "@matteo.collina/tspl": "^0.2.0", "@metcoder95/https-pem": "^1.0.0", "@sinonjs/fake-timers": "^12.0.0", @@ -1131,20 +1131,37 @@ } }, "node_modules/@eslint/config-array": { - "version": "0.23.5", - "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", - "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "version": "0.23.6", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.6.tgz", + "integrity": "sha512-WrTH7nioI9QPY4NZGnsywmecswJdgeq4BCM76qok9VgjTO29ZgUzUvcuJLVPYVQM4uDbaPBU0M33R9DIxI8X3w==", "dev": true, "license": "Apache-2.0", "dependencies": { "@eslint/object-schema": "^3.0.5", "debug": "^4.3.1", - "minimatch": "^10.2.4" + "minimatch": "^11.0.5" }, "engines": { "node": "^20.19.0 || ^22.13.0 || >=24" } }, + "node_modules/@eslint/config-array/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@eslint/config-helpers": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.7.0.tgz", @@ -1196,9 +1213,9 @@ } }, "node_modules/@fastify/busboy": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.4.tgz", - "integrity": "sha512-lQS8xcXT54rdJb+wlG/Q7SMSdtkZEpLPHooSDUZyyZm9LJD7X1kONPhVoPaHq+dsPtWUGGLIz9gBNhs9qKbylw==", + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-3.2.5.tgz", + "integrity": "sha512-y8MTAeBlEQUNVnskmZQwpseZN3EgCksQNOULlfxWY6o6VEqh01+oExMgbM7gN6YLQ8pNDYeweNPKJRt8jQm2ZQ==", "dev": true, "license": "MIT" }, @@ -1297,6 +1314,13 @@ "node": ">=12" } }, + "node_modules/@isaacs/nonrecursive-glob-match": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@isaacs/nonrecursive-glob-match/-/nonrecursive-glob-match-1.1.0.tgz", + "integrity": "sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==", + "dev": true, + "license": "BlueOak-1.0.0" + }, "node_modules/@istanbuljs/load-nyc-config": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", @@ -4557,9 +4581,9 @@ } }, "node_modules/eslint": { - "version": "10.13.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.13.0.tgz", - "integrity": "sha512-UohDjD4zSzEwhf58M3O7vc/ycc8O1I7dNlhtD0WxE8Px8EHNJKtUwzBqrzeGhisRuv2ag4sAYswszCJRgKXYUg==", + "version": "10.15.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.15.0.tgz", + "integrity": "sha512-+5Wg4p+ze3sG1WErYgUO/3H1IQIfFBymVUA0Fo/XTeBOLS6UQIUekpSJ8sdRkn7O7wjh84b55w/roqavH2aScg==", "dev": true, "license": "MIT", "workspaces": [ @@ -4568,11 +4592,11 @@ "dependencies": { "@eslint-community/eslint-utils": "^4.8.0", "@eslint-community/regexpp": "^4.12.2", - "@eslint/config-array": "^0.23.5", + "@eslint/config-array": "^0.23.6", "@eslint/config-helpers": "^0.7.0", "@eslint/core": "^1.2.1", "@eslint/plugin-kit": "^0.7.3", - "@humanfs/node": "^0.16.6", + "@humanfs/node": "^0.16.8", "@humanwhocodes/module-importer": "^1.0.1", "@humanwhocodes/retry": "^0.4.2", "@types/estree": "^1.0.6", @@ -4593,7 +4617,7 @@ "imurmurhash": "^0.1.4", "is-glob": "^4.0.0", "json-stable-stringify-without-jsonify": "^1.0.1", - "minimatch": "^10.2.5", + "minimatch": "^11.0.5", "natural-compare": "^1.4.0", "optionator": "^0.9.3" }, @@ -4942,6 +4966,23 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/eslint/node_modules/minimatch": { + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/nonrecursive-glob-match": "^1.1.0", + "brace-expansion": "^5.0.12" + }, + "engines": { + "node": "20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/eslint/node_modules/p-locate": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", @@ -7195,9 +7236,9 @@ "license": "MIT" }, "node_modules/node-forge": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.2.tgz", - "integrity": "sha512-rRtAR5XLJ8gCKd9du4qrKAsgCG1ObGP4gLeNJMa4vYSeq4bmBMOJk5IHkrviBV0q7uoAJlVd8HEQYQSVUb4FGQ==", + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-1.4.3.tgz", + "integrity": "sha512-P6wzfh6t70avmV8FrVEAd/36sOPJQ+hkaJVX1Laap9J/77m7M0eyozDvc8SwnDf4P7MP94gwbAAo0rg3YVXT+g==", "dev": true, "license": "(BSD-3-Clause OR GPL-2.0)", "engines": { @@ -9032,9 +9073,9 @@ } }, "node_modules/ws": { - "version": "8.22.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", - "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", "dev": true, "license": "MIT", "engines": { diff --git a/deps/undici/src/package.json b/deps/undici/src/package.json index d05d075a005b..ba9f11bd61e0 100644 --- a/deps/undici/src/package.json +++ b/deps/undici/src/package.json @@ -1,6 +1,6 @@ { "name": "undici", - "version": "8.12.4", + "version": "8.13.1", "description": "An HTTP/1.1 client, written from scratch for Node.js", "homepage": "https://undici.nodejs.org", "bugs": { @@ -93,7 +93,7 @@ "test:node-test": "borp --timeout 180000 -p \"test/node-test/**/*.js\"", "test:tdd": "borp --timeout 180000 --expose-gc -p \"test/*.js\"", "test:tdd:node-test": "borp --timeout 180000 -p \"test/node-test/**/*.js\" -w", - "test:typescript": "tsd && tsc test/imports/undici-import.ts --typeRoots ./types --noEmit && tsc ./types/*.d.ts --noEmit --typeRoots ./types", + "test:typescript": "tsd && tsc test/imports/undici-import.ts --typeRoots ./types --noEmit && tsc -p tsconfig.types.json", "test:webidl": "borp --timeout 180000 -p \"test/webidl/*.js\"", "test:websocket": "borp --timeout 180000 -p \"test/websocket/**/*.js\"", "test:websocket:autobahn": "node test/autobahn/client.js", @@ -111,7 +111,7 @@ "prepare": "husky && node ./scripts/platform-shell.js" }, "devDependencies": { - "@fastify/busboy": "3.2.4", + "@fastify/busboy": "3.2.5", "@matteo.collina/tspl": "^0.2.0", "@metcoder95/https-pem": "^1.0.0", "@sinonjs/fake-timers": "^12.0.0", diff --git a/deps/undici/src/tsconfig.types.json b/deps/undici/src/tsconfig.types.json new file mode 100644 index 000000000000..8ae81f8b2611 --- /dev/null +++ b/deps/undici/src/tsconfig.types.json @@ -0,0 +1,7 @@ +{ + "compilerOptions": { + "noEmit": true, + "typeRoots": ["./types"] + }, + "include": ["types/**/*.d.ts"] +} diff --git a/deps/undici/src/types/retry-handler.d.ts b/deps/undici/src/types/retry-handler.d.ts index 180cde921664..ccb73c86282f 100644 --- a/deps/undici/src/types/retry-handler.d.ts +++ b/deps/undici/src/types/retry-handler.d.ts @@ -78,7 +78,7 @@ declare namespace RetryHandler { */ minTimeout?: number; /** - * Factior to multiply the timeout factor between retries. + * Factor to multiply the timeout factor between retries. * * @type {number} * @memberof RetryOptions diff --git a/deps/undici/undici.js b/deps/undici/undici.js index 552dafce800f..f2aca61248ba 100644 --- a/deps/undici/undici.js +++ b/deps/undici/undici.js @@ -615,6 +615,7 @@ var require_symbols = __commonJS({ kMaxResponseSize: /* @__PURE__ */ Symbol("max response size"), kHTTP2Session: /* @__PURE__ */ Symbol("http2Session"), kHTTP2Options: /* @__PURE__ */ Symbol("http2 options"), + kQueuedAbort: /* @__PURE__ */ Symbol("queued abort"), kHTTP2SessionState: /* @__PURE__ */ Symbol("http2Session state"), kRetryHandlerDefaultRetry: /* @__PURE__ */ Symbol("retry agent default retry"), kConstruct: /* @__PURE__ */ Symbol("constructable"), @@ -632,7 +633,8 @@ var require_symbols = __commonJS({ kNoProxyAgent: /* @__PURE__ */ Symbol("no proxy agent"), kHttpProxyAgent: /* @__PURE__ */ Symbol("http proxy agent"), kHttpsProxyAgent: /* @__PURE__ */ Symbol("https proxy agent"), - kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent") + kSocks5ProxyAgent: /* @__PURE__ */ Symbol("socks5 proxy agent"), + kInterceptorKind: /* @__PURE__ */ Symbol("interceptor kind") }; } }); @@ -642,7 +644,8 @@ var require_dispatcher = __commonJS({ "lib/dispatcher/dispatcher.js"(exports2, module2) { "use strict"; var EventEmitter = require("node:events"); - var { kOriginless, kUrl } = require_symbols(); + var { InvalidArgumentError } = require_errors(); + var { kOriginless, kUrl, kInterceptorKind } = require_symbols(); var Dispatcher2 = class extends EventEmitter { static { __name(this, "Dispatcher"); @@ -660,6 +663,7 @@ var require_dispatcher = __commonJS({ const interceptors = Array.isArray(args[0]) ? args[0] : args; const interceptorOrigin = this[kOriginless] === true ? null : this[kUrl]?.origin; let dispatch = this.dispatch.bind(this); + const orderSensitiveKinds = []; for (const interceptor of interceptors) { if (interceptor == null) { continue; @@ -667,11 +671,19 @@ var require_dispatcher = __commonJS({ if (typeof interceptor !== "function") { throw new TypeError(`invalid interceptor, expected function received ${typeof interceptor}`); } + if (interceptor[kInterceptorKind] != null) { + orderSensitiveKinds.push(interceptor[kInterceptorKind]); + } dispatch = interceptor(dispatch, interceptorOrigin); if (dispatch == null || typeof dispatch !== "function" || dispatch.length !== 2) { throw new TypeError("invalid interceptor"); } } + const cacheIndex = orderSensitiveKinds.indexOf("cache"); + const redirectIndex = orderSensitiveKinds.indexOf("redirect"); + if (cacheIndex !== -1 && redirectIndex !== -1 && cacheIndex < redirectIndex) { + throw new InvalidArgumentError("the cache interceptor must be composed after the redirect interceptor; composing the cache before the redirect disables the cache's cross-origin and credential redirect guards (GHSA-75VM-9G8F-99J4, GHSA-MQG3-3V4R-CM32, GHSA-4W7W-5XRC-9H26, GHSA-7XG3-FPHP-28HG)"); + } const originalDispatch = dispatch; const self = this; dispatch = /* @__PURE__ */ __name(function(opts, handler) { @@ -970,7 +982,7 @@ var require_dispatcher_base = __commonJS({ throw err; } handler.onResponseError(null, err); - return false; + return true; } } }; @@ -1095,747 +1107,464 @@ var require_fixed_queue = __commonJS({ } }); -// lib/dispatcher/pool-base.js -var require_pool_base = __commonJS({ - "lib/dispatcher/pool-base.js"(exports2, module2) { +// lib/util/timers.js +var require_timers = __commonJS({ + "lib/util/timers.js"(exports2, module2) { "use strict"; - var { AsyncResource } = require("node:async_hooks"); - var { PoolStats } = require_stats(); - var DispatcherBase = require_dispatcher_base(); - var FixedQueue = require_fixed_queue(); - var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require_symbols(); - var kClients = /* @__PURE__ */ Symbol("clients"); - var kNeedDrain = /* @__PURE__ */ Symbol("needDrain"); - var kQueue = /* @__PURE__ */ Symbol("queue"); - var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve"); - var kOnDrain = /* @__PURE__ */ Symbol("onDrain"); - var kOnConnect = /* @__PURE__ */ Symbol("onConnect"); - var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect"); - var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError"); - var kOnClientBusy = /* @__PURE__ */ Symbol("on client busy"); - var kOnClientDrain = /* @__PURE__ */ Symbol("on client drain"); - var kDrainQueue = /* @__PURE__ */ Symbol("drain queue"); - var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher"); - var kHasDispatcher = /* @__PURE__ */ Symbol("has dispatcher"); - var kAddClient = /* @__PURE__ */ Symbol("add client"); - var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); - var kRetireClient = /* @__PURE__ */ Symbol("retire client"); - var kRetiring = /* @__PURE__ */ Symbol("retiring clients"); - var QueuedRequest = class extends AsyncResource { - static { - __name(this, "QueuedRequest"); - } - constructor(opts, handler) { - super("UNDICI_POOL_QUEUED_REQUEST"); - this.opts = opts; - this.handler = handler; - } - dispatch(dispatcher) { - return this.runInAsyncScope(dispatcher.dispatch, dispatcher, this.opts, this.handler); - } - }; - function closeClients(pool) { - const closeAll = []; - for (let i = 0; i < pool[kClients].length; i++) { - const client = pool[kClients][i]; - if (!client.destroyed) { - closeAll.push(client.close()); - } - } - for (const closed of pool[kRetiring].values()) { - closeAll.push(closed); - } - return Promise.all(closeAll); - } - __name(closeClients, "closeClients"); - var PoolBase = class extends DispatcherBase { - static { - __name(this, "PoolBase"); - } - [kQueue] = new FixedQueue(); - [kQueued] = 0; - [kClients] = []; - // Clients removed from kClients that have not finished closing, - // mapped to a promise that settles once they have. - [kRetiring] = /* @__PURE__ */ new Map(); - [kNeedDrain] = false; - [kOnDrain](client, origin, targets) { - if (client.closed || client.destroyed) { - return; - } - const queue = this[kQueue]; - let needDrain = false; - this[kOnClientDrain](client); - while (!needDrain) { - const item = queue.shift(); - if (!item) { - break; - } - this[kQueued]--; - needDrain = !item.dispatch(client); + var fastNow = 0; + var RESOLUTION_MS = 1e3; + var TICK_MS = (RESOLUTION_MS >> 1) - 1; + var fastNowTimeout; + var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer"); + var fastTimers = []; + var NOT_IN_LIST = -2; + var TO_BE_CLEARED = -1; + var PENDING = 0; + var ACTIVE = 1; + function onTick() { + fastNow += TICK_MS; + let idx = 0; + let len = fastTimers.length; + while (idx < len) { + const timer = fastTimers[idx]; + if (timer._state === PENDING) { + timer._idleStart = fastNow - TICK_MS; + timer._state = ACTIVE; + } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) { + timer._state = TO_BE_CLEARED; + timer._idleStart = -1; + timer._onTimeout(timer._timerArg); } - client[kNeedDrain] = needDrain; - if (needDrain) { - this[kOnClientBusy](client); - if (!queue.isEmpty()) { - return this[kDrainQueue](origin, targets); + if (timer._state === TO_BE_CLEARED) { + timer._state = NOT_IN_LIST; + if (--len !== 0) { + fastTimers[idx] = fastTimers[len]; } - } - if (!needDrain && this[kNeedDrain]) { - this[kNeedDrain] = false; - this.emit("drain", origin, [this, ...targets]); - } - if (this[kClosedResolve] && queue.isEmpty()) { - return closeClients(this).then(this[kClosedResolve]); + } else { + ++idx; } } - [kOnClientBusy]() { + fastTimers.length = len; + if (fastTimers.length !== 0) { + refreshTimeout(); } - [kOnClientDrain]() { + } + __name(onTick, "onTick"); + function refreshTimeout() { + if (fastNowTimeout?.refresh) { + fastNowTimeout.refresh(); + } else { + clearTimeout(fastNowTimeout); + fastNowTimeout = setTimeout(onTick, TICK_MS); + fastNowTimeout?.unref(); } - [kDrainQueue](origin, targets) { - const queue = this[kQueue]; - let hasDispatcher = true; - while (!queue.isEmpty()) { - const dispatcher = this[kGetDispatcher](); - if (!dispatcher) { - hasDispatcher = false; - break; - } - const item = queue.shift(); - this[kQueued]--; - if (!item.dispatch(dispatcher)) { - dispatcher[kNeedDrain] = true; - this[kOnClientBusy](dispatcher); - hasDispatcher = this[kHasDispatcher](); - if (!hasDispatcher) { - break; - } - } - } - if (hasDispatcher && this[kNeedDrain]) { - this[kNeedDrain] = false; - this.emit("drain", origin, [this, ...targets]); - } - if (this[kClosedResolve] && queue.isEmpty()) { - return closeClients(this).then(this[kClosedResolve]); - } + } + __name(refreshTimeout, "refreshTimeout"); + var FastTimer = class { + static { + __name(this, "FastTimer"); } - [kOnConnect] = (origin, targets) => { - this.emit("connect", origin, [this, ...targets]); - }; - [kOnDisconnect] = (origin, targets, err) => { - this.emit("disconnect", origin, [this, ...targets], err); - }; - [kOnConnectionError] = (origin, targets, err) => { - this.emit("connectionError", origin, [this, ...targets], err); - }; - get [kBusy]() { - return this[kNeedDrain]; + [kFastTimer] = true; + /** + * The state of the timer, which can be one of the following: + * - NOT_IN_LIST (-2) + * - TO_BE_CLEARED (-1) + * - PENDING (0) + * - ACTIVE (1) + * + * @type {-2|-1|0|1} + * @private + */ + _state = NOT_IN_LIST; + /** + * The number of milliseconds to wait before calling the callback. + * + * @type {number} + * @private + */ + _idleTimeout = -1; + /** + * The time in milliseconds when the timer was started. This value is used to + * calculate when the timer should expire. + * + * @type {number} + * @default -1 + * @private + */ + _idleStart = -1; + /** + * The function to be executed when the timer expires. + * @type {Function} + * @private + */ + _onTimeout; + /** + * The argument to be passed to the callback when the timer expires. + * + * @type {*} + * @private + */ + _timerArg; + /** + * @constructor + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should wait + * before the specified function or code is executed. + * @param {*} arg + */ + constructor(callback, delay, arg) { + this._onTimeout = callback; + this._idleTimeout = delay; + this._timerArg = arg; + this.refresh(); } - get [kConnected]() { - let ret = 0; - for (const { [kConnected]: connected } of this[kClients]) { - ret += connected; + /** + * Sets the timer's start time to the current time, and reschedules the timer + * to call its callback at the previously specified duration adjusted to the + * current time. + * Using this on a timer that has already called its callback will reactivate + * the timer. + * + * @returns {void} + */ + refresh() { + if (this._state === NOT_IN_LIST) { + fastTimers.push(this); } - return ret; - } - get [kFree]() { - let ret = 0; - for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) { - ret += connected && !needDrain; + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout(); } - return ret; + this._state = PENDING; } - get [kPending]() { - let ret = this[kQueued]; - for (const { [kPending]: pending } of this[kClients]) { - ret += pending; - } - return ret; + /** + * The `clear` method cancels the timer, preventing it from executing. + * + * @returns {void} + * @private + */ + clear() { + this._state = TO_BE_CLEARED; + this._idleStart = -1; } - get [kRunning]() { - let ret = 0; - for (const { [kRunning]: running } of this[kClients]) { - ret += running; + }; + module2.exports = { + /** + * The setTimeout() method sets a timer which executes a function once the + * timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {NodeJS.Timeout|FastTimer} + */ + setTimeout(callback, delay, arg) { + return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg); + }, + /** + * The clearTimeout method cancels an instantiated Timer previously created + * by calling setTimeout. + * + * @param {NodeJS.Timeout|FastTimer} timeout + */ + clearTimeout(timeout) { + if (timeout[kFastTimer]) { + timeout.clear(); + } else { + clearTimeout(timeout); } - return ret; + }, + /** + * The setFastTimeout() method sets a fastTimer which executes a function once + * the timer expires. + * @param {Function} callback A function to be executed after the timer + * expires. + * @param {number} delay The time, in milliseconds that the timer should + * wait before the specified function or code is executed. + * @param {*} [arg] An optional argument to be passed to the callback function + * when the timer expires. + * @returns {FastTimer} + */ + setFastTimeout(callback, delay, arg) { + return new FastTimer(callback, delay, arg); + }, + /** + * The clearTimeout method cancels an instantiated FastTimer previously + * created by calling setFastTimeout. + * + * @param {FastTimer} timeout + */ + clearFastTimeout(timeout) { + timeout.clear(); + }, + /** + * The now method returns the value of the internal fast timer clock. + * + * @returns {number} + */ + now() { + return fastNow; + }, + /** + * Trigger the onTick function to process the fastTimers array. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + * @param {number} [delay=0] The delay in milliseconds to add to the now value. + */ + tick(delay = 0) { + fastNow += delay - RESOLUTION_MS + 1; + onTick(); + onTick(); + }, + /** + * Reset FastTimers. + * Exported for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + reset() { + fastNow = 0; + fastTimers.length = 0; + clearTimeout(fastNowTimeout); + fastNowTimeout = null; + }, + /** + * Exporting for testing purposes only. + * Marking as deprecated to discourage any use outside of testing. + * @deprecated + */ + kFastTimer + }; + } +}); + +// lib/core/tree.js +var require_tree = __commonJS({ + "lib/core/tree.js"(exports2, module2) { + "use strict"; + var { + wellknownHeaderNames, + headerNameLowerCasedRecord + } = require_constants(); + var TstNode = class _TstNode { + static { + __name(this, "TstNode"); } - get [kSize]() { - let ret = this[kQueued]; - for (const { [kSize]: size } of this[kClients]) { - ret += size; + /** @type {any} */ + value = null; + /** @type {null | TstNode} */ + left = null; + /** @type {null | TstNode} */ + middle = null; + /** @type {null | TstNode} */ + right = null; + /** @type {number} */ + code; + /** + * @param {string} key + * @param {any} value + * @param {number} index + */ + constructor(key, value, index) { + if (index === void 0 || index >= key.length) { + throw new TypeError("Unreachable"); } - return ret; - } - get stats() { - return new PoolStats(this); - } - [kClose]() { - if (this[kQueue].isEmpty()) { - return closeClients(this); + const code = this.code = key.charCodeAt(index); + if (code > 127) { + throw new TypeError("key must be ascii string"); + } + if (key.length !== ++index) { + this.middle = new _TstNode(key, value, index); } else { - return new Promise((resolve) => { - this[kClosedResolve] = resolve; - }); + this.value = value; } } - [kDestroy](err) { + /** + * @param {string} key + * @param {any} value + * @returns {void} + */ + add(key, value) { + const length = key.length; + if (length === 0) { + throw new TypeError("Unreachable"); + } + let index = 0; + let node = this; while (true) { - const item = this[kQueue].shift(); - if (!item) { + const code = key.charCodeAt(index); + if (code > 127) { + throw new TypeError("key must be ascii string"); + } + if (node.code === code) { + if (length === ++index) { + node.value = value; + break; + } else if (node.middle !== null) { + node = node.middle; + } else { + node.middle = new _TstNode(key, value, index); + break; + } + } else if (node.code < code) { + if (node.left !== null) { + node = node.left; + } else { + node.left = new _TstNode(key, value, index); + break; + } + } else if (node.right !== null) { + node = node.right; + } else { + node.right = new _TstNode(key, value, index); break; } - item.handler.onResponseError(null, err); - } - const destroyAll = new Array(this[kClients].length); - for (let i = 0; i < this[kClients].length; i++) { - destroyAll[i] = this[kClients][i].destroy(err); - } - for (const client of this[kRetiring].keys()) { - destroyAll.push(client.destroy(err)); - } - return Promise.all(destroyAll); - } - [kDispatch](opts, handler) { - const dispatcher = this[kGetDispatcher](); - if (!dispatcher) { - this[kNeedDrain] = true; - this[kQueue].push(new QueuedRequest(opts, handler)); - this[kQueued]++; - } else if (!dispatcher.dispatch(opts, handler)) { - dispatcher[kNeedDrain] = true; - this[kOnClientBusy](dispatcher); - this[kNeedDrain] = !this[kHasDispatcher](); } - return !this[kNeedDrain]; } - [kHasDispatcher]() { - for (let i = 0; i < this[kClients].length; i++) { - const dispatcher = this[kClients][i]; - if (!dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true) { - return true; + /** + * @param {Uint8Array} key + * @returns {TstNode | null} + */ + search(key) { + const keylength = key.length; + let index = 0; + let node = this; + while (node !== null && index < keylength) { + let code = key[index]; + if (code <= 90 && code >= 65) { + code |= 32; + } + while (node !== null) { + if (code === node.code) { + if (keylength === ++index) { + return node; + } + node = node.middle; + break; + } + node = node.code < code ? node.left : node.right; } } - return false; + return null; } - [kAddClient](client) { - client.on("drain", this[kOnDrain].bind(this, client)).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]); - this[kClients].push(client); - if (this[kNeedDrain]) { - queueMicrotask(() => { - if (this[kNeedDrain] && !client[kNeedDrain]) { - this[kOnDrain](client, client[kUrl], [client, this]); - } - }); - } - return this; + }; + var TernarySearchTree = class { + static { + __name(this, "TernarySearchTree"); } - // Takes a client out of rotation. A closed client no longer takes requests - // from the pool queue (see kOnDrain), but it finishes the requests it - // already has. Until it has, pool.close() waits for it and pool.destroy() - // destroys it. - [kRetireClient](client) { - const idx = this[kClients].indexOf(client); - if (idx !== -1) { - this[kClients].splice(idx, 1); - } - if (client.destroyed || this[kRetiring].has(client)) { - return; + /** @type {TstNode | null} */ + node = null; + /** + * @param {string} key + * @param {any} value + * @returns {void} + * */ + insert(key, value) { + if (this.node === null) { + this.node = new TstNode(key, value, 0); + } else { + this.node.add(key, value); } - let done = false; - let resolveClosed; - const closed = new Promise((resolve) => { - resolveClosed = resolve; - }); - this[kRetiring].set(client, closed); - client.close(() => { - if (!done) { - done = true; - this[kRetiring].delete(client); - resolveClosed(); - } - }); } - [kRemoveClient](client) { - this[kRetireClient](client); - this[kNeedDrain] = !this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true); + /** + * @param {Uint8Array} key + * @returns {any} + */ + lookup(key) { + return this.node?.search(key)?.value ?? null; } }; + var tree = new TernarySearchTree(); + for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]; + tree.insert(key, key); + } module2.exports = { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kRetireClient, - kDrainQueue, - kOnClientBusy, - kOnClientDrain, - kGetDispatcher, - kHasDispatcher + TernarySearchTree, + tree }; } }); -// lib/util/timers.js -var require_timers = __commonJS({ - "lib/util/timers.js"(exports2, module2) { +// lib/core/util.js +var require_util = __commonJS({ + "lib/core/util.js"(exports2, module2) { "use strict"; - var fastNow = 0; - var RESOLUTION_MS = 1e3; - var TICK_MS = (RESOLUTION_MS >> 1) - 1; - var fastNowTimeout; - var kFastTimer = /* @__PURE__ */ Symbol("kFastTimer"); - var fastTimers = []; - var NOT_IN_LIST = -2; - var TO_BE_CLEARED = -1; - var PENDING = 0; - var ACTIVE = 1; - function onTick() { - fastNow += TICK_MS; - let idx = 0; - let len = fastTimers.length; - while (idx < len) { - const timer = fastTimers[idx]; - if (timer._state === PENDING) { - timer._idleStart = fastNow - TICK_MS; - timer._state = ACTIVE; - } else if (timer._state === ACTIVE && fastNow >= timer._idleStart + timer._idleTimeout) { - timer._state = TO_BE_CLEARED; - timer._idleStart = -1; - timer._onTimeout(timer._timerArg); - } - if (timer._state === TO_BE_CLEARED) { - timer._state = NOT_IN_LIST; - if (--len !== 0) { - fastTimers[idx] = fastTimers[len]; - } - } else { - ++idx; - } + var assert = require("node:assert"); + var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols(); + var { IncomingMessage } = require("node:http"); + var stream = require("node:stream"); + var net = require("node:net"); + var { stringify } = require("node:querystring"); + var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = require("node:events"); + var timers = require_timers(); + var { InvalidArgumentError, ConnectTimeoutError } = require_errors(); + var { headerNameLowerCasedRecord } = require_constants(); + var { tree } = require_tree(); + var BodyAsyncIterable = class { + static { + __name(this, "BodyAsyncIterable"); } - fastTimers.length = len; - if (fastTimers.length !== 0) { - refreshTimeout(); + constructor(body) { + this[kBody] = body; + this[kBodyUsed] = false; + } + async *[Symbol.asyncIterator]() { + assert(!this[kBodyUsed], "disturbed"); + this[kBodyUsed] = true; + yield* this[kBody]; } + }; + function noop() { } - __name(onTick, "onTick"); - function refreshTimeout() { - if (fastNowTimeout?.refresh) { - fastNowTimeout.refresh(); + __name(noop, "noop"); + function wrapRequestBody(body) { + if (isStream(body)) { + if (bodyLength(body) === 0) { + body.on("data", function() { + assert(false); + }); + } + if (typeof body.readableDidRead !== "boolean") { + body[kBodyUsed] = false; + EE.prototype.on.call(body, "data", function() { + this[kBodyUsed] = true; + }); + } + return body; + } else if (body && typeof body.pipeTo === "function") { + return new BodyAsyncIterable(body); + } else if (body && isFormDataLike(body)) { + return body; + } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) { + return new BodyAsyncIterable(body); } else { - clearTimeout(fastNowTimeout); - fastNowTimeout = setTimeout(onTick, TICK_MS); - fastNowTimeout?.unref(); + return body; } } - __name(refreshTimeout, "refreshTimeout"); - var FastTimer = class { - static { - __name(this, "FastTimer"); + __name(wrapRequestBody, "wrapRequestBody"); + function isStream(obj) { + return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function"; + } + __name(isStream, "isStream"); + function isBlobLike(object) { + return object instanceof Blob; + } + __name(isBlobLike, "isBlobLike"); + function pathHasQueryOrFragment(url) { + return url.includes("?") || url.includes("#"); + } + __name(pathHasQueryOrFragment, "pathHasQueryOrFragment"); + function serializePathWithQuery(url, queryParams) { + if (pathHasQueryOrFragment(url)) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".'); } - [kFastTimer] = true; - /** - * The state of the timer, which can be one of the following: - * - NOT_IN_LIST (-2) - * - TO_BE_CLEARED (-1) - * - PENDING (0) - * - ACTIVE (1) - * - * @type {-2|-1|0|1} - * @private - */ - _state = NOT_IN_LIST; - /** - * The number of milliseconds to wait before calling the callback. - * - * @type {number} - * @private - */ - _idleTimeout = -1; - /** - * The time in milliseconds when the timer was started. This value is used to - * calculate when the timer should expire. - * - * @type {number} - * @default -1 - * @private - */ - _idleStart = -1; - /** - * The function to be executed when the timer expires. - * @type {Function} - * @private - */ - _onTimeout; - /** - * The argument to be passed to the callback when the timer expires. - * - * @type {*} - * @private - */ - _timerArg; - /** - * @constructor - * @param {Function} callback A function to be executed after the timer - * expires. - * @param {number} delay The time, in milliseconds that the timer should wait - * before the specified function or code is executed. - * @param {*} arg - */ - constructor(callback, delay, arg) { - this._onTimeout = callback; - this._idleTimeout = delay; - this._timerArg = arg; - this.refresh(); - } - /** - * Sets the timer's start time to the current time, and reschedules the timer - * to call its callback at the previously specified duration adjusted to the - * current time. - * Using this on a timer that has already called its callback will reactivate - * the timer. - * - * @returns {void} - */ - refresh() { - if (this._state === NOT_IN_LIST) { - fastTimers.push(this); - } - if (!fastNowTimeout || fastTimers.length === 1) { - refreshTimeout(); - } - this._state = PENDING; - } - /** - * The `clear` method cancels the timer, preventing it from executing. - * - * @returns {void} - * @private - */ - clear() { - this._state = TO_BE_CLEARED; - this._idleStart = -1; - } - }; - module2.exports = { - /** - * The setTimeout() method sets a timer which executes a function once the - * timer expires. - * @param {Function} callback A function to be executed after the timer - * expires. - * @param {number} delay The time, in milliseconds that the timer should - * wait before the specified function or code is executed. - * @param {*} [arg] An optional argument to be passed to the callback function - * when the timer expires. - * @returns {NodeJS.Timeout|FastTimer} - */ - setTimeout(callback, delay, arg) { - return delay <= RESOLUTION_MS ? setTimeout(callback, delay, arg) : new FastTimer(callback, delay, arg); - }, - /** - * The clearTimeout method cancels an instantiated Timer previously created - * by calling setTimeout. - * - * @param {NodeJS.Timeout|FastTimer} timeout - */ - clearTimeout(timeout) { - if (timeout[kFastTimer]) { - timeout.clear(); - } else { - clearTimeout(timeout); - } - }, - /** - * The setFastTimeout() method sets a fastTimer which executes a function once - * the timer expires. - * @param {Function} callback A function to be executed after the timer - * expires. - * @param {number} delay The time, in milliseconds that the timer should - * wait before the specified function or code is executed. - * @param {*} [arg] An optional argument to be passed to the callback function - * when the timer expires. - * @returns {FastTimer} - */ - setFastTimeout(callback, delay, arg) { - return new FastTimer(callback, delay, arg); - }, - /** - * The clearTimeout method cancels an instantiated FastTimer previously - * created by calling setFastTimeout. - * - * @param {FastTimer} timeout - */ - clearFastTimeout(timeout) { - timeout.clear(); - }, - /** - * The now method returns the value of the internal fast timer clock. - * - * @returns {number} - */ - now() { - return fastNow; - }, - /** - * Trigger the onTick function to process the fastTimers array. - * Exported for testing purposes only. - * Marking as deprecated to discourage any use outside of testing. - * @deprecated - * @param {number} [delay=0] The delay in milliseconds to add to the now value. - */ - tick(delay = 0) { - fastNow += delay - RESOLUTION_MS + 1; - onTick(); - onTick(); - }, - /** - * Reset FastTimers. - * Exported for testing purposes only. - * Marking as deprecated to discourage any use outside of testing. - * @deprecated - */ - reset() { - fastNow = 0; - fastTimers.length = 0; - clearTimeout(fastNowTimeout); - fastNowTimeout = null; - }, - /** - * Exporting for testing purposes only. - * Marking as deprecated to discourage any use outside of testing. - * @deprecated - */ - kFastTimer - }; - } -}); - -// lib/core/tree.js -var require_tree = __commonJS({ - "lib/core/tree.js"(exports2, module2) { - "use strict"; - var { - wellknownHeaderNames, - headerNameLowerCasedRecord - } = require_constants(); - var TstNode = class _TstNode { - static { - __name(this, "TstNode"); - } - /** @type {any} */ - value = null; - /** @type {null | TstNode} */ - left = null; - /** @type {null | TstNode} */ - middle = null; - /** @type {null | TstNode} */ - right = null; - /** @type {number} */ - code; - /** - * @param {string} key - * @param {any} value - * @param {number} index - */ - constructor(key, value, index) { - if (index === void 0 || index >= key.length) { - throw new TypeError("Unreachable"); - } - const code = this.code = key.charCodeAt(index); - if (code > 127) { - throw new TypeError("key must be ascii string"); - } - if (key.length !== ++index) { - this.middle = new _TstNode(key, value, index); - } else { - this.value = value; - } - } - /** - * @param {string} key - * @param {any} value - * @returns {void} - */ - add(key, value) { - const length = key.length; - if (length === 0) { - throw new TypeError("Unreachable"); - } - let index = 0; - let node = this; - while (true) { - const code = key.charCodeAt(index); - if (code > 127) { - throw new TypeError("key must be ascii string"); - } - if (node.code === code) { - if (length === ++index) { - node.value = value; - break; - } else if (node.middle !== null) { - node = node.middle; - } else { - node.middle = new _TstNode(key, value, index); - break; - } - } else if (node.code < code) { - if (node.left !== null) { - node = node.left; - } else { - node.left = new _TstNode(key, value, index); - break; - } - } else if (node.right !== null) { - node = node.right; - } else { - node.right = new _TstNode(key, value, index); - break; - } - } - } - /** - * @param {Uint8Array} key - * @returns {TstNode | null} - */ - search(key) { - const keylength = key.length; - let index = 0; - let node = this; - while (node !== null && index < keylength) { - let code = key[index]; - if (code <= 90 && code >= 65) { - code |= 32; - } - while (node !== null) { - if (code === node.code) { - if (keylength === ++index) { - return node; - } - node = node.middle; - break; - } - node = node.code < code ? node.left : node.right; - } - } - return null; - } - }; - var TernarySearchTree = class { - static { - __name(this, "TernarySearchTree"); - } - /** @type {TstNode | null} */ - node = null; - /** - * @param {string} key - * @param {any} value - * @returns {void} - * */ - insert(key, value) { - if (this.node === null) { - this.node = new TstNode(key, value, 0); - } else { - this.node.add(key, value); - } - } - /** - * @param {Uint8Array} key - * @returns {any} - */ - lookup(key) { - return this.node?.search(key)?.value ?? null; - } - }; - var tree = new TernarySearchTree(); - for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = headerNameLowerCasedRecord[wellknownHeaderNames[i]]; - tree.insert(key, key); - } - module2.exports = { - TernarySearchTree, - tree - }; - } -}); - -// lib/core/util.js -var require_util = __commonJS({ - "lib/core/util.js"(exports2, module2) { - "use strict"; - var assert = require("node:assert"); - var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols(); - var { IncomingMessage } = require("node:http"); - var stream = require("node:stream"); - var net = require("node:net"); - var { stringify } = require("node:querystring"); - var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = require("node:events"); - var timers = require_timers(); - var { InvalidArgumentError, ConnectTimeoutError } = require_errors(); - var { headerNameLowerCasedRecord } = require_constants(); - var { tree } = require_tree(); - var BodyAsyncIterable = class { - static { - __name(this, "BodyAsyncIterable"); - } - constructor(body) { - this[kBody] = body; - this[kBodyUsed] = false; - } - async *[Symbol.asyncIterator]() { - assert(!this[kBodyUsed], "disturbed"); - this[kBodyUsed] = true; - yield* this[kBody]; - } - }; - function noop() { - } - __name(noop, "noop"); - function wrapRequestBody(body) { - if (isStream(body)) { - if (bodyLength(body) === 0) { - body.on("data", function() { - assert(false); - }); - } - if (typeof body.readableDidRead !== "boolean") { - body[kBodyUsed] = false; - EE.prototype.on.call(body, "data", function() { - this[kBodyUsed] = true; - }); - } - return body; - } else if (body && typeof body.pipeTo === "function") { - return new BodyAsyncIterable(body); - } else if (body && isFormDataLike(body)) { - return body; - } else if (body && typeof body !== "string" && !ArrayBuffer.isView(body) && isIterable(body)) { - return new BodyAsyncIterable(body); - } else { - return body; - } - } - __name(wrapRequestBody, "wrapRequestBody"); - function isStream(obj) { - return obj && typeof obj === "object" && typeof obj.pipe === "function" && typeof obj.on === "function"; - } - __name(isStream, "isStream"); - function isBlobLike(object) { - return object instanceof Blob; - } - __name(isBlobLike, "isBlobLike"); - function pathHasQueryOrFragment(url) { - return url.includes("?") || url.includes("#"); - } - __name(pathHasQueryOrFragment, "pathHasQueryOrFragment"); - function serializePathWithQuery(url, queryParams) { - if (pathHasQueryOrFragment(url)) { - throw new Error('Query params cannot be passed when url already contains "?" or "#".'); - } - const stringified = stringify(queryParams); - if (stringified) { - url += "?" + stringified; + const stringified = stringify(queryParams); + if (stringified) { + url += "?" + stringified; } return url; } @@ -4460,7 +4189,7 @@ var require_util2 = __commonJS({ return url; } __name(stripURLForReferrer, "stripURLForReferrer"); - var isPotentialleTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/); + var isPotentiallyTrustworthyIPv4 = RegExp.prototype.test.bind(/^127\.(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){2}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)$/); var isPotentiallyTrustworthyIPv6 = RegExp.prototype.test.bind(/^(?:(?:0{1,4}:){7}|(?:0{1,4}:){1,6}:|::)0{0,3}1$/); function isOriginIPPotentiallyTrustworthy(origin) { if (origin.includes(":")) { @@ -4469,7 +4198,7 @@ var require_util2 = __commonJS({ } return isPotentiallyTrustworthyIPv6(origin); } - return isPotentialleTrustworthyIPv4(origin); + return isPotentiallyTrustworthyIPv4(origin); } __name(isOriginIPPotentiallyTrustworthy, "isOriginIPPotentiallyTrustworthy"); function isOriginPotentiallyTrustworthy(origin) { @@ -5134,589 +4863,924 @@ var require_formdata = __commonJS({ if (idx === -1) { return null; } - return this.#state[idx].value; + return this.#state[idx].value; + } + getAll(name) { + webidl.brandCheck(this, webidl.is.FormData); + const prefix = "FormData.getAll"; + webidl.argumentLengthCheck(arguments, 1, prefix); + name = webidl.converters.USVString(name); + return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value); + } + has(name) { + webidl.brandCheck(this, webidl.is.FormData); + const prefix = "FormData.has"; + webidl.argumentLengthCheck(arguments, 1, prefix); + name = webidl.converters.USVString(name); + return this.#state.findIndex((entry) => entry.name === name) !== -1; + } + set(name, value, filename = void 0) { + webidl.brandCheck(this, webidl.is.FormData); + const prefix = "FormData.set"; + webidl.argumentLengthCheck(arguments, 2, prefix); + name = webidl.converters.USVString(name); + if (arguments.length === 3 || webidl.is.Blob(value)) { + value = webidl.converters.Blob(value, prefix, "value"); + if (filename !== void 0) { + filename = webidl.converters.USVString(filename); + } + } else { + value = webidl.converters.USVString(value); + } + const entry = makeEntry(name, value, filename); + const idx = this.#state.findIndex((entry2) => entry2.name === name); + if (idx !== -1) { + this.#state = [ + ...this.#state.slice(0, idx), + entry, + ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name) + ]; + } else { + this.#state.push(entry); + } + } + [nodeUtil.inspect.custom](depth, options) { + const state = Object.groupBy(this.#state, ({ name }) => name); + for (const [name, entries] of Object.entries(state)) { + state[name] = entries.length === 1 ? entries[0].value : entries.map(({ value }) => value); + } + options.depth ??= depth; + options.colors ??= true; + const output = nodeUtil.formatWithOptions(options, state); + return `FormData ${output.slice(output.indexOf("]") + 2)}`; + } + static { + getFormDataState = /* @__PURE__ */ __name((formData) => formData.#state, "getFormDataState"); + setFormDataState = /* @__PURE__ */ __name((formData, newState) => { + formData.#state = newState; + }, "setFormDataState"); + getFormDataBoundary = /* @__PURE__ */ __name((formData) => { + return formData.#boundary ??= `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`; + }, "getFormDataBoundary"); + webidl.is.FormData = (arg) => { + return arg != null && typeof arg === "object" && #state in arg; + }; + } + }; + iteratorMixin("FormData", FormData, getFormDataState, "name", "value", webidl.is.FormData); + Object.defineProperties(FormData.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + getAll: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + [Symbol.toStringTag]: { + value: "FormData", + configurable: true + } + }); + function makeEntry(name, value, filename) { + if (typeof value === "string") { + } else { + if (!webidl.is.File(value)) { + value = new File([value], "blob", { type: value.type }); + } + if (filename !== void 0) { + const options = { + type: value.type, + lastModified: value.lastModified + }; + value = new File([value], filename, options); + } + } + return { name, value }; + } + __name(makeEntry, "makeEntry"); + module2.exports = { FormData, makeEntry, setFormDataState, getFormDataBoundary }; + } +}); + +// lib/core/request.js +var require_request = __commonJS({ + "lib/core/request.js"(exports2, module2) { + "use strict"; + var { + InvalidArgumentError, + NotSupportedError + } = require_errors(); + var assert = require("node:assert"); + var { + isValidHTTPToken, + isValidHeaderValue, + isStream, + destroy, + isBuffer, + isFormDataLike, + isIterable, + hasSafeIterator, + isBlobLike, + serializePathWithQuery, + parseHeaders, + assertRequestHandler, + getServerName, + normalizedMethodRecords, + getProtocolFromUrlString + } = require_util(); + var { channels } = require_diagnostics(); + var { headerNameLowerCasedRecord } = require_constants(); + var invalidPathRegex = /[^\u0021-\u00ff]/; + function isValidContentLengthHeaderValue(val) { + if (typeof val !== "string" || val.length === 0) { + return false; + } + for (let i = 0; i < val.length; i++) { + const charCode = val.charCodeAt(i); + if (charCode < 48 || charCode > 57) { + return false; + } + } + return true; + } + __name(isValidContentLengthHeaderValue, "isValidContentLengthHeaderValue"); + var kHandler = /* @__PURE__ */ Symbol("handler"); + var kController = /* @__PURE__ */ Symbol("controller"); + var kResume = /* @__PURE__ */ Symbol("resume"); + function noop() { + } + __name(noop, "noop"); + var RequestController = class { + static { + __name(this, "RequestController"); + } + #paused = false; + #reason = null; + #aborted = false; + #abort; + [kResume] = null; + rawHeaders = null; + rawTrailers = null; + constructor(abort) { + this.#abort = abort; + } + pause() { + this.#paused = true; + } + resume() { + if (this.#paused) { + this.#paused = false; + this[kResume]?.(); + } } - getAll(name) { - webidl.brandCheck(this, webidl.is.FormData); - const prefix = "FormData.getAll"; - webidl.argumentLengthCheck(arguments, 1, prefix); - name = webidl.converters.USVString(name); - return this.#state.filter((entry) => entry.name === name).map((entry) => entry.value); + abort(reason) { + if (!this.#aborted) { + this.#aborted = true; + this.#reason = reason; + this.#abort(reason); + } } - has(name) { - webidl.brandCheck(this, webidl.is.FormData); - const prefix = "FormData.has"; - webidl.argumentLengthCheck(arguments, 1, prefix); - name = webidl.converters.USVString(name); - return this.#state.findIndex((entry) => entry.name === name) !== -1; + get aborted() { + return this.#aborted; } - set(name, value, filename = void 0) { - webidl.brandCheck(this, webidl.is.FormData); - const prefix = "FormData.set"; - webidl.argumentLengthCheck(arguments, 2, prefix); - name = webidl.converters.USVString(name); - if (arguments.length === 3 || webidl.is.Blob(value)) { - value = webidl.converters.Blob(value, prefix, "value"); - if (filename !== void 0) { - filename = webidl.converters.USVString(filename); - } - } else { - value = webidl.converters.USVString(value); + get reason() { + return this.#reason; + } + get paused() { + return this.#paused; + } + }; + var Request = class { + static { + __name(this, "Request"); + } + constructor(origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + expectContinue, + servername, + throwOnError, + maxRedirections, + typeOfService + }, handler) { + if (typeof path !== "string") { + throw new InvalidArgumentError("path must be a string"); + } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") { + throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); + } else if (invalidPathRegex.test(path)) { + throw new InvalidArgumentError("invalid request path"); } - const entry = makeEntry(name, value, filename); - const idx = this.#state.findIndex((entry2) => entry2.name === name); - if (idx !== -1) { - this.#state = [ - ...this.#state.slice(0, idx), - entry, - ...this.#state.slice(idx + 1).filter((entry2) => entry2.name !== name) - ]; - } else { - this.#state.push(entry); + if (typeof method !== "string") { + throw new InvalidArgumentError("method must be a string"); + } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) { + throw new InvalidArgumentError("invalid request method"); } - } - [nodeUtil.inspect.custom](depth, options) { - const state = this.#state.reduce((a, b) => { - if (a[b.name]) { - if (Array.isArray(a[b.name])) { - a[b.name].push(b.value); + if (upgrade && typeof upgrade !== "string") { + throw new InvalidArgumentError("upgrade must be a string"); + } + if (upgrade && !isValidHeaderValue(upgrade)) { + throw new InvalidArgumentError("invalid upgrade header"); + } + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError("invalid headersTimeout"); + } + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError("invalid bodyTimeout"); + } + if (reset != null && typeof reset !== "boolean") { + throw new InvalidArgumentError("invalid reset"); + } + if (expectContinue != null && typeof expectContinue !== "boolean") { + throw new InvalidArgumentError("invalid expectContinue"); + } + if (throwOnError != null) { + throw new InvalidArgumentError("invalid throwOnError"); + } + if (maxRedirections != null && maxRedirections !== 0) { + throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor"); + } + if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) { + throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255"); + } + this.headersTimeout = headersTimeout; + this.bodyTimeout = bodyTimeout; + this.method = method; + this.typeOfService = typeOfService; + this.abort = null; + if (body == null) { + this.body = null; + } else if (isStream(body)) { + this.body = body; + const rState = this.body._readableState; + if (!rState || !rState.autoDestroy) { + this.endHandler = /* @__PURE__ */ __name(function autoDestroy() { + destroy(this); + }, "autoDestroy"); + this.body.on("end", this.endHandler); + } + this.errorHandler = (err) => { + if (this.abort) { + this.abort(err); } else { - a[b.name] = [a[b.name], b.value]; + this.error = err; + } + }; + this.body.on("error", this.errorHandler); + } else if (isBuffer(body)) { + this.body = body.byteLength ? body : null; + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null; + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null; + } else if (typeof body === "string") { + this.body = body.length ? Buffer.from(body) : null; + } else if (isFormDataLike(body)) { + if (!isUndiciFormData(body)) { + throw new InvalidArgumentError("body must be a FormData created by this undici package instance; FormData from other sources, such as the built-in FormData provided by Node.js, is not supported"); + } + this.body = body; + } else if (isIterable(body) || isBlobLike(body)) { + this.body = body; + } else { + throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable"); + } + this.completed = false; + this.aborted = false; + this.upgrade = upgrade || null; + this.path = query ? serializePathWithQuery(path, query) : path; + this.origin = origin; + this.protocol = getProtocolFromUrlString(origin); + this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" || method === "QUERY" : idempotent; + this.blocking = blocking ?? this.method !== "HEAD"; + this.reset = reset == null ? null : reset; + this.host = null; + this.contentLength = null; + this.contentType = null; + this.headers = []; + this.expectContinue = expectContinue != null ? expectContinue : false; + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError("headers array must be even"); + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]); + } + } else if (headers && typeof headers === "object") { + if (hasSafeIterator(headers)) { + for (const header of headers) { + if (!Array.isArray(header) || header.length !== 2) { + throw new InvalidArgumentError("headers must be in key-value pair format"); + } + processHeader(this, header[0], header[1]); } } else { - a[b.name] = b.value; + const keys = Object.keys(headers); + for (let i = 0; i < keys.length; ++i) { + processHeader(this, keys[i], headers[keys[i]]); + } } - return a; - }, { __proto__: null }); - options.depth ??= depth; - options.colors ??= true; - const output = nodeUtil.formatWithOptions(options, state); - return `FormData ${output.slice(output.indexOf("]") + 2)}`; - } - static { - getFormDataState = /* @__PURE__ */ __name((formData) => formData.#state, "getFormDataState"); - setFormDataState = /* @__PURE__ */ __name((formData, newState) => { - formData.#state = newState; - }, "setFormDataState"); - getFormDataBoundary = /* @__PURE__ */ __name((formData) => { - return formData.#boundary ??= `----formdata-undici-0${`${random(1e11)}`.padStart(11, "0")}`; - }, "getFormDataBoundary"); - webidl.is.FormData = (arg) => { - return arg != null && typeof arg === "object" && #state in arg; - }; + } else if (headers != null) { + throw new InvalidArgumentError("headers must be an object or an array"); + } + assertRequestHandler(handler, method, upgrade); + this.servername = servername || getServerName(this.host) || null; + this[kHandler] = handler; + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }); + } } - }; - iteratorMixin("FormData", FormData, getFormDataState, "name", "value", webidl.is.FormData); - Object.defineProperties(FormData.prototype, { - append: kEnumerableProperty, - delete: kEnumerableProperty, - get: kEnumerableProperty, - getAll: kEnumerableProperty, - has: kEnumerableProperty, - set: kEnumerableProperty, - [Symbol.toStringTag]: { - value: "FormData", - configurable: true + onBodySent(chunk) { + if (channels.bodyChunkSent.hasSubscribers) { + channels.bodyChunkSent.publish({ request: this, chunk }); + } + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk); + } catch (err) { + this.abort(err); + } + } } - }); - function makeEntry(name, value, filename) { - if (typeof value === "string") { - } else { - if (!webidl.is.File(value)) { - value = new File([value], "blob", { type: value.type }); + onRequestSent() { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }); } - if (filename !== void 0) { - const options = { - type: value.type, - lastModified: value.lastModified - }; - value = new File([value], filename, options); + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent(); + } catch (err) { + this.abort(err); + } + } + } + onRequestStart(abort, context) { + assert(!this.aborted); + assert(!this.completed); + this[kController] = new RequestController(abort); + if (this.error) { + this[kController].abort(this.error); + return; } + this.abort = abort; + return this[kHandler].onRequestStart(this[kController], context); } - return { name, value }; - } - __name(makeEntry, "makeEntry"); - module2.exports = { FormData, makeEntry, setFormDataState, getFormDataBoundary }; - } -}); - -// lib/core/request.js -var require_request = __commonJS({ - "lib/core/request.js"(exports2, module2) { - "use strict"; - var { - InvalidArgumentError, - NotSupportedError - } = require_errors(); - var assert = require("node:assert"); - var { - isValidHTTPToken, - isValidHeaderValue, - isStream, - destroy, - isBuffer, - isFormDataLike, - isIterable, - hasSafeIterator, - isBlobLike, - serializePathWithQuery, - parseHeaders, - assertRequestHandler, - getServerName, - normalizedMethodRecords, - getProtocolFromUrlString - } = require_util(); - var { channels } = require_diagnostics(); - var { headerNameLowerCasedRecord } = require_constants(); - var invalidPathRegex = /[^\u0021-\u00ff]/; - function isValidContentLengthHeaderValue(val) { - if (typeof val !== "string" || val.length === 0) { - return false; + onResponseStarted() { + return this[kHandler].onResponseStarted?.(); } - for (let i = 0; i < val.length; i++) { - const charCode = val.charCodeAt(i); - if (charCode < 48 || charCode > 57) { + onResponseStart(statusCode, headers, resume, statusText) { + assert(!this.aborted); + assert(!this.completed); + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); + } + const controller = this[kController]; + if (controller) { + controller[kResume] = resume; + controller.rawHeaders = headers; + } + const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers; + try { + this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText); + return !controller?.paused; + } catch (err) { + this.abort(err); return false; } } - return true; - } - __name(isValidContentLengthHeaderValue, "isValidContentLengthHeaderValue"); - var kHandler = /* @__PURE__ */ Symbol("handler"); - var kController = /* @__PURE__ */ Symbol("controller"); - var kResume = /* @__PURE__ */ Symbol("resume"); - var RequestController = class { - static { - __name(this, "RequestController"); - } - #paused = false; - #reason = null; - #aborted = false; - #abort; - [kResume] = null; - rawHeaders = null; - rawTrailers = null; - constructor(abort) { - this.#abort = abort; + onResponseData(chunk) { + assert(!this.aborted); + assert(!this.completed); + if (channels.bodyChunkReceived.hasSubscribers) { + channels.bodyChunkReceived.publish({ request: this, chunk }); + } + const controller = this[kController]; + try { + this[kHandler].onResponseData?.(controller, chunk); + return !controller?.paused; + } catch (err) { + this.abort(err); + return false; + } } - pause() { - this.#paused = true; + /** + * @param {number} statusCode + * @param {Buffer[]|string[]|import('../../types/header.d.ts').IncomingHttpHeaders} headers + * @param {import('node:stream').Duplex} socket + * @param {string} [statusText] + */ + onRequestUpgrade(statusCode, headers, socket, statusText = "") { + this.onFinally(); + assert(!this.aborted); + assert(!this.completed); + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); + } + const controller = this[kController]; + if (controller) { + controller.rawHeaders = headers; + } + const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers; + const result = this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket); + if (!this.aborted) { + this.completed = true; + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers: [] }); + } + } + return result; } - resume() { - if (this.#paused) { - this.#paused = false; - this[kResume]?.(); + onResponseEnd(trailers) { + this.onFinally(); + assert(!this.aborted); + assert(!this.completed); + this.completed = true; + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }); + } + const controller = this[kController]; + if (controller) { + controller.rawTrailers = trailers; + } + const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers; + try { + return this[kHandler].onResponseEnd?.(controller, parsedTrailers); + } catch (err) { + this.onResponseError(err); } } - abort(reason) { - if (!this.#aborted) { - this.#aborted = true; - this.#reason = reason; - this.#abort(reason); + onResponseError(error) { + this.onFinally(); + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }); + } + if (this.aborted) { + return; } + this.aborted = true; + const controller = this[kController]; + return this[kHandler].onResponseError?.(controller, error); } - get aborted() { - return this.#aborted; + onFinally() { + if (this.errorHandler) { + this.body.off("error", this.errorHandler); + this.errorHandler = null; + } + if (this.endHandler) { + this.body.off("end", this.endHandler); + this.endHandler = null; + } } - get reason() { - return this.#reason; + // Fails a request that was aborted before it reached a connection. The + // handler gets an aborted controller, so wrappers such as RetryHandler can + // tell a caller abort apart from a retryable connection failure. + onQueuedAbort(reason) { + this[kController] = createAbortedController(reason); + return this.onResponseError(reason); } - get paused() { - return this.#paused; + addHeader(key, value) { + processHeader(this, key, value); + return this; } }; - var Request = class { - static { - __name(this, "Request"); + function createAbortedController(reason) { + const controller = new RequestController(noop); + controller.abort(reason); + return controller; + } + __name(createAbortedController, "createAbortedController"); + function processHeader(request, key, val) { + if (val && (typeof val === "object" && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`); + } else if (val === void 0) { + return; } - constructor(origin, { - path, - method, - body, - headers, - query, - idempotent, - blocking, - upgrade, - headersTimeout, - bodyTimeout, - reset, - expectContinue, - servername, - throwOnError, - maxRedirections, - typeOfService - }, handler) { - if (typeof path !== "string") { - throw new InvalidArgumentError("path must be a string"); - } else if (path[0] !== "/" && !(path.startsWith("http://") || path.startsWith("https://")) && method !== "CONNECT") { - throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); - } else if (invalidPathRegex.test(path)) { - throw new InvalidArgumentError("invalid request path"); - } - if (typeof method !== "string") { - throw new InvalidArgumentError("method must be a string"); - } else if (normalizedMethodRecords[method] === void 0 && !isValidHTTPToken(method)) { - throw new InvalidArgumentError("invalid request method"); - } - if (upgrade && typeof upgrade !== "string") { - throw new InvalidArgumentError("upgrade must be a string"); - } - if (upgrade && !isValidHeaderValue(upgrade)) { - throw new InvalidArgumentError("invalid upgrade header"); + let headerName = headerNameLowerCasedRecord[key]; + if (headerName === void 0) { + headerName = key.toLowerCase(); + if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) { + throw new InvalidArgumentError("invalid header key"); } - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError("invalid headersTimeout"); + } + if (Array.isArray(val)) { + const arr = []; + for (let i = 0; i < val.length; i++) { + if (typeof val[i] === "string") { + if (!isValidHeaderValue(val[i])) { + throw new InvalidArgumentError(`invalid ${key} header`); + } + arr.push(val[i]); + } else if (val[i] === null) { + arr.push(""); + } else if (typeof val[i] === "object") { + throw new InvalidArgumentError(`invalid ${key} header`); + } else { + const str = `${val[i]}`; + if (!isValidHeaderValue(str)) { + throw new InvalidArgumentError(`invalid ${key} header`); + } + arr.push(str); + } } - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError("invalid bodyTimeout"); + val = arr; + } else if (typeof val === "string") { + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`); } - if (reset != null && typeof reset !== "boolean") { - throw new InvalidArgumentError("invalid reset"); + } else if (val === null) { + val = ""; + } else { + val = `${val}`; + if (!isValidHeaderValue(val)) { + throw new InvalidArgumentError(`invalid ${key} header`); } - if (expectContinue != null && typeof expectContinue !== "boolean") { - throw new InvalidArgumentError("invalid expectContinue"); + } + if (headerName === "host") { + if (request.host !== null) { + throw new InvalidArgumentError("duplicate host header"); } - if (throwOnError != null) { - throw new InvalidArgumentError("invalid throwOnError"); + if (typeof val !== "string") { + throw new InvalidArgumentError("invalid host header"); } - if (maxRedirections != null && maxRedirections !== 0) { - throw new InvalidArgumentError("maxRedirections is not supported, use the redirect interceptor"); + request.host = val; + } else if (headerName === "content-length") { + if (request.contentLength !== null) { + throw new InvalidArgumentError("duplicate content-length header"); } - if (typeOfService != null && (!Number.isInteger(typeOfService) || typeOfService < 0 || typeOfService > 255)) { - throw new InvalidArgumentError("typeOfService must be an integer between 0 and 255"); + if (!isValidContentLengthHeaderValue(val)) { + throw new InvalidArgumentError("invalid content-length header"); } - this.headersTimeout = headersTimeout; - this.bodyTimeout = bodyTimeout; - this.method = method; - this.typeOfService = typeOfService; - this.abort = null; - if (body == null) { - this.body = null; - } else if (isStream(body)) { - this.body = body; - const rState = this.body._readableState; - if (!rState || !rState.autoDestroy) { - this.endHandler = /* @__PURE__ */ __name(function autoDestroy() { - destroy(this); - }, "autoDestroy"); - this.body.on("end", this.endHandler); - } - this.errorHandler = (err) => { - if (this.abort) { - this.abort(err); - } else { - this.error = err; - } - }; - this.body.on("error", this.errorHandler); - } else if (isBuffer(body)) { - this.body = body.byteLength ? body : null; - } else if (ArrayBuffer.isView(body)) { - this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null; - } else if (body instanceof ArrayBuffer) { - this.body = body.byteLength ? Buffer.from(body) : null; - } else if (typeof body === "string") { - this.body = body.length ? Buffer.from(body) : null; - } else if (isFormDataLike(body)) { - if (!isUndiciFormData(body)) { - throw new InvalidArgumentError("body must be a FormData created by this undici package instance; FormData from other sources, such as the built-in FormData provided by Node.js, is not supported"); - } - this.body = body; - } else if (isIterable(body) || isBlobLike(body)) { - this.body = body; - } else { - throw new InvalidArgumentError("body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable"); + request.contentLength = parseInt(val, 10); + } else if (request.contentType === null && headerName === "content-type") { + request.contentType = val; + request.headers.push(key, val); + } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") { + throw new InvalidArgumentError(`invalid ${headerName} header`); + } else if (headerName === "connection") { + const value = typeof val === "string" ? val : null; + if (value === null) { + throw new InvalidArgumentError("invalid connection header"); } - this.completed = false; - this.aborted = false; - this.upgrade = upgrade || null; - this.path = query ? serializePathWithQuery(path, query) : path; - this.origin = origin; - this.protocol = getProtocolFromUrlString(origin); - this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" || method === "QUERY" : idempotent; - this.blocking = blocking ?? this.method !== "HEAD"; - this.reset = reset == null ? null : reset; - this.host = null; - this.contentLength = null; - this.contentType = null; - this.headers = []; - this.expectContinue = expectContinue != null ? expectContinue : false; - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError("headers array must be even"); - } - for (let i = 0; i < headers.length; i += 2) { - processHeader(this, headers[i], headers[i + 1]); + for (const token of value.toLowerCase().split(",")) { + const trimmed = token.trim(); + if (!isValidHTTPToken(trimmed)) { + throw new InvalidArgumentError("invalid connection header"); } - } else if (headers && typeof headers === "object") { - if (hasSafeIterator(headers)) { - for (const header of headers) { - if (!Array.isArray(header) || header.length !== 2) { - throw new InvalidArgumentError("headers must be in key-value pair format"); - } - processHeader(this, header[0], header[1]); - } - } else { - const keys = Object.keys(headers); - for (let i = 0; i < keys.length; ++i) { - processHeader(this, keys[i], headers[keys[i]]); - } + if (trimmed === "close") { + request.reset = true; } - } else if (headers != null) { - throw new InvalidArgumentError("headers must be an object or an array"); } - assertRequestHandler(handler, method, upgrade); - this.servername = servername || getServerName(this.host) || null; - this[kHandler] = handler; - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }); + } else if (headerName === "expect") { + throw new NotSupportedError("expect header not supported"); + } else { + request.headers.push(key, val); + } + } + __name(processHeader, "processHeader"); + var isFormData; + function isUndiciFormData(body) { + if (isFormData === void 0) { + require_formdata(); + isFormData = require_webidl().webidl.is.FormData; + } + return isFormData(body); + } + __name(isUndiciFormData, "isUndiciFormData"); + module2.exports = Request; + module2.exports.createAbortedController = createAbortedController; + } +}); + +// lib/dispatcher/pool-base.js +var require_pool_base = __commonJS({ + "lib/dispatcher/pool-base.js"(exports2, module2) { + "use strict"; + var { AsyncResource } = require("node:async_hooks"); + var { PoolStats } = require_stats(); + var DispatcherBase = require_dispatcher_base(); + var FixedQueue = require_fixed_queue(); + var { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch, kQueuedAbort } = require_symbols(); + var { createAbortedController } = require_request(); + var kClients = /* @__PURE__ */ Symbol("clients"); + var kNeedDrain = /* @__PURE__ */ Symbol("needDrain"); + var kQueue = /* @__PURE__ */ Symbol("queue"); + var kClosedResolve = /* @__PURE__ */ Symbol("closed resolve"); + var kOnDrain = /* @__PURE__ */ Symbol("onDrain"); + var kOnConnect = /* @__PURE__ */ Symbol("onConnect"); + var kOnDisconnect = /* @__PURE__ */ Symbol("onDisconnect"); + var kOnConnectionError = /* @__PURE__ */ Symbol("onConnectionError"); + var kOnClientBusy = /* @__PURE__ */ Symbol("on client busy"); + var kOnClientDrain = /* @__PURE__ */ Symbol("on client drain"); + var kDrainQueue = /* @__PURE__ */ Symbol("drain queue"); + var kGetDispatcher = /* @__PURE__ */ Symbol("get dispatcher"); + var kHasDispatcher = /* @__PURE__ */ Symbol("has dispatcher"); + var kAddClient = /* @__PURE__ */ Symbol("add client"); + var kRemoveClient = /* @__PURE__ */ Symbol("remove client"); + var kRetireClient = /* @__PURE__ */ Symbol("retire client"); + var kRetiring = /* @__PURE__ */ Symbol("retiring clients"); + var kShiftQueue = /* @__PURE__ */ Symbol("shift queue"); + var kAbortQueued = /* @__PURE__ */ Symbol("abort queued"); + var QueuedRequest = class extends AsyncResource { + static { + __name(this, "QueuedRequest"); + } + constructor(opts, handler) { + super("UNDICI_POOL_QUEUED_REQUEST"); + this.opts = opts; + this.handler = handler; + this.queued = true; + } + dispatch(dispatcher) { + return this.runInAsyncScope(dispatcher.dispatch, dispatcher, this.opts, this.handler); + } + }; + function closeClients(pool) { + const closeAll = []; + for (let i = 0; i < pool[kClients].length; i++) { + const client = pool[kClients][i]; + if (!client.destroyed) { + closeAll.push(client.close()); } } - onBodySent(chunk) { - if (channels.bodyChunkSent.hasSubscribers) { - channels.bodyChunkSent.publish({ request: this, chunk }); + for (const closed of pool[kRetiring].values()) { + closeAll.push(closed); + } + return Promise.all(closeAll); + } + __name(closeClients, "closeClients"); + var PoolBase = class extends DispatcherBase { + static { + __name(this, "PoolBase"); + } + [kQueue] = new FixedQueue(); + [kQueued] = 0; + [kClients] = []; + // Clients removed from kClients that have not finished closing, + // mapped to a promise that settles once they have. + [kRetiring] = /* @__PURE__ */ new Map(); + [kNeedDrain] = false; + [kOnDrain](client, origin, targets) { + if (client.closed || client.destroyed) { + return; } - if (this[kHandler].onBodySent) { - try { - return this[kHandler].onBodySent(chunk); - } catch (err) { - this.abort(err); + let needDrain = false; + this[kOnClientDrain](client); + while (!needDrain) { + const item = this[kShiftQueue](); + if (!item) { + break; } + needDrain = !item.dispatch(client); } - } - onRequestSent() { - if (channels.bodySent.hasSubscribers) { - channels.bodySent.publish({ request: this }); - } - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent(); - } catch (err) { - this.abort(err); + client[kNeedDrain] = needDrain; + if (needDrain) { + this[kOnClientBusy](client); + if (this[kQueued] > 0) { + return this[kDrainQueue](origin, targets); } } - } - onRequestStart(abort, context) { - assert(!this.aborted); - assert(!this.completed); - this[kController] = new RequestController(abort); - if (this.error) { - this[kController].abort(this.error); - return; + if (!needDrain && this[kNeedDrain]) { + this[kNeedDrain] = false; + this.emit("drain", origin, [this, ...targets]); + } + if (this[kClosedResolve] && this[kQueued] === 0) { + return closeClients(this).then(this[kClosedResolve]); } - this.abort = abort; - return this[kHandler].onRequestStart(this[kController], context); } - onResponseStarted() { - return this[kHandler].onResponseStarted?.(); + [kOnClientBusy]() { } - onResponseStart(statusCode, headers, resume, statusText) { - assert(!this.aborted); - assert(!this.completed); - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); + [kOnClientDrain]() { + } + [kDrainQueue](origin, targets) { + let hasDispatcher = true; + while (this[kQueued] > 0) { + let dispatcher; + try { + dispatcher = this[kGetDispatcher](); + } catch (err) { + const item2 = this[kShiftQueue](); + item2.runInAsyncScope(item2.handler.onResponseError, item2.handler, null, err); + hasDispatcher = !this.destroyed && this[kHasDispatcher](false); + continue; + } + if (!dispatcher) { + hasDispatcher = false; + break; + } + const item = this[kShiftQueue](); + if (!item.dispatch(dispatcher)) { + dispatcher[kNeedDrain] = true; + this[kOnClientBusy](dispatcher); + hasDispatcher = this[kHasDispatcher](false); + if (!hasDispatcher) { + break; + } + } } - const controller = this[kController]; - if (controller) { - controller[kResume] = resume; - controller.rawHeaders = headers; + if (hasDispatcher && this[kNeedDrain]) { + this[kNeedDrain] = false; + this.emit("drain", origin, [this, ...targets]); } - const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers; - try { - this[kHandler].onResponseStart?.(controller, statusCode, parsedHeaders, statusText); - return !controller?.paused; - } catch (err) { - this.abort(err); - return false; + if (this[kClosedResolve] && this[kQueued] === 0) { + return closeClients(this).then(this[kClosedResolve]); } } - onResponseData(chunk) { - assert(!this.aborted); - assert(!this.completed); - if (channels.bodyChunkReceived.hasSubscribers) { - channels.bodyChunkReceived.publish({ request: this, chunk }); + // Aborted requests stay in the queue as tombstones (queued === false) and + // are skipped here; kQueued only counts the live ones. + [kShiftQueue]() { + const queue = this[kQueue]; + let item = queue.shift(); + while (item !== null && item.queued === false) { + item = queue.shift(); } - const controller = this[kController]; - try { - this[kHandler].onResponseData?.(controller, chunk); - return !controller?.paused; - } catch (err) { - this.abort(err); - return false; + if (item !== null) { + this[kQueued]--; + item.queued = false; } + return item; } - /** - * @param {number} statusCode - * @param {Buffer[]|string[]|import('../../types/header.d.ts').IncomingHttpHeaders} headers - * @param {import('node:stream').Duplex} socket - * @param {string} [statusText] - */ - onRequestUpgrade(statusCode, headers, socket, statusText = "") { - this.onFinally(); - assert(!this.aborted); - assert(!this.completed); - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }); - } - const controller = this[kController]; - if (controller) { - controller.rawHeaders = headers; + // Called through the handler's kQueuedAbort hook when a queued request is + // aborted. + [kAbortQueued](item, reason) { + if (!item.queued) { + return; } - const parsedHeaders = Array.isArray(headers) ? parseHeaders(headers) : headers; - const result = this[kHandler].onRequestUpgrade?.(controller, statusCode, parsedHeaders, socket); - if (!this.aborted) { - this.completed = true; - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers: [] }); - } + const { handler } = item; + item.queued = false; + item.opts = null; + item.handler = null; + this[kQueued]--; + item.runInAsyncScope(handler.onResponseError, handler, createAbortedController(reason), reason); + if (this[kClosedResolve] && this[kQueued] === 0) { + closeClients(this).then(this[kClosedResolve]); } - return result; } - onResponseEnd(trailers) { - this.onFinally(); - assert(!this.aborted); - assert(!this.completed); - this.completed = true; - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers }); - } - const controller = this[kController]; - if (controller) { - controller.rawTrailers = trailers; - } - const parsedTrailers = Array.isArray(trailers) ? parseHeaders(trailers) : trailers; - try { - return this[kHandler].onResponseEnd?.(controller, parsedTrailers); - } catch (err) { - this.onResponseError(err); - } + [kOnConnect] = (origin, targets) => { + this.emit("connect", origin, [this, ...targets]); + }; + [kOnDisconnect] = (origin, targets, err) => { + this.emit("disconnect", origin, [this, ...targets], err); + }; + [kOnConnectionError] = (origin, targets, err) => { + this.emit("connectionError", origin, [this, ...targets], err); + }; + get [kBusy]() { + return this[kNeedDrain]; } - onResponseError(error) { - this.onFinally(); - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }); + get [kConnected]() { + let ret = 0; + for (const { [kConnected]: connected } of this[kClients]) { + ret += connected; } - if (this.aborted) { - return; + return ret; + } + get [kFree]() { + let ret = 0; + for (const { [kConnected]: connected, [kNeedDrain]: needDrain } of this[kClients]) { + ret += connected && !needDrain; } - this.aborted = true; - const controller = this[kController]; - return this[kHandler].onResponseError?.(controller, error); + return ret; } - onFinally() { - if (this.errorHandler) { - this.body.off("error", this.errorHandler); - this.errorHandler = null; + get [kPending]() { + let ret = this[kQueued]; + for (const { [kPending]: pending } of this[kClients]) { + ret += pending; } - if (this.endHandler) { - this.body.off("end", this.endHandler); - this.endHandler = null; + return ret; + } + get [kRunning]() { + let ret = 0; + for (const { [kRunning]: running } of this[kClients]) { + ret += running; } + return ret; } - addHeader(key, value) { - processHeader(this, key, value); - return this; + get [kSize]() { + let ret = this[kQueued]; + for (const { [kSize]: size } of this[kClients]) { + ret += size; + } + return ret; } - }; - function processHeader(request, key, val) { - if (val && (typeof val === "object" && !Array.isArray(val))) { - throw new InvalidArgumentError(`invalid ${key} header`); - } else if (val === void 0) { - return; + get stats() { + return new PoolStats(this); } - let headerName = headerNameLowerCasedRecord[key]; - if (headerName === void 0) { - headerName = key.toLowerCase(); - if (headerNameLowerCasedRecord[headerName] === void 0 && !isValidHTTPToken(headerName)) { - throw new InvalidArgumentError("invalid header key"); + [kClose]() { + if (this[kQueued] === 0) { + return closeClients(this); + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve; + }); } } - if (Array.isArray(val)) { - const arr = []; - for (let i = 0; i < val.length; i++) { - if (typeof val[i] === "string") { - if (!isValidHeaderValue(val[i])) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(val[i]); - } else if (val[i] === null) { - arr.push(""); - } else if (typeof val[i] === "object") { - throw new InvalidArgumentError(`invalid ${key} header`); - } else { - const str = `${val[i]}`; - if (!isValidHeaderValue(str)) { - throw new InvalidArgumentError(`invalid ${key} header`); - } - arr.push(str); + [kDestroy](err) { + while (true) { + const item = this[kShiftQueue](); + if (!item) { + break; } + item.handler.onResponseError(null, err); } - val = arr; - } else if (typeof val === "string") { - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); + const destroyAll = new Array(this[kClients].length); + for (let i = 0; i < this[kClients].length; i++) { + destroyAll[i] = this[kClients][i].destroy(err); } - } else if (val === null) { - val = ""; - } else { - val = `${val}`; - if (!isValidHeaderValue(val)) { - throw new InvalidArgumentError(`invalid ${key} header`); + for (const client of this[kRetiring].keys()) { + destroyAll.push(client.destroy(err)); } + return Promise.all(destroyAll); } - if (headerName === "host") { - if (request.host !== null) { - throw new InvalidArgumentError("duplicate host header"); + [kDispatch](opts, handler) { + const dispatcher = this[kGetDispatcher](); + if (!dispatcher) { + const item = new QueuedRequest(opts, handler); + this[kNeedDrain] = true; + this[kQueue].push(item); + this[kQueued]++; + const onQueued = opts[kQueuedAbort]; + if (onQueued !== void 0) { + onQueued((reason) => this[kAbortQueued](item, reason)); + } + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true; + this[kOnClientBusy](dispatcher); + this[kNeedDrain] = !this[kHasDispatcher](); } - if (typeof val !== "string") { - throw new InvalidArgumentError("invalid host header"); + return !this[kNeedDrain]; + } + [kHasDispatcher]() { + for (let i = 0; i < this[kClients].length; i++) { + const dispatcher = this[kClients][i]; + if (!dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true) { + return true; + } } - request.host = val; - } else if (headerName === "content-length") { - if (request.contentLength !== null) { - throw new InvalidArgumentError("duplicate content-length header"); + return false; + } + [kAddClient](client) { + client.on("drain", this[kOnDrain].bind(this, client)).on("connect", this[kOnConnect]).on("disconnect", this[kOnDisconnect]).on("connectionError", this[kOnConnectionError]); + this[kClients].push(client); + if (this[kNeedDrain]) { + queueMicrotask(() => { + if (this[kNeedDrain] && !client[kNeedDrain]) { + this[kOnDrain](client, client[kUrl], [client, this]); + } + }); } - if (!isValidContentLengthHeaderValue(val)) { - throw new InvalidArgumentError("invalid content-length header"); + return this; + } + // Takes a client out of rotation. A closed client no longer takes requests + // from the pool queue (see kOnDrain), but it finishes the requests it + // already has. Until it has, pool.close() waits for it and pool.destroy() + // destroys it. + [kRetireClient](client) { + const idx = this[kClients].indexOf(client); + if (idx !== -1) { + this[kClients].splice(idx, 1); } - request.contentLength = parseInt(val, 10); - } else if (request.contentType === null && headerName === "content-type") { - request.contentType = val; - request.headers.push(key, val); - } else if (headerName === "transfer-encoding" || headerName === "keep-alive" || headerName === "upgrade") { - throw new InvalidArgumentError(`invalid ${headerName} header`); - } else if (headerName === "connection") { - const value = typeof val === "string" ? val : null; - if (value === null) { - throw new InvalidArgumentError("invalid connection header"); + if (client.destroyed || this[kRetiring].has(client)) { + return; } - for (const token of value.toLowerCase().split(",")) { - const trimmed = token.trim(); - if (!isValidHTTPToken(trimmed)) { - throw new InvalidArgumentError("invalid connection header"); - } - if (trimmed === "close") { - request.reset = true; + let done = false; + let resolveClosed; + const closed = new Promise((resolve) => { + resolveClosed = resolve; + }); + this[kRetiring].set(client, closed); + client.close(() => { + if (!done) { + done = true; + this[kRetiring].delete(client); + resolveClosed(); } - } - } else if (headerName === "expect") { - throw new NotSupportedError("expect header not supported"); - } else { - request.headers.push(key, val); + }); } - } - __name(processHeader, "processHeader"); - var isFormData; - function isUndiciFormData(body) { - if (isFormData === void 0) { - require_formdata(); - isFormData = require_webidl().webidl.is.FormData; + [kRemoveClient](client) { + this[kRetireClient](client); + this[kNeedDrain] = !this[kClients].some((dispatcher) => !dispatcher[kNeedDrain] && dispatcher.closed !== true && dispatcher.destroyed !== true); } - return isFormData(body); - } - __name(isUndiciFormData, "isUndiciFormData"); - module2.exports = Request; + }; + module2.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kRetireClient, + kDrainQueue, + kOnClientBusy, + kOnClientDrain, + kGetDispatcher, + kHasDispatcher + }; } }); @@ -7304,6 +7368,7 @@ var require_client_h1 = __commonJS({ var kIdleSocketValidation = /* @__PURE__ */ Symbol("kIdleSocketValidation"); var kIdleSocketValidationTimeout = /* @__PURE__ */ Symbol("kIdleSocketValidationTimeout"); var kSocketUsed = /* @__PURE__ */ Symbol("kSocketUsed"); + var kIdleSince = /* @__PURE__ */ Symbol("kIdleSince"); var kTypeOfService = /* @__PURE__ */ Symbol("kTypeOfService"); var extractBody; function lazyllhttp() { @@ -8088,6 +8153,11 @@ var require_client_h1 = __commonJS({ }); } __name(scheduleIdleSocketValidation, "scheduleIdleSocketValidation"); + function isIdleSocketExpired(socket) { + const parser = socket[kParser]; + return parser.timeoutType === TIMEOUT_KEEP_ALIVE && parser.timeoutValue > 0 && performance.now() - socket[kIdleSince] >= parser.timeoutValue; + } + __name(isIdleSocketExpired, "isIdleSocketExpired"); function resumeH1(client) { const socket = client[kSocket]; if (socket && !socket.destroyed) { @@ -8100,6 +8170,10 @@ var require_client_h1 = __commonJS({ socket.ref(); socket[kNoRef] = false; } + if (client[kRunning] === 0 && client[kPending] > 0 && isIdleSocketExpired(socket)) { + util.destroy(socket, new InformationalError("socket idle timeout")); + return; + } if (client[kRunning] === 0 && client[kPending] > 0 && socket[kSocketUsed]) { if (socket[kIdleSocketValidation] === 0) { scheduleIdleSocketValidation(client, socket); @@ -8125,6 +8199,7 @@ var require_client_h1 = __commonJS({ } if (client[kSize] === 0) { if (socket[kParser].timeoutType !== TIMEOUT_KEEP_ALIVE) { + socket[kIdleSince] = performance.now(); socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_KEEP_ALIVE); } } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { @@ -8688,6 +8763,7 @@ var require_client_h2 = __commonJS({ HTTP2_HEADER_STATUS, HTTP2_HEADER_PROTOCOL, NGHTTP2_NO_ERROR, + NGHTTP2_PROTOCOL_ERROR, NGHTTP2_REFUSED_STREAM } } = http2; @@ -8853,7 +8929,9 @@ var require_client_h2 = __commonJS({ // refH2Session/unrefH2Session. refed: true, ping: { - interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref() + interval: client[kHTTP2Options].pingInterval === 0 ? null : setInterval(onHttp2SendPing, client[kHTTP2Options].pingInterval, session).unref(), + // Set while a periodic PING waits for its ack. + pending: false } }; session[kReceivedGoAway] = false; @@ -9044,11 +9122,15 @@ var require_client_h2 = __commonJS({ if (session.closed || session.destroyed) { return; } + resetUnresponsiveHttp2Session(session); + } + __name(onHttp2ProbeTimeout, "onHttp2ProbeTimeout"); + function resetUnresponsiveHttp2Session(session) { const err = new SocketError("HTTP/2: connection unresponsive", util.getSocketInfo(session[kSocket])); session[kError] = err; resetHttp2Session(session, err); } - __name(onHttp2ProbeTimeout, "onHttp2ProbeTimeout"); + __name(resetUnresponsiveHttp2Session, "resetUnresponsiveHttp2Session"); function clearHttp2IdleTimeout(session) { const state = session[kHTTP2SessionState]; if (state?.idleTimeout != null) { @@ -9117,13 +9199,19 @@ var require_client_h2 = __commonJS({ state.ping.interval = null; return; } + if (state.ping.pending) { + resetUnresponsiveHttp2Session(session); + return; + } + state.ping.pending = true; session.ping(onPing.bind(session)); function onPing(err, duration) { + state.ping.pending = false; const client = this[kClient]; const socket = this[kSocket]; if (err != null) { const error = new InformationalError(`HTTP/2: "PING" errored - type ${err.message}`); - socket[kError] = error; + socket[kError] ??= error; client[kOnError](error); } else { client.emit("ping", duration); @@ -9813,8 +9901,10 @@ var require_client_h2 = __commonJS({ } stream.off("error", onError); stream.on("error", noop); - if (state.responseContentLength != null && state.bytesRead !== state.responseContentLength) { - err = new ResponseContentLengthMismatchError(); + if ((err.code === "ERR_HTTP2_ERROR" || err.code === "ERR_HTTP2_STREAM_ERROR" && stream.rstCode === NGHTTP2_PROTOCOL_ERROR) && state.responseContentLength != null && state.bytesRead !== state.responseContentLength) { + const mismatch = new ResponseContentLengthMismatchError(); + mismatch.cause = err; + err = mismatch; } if (typeof stream.rstCode === "number" && stream.rstCode !== NGHTTP2_NO_ERROR) { err.http2ErrorCode = stream.rstCode; @@ -10122,11 +10212,13 @@ var require_client = __commonJS({ kHostAuthority, kResume, kHTTP2Options, - kUseMilo + kUseMilo, + kQueuedAbort } = require_symbols(); var connectH1 = require_client_h1(); var connectH2 = require_client_h2(); var kClosedResolve = /* @__PURE__ */ Symbol("kClosedResolve"); + var kCancelConnect = /* @__PURE__ */ Symbol("kCancelConnect"); var getDefaultNodeMaxHeaderSize = http && http.maxHeaderSize && Number.isInteger(http.maxHeaderSize) && http.maxHeaderSize > 0 ? () => http.maxHeaderSize : () => { throw new InvalidArgumentError("http module not available or http.maxHeaderSize invalid"); }; @@ -10340,6 +10432,7 @@ var require_client = __commonJS({ this[kClosedResolve] = null; this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1; this[kHTTPContext] = null; + this[kCancelConnect] = null; this[kHTTP2Options] = { pingInterval: h2Options?.pingInterval ?? pingInterval ?? 6e4, connectionWindowSize: h2Options?.connectionWindowSize ?? connectionWindowSize ?? 524288, @@ -10392,6 +10485,7 @@ var require_client = __commonJS({ } [kConnect](cb) { connect(this); + this[kCancelConnect] = null; this.once("connect", cb); } [kDispatch](opts, handler) { @@ -10404,6 +10498,12 @@ var require_client = __commonJS({ } else { this[kResume](true); } + if (request.abort === null && !request.aborted) { + const onQueued = opts[kQueuedAbort]; + if (onQueued !== void 0) { + onQueued((reason) => abortPendingRequest(this, request, reason)); + } + } if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { this[kNeedDrain] = 2; } @@ -10444,6 +10544,42 @@ var require_client = __commonJS({ }); } }; + function failQueuedRequest(client, request, reason) { + try { + request.onQueuedAbort(reason); + assert(request.aborted); + } catch (err) { + client.emit("error", err); + } + } + __name(failQueuedRequest, "failQueuedRequest"); + function abortPendingRequest(client, request, reason) { + if (request.aborted || request.abort !== null) { + return; + } + const queue = client[kQueue]; + const idx = queue.indexOf(request, client[kPendingIdx]); + if (idx === -1) { + return; + } + if (idx === client[kPendingIdx] && client[kResuming] === 2) { + return; + } + queue.splice(idx, 1); + failQueuedRequest(client, request, reason); + client[kResume](true); + if (client[kCancelConnect] !== null && client[kSize] === 0) { + queueMicrotask(() => cancelUnusedConnect(client)); + } + } + __name(abortPendingRequest, "abortPendingRequest"); + function cancelUnusedConnect(client) { + const cancel = client[kCancelConnect]; + if (cancel !== null && client[kSize] === 0) { + cancel(new InformationalError("no request waits for this connection")); + } + } + __name(cancelUnusedConnect, "cancelUnusedConnect"); function onError(client, err) { if (client[kRunning] === 0 && err.code !== "UND_ERR_INFO" && err.code !== "UND_ERR_SOCKET") { assert(client[kPendingIdx] === client[kRunningIdx]); @@ -10470,6 +10606,28 @@ var require_client = __commonJS({ hostname = ip; } client[kConnecting] = true; + const servername = client[kServerName]; + let calledBack = false; + let cancelled = false; + const abandon = /* @__PURE__ */ __name((socket, err) => { + client[kConnecting] = false; + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + version: client[kHTTPContext]?.version, + servername, + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }); + } + util.destroy(socket.on("error", noop), err); + }, "abandon"); if (channels.beforeConnect.hasSubscribers) { channels.beforeConnect.publish({ connectParams: { @@ -10478,23 +10636,31 @@ var require_client = __commonJS({ protocol, port, version: client[kHTTPContext]?.version, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, connector: client[kConnector] }); } try { - client[kConnector]({ + const connecting = client[kConnector]({ host, hostname, protocol, port, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, (err, socket) => { + calledBack = true; + if (cancelled) { + if (socket) { + util.destroy(socket.on("error", noop)); + } + return; + } + client[kCancelConnect] = null; if (err) { - handleConnectError(client, err, { host, hostname, protocol, port }); + handleConnectError(client, err, { host, hostname, protocol, port, servername }); client[kResume](); return; } @@ -10504,11 +10670,16 @@ var require_client = __commonJS({ return; } assert(socket); + if (client[kServerName] !== servername) { + abandon(socket, new InformationalError("servername changed")); + client[kResume](); + return; + } try { client[kHTTPContext] = socket.alpnProtocol === "h2" ? connectH2(client, socket) : connectH1(client, socket); } catch (err2) { socket.destroy().on("error", noop); - handleConnectError(client, err2, { host, hostname, protocol, port }); + handleConnectError(client, err2, { host, hostname, protocol, port, servername }); client[kResume](); return; } @@ -10525,7 +10696,7 @@ var require_client = __commonJS({ protocol, port, version: client[kHTTPContext]?.version, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, connector: client[kConnector], @@ -10535,13 +10706,20 @@ var require_client = __commonJS({ client.emit("connect", client[kUrl], [client]); client[kResume](); }); + if (!calledBack && util.isStream(connecting)) { + client[kCancelConnect] = (err) => { + cancelled = true; + client[kCancelConnect] = null; + abandon(connecting, err); + }; + } } catch (err) { - handleConnectError(client, err, { host, hostname, protocol, port }); + handleConnectError(client, err, { host, hostname, protocol, port, servername }); client[kResume](); } } __name(connect, "connect"); - function handleConnectError(client, err, { host, hostname, protocol, port }) { + function handleConnectError(client, err, { host, hostname, protocol, port, servername }) { if (client.destroyed) { return; } @@ -10554,7 +10732,7 @@ var require_client = __commonJS({ protocol, port, version: client[kHTTPContext]?.version, - servername: client[kServerName], + servername, localAddress: client[kLocalAddress] }, connector: client[kConnector], @@ -10567,7 +10745,7 @@ var require_client = __commonJS({ for (let i = 0; i < running.length; i++) { util.errorRequest(client, running[i], err); } - while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === servername) { const request = client[kQueue].splice(client[kPendingIdx], 1)[0]; util.errorRequest(client, request, err); } @@ -10644,6 +10822,7 @@ var require_client = __commonJS({ client[kHTTPContext] = null; resume(client); }); + client[kCancelConnect]?.(new InformationalError("servername changed")); } if (client[kConnecting]) { return; @@ -10693,7 +10872,7 @@ var require_pool = __commonJS({ InvalidArgumentError } = require_errors(); var util = require_util(); - var { kConnecting, kHTTPContext, kUrl, kQueued } = require_symbols(); + var { kConnecting, kHTTPContext, kHTTP2Session, kRemoteSettings, kUrl, kQueued } = require_symbols(); var buildConnector = require_connect(); var kOptions = /* @__PURE__ */ Symbol("options"); var kConnections = /* @__PURE__ */ Symbol("connections"); @@ -10775,9 +10954,19 @@ var require_pool = __commonJS({ this[kProtocol] = client[kHTTPContext]?.version; } if (client === this[kProtocolProbe]) { - if (this[kProtocol] !== "h2") { - this[kProtocolProbe] = null; - this[kDrainQueue](origin2, targets.slice(1)); + const releaseProbe = /* @__PURE__ */ __name(() => { + if (client === this[kProtocolProbe]) { + this[kProtocolProbe] = null; + if (!this.destroyed && (this[kQueued] > 0 || !this.closed && this[kHasDispatcher](false))) { + this[kDrainQueue](origin2, targets.slice(1)); + } + } + }, "releaseProbe"); + const session = client[kHTTP2Session]; + if (this[kProtocol] !== "h2" || session[kRemoteSettings]) { + releaseProbe(); + } else { + session.once("remoteSettings", releaseProbe); } } }); @@ -10831,7 +11020,7 @@ var require_pool = __commonJS({ return createClient(this); } } - [kHasDispatcher]() { + [kHasDispatcher](create = true) { const clientTtlOption = this[kOptions].clientTtl; for (let i = 0; i < this[kClients].length; i++) { const client = this[kClients][i]; @@ -10846,7 +11035,7 @@ var require_pool = __commonJS({ return false; } if (!this[kConnections] || this[kClients].length < this[kConnections]) { - createClient(this); + if (create) createClient(this); return true; } return false; @@ -10937,11 +11126,19 @@ var require_agent = __commonJS({ let dispatcher = this[kClients].get(key); if (!dispatcher) { dispatcher = this[kFactory](opts.origin, allowH2 === false ? { ...this[kOptions], allowH2: false } : this[kOptions]); - const closeClientIfUnused = /* @__PURE__ */ __name(() => { + const closeClientIfUnused = /* @__PURE__ */ __name((deferred = false) => { if (this[kClients].get(key) !== dispatcher) { return; } - if (dispatcher[kConnected] > 0 || dispatcher[kBusy] || dispatcher[kPending] > 0) { + if (dispatcher[kConnected] > 0 || dispatcher[kBusy]) { + return; + } + if (dispatcher[kPending] > 0) { + if (!deferred) { + queueMicrotask(() => { + closeClientIfUnused(true); + }); + } return; } this[kClients].delete(key); @@ -12094,8 +12291,10 @@ var require_proxy_agent = __commonJS({ headers: this[kProxyHeaders], connect, factory: agentFactory, - username: opts.username || username, - password: opts.password || password, + // Socks5ProxyAgent decodes the credentials embedded in the URI; + // the URL getters return them still percent-encoded. + username: opts.username, + password: opts.password, connectTimeout, proxyTls: opts.proxyTls, requestTls: opts.requestTls @@ -14274,7 +14473,7 @@ var require_fetch = __commonJS({ var EE = require("node:events"); var { Readable, pipeline, finished, isErrored, isReadable } = require("node:stream"); var { addAbortListener, bufferToLowerCasedHeaderName } = require_util(); - var { SocketError } = require_errors(); + var { SocketError, InformationalError } = require_errors(); var { dataURLProcessor, serializeAMimeType, minimizeSupportedMimeType } = require_data_url(); var { getGlobalDispatcher: getGlobalDispatcher2 } = require_global2(); var { webidl } = require_webidl(); @@ -15312,6 +15511,7 @@ var require_fetch = __commonJS({ } } } + this.nullBodyStatus = nullBodyStatus.includes(status); this.body = new Readable({ read: /* @__PURE__ */ __name(() => controller.resume(), "read") }); const onError = /* @__PURE__ */ __name((err) => this.onResponseError(controller, err), "onError"); resolve({ @@ -15326,6 +15526,10 @@ var require_fetch = __commonJS({ }); }, onResponseData(controller, chunk) { + if (this.nullBodyStatus) { + controller.abort(new InformationalError("response with null body status has content")); + return; + } if (fetchParams.controller.dump) { return; } @@ -15346,6 +15550,10 @@ var require_fetch = __commonJS({ if (this.abort) { fetchParams.controller.off("terminated", this.abort); } + if (this.nullBodyStatus) { + this.body?.destroy(); + return; + } if (request.mode === "websocket" && allowH2 !== false && error?.code === "UND_ERR_INFO" && error?.message === "HTTP/2: Extended CONNECT protocol not supported by server") { resolve(dispatchWithProtocolPreference(body2, false)); return; @@ -18488,6 +18696,94 @@ var require_readable = __commonJS({ } }); +// lib/api/abort-signal.js +var require_abort_signal = __commonJS({ + "lib/api/abort-signal.js"(exports2, module2) { + "use strict"; + var { addAbortListener } = require_util(); + var { RequestAbortedError } = require_errors(); + var { kQueuedAbort } = require_symbols(); + var kListener = /* @__PURE__ */ Symbol("kListener"); + var kSignal = /* @__PURE__ */ Symbol("kSignal"); + function abort(self) { + self.reason = self[kSignal]?.reason ?? new RequestAbortedError(); + if (self.abort) { + self.abort(self.reason); + } + removeSignal(self); + } + __name(abort, "abort"); + function addSignal(self, signal) { + self.reason = null; + self[kSignal] = null; + self[kListener] = null; + if (!signal) { + return; + } + if (signal.aborted) { + self.reason = signal.reason ?? new RequestAbortedError(); + return; + } + self[kSignal] = signal; + self[kListener] = () => { + abort(self); + }; + addAbortListener(self[kSignal], self[kListener]); + } + __name(addSignal, "addSignal"); + function removeSignal(self) { + if (!self[kSignal]) { + return; + } + if ("removeEventListener" in self[kSignal]) { + self[kSignal].removeEventListener("abort", self[kListener]); + } else { + self[kSignal].removeListener("abort", self[kListener]); + } + self[kSignal] = null; + self[kListener] = null; + } + __name(removeSignal, "removeSignal"); + function queuedAbortHook(handler) { + let started = null; + let installed = null; + return (cancel) => { + if (handler.reason) { + cancel(handler.reason); + return; + } + if (handler.abort !== installed) { + started = handler.abort; + } + if (started === null) { + installed = cancel; + } else { + const abortStarted = started; + installed = /* @__PURE__ */ __name((reason) => { + abortStarted(reason); + cancel(reason); + }, "installed"); + } + handler.abort = installed; + }; + } + __name(queuedAbortHook, "queuedAbortHook"); + function dispatchWithSignal(dispatcher, opts, handler) { + if (handler.reason) { + handler.onResponseError(null, handler.reason); + return; + } + dispatcher.dispatch({ ...opts, [kQueuedAbort]: queuedAbortHook(handler) }, handler); + } + __name(dispatchWithSignal, "dispatchWithSignal"); + module2.exports = { + addSignal, + removeSignal, + dispatchWithSignal + }; + } +}); + // lib/api/api-request.js var require_api_request = __commonJS({ "lib/api/api-request.js"(exports2, module2) { @@ -18497,6 +18793,7 @@ var require_api_request = __commonJS({ var { Readable } = require_readable(); var { InvalidArgumentError, RequestAbortedError } = require_errors(); var util = require_util(); + var { dispatchWithSignal } = require_abort_signal(); function noop() { } __name(noop, "noop"); @@ -18525,6 +18822,9 @@ var require_api_request = __commonJS({ if (onInfo && typeof onInfo !== "function") { throw new InvalidArgumentError("invalid onInfo callback"); } + if (signal?.aborted) { + throw signal.reason ?? new RequestAbortedError(); + } super("UNDICI_REQUEST"); } catch (err) { if (util.isStream(body)) { @@ -18546,9 +18846,7 @@ var require_api_request = __commonJS({ this.highWaterMark = highWaterMark; this.reason = null; this.removeAbortListener = null; - if (signal?.aborted) { - this.reason = signal.reason ?? new RequestAbortedError(); - } else if (signal) { + if (signal) { this.removeAbortListener = util.addAbortListener(signal, () => { this.reason = signal.reason ?? new RequestAbortedError(); if (this.res) { @@ -18577,7 +18875,7 @@ var require_api_request = __commonJS({ const responseHeaderData = responseHeaders === "raw" ? util.parseRawHeaders(rawHeaders) : headers; if (statusCode < 200) { if (this.onInfo) { - this.onInfo({ statusCode, headers: responseHeaderData }); + this.runInAsyncScope(this.onInfo, null, { statusCode, headers: responseHeaderData }); } return; } @@ -18679,7 +18977,11 @@ var require_api_request = __commonJS({ } try { const handler = new RequestHandler(opts, callback); - this.dispatch(opts, handler); + if (opts.signal == null) { + this.dispatch(opts, handler); + } else { + dispatchWithSignal(this, opts, handler); + } } catch (err) { if (typeof callback !== "function") { throw err; @@ -18694,61 +18996,6 @@ var require_api_request = __commonJS({ } }); -// lib/api/abort-signal.js -var require_abort_signal = __commonJS({ - "lib/api/abort-signal.js"(exports2, module2) { - "use strict"; - var { addAbortListener } = require_util(); - var { RequestAbortedError } = require_errors(); - var kListener = /* @__PURE__ */ Symbol("kListener"); - var kSignal = /* @__PURE__ */ Symbol("kSignal"); - function abort(self) { - if (self.abort) { - self.abort(self[kSignal]?.reason); - } else { - self.reason = self[kSignal]?.reason ?? new RequestAbortedError(); - } - removeSignal(self); - } - __name(abort, "abort"); - function addSignal(self, signal) { - self.reason = null; - self[kSignal] = null; - self[kListener] = null; - if (!signal) { - return; - } - if (signal.aborted) { - abort(self); - return; - } - self[kSignal] = signal; - self[kListener] = () => { - abort(self); - }; - addAbortListener(self[kSignal], self[kListener]); - } - __name(addSignal, "addSignal"); - function removeSignal(self) { - if (!self[kSignal]) { - return; - } - if ("removeEventListener" in self[kSignal]) { - self[kSignal].removeEventListener("abort", self[kListener]); - } else { - self[kSignal].removeListener("abort", self[kListener]); - } - self[kSignal] = null; - self[kListener] = null; - } - __name(removeSignal, "removeSignal"); - module2.exports = { - addSignal, - removeSignal - }; - } -}); - // lib/api/api-stream.js var require_api_stream = __commonJS({ "lib/api/api-stream.js"(exports2, module2) { @@ -18757,7 +19004,7 @@ var require_api_stream = __commonJS({ var { AsyncResource } = require("node:async_hooks"); var { InvalidArgumentError, InvalidReturnValueError } = require_errors(); var util = require_util(); - var { addSignal, removeSignal } = require_abort_signal(); + var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal(); function noop() { } __name(noop, "noop"); @@ -18953,7 +19200,11 @@ var require_api_stream = __commonJS({ } try { const handler = new StreamHandler(opts, factory, callback); - this.dispatch(opts, handler); + if (opts.signal == null) { + this.dispatch(opts, handler); + } else { + dispatchWithSignal(this, opts, handler); + } } catch (err) { if (typeof callback !== "function") { throw err; @@ -18985,7 +19236,7 @@ var require_api_pipeline = __commonJS({ } = require_errors(); var util = require_util(); var { kBodyUsed } = require_symbols(); - var { addSignal, removeSignal } = require_abort_signal(); + var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal(); function noop() { } __name(noop, "noop"); @@ -19080,7 +19331,7 @@ var require_api_pipeline = __commonJS({ if (!err && !ret._readableState.endEmitted) { err = new RequestAbortedError(); } - if (abort && err) { + if (abort && (err || !res?.readableEnded)) { abort(); } util.destroy(body, err); @@ -19174,7 +19425,12 @@ var require_api_pipeline = __commonJS({ function pipeline(opts, handler) { try { const pipelineHandler = new PipelineHandler(opts, handler); - this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler); + const pipelineOpts = { ...opts, body: pipelineHandler.req }; + if (opts.signal == null) { + this.dispatch(pipelineOpts, pipelineHandler); + } else { + dispatchWithSignal(this, pipelineOpts, pipelineHandler); + } return pipelineHandler.ret; } catch (err) { return new PassThrough().destroy(err); @@ -19194,7 +19450,7 @@ var require_api_upgrade = __commonJS({ var assert = require("node:assert"); var util = require_util(); var { kHTTP2Stream } = require_symbols(); - var { addSignal, removeSignal } = require_abort_signal(); + var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal(); var UpgradeHandler = class extends AsyncResource { static { __name(this, "UpgradeHandler"); @@ -19275,7 +19531,11 @@ var require_api_upgrade = __commonJS({ method: opts.method || "GET", upgrade: opts.protocol || "Websocket" }; - this.dispatch(upgradeOpts, upgradeHandler); + if (opts.signal == null) { + this.dispatch(upgradeOpts, upgradeHandler); + } else { + dispatchWithSignal(this, upgradeOpts, upgradeHandler); + } } catch (err) { if (typeof callback !== "function") { throw err; @@ -19297,7 +19557,7 @@ var require_api_connect = __commonJS({ var { AsyncResource } = require("node:async_hooks"); var { InvalidArgumentError, SocketError } = require_errors(); var util = require_util(); - var { addSignal, removeSignal } = require_abort_signal(); + var { addSignal, removeSignal, dispatchWithSignal } = require_abort_signal(); var ConnectHandler = class extends AsyncResource { static { __name(this, "ConnectHandler"); @@ -19371,7 +19631,11 @@ var require_api_connect = __commonJS({ try { const connectHandler = new ConnectHandler(opts, callback); const connectOptions = { ...opts, method: "CONNECT" }; - this.dispatch(connectOptions, connectHandler); + if (opts.signal == null) { + this.dispatch(connectOptions, connectHandler); + } else { + dispatchWithSignal(this, connectOptions, connectHandler); + } } catch (err) { if (typeof callback !== "function") { throw err; diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index 0101d1257665..8d2e7f417716 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 15 #define V8_MINOR_VERSION 6 #define V8_BUILD_NUMBER 75 -#define V8_PATCH_LEVEL 50 +#define V8_PATCH_LEVEL 60 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/baseline/baseline-compiler.cc b/deps/v8/src/baseline/baseline-compiler.cc index b09ed33e0085..b45a1942ac9f 100644 --- a/deps/v8/src/baseline/baseline-compiler.cc +++ b/deps/v8/src/baseline/baseline-compiler.cc @@ -1882,27 +1882,25 @@ void BaselineCompiler::VisitIntrinsicAsyncFunctionResolve( void BaselineCompiler::VisitIntrinsicGeneratorYieldResult( interpreter::RegisterList args) { - Register value = WriteBarrierDescriptor::ValueRegister(); Register generator = WriteBarrierDescriptor::ObjectRegister(); - DCHECK(!AreAliased(value, generator, kInterpreterAccumulatorRegister)); + DCHECK(!AreAliased(generator, kInterpreterAccumulatorRegister)); Label allocate, done; __ LoadRegister(generator, args[1]); // generator - // Check whether the generator user asked to skip result allocation - // (yielded_value_ == TheHole). + // Check whether the caller asked to skip result allocation + // (resume_mode_ == kNextTrySkipAlloc). __ LoadTaggedField(kInterpreterAccumulatorRegister, generator, - offsetof(JSGeneratorObject, yielded_value_)); - __ JumpIfNotRoot(kInterpreterAccumulatorRegister, RootIndex::kTheHoleValue, - &allocate); - - // Skip allocation: store value into yielded_value_. - __ LoadRegister(value, args[0]); // value - __ StoreTaggedFieldWithWriteBarrier( - generator, offsetof(JSGeneratorObject, yielded_value_), value); - - __ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kTheHoleValue); + offsetof(JSGeneratorObject, resume_mode_)); + __ JumpIfSmi(kNotEqual, kInterpreterAccumulatorRegister, + Smi::FromInt(JSGeneratorObject::kNextTrySkipAlloc), &allocate); + + // Skip allocation: ack handshake and return bare value. + __ StoreTaggedSignedField(generator, + offsetof(JSGeneratorObject, resume_mode_), + Smi::FromInt(JSGeneratorObject::kNextAllocSkipped)); + __ LoadRegister(kInterpreterAccumulatorRegister, args[0]); // value __ Jump(&done); __ Bind(&allocate); diff --git a/deps/v8/src/builtins/builtins-generator-gen.cc b/deps/v8/src/builtins/builtins-generator-gen.cc index c407accc24ac..cce7df4fe5ee 100644 --- a/deps/v8/src/builtins/builtins-generator-gen.cc +++ b/deps/v8/src/builtins/builtins-generator-gen.cc @@ -122,6 +122,10 @@ void GeneratorBuiltinsAssembler::InnerResume( case JSGeneratorObject::kRethrow: // Currently only async generators use this mode. UNREACHABLE(); + case JSGeneratorObject::kNextTrySkipAlloc: + case JSGeneratorObject::kNextAllocSkipped: + // Handshake states only set by optimized callers or the generator body. + UNREACHABLE(); } args->PopAndReturn(builtin_result); } diff --git a/deps/v8/src/builtins/generator.tq b/deps/v8/src/builtins/generator.tq index 8f8fd2d5c97f..44cbd2a45ee1 100644 --- a/deps/v8/src/builtins/generator.tq +++ b/deps/v8/src/builtins/generator.tq @@ -19,8 +19,6 @@ transitioning javascript builtin GeneratorPrototypeNextLazyDeoptContinuation( js-implicit context: NativeContext, receiver: JSAny)(generator: JSAny, exception: JSAny|TheHole, result: JSAny): JSAny { const gen = UnsafeCast<JSGeneratorObject>(generator); - const yieldedValue = gen.yielded_value; - gen.yielded_value = Undefined; // Exception path: close the generator and rethrow. typeswitch (exception) { @@ -36,15 +34,13 @@ transitioning javascript builtin GeneratorPrototypeNextLazyDeoptContinuation( // continuation is now kGeneratorExecuting; close it and wrap the result. // Otherwise (yielded), return the result as-is. if (gen.continuation == SmiConstant(kGeneratorExecuting)) { - dcheck(result != TheHole); gen.continuation = SmiConstant(kGeneratorClosed); return AllocateJSIteratorResult(result, True); } // Allocating the iterator result object was skipped; allocate it here. - if (result == TheHole) { - const val = (yieldedValue == TheHole) ? Undefined : yieldedValue; - return AllocateJSIteratorResult(val, False); + if (gen.resume_mode == SmiConstant(kGeneratorResumeModeNextAllocSkipped)) { + return AllocateJSIteratorResult(result, False); } return result; diff --git a/deps/v8/src/codegen/compiler.cc b/deps/v8/src/codegen/compiler.cc index 7a965c17292a..378a43860dfd 100644 --- a/deps/v8/src/codegen/compiler.cc +++ b/deps/v8/src/codegen/compiler.cc @@ -2177,6 +2177,11 @@ class ConstantPoolPointerForwarder { } } + bool HasScopeInfoToUpdate(Tagged<ScopeInfo> scope_info) const { + return scope_infos_to_update_.find(scope_info->UniqueIdInScript()) != + scope_infos_to_update_.end(); + } + void UpdateStandaloneScopeInfo(Tagged<ScopeInfo> scope_info) { if (!scope_info->HasOuterScopeInfo()) return; @@ -2354,6 +2359,23 @@ void VerifyCodeMerge(Isolate* isolate, DirectHandle<Script> script) { // * All constant pool SFI entries point to an SFI referring to the old // script (i.e. references were updated correctly). std::unordered_map<int, Tagged<ScopeInfo>> scope_infos; + auto verify_scope_info = [&](Tagged<ScopeInfo> scope_info) { + while (true) { + auto it = scope_infos.find(scope_info->UniqueIdInScript()); + if (it != scope_infos.end()) { + if (it->second != scope_info) { + isolate->PushParamsAndDie("duplicate scope info unique id", + reinterpret_cast<void*>(it->second.ptr()), + reinterpret_cast<void*>(scope_info.ptr())); + UNREACHABLE(); + } + break; + } + scope_infos[scope_info->UniqueIdInScript()] = scope_info; + if (!scope_info->HasOuterScopeInfo()) break; + scope_info = scope_info->OuterScopeInfo(); + } + }; uint32_t script_infos_len = script->infos()->ulength().value(); for (uint32_t info_idx = 0; info_idx < script_infos_len; info_idx++) { Tagged<ScopeInfo> scope_info; @@ -2377,6 +2399,8 @@ void VerifyCodeMerge(Isolate* isolate, DirectHandle<Script> script) { int id = inner_sfi->function_literal_id(kRelaxedLoad); CHECK_EQ(MakeWeak(inner_sfi), script->infos()->get(id)); CHECK_EQ(inner_sfi->script(), *script); + } else if (Is<ScopeInfo>(entry)) { + verify_scope_info(Cast<ScopeInfo>(entry)); } } } @@ -2391,21 +2415,7 @@ void VerifyCodeMerge(Isolate* isolate, DirectHandle<Script> script) { } else { scope_info = Cast<ScopeInfo>(info); } - while (true) { - auto it = scope_infos.find(scope_info->UniqueIdInScript()); - if (it != scope_infos.end()) { - if (it->second != scope_info) { - isolate->PushParamsAndDie("duplicate scope info unique id", - reinterpret_cast<void*>(it->second.ptr()), - reinterpret_cast<void*>(scope_info.ptr())); - UNREACHABLE(); - } - break; - } - scope_infos[scope_info->UniqueIdInScript()] = scope_info; - if (!scope_info->HasOuterScopeInfo()) break; - scope_info = scope_info->OuterScopeInfo(); - } + verify_scope_info(scope_info); } } } // namespace @@ -2553,6 +2563,9 @@ void BackgroundMergeTask::BeginMergeInBackground( for (DirectHandle<SharedFunctionInfo> new_sfi : used_new_sfis_) { forwarder.UpdateScopeInfo(*new_sfi); } + for (DirectHandle<ScopeInfo> new_scope : used_new_scope_infos_) { + forwarder.UpdateStandaloneScopeInfo(*new_scope); + } for (const auto& new_compiled_data : new_compiled_data_for_cached_sfis_) { // It's possible that new_compiled_data.cached_sfi had // scope_info()->IsEmpty() while an inner function has scope info if the @@ -2659,6 +2672,14 @@ Handle<SharedFunctionInfo> BackgroundMergeTask::CompleteMergeInForeground( compiled_data_it++; } } else if (!maybe_old_info.IsWeak()) { + // Standalone eval ScopeInfos are only recorded for scopes within their + // owning closure, so if the slot in old_script was cleared, the ScopeInfo + // itself cannot still be alive in old_script. + DCHECK_IMPLIES( + maybe_new_info.IsWeak() && + Is<ScopeInfo>(maybe_new_info.GetHeapObjectAssumeWeak()), + !forwarder.HasScopeInfoToUpdate( + Cast<ScopeInfo>(maybe_new_info.GetHeapObjectAssumeWeak()))); old_script->infos()->set(i, maybe_new_info, kReleaseStore); } } diff --git a/deps/v8/src/common/assert-scope.h b/deps/v8/src/common/assert-scope.h index ca36c690d4a2..2dcb5b05f4c6 100644 --- a/deps/v8/src/common/assert-scope.h +++ b/deps/v8/src/common/assert-scope.h @@ -75,21 +75,25 @@ class V8_NODISCARD PerThreadAssertScope // Per-isolate assert scopes. -#define PER_ISOLATE_DCHECK_TYPE(V, enable) \ - /* Scope to document where we do not expect javascript execution. */ \ - /* Scope to introduce an exception to DisallowJavascriptExecution. */ \ - V(AllowJavascriptExecution, DisallowJavascriptExecution, \ - javascript_execution_assert, enable) \ - /* Scope to document where we do not expect deoptimization. */ \ - /* Scope to introduce an exception to DisallowDeoptimization. */ \ - V(AllowDeoptimization, DisallowDeoptimization, deoptimization_assert, \ - enable) \ - /* Scope to document where we do not expect deoptimization. */ \ - /* Scope to introduce an exception to DisallowDeoptimization. */ \ - V(AllowCompilation, DisallowCompilation, compilation_assert, enable) \ - /* Scope to document where we do not expect exceptions. */ \ - /* Scope to introduce an exception to DisallowExceptions. */ \ - V(AllowExceptions, DisallowExceptions, no_exception_assert, enable) +#define PER_ISOLATE_DCHECK_TYPE(V, enable) \ + /* Scope to document where we do not expect javascript execution. */ \ + /* Scope to introduce an exception to DisallowJavascriptExecution. */ \ + V(AllowJavascriptExecution, DisallowJavascriptExecution, \ + javascript_execution_assert, enable) \ + /* Scope to document where we do not expect deoptimization. */ \ + /* Scope to introduce an exception to DisallowDeoptimization. */ \ + V(AllowDeoptimization, DisallowDeoptimization, deoptimization_assert, \ + enable) \ + /* Scope to document where we do not expect deoptimization. */ \ + /* Scope to introduce an exception to DisallowDeoptimization. */ \ + V(AllowCompilation, DisallowCompilation, compilation_assert, enable) \ + /* Scope to document where we do not expect exceptions. */ \ + /* Scope to introduce an exception to DisallowExceptions. */ \ + V(AllowExceptions, DisallowExceptions, no_exception_assert, enable) \ + /* Scope to document where we do not expect JS object modifications. */ \ + /* Scope to introduce an exception to DisallowJSObjectModification. */ \ + V(AllowJSObjectModification, DisallowJSObjectModification, \ + js_object_modification_assert, enable) #define PER_ISOLATE_CHECK_TYPE(V, enable) \ /* Scope in which javascript execution leads to exception being thrown. */ \ diff --git a/deps/v8/src/compiler/backend/register-allocator.cc b/deps/v8/src/compiler/backend/register-allocator.cc index 6e85eca12994..b4bbdbbe72a7 100644 --- a/deps/v8/src/compiler/backend/register-allocator.cc +++ b/deps/v8/src/compiler/backend/register-allocator.cc @@ -4406,8 +4406,9 @@ void LinearScanAllocator::AllocateBlockedReg(LiveRange* current, InstructionBlock* deferred_block = code()->GetInstructionBlock(current->Start().ToInstructionIndex()); new_end = - std::min(new_end, LifetimePosition::GapFromInstructionIndex( - LastDeferredInstructionIndex(deferred_block))); + std::min(new_end, LifetimePosition::InstructionFromInstructionIndex( + LastDeferredInstructionIndex(deferred_block)) + .NextFullStart()); } // We couldn't spill until the next register use. Split before the register diff --git a/deps/v8/src/compiler/escape-analysis-reducer.cc b/deps/v8/src/compiler/escape-analysis-reducer.cc index 4d54bdf1baa7..1b83aca3b58d 100644 --- a/deps/v8/src/compiler/escape-analysis-reducer.cc +++ b/deps/v8/src/compiler/escape-analysis-reducer.cc @@ -309,6 +309,7 @@ void EscapeAnalysisReducer::Finalize() { NodeProperties::SetType(load, Type::None()); NodeProperties::SetType(dead_value, Type::None()); NodeProperties::ReplaceUses(load, dead_value, load); + NodeProperties::ReplaceValueInput(dead_value, load, 0); continue; } diff --git a/deps/v8/src/compiler/simplified-operator.cc b/deps/v8/src/compiler/simplified-operator.cc index 80159d7cc658..47a492b01363 100644 --- a/deps/v8/src/compiler/simplified-operator.cc +++ b/deps/v8/src/compiler/simplified-operator.cc @@ -1167,9 +1167,12 @@ struct SimplifiedOperatorGlobalCache final { DEOPTIMIZE_REASON_LIST(CHECK_IF) #undef CHECK_IF + // Looking up a string key can internalize it in place into a ThinString, + // so Operator::kNoWrite (and thus Operator::kEliminatable) does not hold. struct FindOrderedHashMapEntryOperator final : public Operator { FindOrderedHashMapEntryOperator() - : Operator(IrOpcode::kFindOrderedHashMapEntry, Operator::kEliminatable, + : Operator(IrOpcode::kFindOrderedHashMapEntry, + Operator::kNoThrow | Operator::kNoDeopt, "FindOrderedHashMapEntry", 2, 1, 1, 1, 1, 0) {} }; FindOrderedHashMapEntryOperator kFindOrderedHashMapEntry; @@ -1183,9 +1186,12 @@ struct SimplifiedOperatorGlobalCache final { FindOrderedHashMapEntryForInt32KeyOperator kFindOrderedHashMapEntryForInt32Key; + // Looking up a string key can internalize it in place into a ThinString, + // so Operator::kNoWrite (and thus Operator::kEliminatable) does not hold. struct FindOrderedHashSetEntryOperator final : public Operator { FindOrderedHashSetEntryOperator() - : Operator(IrOpcode::kFindOrderedHashSetEntry, Operator::kEliminatable, + : Operator(IrOpcode::kFindOrderedHashSetEntry, + Operator::kNoThrow | Operator::kNoDeopt, "FindOrderedHashSetEntry", 2, 1, 1, 1, 1, 0) {} }; FindOrderedHashSetEntryOperator kFindOrderedHashSetEntry; diff --git a/deps/v8/src/compiler/turboshaft/builtin-call-descriptors.h b/deps/v8/src/compiler/turboshaft/builtin-call-descriptors.h index 9a72d2862a68..c514fece5b9f 100644 --- a/deps/v8/src/compiler/turboshaft/builtin-call-descriptors.h +++ b/deps/v8/src/compiler/turboshaft/builtin-call-descriptors.h @@ -300,15 +300,19 @@ struct builtin : CallDescriptorBuilder { static constexpr auto kFunction = B; struct Arguments : ArgumentsBase { ARG(V<Object>, table) - ARG(V<Smi>, key) + ARG(V<Object>, key) }; using returns_t = std::tuple<V<Smi>>; static constexpr bool kCanTriggerLazyDeopt = false; static constexpr bool kNeedsContext = true; - static constexpr Operator::Properties kProperties = Operator::kEliminatable; - static constexpr OpEffects kEffects = - base_effects.AssumesConsistentHeap().CanReadMemory().CanAllocate(); + static constexpr Operator::Properties kProperties = + Operator::kNoThrow | Operator::kNoDeopt; + // Looking up a string key can internalize it in place into a ThinString. + static constexpr OpEffects kEffects = base_effects.AssumesConsistentHeap() + .CanReadMemory() + .CanWriteHeapMemory() + .CanAllocate(); }; using FindOrderedHashMapEntry = FindOrderedHashEntry<Builtin::kFindOrderedHashMapEntry>; diff --git a/deps/v8/src/compiler/turboshaft/late-load-elimination-reducer.cc b/deps/v8/src/compiler/turboshaft/late-load-elimination-reducer.cc index 1a3e7d73aa46..b4e8819028a0 100644 --- a/deps/v8/src/compiler/turboshaft/late-load-elimination-reducer.cc +++ b/deps/v8/src/compiler/turboshaft/late-load-elimination-reducer.cc @@ -247,6 +247,12 @@ void LateLoadEliminationAnalyzer::ProcessBlock(const Block& block, break; case Opcode::kCatchBlockBegin: + // Throwing an exception can have arbitrary side effects (e.g., via + // debugger pause-on-exception), even when the throwing operation itself + // does not have `can_write` effects on its non-throwing path. + memory_.InvalidateMaybeAliasing(); + break; + case Opcode::kRetain: case Opcode::kDidntThrow: case Opcode::kCheckException: diff --git a/deps/v8/src/compiler/turboshaft/operations.h b/deps/v8/src/compiler/turboshaft/operations.h index 4d62936f230e..6e87f793f6a0 100644 --- a/deps/v8/src/compiler/turboshaft/operations.h +++ b/deps/v8/src/compiler/turboshaft/operations.h @@ -7478,8 +7478,22 @@ struct FindOrderedHashEntryOp }; Kind kind; - static constexpr OpEffects effects = - OpEffects().CanDependOnChecks().CanReadMemory().CanAllocate(); + OpEffects Effects() const { + switch (kind) { + case Kind::kFindOrderedHashMapEntry: + case Kind::kFindOrderedHashSetEntry: + // Looking up a string key can internalize it in place into a + // ThinString, overwriting its payload (e.g., ConsString::first_). + return OpEffects() + .CanDependOnChecks() + .CanReadMemory() + .CanWriteHeapMemory() + .CanAllocate(); + case Kind::kFindOrderedHashMapEntryForInt32Key: + return OpEffects().CanDependOnChecks().CanReadMemory(); + } + UNREACHABLE(); + } base::Vector<const RegisterRepresentation> outputs_rep() const { switch (kind) { case Kind::kFindOrderedHashMapEntry: @@ -11092,6 +11106,8 @@ inline OpEffects Operation::Effects() const { return Cast<StoreOp>().Effects(); case Opcode::kCall: return Cast<CallOp>().Effects(); + case Opcode::kFindOrderedHashEntry: + return Cast<FindOrderedHashEntryOp>().Effects(); case Opcode::kDidntThrow: return Cast<DidntThrowOp>().Effects(); case Opcode::kTaggedBitcast: diff --git a/deps/v8/src/compiler/turboshaft/wasm-load-elimination-reducer.cc b/deps/v8/src/compiler/turboshaft/wasm-load-elimination-reducer.cc index f5de6b1b0fd2..7d04cbb2ac65 100644 --- a/deps/v8/src/compiler/turboshaft/wasm-load-elimination-reducer.cc +++ b/deps/v8/src/compiler/turboshaft/wasm-load-elimination-reducer.cc @@ -141,11 +141,21 @@ void WasmLoadEliminationAnalyzer::ProcessBlock(const Block& block, memory_.InvalidateMutableSharedBase(); } break; + case Opcode::kCatchBlockBegin: + // Throwing an exception can have arbitrary side effects (e.g., via + // debugger pause-on-exception), even when the throwing operation itself + // does not have `can_write` effects on its non-throwing path. + memory_.InvalidateMaybeAliasing(); + break; + + case Opcode::kGlobalSet: + InvalidateIfAlias(op.Cast<GlobalSetOp>().value()); + break; + case Opcode::kMemoryCopy: case Opcode::kMemoryFill: // These should never operate on GC objects. case Opcode::kAssumeMap: - case Opcode::kCatchBlockBegin: case Opcode::kRetain: case Opcode::kDidntThrow: case Opcode::kCheckException: @@ -153,7 +163,6 @@ void WasmLoadEliminationAnalyzer::ProcessBlock(const Block& block, case Opcode::kJSStackCheck: case Opcode::kWasmStackCheck: case Opcode::kSimd128LaneMemory: - case Opcode::kGlobalSet: case Opcode::kWasmIncCoverageCounter: case Opcode::kParameter: case Opcode::kSetStackPointer: @@ -360,6 +369,10 @@ void WasmLoadEliminationAnalyzer::ProcessStore(OpIndex op_idx, // among threads. memory_.InvalidateMutableSharedBase(); } + + // Updating aliases if the value stored was known as non-aliasing (e.g., + // storing a struct reference into an exception values array). + InvalidateIfAlias(op.value()); } void WasmLoadEliminationAnalyzer::ProcessArrayGet(OpIndex op_idx, @@ -469,9 +482,6 @@ void WasmLoadEliminationAnalyzer::ProcessCall(OpIndex op_idx, // Some builtins do not create aliases and do not invalidate existing // memory, and some even return fresh objects. For such cases, we don't // invalidate the state, and record the non-alias if any. - if (!op.Effects().can_write()) { - return; - } // TODO(jkummerow): Add special handling to builtins that are known not to // have relevant side effects. Alternatively, specify their effects to not // include `CanWriteMemory()`. @@ -489,9 +499,12 @@ void WasmLoadEliminationAnalyzer::ProcessCall(OpIndex op_idx, #endif // Not a builtin call, or not a builtin that we know doesn't invalidate // memory. - InvalidateAllNonAliasingInputs(op); + if (!op.Effects().can_write()) { + return; + } + // The call could modify arbitrary memory, so we invalidate every // potentially-aliasing object. memory_.InvalidateMaybeAliasing(); diff --git a/deps/v8/src/compiler/verifier.cc b/deps/v8/src/compiler/verifier.cc index 39d2dbced497..2552221cd7e8 100644 --- a/deps/v8/src/compiler/verifier.cc +++ b/deps/v8/src/compiler/verifier.cc @@ -303,6 +303,7 @@ void Verifier::Visitor::Check(Node* node, const AllNodes& all) { UNREACHABLE(); case IrOpcode::kDeadValue: CheckValueInputIs(node, 0, Type::None()); + CHECK_NE(NodeProperties::GetValueInput(node, 0), node); CheckTypeIs(node, Type::None()); break; case IrOpcode::kUnreachable: diff --git a/deps/v8/src/diagnostics/objects-printer.cc b/deps/v8/src/diagnostics/objects-printer.cc index 96fb166732a6..6686aeb620a6 100644 --- a/deps/v8/src/diagnostics/objects-printer.cc +++ b/deps/v8/src/diagnostics/objects-printer.cc @@ -948,16 +948,25 @@ void JSGeneratorObject::JSGeneratorObjectPrint(std::ostream& os) { os << "\n - debug pos: " << Brief(input_or_debug_pos()); } const char* mode = "(invalid)"; - switch (resume_mode()) { + switch (static_cast<ResumeMode>(resume_mode())) { case kNext: mode = ".next()"; break; + case kNextTrySkipAlloc: + mode = ".next() (try skip alloc)"; + break; case kReturn: mode = ".return()"; break; case kThrow: mode = ".throw()"; break; + case kRethrow: + mode = ".throw() (rethrow)"; + break; + case kNextAllocSkipped: + mode = ".next() (alloc skipped)"; + break; } os << "\n - resume mode: " << mode; os << "\n - continuation: " << continuation(); diff --git a/deps/v8/src/execution/isolate.h b/deps/v8/src/execution/isolate.h index f8c0c95e78fd..a847348731cc 100644 --- a/deps/v8/src/execution/isolate.h +++ b/deps/v8/src/execution/isolate.h @@ -544,6 +544,7 @@ using DebugObjectCache = std::vector<Handle<HeapObject>>; V(bool, deoptimization_assert, true) \ V(bool, compilation_assert, true) \ V(bool, no_exception_assert, true) \ + V(bool, js_object_modification_assert, true) \ V(uint32_t, wasm_switch_to_the_central_stack_counter, 0) #define THREAD_LOCAL_TOP_ACCESSOR(type, name) \ diff --git a/deps/v8/src/handles/global-handles.cc b/deps/v8/src/handles/global-handles.cc index fa3079d554f8..33199ff15975 100644 --- a/deps/v8/src/handles/global-handles.cc +++ b/deps/v8/src/handles/global-handles.cc @@ -744,6 +744,7 @@ void GlobalHandles::ProcessWeakYoungObjects( void GlobalHandles::InvokeSecondPassPhantomCallbacks() { DCHECK(!AllowJavascriptExecution::IsAllowed(isolate())); + DCHECK(!AllowJSObjectModification::IsAllowed(isolate())); DCHECK(AllowGarbageCollection::IsAllowed()); if (second_pass_callbacks_.empty()) return; @@ -855,6 +856,8 @@ size_t GlobalHandles::InvokeFirstPassWeakCallbacks() { void GlobalHandles::PendingPhantomCallback::Invoke(Isolate* isolate, InvocationType type) { + DCHECK(!AllowJavascriptExecution::IsAllowed(isolate)); + DCHECK(!AllowJSObjectModification::IsAllowed(isolate)); Data::Callback* callback_addr = nullptr; if (type == kFirstPass) { callback_addr = &callback_; @@ -894,6 +897,7 @@ void GlobalHandles::PostGarbageCollectionProcessing( DCHECK(second_pass_callbacks_task_posted_); second_pass_callbacks_task_posted_ = false; DisallowJavascriptExecution no_js(isolate()); + DisallowJSObjectModification no_js_object_modification(isolate()); InvokeSecondPassPhantomCallbacks(); })); } diff --git a/deps/v8/src/heap/cppgc-js/cpp-heap.cc b/deps/v8/src/heap/cppgc-js/cpp-heap.cc index c1de0c1c279f..c23ec777922e 100644 --- a/deps/v8/src/heap/cppgc-js/cpp-heap.cc +++ b/deps/v8/src/heap/cppgc-js/cpp-heap.cc @@ -556,33 +556,42 @@ namespace { class SweepingOnMutatorThreadForGlobalHandlesScope final { public: - explicit SweepingOnMutatorThreadForGlobalHandlesScope( - TracedHandles& traced_handles) - : traced_handles_(traced_handles) { - traced_handles_.SetIsSweepingOnMutatorThread(true); + explicit SweepingOnMutatorThreadForGlobalHandlesScope(Isolate& isolate) + : isolate_(isolate), + no_js_(&isolate), + no_js_object_modification_(&isolate) { + isolate_.traced_handles()->SetIsSweepingOnMutatorThread(true); } ~SweepingOnMutatorThreadForGlobalHandlesScope() { - traced_handles_.SetIsSweepingOnMutatorThread(false); + isolate_.traced_handles()->SetIsSweepingOnMutatorThread(false); } - TracedHandles& traced_handles_; + private: + Isolate& isolate_; + // Mutator-thread sweeping runs CppHeap pre-finalizers and C++ destructors + // (both during the atomic pause and outside it via incremental sweep tasks or + // lazy sweeping on Oilpan allocation). Disallow JS execution and JSObject + // modification during these embedder finalizers. + DisallowJavascriptExecution no_js_; + DisallowJSObjectModification no_js_object_modification_; }; class SweepingOnMutatorThreadForGlobalHandlesObserver final : public cppgc::internal::Sweeper::SweepingOnMutatorThreadObserver { public: SweepingOnMutatorThreadForGlobalHandlesObserver(CppHeap& cpp_heap, - TracedHandles& traced_handles) + Isolate& isolate) : cppgc::internal::Sweeper::SweepingOnMutatorThreadObserver( cpp_heap.sweeper()), - traced_handles_(traced_handles) {} + isolate_(isolate) {} - void Start() override { traced_handles_.SetIsSweepingOnMutatorThread(true); } + void Start() override { scope_.emplace(isolate_); } - void End() override { traced_handles_.SetIsSweepingOnMutatorThread(false); } + void End() override { scope_.reset(); } private: - TracedHandles& traced_handles_; + Isolate& isolate_; + std::optional<SweepingOnMutatorThreadForGlobalHandlesScope> scope_; }; class MoveListenerImpl final : public HeapProfilerNativeMoveListener, @@ -644,7 +653,7 @@ void CppHeap::AttachIsolate(Isolate* isolate) { UpdateGCCapabilitiesFromFlags(); sweeping_on_mutator_thread_observer_ = std::make_unique<SweepingOnMutatorThreadForGlobalHandlesObserver>( - *this, *isolate_->traced_handles()); + *this, *isolate_); no_gc_scope_--; // Propagate overridden stack state to the attached heap, if necessary. @@ -994,6 +1003,10 @@ void CppHeap::FinishMarkingAndProcessWeakness() { { cppgc::subtle::DisallowGarbageCollectionScope disallow_gc_scope(*this); + if (isolate_) { + DCHECK(!AllowJavascriptExecution::IsAllowed(isolate_)); + DCHECK(!AllowJSObjectModification::IsAllowed(isolate_)); + } marker_->LeaveAtomicPause(); } marker_.reset(); @@ -1031,7 +1044,7 @@ void CppHeap::CompactAndSweep() { std::optional<SweepingOnMutatorThreadForGlobalHandlesScope> global_handles_scope; if (isolate_) { - global_handles_scope.emplace(*isolate_->traced_handles()); + global_handles_scope.emplace(*isolate_); } bytes_allocated_in_prefinalizers = ExecutePreFinalizers(); } @@ -1058,7 +1071,7 @@ void CppHeap::CompactAndSweep() { std::optional<SweepingOnMutatorThreadForGlobalHandlesScope> global_handles_scope; if (isolate_) { - global_handles_scope.emplace(*isolate_->traced_handles()); + global_handles_scope.emplace(*isolate_); } compactable_space_handling = compactor_.CompactSpacesIfEnabled(); } diff --git a/deps/v8/src/heap/gc-callbacks.h b/deps/v8/src/heap/gc-callbacks.h index e40e6b7de9be..ddc8c877af2e 100644 --- a/deps/v8/src/heap/gc-callbacks.h +++ b/deps/v8/src/heap/gc-callbacks.h @@ -39,6 +39,10 @@ class GCCallbacks final { AllowGarbageCollection scope; for (const CallbackData& callback_data : callbacks_) { if (gc_type & callback_data.gc_type) { + Isolate* isolate = reinterpret_cast<Isolate*>(callback_data.isolate); + USE(isolate); + DCHECK(!AllowJavascriptExecution::IsAllowed(isolate)); + DCHECK(!AllowJSObjectModification::IsAllowed(isolate)); callback_data.callback(callback_data.isolate, gc_type, gc_callback_flags, callback_data.user_data); } diff --git a/deps/v8/src/heap/heap.cc b/deps/v8/src/heap/heap.cc index a925a9eb1773..c08b0377c6c3 100644 --- a/deps/v8/src/heap/heap.cc +++ b/deps/v8/src/heap/heap.cc @@ -1419,6 +1419,7 @@ namespace { template <typename Callback> void InvokeExternalCallbacks(Isolate* isolate, Callback callback) { DCHECK(!AllowJavascriptExecution::IsAllowed(isolate)); + DCHECK(!AllowJSObjectModification::IsAllowed(isolate)); AllowGarbageCollection allow_gc; // Temporary override any embedder stack state as callbacks may create // their own state on the stack and recursively trigger GC. @@ -1466,8 +1467,14 @@ void Heap::CollectGarbage( // collection is triggered. Note that these callbacks may trigger another // garbage collection since they may allocate. - // JS execution is not allowed in any of the callbacks. + // JS execution and object modifications are not allowed during GC or in any + // of the embedder callbacks triggered below: first-pass weak callbacks + // (GlobalHandles::InvokeFirstPassWeakCallbacks), second-pass phantom + // callbacks (PostGarbageCollectionProcessing), GC prologue and epilogue + // callbacks (v8::Isolate::GCCallback), and CppHeap pre-finalizers and object + // finalizers (C++ destructors). DisallowJavascriptExecution no_js(isolate()); + DisallowJSObjectModification no_js_object_modification(isolate()); // Some custom flushing (currently: FlushBytecodeFromSFI) can create // fresh TrustedPointerTableEntries during GC. These must not be affected @@ -1829,6 +1836,13 @@ void Heap::StartIncrementalMarking(GCFlags gc_flags, return; } + // Completing sweeping below may trigger embedder CppHeap object finalizers + // (C++ destructors, via FinishSweepingIfRunning / FinishSweepingIfOutOfWork), + // and incremental_marking()->Start() triggers embedder GC prologue and + // epilogue callbacks. + DisallowJavascriptExecution no_js(isolate()); + DisallowJSObjectModification no_js_object_modification(isolate()); + TRACE_EVENT( "v8", perfetto::StaticString(IsYoungGenerationCollector(collector) diff --git a/deps/v8/src/interpreter/bytecode-generator.cc b/deps/v8/src/interpreter/bytecode-generator.cc index f6651020361a..1d5a0334e745 100644 --- a/deps/v8/src/interpreter/bytecode-generator.cc +++ b/deps/v8/src/interpreter/bytecode-generator.cc @@ -1618,6 +1618,7 @@ void BytecodeGenerator::AllocateDeferredConstants(IsolateT* isolate, } for (std::pair<Call*, Scope*> call : eval_calls_) { + DCHECK_EQ(call.second->GetClosureScope(), closure_scope()); Tagged<ScopeInfo> current; int index = call.first->eval_scope_info_index(); if (script->infos() @@ -6171,11 +6172,16 @@ void BytecodeGenerator::VisitYield(Yield* expr) { builder()->StoreAccumulatorInRegister(input).CallRuntime( Runtime::kInlineGeneratorGetResumeMode, generator_object()); - // Now dispatch on resume mode. - static_assert(JSGeneratorObject::kNext + 1 == JSGeneratorObject::kReturn); + // Now dispatch on resume mode. kNextAllocSkipped is never observed here; + // every resume path overwrites resume_mode_ first. + static_assert(JSGeneratorObject::kNext + 1 == + JSGeneratorObject::kNextTrySkipAlloc); + static_assert(JSGeneratorObject::kNextTrySkipAlloc + 1 == + JSGeneratorObject::kReturn); static_assert(JSGeneratorObject::kReturn + 1 == JSGeneratorObject::kThrow); + static_assert(JSGeneratorObject::kThrow + 1 == JSGeneratorObject::kRethrow); BytecodeJumpTable* jump_table = - builder()->AllocateJumpTable(is_async ? 3 : 2, JSGeneratorObject::kNext); + builder()->AllocateJumpTable(is_async ? 4 : 3, JSGeneratorObject::kNext); builder()->SwitchOnSmiNoFeedback(jump_table); @@ -6213,6 +6219,7 @@ void BytecodeGenerator::VisitYield(Yield* expr) { { // Resume with next. builder()->Bind(jump_table, JSGeneratorObject::kNext); + builder()->Bind(jump_table, JSGeneratorObject::kNextTrySkipAlloc); BuildIncrementBlockCoverageCounterIfEnabled(expr, SourceRangeKind::kContinuation); builder()->LoadAccumulatorWithRegister(input); @@ -6322,8 +6329,10 @@ void BytecodeGenerator::VisitYieldStar(YieldStar* expr) { { BytecodeLabels after_switch(zone()); + // The table is based at kReturn, so every mode below it (the whole + // kNext family) falls through to the default case below. BytecodeJumpTable* switch_jump_table = - builder()->AllocateJumpTable(2, 1); + builder()->AllocateJumpTable(2, JSGeneratorObject::kReturn); builder() ->LoadAccumulatorWithRegister(resume_mode) @@ -6331,8 +6340,11 @@ void BytecodeGenerator::VisitYieldStar(YieldStar* expr) { // Fallthrough to default case. // TODO(ignition): Add debug code to check that {resume_mode} really is - // {JSGeneratorObject::kNext} in this case. - static_assert(JSGeneratorObject::kNext == 0); + // {JSGeneratorObject::kNext} or + // {JSGeneratorObject::kNextTrySkipAlloc} in this case. + static_assert(JSGeneratorObject::kNext < JSGeneratorObject::kReturn); + static_assert(JSGeneratorObject::kNextTrySkipAlloc < + JSGeneratorObject::kReturn); { FeedbackSlot slot = feedback_spec()->AddCallICSlot(); builder()->CallProperty(iterator.next(), iterator_and_input, @@ -6340,7 +6352,8 @@ void BytecodeGenerator::VisitYieldStar(YieldStar* expr) { builder()->Jump(after_switch.New()); } - static_assert(JSGeneratorObject::kReturn == 1); + static_assert(JSGeneratorObject::kReturn + 1 == + JSGeneratorObject::kThrow); builder()->Bind(switch_jump_table, JSGeneratorObject::kReturn); { const AstRawString* return_string = @@ -6361,7 +6374,6 @@ void BytecodeGenerator::VisitYieldStar(YieldStar* expr) { } } - static_assert(JSGeneratorObject::kThrow == 2); builder()->Bind(switch_jump_table, JSGeneratorObject::kThrow); { const AstRawString* throw_string = @@ -6491,7 +6503,8 @@ void BytecodeGenerator::BuildAwait(int position) { Register input = register_allocator()->NewRegister(); Register resume_mode = register_allocator()->NewRegister(); - // Now dispatch on resume mode. + // Now dispatch on resume mode. The skip-allocation handshake is only set on + // JS_GENERATOR_OBJECT_TYPE receivers, which never await. BytecodeLabel resume_next; builder() ->StoreAccumulatorInRegister(input) @@ -7073,7 +7086,8 @@ void BytecodeGenerator::VisitCall(Call* expr) { private_name_lookup_skips_outer_class = scope_with_context->AsClassScope()->IsParsingHeritage(); } - if (scope_with_context) { + if (scope_with_context && + scope_with_context->IsOuterScopeUpToClosureScopeOf(current_scope())) { eval_calls_.emplace_back(expr, scope_with_context); } int eval_flags = ResolveEvalFlags::Encode( diff --git a/deps/v8/src/interpreter/interpreter-intrinsics-generator.cc b/deps/v8/src/interpreter/interpreter-intrinsics-generator.cc index 9a2521ddcfe6..b3b786851bcb 100644 --- a/deps/v8/src/interpreter/interpreter-intrinsics-generator.cc +++ b/deps/v8/src/interpreter/interpreter-intrinsics-generator.cc @@ -157,19 +157,20 @@ TNode<Object> IntrinsicsGenerator::GeneratorYieldResult( compiler::TypedCodeAssemblerVariable<Object> result(assembler_); compiler::CodeAssemblerLabel allocate(assembler_), allocate_done(assembler_); - // Check if yielded_value_ is TheHole (signaling to skip allocating the result - // object. - TNode<Object> current_yielded_value = assembler_->LoadObjectField( - assembler_->CAST(generator), offsetof(JSGeneratorObject, yielded_value_)); - assembler_->GotoIf(assembler_->TaggedNotEqual(current_yielded_value, - assembler_->TheHoleConstant()), - &allocate); - - // Store value - assembler_->StoreObjectField(assembler_->CAST(generator), - offsetof(JSGeneratorObject, yielded_value_), - value); - result = assembler_->TheHoleConstant(); + // Check whether the caller asked to skip result allocation + // (resume_mode_ == kNextTrySkipAlloc). + TNode<Object> mode = assembler_->LoadObjectField( + assembler_->CAST(generator), offsetof(JSGeneratorObject, resume_mode_)); + assembler_->GotoIf( + assembler_->TaggedNotEqual( + mode, assembler_->SmiConstant(JSGeneratorObject::kNextTrySkipAlloc)), + &allocate); + + // Skip allocation: ack handshake and return bare value. + assembler_->StoreObjectField( + assembler_->CAST(generator), offsetof(JSGeneratorObject, resume_mode_), + assembler_->SmiConstant(JSGeneratorObject::kNextAllocSkipped)); + result = value; assembler_->Goto(&allocate_done); assembler_->Bind(&allocate); diff --git a/deps/v8/src/maglev/maglev-graph-builder.cc b/deps/v8/src/maglev/maglev-graph-builder.cc index 05a3fa8fcb50..69fe4b26b5ef 100644 --- a/deps/v8/src/maglev/maglev-graph-builder.cc +++ b/deps/v8/src/maglev/maglev-graph-builder.cc @@ -516,11 +516,13 @@ void MaglevGraphBuilder::MaglevSubGraphBuilder::EndLoop(LoopLabel* loop_label) { void MaglevGraphBuilder::MaglevSubGraphBuilder::Bind(Label* label) { DCHECK_NULL(builder_->current_block()); + CHECK_NOT_NULL(label->variable_merge_state_); DCHECK_NULL(variable_frame_.known_node_aspects()); variable_frame_.CopyFrom(*dummy_unit_, *label->variable_merge_state_); if (label->ShouldTrackInterpreterFrameState()) { + DCHECK_NOT_NULL(label->merge_state_); DCHECK_EQ(*label->future_bind_offset_, builder_->iterator_.current_offset()); builder_->current_interpreter_frame_.CopyFrom(*compilation_unit(), @@ -545,6 +547,9 @@ void MaglevGraphBuilder::MaglevSubGraphBuilder::Bind(Label* label) { builder_->ProcessMergePointPredecessors(*label->variable_merge_state_, label->ref_); builder_->StartNewBlock(nullptr, label->variable_merge_state_, label->ref_); + + label->variable_merge_state_ = nullptr; + label->merge_state_ = nullptr; } template <typename FCond, typename FTrue, typename FFalse> @@ -8421,6 +8426,10 @@ MaybeReduceResult MaglevGraphBuilder::TryReduceGeneratorPrototypeNext( ValueNode* executing_constant = GetSmiConstant(JSGeneratorObject::kGeneratorExecuting); ValueNode* next_constant = GetSmiConstant(JSGeneratorObject::kNext); + ValueNode* try_skip_alloc_constant = + GetSmiConstant(JSGeneratorObject::kNextTrySkipAlloc); + ValueNode* alloc_skipped_constant = + GetSmiConstant(JSGeneratorObject::kNextAllocSkipped); // If any of the constants have an empty type, we're in dead code, and the // write barrier elision logic inside StoreTaggedFieldNoWriteBarrier will be @@ -8431,13 +8440,14 @@ MaybeReduceResult MaglevGraphBuilder::TryReduceGeneratorPrototypeNext( ABORT_IF_EMPTY_TYPE(closed_constant); ABORT_IF_EMPTY_TYPE(executing_constant); ABORT_IF_EMPTY_TYPE(next_constant); - - // The fast path below asks the generator to store the yielded value into - // yielded_value_ rather than allocate a result object, and rebuilds the - // object here as a VirtualObject that escape analysis can then elide. A - // current try-catch block, either in this function or in a caller we were - // inlined into, defeats that as would pay for the protocol and allocate - // anyway. + ABORT_IF_EMPTY_TYPE(try_skip_alloc_constant); + ABORT_IF_EMPTY_TYPE(alloc_skipped_constant); + + // The fast path below asks the generator to hand back the bare yielded value + // rather than allocate a result object, and rebuilds the object here as a + // VirtualObject that escape analysis can then elide. A current try-catch + // block, either in this function or in a caller we were inlined into, + // defeats that as would pay for the protocol and allocate anyway. const bool can_skip_allocation = GetCurrentTryCatchBlock().ref == nullptr; MaglevSubGraphBuilder::Label generator_already_closed(&subgraph, 1); @@ -8459,19 +8469,12 @@ MaybeReduceResult MaglevGraphBuilder::TryReduceGeneratorPrototypeNext( AssertCondition::kNotEqual, DeoptimizeReason::kWrongValue)); CHECK(BuildStoreTaggedFieldNoWriteBarrier( - receiver, next_constant, offsetof(JSGeneratorObject, resume_mode_), + receiver, + can_skip_allocation ? try_skip_alloc_constant : next_constant, + offsetof(JSGeneratorObject, resume_mode_), StoreTaggedMode::kDefault) .IsDoneWithoutAbort()); - // Tell the generator to skip allocating the result object if possible. - if (can_skip_allocation) { - CHECK(BuildStoreTaggedFieldNoWriteBarrier( - receiver, GetRootConstant(RootIndex::kTheHoleValue), - offsetof(JSGeneratorObject, yielded_value_), - StoreTaggedMode::kDefault) - .IsDoneWithoutAbort()); - } - ValueNode* result; { LazyDeoptFrameScope lazy_deopt_scope( @@ -8502,33 +8505,23 @@ MaybeReduceResult MaglevGraphBuilder::TryReduceGeneratorPrototypeNext( if (can_skip_allocation) { MaglevSubGraphBuilder::Label allocation_not_skipped(&subgraph, 1); - ValueNode* yielded_value; - GET_VALUE(yielded_value, - BuildLoadTaggedField( - receiver, offsetof(JSGeneratorObject, yielded_value_))); - // We unconditionally clear yielded_value_ here. If the generator did - // not hit the GeneratorYieldResult intrinsic (if it suspended via - // yield*), yielded_value_ would still hold TheHole. If it leaked to JS - // space (e.g., on a subsequent unoptimized next() call), it could cause - // a crash when JS attempts to access its properties. - CHECK(BuildStoreTaggedFieldNoWriteBarrier( - receiver, GetRootConstant(RootIndex::kUndefinedValue), - offsetof(JSGeneratorObject, yielded_value_), - StoreTaggedMode::kDefault) - .IsDoneWithoutAbort()); // Check whether skipping allocating the result object was successful. + ValueNode* generator_mode; + GET_VALUE(generator_mode, + BuildLoadTaggedField(receiver, + offsetof(JSGeneratorObject, resume_mode_))); CHECK(subgraph - .GotoIfFalse<BranchIfRootConstant>( - &allocation_not_skipped, {result}, RootIndex::kTheHoleValue) + .GotoIfFalse<BranchIfReferenceEqual>( + &allocation_not_skipped, + {generator_mode, alloc_skipped_constant}) .IsDoneWithoutAbort()); - // Was able to avoid allocating the result object. Use - // yielded_value from the generator object. + // Was able to avoid allocating the result object. compiler::MapRef map = broker()->target_native_context().iterator_result_map(broker()); - VirtualObject* iter_result = reducer_.CreateJSIteratorResult( - map, yielded_value, GetBooleanConstant(false)); + VirtualObject* iter_result = + reducer_.CreateJSIteratorResult(map, result, GetBooleanConstant(false)); ValueNode* alloc_result; GET_VALUE(alloc_result, reducer_.BuildInlinedAllocation( iter_result, AllocationType::kYoung)); @@ -12353,12 +12346,12 @@ ReduceResult MaglevGraphBuilder::VisitIntrinsicGeneratorYieldResult( compiler::MapRef map = broker()->target_native_context().iterator_result_map(broker()); - // Check if yielded_value_ is TheHole (signaling to skip allocating the result - // object). - ValueNode* current_yielded_value; - GET_VALUE_OR_ABORT(current_yielded_value, - BuildLoadTaggedField(generator, offsetof(JSGeneratorObject, - yielded_value_))); + // Check whether the caller asked to skip result allocation + // (resume_mode_ == kNextTrySkipAlloc). + ValueNode* mode; + GET_VALUE_OR_ABORT( + mode, BuildLoadTaggedField(generator, + offsetof(JSGeneratorObject, resume_mode_))); Subgraph<MaglevGraphBuilder> subgraph(&reducer_, 1); Subgraph<MaglevGraphBuilder>::Variable ret_val(0); @@ -12366,14 +12359,17 @@ ReduceResult MaglevGraphBuilder::VisitIntrinsicGeneratorYieldResult( RETURN_IF_ABORT(subgraph.Branch( {&ret_val}, [&](BranchBuilder& builder) { - return BuildBranchIfRootConstant(builder, current_yielded_value, - RootIndex::kTheHoleValue); + return BuildBranchIfReferenceEqual( + builder, mode, + GetSmiConstant(JSGeneratorObject::kNextTrySkipAlloc)); }, [&] { + // Skip allocation: ack handshake and return bare value. RETURN_IF_ABORT(BuildStoreTaggedField( - generator, value, offsetof(JSGeneratorObject, yielded_value_), + generator, GetSmiConstant(JSGeneratorObject::kNextAllocSkipped), + offsetof(JSGeneratorObject, resume_mode_), StoreTaggedMode::kDefault)); - subgraph.set(ret_val, GetRootConstant(RootIndex::kTheHoleValue)); + subgraph.set(ret_val, value); return ReduceResult::Done(); }, [&] { diff --git a/deps/v8/src/maglev/maglev-graph-optimizer.cc b/deps/v8/src/maglev/maglev-graph-optimizer.cc index e0e64964a520..259732b5a518 100644 --- a/deps/v8/src/maglev/maglev-graph-optimizer.cc +++ b/deps/v8/src/maglev/maglev-graph-optimizer.cc @@ -389,8 +389,10 @@ void Subgraph<MaglevGraphOptimizer>::Goto(Label* label) { void Subgraph<MaglevGraphOptimizer>::Bind(Label* label) { DCHECK_NULL(reducer_->current_block()); - DCHECK_NOT_NULL(label->variable_merge_state_); + CHECK_NOT_NULL(label->variable_merge_state_); + DCHECK_NULL(label->merge_state_); MergePointInterpreterFrameState* merge_state = label->variable_merge_state_; + label->variable_merge_state_ = nullptr; DCHECK_EQ(merge_state->predecessors_so_far(), label->predecessor_count_); DCHECK_GT(label->predecessor_count_, 0); diff --git a/deps/v8/src/maglev/maglev-ir.h b/deps/v8/src/maglev/maglev-ir.h index a2badf6c94ce..c1b16a843499 100644 --- a/deps/v8/src/maglev/maglev-ir.h +++ b/deps/v8/src/maglev/maglev-ir.h @@ -7975,9 +7975,11 @@ class MapPrototypeGet : public FixedInputValueNodeT<2, MapPrototypeGet> { public: explicit MapPrototypeGet(uint64_t bitfield) : Base(bitfield) {} + // Looking up a string key can allocate and internalize the key in place. static constexpr OpProperties kProperties = OpProperties::Call() | OpProperties::CanAllocate() | - OpProperties::CanRead() | OpProperties::TaggedValue(); + OpProperties::CanRead() | OpProperties::CanWrite() | + OpProperties::TaggedValue(); DECLARE_INPUTS(Table, Key) DECLARE_INPUT_TYPES(Tagged, Tagged) @@ -8009,11 +8011,11 @@ class SetPrototypeHas : public FixedInputValueNodeT<2, SetPrototypeHas> { public: explicit SetPrototypeHas(uint64_t bitfield) : Base(bitfield) {} - // CanAllocate is needed, since finding strings in hash tables does an - // equality comparison which flattens strings. + // Looking up a string key can allocate and internalize the key in place. static constexpr OpProperties kProperties = OpProperties::Call() | OpProperties::CanAllocate() | - OpProperties::CanRead() | OpProperties::TaggedValue(); + OpProperties::CanRead() | OpProperties::CanWrite() | + OpProperties::TaggedValue(); DECLARE_INPUTS(Table, Key) DECLARE_INPUT_TYPES(Tagged, Tagged) diff --git a/deps/v8/src/maglev/maglev-reducer.h b/deps/v8/src/maglev/maglev-reducer.h index ef286e3e6b14..300a29365fcb 100644 --- a/deps/v8/src/maglev/maglev-reducer.h +++ b/deps/v8/src/maglev/maglev-reducer.h @@ -1928,6 +1928,21 @@ class SubgraphBase { // NOLINTNEXTLINE(runtime/explicit) Label(const LabelForTrackingInterpreterFrameState& label); + Label(const Label&) = delete; + Label(Label&&) = delete; + Label& operator=(const Label&) = delete; + Label& operator=(Label&&) = delete; + + ~Label() { + // If variable_merge_state_ is non-null, at least one finalized BasicBlock + // in the graph has a control node whose BasicBlockRef is linked into + // `ref_` (in kRefList state) waiting for Bind() to resolve it to a target + // BasicBlock*. Destroying an unbound Label with live predecessors would + // leave dangling BasicBlockRef* pointers in the graph. + CHECK_NULL(variable_merge_state_); + DCHECK_NULL(merge_state_); + } + BasicBlockRef* ref() { return &ref_; } int predecessor_count() const { return predecessor_count_; } bool ShouldTrackInterpreterFrameState() const { diff --git a/deps/v8/src/objects/js-generator.h b/deps/v8/src/objects/js-generator.h index 874ab784e845..428231e898aa 100644 --- a/deps/v8/src/objects/js-generator.h +++ b/deps/v8/src/objects/js-generator.h @@ -23,7 +23,14 @@ V8_OBJECT class JSGeneratorObject : public JSObject { V8_IT_OWN_TYPE; public: - enum ResumeMode { kNext, kReturn, kThrow, kRethrow }; + enum ResumeMode { + kNext, + kNextTrySkipAlloc, + kReturn, + kThrow, + kRethrow, + kNextAllocSkipped + }; inline Tagged<JSFunction> function() const; inline void set_function(Tagged<JSFunction> value, diff --git a/deps/v8/src/objects/js-generator.tq b/deps/v8/src/objects/js-generator.tq index 77ca66a81672..f4384965c5e9 100644 --- a/deps/v8/src/objects/js-generator.tq +++ b/deps/v8/src/objects/js-generator.tq @@ -9,6 +9,8 @@ const kGeneratorClosed: constexpr int31 generates 'JSGeneratorObject::kGeneratorClosed'; const kGeneratorResumeModeNext: constexpr int31 generates 'JSGeneratorObject::kNext'; +const kGeneratorResumeModeNextAllocSkipped: + constexpr int31 generates 'JSGeneratorObject::kNextAllocSkipped'; const kGeneratorResumeModeThrow: constexpr int31 generates 'JSGeneratorObject::kThrow'; diff --git a/deps/v8/src/objects/js-objects.cc b/deps/v8/src/objects/js-objects.cc index 69e7d3101a5d..ce77a72da60d 100644 --- a/deps/v8/src/objects/js-objects.cc +++ b/deps/v8/src/objects/js-objects.cc @@ -968,6 +968,7 @@ void JSReceiver::DeleteNormalizedProperty(DirectHandle<JSReceiver> object, InternalIndex entry) { DCHECK(!object->HasFastProperties()); Isolate* isolate = Isolate::Current(); + CHECK(AllowJSObjectModification::IsAllowed(isolate)); DCHECK(entry.is_found()); if (IsJSGlobalObject(*object)) { @@ -2866,6 +2867,7 @@ Maybe<bool> JSObject::SetNormalizedProperty(DirectHandle<JSObject> object, DCHECK(!object->HasFastProperties()); DCHECK(IsUniqueName(*name)); Isolate* isolate = Isolate::Current(); + CHECK(AllowJSObjectModification::IsAllowed(isolate)); uint32_t hash = name->hash(); @@ -3557,6 +3559,7 @@ void MigrateFastToSlow(Isolate* isolate, DirectHandle<JSObject> object, void JSObject::MigrateToMap(Isolate* isolate, DirectHandle<JSObject> object, DirectHandle<Map> new_map, int expected_additional_properties) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); if (object->map() == *new_map) return; DirectHandle<Map> old_map(object->map(), isolate); NotifyMapChange(old_map, new_map, isolate); @@ -3995,9 +3998,10 @@ void JSObject::NormalizeProperties(Isolate* isolate, void JSObject::MigrateSlowToFast(DirectHandle<JSObject> object, int unused_property_fields, const char* reason) { + Isolate* isolate = Isolate::Current(); + CHECK(AllowJSObjectModification::IsAllowed(isolate)); if (object->HasFastProperties()) return; DCHECK(!IsJSGlobalObject(*object)); - Isolate* isolate = Isolate::Current(); Factory* factory = isolate->factory(); DirectHandle<NameDictionary> dictionary; @@ -5515,6 +5519,7 @@ Maybe<bool> JSObject::SetPrototype(Isolate* isolate, // static void JSObject::SetImmutableProto(Isolate* isolate, DirectHandle<JSObject> object) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); DirectHandle<Map> map(object->map(), isolate); // Nothing to do if prototype is already set. @@ -5611,6 +5616,7 @@ Maybe<bool> JSObject::AddDataElement(Isolate* isolate, DirectHandle<JSObject> object, uint32_t index, DirectHandle<Object> value, PropertyAttributes attributes) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); DCHECK(object->map()->is_extensible()); uint32_t old_length = 0; diff --git a/deps/v8/src/objects/lookup.cc b/deps/v8/src/objects/lookup.cc index 872d78cc45bd..27af06bca45b 100644 --- a/deps/v8/src/objects/lookup.cc +++ b/deps/v8/src/objects/lookup.cc @@ -433,6 +433,7 @@ void LookupIterator::InternalUpdateProtector( } void LookupIterator::PrepareForDataProperty(DirectHandle<Object> value) { + CHECK(AllowJSObjectModification::IsAllowed(isolate_)); DCHECK(state_ == DATA || state_ == ACCESSOR); DCHECK(HolderIsReceiverOrHiddenPrototype()); DCHECK(!IsWasmObject(*receiver_)); @@ -565,6 +566,7 @@ void LookupIterator::PrepareForDataProperty(DirectHandle<Object> value) { void LookupIterator::ReconfigureDataProperty(DirectHandle<Object> value, PropertyAttributes attributes) { + CHECK(AllowJSObjectModification::IsAllowed(isolate_)); DCHECK(state_ == DATA || state_ == ACCESSOR); DCHECK(HolderIsReceiverOrHiddenPrototype()); @@ -733,6 +735,7 @@ void LookupIterator::PrepareTransitionToDataProperty( Maybe<bool> LookupIterator::ApplyTransitionToDataProperty( DirectHandle<JSTransitionableReceiver> receiver, Maybe<ShouldThrow> should_throw) { + CHECK(AllowJSObjectModification::IsAllowed(isolate_)); DCHECK_EQ(TRANSITION, state_); DCHECK_IMPLIES(!receiver.is_identical_to(GetStoreTarget<JSReceiver>()), @@ -827,6 +830,7 @@ Maybe<bool> LookupIterator::ApplyTransitionToDataProperty( } void LookupIterator::Delete() { + CHECK(AllowJSObjectModification::IsAllowed(isolate_)); DirectHandle<JSReceiver> holder = Cast<JSReceiver>(holder_); if (IsElement(*holder)) { DirectHandle<JSObject> object = Cast<JSObject>(holder); diff --git a/deps/v8/src/objects/map-inl.h b/deps/v8/src/objects/map-inl.h index 63cfe9edd10f..ff8f439cf177 100644 --- a/deps/v8/src/objects/map-inl.h +++ b/deps/v8/src/objects/map-inl.h @@ -959,6 +959,7 @@ void Map::clear_padding() { } void Map::AppendDescriptor(Isolate* isolate, Descriptor* desc) { + DCHECK(AllowJSObjectModification::IsAllowed(isolate)); Tagged<DescriptorArray> descriptors = instance_descriptors(); int number_of_own_descriptors = NumberOfOwnDescriptors(); DCHECK(descriptors->number_of_descriptors() == number_of_own_descriptors); diff --git a/deps/v8/src/objects/map-updater.cc b/deps/v8/src/objects/map-updater.cc index 84999a3a34da..e9112f7713ba 100644 --- a/deps/v8/src/objects/map-updater.cc +++ b/deps/v8/src/objects/map-updater.cc @@ -1268,6 +1268,7 @@ void MapUpdater::UpdateFieldType(Isolate* isolate, DirectHandle<Map> map, PropertyConstness new_constness, Representation new_representation, DirectHandle<FieldType> new_type) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); // We store raw pointers in the queue, so no allocations are allowed. DisallowGarbageCollection no_gc; PropertyDetails details = map->instance_descriptors()->GetDetails(descriptor); diff --git a/deps/v8/src/objects/map.cc b/deps/v8/src/objects/map.cc index cdc41455019e..f10d4647fd60 100644 --- a/deps/v8/src/objects/map.cc +++ b/deps/v8/src/objects/map.cc @@ -709,6 +709,7 @@ Map::FieldCounts Map::GetFieldCounts() const { } void Map::DeprecateTransitionTree(Isolate* isolate) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); DCHECK(CanBeDeprecated()); return DeprecateTransitionTreeImpl(isolate); } @@ -736,6 +737,7 @@ void Map::DeprecateTransitionTreeImpl(Isolate* isolate) { // proper sharing of descriptor arrays. void Map::ReplaceDescriptors(Isolate* isolate, Tagged<DescriptorArray> new_descriptors) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); // Don't overwrite the empty descriptor array or initial map's descriptors. if (NumberOfOwnDescriptors() == 0 || IsUndefined(GetBackPointer())) { return; @@ -912,6 +914,7 @@ DirectHandle<Map> Map::Update(Isolate* isolate, DirectHandle<Map> map) { void Map::EnsureDescriptorSlack(Isolate* isolate, DirectHandle<Map> map, int slack) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); // Only supports adding slack to owned descriptors. CHECK(map->owns_descriptors()); @@ -1628,6 +1631,7 @@ void Map::ConnectTransition(Isolate* isolate, DirectHandle<Map> parent, DirectHandle<Map> child, DirectHandle<Name> name, TransitionKindFlag transition_kind, bool force_connect) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); DCHECK_EQ(parent->map(), child->map()); DCHECK_IMPLIES(name->IsInteresting(isolate), child->may_have_interesting_properties()); diff --git a/deps/v8/src/objects/transitions.cc b/deps/v8/src/objects/transitions.cc index 0c0ac419f30d..5f79fea14e80 100644 --- a/deps/v8/src/objects/transitions.cc +++ b/deps/v8/src/objects/transitions.cc @@ -413,6 +413,7 @@ bool TransitionsAccessor::PutPrototypeTransition(Isolate* isolate, DirectHandle<Map> map, DirectHandle<Object> prototype, DirectHandle<Map> target_map) { + CHECK(AllowJSObjectModification::IsAllowed(isolate)); DCHECK(IsUndefined(map->GetBackPointer())); DCHECK_NE(map->prototype(), *prototype); DCHECK(IsMap(Cast<HeapObject>(*prototype)->map())); diff --git a/deps/v8/src/runtime/runtime-compiler.cc b/deps/v8/src/runtime/runtime-compiler.cc index f195b42d3109..f37efcfbb018 100644 --- a/deps/v8/src/runtime/runtime-compiler.cc +++ b/deps/v8/src/runtime/runtime-compiler.cc @@ -857,11 +857,15 @@ static Tagged<Object> CompileGlobalEval( DirectHandle<JSFunction> compiled; DirectHandle<Context> context(isolate->context(), isolate); if (!Is<NativeContext>(*context)) { - Tagged<WeakFixedArray> array = Cast<Script>(outer_info->script())->infos(); + Tagged<Script> script = Cast<Script>(outer_info->script()); + Tagged<WeakFixedArray> array = script->infos(); Tagged<ScopeInfo> stored_info; - CHECK(array->get(eval_scope_info_index) - .GetHeapObjectIfWeak(isolate, &stored_info)); - CHECK_EQ(stored_info, context->scope_info()); + if (array->get(eval_scope_info_index) + .GetHeapObjectIfWeak(isolate, &stored_info)) { + CHECK_EQ(stored_info, context->scope_info()); + } else { + CHECK_EQ(outer_info->GetOuterScopeInfo(), context->scope_info()); + } } ASSIGN_RETURN_ON_EXCEPTION_VALUE( isolate, compiled, diff --git a/deps/v8/test/inspector/inspector.status b/deps/v8/test/inspector/inspector.status index a72ba8c9f1de..2a5bbb71c845 100644 --- a/deps/v8/test/inspector/inspector.status +++ b/deps/v8/test/inspector/inspector.status @@ -75,6 +75,7 @@ 'cpu-profiler/console-profile-wasm': [SKIP], 'runtime/get-properties': [SKIP], 'regress/regress-577352626': [SKIP], + 'regress/regress-581361633': [SKIP], 'regress/regress-crbug-349248170': [SKIP], }], # not has_webassembly or variant == jitless diff --git a/deps/v8/test/inspector/regress/regress-581361633-expected.txt b/deps/v8/test/inspector/regress/regress-581361633-expected.txt new file mode 100644 index 000000000000..e6d3b8e67ffa --- /dev/null +++ b/deps/v8/test/inspector/regress/regress-581361633-expected.txt @@ -0,0 +1,3 @@ +Regression test for crbug.com/581361633. +pauseCount: 2 +runProbe() -> 405051 diff --git a/deps/v8/test/inspector/regress/regress-581361633.js b/deps/v8/test/inspector/regress/regress-581361633.js new file mode 100644 index 000000000000..66d64e411231 --- /dev/null +++ b/deps/v8/test/inspector/regress/regress-581361633.js @@ -0,0 +1,141 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --allow-natives-syntax --no-wasm-trap-handler +// Flags: --stress-wasm-memory-moving + +const {session, contextGroup, Protocol} = + InspectorTest.start('Regression test for crbug.com/581361633.'); + +contextGroup.addScript(utils.read('test/mjsunit/wasm/wasm-module-builder.js')); + +contextGroup.addScript(` +const builder = new WasmModuleBuilder(); +builder.addMemory(1, 10); +builder.exportMemoryAs('mem'); +const structType = builder.addStruct([makeField(kWasmI32, true)]); +const globalStruct = + builder.addGlobal(wasmRefNullType(structType), true, false); +const tag = builder.addTag(kSig_v_v); +const setupIdx = builder.addImport('env', 'setup', kSig_v_v); +const intToStringIdx = builder.addImport( + 'env', 'intToString', + makeSig([kWasmI32, kWasmI32], [kWasmExternRef])); + +builder.addFunction('mutateStruct', kSig_v_i) + .addBody([ + kExprGlobalGet, globalStruct.index, + kExprLocalGet, 0, + kGCPrefix, kExprStructSet, structType, 0, + ]) + .exportFunc(); + +builder.addFunction('probe', kSig_i_v) + .addLocals(wasmRefNullType(structType), 1) + .addLocals(kWasmI32, 1) + .addBody([ + kExprCallFunction, setupIdx, + + // Allocate a fresh struct, store it in a global, and read its field + // before the first try_table so WasmLoadEliminationReducer caches + // field 0 = 10. + kExprI32Const, 10, + kGCPrefix, kExprStructNew, structType, + kExprLocalTee, 0, + kExprGlobalSet, globalStruct.index, + kExprLocalGet, 0, + kGCPrefix, kExprStructGet, structType, 0, + kExprDrop, + + // Pre-throw memory access so LateLoadEliminationReducer caches + // memory0_start before the first try_table. + kExprI32Const, 0, + kExprI32Const, 0x11, + kExprI32StoreMem, 2, 0, + + // 1. Throw via WasmThrow inside try_table. + kExprBlock, kWasmVoid, + kExprTryTable, kWasmVoid, 1, + kCatchAllNoRef, 0, + kExprThrow, tag, + kExprEnd, + kExprEnd, + + // Post-catch memory access and struct field load after WasmThrow: + // both must reload after the catch block (and this also re-caches + // memory0_start and field 0 before the second try_table). + kExprI32Const, 0, + kExprI32Const, 0x22, + kExprI32StoreMem, 2, 0, + kExprLocalGet, 0, + kGCPrefix, kExprStructGet, structType, 0, + kExprLocalSet, 1, + + // 2. Throw via well-known import WasmIntToString (invalid radix 37) + // inside try_table. + kExprBlock, kWasmVoid, + kExprTryTable, kWasmVoid, 1, + kCatchAllNoRef, 0, + kExprI32Const, 42, + kExprI32Const, 37, + kExprCallFunction, intToStringIdx, + kExprDrop, + kExprEnd, + kExprEnd, + + // Post-catch memory access and struct field load after WasmIntToString. + kExprI32Const, 0, + kExprI32Const, 0x33, + kExprI32StoreMem, 2, 0, + kExprLocalGet, 1, + ...wasmI32Const(100), + kExprI32Mul, + kExprLocalGet, 0, + kGCPrefix, kExprStructGet, structType, 0, + kExprI32Add, + ]) + .exportFunc(); + +function setup() { + console.log('setup'); + inspector.runNestedMessageLoop(); +} + +const intToString = Function.prototype.call.bind(Number.prototype.toString); +const instance = builder.instantiate({env: {setup, intToString}}); +const mem = instance.exports.mem; +%WasmTierUpFunction(instance.exports.probe); + +function runProbe() { + const res = instance.exports.probe(); + return res * 100 + new Uint8Array(mem.buffer)[0]; +} +`); + +let pauseCount = 0; +Protocol.Debugger.onPaused(async () => { + pauseCount++; + const newFieldVal = pauseCount === 1 ? 40 : 50; + await Protocol.Runtime.evaluate({ + expression: `mem.grow(1); instance.exports.mutateStruct(${newFieldVal});` + }); + await Protocol.Debugger.resume(); +}); + +(async () => { + await Protocol.Runtime.enable(); + + const consolePromise = Protocol.Runtime.onceConsoleAPICalled(); + const evalPromise = Protocol.Runtime.evaluate({expression: 'runProbe()'}); + + await consolePromise; + await Protocol.Debugger.enable(); + await Protocol.Debugger.setPauseOnExceptions({state: 'all'}); + await Protocol.Runtime.runIfWaitingForDebugger(); + + const {result} = await evalPromise; + InspectorTest.log('pauseCount: ' + pauseCount); + InspectorTest.log('runProbe() -> ' + result.result.value); + InspectorTest.completeTest(); +})(); diff --git a/deps/v8/test/mjsunit/compiler/regress-577461556.js b/deps/v8/test/mjsunit/compiler/regress-577461556.js new file mode 100644 index 000000000000..a3e836aa001b --- /dev/null +++ b/deps/v8/test/mjsunit/compiler/regress-577461556.js @@ -0,0 +1,58 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --allow-natives-syntax + +const receiver = {prefix_for_key_check_long_enough: 0x1234}; + +function testMapHas(obj, map, suffix) { + const key = 'prefix_for_key_check_long_enough' + suffix; + const has = map.has(key); + return [obj[key], has]; +} + +function testMapGet(obj, map, suffix) { + const key = 'prefix_for_key_check_long_enough' + suffix; + const val = map.get(key); + return [obj[key], val]; +} + +function testSetHas(obj, set, suffix) { + const key = 'prefix_for_key_check_long_enough' + suffix; + const has = set.has(key); + return [obj[key], has]; +} + +// Map.prototype.has +{ + const map = new Map([['prefix_for_key_check_long_enough_hit', 42]]); + %PrepareFunctionForOptimization(testMapHas); + assertEquals([0x1234, false], testMapHas(receiver, map, '')); + assertEquals([0x1234, false], testMapHas(receiver, map, '')); + %OptimizeFunctionOnNextCall(testMapHas); + assertEquals([undefined, false], testMapHas(receiver, map, '_miss')); + assertEquals([undefined, true], testMapHas(receiver, map, '_hit')); +} + +// Map.prototype.get +{ + const map = new Map([['prefix_for_key_check_long_enough_hit', 42]]); + %PrepareFunctionForOptimization(testMapGet); + assertEquals([0x1234, undefined], testMapGet(receiver, map, '')); + assertEquals([0x1234, undefined], testMapGet(receiver, map, '')); + %OptimizeFunctionOnNextCall(testMapGet); + assertEquals([undefined, undefined], testMapGet(receiver, map, '_miss')); + assertEquals([undefined, 42], testMapGet(receiver, map, '_hit')); +} + +// Set.prototype.has +{ + const set = new Set(['prefix_for_key_check_long_enough_hit']); + %PrepareFunctionForOptimization(testSetHas); + assertEquals([0x1234, false], testSetHas(receiver, set, '')); + assertEquals([0x1234, false], testSetHas(receiver, set, '')); + %OptimizeFunctionOnNextCall(testSetHas); + assertEquals([undefined, false], testSetHas(receiver, set, '_miss')); + assertEquals([undefined, true], testSetHas(receiver, set, '_hit')); +} diff --git a/deps/v8/test/mjsunit/compiler/regress-579278668.js b/deps/v8/test/mjsunit/compiler/regress-579278668.js new file mode 100644 index 000000000000..ae5ba2d6d109 --- /dev/null +++ b/deps/v8/test/mjsunit/compiler/regress-579278668.js @@ -0,0 +1,47 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --allow-natives-syntax + +class DoubleHolder extends Array {} + +const box = { f2: false }; +function double_getter() { + let f2 = box.f2; + let p0 = this[0]; + let p1 = f2 ? 1.5 : p0; + if (p1 === 0.0) return 1; + return p1; +} +function array_getter() { + return this[0]; +} +Object.defineProperty(DoubleHolder.prototype, "trigger", { get: double_getter }); +Object.defineProperty(Array.prototype, "trigger", { get: array_getter }); + +function access(o) { + return o.trigger; +} + +function victim(...args) { + return access(args); +} + +const double_arr = new DoubleHolder(); +double_arr[0] = 1.1; + +%PrepareFunctionForOptimization(double_getter); +%PrepareFunctionForOptimization(array_getter); +%PrepareFunctionForOptimization(access); +%PrepareFunctionForOptimization(victim); + +for (let i = 0; i < 10; i++) { + box.f2 = (i % 2 === 0); + access(double_arr); + access([1, 2]); +} + +assertEquals(1, victim(1, 2)); +%OptimizeFunctionOnNextCall(victim); +assertEquals(1, victim(1, 2)); diff --git a/deps/v8/test/mjsunit/maglev/generator-next-leak-the-hole.js b/deps/v8/test/mjsunit/maglev/generator-next-leak-the-hole.js index 6f3cd4f28548..c2a0522705ab 100644 --- a/deps/v8/test/mjsunit/maglev/generator-next-leak-the-hole.js +++ b/deps/v8/test/mjsunit/maglev/generator-next-leak-the-hole.js @@ -4,8 +4,9 @@ // Flags: --allow-natives-syntax --maglev -// Test that we do not leak TheHole (which signals to skip IteratorResult -// allocation) when a generator suspends via yield*. +// Test that a generator suspending via yield* does not skip result allocation. +// The body suspends inside the delegated iterator and never hits +// %GeneratorYieldResult. function* inner() { yield 2; @@ -29,10 +30,6 @@ test(generatorObject); // yields 1 %OptimizeMaglevOnNextCall(test); test(generatorObject); // yields 2 (delegated to inner) -// At this point, yielded_value_ should be cleared. -// If it wasn't, the next call (unoptimized) will incorrectly see TheHole, -// skip allocating the IteratorResult, and return TheHole to JS space. -// This would then cause a crash when the JS code tries to access res.value. let res = generatorObject.next(); assertEquals(3, res.value); assertEquals(false, res.done); diff --git a/deps/v8/test/mjsunit/maglev/generator-next-yield-undefined.js b/deps/v8/test/mjsunit/maglev/generator-next-yield-undefined.js new file mode 100644 index 000000000000..5f9650c22fab --- /dev/null +++ b/deps/v8/test/mjsunit/maglev/generator-next-yield-undefined.js @@ -0,0 +1,178 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --allow-natives-syntax --maglev --sparkplug + +// Tests that yielding undefined does not confuse the skip-allocation fast path +// in inlined Generator.prototype.next. + +(function yieldUndefinedOnFastPath() { + function* gen() { + yield undefined; + yield undefined; + } + + function callNext(g) { + return g.next(); + } + %PrepareFunctionForOptimization(callNext); + + const g = gen(); + let res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); + + %OptimizeMaglevOnNextCall(callNext); + res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); +})(); + +// Same as above, with the generator body in Sparkplug: covers the baseline ack. +(function yieldUndefinedOnFastPathBaselineBody() { + function* gen() { + yield undefined; + yield undefined; + } + %CompileBaseline(gen); + + function callNext(g) { + return g.next(); + } + %PrepareFunctionForOptimization(callNext); + + const g = gen(); + let res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); + + %OptimizeMaglevOnNextCall(callNext); + res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); + assertTrue(%ActiveTierIsSparkplug(gen)); +})(); + +// Same as above, with the generator body in Maglev: covers the Maglev ack. +(function yieldUndefinedOnFastPathMaglevBody() { + function* gen() { + yield undefined; + yield undefined; + } + %PrepareFunctionForOptimization(gen); + for (const _ of gen()); + %OptimizeMaglevOnNextCall(gen); + + function callNext(g) { + return g.next(); + } + %PrepareFunctionForOptimization(callNext); + + const g = gen(); // Maglev-compiles the body. + let res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); + + %OptimizeMaglevOnNextCall(callNext); + res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); + assertOptimized(gen); +})(); + +// Skip path + lazy deopt: the continuation must wrap the returned value, which +// is the bare yielded value rather than a result object. +(function lazyDeoptOnFastPath() { + function* gen() { + yield 1; + %DeoptimizeFunction(callNext); + yield 42; + yield undefined; + } + + function callNext(g) { + return g.next(); + } + %PrepareFunctionForOptimization(callNext); + + const g = gen(); + callNext(g); + + %OptimizeMaglevOnNextCall(callNext); + let res = callNext(g); + assertUnoptimized(callNext); + assertEquals(42, res.value); + assertFalse(res.done); + + res = g.next(); + assertEquals(undefined, res.value); + assertFalse(res.done); +})(); + +// A try-catch around the call disables the handshake, so the body allocates +// the result object itself. Yielding `undefined` must still work, including +// when the call lazy-deopts. +(function lazyDeoptWithoutHandshake() { + function* gen() { + yield undefined; + %DeoptimizeFunction(callNext); + yield undefined; + } + + function callNext(g) { + try { + return g.next(); + } catch (e) { + return e; + } + } + %PrepareFunctionForOptimization(callNext); + + const g = gen(); + let res = callNext(g); + assertEquals(undefined, res.value); + assertFalse(res.done); + + %OptimizeMaglevOnNextCall(callNext); + res = callNext(g); + assertUnoptimized(callNext); + assertEquals(undefined, res.value); + assertFalse(res.done); + + res = g.next(); + assertEquals(undefined, res.value); + assertTrue(res.done); +})(); + +// The generator returning `undefined` closes it and must be reported as done, +// never as a skipped allocation. +(function returnUndefined() { + function* gen() { + yield 1; + return undefined; + } + + function callNext(g) { + return g.next(); + } + %PrepareFunctionForOptimization(callNext); + + let g = gen(); + callNext(g); + callNext(g); + + %OptimizeMaglevOnNextCall(callNext); + g = gen(); + let res = callNext(g); + assertEquals(1, res.value); + assertFalse(res.done); + + res = callNext(g); + assertEquals(undefined, res.value); + assertTrue(res.done); + + res = callNext(g); + assertEquals(undefined, res.value); + assertTrue(res.done); +})(); diff --git a/deps/v8/test/mjsunit/regress/regress-577453560.js b/deps/v8/test/mjsunit/regress/regress-577453560.js new file mode 100644 index 000000000000..2f2c88fe1184 --- /dev/null +++ b/deps/v8/test/mjsunit/regress/regress-577453560.js @@ -0,0 +1,98 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --compile-hints-magic --stress-background-compile --stress-flush-code +// Flags: --expose-gc + +function flush() { + for (let i = 0; i < 10; i++) gc({type: "major"}); +} + +// 1. Contextless arrow calling eval inside a function with context. +{ + let code = `//# allFunctionsCalledOnLoad + "use strict"; + function outer() { + return function(x) { + return () => eval("x"); + }; + } + outer;`; + + let o = Realm.eval(Realm.current(), code); + flush(); + let f = o()(42); + Realm.eval(Realm.current(), code); + assertEquals(42, f()); +} + +// 2. Contextless arrow calling eval inside a lexical block scope, catch scope, +// and default parameter scope. +{ + let code = `//# allFunctionsCalledOnLoad + "use strict"; + function outer() { + return [ + function() { + { + let x = 10; + return () => eval("x"); + } + }, + function() { + try { + throw 20; + } catch (x) { + return () => eval("x"); + } + }, + function(x = 30, f = () => eval("x")) { + return f; + }, + function(x) { + return () => () => eval("() => eval('x')"); + } + ]; + } + outer;`; + + let o = Realm.eval(Realm.current(), code); + flush(); + let [fBlock, fCatch, fParam, fMulti] = o(); + let b = fBlock(); + let c = fCatch(); + let p = fParam(); + let m = fMulti(40)(); + Realm.eval(Realm.current(), code); + assertEquals(10, b()); + assertEquals(20, c()); + assertEquals(30, p()); + assertEquals(40, m()()); +} + +// 3. Standalone block-scoped eval merged while the owning closure's ScopeInfo +// is kept alive by a sibling closure. +{ + let code = `//# allFunctionsCalledOnLoad + "use strict"; + function outer(x) { + let keepScopeAlive = () => x; + let runBlockEval = function() { + { + let y = 12; + return eval("x + y"); + } + }; + return [keepScopeAlive, runBlockEval]; + } + outer;`; + + let o = Realm.eval(Realm.current(), code); + let [keep, run] = o(30); + flush(); + let o2 = Realm.eval(Realm.current(), code); + assertEquals(30, keep()); + assertEquals(42, run()); + assertEquals(42, o2(30)[1]()); +} diff --git a/deps/v8/test/mjsunit/turbolev/regress-577461556.js b/deps/v8/test/mjsunit/turbolev/regress-577461556.js new file mode 100644 index 000000000000..54cecad7b541 --- /dev/null +++ b/deps/v8/test/mjsunit/turbolev/regress-577461556.js @@ -0,0 +1,48 @@ +// Copyright 2026 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Flags: --allow-natives-syntax --turbolev --turbofan + +const prefix = 'ABCDEFGHIJKLMNO'; +const key = %ConstructInternalizedString(prefix + 'P'); + +function inspect(s, expected) { + return [s === expected, s.length, s.charCodeAt(15)]; +} +%PrepareFunctionForOptimization(inspect); +inspect(key, prefix); +%OptimizeFunctionOnNextCall(inspect); +inspect(key, prefix); + +function testMapGet(map, suffix) { + const s = prefix + ('P' + suffix); + const found = map.get(s); + return [found, ...inspect(s, prefix)]; +} + +function testSetHas(set, suffix) { + const s = prefix + ('P' + suffix); + const found = set.has(s); + return [found, ...inspect(s, prefix)]; +} + +// Map.prototype.get +{ + const map = new Map([[key, 42]]); + %PrepareFunctionForOptimization(testMapGet); + assertEquals([42, false, 16, 80], testMapGet(map, '')); + assertEquals([42, false, 16, 80], testMapGet(map, '')); + %OptimizeFunctionOnNextCall(testMapGet); + assertEquals([42, false, 16, 80], testMapGet(map, '')); +} + +// Set.prototype.has +{ + const set = new Set([key]); + %PrepareFunctionForOptimization(testSetHas); + assertEquals([true, false, 16, 80], testSetHas(set, '')); + assertEquals([true, false, 16, 80], testSetHas(set, '')); + %OptimizeFunctionOnNextCall(testSetHas); + assertEquals([true, false, 16, 80], testSetHas(set, '')); +} diff --git a/deps/v8/test/unittests/api/gc-callbacks-unittest.cc b/deps/v8/test/unittests/api/gc-callbacks-unittest.cc index 572799d47650..ae4a55e64fd8 100644 --- a/deps/v8/test/unittests/api/gc-callbacks-unittest.cc +++ b/deps/v8/test/unittests/api/gc-callbacks-unittest.cc @@ -163,6 +163,95 @@ TEST_F(GCCallbacksTest, GCCallbacks) { isolate->RemoveGCEpilogueCallback(EpilogueCallbackAlloc); } +TEST_F(GCCallbacksTest, DisallowJSObjectModification) { + // `v8_unittests` runs death tests in "threadsafe" mode, which re-spawns the + // process and re-runs the test from `main()` for every + // `EXPECT_DEATH_IF_SUPPORTED` check. Ensure `i::v8_flags.hard_abort = true` + // so each expected `CHECK` failure terminates immediately without `abort()` / + // core-dump overhead. + i::v8_flags.hard_abort = true; + + v8::Isolate* isolate = v8_isolate(); + v8::HandleScope scope(isolate); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + + v8::Local<v8::String> existing_key = NewString("existing"); + v8::Local<v8::String> new_key = NewString("new_prop"); + v8::Local<v8::Value> value = v8::Integer::New(isolate, 42); + + v8::Local<v8::Object> fast_obj = v8::Object::New(isolate); + CHECK(fast_obj->CreateDataProperty(context, existing_key, value).FromJust()); + CHECK(Utils::OpenDirectHandle(*fast_obj)->HasFastProperties()); + + v8::Local<v8::Object> dict_obj = v8::Object::New(isolate); + CHECK(dict_obj->CreateDataProperty(context, existing_key, value).FromJust()); + i::JSObject::NormalizeProperties( + i_isolate(), i::Cast<i::JSObject>(Utils::OpenDirectHandle(*dict_obj)), + i::KEEP_INOBJECT_PROPERTIES, 0, "test"); + CHECK(!Utils::OpenDirectHandle(*dict_obj)->HasFastProperties()); + +#if !defined(DEBUG) && defined(OFFICIAL_BUILD) + constexpr const char* kExpectedDeathMessage = ""; +#else + constexpr const char* kExpectedDeathMessage = + "Check failed: AllowJSObjectModification::IsAllowed"; +#endif + + size_t prologue_count = 0; + size_t epilogue_count = 0; + using CallbackFn = + std::function<void(v8::Isolate*, v8::GCType, v8::GCCallbackFlags)>; + CallbackFn on_prologue = [&](v8::Isolate*, v8::GCType, v8::GCCallbackFlags) { + // Adding a new property to a fast-mode JSObject. + EXPECT_DEATH_IF_SUPPORTED( + fast_obj->CreateDataProperty(context, new_key, value).Check(), + kExpectedDeathMessage); + // Adding an indexed element to a fast-mode JSObject. + EXPECT_DEATH_IF_SUPPORTED( + fast_obj->CreateDataProperty(context, 0, value).Check(), + kExpectedDeathMessage); + // Reconfiguring an existing property on a fast-mode JSObject. + EXPECT_DEATH_IF_SUPPORTED( + fast_obj->DefineOwnProperty(context, existing_key, value, v8::ReadOnly) + .Check(), + kExpectedDeathMessage); + // Deleting a property from a fast-mode JSObject. + EXPECT_DEATH_IF_SUPPORTED(fast_obj->Delete(context, existing_key).Check(), + kExpectedDeathMessage); + // Adding a property to a dictionary-mode JSObject. + EXPECT_DEATH_IF_SUPPORTED( + dict_obj->CreateDataProperty(context, new_key, value).Check(), + kExpectedDeathMessage); + // Deleting a property from a dictionary-mode JSObject. + EXPECT_DEATH_IF_SUPPORTED(dict_obj->Delete(context, existing_key).Check(), + kExpectedDeathMessage); + prologue_count++; + }; + CallbackFn on_epilogue = [&](v8::Isolate*, v8::GCType, v8::GCCallbackFlags) { + // Run a single representative check in epilogue to avoid spawning 6 more + // "threadsafe" death-test subprocesses. + EXPECT_DEATH_IF_SUPPORTED( + fast_obj->CreateDataProperty(context, new_key, value).Check(), + kExpectedDeathMessage); + epilogue_count++; + }; + + auto callback_thunk = [](v8::Isolate* isolate, v8::GCType type, + v8::GCCallbackFlags flags, void* data) { + auto* fn = static_cast<CallbackFn*>(data); + (*fn)(isolate, type, flags); + }; + + isolate->AddGCPrologueCallback(callback_thunk, &on_prologue); + isolate->AddGCEpilogueCallback(callback_thunk, &on_epilogue); + InvokeMajorGC(); + isolate->RemoveGCPrologueCallback(callback_thunk, &on_prologue); + isolate->RemoveGCEpilogueCallback(callback_thunk, &on_epilogue); + + EXPECT_EQ(1u, prologue_count); + EXPECT_EQ(1u, epilogue_count); +} + } // namespace } // namespace v8 diff --git a/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc b/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc index 875088a20cdf..b0627fff43e6 100644 --- a/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc +++ b/deps/v8/test/unittests/compiler/regalloc/register-allocator-unittest.cc @@ -813,6 +813,48 @@ INSTANTIATE_TEST_SUITE_P( ::testing::Combine(::testing::ValuesIn(kParameterTypes), ::testing::Range(0, SlotConstraintTest::kMaxVariant))); +TEST_F(RegisterAllocatorTest, AllocateBlockedRegDeferredClampBelowStart) { + SetNumRegs(3, 1); + + // B0 (non-deferred): branch selector `c`, value `d` used at the deferred + // jump, and phi inputs `w0..w2` creating register pressure. + StartBlock(); + VReg c = Parameter(Reg()); + VReg d = Define(Reg()); + VReg w0 = Define(Reg()); + VReg w1 = Define(Reg()); + VReg w2 = Define(Reg()); + EndBlock(Branch(Reg(c), 1, 2)); // succs: B1 (deferred), B2 + + // B1 (deferred): a call clobbers all registers, defs re-occupy all + // registers, ending with a jump that uses `d` in a register. The next block + // in RPO order (B2) is not deferred. + StartBlock(true); + EmitCall(Slot(-1)); + VReg z0 = Define(Reg()); + VReg z1 = Define(Reg()); + VReg z2 = Define(Reg()); + EndBlock(Jump(2, Reg(d))); // succ: B3 + + // B2 (non-deferred; predecessor B0). + StartBlock(); + EmitNop(); + EndBlock(Jump(1)); // succ: B3 + + // B3: merge with phis keeping `z0..z2` live out of B1, and a late use of `d` + // so that its split child survives past the B2 block boundary. + StartBlock(); + VReg p0 = Phi(z0, w0); + VReg p1 = Phi(z1, w1); + VReg p2 = Phi(z2, w2); + EmitI(Use(d)); + EmitI(Use(p0), Use(p1), Use(p2)); + Return(p0); + EndBlock(Last()); + + Allocate(); +} + } // namespace } // namespace compiler } // namespace internal diff --git a/deps/v8/test/unittests/compiler/turboshaft/late-load-elimination-reducer-unittest.cc b/deps/v8/test/unittests/compiler/turboshaft/late-load-elimination-reducer-unittest.cc index 56dacca7d578..fbbdf0c863e5 100644 --- a/deps/v8/test/unittests/compiler/turboshaft/late-load-elimination-reducer-unittest.cc +++ b/deps/v8/test/unittests/compiler/turboshaft/late-load-elimination-reducer-unittest.cc @@ -8,7 +8,9 @@ #include "src/compiler/turboshaft/wasm-load-elimination-reducer.h" #endif +#include "src/compiler/access-builder.h" #include "src/compiler/turboshaft/assembler.h" +#include "src/compiler/turboshaft/builtin-call-descriptors.h" #include "src/compiler/turboshaft/copying-phase.h" #include "src/compiler/turboshaft/machine-optimization-reducer.h" #include "src/compiler/turboshaft/operations.h" @@ -18,6 +20,7 @@ #include "src/compiler/turboshaft/required-optimization-reducer.h" #include "src/compiler/turboshaft/variable-reducer.h" #include "src/flags/flags.h" +#include "src/objects/string.h" #include "test/common/flag-utils.h" #include "test/unittests/compiler/turboshaft/reducer-test.h" @@ -528,6 +531,81 @@ TEST_F(LateLoadEliminationReducerTest, ASSERT_NE(load1, nullptr); } +TEST_F(LateLoadEliminationReducerTest, + FindOrderedHashEntry_Invalidates_String_First_Load) { + { + auto effects_test = CreateFromGraph(2, [](auto& Asm) { + V<Object> table = Asm.GetParameter(0); + V<Smi> key = V<Smi>::Cast(Asm.GetParameter(1)); + V<Smi> C(map_op) = __ FindOrderedHashMapEntry(table, key); + V<Smi> C(set_op) = __ FindOrderedHashSetEntry(table, key); + V<WordPtr> C(int32_op) = + __ FindOrderedHashMapEntryForInt32Key(table, __ Word32Constant(0)); + __ Return(__ Word32Constant(0), + base::VectorOf<OpIndex>({map_op, set_op, int32_op})); + }); + const Operation* map_op = effects_test.GetCapture("map_op").Get(); + EXPECT_TRUE(map_op->Effects().can_write()); + EXPECT_TRUE(map_op->Effects().can_allocate); + + const Operation* set_op = effects_test.GetCapture("set_op").Get(); + EXPECT_TRUE(set_op->Effects().can_write()); + EXPECT_TRUE(set_op->Effects().can_allocate); + + const Operation* int32_op = effects_test.GetCapture("int32_op").Get(); + EXPECT_FALSE(int32_op->Effects().can_write()); + EXPECT_FALSE(int32_op->Effects().can_allocate); + EXPECT_TRUE(int32_op->Effects().produces.load_heap_memory); + } + + EXPECT_EQ(AccessBuilder::ForConsStringFirst().offset, + AccessBuilder::ForThinStringActual().offset); + + auto test = CreateFromGraph(3, [](auto& Asm) { + V<Object> table = Asm.GetParameter(0); + V<String> first0 = V<String>::Cast(Asm.GetParameter(1)); + V<String> first1 = V<String>::Cast(Asm.GetParameter(2)); + + auto escaped_alloc = __ template Allocate<ConsString>( + __ WordPtrConstant(sizeof(ConsString)), AllocationType::kYoung, + AllocationAlignment::kTaggedAligned); + __ InitializeField(escaped_alloc, AccessBuilder::ForConsStringFirst(), + first0); + V<ConsString> escaped_str = + __ FinishInitialization(std::move(escaped_alloc)); + + auto local_alloc = __ template Allocate<ConsString>( + __ WordPtrConstant(sizeof(ConsString)), AllocationType::kYoung, + AllocationAlignment::kTaggedAligned); + __ InitializeField(local_alloc, AccessBuilder::ForConsStringFirst(), + first1); + V<ConsString> local_str = __ FinishInitialization(std::move(local_alloc)); + + V<Smi> entry = __ template CallBuiltin<builtin::FindOrderedHashMapEntry>( + Asm.context(), {.table = table, .key = escaped_str}); + + // String::MakeThin overwrites ConsString::first_ with ThinString::actual_. + V<String> C(escaped_load) = __ template LoadField<String>( + escaped_str, AccessBuilder::ForThinStringActual()); + V<String> C(local_load) = __ template LoadField<String>( + local_str, AccessBuilder::ForConsStringFirst()); + + __ Return(__ Word32Constant(0), + base::VectorOf<OpIndex>({entry, escaped_load, local_load})); + }); + + test.Run<LateLoadEliminationReducer>(); + + // The load from the escaped ConsString must NOT be replaced with `first0`. + const LoadOp* escaped_load = test.GetCapturedAs<LoadOp>("escaped_load"); + ASSERT_NE(escaped_load, nullptr); + + // Non-escaping allocations remain eligible for load elimination. + if (!LATE_LOAD_ELIM_VERIFY) { + ASSERT_TRUE(test.GetCapture("local_load").IsEmpty()); + } +} + #if V8_ENABLE_WEBASSEMBLY class WasmLateLoadEliminationReducerTest diff --git a/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncGenerators.golden b/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncGenerators.golden index 4abee9333919..897eee2790c8 100644 --- a/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncGenerators.golden +++ b/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncGenerators.golden @@ -29,7 +29,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(6), B(Star6), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [18]), U8(3), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [18]), U8(4), I8(0), B(Ldar), R(6), /* 17 E> */ B(ReThrow), B(Ldar), R(6), @@ -60,7 +60,7 @@ bytecodes: [ B(Star3), B(InvokeIntrinsic), U8(Runtime::k_GeneratorClose), R(0), RegCount8(1), B(Ldar), R(1), - B(SwitchOnSmiNoFeedback), U8(4:Smi [10]), U8(2), I8(1), + B(SwitchOnSmiNoFeedback), U8(5:Smi [10]), U8(2), I8(1), B(Ldar), R(3), B(SetPendingMessage), B(Ldar), R(2), @@ -77,6 +77,7 @@ bytecodes: [ constant pool: [ Smi [30], Smi [18], + Smi [18], Smi [10], Smi [7], Smi [10], @@ -110,7 +111,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(6), B(Star6), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [18]), U8(3), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [18]), U8(4), I8(0), B(Ldar), R(6), /* 17 E> */ B(ReThrow), B(Ldar), R(6), @@ -127,7 +128,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(6), B(Star6), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(5:Smi [18]), U8(3), I8(0), + B(SwitchOnSmiNoFeedback), U8(6:Smi [18]), U8(4), I8(0), B(Ldar), R(6), /* 22 E> */ B(ReThrow), B(Ldar), R(6), @@ -158,7 +159,7 @@ bytecodes: [ B(Star3), B(InvokeIntrinsic), U8(Runtime::k_GeneratorClose), R(0), RegCount8(1), B(Ldar), R(1), - B(SwitchOnSmiNoFeedback), U8(8:Smi [10]), U8(2), I8(1), + B(SwitchOnSmiNoFeedback), U8(10:Smi [10]), U8(2), I8(1), B(Ldar), R(3), B(SetPendingMessage), B(Ldar), R(2), @@ -176,9 +177,11 @@ constant pool: [ Smi [30], Smi [72], Smi [18], + Smi [18], Smi [10], Smi [7], Smi [18], + Smi [18], Smi [10], Smi [7], Smi [10], @@ -212,7 +215,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(9), B(Star9), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [18]), U8(3), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [18]), U8(4), I8(0), B(Ldar), R(9), /* 17 E> */ B(ReThrow), B(Ldar), R(9), @@ -221,11 +224,11 @@ bytecodes: [ B(Star4), B(Mov), R(9), R(5), B(Jump), U8(209), - /* 36 S> */ B(CreateArrayLiteral), U8(5:ARRAY_BOILERPLATE_DESCRIPTION_TYPE), FBV(0), Flag8(0x25), + /* 36 S> */ B(CreateArrayLiteral), U8(6:ARRAY_BOILERPLATE_DESCRIPTION_TYPE), FBV(0), Flag8(0x25), B(Star11), B(GetIterator), R(11), FBV(1), FBV(3), B(Star10), - B(GetNamedProperty), R(10), U8(6:"next"), FBV(5), + B(GetNamedProperty), R(10), U8(7:"next"), FBV(5), B(Star9), B(LdaFalse), B(Star12), @@ -238,9 +241,9 @@ bytecodes: [ B(Star11), B(JumpIfJSReceiver), U8(7), B(CallRuntime), U16(Runtime::kThrowIteratorResultNotAnObject), R(11), RegCount8(1), - B(GetNamedProperty), R(11), U8(7:"done"), FBV(9), + B(GetNamedProperty), R(11), U8(8:"done"), FBV(9), B(JumpIfToBooleanTrue), U8(64), - B(GetNamedProperty), R(11), U8(8:"value"), FBV(11), + B(GetNamedProperty), R(11), U8(9:"value"), FBV(11), B(Star11), B(LdaFalse), /* 31 S> */ B(Star12), @@ -253,7 +256,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(17), B(Star), R(17), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(9:Smi [18]), U8(3), I8(0), + B(SwitchOnSmiNoFeedback), U8(10:Smi [18]), U8(4), I8(0), B(Ldar), R(17), /* 42 E> */ B(ReThrow), B(Ldar), R(17), @@ -277,7 +280,7 @@ bytecodes: [ B(Ldar), R(12), B(JumpIfToBooleanTrue), U8(38), B(Mov), R(context), R(17), - B(GetNamedProperty), R(10), U8(12:"return"), FBV(15), + B(GetNamedProperty), R(10), U8(14:"return"), FBV(15), B(JumpIfUndefinedOrNull), U8(29), B(Star), R(18), B(CallProperty0), R(18), R(10), FBV(17), @@ -292,7 +295,7 @@ bytecodes: [ B(Ldar), R(17), B(ReThrow), B(Ldar), R(13), - B(SwitchOnSmiNoFeedback), U8(13:Smi [6]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(15:Smi [6]), U8(2), I8(0), B(Jump), U8(16), B(Ldar), R(15), B(SetPendingMessage), @@ -324,7 +327,7 @@ bytecodes: [ B(Star6), B(InvokeIntrinsic), U8(Runtime::k_GeneratorClose), R(0), RegCount8(1), B(Ldar), R(4), - B(SwitchOnSmiNoFeedback), U8(15:Smi [10]), U8(2), I8(1), + B(SwitchOnSmiNoFeedback), U8(17:Smi [10]), U8(2), I8(1), B(Ldar), R(6), B(SetPendingMessage), B(Ldar), R(5), @@ -342,6 +345,7 @@ constant pool: [ Smi [30], Smi [127], Smi [18], + Smi [18], Smi [10], Smi [7], ARRAY_BOILERPLATE_DESCRIPTION_TYPE, @@ -349,6 +353,7 @@ constant pool: [ INTERNALIZED_ONE_BYTE_STRING_TYPE ["done"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["value"], Smi [18], + Smi [18], Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["return"], @@ -388,7 +393,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(6), B(Star6), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(5:Smi [18]), U8(3), I8(0), + B(SwitchOnSmiNoFeedback), U8(5:Smi [18]), U8(4), I8(0), B(Ldar), R(6), /* 44 E> */ B(ReThrow), B(Ldar), R(6), @@ -396,34 +401,34 @@ bytecodes: [ B(LdaSmi), I8(1), B(Star1), B(Mov), R(6), R(2), - B(JumpConstant), U8(18:Smi [325]), - /* 49 S> */ B(LdaGlobal), U8(8:"g"), FBV(0), + B(JumpConstant), U8(19:Smi [325]), + /* 49 S> */ B(LdaGlobal), U8(9:"g"), FBV(0), B(Star10), /* 56 E> */ B(CallUndefinedReceiver0), R(10), FBV(2), B(Star11), - B(GetNamedProperty), R(11), U8(9:SYMBOL_TYPE), FBV(4), + B(GetNamedProperty), R(11), U8(10:SYMBOL_TYPE), FBV(4), B(JumpIfUndefinedOrNull), U8(14), B(Star12), B(CallProperty0), R(12), R(11), FBV(6), B(JumpIfJSReceiver), U8(21), B(CallRuntime), U16(Runtime::kThrowSymbolAsyncIteratorInvalid), R(0), RegCount8(0), - B(GetNamedProperty), R(11), U8(10:SYMBOL_TYPE), FBV(8), + B(GetNamedProperty), R(11), U8(11:SYMBOL_TYPE), FBV(8), B(Star12), B(CallProperty0), R(12), R(11), FBV(10), B(Star12), B(InvokeIntrinsic), U8(Runtime::k_CreateAsyncFromSyncIterator), R(12), RegCount8(1), B(Star8), - B(GetNamedProperty), R(8), U8(11:"next"), FBV(12), + B(GetNamedProperty), R(8), U8(12:"next"), FBV(12), B(Star10), B(LdaUndefined), B(Star9), B(LdaZero), B(Star7), B(Ldar), R(7), - B(SwitchOnSmiNoFeedback), U8(12:Smi [11]), U8(2), I8(1), + B(SwitchOnSmiNoFeedback), U8(13:Smi [11]), U8(2), I8(2), B(CallProperty1), R(10), R(8), R(9), FBV(14), B(Jump), U8(130), - B(GetNamedProperty), R(8), U8(14:"return"), FBV(16), + B(GetNamedProperty), R(8), U8(15:"return"), FBV(16), B(JumpIfUndefinedOrNull), U8(10), B(Star11), B(CallProperty1), R(11), R(8), R(9), FBV(18), @@ -445,12 +450,12 @@ bytecodes: [ B(Star1), B(Mov), R(11), R(2), B(Jump), U8(207), - B(GetNamedProperty), R(8), U8(15:"throw"), FBV(20), + B(GetNamedProperty), R(8), U8(16:"throw"), FBV(20), B(JumpIfUndefinedOrNull), U8(10), B(Star13), B(CallProperty1), R(13), R(8), R(9), FBV(22), B(Jump), U8(61), - B(GetNamedProperty), R(8), U8(14:"return"), FBV(24), + B(GetNamedProperty), R(8), U8(15:"return"), FBV(24), B(JumpIfUndefinedOrNull), U8(50), B(Star13), B(CallProperty0), R(13), R(8), FBV(26), @@ -490,9 +495,9 @@ bytecodes: [ B(Mov), R(13), R(6), B(JumpIfJSReceiver), U8(7), B(CallRuntime), U16(Runtime::kThrowIteratorResultNotAnObject), R(6), RegCount8(1), - B(GetNamedProperty), R(6), U8(16:"done"), FBV(28), + B(GetNamedProperty), R(6), U8(17:"done"), FBV(28), B(JumpIfToBooleanTrue), U8(37), - B(GetNamedProperty), R(6), U8(17:"value"), FBV(30), + B(GetNamedProperty), R(6), U8(18:"value"), FBV(30), B(Star), R(16), B(LdaFalse), B(Star), R(17), @@ -504,9 +509,9 @@ bytecodes: [ B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), B(Star7), B(JumpLoop), U8(221), I8(0), FBV(32), - B(GetNamedProperty), R(6), U8(17:"value"), FBV(34), + B(GetNamedProperty), R(6), U8(18:"value"), FBV(34), B(Star8), - B(LdaSmi), I8(1), + B(LdaSmi), I8(2), B(TestReferenceEqual), R(7), B(JumpIfFalse), U8(10), B(LdaSmi), I8(1), @@ -535,7 +540,7 @@ bytecodes: [ B(Star3), B(InvokeIntrinsic), U8(Runtime::k_GeneratorClose), R(0), RegCount8(1), B(Ldar), R(1), - B(SwitchOnSmiNoFeedback), U8(19:Smi [10]), U8(2), I8(1), + B(SwitchOnSmiNoFeedback), U8(20:Smi [10]), U8(2), I8(1), B(Ldar), R(3), B(SetPendingMessage), B(Ldar), R(2), @@ -556,6 +561,7 @@ constant pool: [ Smi [261], Smi [318], Smi [18], + Smi [18], Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["g"], diff --git a/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncModules.golden b/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncModules.golden index 1880b2c60add..1e637beb5642 100644 --- a/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncModules.golden +++ b/deps/v8/test/unittests/interpreter/bytecode_expectations/AsyncModules.golden @@ -26,7 +26,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), @@ -61,6 +61,7 @@ constant pool: [ Smi [25], Smi [59], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -86,12 +87,12 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), B(Return), - /* 0 S> */ B(LdaConstant), U8(4:"foo"), + /* 0 S> */ B(LdaConstant), U8(5:"foo"), B(Star3), B(LdaSmi), I8(2), B(Star4), @@ -126,6 +127,7 @@ constant pool: [ Smi [25], Smi [71], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["foo"], ] @@ -158,7 +160,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(3), B(Star3), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(3:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(3:Smi [10]), U8(3), I8(0), B(Ldar), R(3), /* 0 E> */ B(Throw), B(Ldar), R(3), @@ -195,6 +197,7 @@ constant pool: [ Smi [64], SHARED_FUNCTION_INFO_TYPE, Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -221,12 +224,12 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), B(Return), - /* 28 S> */ B(LdaConstant), U8(4:"goo"), + /* 28 S> */ B(LdaConstant), U8(5:"goo"), B(Star3), B(LdaSmi), I8(2), B(Star4), @@ -261,6 +264,7 @@ constant pool: [ Smi [25], Smi [71], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["goo"], ] diff --git a/deps/v8/test/unittests/interpreter/bytecode_expectations/ForOfLoop.golden b/deps/v8/test/unittests/interpreter/bytecode_expectations/ForOfLoop.golden index ee6263cdeb12..3a9f2550b3c1 100644 --- a/deps/v8/test/unittests/interpreter/bytecode_expectations/ForOfLoop.golden +++ b/deps/v8/test/unittests/interpreter/bytecode_expectations/ForOfLoop.golden @@ -425,14 +425,14 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(5), B(Star5), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(5), /* 11 E> */ B(Throw), B(Ldar), R(5), B(Return), /* 35 S> */ B(GetIterator), R(arg0), FBV(0), FBV(2), B(Star6), - B(GetNamedProperty), R(6), U8(3:"next"), FBV(4), + B(GetNamedProperty), R(6), U8(4:"next"), FBV(4), B(Star5), B(LdaFalse), B(Star8), @@ -445,9 +445,9 @@ bytecodes: [ B(Star7), B(JumpIfJSReceiver), U8(7), B(CallRuntime), U16(Runtime::kThrowIteratorResultNotAnObject), R(7), RegCount8(1), - B(GetNamedProperty), R(7), U8(4:"done"), FBV(8), + B(GetNamedProperty), R(7), U8(5:"done"), FBV(8), B(JumpIfToBooleanTrue), U8(24), - B(GetNamedProperty), R(7), U8(5:"value"), FBV(10), + B(GetNamedProperty), R(7), U8(6:"value"), FBV(10), B(Star7), B(LdaFalse), /* 30 S> */ B(Star8), @@ -469,7 +469,7 @@ bytecodes: [ B(Ldar), R(8), B(JumpIfToBooleanTrue), U8(35), B(Mov), R(context), R(13), - B(GetNamedProperty), R(6), U8(6:"return"), FBV(14), + B(GetNamedProperty), R(6), U8(7:"return"), FBV(14), B(JumpIfUndefinedOrNull), U8(26), B(Star14), B(CallProperty0), R(14), R(6), FBV(16), @@ -496,6 +496,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["next"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["done"], @@ -527,14 +528,14 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(4), B(Star4), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(4), /* 11 E> */ B(Throw), B(Ldar), R(4), B(Return), /* 35 S> */ B(GetIterator), R(arg0), FBV(0), FBV(2), B(Star5), - B(GetNamedProperty), R(5), U8(4:"next"), FBV(4), + B(GetNamedProperty), R(5), U8(5:"next"), FBV(4), B(Star4), B(LdaFalse), B(Star7), @@ -547,9 +548,9 @@ bytecodes: [ B(Star6), B(JumpIfJSReceiver), U8(7), B(CallRuntime), U16(Runtime::kThrowIteratorResultNotAnObject), R(6), RegCount8(1), - B(GetNamedProperty), R(6), U8(5:"done"), FBV(8), + B(GetNamedProperty), R(6), U8(6:"done"), FBV(8), B(JumpIfToBooleanTrue), U8(60), - B(GetNamedProperty), R(6), U8(6:"value"), FBV(10), + B(GetNamedProperty), R(6), U8(7:"value"), FBV(10), B(Star6), B(LdaFalse), /* 30 S> */ B(Star7), @@ -562,7 +563,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(12), B(Star12), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(7:Smi [15]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(8:Smi [15]), U8(3), I8(0), B(Ldar), R(12), /* 40 E> */ B(Throw), B(LdaSmi), I8(1), @@ -584,7 +585,7 @@ bytecodes: [ B(Ldar), R(7), B(JumpIfToBooleanTrue), U8(35), B(Mov), R(context), R(12), - B(GetNamedProperty), R(5), U8(9:"return"), FBV(14), + B(GetNamedProperty), R(5), U8(11:"return"), FBV(14), B(JumpIfUndefinedOrNull), U8(26), B(Star13), B(CallProperty0), R(13), R(5), FBV(16), @@ -599,7 +600,7 @@ bytecodes: [ B(Ldar), R(12), B(ReThrow), B(Ldar), R(8), - B(SwitchOnSmiNoFeedback), U8(10:Smi [6]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(12:Smi [6]), U8(2), I8(0), B(Jump), U8(11), B(Ldar), R(10), B(SetPendingMessage), @@ -614,11 +615,13 @@ constant pool: [ Smi [20], Smi [104], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["next"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["done"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["value"], Smi [15], + Smi [15], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["return"], Smi [6], diff --git a/deps/v8/test/unittests/interpreter/bytecode_expectations/Generators.golden b/deps/v8/test/unittests/interpreter/bytecode_expectations/Generators.golden index f4b7ed48280e..fd0b813a7a25 100644 --- a/deps/v8/test/unittests/interpreter/bytecode_expectations/Generators.golden +++ b/deps/v8/test/unittests/interpreter/bytecode_expectations/Generators.golden @@ -24,7 +24,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 11 E> */ B(Throw), B(Ldar), R(1), @@ -35,6 +35,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -58,7 +59,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 11 E> */ B(Throw), B(Ldar), R(1), @@ -71,7 +72,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(4:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(5:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 16 E> */ B(Throw), B(Ldar), R(1), @@ -83,8 +84,10 @@ constant pool: [ Smi [20], Smi [54], Smi [10], + Smi [10], Smi [7], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -108,16 +111,16 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(4), B(Star4), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(4), /* 11 E> */ B(Throw), B(Ldar), R(4), B(Return), - /* 30 S> */ B(CreateArrayLiteral), U8(4:ARRAY_BOILERPLATE_DESCRIPTION_TYPE), FBV(0), Flag8(0x25), + /* 30 S> */ B(CreateArrayLiteral), U8(5:ARRAY_BOILERPLATE_DESCRIPTION_TYPE), FBV(0), Flag8(0x25), B(Star6), B(GetIterator), R(6), FBV(1), FBV(3), B(Star5), - B(GetNamedProperty), R(5), U8(5:"next"), FBV(5), + B(GetNamedProperty), R(5), U8(6:"next"), FBV(5), B(Star4), B(LdaFalse), B(Star7), @@ -130,9 +133,9 @@ bytecodes: [ B(Star6), B(JumpIfJSReceiver), U8(7), B(CallRuntime), U16(Runtime::kThrowIteratorResultNotAnObject), R(6), RegCount8(1), - B(GetNamedProperty), R(6), U8(6:"done"), FBV(9), + B(GetNamedProperty), R(6), U8(7:"done"), FBV(9), B(JumpIfToBooleanTrue), U8(60), - B(GetNamedProperty), R(6), U8(7:"value"), FBV(11), + B(GetNamedProperty), R(6), U8(8:"value"), FBV(11), B(Star6), B(LdaFalse), /* 25 S> */ B(Star7), @@ -145,7 +148,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(12), B(Star12), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(8:Smi [15]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(9:Smi [15]), U8(3), I8(0), B(Ldar), R(12), /* 36 E> */ B(Throw), B(LdaSmi), I8(1), @@ -167,7 +170,7 @@ bytecodes: [ B(Ldar), R(7), B(JumpIfToBooleanTrue), U8(35), B(Mov), R(context), R(12), - B(GetNamedProperty), R(5), U8(10:"return"), FBV(15), + B(GetNamedProperty), R(5), U8(12:"return"), FBV(15), B(JumpIfUndefinedOrNull), U8(26), B(Star13), B(CallProperty0), R(13), R(5), FBV(17), @@ -182,7 +185,7 @@ bytecodes: [ B(Ldar), R(12), B(ReThrow), B(Ldar), R(8), - B(SwitchOnSmiNoFeedback), U8(11:Smi [6]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(13:Smi [6]), U8(2), I8(0), B(Jump), U8(11), B(Ldar), R(10), B(SetPendingMessage), @@ -197,12 +200,14 @@ constant pool: [ Smi [20], Smi [109], Smi [10], + Smi [10], Smi [7], ARRAY_BOILERPLATE_DESCRIPTION_TYPE, INTERNALIZED_ONE_BYTE_STRING_TYPE ["next"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["done"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["value"], Smi [15], + Smi [15], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["return"], Smi [6], @@ -232,40 +237,40 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 38 E> */ B(Throw), B(Ldar), R(1), B(Return), - /* 43 S> */ B(LdaGlobal), U8(4:"g"), FBV(0), + /* 43 S> */ B(LdaGlobal), U8(5:"g"), FBV(0), B(Star5), /* 50 E> */ B(CallUndefinedReceiver0), R(5), FBV(2), B(Star6), B(GetIterator), R(6), FBV(4), FBV(6), B(Star3), - B(GetNamedProperty), R(3), U8(5:"next"), FBV(8), + B(GetNamedProperty), R(3), U8(6:"next"), FBV(8), B(Star5), B(LdaUndefined), B(Star4), B(LdaZero), B(Star2), B(Ldar), R(2), - B(SwitchOnSmiNoFeedback), U8(6:Smi [11]), U8(2), I8(1), + B(SwitchOnSmiNoFeedback), U8(7:Smi [11]), U8(2), I8(2), B(CallProperty1), R(5), R(3), R(4), FBV(10), B(Jump), U8(59), - B(GetNamedProperty), R(3), U8(8:"return"), FBV(12), + B(GetNamedProperty), R(3), U8(9:"return"), FBV(12), B(JumpIfUndefinedOrNull), U8(10), B(Star6), B(CallProperty1), R(6), R(3), R(4), FBV(14), B(Jump), U8(45), B(Ldar), R(4), B(Return), - B(GetNamedProperty), R(3), U8(9:"throw"), FBV(16), + B(GetNamedProperty), R(3), U8(10:"throw"), FBV(16), B(JumpIfUndefinedOrNull), U8(10), B(Star6), B(CallProperty1), R(6), R(3), R(4), FBV(18), B(Jump), U8(28), - B(GetNamedProperty), R(3), U8(8:"return"), FBV(20), + B(GetNamedProperty), R(3), U8(9:"return"), FBV(20), B(JumpIfUndefinedOrNull), U8(17), B(Star6), B(CallProperty0), R(6), R(3), FBV(22), @@ -277,7 +282,7 @@ bytecodes: [ B(Star1), B(JumpIfJSReceiver), U8(7), B(CallRuntime), U16(Runtime::kThrowIteratorResultNotAnObject), R(1), RegCount8(1), - B(GetNamedProperty), R(1), U8(10:"done"), FBV(24), + B(GetNamedProperty), R(1), U8(11:"done"), FBV(24), B(JumpIfToBooleanTrue), U8(23), B(Ldar), R(1), /* 43 E> */ B(SuspendGenerator), R(0), R(0), RegCount8(6), U8(1), @@ -286,9 +291,9 @@ bytecodes: [ B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), B(Star2), B(JumpLoop), U8(101), I8(0), FBV(26), - B(GetNamedProperty), R(1), U8(11:"value"), FBV(28), + B(GetNamedProperty), R(1), U8(12:"value"), FBV(28), B(Star3), - B(LdaSmi), I8(1), + B(LdaSmi), I8(2), B(TestReferenceEqual), R(2), B(JumpIfFalse), U8(5), B(Ldar), R(3), @@ -300,6 +305,7 @@ constant pool: [ Smi [20], Smi [152], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["g"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["next"], diff --git a/deps/v8/test/unittests/interpreter/bytecode_expectations/Modules.golden b/deps/v8/test/unittests/interpreter/bytecode_expectations/Modules.golden index 5f885b398b62..993353056b2b 100644 --- a/deps/v8/test/unittests/interpreter/bytecode_expectations/Modules.golden +++ b/deps/v8/test/unittests/interpreter/bytecode_expectations/Modules.golden @@ -24,7 +24,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 0 E> */ B(Throw), B(Ldar), R(1), @@ -35,6 +35,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -57,7 +58,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 0 E> */ B(Throw), B(Ldar), R(1), @@ -68,6 +69,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -92,13 +94,13 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), B(Return), /* 32 S> */ B(LdaModuleVariable), I8(-1), U8(0), - B(ThrowReferenceErrorIfTdzHole), U8(3:"goo"), + B(ThrowReferenceErrorIfTdzHole), U8(4:"goo"), B(Star2), B(LdaSmi), I8(42), B(Star3), @@ -116,6 +118,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["goo"], ] @@ -141,7 +144,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), @@ -162,6 +165,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -190,7 +194,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), @@ -212,6 +216,7 @@ constant pool: [ Smi [31], FIXED_ARRAY_TYPE, Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -240,7 +245,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), @@ -262,6 +267,7 @@ constant pool: [ Smi [31], FIXED_ARRAY_TYPE, Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -288,12 +294,12 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 0 E> */ B(Throw), B(Ldar), R(1), B(Return), - B(CreateClosure), U8(4:SHARED_FUNCTION_INFO_TYPE), FBV(0), Flag8(0x0), + B(CreateClosure), U8(5:SHARED_FUNCTION_INFO_TYPE), FBV(0), Flag8(0x0), B(StaModuleVariable), I8(1), U8(0), B(LdaUndefined), /* 33 S> */ B(Return), @@ -302,6 +308,7 @@ constant pool: [ Smi [31], FIXED_ARRAY_TYPE, Smi [10], + Smi [10], Smi [7], SHARED_FUNCTION_INFO_TYPE, ] @@ -329,16 +336,16 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 0 E> */ B(Throw), B(Ldar), R(1), B(Return), B(LdaTheHole), B(Star4), - B(CreateClosure), U8(5:SHARED_FUNCTION_INFO_TYPE), FBV(0), Flag8(0x0), + B(CreateClosure), U8(6:SHARED_FUNCTION_INFO_TYPE), FBV(0), Flag8(0x0), B(Star1), - B(LdaConstant), U8(4:CLASS_BOILERPLATE_TYPE), + B(LdaConstant), U8(5:CLASS_BOILERPLATE_TYPE), B(Star2), B(Mov), R(1), R(3), B(CallRuntime), U16(Runtime::kDefineClass), R(2), RegCount8(3), @@ -351,6 +358,7 @@ constant pool: [ Smi [31], FIXED_ARRAY_TYPE, Smi [10], + Smi [10], Smi [7], CLASS_BOILERPLATE_TYPE, SHARED_FUNCTION_INFO_TYPE, @@ -375,7 +383,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 0 E> */ B(Throw), B(Ldar), R(1), @@ -386,6 +394,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -408,7 +417,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(1), B(Star1), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(1), /* 0 E> */ B(Throw), B(Ldar), R(1), @@ -419,6 +428,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -446,14 +456,14 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 0 E> */ B(Throw), B(Ldar), R(2), B(Return), - /* 31 S> */ B(GetNamedProperty), R(1), U8(3:"f"), FBV(0), + /* 31 S> */ B(GetNamedProperty), R(1), U8(4:"f"), FBV(0), B(Star2), - /* 42 E> */ B(GetNamedProperty), R(1), U8(4:"x"), FBV(2), + /* 42 E> */ B(GetNamedProperty), R(1), U8(5:"x"), FBV(2), B(Star5), /* 31 E> */ B(CallProperty2), R(2), R(1), R(1), R(5), FBV(4), B(LdaUndefined), @@ -462,6 +472,7 @@ bytecodes: [ constant pool: [ Smi [28], Smi [10], + Smi [10], Smi [7], INTERNALIZED_ONE_BYTE_STRING_TYPE ["f"], INTERNALIZED_ONE_BYTE_STRING_TYPE ["x"], diff --git a/deps/v8/test/unittests/interpreter/bytecode_expectations/StandardForLoop.golden b/deps/v8/test/unittests/interpreter/bytecode_expectations/StandardForLoop.golden index e0e42d1bd62b..c35e8c1b3852 100644 --- a/deps/v8/test/unittests/interpreter/bytecode_expectations/StandardForLoop.golden +++ b/deps/v8/test/unittests/interpreter/bytecode_expectations/StandardForLoop.golden @@ -261,7 +261,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(3), B(Star3), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(1:Smi [10]), U8(3), I8(0), B(Ldar), R(3), /* 11 E> */ B(Throw), B(Ldar), R(3), @@ -282,6 +282,7 @@ bytecodes: [ constant pool: [ Smi [20], Smi [10], + Smi [10], Smi [7], ] handlers: [ @@ -307,7 +308,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(2:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 11 E> */ B(Throw), B(Ldar), R(2), @@ -324,7 +325,7 @@ bytecodes: [ B(ResumeGenerator), R(0), R(0), RegCount8(2), B(Star2), B(InvokeIntrinsic), U8(Runtime::k_GeneratorGetResumeMode), R(0), RegCount8(1), - B(SwitchOnSmiNoFeedback), U8(4:Smi [10]), U8(2), I8(0), + B(SwitchOnSmiNoFeedback), U8(5:Smi [10]), U8(3), I8(0), B(Ldar), R(2), /* 47 E> */ B(Throw), B(Ldar), R(2), @@ -340,8 +341,10 @@ constant pool: [ Smi [20], Smi [63], Smi [10], + Smi [10], Smi [7], Smi [10], + Smi [10], Smi [7], ] handlers: [ diff --git a/deps/zlib/CMakeLists.txt b/deps/zlib/CMakeLists.txt index 87d6613be3ff..2d8bed5aac91 100644 --- a/deps/zlib/CMakeLists.txt +++ b/deps/zlib/CMakeLists.txt @@ -1,9 +1,9 @@ -cmake_minimum_required(VERSION 3.12...3.31) +cmake_minimum_required(VERSION 3.15...3.31) project( zlib LANGUAGES C - VERSION 1.3.2.1 + VERSION 1.4 HOMEPAGE_URL "https://zlib.net/" DESCRIPTION "a general-purpose lossless data-compression library") @@ -23,8 +23,8 @@ option(ZLIB_BUILD_TESTING "Enable Zlib Examples as tests" ON) option(ZLIB_BUILD_SHARED "Enable building zlib shared library" ON) option(ZLIB_BUILD_STATIC "Enable building zlib static library" ON) option(ZLIB_INSTALL "Enable installation of zlib" ON) -option(ZLIB_PREFIX "prefix for all types and library functions, see zconf.h.in" - OFF) +set(ZLIB_PREFIX "" CACHE STRING + "prefix for all types and library functions, see zconf.h.in") mark_as_advanced(ZLIB_PREFIX) get_property(IS_MULTI GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) @@ -35,7 +35,7 @@ if(NOT DEFINED CMAKE_BUILD_TYPE AND NOT IS_MULTI) endif(NOT DEFINED CMAKE_BUILD_TYPE AND NOT IS_MULTI) include(CheckCSourceCompiles) -include(CheckFunctionExists) +include(CheckSymbolExists) include(CheckIncludeFile) include(CMakePackageConfigHelpers) include(CheckTypeSize) @@ -44,12 +44,16 @@ include(GNUInstallDirs) set(CPACK_INCLUDED TRUE) +set(Z_PREFIX "${ZLIB_PREFIX}") + +# +# Create zconf.h.cmakein +# if(NOT ZLIB_CONF_WRITTEN) - set(Z_PREFIX ${ZLIB_PREFIX}) set(CONF_OUT_FILE ${zlib_BINARY_DIR}/zconf.h.cmakein) file(READ ${zlib_SOURCE_DIR}/zconf.h ZCONF_CONTENT LIMIT 245) file(WRITE ${CONF_OUT_FILE} ${ZCONF_CONTENT}) - file(APPEND ${CONF_OUT_FILE} "#cmakedefine Z_PREFIX 1\n") + file(APPEND ${CONF_OUT_FILE} "#cmakedefine Z_PREFIX @Z_PREFIX@\n") file(APPEND ${CONF_OUT_FILE} "#cmakedefine HAVE_STDARG_H 1\n") file(APPEND ${CONF_OUT_FILE} "#cmakedefine HAVE_UNISTD_H 1\n") file(READ ${zlib_SOURCE_DIR}/zconf.h ZCONF_CONTENT OFFSET 244) @@ -149,6 +153,73 @@ if (ENABLE_SIMD_OPTIMIZATIONS) endif() endif() +# +# Create zlib.def.cmakein +# +if(NOT ZLIB_DEF_WRITTEN) + file(STRINGS "${zlib_SOURCE_DIR}/win32/zlib.def" ZLIB_DEF_LINES) + + set(ZLIB_DEF_OUT "") + + foreach(line IN LISTS ZLIB_DEF_LINES) + if(line MATCHES "^;") + string(APPEND ZLIB_DEF_OUT "${line}\n") + elseif(line MATCHES "^(LIBRARY|EXPORTS|DESCRIPTION)") + string(APPEND ZLIB_DEF_OUT "${line}\n") + elseif(line MATCHES "^ *$") + string(APPEND ZLIB_DEF_OUT "\n") + elseif(line MATCHES "^ *[A-Za-z_][A-Za-z0-9_]*") + string(REGEX REPLACE "^ +" "" sym "${line}") + string(APPEND ZLIB_DEF_OUT + " @ZLIB_PREFIX@${sym}\n") + else() + string(APPEND ZLIB_DEF_OUT "${line}\n") + endif() + endforeach() + + file(WRITE + "${CMAKE_CURRENT_BINARY_DIR}/zlib.def.cmakein" + "${ZLIB_DEF_OUT}" + ) + + set(ZLIB_DEF_WRITTEN + TRUE + CACHE BOOL "zlib.def.cmakein was created") + mark_as_advanced(ZLIB_DEF_WRITTEN) +endif(NOT ZLIB_DEF_WRITTEN) + +# +#Create zlib.map +# +if(NOT ZLIB_MAP_WRITTEN) + file(STRINGS "${zlib_SOURCE_DIR}/zlib.map" ZLIB_MAP_CONTENT) + set(ZLIB_MAP_OUT "") + + foreach(line IN LISTS ZLIB_MAP_CONTENT) + if(line MATCHES "^ *[A-Za-z_][A-Za-z0-9_]* *; *$") + if(line MATCHES "^ *\\* *; *$") + string(APPEND ZLIB_MAP_OUT "${line}\n") + else() + string(REGEX REPLACE "^ +" "" sym "${line}") + string(APPEND ZLIB_MAP_OUT + " @ZLIB_PREFIX@${sym}\n") + endif() + else() + string(APPEND ZLIB_MAP_OUT "${line}\n") + endif() + endforeach() + + file(WRITE + "${zlib_BINARY_DIR}/zlib.map.cmakein" + "${ZLIB_MAP_OUT}" + ) + + set(ZLIB_MAP_WRITTEN + TRUE + CACHE BOOL "zlib.map.cmakein was created") + mark_as_advanced(ZLIB_MAP_WRITTEN) +endif(NOT ZLIB_MAP_WRITTEN) + # # Check to see if we have large file support # @@ -159,7 +230,7 @@ unset(CMAKE_REQUIRED_DEFINITIONS) # clear variable # # Check for fseeko # -check_function_exists(fseeko HAVE_FSEEKO) +check_symbol_exists(fseeko stdio.h HAVE_FSEEKO) # # Check for stdarg.h @@ -190,8 +261,21 @@ check_c_source_compiles( unset(CMAKE_COMPILE_FLAGS) set(ZLIB_PC ${zlib_BINARY_DIR}/zlib.pc) +if(IS_ABSOLUTE "${CMAKE_INSTALL_INCLUDEDIR}") + set(pc_includedir "${CMAKE_INSTALL_INCLUDEDIR}") +else() + set(pc_includedir "\${prefix}/${CMAKE_INSTALL_INCLUDEDIR}") +endif() +if(IS_ABSOLUTE "${CMAKE_INSTALL_LIBDIR}") + set(pc_libdir "${CMAKE_INSTALL_LIBDIR}") +else() + set(pc_libdir "\${exec_prefix}/${CMAKE_INSTALL_LIBDIR}") +endif() + configure_file(${zlib_SOURCE_DIR}/zlib.pc.cmakein ${ZLIB_PC} @ONLY) configure_file(${zlib_BINARY_DIR}/zconf.h.cmakein ${zlib_BINARY_DIR}/zconf.h) +configure_file(${zlib_BINARY_DIR}/zlib.def.cmakein ${zlib_BINARY_DIR}/zlib.def) +configure_file(${zlib_BINARY_DIR}/zlib.map.cmakein ${zlib_BINARY_DIR}/zlib.map) # ============================================================================ # zlib @@ -293,9 +377,12 @@ endif() if(ZLIB_BUILD_SHARED) add_library( - zlib SHARED ${ZLIB_SRCS} ${ZLIB_PUBLIC_HDRS} ${ZLIB_PRIVATE_HDRS} - $<$<OR:$<BOOL:${WIN32}>,$<BOOL:${CYGWIN}>>:win32/zlib1.rc>) + zlib SHARED ${ZLIB_SRCS} ${ZLIB_PUBLIC_HDRS} + ${ZLIB_PRIVATE_HDRS} + $<$<OR:$<BOOL:${WIN32}>,$<BOOL:${CYGWIN}>>:win32/zlib-cmake.rc> + $<$<BOOL:${MSVC}>:${zlib_BINARY_DIR}/zlib.def>) add_library(ZLIB::ZLIB ALIAS zlib) + target_include_directories( zlib PUBLIC $<BUILD_INTERFACE:${zlib_BINARY_DIR}> @@ -304,37 +391,48 @@ if(ZLIB_BUILD_SHARED) target_compile_definitions( zlib PRIVATE ZLIB_BUILD - $<$<BOOL:NOT:${HAVE_FSEEKO}>:NO_FSEEKO> + $<$<NOT:$<BOOL:${HAVE_FSEEKO}>>:NO_FSEEKO> $<$<BOOL:${HAVE___ATTR__VIS_HIDDEN}>:HAVE_HIDDEN> $<$<BOOL:${MSVC}>:_CRT_SECURE_NO_DEPRECATE> $<$<BOOL:${MSVC}>:_CRT_NONSTDC_NO_DEPRECATE> - PUBLIC $<$<BOOL:${HAVE_OFF64_T}>:_LARGEFILE64_SOURCE=1>) + PUBLIC $<$<BOOL:${HAVE_OFF64_T}>:_LARGEFILE64_SOURCE=1> + $<$<BOOL:${ZLIB_PREFIX}>:Z_PREFIX=${ZLIB_PREFIX}>) + set(INSTALL_VERSION ${zlib_VERSION}) - if(NOT CYGWIN) + if(CYGWIN) + set_target_properties(zlib PROPERTIES PREFIX "lib") + else(CYGWIN) set_target_properties(zlib PROPERTIES SOVERSION ${zlib_VERSION_MAJOR} VERSION ${INSTALL_VERSION}) - endif(NOT CYGWIN) + endif(CYGWIN) + + set_target_properties(zlib + PROPERTIES + DEFINE_SYMBOL ZLIB_DLL + EXPORT_NAME ZLIB + PUBLIC_HEADER "${ZLIB_PUBLIC_HDRS}") + + if(MSVC) + set_target_properties(zlib PROPERTIES OUTPUT_NAME libz) + else(MSVC) + set_target_properties(zlib PROPERTIES OUTPUT_NAME z) + endif(MSVC) - set_target_properties( - zlib - PROPERTIES DEFINE_SYMBOL ZLIB_DLL - EXPORT_NAME ZLIB - OUTPUT_NAME z) if(UNIX AND NOT APPLE - AND NOT (CMAKE_SYSTEM_NAME STREQUAL AIX) - AND NOT (CMAKE_SYSTEM_NAME STREQUAL SunOS)) + AND NOT (CMAKE_SYSTEM_NAME STREQUAL "AIX") + AND NOT (CMAKE_SYSTEM_NAME STREQUAL "SunOS")) # On unix-like platforms the library is almost always called libz set_target_properties( zlib PROPERTIES LINK_FLAGS - "-Wl,--version-script,\"${zlib_SOURCE_DIR}/zlib.map\"") + "-Wl,--version-script,\"${zlib_BINARY_DIR}/zlib.map\"") endif( UNIX AND NOT APPLE - AND NOT (CMAKE_SYSTEM_NAME STREQUAL AIX) - AND NOT (CMAKE_SYSTEM_NAME STREQUAL SunOS)) + AND NOT (CMAKE_SYSTEM_NAME STREQUAL "AIX") + AND NOT (CMAKE_SYSTEM_NAME STREQUAL "SunOS")) endif(ZLIB_BUILD_SHARED) if(ZLIB_BUILD_STATIC) @@ -349,14 +447,31 @@ if(ZLIB_BUILD_STATIC) target_compile_definitions( zlibstatic PRIVATE ZLIB_BUILD - $<$<BOOL:NOT:${HAVE_FSEEKO}>:NO_FSEEKO> + $<$<NOT:$<BOOL:${HAVE_FSEEKO}>>:NO_FSEEKO> $<$<BOOL:${HAVE___ATTR__VIS_HIDDEN}>:HAVE_HIDDEN> $<$<BOOL:${MSVC}>:_CRT_SECURE_NO_DEPRECATE> $<$<BOOL:${MSVC}>:_CRT_NONSTDC_NO_DEPRECATE> - PUBLIC $<$<BOOL:${HAVE_OFF64_T}>:_LARGEFILE64_SOURCE=1>) - set_target_properties( - zlibstatic PROPERTIES EXPORT_NAME ZLIBSTATIC OUTPUT_NAME - z${zlib_static_suffix}) + PUBLIC $<$<BOOL:${HAVE_OFF64_T}>:_LARGEFILE64_SOURCE=1> + $<$<BOOL:${ZLIB_PREFIX}>:Z_PREFIX=${ZLIB_PREFIX}>) + + if(CYGWIN) + set_target_properties(zlibstatic PROPERTIES PREFIX "lib") + endif(CYGWIN) + + if(MSVC) + set_target_properties(zlibstatic + PROPERTIES + ARCHIVE_OUTPUT_NAME libz${zlib_static_suffix}) + else(MSVC) + set_target_properties(zlibstatic + PROPERTIES + ARCHIVE_OUTPUT_NAME z${zlib_static_suffix}) + endif(MSVC) + + set_target_properties(zlibstatic + PROPERTIES + EXPORT_NAME ZLIBSTATIC + PUBLIC_HEADER "${ZLIB_PUBLIC_HDRS}") endif(ZLIB_BUILD_STATIC) if(ZLIB_INSTALL) @@ -367,7 +482,10 @@ if(ZLIB_INSTALL) EXPORT zlibSharedExport RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" - LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + PUBLIC_HEADER + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}" + COMPONENT Development) install( EXPORT zlibSharedExport FILE ZLIB-shared.cmake @@ -391,7 +509,8 @@ if(ZLIB_INSTALL) EXPORT zlibStaticExport RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}" ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}" - LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}") + LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}" + PUBLIC_HEADER DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install( EXPORT zlibStaticExport FILE ZLIB-static.cmake @@ -412,10 +531,6 @@ if(ZLIB_INSTALL) install(FILES ${zlib_BINARY_DIR}/ZLIBConfig.cmake ${zlib_BINARY_DIR}/ZLIBConfigVersion.cmake DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/zlib) - install( - FILES ${ZLIB_PUBLIC_HDRS} - COMPONENT Development - DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}") install( FILES zlib.3 COMPONENT Docs diff --git a/deps/zlib/README b/deps/zlib/README index e28388bfefa9..265c8b47d316 100644 --- a/deps/zlib/README +++ b/deps/zlib/README @@ -1,6 +1,6 @@ ZLIB DATA COMPRESSION LIBRARY -zlib 1.3.2.1 is a general purpose data compression library. All the code is +zlib 1.4 is a general purpose data compression library. All the code is thread safe (though see the FAQ for caveats). The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 at https://datatracker.ietf.org/doc/html/rfc1950 (zlib format), rfc1951 (deflate @@ -31,7 +31,7 @@ Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan. 1997 issue of Dr. Dobb's Journal; a copy of the article is available at https://zlib.net/nelson/ . -The changes made in version 1.3.2.1 are documented in the file ChangeLog. +The changes made in version 1.4 are documented in the file ChangeLog. Unsupported third party contributions are provided in directory contrib/ . diff --git a/deps/zlib/README.chromium b/deps/zlib/README.chromium index 232ef66aeb2b..0c95bd0b132a 100644 --- a/deps/zlib/README.chromium +++ b/deps/zlib/README.chromium @@ -1,10 +1,10 @@ Name: zlib Short Name: zlib URL: https://github.com/madler/zlib -Version: 1.3.2 -Revision: 09a1572aa624e5ddb6c075dc013880de70b1b9b9 +Version: 1.4 +Revision: 99623ef7097352da7993ba614161fd6a311e046e Update Mechanism: Manual (https://crbug.com/422348588) -CPEPrefix: cpe:/a:zlib:zlib:1.3.2 +CPEPrefix: cpe:/a:zlib:zlib:1.4 Security Critical: yes Shipped: yes License: Zlib @@ -15,7 +15,7 @@ Description: "A massively spiffy yet delicately unobtrusive compression library." zlib is a free, general-purpose, legally unencumbered lossless data-compression -library. zlib implements the "deflate" compression algorithm described by RFC +library. zlib implements the "deflate" compression algorithm described by RFC 1951, which combines the LZ77 (Lempel-Ziv) algorithm with Huffman coding. zlib also implements the zlib (RFC 1950) and gzip (RFC 1952) wrapper formats. diff --git a/deps/zlib/compress.c b/deps/zlib/compress.c index e3a7516e4f99..8a3e6bc8afbc 100644 --- a/deps/zlib/compress.c +++ b/deps/zlib/compress.c @@ -28,8 +28,8 @@ int ZEXPORT compress2_z(Bytef *dest, z_size_t *destLen, const Bytef *source, const uInt max = (uInt)-1; z_size_t left; - if ((sourceLen > 0 && source == NULL) || - destLen == NULL || (*destLen > 0 && dest == NULL)) + if ((sourceLen > 0 && source == Z_NULL) || + destLen == Z_NULL || (*destLen > 0 && dest == Z_NULL)) return Z_STREAM_ERROR; left = *destLen; diff --git a/deps/zlib/contrib/minizip/ChangeLogUnzip b/deps/zlib/contrib/minizip/ChangeLogUnzip deleted file mode 100644 index e62af147dce6..000000000000 --- a/deps/zlib/contrib/minizip/ChangeLogUnzip +++ /dev/null @@ -1,67 +0,0 @@ -Change in 1.01e (12 feb 05) -- Fix in zipOpen2 for globalcomment (Rolf Kalbermatter) -- Fix possible memory leak in unzip.c (Zoran Stevanovic) - -Change in 1.01b (20 may 04) -- Integrate patch from Debian package (submited by Mark Brown) -- Add tools mztools from Xavier Roche - -Change in 1.01 (8 may 04) -- fix buffer overrun risk in unzip.c (Xavier Roche) -- fix a minor buffer insecurity in minizip.c (Mike Whittaker) - -Change in 1.00: (10 sept 03) -- rename to 1.00 -- cosmetic code change - -Change in 0.22: (19 May 03) -- crypting support (unless you define NOCRYPT) -- append file in existing zipfile - -Change in 0.21: (10 Mar 03) -- bug fixes - -Change in 0.17: (27 Jan 02) -- bug fixes - -Change in 0.16: (19 Jan 02) -- Support of ioapi for virtualize zip file access - -Change in 0.15: (19 Mar 98) -- fix memory leak in minizip.c - -Change in 0.14: (10 Mar 98) -- fix bugs in minizip.c sample for zipping big file -- fix problem in month in date handling -- fix bug in unzlocal_GetCurrentFileInfoInternal in unzip.c for - comment handling - -Change in 0.13: (6 Mar 98) -- fix bugs in zip.c -- add real minizip sample - -Change in 0.12: (4 Mar 98) -- add zip.c and zip.h for creates .zip file -- fix change_file_date in miniunz.c for Unix (Jean-loup Gailly) -- fix miniunz.c for file without specific record for directory - -Change in 0.11: (3 Mar 98) -- fix bug in unzGetCurrentFileInfo for get extra field and comment -- enhance miniunz sample, remove the bad unztst.c sample - -Change in 0.10: (2 Mar 98) -- fix bug in unzReadCurrentFile -- rename unzip* to unz* function and structure -- remove Windows-like hungary notation variable name -- modify some structure in unzip.h -- add somes comment in source -- remove unzipGetcCurrentFile function -- replace ZUNZEXPORT by ZEXPORT -- add unzGetLocalExtrafield for get the local extrafield info -- add a new sample, miniunz.c - -Change in 0.4: (25 Feb 98) -- suppress the type unzipFileInZip. - Only on file in the zipfile can be open at the same time -- fix somes typo in code -- added tm_unz structure in unzip_file_info (date/time in readable format) diff --git a/deps/zlib/contrib/minizip/README.chromium b/deps/zlib/contrib/minizip/README.chromium index 78cbd20018b1..98a7a72a4299 100644 --- a/deps/zlib/contrib/minizip/README.chromium +++ b/deps/zlib/contrib/minizip/README.chromium @@ -1,8 +1,8 @@ Name: ZIP file API for reading file entries in a ZIP archive Short Name: minizip URL: https://github.com/madler/zlib/tree/master/contrib/minizip -Version: 1.3.2 -Revision: 09a1572aa624e5ddb6c075dc013880de70b1b9b9 +Version: 1.4 +Revision: 99623ef7097352da7993ba614161fd6a311e046e Update Mechanism: Manual License: Zlib License File: //third_party/zlib/LICENSE diff --git a/deps/zlib/contrib/minizip/skipset.h b/deps/zlib/contrib/minizip/skipset.h index ec4d4ab4dc48..ad09dd09b199 100644 --- a/deps/zlib/contrib/minizip/skipset.h +++ b/deps/zlib/contrib/minizip/skipset.h @@ -1,56 +1,59 @@ /* skipset.h -- set operations using a skiplist -// Copyright (C) 2024-2026 Mark Adler -// See MiniZip_info.txt for the license. - -// This implements a skiplist set, i.e. just keys, no data, with ~O(log n) time -// insert and search operations. The application defines the type of a key, and -// provides a function to compare two keys. - -// This header is not definitions of functions found in another source file -- -// it creates the set functions, with the application's key type, right where -// the #include is. Before this header is #included, these must be defined: -// -// 1. A macro or typedef for set_key_t, the type of a key. -// 2. A macro or function set_cmp(a, b) to compare two keys. The return values -// are < 0 for a < b, 0 for a == b, and > 0 for a > b. -// 3. A macro or function set_drop(s, k) to release the key k's resources, if -// any, when doing a set_end() or set_clear(). s is a pointer to the set -// that key is in, for use with set_free() if desired. -// -// Example usage: -// -// typedef int set_key_t; -// #define set_cmp(a, b) ((a) < (b) ? -1 : (a) == (b) ? 0 : 1) -// #define set_drop(s, k) -// #include "skipset.h" -// -// int test(void) { // return 0: good, 1: bad, -1: out of memory -// set_t set; -// if (setjmp(set.env)) -// return -1; -// set_start(&set); -// set_insert(&set, 2); -// set_insert(&set, 1); -// set_insert(&set, 7); -// int bad = !set_found(&set, 2); -// bad = bad || set_found(&set, 5); -// set_end(&set); -// return bad; -// } -// -// Interface summary (see more details below): -// - set_t is the type of the set being operated on (a set_t pointer is passed) -// - set_start() initializes a new, empty set (initialize set.env first) -// - set_insert() inserts a new key into the set, or not if it's already there -// - set_found() determines whether or not a key is in the set -// - set_end() ends the use of the set, freeing all memory -// - set_clear() empties the set, equivalent to set_end() and then set_start() -// - set_ok() checks if set appears to be usable, i.e. started and not ended -// -// Auxiliary functions available to the application: -// - set_alloc() allocates memory with optional tracking (#define SET_TRACK) -// - set_free() deallocates memory allocated by set_alloc() -// - set_rand() returns 32 random bits (seeded by set_start()) */ + Copyright (C) 2024-2026 Mark Adler + See MiniZip_info.txt for the license. + */ + +/* + This implements a skiplist set, i.e. just keys, no data, with ~O(log n) time + insert and search operations. The application defines the type of a key, and + provides a function to compare two keys. + + This header is not definitions of functions found in another source file -- + it creates the set functions, with the application's key type, right where + the #include is. Before this header is #included, these must be defined: + + 1. A macro or typedef for set_key_t, the type of a key. + 2. A macro or function set_cmp(a, b) to compare two keys. The return values + are < 0 for a < b, 0 for a == b, and > 0 for a > b. + 3. A macro or function set_drop(s, k) to release the key k's resources, if + any, when doing a set_end() or set_clear(). s is a pointer to the set + that key is in, for use with set_free() if desired. + + Example usage: + + typedef int set_key_t; + #define set_cmp(a, b) ((a) < (b) ? -1 : (a) == (b) ? 0 : 1) + #define set_drop(s, k) + #include "skipset.h" + + int test(void) { // return 0: good, 1: bad, -1: out of memory + set_t set; + if (setjmp(set.env)) + return -1; + set_start(&set); + set_insert(&set, 2); + set_insert(&set, 1); + set_insert(&set, 7); + int bad = !set_found(&set, 2); + bad = bad || set_found(&set, 5); + set_end(&set); + return bad; + } + + Interface summary (see more details below): + - set_t is the type of the set being operated on (a set_t pointer is passed) + - set_start() initializes a new, empty set (initialize set.env first) + - set_insert() inserts a new key into the set, or not if it's already there + - set_found() determines whether or not a key is in the set + - set_end() ends the use of the set, freeing all memory + - set_clear() empties the set, equivalent to set_end() and then set_start() + - set_ok() checks if set appears to be usable, i.e. started and not ended + + Auxiliary functions available to the application: + - set_alloc() allocates memory with optional tracking (#define SET_TRACK) + - set_free() deallocates memory allocated by set_alloc() + - set_rand() returns 32 random bits (seeded by set_start()) + */ #ifndef SKIPSET_H #define SKIPSET_H @@ -63,38 +66,44 @@ #include <assert.h> /* assert.h */ #include "ints.h" /* i16_t, ui32_t, ui64_t */ -/* Structures and functions below noted as "--private--" should not be used by -// the application. set_t is partially private and partially public -- see the -// comments there. +/* + Structures and functions below noted as "--private--" should not be used by + the application. set_t is partially private and partially public -- see the + comments there. -// There is no POSIX random() in MSVC, and rand() is awful. For portability, we -// cannot rely on a library function for random numbers. Instead we use the -// fast and effective algorithm below, invented by Melissa O'Neill. + There is no POSIX random() in MSVC, and rand() is awful. For portability, we + cannot rely on a library function for random numbers. Instead we use the + fast and effective algorithm below, invented by Melissa O'Neill. + */ -// *Really* minimal PCG32 code / (c) 2014 M.E. O'Neill / www.pcg-random.org -// Licensed under Apache License 2.0 (NO WARRANTY, etc. see website) -// --private-- Random number generator state. */ +/* + *Really* minimal PCG32 code / (c) 2014 M.E. O'Neill / www.pcg-random.org + Licensed under Apache License 2.0 (NO WARRANTY, etc. see website) + --private-- Random number generator state. + */ typedef struct { ui64_t state; /* 64-bit generator state */ ui64_t inc; /* 63-bit sequence id */ } set_rand_t; /* --private-- Initialize the state *gen using seed and seq. seed seeds the -// advancing 64-bit state. seq is a sequence selection constant. */ -void set_seed(set_rand_t *gen, ui64_t seed, ui64_t seq) { + advancing 64-bit state. seq is a sequence selection constant. */ +static void set_seed(set_rand_t *gen, ui64_t seed, ui64_t seq) { gen->inc = (seq << 1) | 1; gen->state = (seed + gen->inc) * 6364136223846793005ULL + gen->inc; } /* Start a unique random number sequence using bits from noise sources. */ -void set_uniq(set_rand_t *gen, const void *ptr) { +static void set_uniq(set_rand_t *gen, const void *ptr) { set_seed(gen, ((ui64_t)(ptrdiff_t)ptr << 32) ^ ((ui64_t)time(NULL) << 12) ^ clock(), 0); } /* Return 32 random bits, advancing the state *gen. */ -ui32_t set_rand(set_rand_t *gen) { +static ui32_t set_rand(set_rand_t *gen) { + ui32_t mix; + int rot; ui64_t state = gen->state; gen->state = state * 6364136223846793005ULL + gen->inc; - ui32_t mix = (ui32_t)(((state >> 18) ^ state) >> 27); - int rot = state >> 59; + mix = (ui32_t)(((state >> 18) ^ state) >> 27); + rot = state >> 59; return (mix >> rot) | (mix << ((-rot) & 31)); } /* End of PCG32 code. */ @@ -109,7 +118,7 @@ struct set_node_s { }; /* A set. The application sets env, may use gen with set_rand(), and may read -// allocs and memory. The remaining variables are --private-- . */ + allocs and memory. The remaining variables are --private-- . */ typedef struct set_s { set_node_t *head; /* skiplist head -- no key, just links */ set_node_t *path; /* right[] is path to key from set_found() */ @@ -120,15 +129,15 @@ typedef struct set_s { jmp_buf env; /* setjmp() environment for allocation errors */ #ifdef SET_TRACK size_t allocs; /* number of allocations */ - size_t memory; /* total amount of allocated memory (>= requests) */ + size_t memory; /* total size of allocated memory (>= requests) */ #endif } set_t; /* Memory allocation and deallocation. set_alloc(set, ptr, size) returns a -// pointer to an allocation of size bytes if ptr is NULL, or the previous -// allocation ptr resized to size bytes. set_alloc() will never return NULL. -// set_free(set, ptr) frees an allocation created by set_alloc(). These may be -// used by the application. e.g. if allocation tracking is desired. */ + pointer to an allocation of size bytes if ptr is NULL, or the previous + allocation ptr resized to size bytes. set_alloc() will never return NULL. + set_free(set, ptr) frees an allocation created by set_alloc(). These may be + used by the application. e.g. if allocation tracking is desired. */ #ifdef SET_TRACK /* Track the number of allocations and the total backing memory size. */ # if defined(_WIN32) @@ -146,11 +155,11 @@ typedef struct set_s { # elif defined(__NetBSD__) # include <jemalloc/jemalloc.h> # define SET_ALLOC_SIZE(ptr) malloc_usable_size(ptr) -# else // e.g. OpenBSD +# else /* e.g. OpenBSD */ # define SET_ALLOC_SIZE(ptr) 0 # endif -// With tracking. -void *set_alloc(set_t *set, void *ptr, size_t size) { +/* With tracking. */ +static void *set_alloc(set_t *set, void *ptr, size_t size) { size_t had = ptr == NULL ? 0 : SET_ALLOC_SIZE(ptr); void *mem = realloc(ptr, size); if (mem == NULL) @@ -159,7 +168,7 @@ void *set_alloc(set_t *set, void *ptr, size_t size) { set->memory += SET_ALLOC_SIZE(mem) - had; return mem; } -void set_free(set_t *set, void *ptr) { +static void set_free(set_t *set, void *ptr) { if (ptr != NULL) { set->allocs--; set->memory -= SET_ALLOC_SIZE(ptr); @@ -168,23 +177,24 @@ void set_free(set_t *set, void *ptr) { } #else /* Without tracking. */ -void *set_alloc(set_t *set, void *ptr, size_t size) { +static void *set_alloc(set_t *set, void *ptr, size_t size) { void *mem = realloc(ptr, size); if (mem == NULL) longjmp(set->env, ENOMEM); return mem; } -void set_free(set_t *set, void *ptr) { +static void set_free(set_t *set, void *ptr) { (void)set; free(ptr); } #endif /* --private-- Grow node's array right[] as needed to be able to hold at least -// want links. If fill is true, assure that the first want links are filled in, -// setting them to set->head if not previously filled in. Otherwise it is -// assumed that the first want links are about to be filled in. */ -void set_grow(set_t *set, set_node_t *node, int want, int fill) { + want links. If fill is true, assure that the first want links are filled in, + setting them to set->head if not previously filled in. Otherwise it is + assumed that the first want links are about to be filled in. */ +static void set_grow(set_t *set, set_node_t *node, int want, int fill) { + int i; if (node->size < want) { int more = node->size ? node->size : 1; while (more < want) @@ -193,7 +203,6 @@ void set_grow(set_t *set, set_node_t *node, int want, int fill) { (size_t)more * sizeof(set_node_t *)); node->size = (i16_t)more; } - int i; if (fill) for (i = node->fill; i < want; i++) node->right[i] = set->head; @@ -201,7 +210,7 @@ void set_grow(set_t *set, set_node_t *node, int want, int fill) { } /* --private-- Return a new node. key is left uninitialized. */ -set_node_t *set_node(set_t *set) { +static set_node_t *set_node(set_t *set) { set_node_t *node = set_alloc(set, NULL, sizeof(set_node_t)); node->size = 0; node->fill = 0; @@ -210,7 +219,7 @@ set_node_t *set_node(set_t *set) { } /* --private-- Free the list linked from head, along with the keys. */ -void set_sweep(set_t *set) { +static void set_sweep(set_t *set) { set_node_t *step = set->head->right[0]; while (step != set->head) { set_node_t *next = step->right[0]; /* save link to next node */ @@ -222,12 +231,12 @@ void set_sweep(set_t *set) { } /* Initialize a new set. set->env must be initialized using setjmp() before -// set_start() is called. A longjmp(set->env, ENOMEM) will be used to handle a -// memory allocation failure during any of the operations. (See setjmp.h and -// errno.h.) The set can still be used if this happens, assuming that it didn't -// happen during set_start(). Whether set_start() completed or not, set_end() -// can be used to free the set's memory after a longjmp(). */ -void set_start(set_t *set) { + set_start() is called. A longjmp(set->env, ENOMEM) will be used to handle a + memory allocation failure during any of the operations. (See setjmp.h and + errno.h.) The set can still be used if this happens, assuming that it didn't + happen during set_start(). Whether set_start() completed or not, set_end() + can be used to free the set's memory after a longjmp(). */ +SKIPSET_EXPORT void set_start(set_t *set) { #ifdef SET_TRACK set->allocs = 0; set->memory = 0; @@ -235,7 +244,7 @@ void set_start(set_t *set) { set->head = set->path = set->node = NULL; /* in case set_node() fails */ set->path = set_node(set); set->head = set_node(set); - set_grow(set, set->head, 1, 1); /* one link back to head for an empty set */ + set_grow(set, set->head, 1, 1); /* one link back to head for empty set */ *(unsigned char *)&set->head->key = 137; /* set id */ set->depth = 0; set_uniq(&set->gen, set); @@ -243,34 +252,36 @@ void set_start(set_t *set) { } /* Return true if *set appears to be in a usable state. If *set has been zeroed -// out, then set_ok(set) will be false and set_end(set) will be safe. */ -int set_ok(set_t *set) { + out, then set_ok(set) will be false and set_end(set) will be safe. */ +SKIPSET_EXPORT int set_ok(set_t *set) { return set->head != NULL && set->head->right != NULL && *(unsigned char *)&set->head->key == 137; } +#if 0 /* not used in minizip */ /* Empty the set. This frees the memory used for the previous set contents. -// After set_clear(), *set is ready for use, as if after a set_start(). */ -void set_clear(set_t *set) { + After set_clear(), *set is ready for use, as if after a set_start(). */ +SKIPSET_EXPORT void set_clear(set_t *set) { assert(set_ok(set) && "improper use"); /* Free all the keys and their nodes. */ set_sweep(set); /* Leave the head and path allocations as is. Clear their contents, with - // head pointing to itself and setting depth to zero, for an empty set. */ + head pointing to itself and setting depth to zero, for an empty set. */ set->head->right[0] = set->head; set->head->fill = 1; set->path->fill = 0; set->depth = 0; } +#endif /* Done using the set -- free all allocations. The only operation on *set -// permitted after this is set_start(). Though another set_end() would do no -// harm. This can be done at any time after a set_start(), or after a longjmp() -// on any allocation failure, including during a set_start(). */ -void set_end(set_t *set) { + permitted after this is set_start(). Though another set_end() would do no + harm. This can be done at any time after a set_start(), or after a longjmp() + on any allocation failure, including during a set_start(). */ +SKIPSET_EXPORT void set_end(set_t *set) { if (set->head != NULL) { /* Empty the set and free the head node. */ if (set->head->right != NULL) { @@ -296,13 +307,16 @@ void set_end(set_t *set) { } /* Look for key. Return 1 if found or 0 if not. This also puts the path to get -// there in set->path, for use by set_insert(). */ -int set_found(set_t *set, set_key_t key) { + there in set->path, for use by set_insert(). */ +SKIPSET_EXPORT int set_found(set_t *set, set_key_t key) { + set_node_t *head, *here; + int i; assert(set_ok(set) && "improper use"); - /* Start at depth and work down and right as determined by key comparisons. */ - set_node_t *head = set->head, *here = head; - int i = set->depth; + /* Start at depth. Work down and right as determined by key comparisons. */ + head = set->head; + here = head; + i = set->depth; set_grow(set, set->path, i + 1, 0); do { while (here->right[i] != head && @@ -316,8 +330,11 @@ int set_found(set_t *set, set_key_t key) { return here != head && set_cmp(here->key, key) == 0; } -/* Insert the key key. Return 0 on success, or 1 if key is already in the set. */ -int set_insert(set_t *set, set_key_t key) { +/* Insert the key key. Return 0 on success, or 1 if it's already in the set. */ +SKIPSET_EXPORT int set_insert(set_t *set, set_key_t key) { + int level = 0; + int bit; + int i; assert(set_ok(set) && "improper use"); if (set_found(set, key)) @@ -325,13 +342,12 @@ int set_insert(set_t *set, set_key_t key) { return 1; /* Randomly generate a new level-- level 0 with probability 1/2, 1 with - // probability 1/4, 2 with probability 1/8, etc. */ - int level = 0; + probability 1/4, 2 with probability 1/8, etc. */ for (;;) { if (set->ran == 1) /* Ran out. Get another 32 random bits. */ set->ran = set_rand(&set->gen) | (1ULL << 32); - int bit = set->ran & 1; + bit = set->ran & 1; set->ran >>= 1; if (bit) break; @@ -347,11 +363,10 @@ int set_insert(set_t *set, set_key_t key) { } /* Make a new node for the provided key, and insert it in the lists up to - // and including level. */ + and including level. */ set->node = set_node(set); set->node->key = key; set_grow(set, set->node, level + 1, 0); - int i; for (i = 0; i <= level; i++) { set->node->right[i] = set->path->right[i]->right[i]; set->path->right[i]->right[i] = set->node; diff --git a/deps/zlib/contrib/minizip/unzip.c b/deps/zlib/contrib/minizip/unzip.c index 4eb0de302cfd..c5e69721a8f7 100644 --- a/deps/zlib/contrib/minizip/unzip.c +++ b/deps/zlib/contrib/minizip/unzip.c @@ -1054,14 +1054,16 @@ local int unz64local_GetCurrentFileInfoInternal(unzFile file, /* dataSize includes version (1 byte), uCrc (4 bytes), and * the filename data. If it's too small, fileNameSize below * would overflow. */ - err = UNZ_ERRNO; - break; + if (ZSEEK64(s->z_filefunc, s->filestream, dataSize, ZLIB_FILEFUNC_SEEK_CUR) != 0) + { + err = UNZ_ERRNO; + } } else if (unz64local_getByte(&s->z_filefunc, s->filestream, &version) != UNZ_OK) { err = UNZ_ERRNO; } - if (version != 1) + else if (version != 1) { if (ZSEEK64(s->z_filefunc, s->filestream,dataSize - 1, ZLIB_FILEFUNC_SEEK_CUR) != 0) { @@ -1320,13 +1322,12 @@ extern int ZEXPORT unzLocateFile(unzFile file, const char *szFileName, int iCase /* -/////////////////////////////////////////// -// Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) -// I need random access -// -// Further optimization could be realized by adding an ability -// to cache the directory in memory. The goal being a single -// comprehensive file read to put the file I need in a memory. + Contributed by Ryan Haksi (mailto://cryogen@infoserve.net) + I need random access + + Further optimization could be realized by adding an ability + to cache the directory in memory. The goal being a single + comprehensive file read to put the file I need in a memory. */ /* @@ -1395,8 +1396,7 @@ extern int ZEXPORT unzGoToFilePos(unzFile file, unz_file_pos* file_pos) { } /* -// Unzip Helper Functions - should be here? -/////////////////////////////////////////// + Unzip Helper Functions - should be here? */ /* diff --git a/deps/zlib/contrib/minizip/zip.c b/deps/zlib/contrib/minizip/zip.c index 31005c51b062..0bbdf77e5fc0 100644 --- a/deps/zlib/contrib/minizip/zip.c +++ b/deps/zlib/contrib/minizip/zip.c @@ -128,7 +128,8 @@ typedef struct linkedlist_data_s /* zipAlreadyThere() set functions for a set of zero-terminated strings, and -// a block_t type for reading the central directory datablocks. */ + a block_t type for reading the central directory datablocks. */ +#define SKIPSET_EXPORT static typedef char *set_key_t; #define set_cmp(a, b) strcmp(a, b) #define set_drop(s, k) set_free(s, k) @@ -286,18 +287,18 @@ local int add_data_in_datablock(linkedlist_data* ll, const void* buf, uLong len) } /* zipAlreadyThere() operations. "set" in the zip internal structure keeps the -// set of names that are in the under-construction central directory so far. A -// skipset provides ~O(log n) time insertion and searching. Central directory -// records, stored in a linked list of allocated memory datablocks, is read -// through "block" in the zip internal structure. - -// The block_*() functions support extracting the central directory file names -// from the datablocks. They are designed to support a growing directory by -// automatically continuing once more data has been appended to the linked -// datablocks. - -// Initialize *block to the head of list. This should only be called once the -// list has at least some data in it, i.e. list->first_block is not NULL. */ + set of names that are in the under-construction central directory so far. A + skipset provides ~O(log n) time insertion and searching. Central directory + records, stored in a linked list of allocated memory datablocks, is read + through "block" in the zip internal structure. + + The block_*() functions support extracting the central directory file names + from the datablocks. They are designed to support a growing directory by + automatically continuing once more data has been appended to the linked + datablocks. + + Initialize *block to the head of list. This should only be called once the + list has at least some data in it, i.e. list->first_block is not NULL. */ local void block_init(block_t *block, linkedlist_data *list) { block->node = list->first_block; block->next = block->node->data; @@ -305,8 +306,8 @@ local void block_init(block_t *block, linkedlist_data *list) { } /* Mark *block as bad, with all subsequent reads returning end, even if more -// data is added to the datablocks. This is invoked if the central directory is -// invalid, so there is no longer any point in attempting to interpret it. */ + data is added to the datablocks. This is invoked if the central directory is + invalid, so there is no longer any point in attempting to interpret it. */ local void block_stop(block_t *block) { block->left = 0; block->next = NULL; @@ -357,7 +358,7 @@ local int block_get(block_t *block) { } /* Return a 16-bit unsigned little-endian value from block, or a negative value -// if the end is reached. */ + if the end is reached. */ local long block_get2(block_t *block) { int low = block_get(block); int high = block_get(block); @@ -367,6 +368,7 @@ local long block_get2(block_t *block) { /* Read up to len bytes from block into buf. Return the number of bytes read. */ local size_t block_read(block_t *block, unsigned char *buf, size_t len) { size_t need = len; + size_t take; while (need) { if (block->left == 0) { /* Get a byte to update and step through the linked list as needed. */ @@ -378,7 +380,7 @@ local size_t block_read(block_t *block, unsigned char *buf, size_t len) { need--; continue; } - size_t take = need > block->left ? block->left : need; + take = need > block->left ? block->left : need; memcpy(buf, block->next, take); block->next += take; block->left -= take; @@ -389,7 +391,7 @@ local size_t block_read(block_t *block, unsigned char *buf, size_t len) { } /* Skip n bytes in block. Return 0 on success or -1 if there are less than n -// bytes to the end. */ + bytes to the end. */ local int block_skip(block_t *block, size_t n) { while (n > block->left) { n -= block->left; @@ -405,9 +407,10 @@ local int block_skip(block_t *block, size_t n) { } /* Process the next central directory record at *block. Return the allocated, -// zero-terminated file name, or NULL for end of input or invalid data. If -// invalid, *block is marked bad. This uses *set for the allocation of memory. */ + zero-terminated file name, or NULL for end of input or invalid data. If + invalid, *block is marked bad. This uses *set for the allocation of memory. */ local char *block_central_name(block_t *block, set_t *set) { + unsigned flen, xlen, clen; char *name = NULL; for (;;) { if (block_end(block)) @@ -421,11 +424,11 @@ local char *block_central_name(block_t *block, set_t *set) { break; /* Go through the remaining fixed-length portion of the record, - // extracting the lengths of the three variable-length fields. */ + extracting the lengths of the three variable-length fields. */ block_skip(block, 24); - unsigned flen = (unsigned)block_get2(block); /* file name length */ - unsigned xlen = (unsigned)block_get2(block); /* extra length */ - unsigned clen = (unsigned)block_get2(block); /* comment length */ + flen = (unsigned)block_get2(block); /* file name length */ + xlen = (unsigned)block_get2(block); /* extra length */ + clen = (unsigned)block_get2(block); /* comment length */ if (block_skip(block, 12) == -1) /* Premature end of the record. */ break; @@ -440,9 +443,9 @@ local char *block_central_name(block_t *block, set_t *set) { /* Check for embedded nuls in the name. */ if (memchr(name, 0, flen) != NULL) { /* This name can never match the zero-terminated name provided to - // zipAlreadyThere(), so we discard it and go back to get another - // name. (Who the heck is putting nuls inside their zip file entry - // names anyway?) */ + zipAlreadyThere(), so we discard it and go back to get another + name. (Who the heck is putting nuls inside their zip file entry + names anyway?) */ set_free(set, name); continue; } @@ -453,16 +456,19 @@ local char *block_central_name(block_t *block, set_t *set) { } /* Invalid signature or premature end of the central directory record. - // Abandon trying to process the central directory. */ + Abandon trying to process the central directory. */ set_free(set, name); block_stop(block); return NULL; } /* Return 0 if name is not in the central directory so far, 1 if it is, -1 if -// the central directory is invalid, -2 if out of memory, or ZIP_PARAMERROR if -// file is NULL. */ + the central directory is invalid, -2 if out of memory, or ZIP_PARAMERROR if + file is NULL. */ extern int ZEXPORT zipAlreadyThere(zipFile file, char const *name) { + size_t len; + char *copy; + int found; zip64_internal *zip = file; if (zip == NULL) return ZIP_PARAMERROR; @@ -476,14 +482,14 @@ extern int ZEXPORT zipAlreadyThere(zipFile file, char const *name) { } if (!set_ok(&zip->set)) { /* This is the first time here with some central directory content. We - // construct this set of names only on demand. Prepare set and block. */ + construct this set of names only on demand. Prepare set and block. */ set_start(&zip->set); block_init(&zip->block, &zip->central_dir); } /* Update the set of names from the current central directory contents. - // This reads any new central directory records since the last time we were - // here. */ + This reads any new central directory records since the last time we were + here. */ for (;;) { char *there = block_central_name(&zip->block, &zip->set); if (there == NULL) { @@ -496,15 +502,15 @@ extern int ZEXPORT zipAlreadyThere(zipFile file, char const *name) { /* Add there to the set. */ if (set_insert(&zip->set, there)) /* There's already a duplicate in the central directory! We'll just - // let this be and carry on. */ + let this be and carry on. */ set_free(&zip->set, there); } /* Return true if name is in the central directory. */ - size_t len = strlen(name); - char *copy = set_alloc(&zip->set, NULL, len + 1); + len = strlen(name); + copy = set_alloc(&zip->set, NULL, len + 1); memcpy(copy, name, len + 1); - int found = set_found(&zip->set, copy); + found = set_found(&zip->set, copy); set_free(&zip->set, copy); return found; } @@ -939,7 +945,7 @@ local int LoadCentralDirectoryRecord(zip64_internal* pziinit) { err=ZIP_ERRNO; /* TODO.. - // read the comment from the standard central header. */ + read the comment from the standard central header. */ size_comment = 0; } else @@ -1334,8 +1340,8 @@ extern int ZEXPORT zipOpenNewFileInZip4_64(zipFile file, const char* filename, c if ((comment!=NULL) && (strlen(comment)>0xffff)) return ZIP_PARAMERROR; /* The extra field length must fit in 16 bits. If the member also requires - // a Zip64 extra block, that will also need to fit within that 16-bit - // length, but that will be checked for later. */ + a Zip64 extra block, that will also need to fit within that 16-bit + length, but that will be checked for later. */ if ((size_extrafield_local>0xffff) || (size_extrafield_global>0xffff)) return ZIP_PARAMERROR; @@ -1927,8 +1933,8 @@ extern int ZEXPORT zipCloseFileInZipRaw64(zipFile file, ZPOS64_T uncompressed_si } /* Update how much extra free space we got in the memory buffer - // and increase the centralheader size so the new ZIP64 fields are included - // ( 4 below is the size of HeaderID and DataSize field ) */ + and increase the centralheader size so the new ZIP64 fields are included + ( 4 below is the size of HeaderID and DataSize field ) */ zi->ci.size_centralExtraFree -= datasize + 4; zi->ci.size_centralheader += datasize + 4; diff --git a/deps/zlib/contrib/optimizations/inflate.c b/deps/zlib/contrib/optimizations/inflate.c index 3268320e9120..5c5938d3e522 100644 --- a/deps/zlib/contrib/optimizations/inflate.c +++ b/deps/zlib/contrib/optimizations/inflate.c @@ -133,6 +133,14 @@ int ZEXPORT inflateReset(z_streamp strm) { if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; + if (state->wbits != state->reqbits) { + if (state->window != Z_NULL) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + state->wbits = state->reqbits; + } + state->wrap = state->reqwrap; state->wsize = 0; state->whave = 0; state->wnext = 0; @@ -171,8 +179,8 @@ int ZEXPORT inflateReset2(z_streamp strm, int windowBits) { } /* update state and reset the rest of it */ - state->wrap = wrap; - state->wbits = (unsigned)windowBits; + state->reqwrap = state->wrap = wrap; + state->reqbits = state->wbits = (unsigned)windowBits; return inflateReset(strm); } @@ -665,13 +673,13 @@ int ZEXPORT inflate(z_streamp strm, int flush) { } DROPBITS(4); len = BITS(4) + 8; - if (state->wbits == 0) - state->wbits = len; - if (len > 15 || len > state->wbits) { - strm->msg = (char *)"invalid window size"; + if (len > 15 || (state->wbits != 0 && len > state->wbits)) { + strm->msg = (z_const char *)"invalid window size"; state->mode = BAD; break; } + if (state->wbits == 0) + state->wbits = len; state->dmax = 1U << len; state->flags = 0; /* indicate zlib header */ Tracev((stderr, "inflate: zlib header ok\n")); @@ -828,6 +836,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) { case DICT: if (state->havedict == 0) { RESTORE(); + strm->total_in += in - strm->avail_in; return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); @@ -1037,7 +1046,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) { /* fallthrough */ case LEN: if (have >= INFLATE_FAST_MIN_INPUT && - left >= INFLATE_FAST_MIN_OUTPUT) { + left >= INFLATE_FAST_MIN_OUTPUT && + bits < 8) { RESTORE(); inflate_fast_chunk_(strm, out); LOAD(); @@ -1337,7 +1347,8 @@ int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary, int ret; /* check state */ - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + if (inflateStateCheck(strm) || dictionary == Z_NULL) + return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; @@ -1442,15 +1453,23 @@ int ZEXPORT inflateSync(z_streamp strm) { /* return no joy or set up to restart inflate() on a new block */ if (state->have != 4) return Z_DATA_ERROR; - if (state->flags == -1) - state->wrap = 0; /* if no header yet, treat as raw */ - else - state->wrap &= ~4; /* no point in computing a check value now */ flags = state->flags; in = strm->total_in; out = strm->total_out; inflateReset(strm); strm->total_in = in; strm->total_out = out; state->flags = flags; + if (flags == -1) + state->wrap = 0; /* if no header yet, treat as raw */ + else + state->wrap &= ~4; /* no point in computing a check value now */ + if (state->wbits == 0) { + /* we never got to see a header for the window size -- set to max */ + if (state->window != Z_NULL) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + state->wbits = 15; + } state->mode = TYPE; return Z_OK; } @@ -1478,14 +1497,22 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) { unsigned wsize; /* check input */ - if (inflateStateCheck(source) || dest == Z_NULL) + if (dest == Z_NULL) return Z_STREAM_ERROR; + if (inflateStateCheck(source)) { + dest->state = Z_NULL; + return Z_STREAM_ERROR; + } state = (struct inflate_state FAR *)source->state; /* allocate space */ copy = (struct inflate_state FAR *) ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; + if (copy == Z_NULL) { + dest->state = Z_NULL; + return Z_MEM_ERROR; + } + zmemzero(copy, sizeof(struct inflate_state)); window = Z_NULL; if (state->window != Z_NULL) { window = (unsigned char FAR *)ZALLOC( @@ -1493,6 +1520,7 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) { sizeof(unsigned char)); if (window == Z_NULL) { ZFREE(source, copy); + dest->state = Z_NULL; return Z_MEM_ERROR; } } @@ -1540,6 +1568,10 @@ int ZEXPORT inflateValidate(z_streamp strm, int check) { state->wrap |= 4; else state->wrap &= ~4; + if (check && state->reqwrap) + state->reqwrap |= 4; + else + state->reqwrap &= ~4; return Z_OK; } diff --git a/deps/zlib/contrib/tests/utils_unittest.cc b/deps/zlib/contrib/tests/utils_unittest.cc index 148cc7c66558..a9a40a755b6d 100644 --- a/deps/zlib/contrib/tests/utils_unittest.cc +++ b/deps/zlib/contrib/tests/utils_unittest.cc @@ -1438,7 +1438,15 @@ TEST(ZlibTest, ZipUnicodePathExtraSizeFilenameOverflow) { base::FilePath zip_file = TestDataDir().AppendASCII("unicode_path_extra_overflow.zip"); unzFile uzf = unzOpen(zip_file.AsUTF8Unsafe().c_str()); ASSERT_NE(uzf, nullptr); - EXPECT_EQ(unzGoToFirstFile(uzf), UNZ_ERRNO); + + char name[100]; + unz_file_info file_info; + ASSERT_EQ(unzGoToFirstFile(uzf), UNZ_OK); + // The bad Unicode Path Extra Field should be ignored, and we get the regular + // filename. + ASSERT_EQ(unzGetCurrentFileInfo(uzf, &file_info, name, sizeof(name), nullptr, + 0, nullptr, 0), UNZ_OK); + ASSERT_EQ(std::string(name), "\xc8\xfe \xc8\xfe\xc8\xfe.txt"); EXPECT_EQ(unzClose(uzf), UNZ_OK); } @@ -1482,6 +1490,34 @@ TEST(ZlibTest, ZipUnicodePathExtra) { EXPECT_EQ(unzClose(uzf), UNZ_OK); } +TEST(ZlibTest, ShortZipUnicodePathExtra) { + base::FilePath zip_file = TestDataDir().AppendASCII("short_unicode_path_extra.zip"); + unzFile uzf = unzOpen(zip_file.AsUTF8Unsafe().c_str()); + ASSERT_NE(uzf, nullptr); + + char name[100]; + unz_file_info file_info; + + ASSERT_EQ(unzGoToFirstFile(uzf), UNZ_OK); + ASSERT_EQ(unzGetCurrentFileInfo(uzf, &file_info, name, sizeof(name), nullptr, + 0, nullptr, 0), UNZ_OK); + ASSERT_EQ(std::string(name), "receipt.txt"); + + // The "decoy.dat" entry has an invalid (too short) Unicode Path Extra Field. + // Ignore the extra field rather than erroring out. + ASSERT_EQ(unzGoToNextFile(uzf), UNZ_OK); + ASSERT_EQ(unzGetCurrentFileInfo(uzf, &file_info, name, sizeof(name), nullptr, + 0, nullptr, 0), UNZ_OK); + ASSERT_EQ(std::string(name), "decoy.dat"); + + ASSERT_EQ(unzGoToNextFile(uzf), UNZ_OK); + ASSERT_EQ(unzGetCurrentFileInfo(uzf, &file_info, name, sizeof(name), nullptr, + 0, nullptr, 0), UNZ_OK); + ASSERT_EQ(std::string(name), "malware.exe"); + + EXPECT_EQ(unzClose(uzf), UNZ_OK); +} + TEST(ZlibTest, ZipEncryptionFlagMismatch) { // Test archive created with info-zip: // $ echo -n a > a && zip -P a -k a.zip a diff --git a/deps/zlib/crc32.c b/deps/zlib/crc32.c index 2ec5ab5cebef..97738d9f154c 100644 --- a/deps/zlib/crc32.c +++ b/deps/zlib/crc32.c @@ -757,7 +757,7 @@ uLong ZEXPORT crc32_z(uLong crc, const unsigned char FAR *buf, z_size_t len) { #endif /* Initialize the CRC for each braid. */ - crc0 = crc; + crc0 = (z_crc_t)crc; #if N > 1 crc1 = 0; #if N > 2 diff --git a/deps/zlib/deflate.c b/deps/zlib/deflate.c index b98a985e5cac..8b8f0ed3400f 100644 --- a/deps/zlib/deflate.c +++ b/deps/zlib/deflate.c @@ -71,7 +71,7 @@ #endif const char deflate_copyright[] = - " deflate 1.3.2.1 Copyright 1995-2026 Jean-loup Gailly and Mark Adler "; + " deflate 1.4 Copyright 1995-2026 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -475,7 +475,6 @@ int ZEXPORT deflateInit2_(z_streamp strm, int level, int method, s->status = INIT_STATE; /* to pass state test in deflateReset() */ s->wrap = wrap; - s->gzhead = Z_NULL; s->w_bits = (uInt)windowBits; s->w_size = 1 << s->w_bits; s->w_mask = s->w_size - 1; @@ -626,7 +625,8 @@ int ZEXPORT deflateSetDictionary(z_streamp strm, const Bytef *dictionary, return Z_STREAM_ERROR; s = strm->state; wrap = s->wrap; - if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead || + (wrap == 0 && (long)s->strstart != s->block_start)) return Z_STREAM_ERROR; /* when using zlib wrappers, compute Adler-32 for provided dictionary */ @@ -725,7 +725,20 @@ int ZEXPORT deflateResetKeep(z_streamp strm) { adler32(0L, Z_NULL, 0); s->last_flush = -2; - _tr_init(s); + s->gzhead = Z_NULL; + + { + /* Retain the hash work done for level 0. */ + uInt matches = s->level == 0 ? s->matches : 0; + _tr_init(s); + s->matches = matches; + } + + /* Keep the window and the hash, but drop what was left unfinished */ + s->block_start = (long)s->strstart; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; return Z_OK; } @@ -737,6 +750,7 @@ local void lm_init(deflate_state *s) { s->window_size = (ulg)2L*s->w_size; CLEAR_HASH(s); + s->matches = 0; /* the hash is clear */ /* Set the default configuration parameters: */ @@ -799,18 +813,23 @@ int ZEXPORT deflateUsed(z_streamp strm, int *bits) { int ZEXPORT deflatePrime(z_streamp strm, int bits, int value) { deflate_state *s; int put; + int need; if (deflateStateCheck(strm)) return Z_STREAM_ERROR; s = strm->state; -#ifdef LIT_MEM - if (bits < 0 || bits > 16 || - (uchf *)s->d_buf < s->pending_out + ((Buf_size + 7) >> 3)) + if (bits < 0 || bits > 16) return Z_BUF_ERROR; -#else - if (bits < 0 || bits > 16 || - s->sym_buf < s->pending_out + ((Buf_size + 7) >> 3)) + if (s->pending_out != s->pending_buf) { + /* move partially flushed pending output to buffer start */ + Bytef *to = s->pending_buf, *from = s->pending_out; + ulg n = s->pending; + while (n--) + *to++ = *from++; + s->pending_out = s->pending_buf; + } + need = (s->bi_valid + bits) >> 3; + if (s->pending_buf_size - s->pending < (ulg)need) return Z_BUF_ERROR; -#endif do { put = Buf_size - s->bi_valid; if (put > bits) @@ -1395,46 +1414,50 @@ int ZEXPORT deflateEnd(z_streamp strm) { */ int ZEXPORT deflateCopy(z_streamp dest, z_streamp source) { #ifdef MAXSEG_64K - (void)dest; (void)source; + if (dest != Z_NULL) + dest->state = Z_NULL; return Z_STREAM_ERROR; #else deflate_state *ds; deflate_state *ss; - - if (deflateStateCheck(source) || dest == Z_NULL) { + if (dest == Z_NULL) + return Z_STREAM_ERROR; + if (deflateStateCheck(source)) { + dest->state = Z_NULL; return Z_STREAM_ERROR; } ss = source->state; - zmemcpy(dest, source, sizeof(z_stream)); - - ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); - if (ds == Z_NULL) return Z_MEM_ERROR; - zmemzero(ds, sizeof(deflate_state)); - dest->state = (struct internal_state FAR *) ds; + ds = (deflate_state *) ZALLOC(source, 1, sizeof(deflate_state)); + if (ds == Z_NULL) { + dest->state = Z_NULL; + return Z_MEM_ERROR; + } zmemcpy(ds, ss, sizeof(deflate_state)); - ds->strm = dest; - - ds->window = (Bytef *) ZALLOC(dest, - ds->w_size + WINDOW_PADDING, - 2*sizeof(Byte)); - ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); - ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); -#ifdef LIT_MEM - ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 5); -#else - ds->pending_buf = (uchf *) ZALLOC(dest, ds->lit_bufsize, 4); -#endif - + ds->window = (Bytef *) ZALLOC(source, ds->w_size + WINDOW_PADDING, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(source, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(source, ds->hash_size, sizeof(Pos)); + ds->pending_buf = (uchf *) ZALLOC(source, ds->lit_bufsize, LIT_BUFS); if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || ds->pending_buf == Z_NULL) { - deflateEnd (dest); + TRY_FREE(source, ds->pending_buf); + TRY_FREE(source, ds->head); + TRY_FREE(source, ds->prev); + TRY_FREE(source, ds->window); + ZFREE(source, ds); + dest->state = Z_NULL; return Z_MEM_ERROR; } - /* following zmemcpy do not work for 16-bit MSDOS */ + + /* copy the stream and attach the new state */ + zmemcpy(dest, source, sizeof(z_stream)); + dest->state = (struct internal_state FAR *) ds; + ds->strm = dest; + + /* following zmemcpy's do not work for 16-bit MSDOS */ zmemcpy(ds->window, ss->window, ss->high_water); zmemcpy(ds->prev, ss->prev, (ss->slid || ss->strstart - ss->insert > ds->w_size ? ds->w_size : @@ -1766,7 +1789,10 @@ local void check_match(deflate_state *s, IPos start, IPos match, int length) { /* Same but force premature exit if necessary. */ #define FLUSH_BLOCK(s, last) { \ FLUSH_BLOCK_ONLY(s, last); \ - if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ + if (s->strm->avail_out == 0) { \ + if (!(last)) return need_more; \ + if (s->pending != 0 || s->wrap != 0) return finish_started; \ + } \ } /* Maximum stored block length in deflate format (not including header). */ @@ -1801,7 +1827,7 @@ local block_state deflate_stored(deflate_state *s, int flush) { * possible. If flushing, copy the remaining available input to next_out as * stored blocks, if there is enough space. */ - int last = 0; + int last = 0, all; unsigned len, left, have; unsigned used = s->strm->avail_in; do { @@ -1816,11 +1842,14 @@ local block_state deflate_stored(deflate_state *s, int flush) { /* maximum stored block length that will fit in avail_out: */ have = s->strm->avail_out - have; left = (unsigned)(s->strstart - s->block_start); /* window bytes */ - if (len > (ulg)left + s->strm->avail_in) + if (left < len && s->strm->avail_in < len - left) len = left + s->strm->avail_in; /* limit len to the input */ if (len > have) len = have; /* limit len to the output */ + /* all is true if len is all of the available input */ + all = len >= left && len - left == s->strm->avail_in; + /* If the stored block would be less than min_block in length, or if * unable to copy all of the available input when flushing, then try * copying to the window and the pending buffer instead. Also don't @@ -1828,13 +1857,13 @@ local block_state deflate_stored(deflate_state *s, int flush) { */ if (len < min_block && ((len == 0 && flush != Z_FINISH) || flush == Z_NO_FLUSH || - len != left + s->strm->avail_in)) + !all)) break; /* Make a dummy stored block in pending to get the header bytes, * including any pending bits. This also updates the debugging counts. */ - last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0; + last = flush == Z_FINISH && all ? 1 : 0; _tr_stored_block(s, (char *)0, 0L, last); /* Replace the lengths in the dummy stored block with len. */ @@ -2178,7 +2207,8 @@ local block_state deflate_slow(deflate_state *s, int flush) { uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ - check_match(s, s->strstart - 1, s->prev_match, (int)s->prev_length); + check_match(s, s->strstart - 1, s->prev_match, + (int)s->prev_length); _tr_tally_dist(s, s->strstart - 1 - s->prev_match, s->prev_length - MIN_MATCH, bflush); diff --git a/deps/zlib/deflate.h b/deps/zlib/deflate.h index c55fd8f6a07b..6cec2f315d75 100644 --- a/deps/zlib/deflate.h +++ b/deps/zlib/deflate.h @@ -230,9 +230,11 @@ typedef struct internal_state { */ #ifdef LIT_MEM +# define LIT_BUFS 5 ushf *d_buf; /* buffer for distances */ uchf *l_buf; /* buffer for literals/lengths */ #else +# define LIT_BUFS 4 uchf *sym_buf; /* buffer for distances and literals/lengths */ #endif diff --git a/deps/zlib/google/test/data/short_unicode_path_extra.zip b/deps/zlib/google/test/data/short_unicode_path_extra.zip new file mode 100644 index 000000000000..f2ca0ffbb683 Binary files /dev/null and b/deps/zlib/google/test/data/short_unicode_path_extra.zip differ diff --git a/deps/zlib/google/test_data.filelist b/deps/zlib/google/test_data.filelist index 9761df114797..0e59c5144a9e 100644 --- a/deps/zlib/google/test_data.filelist +++ b/deps/zlib/google/test_data.filelist @@ -23,6 +23,7 @@ test/data/enc_flag_mismatch.zip test/data/evil.zip test/data/evil_via_absolute_file_name.zip test/data/evil_via_invalid_utf8.zip +test/data/short_unicode_path_extra.zip test/data/symlink_absolute_path.zip test/data/symlink_duplicate_link.zip test/data/symlink_evil_relative_path.zip diff --git a/deps/zlib/gzguts.h b/deps/zlib/gzguts.h index f7946bdc514f..df4b0d6707e7 100644 --- a/deps/zlib/gzguts.h +++ b/deps/zlib/gzguts.h @@ -92,8 +92,10 @@ # define vsnprintf _vsnprintf # endif # endif -# elif !defined(__STDC_VERSION__) || __STDC_VERSION__-0 < 199901L -/* Otherwise if C89/90, assume no C99 snprintf() or vsnprintf() */ +# elif (!defined(__STDC_VERSION__) || __STDC_VERSION__-0 < 199901L) && \ + (!defined(__cplusplus) || __cplusplus < 201103L) +/* Otherwise if C89/90 (and not C++11 or later), assume no C99 snprintf() or + vsnprintf() */ # ifndef NO_snprintf # define NO_snprintf # endif @@ -128,17 +130,26 @@ # include <windows.h> # define zstrerror() gz_strwinerror((DWORD)GetLastError()) #else +# include <errno.h> # ifndef NO_STRERROR -# include <errno.h> # define zstrerror() strerror(errno) # else # define zstrerror() "stdio error (consult errno)" # endif #endif -/* some environments don't define EWOULDBLOCK */ -#ifndef EWOULDBLOCK -# define EWOULDBLOCK EAGAIN +#ifdef EAGAIN +# ifdef EWOULDBLOCK +# define BLOCKED(e) ((e) == EAGAIN || (e) == EWOULDBLOCK) +# else +# define BLOCKED(e) ((e) == EAGAIN) +# endif +#else +# ifdef EWOULDBLOCK +# define BLOCKED(e) ((e) == EWOULDBLOCK) +# else +# define BLOCKED(e) (0) +# endif #endif /* provide prototypes for these when building zlib without LFS */ @@ -219,3 +230,10 @@ char ZLIB_INTERNAL *gz_strwinerror(DWORD error); (possible z_off64_t types off_t, off64_t, and long are all signed) */ unsigned ZLIB_INTERNAL gz_intmax(void); #define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax()) + +/* largest value representable in z_off64_t */ +#ifndef CHAR_BIT +# define CHAR_BIT 8 +#endif +#define GZ_OFF_MAX \ + ((((z_off64_t)1 << (sizeof(z_off64_t) * CHAR_BIT - 2)) - 1) * 2 + 1) diff --git a/deps/zlib/gzlib.c b/deps/zlib/gzlib.c index 2db29c8f0760..ff8aebd4244e 100644 --- a/deps/zlib/gzlib.c +++ b/deps/zlib/gzlib.c @@ -71,9 +71,9 @@ char ZLIB_INTERNAL *gz_strwinerror(DWORD error) { /* Reset gzip file state */ local void gz_reset(gz_statep state) { state->x.have = 0; /* no output data available */ + state->past = 0; /* have not read past end yet */ if (state->mode == GZ_READ) { /* for reading ... */ state->eof = 0; /* not at end of file */ - state->past = 0; /* have not read past end yet */ state->how = LOOK; /* look for gzip header */ state->junk = -1; /* mark first member */ } @@ -91,9 +91,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) { gz_statep state; z_size_t len; int oflag = 0; -#ifdef O_EXCL int exclusive = 0; -#endif /* check input */ if (path == NULL || mode == NULL) @@ -139,11 +137,9 @@ local gzFile gz_open(const void *path, int fd, const char *mode) { oflag |= O_CLOEXEC; break; #endif -#ifdef O_EXCL case 'x': exclusive = 1; break; -#endif case 'f': state->strategy = Z_FILTERED; break; @@ -199,10 +195,21 @@ local gzFile gz_open(const void *path, int fd, const char *mode) { /* if reading, direct == 1 for auto-detect, -1 for gzip only; if writing or appending, direct == 0 for gzip, 1 for transparent (copy in to out) */ +#ifndef O_EXCL + if (exclusive && state->mode != GZ_READ && fd < 0) { + /* exclusive creation request can't be honored -- fail out */ + free(state); + return NULL; + } +#endif + /* save the path name for error messages */ #ifdef WIDECHAR - if (fd == -2) + if (fd == -2) { len = wcstombs(NULL, path, 0); + if (len == (z_size_t)-1) + len = 0; /* not representable in the current locale */ + } else #endif len = strlen((const char *)path); @@ -213,9 +220,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) { } #ifdef WIDECHAR if (fd == -2) { - if (len) - wcstombs(state->path, path, len + 1); - else + if (len == 0 || wcstombs(state->path, path, len + 1) != len) *(state->path) = 0; } else @@ -224,7 +229,7 @@ local gzFile gz_open(const void *path, int fd, const char *mode) { #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(state->path, len + 1, "%s", (const char *)path); #else - strcpy(state->path, path); + strcpy(state->path, (const char *)path); #endif } @@ -258,9 +263,9 @@ local gzFile gz_open(const void *path, int fd, const char *mode) { if (oflag & O_NONBLOCK) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK); #endif -#ifdef O_CLOEXEC +#if defined(O_CLOEXEC) && defined(FD_CLOEXEC) if (oflag & O_CLOEXEC) - fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | O_CLOEXEC); + fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); #endif state->fd = fd; } @@ -302,7 +307,7 @@ gzFile ZEXPORT gzdopen(int fd, const char *mode) { char *path; /* identifier for error messages */ gzFile gz; - if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) + if (fd < 0 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL) return NULL; #if !defined(NO_snprintf) && !defined(NO_vsnprintf) (void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); @@ -369,7 +374,7 @@ int ZEXPORT gzrewind(gzFile file) { /* -- see zlib.h -- */ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) { unsigned n; - z_off64_t ret; + z_off64_t ret, pos; gz_statep state; /* get internal structure and check integrity */ @@ -387,18 +392,19 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) { if (whence != SEEK_SET && whence != SEEK_CUR) return -1; - /* normalize offset to a SEEK_CUR specification */ - if (whence == SEEK_SET) - offset -= state->x.pos; - else { - offset += state->past ? 0 : state->skip; - state->skip = 0; - } + /* compute the absolute position */ + pos = whence == SEEK_SET ? 0 : + state->x.pos + (state->past ? 0 : state->skip); + if (offset > GZ_OFF_MAX - pos) + return -1; /* would overflow z_off64_t */ + if (offset < -pos) + return -1; /* before start of file */ + pos += offset; /* if within raw area while reading, just go there */ - if (state->mode == GZ_READ && state->how == COPY && - state->x.pos + offset >= 0) { - ret = LSEEK(state->fd, offset - (z_off64_t)state->x.have, SEEK_CUR); + if (state->mode == GZ_READ && state->how == COPY) { + ret = LSEEK(state->fd, pos - state->x.pos - (z_off64_t)state->x.have, + SEEK_CUR); if (ret == -1) return -1; state->x.have = 0; @@ -407,20 +413,18 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) { state->skip = 0; gz_error(state, Z_OK, NULL); state->strm.avail_in = 0; - state->x.pos += offset; - return state->x.pos; + state->x.pos = pos; + return pos; } - /* calculate skip amount, rewinding if needed for back seek when reading */ - if (offset < 0) { + /* rewind if needed for back seek when reading */ + if (pos < state->x.pos) { if (state->mode != GZ_READ) /* writing -- can't go backwards */ return -1; - offset += state->x.pos; - if (offset < 0) /* before start of file! */ - return -1; - if (gzrewind(file) == -1) /* rewind, then skip to offset */ + if (gzrewind(file) == -1) /* rewind, then skip to pos */ return -1; } + offset = pos - state->x.pos; /* if reading, skip what's in output buffer (one less gzgetc() check) */ if (state->mode == GZ_READ) { @@ -434,7 +438,7 @@ z_off64_t ZEXPORT gzseek64(gzFile file, z_off64_t offset, int whence) { /* request skip (if not zero) */ state->skip = offset; - return state->x.pos + offset; + return pos; } /* -- see zlib.h -- */ @@ -563,10 +567,6 @@ void ZLIB_INTERNAL gz_error(gz_statep state, int err, const char *msg) { state->msg = NULL; } - /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */ - if (err != Z_OK && err != Z_BUF_ERROR && !state->again) - state->x.have = 0; - /* set error code, and if no message, then done */ state->err = err; if (msg == NULL) diff --git a/deps/zlib/gzread.c b/deps/zlib/gzread.c index bf41d63bc615..ec57af65905d 100644 --- a/deps/zlib/gzread.c +++ b/deps/zlib/gzread.c @@ -33,7 +33,7 @@ local int gz_load(gz_statep state, unsigned char *buf, unsigned len, *have += (unsigned)ret; } while (*have < len); if (ret < 0) { - if (errno == EAGAIN || errno == EWOULDBLOCK) { + if (BLOCKED(errno)) { state->again = 1; if (*have != 0) return 0; @@ -125,6 +125,13 @@ local int gz_look(gz_statep state) { if we're looking for a gzip member after the first one, which is not at the start, then proceed directly to look for a gzip member next */ if (state->direct == -1 || state->junk == 0) { + /* wait for input before committing to another gzip member */ + if (state->junk == 0 && strm->avail_in == 0) { + if (gz_avail(state) == -1) + return -1; + if (strm->avail_in == 0) + return 0; + } inflateReset(strm); state->how = GZIP; state->junk = state->junk != -1; @@ -153,7 +160,7 @@ local int gz_look(gz_statep state) { strm->next_in[2] == 8 && strm->next_in[3] < 32) { inflateReset(strm); state->how = GZIP; - state->junk = 1; + state->junk = 0; state->direct = 0; return 0; } @@ -248,6 +255,11 @@ local int gz_decomp(gz_statep state) { local int gz_fetch(gz_statep state) { z_streamp strm = &(state->strm); + /* after a serious error, only what is already in the output buffer is + delivered -- don't try to decompress any more */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again) + return -1; + do { switch(state->how) { case LOOK: /* -> LOOK, COPY (only if never GZIP), or GZIP */ @@ -276,32 +288,46 @@ local int gz_fetch(gz_statep state) { return 0; } +/* Apply as much of a pending skip request as the output already available in + state->x allows. */ +local void gz_skip_have(gz_statep state) { + unsigned n; + + n = GT_OFF(state->x.have) || + (z_off64_t)state->x.have > state->skip ? + (unsigned)state->skip : state->x.have; + state->x.have -= n; + state->x.next += n; + state->x.pos += n; + state->skip -= n; +} + /* Skip state->skip (> 0) uncompressed bytes of output. Return -1 on error, 0 on success. */ local int gz_skip(gz_statep state) { - unsigned n; - /* skip over len bytes or reach end-of-file, whichever comes first */ do { /* skip over whatever is in output buffer */ - if (state->x.have) { - n = GT_OFF(state->x.have) || - (z_off64_t)state->x.have > state->skip ? - (unsigned)state->skip : state->x.have; - state->x.have -= n; - state->x.next += n; - state->x.pos += n; - state->skip -= n; - } + if (state->x.have) + gz_skip_have(state); /* output buffer empty -- return if we're at the end of the input */ - else if (state->eof && state->strm.avail_in == 0) + else if (state->eof && state->strm.avail_in == 0) { + if (state->how == GZIP && state->err == Z_OK) + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); + state->skip = 0; + state->past = 1; break; + } /* need more data to skip -- load up output buffer */ else { - /* get more output, looking for header if required */ - if (gz_fetch(state) == -1) + /* get more output, looking for header if required. If the fetch + stalled but provided some output, consume it before returning + so that x.have > 0 always implies the data is at the current + logical position (x.pos), as assumed by the gzgetc() fast path + in zlib.h and gzread.c */ + if (gz_fetch(state) == -1 && state->x.have == 0) return -1; } } while (state->skip); @@ -349,8 +375,11 @@ local z_size_t gz_read(gz_statep state, voidp buf, z_size_t len) { } /* output buffer empty -- return if we're at the end of the input */ - else if (state->eof && state->strm.avail_in == 0) + else if (state->eof && state->strm.avail_in == 0) { + if (state->how == GZIP && state->err == Z_OK) + gz_error(state, Z_BUF_ERROR, "unexpected end of file"); break; + } /* need output data -- for small len or new stream load up our output buffer, so that gzgetc() can be fast */ @@ -403,15 +432,21 @@ int ZEXPORT gzread(gzFile file, voidp buf, unsigned len) { if (state->mode != GZ_READ) return -1; - /* check that there was no (serious) error */ - if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again) + /* check that there was no (serious) error -- if there was, deliver any + data read before the error until it is exhausted, and only then return + the error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again && + state->x.have == 0) return -1; - gz_error(state, Z_OK, NULL); + if (state->again) + gz_error(state, Z_OK, NULL); /* since an int is returned, make sure len fits in one, otherwise return - with an error (this avoids a flaw in the interface) */ + with an error (this avoids a flaw in the interface) -- keep a pending + serious error, which is the one the caller needs to see */ if ((int)len < 0) { - gz_error(state, Z_STREAM_ERROR, "request does not fit in an int"); + if (state->err == Z_OK || state->err == Z_BUF_ERROR) + gz_error(state, Z_STREAM_ERROR, "request does not fit in an int"); return -1; } @@ -448,15 +483,22 @@ z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, if (state->mode != GZ_READ) return 0; - /* check that there was no (serious) error */ - if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again) + /* check that there was no (serious) error -- if there was, deliver any + data read before the error until it is exhausted, and only then return + the error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again && + state->x.have == 0) return 0; - gz_error(state, Z_OK, NULL); + if (state->again) + gz_error(state, Z_OK, NULL); - /* compute bytes to read -- error on overflow */ + /* compute bytes to read -- error on overflow, keeping a pending serious + error, which is the one the caller needs to see */ len = nitems * size; if (size && len / size != nitems) { - gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); + if (state->err == Z_OK || state->err == Z_BUF_ERROR) + gz_error(state, Z_STREAM_ERROR, + "request does not fit in a size_t"); return 0; } @@ -485,10 +527,14 @@ int ZEXPORT gzgetc(gzFile file) { if (state->mode != GZ_READ) return -1; - /* check that there was no (serious) error */ - if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again) + /* check that there was no (serious) error -- if there was, deliver any + data read before the error until it is exhausted, and only then return + the error, as the gzgetc() macro does */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again && + state->x.have == 0) return -1; - gz_error(state, Z_OK, NULL); + if (state->again) + gz_error(state, Z_OK, NULL); /* try output buffer (no need to check for skip request) */ if (state->x.have) { @@ -520,10 +566,15 @@ int ZEXPORT gzungetc(int c, gzFile file) { if (state->how == LOOK && state->x.have == 0) (void)gz_look(state); - /* check that there was no (serious) error */ - if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again) + /* check that there was no (serious) error -- a character can still be + pushed back after one, since it is data that was read before the + error, and it will be returned before the error is signaled -- but only + if there is an output buffer to put it in */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again && + state->size == 0) return -1; - gz_error(state, Z_OK, NULL); + if (state->again) + gz_error(state, Z_OK, NULL); /* process a skip request */ if (state->skip && gz_skip(state) == -1) @@ -545,7 +596,8 @@ int ZEXPORT gzungetc(int c, gzFile file) { /* if no room, give up (must have already done a gzungetc()) */ if (state->x.have == (state->size << 1)) { - gz_error(state, Z_DATA_ERROR, "out of room to push characters"); + if (state->err == Z_OK || state->err == Z_BUF_ERROR) + gz_error(state, Z_DATA_ERROR, "out of room to push characters"); return -1; } @@ -581,10 +633,14 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) { if (state->mode != GZ_READ) return NULL; - /* check that there was no (serious) error */ - if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again) + /* check that there was no (serious) error -- if there was, deliver any + data read before the error until it is exhausted, and only then return + the error */ + if (state->err != Z_OK && state->err != Z_BUF_ERROR && !state->again && + state->x.have == 0) return NULL; - gz_error(state, Z_OK, NULL); + if (state->again) + gz_error(state, Z_OK, NULL); /* process a skip request */ if (state->skip && gz_skip(state) == -1) @@ -596,8 +652,9 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) { left = (unsigned)len - 1; if (left) do { /* assure that something is in the output buffer */ - if (state->x.have == 0 && gz_fetch(state) == -1) - break; /* error */ + if (state->x.have == 0 && gz_fetch(state) == -1 && + state->x.have == 0) + break; /* error, and nothing left to return */ if (state->x.have == 0) { /* end of file */ state->past = 1; /* read past end */ break; /* return what we have */ @@ -621,7 +678,7 @@ char * ZEXPORT gzgets(gzFile file, char *buf, int len) { /* append a terminating zero to the string (we don't check for a zero in the contents, let the user worry about that) -- return the terminated string, or if nothing was read, NULL */ - if (buf == str) + if (buf == str && len > 1) return NULL; buf[0] = 0; return str; @@ -638,8 +695,10 @@ int ZEXPORT gzdirect(gzFile file) { /* if the state is not known, but we can find out, then do so (this is mainly for right after a gzopen() or gzdopen()) */ - if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) + if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0) { (void)gz_look(state); + gz_skip_have(state); /* apply skip to current buffer */ + } /* return 1 if transparent, 0 if processing a gzip stream */ return state->direct == 1; diff --git a/deps/zlib/gzwrite.c b/deps/zlib/gzwrite.c index 13a3700a83c7..32560fe0b026 100644 --- a/deps/zlib/gzwrite.c +++ b/deps/zlib/gzwrite.c @@ -41,8 +41,8 @@ local int gz_init(gz_statep state) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } - strm->next_in = NULL; } + strm->next_in = NULL; /* mark state as initialized */ state->size = state->want; @@ -79,7 +79,7 @@ local int gz_comp(gz_statep state, int flush) { put = strm->avail_in > max ? max : strm->avail_in; writ = (int)write(state->fd, strm->next_in, put); if (writ < 0) { - if (errno == EAGAIN || errno == EWOULDBLOCK) + if (BLOCKED(errno)) state->again = 1; gz_error(state, Z_ERRNO, zstrerror()); return -1; @@ -114,7 +114,7 @@ local int gz_comp(gz_statep state, int flush) { (unsigned)(strm->next_out - state->x.next); writ = (int)write(state->fd, state->x.next, put); if (writ < 0) { - if (errno == EAGAIN || errno == EWOULDBLOCK) + if (BLOCKED(errno)) state->again = 1; gz_error(state, Z_ERRNO, zstrerror()); return -1; @@ -156,6 +156,11 @@ local int gz_zero(gz_statep state) { unsigned n; z_streamp strm = &(state->strm); + /* allocate memory if this is the first time through -- the input buffer + must exist before it is zeroed below */ + if (state->size == 0 && gz_init(state) == -1) + return -1; + /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return -1; @@ -175,8 +180,14 @@ local int gz_zero(gz_statep state) { n -= strm->avail_in; state->x.pos += n; state->skip -= n; - if (ret == -1) + if (ret == -1) { + /* discard any unconsumed zero fill -- it was not yet accounted + for in state->skip, so it will be generated again when the + operation is retried */ + strm->avail_in = 0; + strm->next_in = state->in; return -1; + } } while (state->skip); return 0; } @@ -242,9 +253,13 @@ local z_size_t gz_write(gz_statep state, voidpc buf, z_size_t len) { n -= state->strm.avail_in; state->x.pos += n; len -= n; - if (ret == -1) + if (ret == -1) { + state->strm.avail_in = 0; + state->strm.next_in = state->in; return state->again ? put - len : 0; + } } while (len); + state->strm.next_in = state->in; } /* input was all buffered or compressed */ @@ -371,9 +386,10 @@ int ZEXPORT gzputs(gzFile file, const char *s) { return len && put == 0 ? -1 : (int)put; } -#if (((!defined(STDC) && !defined(Z_HAVE_STDARG_H)) || !defined(NO_vsnprintf)) && \ - (defined(STDC) || defined(Z_HAVE_STDARG_H) || !defined(NO_snprintf))) || \ - defined(ZLIB_INSECURE) +#if (((!defined(STDC) && !defined(Z_HAVE_STDARG_H)) || \ + !defined(NO_vsnprintf)) && \ + (defined(STDC) || defined(Z_HAVE_STDARG_H) || \ + !defined(NO_snprintf))) || defined(ZLIB_INSECURE) /* If the second half of the input buffer is occupied, write out the contents. If there is any input remaining due to a non-blocking stall on write, move it to the start of the buffer. Return true if this did not open up the @@ -383,7 +399,8 @@ local int gz_vacate(gz_statep state) { z_streamp strm; strm = &(state->strm); - if (strm->next_in + strm->avail_in <= state->in + state->size) + if (strm->next_in == NULL || + strm->next_in + strm->avail_in <= state->in + state->size) return 0; (void)gz_comp(state, Z_NO_FLUSH); if (strm->avail_in == 0) { @@ -443,6 +460,7 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) { a Z_BUF_ERROR to let the application know that this gzprintf() needs to be retried. */ gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf"); + return state->err; } if (!state->again) return state->err; @@ -478,6 +496,14 @@ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) { /* write out buffer if more than half is occupied */ ret = gz_vacate(state); + if (ret) { + /* discard unwritten formatted output */ + strm->avail_in -= (unsigned)len; + state->x.pos -= len; + if (state->again) + gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf"); + return state->err; + } if (state->err && !state->again) return state->err; return len; @@ -551,6 +577,7 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3, a Z_BUF_ERROR to let the application know that this gzprintf() needs to be retried. */ gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf"); + return state->err; } if (!state->again) return state->err; @@ -591,6 +618,14 @@ int ZEXPORTVA gzprintf(gzFile file, const char *format, int a1, int a2, int a3, /* write out buffer if more than half is occupied */ ret = gz_vacate(state); + if (ret) { + /* discard unwritten formatted output */ + strm->avail_in -= (unsigned)len; + state->x.pos -= len; + if (state->again) + gz_error(state, Z_BUF_ERROR, "stalled write on gzprintf"); + return state->err; + } if (state->err && !state->again) return state->err; return (int)len; diff --git a/deps/zlib/inflate.c b/deps/zlib/inflate.c index 0742ce10ed94..1f51dbbbe89f 100644 --- a/deps/zlib/inflate.c +++ b/deps/zlib/inflate.c @@ -127,6 +127,14 @@ int ZEXPORT inflateReset(z_streamp strm) { if (inflateStateCheck(strm)) return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; + if (state->wbits != state->reqbits) { + if (state->window != Z_NULL) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + state->wbits = state->reqbits; + } + state->wrap = state->reqwrap; state->wsize = 0; state->whave = 0; state->wnext = 0; @@ -165,8 +173,8 @@ int ZEXPORT inflateReset2(z_streamp strm, int windowBits) { } /* update state and reset the rest of it */ - state->wrap = wrap; - state->wbits = (unsigned)windowBits; + state->reqwrap = state->wrap = wrap; + state->reqbits = state->wbits = (unsigned)windowBits; return inflateReset(strm); } @@ -538,13 +546,13 @@ int ZEXPORT inflate(z_streamp strm, int flush) { } DROPBITS(4); len = BITS(4) + 8; - if (state->wbits == 0) - state->wbits = len; - if (len > 15 || len > state->wbits) { + if (len > 15 || (state->wbits != 0 && len > state->wbits)) { strm->msg = (z_const char *)"invalid window size"; state->mode = BAD; break; } + if (state->wbits == 0) + state->wbits = len; state->dmax = 1U << len; state->flags = 0; /* indicate zlib header */ Tracev((stderr, "inflate: zlib header ok\n")); @@ -701,6 +709,7 @@ int ZEXPORT inflate(z_streamp strm, int flush) { case DICT: if (state->havedict == 0) { RESTORE(); + strm->total_in += in - strm->avail_in; return Z_NEED_DICT; } strm->adler = state->check = adler32(0L, Z_NULL, 0); @@ -914,7 +923,8 @@ int ZEXPORT inflate(z_streamp strm, int flush) { /* fallthrough */ case LEN: if (have >= INFLATE_FAST_MIN_INPUT && - left >= INFLATE_FAST_MIN_OUTPUT) { + left >= INFLATE_FAST_MIN_OUTPUT && + bits < 8) { RESTORE(); inflate_fast(strm, out); LOAD(); @@ -1193,7 +1203,8 @@ int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary, int ret; /* check state */ - if (inflateStateCheck(strm)) return Z_STREAM_ERROR; + if (inflateStateCheck(strm) || dictionary == Z_NULL) + return Z_STREAM_ERROR; state = (struct inflate_state FAR *)strm->state; if (state->wrap != 0 && state->mode != DICT) return Z_STREAM_ERROR; @@ -1298,15 +1309,23 @@ int ZEXPORT inflateSync(z_streamp strm) { /* return no joy or set up to restart inflate() on a new block */ if (state->have != 4) return Z_DATA_ERROR; - if (state->flags == -1) - state->wrap = 0; /* if no header yet, treat as raw */ - else - state->wrap &= ~4; /* no point in computing a check value now */ flags = state->flags; in = strm->total_in; out = strm->total_out; inflateReset(strm); strm->total_in = in; strm->total_out = out; state->flags = flags; + if (flags == -1) + state->wrap = 0; /* if no header yet, treat as raw */ + else + state->wrap &= ~4; /* no point in computing a check value now */ + if (state->wbits == 0) { + /* we never got to see a header for the window size -- set to max */ + if (state->window != Z_NULL) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + state->wbits = 15; + } state->mode = TYPE; return Z_OK; } @@ -1333,14 +1352,21 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) { unsigned char FAR *window; /* check input */ - if (inflateStateCheck(source) || dest == Z_NULL) + if (dest == Z_NULL) return Z_STREAM_ERROR; + if (inflateStateCheck(source)) { + dest->state = Z_NULL; + return Z_STREAM_ERROR; + } state = (struct inflate_state FAR *)source->state; /* allocate space */ copy = (struct inflate_state FAR *) ZALLOC(source, 1, sizeof(struct inflate_state)); - if (copy == Z_NULL) return Z_MEM_ERROR; + if (copy == Z_NULL) { + dest->state = Z_NULL; + return Z_MEM_ERROR; + } zmemzero(copy, sizeof(struct inflate_state)); window = Z_NULL; if (state->window != Z_NULL) { @@ -1348,6 +1374,7 @@ int ZEXPORT inflateCopy(z_streamp dest, z_streamp source) { ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); if (window == Z_NULL) { ZFREE(source, copy); + dest->state = Z_NULL; return Z_MEM_ERROR; } } @@ -1393,6 +1420,10 @@ int ZEXPORT inflateValidate(z_streamp strm, int check) { state->wrap |= 4; else state->wrap &= ~4; + if (check && state->reqwrap) + state->reqwrap |= 4; + else + state->reqwrap &= ~4; return Z_OK; } diff --git a/deps/zlib/inflate.h b/deps/zlib/inflate.h index f758e0dcc18d..e7dfc8e62b55 100644 --- a/deps/zlib/inflate.h +++ b/deps/zlib/inflate.h @@ -85,6 +85,7 @@ struct inflate_state { int last; /* true if processing last block */ int wrap; /* bit 0 true for zlib, bit 1 true for gzip, bit 2 true to validate check value */ + int reqwrap; /* requested wrap */ int havedict; /* true if dictionary provided */ int flags; /* gzip header method and flags, 0 if zlib, or -1 if raw or no header yet */ @@ -93,7 +94,8 @@ struct inflate_state { unsigned long total; /* protected copy of output count */ gz_headerp head; /* where to save gzip header information */ /* sliding window */ - unsigned wbits; /* log base 2 of requested window size */ + unsigned reqbits; /* requested log base 2 of window size */ + unsigned wbits; /* current log base 2 of window size */ unsigned wsize; /* window size or zero if not using window */ unsigned whave; /* valid bytes in the window */ unsigned wnext; /* window write index */ diff --git a/deps/zlib/inftrees.c b/deps/zlib/inftrees.c index 99d8d7730750..0fb8570b0ae3 100644 --- a/deps/zlib/inftrees.c +++ b/deps/zlib/inftrees.c @@ -23,7 +23,7 @@ #define MAXBITS 15 const char inflate_copyright[] = - " inflate 1.3.2.1 Copyright 1995-2026 Mark Adler "; + " inflate 1.4 Copyright 1995-2026 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -71,7 +71,7 @@ int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const unsigned short lext[31] = { /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, - 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 68, 193}; + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 71, 77}; static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, diff --git a/deps/zlib/inftrees.h b/deps/zlib/inftrees.h index c572f49d555f..85b30df52fab 100644 --- a/deps/zlib/inftrees.h +++ b/deps/zlib/inftrees.h @@ -46,8 +46,14 @@ typedef struct { inflate_table() calls in inflate.c and infback.c. If the root table size is changed, then these maximum sizes would be need to be recalculated and updated. */ -#define ENOUGH_LENS 1332 -#define ENOUGH_DISTS 592 +#ifndef PKZIP_BUG_WORKAROUND +# define ENOUGH_LENS 1332 +# define ENOUGH_DISTS 592 +#else +/* That workaround permits 288 literal/length codes and 32 distance codes. */ +# define ENOUGH_LENS 1334 +# define ENOUGH_DISTS 594 +#endif #define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) /* Type of code to build for inflate_table() */ diff --git a/deps/zlib/patches/0000-build-minizip.patch b/deps/zlib/patches/0000-build-minizip.patch new file mode 100644 index 000000000000..828675b4ee18 --- /dev/null +++ b/deps/zlib/patches/0000-build-minizip.patch @@ -0,0 +1,39 @@ +diff --git a/contrib/minizip/ioapi.c b/contrib/minizip/ioapi.c +index 782d32469ae5d..a38881dca90a2 100644 +--- a/contrib/minizip/ioapi.c ++++ b/contrib/minizip/ioapi.c +@@ -14,7 +14,7 @@ + #define _CRT_SECURE_NO_WARNINGS + #endif + +-#if defined(__APPLE__) || defined(IOAPI_NO_64) || defined(__HAIKU__) || defined(MINIZIP_FOPEN_NO_64) || (defined(__ANDROID_API__) && __ANDROID_API__ < 24) ++#if defined(__APPLE__) || defined(__Fuchsia__) || defined(IOAPI_NO_64) || defined(__HAIKU__) || defined(MINIZIP_FOPEN_NO_64) || (defined(__ANDROID_API__) && __ANDROID_API__ < 24) + /* In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions */ + #define FOPEN_FUNC(filename, mode) fopen(filename, mode) + #define FTELLO_FUNC(stream) ftello(stream) +diff --git a/contrib/minizip/iowin32.c b/contrib/minizip/iowin32.c +index 08536e94b8a28..bbd7773e67146 100644 +--- a/contrib/minizip/iowin32.c ++++ b/contrib/minizip/iowin32.c +@@ -24,7 +24,12 @@ + #define INVALID_SET_FILE_POINTER ((DWORD)-1) + #endif + ++#ifdef _WIN32_WINNT ++#undef _WIN32_WINNT ++#define _WIN32_WINNT 0x601 ++#endif + ++#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 + /* see Include/shared/winapifamily.h in the Windows Kit */ + #if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) + +@@ -37,6 +42,7 @@ + #define IOWIN32_USING_WINRT_API 1 + #endif + #endif ++#endif + + typedef struct + { + diff --git a/deps/zlib/patches/0000-build.patch b/deps/zlib/patches/0000-build.patch index 0f2b83409bff..3e1264f5a3fe 100644 --- a/deps/zlib/patches/0000-build.patch +++ b/deps/zlib/patches/0000-build.patch @@ -1,41 +1,3 @@ -diff --git a/contrib/minizip/ioapi.c b/contrib/minizip/ioapi.c -index 782d32469ae5d..a38881dca90a2 100644 ---- a/contrib/minizip/ioapi.c -+++ b/contrib/minizip/ioapi.c -@@ -14,7 +14,7 @@ - #define _CRT_SECURE_NO_WARNINGS - #endif - --#if defined(__APPLE__) || defined(IOAPI_NO_64) || defined(__HAIKU__) || defined(MINIZIP_FOPEN_NO_64) || (defined(__ANDROID_API__) && __ANDROID_API__ < 24) -+#if defined(__APPLE__) || defined(__Fuchsia__) || defined(IOAPI_NO_64) || defined(__HAIKU__) || defined(MINIZIP_FOPEN_NO_64) || (defined(__ANDROID_API__) && __ANDROID_API__ < 24) - // In darwin and perhaps other BSD variants off_t is a 64 bit value, hence no need for specific 64 bit functions - #define FOPEN_FUNC(filename, mode) fopen(filename, mode) - #define FTELLO_FUNC(stream) ftello(stream) -diff --git a/contrib/minizip/iowin32.c b/contrib/minizip/iowin32.c -index 08536e94b8a28..bbd7773e67146 100644 ---- a/contrib/minizip/iowin32.c -+++ b/contrib/minizip/iowin32.c -@@ -24,7 +24,12 @@ - #define INVALID_SET_FILE_POINTER ((DWORD)-1) - #endif - -+#ifdef _WIN32_WINNT -+#undef _WIN32_WINNT -+#define _WIN32_WINNT 0x601 -+#endif - -+#if _WIN32_WINNT >= _WIN32_WINNT_WIN8 - /* see Include/shared/winapifamily.h in the Windows Kit */ - #if defined(WINAPI_FAMILY_PARTITION) && (!(defined(IOWIN32_USING_WINRT_API))) - -@@ -37,6 +42,7 @@ - #define IOWIN32_USING_WINRT_API 1 - #endif - #endif -+#endif - - typedef struct - { diff --git a/gzread.c b/gzread.c index 956b91ea7d9e..832d3ef98c59 100644 --- a/gzread.c diff --git a/deps/zlib/patches/0015-minizip-unzip-enable-decryption.patch b/deps/zlib/patches/0015-minizip-unzip-enable-decryption.patch index dcc7499f3535..1df40ad86445 100644 --- a/deps/zlib/patches/0015-minizip-unzip-enable-decryption.patch +++ b/deps/zlib/patches/0015-minizip-unzip-enable-decryption.patch @@ -18,7 +18,7 @@ diff --git a/third_party/zlib/contrib/minizip/unzip.c b/third_party/zlib/contrib index 82275d6c1775d..c8a01b23efd42 100644 --- a/third_party/zlib/contrib/minizip/unzip.c +++ b/third_party/zlib/contrib/minizip/unzip.c -@@ -1502,6 +1498,7 @@ extern int ZEXPORT unzOpenCurrentFile3(unzFile file, int* method, +@@ -1499,6 +1501,7 @@ extern int ZEXPORT unzOpenCurrentFile3(unzFile file, int* method, zdecode(s->keys,s->pcrc_32_tab,source[i]); s->pfile_in_zip_read->pos_in_zipfile+=12; @@ -45,7 +45,7 @@ diff --git a/third_party/zlib/contrib/minizip/unzip.c b/third_party/zlib/contrib index 0264f7ac570f7..4eb0de302cfdf 100644 --- a/third_party/zlib/contrib/minizip/unzip.c +++ b/third_party/zlib/contrib/minizip/unzip.c -@@ -1439,6 +1439,8 @@ local int unz64local_CheckCurrentFileCoherencyHeader(unz64_s* s, uInt* piSizeVar +@@ -1284,6 +1284,8 @@ local int unz64local_CheckCurrentFileCoherencyHeader(unz64_s* s, uInt* piSizeVar */ if (unz64local_getShort(&s->z_filefunc, s->filestream,&uFlags) != UNZ_OK) err=UNZ_ERRNO; diff --git a/deps/zlib/patches/0016-minizip-parse-unicode-path-extra-field.patch b/deps/zlib/patches/0016-minizip-parse-unicode-path-extra-field.patch index bb3e077c7147..2b2eb3375e52 100644 --- a/deps/zlib/patches/0016-minizip-parse-unicode-path-extra-field.patch +++ b/deps/zlib/patches/0016-minizip-parse-unicode-path-extra-field.patch @@ -90,8 +90,20 @@ Date: Mon Apr 27 13:24:27 2026 +0200 Change-Id: I06e6c8a8ff8baa729b10a67a998f8804803ae6cd Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/7797172 +commit 14964355aff9695897f7a2e06a4af2c4e25b71d5 +Author: Hans Wennborg <hans@chromium.org> +Date: Wed Sep 16 15:45:40 2026 +0200 + + [minizip] Ignore invalid Unicode Path Extra Fields rather than erroring + + To match what other extractors do. + + Bug: 553273868 + Change-Id: Ia5d64fb92d2abe5eba1e74f7180688a7a4362987 + Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8418328 + diff --git a/third_party/zlib/contrib/minizip/unzip.c b/third_party/zlib/contrib/minizip/unzip.c -index 56f1468cd8d22..0264f7ac570f7 100644 +index fb5eb0bf0f852..c15f4484f75f7 100644 --- a/third_party/zlib/contrib/minizip/unzip.c +++ b/third_party/zlib/contrib/minizip/unzip.c @@ -63,6 +63,7 @@ @@ -102,7 +114,7 @@ index 56f1468cd8d22..0264f7ac570f7 100644 #include <stdio.h> #include <stdlib.h> #include <string.h> -@@ -195,6 +196,26 @@ typedef struct +@@ -195,6 +196,26 @@ Reads a long in LSB order from the given gz_stream. Sets */ @@ -129,7 +141,7 @@ index 56f1468cd8d22..0264f7ac570f7 100644 local int unz64local_getShort(const zlib_filefunc64_32_def* pzlib_filefunc_def, voidpf filestream, uLong *pX) { -@@ -836,6 +857,10 @@ local int unz64local_GetCurrentFileInfoInternal(unzFile file, +@@ -836,6 +857,10 @@ uLong uMagic; long lSeek=0; uLong uL; @@ -140,7 +152,7 @@ index 56f1468cd8d22..0264f7ac570f7 100644 if (file==NULL) return UNZ_PARAMERROR; -@@ -907,21 +932,34 @@ local int unz64local_GetCurrentFileInfoInternal(unzFile file, +@@ -907,21 +932,34 @@ file_info_internal.offset_curfile = uL; lSeek+=file_info.size_filename; @@ -186,7 +198,7 @@ index 56f1468cd8d22..0264f7ac570f7 100644 } /* Read extrafield */ -@@ -1007,6 +1045,62 @@ local int unz64local_GetCurrentFileInfoInternal(unzFile file, +@@ -1007,6 +1045,64 @@ } } @@ -199,14 +211,16 @@ index 56f1468cd8d22..0264f7ac570f7 100644 + /* dataSize includes version (1 byte), uCrc (4 bytes), and + * the filename data. If it's too small, fileNameSize below + * would overflow. */ -+ err = UNZ_ERRNO; -+ break; ++ if (ZSEEK64(s->z_filefunc, s->filestream, dataSize, ZLIB_FILEFUNC_SEEK_CUR) != 0) ++ { ++ err = UNZ_ERRNO; ++ } + } + else if (unz64local_getByte(&s->z_filefunc, s->filestream, &version) != UNZ_OK) + { + err = UNZ_ERRNO; + } -+ if (version != 1) ++ else if (version != 1) + { + if (ZSEEK64(s->z_filefunc, s->filestream,dataSize - 1, ZLIB_FILEFUNC_SEEK_CUR) != 0) + { @@ -249,7 +263,7 @@ index 56f1468cd8d22..0264f7ac570f7 100644 else { if (ZSEEK64(s->z_filefunc, s->filestream,dataSize,ZLIB_FILEFUNC_SEEK_CUR)!=0) -@@ -1106,6 +1200,9 @@ extern int ZEXPORT unzGetCurrentFileInfo(unzFile file, +@@ -1106,6 +1202,9 @@ pfile_info->compressed_size = (uLong)file_info64.compressed_size; pfile_info->uncompressed_size = (uLong)file_info64.uncompressed_size; diff --git a/deps/zlib/patches/0018-support-prefixed-zip64.patch b/deps/zlib/patches/0018-support-prefixed-zip64.patch index f65d470046f0..8dc483f6e1da 100644 --- a/deps/zlib/patches/0018-support-prefixed-zip64.patch +++ b/deps/zlib/patches/0018-support-prefixed-zip64.patch @@ -30,10 +30,10 @@ Date: Fri May 16 15:35:36 2025 +0200 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/6554217 diff --git a/third_party/zlib/contrib/minizip/unzip.c b/third_party/zlib/contrib/minizip/unzip.c -index a39e1752f6d2e..2c8a73e87e011 100644 +index c15f4484f75f7..2ec74e0ff2af8 100644 --- a/third_party/zlib/contrib/minizip/unzip.c +++ b/third_party/zlib/contrib/minizip/unzip.c -@@ -482,6 +482,44 @@ local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib +@@ -485,6 +485,46 @@ local ZPOS64_T unz64local_SearchCentralDir64(const zlib_filefunc64_32_def* pzlib if (uL != 1) return CENTRALDIRINVALID; diff --git a/deps/zlib/test/minigzip.c b/deps/zlib/test/minigzip.c index 40da8736fbd2..968220b76e43 100644 --- a/deps/zlib/test/minigzip.c +++ b/deps/zlib/test/minigzip.c @@ -37,6 +37,9 @@ #ifdef USE_MMAP # include <sys/types.h> # include <sys/mman.h> +# ifndef MAP_FAILED +# define MAP_FAILED ((void *)-1) +# endif # include <sys/stat.h> #endif @@ -337,7 +340,7 @@ static int gz_compress_mmap(FILE *in, gzFile out) { int len; int err; int ifd = fileno(in); - caddr_t buf; /* mmap'ed buffer for the entire input file */ + void *buf; /* mmap'ed buffer for the entire input file */ off_t buf_len; /* length of the input file */ struct stat sb; @@ -347,8 +350,8 @@ static int gz_compress_mmap(FILE *in, gzFile out) { if (buf_len <= 0) return Z_ERRNO; /* Now do the actual mmap: */ - buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); - if (buf == (caddr_t)(-1)) return Z_ERRNO; + buf = mmap(NULL, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); + if (buf == MAP_FAILED) return Z_ERRNO; /* Compress the whole file at once: */ len = gzwrite(out, (char *)buf, (unsigned)buf_len); diff --git a/deps/zlib/trees.c b/deps/zlib/trees.c index 1aa15510271a..00650531ab49 100644 --- a/deps/zlib/trees.c +++ b/deps/zlib/trees.c @@ -250,7 +250,7 @@ local void gen_codes(ct_data *tree, int max_code, ushf *bl_count) { tree[n].Code = (ush)bi_reverse(next_code[len]++, len); Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", - n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); + n, (isgraph(n & 0xff) ? n : ' '), len, tree[n].Code, next_code[len] - 1)); } } diff --git a/deps/zlib/uncompr.c b/deps/zlib/uncompr.c index 2195e7855064..16a04ba27b73 100644 --- a/deps/zlib/uncompr.c +++ b/deps/zlib/uncompr.c @@ -33,8 +33,8 @@ int ZEXPORT uncompress2_z(Bytef *dest, z_size_t *destLen, const Bytef *source, const uInt max = (uInt)-1; z_size_t len, left; - if (sourceLen == NULL || (*sourceLen > 0 && source == NULL) || - destLen == NULL || (*destLen > 0 && dest == NULL)) + if (sourceLen == Z_NULL || (*sourceLen > 0 && source == Z_NULL) || + destLen == Z_NULL || (*destLen > 0 && dest == Z_NULL)) return Z_STREAM_ERROR; len = *sourceLen; diff --git a/deps/zlib/zconf.h b/deps/zlib/zconf.h index 4d64a653071c..fc8db455a85f 100644 --- a/deps/zlib/zconf.h +++ b/deps/zlib/zconf.h @@ -514,6 +514,10 @@ typedef uLong FAR uLongf; #if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 # define Z_LFS64 +#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \ + !defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__)) +# define Z_LFS64 /* native Windows has 64-bit file offsets */ +# define Z_WINLFS #endif #if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) @@ -531,7 +535,7 @@ typedef uLong FAR uLongf; #endif #ifndef z_off_t -# define z_off_t long long +# define z_off_t long #endif #if !defined(_WIN32) && defined(Z_LARGE64) @@ -546,6 +550,11 @@ typedef uLong FAR uLongf; # define z_off64_t z_off_t #endif +#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO) +# undef z_off_t +# define z_off_t z_off64_t +#endif + /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) #pragma map(deflateInit_,"DEIN") diff --git a/deps/zlib/zconf.h.in b/deps/zlib/zconf.h.in index 828ca617e907..3d308f6887fd 100644 --- a/deps/zlib/zconf.h.in +++ b/deps/zlib/zconf.h.in @@ -499,6 +499,10 @@ typedef uLong FAR uLongf; #if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 # define Z_LFS64 +#elif defined(_WIN32) && !defined(__CYGWIN__) && !defined(__BORLANDC__) && \ + !defined(UNDER_CE) && (defined(__MINGW32__) || !defined(__GNUC__)) +# define Z_LFS64 /* native Windows has 64-bit file offsets */ +# define Z_WINLFS #endif #if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) @@ -516,7 +520,7 @@ typedef uLong FAR uLongf; #endif #ifndef z_off_t -# define z_off_t long long +# define z_off_t long #endif #if !defined(_WIN32) && defined(Z_LARGE64) @@ -531,6 +535,11 @@ typedef uLong FAR uLongf; # define z_off64_t z_off_t #endif +#if defined(Z_WINLFS) && defined(Z_WANT64) && !defined(Z_SOLO) +# undef z_off_t +# define z_off_t z_off64_t +#endif + /* MVS linker does not support external names larger than 8 bytes */ #if defined(__MVS__) #pragma map(deflateInit_,"DEIN") diff --git a/deps/zlib/zlib.3 b/deps/zlib/zlib.3 index 7dbae9433183..d6922c405fbd 100644 --- a/deps/zlib/zlib.3 +++ b/deps/zlib/zlib.3 @@ -1,4 +1,4 @@ -.TH ZLIB 3 "xx Feb 2026" +.TH ZLIB 3 "4 Nov 2026" .SH NAME zlib \- compression/decompression library .SH SYNOPSIS @@ -105,7 +105,7 @@ before asking for help. Send questions and/or comments to zlib@gzip.org, or (for the Windows DLL version) to Gilles Vollant (info@winimage.com). .SH AUTHORS AND LICENSE -Version 1.3.2.1 +Version 1.4 .LP Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler .LP diff --git a/deps/zlib/zlib.h b/deps/zlib/zlib.h index 13909f2f8eb2..99d5f0084ba2 100644 --- a/deps/zlib/zlib.h +++ b/deps/zlib/zlib.h @@ -1,5 +1,5 @@ /* zlib.h -- interface of the 'zlib' general purpose compression library - version 1.3.2.1, February xxth, 2026 + version 1.4, November 4th, 2026 Copyright (C) 1995-2026 Jean-loup Gailly and Mark Adler @@ -41,12 +41,12 @@ extern "C" { #endif -#define ZLIB_VERSION "1.3.2.1-motley" -#define ZLIB_VERNUM 0x1321 +#define ZLIB_VERSION "1.4" +#define ZLIB_VERNUM 0x1400 #define ZLIB_VER_MAJOR 1 -#define ZLIB_VER_MINOR 3 -#define ZLIB_VER_REVISION 2 -#define ZLIB_VER_SUBREVISION 1 +#define ZLIB_VER_MINOR 4 +#define ZLIB_VER_REVISION 0 +#define ZLIB_VER_SUBREVISION 0 /* The 'zlib' compression library provides in-memory compression and @@ -695,7 +695,9 @@ ZEXTERN int ZEXPORT deflateCopy(z_streamp dest, deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. + destination. If deflateCopy fails and dest is not Z_NULL, then dest->state + is set to Z_NULL with dest otherwise unchanged, so that deflateEnd(dest) can + be called safely, though dest is not a usable stream. */ ZEXTERN int ZEXPORT deflateReset(z_streamp strm); @@ -768,17 +770,17 @@ ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm, uLong sourceLen); ZEXTERN z_size_t ZEXPORT deflateBound_z(z_streamp strm, z_size_t sourceLen); /* deflateBound() returns an upper bound on the compressed size after - deflation of sourceLen bytes. It must be called after deflateInit() or - deflateInit2(), and after deflateSetHeader(), if used. This would be used - to allocate an output buffer for deflation in a single pass, and so would be - called before deflate(). If that first deflate() call is provided the - sourceLen input bytes, an output buffer allocated to the size returned by - deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed - to return Z_STREAM_END. Note that it is possible for the compressed size to - be larger than the value returned by deflateBound() if flush options other - than Z_FINISH or Z_NO_FLUSH are used. - - delfateBound_z() is the same, but takes and returns a size_t length. Note + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader() or deflateSetDictionary(), if + used. This would be used to allocate an output buffer for deflation in a + single pass, and so would be called before deflate(). If that first + deflate() call is provided the sourceLen input bytes, an output buffer + allocated to the size returned by deflateBound(), and the flush value + Z_FINISH, then deflate() is guaranteed to return Z_STREAM_END. Note that it + is possible for the compressed size to be larger than the value returned by + deflateBound() if flush options other than Z_FINISH or Z_NO_FLUSH are used. + + deflateBound_z() is the same, but takes and returns a size_t length. Note that a long is 32 bits on Windows. */ @@ -788,7 +790,7 @@ ZEXTERN int ZEXPORT deflatePending(z_streamp strm, /* deflatePending() returns the number of bytes and bits of output that have been generated, but not yet provided in the available output. The bytes not - provided would be due to the available output space having being consumed. + provided would be due to the available output space having been consumed. The number of bits of output not provided are between 0 and 7, where they await more bits to join them in order to fill out a full byte. If pending or bits are Z_NULL, then those values are not set. @@ -868,8 +870,7 @@ ZEXTERN int ZEXPORT inflateInit2(z_streamp strm, instead. windowBits must be greater than or equal to the windowBits value provided to deflateInit2() while compressing, or it must be equal to 15 if deflateInit2() was not used. If a compressed stream with a larger window - size is given as input, inflate() will return with the error code - Z_DATA_ERROR instead of trying to allocate a larger window. + size is given as input, inflate() may return with a Z_DATA_ERROR. windowBits can also be zero to request that inflate use the window size in the zlib header of the compressed stream. @@ -979,7 +980,9 @@ ZEXTERN int ZEXPORT inflateCopy(z_streamp dest, inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream state was inconsistent (such as zalloc being Z_NULL). msg is left unchanged in both source and - destination. + destination. If inflateCopy fails and dest is not Z_NULL, then dest->state + is set to Z_NULL with dest otherwise unchanged, so that inflateEnd(dest) can + be called safely, though dest is not a usable stream. */ ZEXTERN int ZEXPORT inflateReset(z_streamp strm); @@ -1094,9 +1097,10 @@ ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm, a terminating zero. If any of extra, name, or comment are not present in the header, then that field's pointer is set to Z_NULL. This allows the use of deflateSetHeader() with the returned structure to duplicate the header. - Note that if those fields initially pointed to allocated memory, then the - application will need to save them elsewhere so that they can be eventually - freed. + Though take care that none of the fields were truncated before so using it, + lest havoc ensue. Note that if those fields initially pointed to allocated + memory, then the application will need to save them elsewhere so that they + can be eventually freed. If inflateGetHeader is not used, then the header information is simply discarded. The header is always checked for validity, including the header @@ -1393,8 +1397,8 @@ ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode); errno can be checked to determine if the reason gzopen failed was that the file could not be opened. Note that if 'N' is in mode for non-blocking, the open() itself can fail in order to not block. In that case gzopen() will - return NULL and errno will be EAGAIN or ENONBLOCK. The call to gzopen() can - then be re-tried. If the application would like to block on opening the + return NULL and errno will be EAGAIN or EWOULDBLOCK. The call to gzopen() + can then be re-tried. If the application would like to block on opening the file, then it can use open() without O_NONBLOCK, and then gzdopen() with the resulting file descriptor and 'N' in the mode, which will set it to non- blocking. @@ -1500,9 +1504,12 @@ ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems, gzfread() returns the number of full items read of size size, or zero if the end of the file was reached and a full item could not be read, or if there was an error. gzerror() must be consulted if zero is returned in - order to determine if there was an error. If the multiplication of size and - nitems overflows, i.e. the product does not fit in a z_size_t, then nothing - is read, zero is returned, and the error state is set to Z_STREAM_ERROR. + order to determine if there was an error. If some data was read before an + error, then that data is returned until exhausted, after which the next call + will return zero and gzerror() will report the error. If the multiplication + of size and nitems overflows, i.e. the product does not fit in a z_size_t, + then nothing is read, zero is returned, and the error state is set to + Z_STREAM_ERROR. In the event that the end of file is reached and only a partial item is available at the end, i.e. the remaining uncompressed data length is not a @@ -1568,7 +1575,7 @@ ZEXTERN int ZEXPORTVA gzprintf(); these possibilities can be determined using zlibCompileFlags(). If a Z_BUF_ERROR is returned, then nothing was written due to a stall on - the non-blocking write destination. + the non-blocking write destination. The operation can be retried. */ ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s); @@ -1676,7 +1683,9 @@ ZEXTERN z_off_t ZEXPORT gzseek(gzFile file, gzseek returns the resulting offset location as measured in bytes from the beginning of the uncompressed stream, or -1 in case of error, in particular if the file is opened for writing and the new starting position - would be before the current position. + would be before the current position, or if the resulting position would + not be representable in the offset type. If gzseek returns -1, the stream + position is unchanged. */ ZEXTERN int ZEXPORT gzrewind(gzFile file); @@ -1777,7 +1786,8 @@ ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum); If errnum is not NULL, *errnum is set to zlib error number. If an error occurred in the file system and not in the compression library, *errnum is set to Z_ERRNO and the application may consult errno to get the exact error - code. + code. The error is reported by gzerror() as soon as it is detected, which + may be before all of the data read prior to the error has been returned. The application must not modify the returned string. Future calls to this function may invalidate the previously returned string. If file is @@ -1976,7 +1986,8 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if * both are true, the application gets the *64 functions, and the regular * functions are changed to 64 bits) -- in case these are set on systems - * without large file support, _LFS64_LARGEFILE must also be true + * without large file support, _LFS64_LARGEFILE must also be true, except on + * native Windows, where 64-bit offsets are always available */ #ifdef Z_LARGE64 ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *); @@ -2058,7 +2069,7 @@ ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */ #endif /* !Z_SOLO */ -/* undocumented functions */ +/* undocumented functions (not part of the zlib API) */ ZEXTERN const char * ZEXPORT zError(int); ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp); ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void); diff --git a/deps/zlib/zlib.pc.cmakein b/deps/zlib/zlib.pc.cmakein index a392727c542b..c8edaf65d043 100644 --- a/deps/zlib/zlib.pc.cmakein +++ b/deps/zlib/zlib.pc.cmakein @@ -1,8 +1,8 @@ prefix=@CMAKE_INSTALL_PREFIX@ -exec_prefix=@CMAKE_INSTALL_PREFIX@ -libdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ -sharedlibdir=${exec_prefix}/@CMAKE_INSTALL_LIBDIR@ -includedir=${exec_prefix}/@CMAKE_INSTALL_INCLUDEDIR@ +exec_prefix=${prefix} +libdir=@pc_libdir@ +sharedlibdir=${libdir} +includedir=@pc_includedir@ Name: zlib Description: zlib compression library diff --git a/deps/zlib/zlibConfig.cmake.in b/deps/zlib/zlibConfig.cmake.in index 8252ab34ca32..72c31046d70a 100644 --- a/deps/zlib/zlibConfig.cmake.in +++ b/deps/zlib/zlibConfig.cmake.in @@ -1,5 +1,3 @@ -@PACKAGE_INIT@ - set(_ZLIB_supported_components "shared" "static") if(ZLIB_FIND_COMPONENTS) @@ -9,10 +7,34 @@ if(ZLIB_FIND_COMPONENTS) set(ZLIB_NOT_FOUND_MESSAGE "Unsupported component: ${_comp}") endif(NOT _comp IN_LIST _ZLIB_supported_components) - include("${CMAKE_CURRENT_LIST_DIR}/ZLIB-${_comp}.cmake") + include("${CMAKE_CURRENT_LIST_DIR}/ZLIB-${_comp}.cmake" + OPTIONAL + RESULT_VARIABLE _comp_loaded) + + if(NOT _comp_loaded) + set(ZLIB_FOUND False) + set(ZLIB_NOT_FOUND_MESSAGE "Component ${_comp} not found.") + else(NOT _comp_loaded) + set(ZLIB_${_comp}_FOUND TRUE) + endif(NOT _comp_loaded) endforeach(_comp ${ZLIB_FIND_COMPONENTS}) else(ZLIB_FIND_COMPONENTS) foreach(_component_config IN LISTS _ZLIB_supported_components) - include("${CMAKE_CURRENT_LIST_DIR}/ZLIB-${_component_config}.cmake") + include("${CMAKE_CURRENT_LIST_DIR}/ZLIB-${_component_config}.cmake" + OPTIONAL) endforeach(_component_config IN LISTS _ZLIB_supported_components) + + if(NOT TARGET ZLIB::ZLIB) + set(ZLIB_FOUND False) + set(ZLIB_NOT_FOUND_MESSAGE "Target ZLIB::ZLIB not created\n") + string(APPEND ZLIB_NOT_FOUND_MESSAGE "build zlib with support for shared libs or\n") + string(APPEND ZLIB_NOT_FOUND_MESSAGE "specify COMPONENTS static in your find_package call") + endif(NOT TARGET ZLIB::ZLIB) + + if(NOT TARGET ZLIB::ZLIBSTATIC) + set(ZLIB_FOUND False) + set(ZLIB_NOT_FOUND_MESSAGE "Target ZLIB::ZLIBSTATIC not created\n") + string(APPEND ZLIB_NOT_FOUND_MESSAGE "build zlib with support for static libs or\n") + string(APPEND ZLIB_NOT_FOUND_MESSAGE "specify COMPONENTS shared in your find_package call") + endif(NOT TARGET ZLIB::ZLIBSTATIC) endif(ZLIB_FIND_COMPONENTS) diff --git a/deps/zlib/zutil.c b/deps/zlib/zutil.c index 0e30c566429e..6c01021dfe43 100644 --- a/deps/zlib/zutil.c +++ b/deps/zlib/zutil.c @@ -227,7 +227,11 @@ voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { } else { buf = farmalloc(bsize + 16L); } - if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + if (buf == NULL) return NULL; + if (next_ptr >= MAX_PTR) { + farfree(buf); + return NULL; + } table[next_ptr].org_ptr = buf; /* Normalize the pointer to seg:0 */ diff --git a/doc/api/bench.md b/doc/api/bench.md index 866449165530..4c31cc309019 100644 --- a/doc/api/bench.md +++ b/doc/api/bench.md @@ -71,7 +71,7 @@ to their caller. Each warmup and measured sample invokes the benchmark function once with a fresh {BenchContext}. The function must either call `context.start()` and -`context.end(operations)` exactly once, or call `context.record(sample)` exactly +`context.end([operations])` exactly once, or call `context.record(sample)` exactly once to provide an externally measured sample. Setup before `start()` and cleanup after `end()` are outside the measured region. Promise-returning functions are awaited. @@ -90,6 +90,32 @@ system load can all affect results. Keep raw samples when comparing results and investigate noisy or skewed distributions rather than treating a confidence interval as a pass/fail threshold. +### Garbage collection + +Warmup invocations can leave garbage on the heap that is collected during the +first measured samples, charging warmup allocations to measured work. The `gc` +option forces a full garbage collection outside the measured region: + +* `'none'`: No garbage collection is forced. This is the default. +* `'once'`: A full garbage collection runs after warmup, before the first + measured sample. Garbage produced by measured samples is still collected + during measurement, so its cost remains part of the results. +* `'sample'`: A full garbage collection runs before every measured sample. This + reduces variance between samples, but samples that are too short to trigger a + collection on their own exclude the cost of collecting their garbage, which + can make allocation-heavy code appear faster than it is in practice. + +Forced collection runs after `beforeEach` hooks and any event loop turn between +samples, and is excluded from benchmark timeout accounting. The effective mode +is reported as `gc` in `'bench:plan'` events. The mode can be overridden for +every benchmark through `createRunner()`, [`run()`][], or [`--bench-gc`][]. + +Forcing garbage collection requires the `--expose-gc` flag, which also makes +`globalThis.gc()` available to benchmark code. A benchmark whose effective mode +is `'once'` or `'sample'` fails when the flag is not set. When `--bench-gc` +selects one of these modes, the command-line runner adds `--expose-gc` to +benchmark child processes automatically. + ### Measurement integrity A statistically consistent result does not prove that a benchmark measured the @@ -98,8 +124,9 @@ specialize it more narrowly than the workload being modeled. Framework and loop overhead can also dominate operations that are too short. To reduce these risks: * Make values produced by measured work observable outside the measured - interval, for example by validating an aggregate derived from every result. - Passing them only through unused local computations is insufficient. + interval, for example by validating an aggregate derived from every result + or by passing each result to [`doNotOptimize()`][]. Passing them only through + unused local computations is insufficient. * Perform enough operations in each sample to amortize fixed timer reads and calls to `context.start()` and `context.end()`. If loop bookkeeping is material relative to one operation, batch multiple operations per iteration and report @@ -112,7 +139,10 @@ overhead can also dominate operations that are too short. To reduce these risks: `node:bench` does not force a particular optimization state or infer whether an engine eliminated work. Such controls and diagnostics are runtime-specific and -heuristic, and do not replace validating the benchmark workload. +heuristic, and do not replace validating the benchmark workload. The `spec` +reporter flags rates that are implausibly fast for real work, which often +indicates eliminated work, but the absence of that warning does not prove the +work was measured. ### Dynamic sampling and variable batches @@ -221,9 +251,10 @@ arbitrary functions or closures to move them between isolates, because closures cannot be reconstructed with their original lexical environment. Benchmark files passed to `--bench` should declare benchmarks but must not call -`run()`. The CLI supports `--bench-name-pattern`, `--bench-samples`, -`--bench-warmup`, `--bench-reporter`, and `--bench-reporter-destination`. See -the [command-line options documentation][] for details. +`run()`. The CLI supports `--bench-gc`, `--bench-name-pattern`, +`--bench-samples`, `--bench-warmup`, `--bench-reporter`, and +`--bench-reporter-destination`. See the [command-line options documentation][] +for details. Preload modules passed through `--require` or `--import` should not declare benchmarks. Such declarations are not associated with an entry file and have @@ -260,13 +291,39 @@ bench('example', (b) => { run().compose(spec).pipe(process.stdout); ``` -The `spec` reporter buffers results and outputs a concise table containing the -sample count, mean rate, 95% confidence interval for the mean, median rate, and -warnings. A coefficient of variation above 5% is reported as `noisy`, and an -absolute skewness above 1 is reported as `skewed`. The exact human-readable -format is subject to change. - -The `json` reporter emits every lifecycle record as newline-delimited JSON. +The built-in reporters collect a snapshot of the reporting process's +environment when they receive their first record. The snapshot contains: + +* `node` {string} The value of `process.version`. +* `v8` {string} The value of `process.versions.v8`. +* `platform` {string} The value of `process.platform`. +* `arch` {string} The value of `process.arch`. +* `os` {Object} The operating system `type`, `release`, and `machine`, as + returned by the corresponding [`os`][] functions. +* `cpus` {Object\[]} The logical CPUs grouped by `model`, with the `count` of + each model. +* `availableParallelism` {number} The value of `os.availableParallelism()`. +* `memory` {Object} The `total` and `free` system memory in bytes, and the + `constrained` memory limit in bytes, or `null` when the process is not + constrained below the total system memory. +* `loadavg` {number\[]} The value of `os.loadavg()`. +* `execArgv` {string\[]} The value of `process.execArgv`. + +With process isolation, reporters run in the parent process. Benchmark children +are started from the same executable, but their `execArgv` can differ. + +The `spec` reporter buffers results and outputs a summary of the environment +followed by a concise table containing the sample count, mean rate, 95% +confidence interval for the mean, median rate, and warnings. A coefficient of +variation above 5% is reported as `noisy`, an absolute skewness above 1 is +reported as `skewed`, and a median rate of at least one operation per +nanosecond is reported as `implausible`, as it usually indicates that the +measured work was optimized away. The exact human-readable format is subject to +change. + +The `json` reporter emits a `'bench:environment'` record containing the +environment snapshot before the first lifecycle record, and then emits every +lifecycle record as newline-delimited JSON. BigInt values, including `duration_ns`, are encoded as decimal strings. Errors are represented using their `name`, `message`, `stack`, `code`, `cause`, and `errors` properties. As required by JSON, non-finite numbers are encoded as @@ -298,6 +355,9 @@ added: v26.9.0 --> * `options` {Object} + * `gc` {string} Overrides the [garbage collection][] mode for every + benchmark declared through this runner. One of `'none'`, `'once'`, or + `'sample'`. * `yieldBetweenSamples` {boolean} Schedule an event loop turn between sample callbacks. Disabling this also prevents timer-based abort signals from firing between synchronous callbacks. Benchmark timeouts continue to be @@ -311,8 +371,8 @@ the module-level functions. Call the returned `run()` function to start the runner and obtain its {BenchmarksStream}. Each runner can be started once. Its `run()` function accepts the same options -as the module-level [`run()`][]. `run({ yieldBetweenSamples })` overrides the -value passed to `createRunner()`. Unlike the module-level runner, a failed +as the module-level [`run()`][]. `run({ gc })` and `run({ yieldBetweenSamples })` +override the values passed to `createRunner()`. Unlike the module-level runner, a failed benchmark in an explicit runner does not change the process exit code. ## `bench([name][, options], fn)` @@ -327,6 +387,8 @@ added: v26.9.0 * `diagnosticChannels` {Array} String diagnostics channel names, deduplicated and inherited from containing suites by union. Symbol values in the array are silently ignored. **Default:** `[]`. + * `gc` {string} The [garbage collection][] mode. One of `'none'`, `'once'`, + or `'sample'`. **Default:** `'none'`. * `only` {boolean} When any benchmark or containing suite has `only` set, benchmarks without `only` in their hierarchy are skipped. **Default:** `false`. @@ -435,6 +497,61 @@ added: v26.9.0 Alias for `suite()`. +## `doNotOptimize(value)` + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +* `value` {any} A value produced by measured work. +* Returns: {any} `value`. + +Stores `value` where the optimizing compiler cannot prove it is unused, so the +computation that produced it is not eliminated as dead code. Returning `value` +allows the call to wrap an expression. + +```mjs +import { bench, doNotOptimize } from 'node:bench'; + +bench('Math.sqrt', (b) => { + const n = 1_000_000; + b.start(); + for (let i = 0; i < n; i++) { + doNotOptimize(Math.sqrt(i)); + } + b.end(n); +}); +``` + +```cjs +const { bench, doNotOptimize } = require('node:bench'); + +bench('Math.sqrt', (b) => { + const n = 1_000_000; + b.start(); + for (let i = 0; i < n; i++) { + doNotOptimize(Math.sqrt(i)); + } + b.end(n); +}); +``` + +The call adds a small, constant cost to every invocation, so it is best suited +to work that takes longer than a few nanoseconds per call. For cheaper +operations, accumulate results into a value that is passed to +`doNotOptimize()` once after the measured region. + +`doNotOptimize()` only prevents the result from being discarded. It does not +prevent the compiler from hoisting loop-invariant work or folding constant +inputs; vary inputs between iterations when the work would otherwise be +invariant. + +`doNotOptimize()` is intended to be called only from benchmark functions while +a runner is executing them. Non-number values are retained until the current +sample finishes, after which the runner releases them. When called outside a +benchmark function, the most recent non-number value remains reachable until +`doNotOptimize()` is called again. + ## `before(fn)` <!-- YAML @@ -488,6 +605,9 @@ added: v26.9.0 --> * `options` {Object} + * `gc` {string} Overrides the [garbage collection][] mode for every + benchmark. One of `'none'`, `'once'`, or `'sample'`. **Default:** the value + passed to `createRunner()` for an explicit runner. * `namePattern` {string|RegExp} Only runs benchmarks whose full hierarchical name matches the pattern. String values are interpreted as JavaScript regular expressions. @@ -642,14 +762,14 @@ added: v26.9.0 Starts the measured region using `process.hrtime.bigint()`. Calling `start()` more than once is an error. -### `context.end(operations[, options])` +### `context.end([operations[, options]])` <!-- YAML added: v26.9.0 --> * `operations` {number} The number of completed operations. Must be a positive - safe integer. + safe integer. **Default:** `1`. * `options` {Object} * `detail` {any} Additional structured-cloneable sample data. With CLI process isolation, it must also be supported by advanced child process @@ -671,7 +791,7 @@ added: v26.9.0 * `sample` {Object} * `operations` {number} The number of completed operations. Must be a positive - safe integer. + safe integer. **Default:** `1`. * `duration_ns` {bigint} An externally measured positive duration in nanoseconds no greater than `Number.MAX_SAFE_INTEGER`. * `detail` {any} Additional structured-cloneable sample data. With CLI process @@ -780,6 +900,8 @@ isolation, all files share one runner and their plans are emitted before any benchmark executes. Plan data contains the benchmark-scoped identity, location, tags, and parameters described in [benchmark result][], together with: +* `gc` {string} The effective [garbage collection][] mode after run-level + overrides. * `diagnosticChannels` {string\[]} The inherited string channel names subscribed to during each callback. * `samples` {number} The effective maximum number of measured callback @@ -798,7 +920,8 @@ tags, and parameters described in [benchmark result][], together with: The plan contains execution settings known to the runner. Runtime version, operating system, processor, and other environment metadata are intentionally -left for reporters and higher-level tools to collect. +left for reporters and higher-level tools to collect. The built-in reporters +include an [environment snapshot][benchmark reporters]. `'bench:complete'` data contains a [benchmark result][]. A failed result has an additional `error` property and may contain samples recorded before the error. @@ -854,8 +977,13 @@ A completed benchmark result contains: interval for the median rate, with `lower` and `upper` properties. * `skewness` {number} The skewness of the scaled rate histogram. +[`--bench-gc`]: cli.md#--bench-gcmode [`context.record()`]: #contextrecordsample [`createRunner()`]: #createrunneroptions +[`doNotOptimize()`]: #donotoptimizevalue +[`os`]: os.md [`run()`]: #runoptions +[benchmark reporters]: #benchmark-reporters [benchmark result]: #benchmark-result [command-line options documentation]: cli.md#--bench +[garbage collection]: #garbage-collection diff --git a/doc/api/cli.md b/doc/api/cli.md index 70c5743afc98..6bc3051318d8 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -554,6 +554,25 @@ details. This flag cannot be combined with `--test`, `--watch`, `--watch-path`, `--check`, `--eval`, or `--interactive`. +### `--bench-gc=mode` + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +> Stability: 1 - Experimental + +Overrides the garbage collection mode for every selected benchmark. When `mode` +is `'once'`, a full garbage collection runs before the first measured sample. +When `mode` is `'sample'`, a full garbage collection runs before every measured +sample. When `mode` is `'none'`, no garbage collection is forced. Without this +option, each benchmark uses its own `gc` value, which defaults to `'none'`. + +Forcing garbage collection requires the `--expose-gc` flag. With process +isolation, `--expose-gc` is added to benchmark child processes automatically +when `mode` is `'once'` or `'sample'`. With `--bench-isolation=none`, +`--expose-gc` must be passed explicitly. + ### `--bench-isolation=mode` <!-- YAML @@ -1516,33 +1535,6 @@ added: Enable experimental support for inspector network resources. -### `--experimental-loader=module` - -<!-- YAML -added: v8.8.0 -changes: - - version: - - v23.6.1 - - v22.13.1 - - v20.18.2 - pr-url: https://github.com/nodejs-private/node-private/pull/629 - description: Using this feature with the permission model enabled requires - passing `--allow-worker`. - - version: v12.11.1 - pr-url: https://github.com/nodejs/node/pull/29752 - description: This flag was renamed from `--loader` to - `--experimental-loader`. ---> - -> This flag is discouraged and may be removed in a future version of Node.js. -> Please use -> [`--import` with `register()`][preloading asynchronous module customization hooks] instead. - -Specify the `module` containing exported [asynchronous module customization hooks][]. -`module` may be any string accepted as an [`import` specifier][]. - -This feature requires `--allow-worker` if used with the [Permission Model][]. - ### `--experimental-network-inspection` <!-- YAML @@ -2380,7 +2372,7 @@ changes: description: SQLite is unflagged but still experimental. --> -Disable the experimental [`node:sqlite`][] module. +Disable the [`node:sqlite`][] module. ### `--no-experimental-vfs` @@ -2722,9 +2714,13 @@ Identical to `-e` but prints the result. <!-- YAML added: v26.11.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67506 + description: The flag is no longer experimental. --> -> Stability: 1.1 - Active development +> Stability: 2 - Stable Exits the process with code `124` if it is still running after `duration`, measured from the start of the process. `duration` is a positive integer @@ -2902,9 +2898,13 @@ error. <!-- YAML added: v26.11.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67506 + description: The flag is no longer experimental. --> -> Stability: 1.1 - Active development +> Stability: 2 - Stable Enables the report to be generated when [`--process-timeout`][] expires, in addition to the summary printed to stderr. Useful to inspect the JavaScript @@ -4283,6 +4283,7 @@ one is included in the list below. * `--allow-openssl-store` * `--allow-wasi` * `--allow-worker` +* `--bench-gc` * `--bench-isolation` * `--bench-name-pattern` * `--bench-reporter-destination` @@ -4314,7 +4315,6 @@ one is included in the list below. * `--experimental-import-meta-resolve` * `--experimental-import-text` * `--experimental-json-modules` -* `--experimental-loader` * `--experimental-modules` * `--experimental-package-map` * `--experimental-print-required-tla` @@ -4998,7 +4998,6 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12 [`dns.setDefaultResultOrder()`]: dns.md#dnssetdefaultresultorderorder [`dnsPromises.lookup()`]: dns.md#dnspromiseslookuphostname-options [`import.meta.url`]: esm.md#importmetaurl -[`import` specifier]: esm.md#import-specifiers [`inspector.open()`]: inspector.md#inspectoropenport-host-wait [`net.getDefaultAutoSelectFamilyAttemptTimeout()`]: net.md#netgetdefaultautoselectfamilyattempttimeout [`node:ffi`]: ffi.md @@ -5015,7 +5014,6 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12 [`v8.startupSnapshot.setDeserializeMainFunction()`]: v8.md#v8startupsnapshotsetdeserializemainfunctioncallback-data [`v8.startupSnapshot` API]: v8.md#startup-snapshot-api [`vfs.mount()`]: vfs.md#vfsmount -[asynchronous module customization hooks]: module.md#asynchronous-customization-hooks [benchmark runner]: bench.md#command-line-runner [captured by the built-in snapshot of Node.js]: https://github.com/nodejs/node/blob/b19525a33cc84033af4addd0f80acd4dc33ce0cf/test/parallel/test-bootstrap-modules.js#L24 [collecting code coverage from tests]: test.md#collecting-code-coverage @@ -5033,7 +5031,6 @@ node --stack-trace-limit=12 -p -e "Error.stackTraceLimit" # prints 12 [jitless]: https://v8.dev/blog/jitless [libuv threadpool documentation]: https://docs.libuv.org/en/latest/threadpool.html [module compile cache]: module.md#module-compile-cache -[preloading asynchronous module customization hooks]: module.md#registration-of-asynchronous-customization-hooks [randomizing tests execution order]: test.md#randomizing-tests-execution-order [remote code execution]: https://www.owasp.org/index.php/Code_Injection [running tests from the command line]: test.md#running-tests-from-the-command-line diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 54a2cbef52ba..00f068667fbe 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -4213,34 +4213,24 @@ changes: * `algorithm` {string} * `options` {Object} [`stream.transform` options][] - * `customization` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE - hash functions, specifies the customization byte string. **Default:** an - empty byte string. - * `functionName` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE - hash functions, specifies the NIST function-name byte string. **Default:** - an empty byte string. - * `outputLength` {number} For XOF hash functions, specifies the desired - output length in bytes. + * `customization` {string|ArrayBuffer|Buffer|TypedArray|DataView} The + customization byte string for digests that support it, such as cSHAKE. + * `functionName` {string|ArrayBuffer|Buffer|TypedArray|DataView} The NIST + function-name byte string for digests that support it, such as cSHAKE. + * `outputLength` {number} For a fixed-length digest, an explicit value must + match the digest size in bytes. * Returns: {Hash} Creates and returns a `Hash` object that can be used to generate hash digests -using the given `algorithm`. Optional `options` argument controls stream +using the given `algorithm`. The optional `options` argument controls stream behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option specifies the desired output length in bytes. It is required for XOF hash functions without a default output length. -The `functionName` and `customization` options apply only to cSHAKE-128 and -cSHAKE-256. They are supported only when Node.js is built with OpenSSL 4.0 or -later and the selected provider supports the corresponding digest parameters. -Strings are encoded as UTF-8, and neither strings nor byte values may contain -NUL bytes. Both options default to an empty byte string. For OpenSSL's built-in -providers, `functionName` is case-sensitive and must be `''`, `'TupleHash'`, -`'ParallelHash'`, or `'KMAC'`. Other providers can impose different -restrictions. With both options empty, cSHAKE produces the same output as the -corresponding SHAKE function for the same output length. `cshake-128` and -`cshake-256` default to output lengths of 32 and 64 bytes, respectively. +The selected digest determines which options are supported in addition to the +standard [`stream.transform` options][]. -When the data is small (< 5MB) and readily available, [`crypto.hash()`][] is usually faster. +For readily available data up to 5 MB, [`crypto.hash()`][] can be faster. The available algorithms depend on the version and configuration of OpenSSL on the platform. Examples are `'sha256'` and `'sha512'`. Use @@ -4419,15 +4409,13 @@ added: byte string for MACs that support it, such as KMAC. * `salt` {ArrayBuffer|Buffer|TypedArray|DataView} A salt byte string for MACs that support it, such as BLAKE2 MACs. - * `outputLength` {number} The requested provider output size in bytes. Must be - an unsigned 32-bit integer. Provider-specific restrictions also apply. + * `outputLength` {number} The requested MAC output size in bytes. Must be + an unsigned 32-bit integer. Algorithm-specific restrictions also apply. * Returns: {Mac} -`algorithm` must be a non-empty provider MAC name. The MAC-specific properties -listed above are extensions to the standard [`stream.transform` options][] and -are passed only when the selected provider implementation advertises the -corresponding parameter with the expected type. A supplied MAC-specific option -that the selected implementation does not support causes an error. +`algorithm` must be a non-empty MAC name. Use [`crypto.getMacs()`][] to list +available algorithms. The selected MAC determines which options it accepts. +Supplying an unsupported MAC-specific option causes an error. The following table summarizes the MAC-specific options accepted by MAC implementations in OpenSSL's built-in providers. The `key` argument is required @@ -4444,20 +4432,13 @@ for every MAC. The table lists only MAC-specific options; standard | Poly1305 | None | None | Each key must be used for only one message. | | SipHash | None | `outputLength` | | -`outputLength` configures the output size of the provider MAC. It is never -implemented by computing a longer tag and truncating it. A value of `0` is -passed to the provider and is accepted only when that provider can initialize -and finalize the MAC with a zero-byte output. When `outputLength` is omitted, -the provider's default output size is used and must be nonzero. +`outputLength` configures the size of the tag computed by the MAC. KMAC, for +example, incorporates the requested length into the tag computation. A value +of `0` is accepted only for MACs that support an empty tag. When omitted, the +default output size is used and must be nonzero. The `key` must contain bytes or be a [`KeyObject`][] of type `secret`. Key -length and other key requirements are determined by the selected provider -implementation. - -Available algorithms and their accepted parameters depend on the OpenSSL -version, loaded providers, and active default property query. Use -[`crypto.getMacs()`][] to list fetchable MAC names. A listed name can still -require options or a key with provider-specific properties. +length and other key requirements depend on the selected MAC algorithm. ### `crypto.createPrivateKey(key)` @@ -5735,23 +5716,14 @@ added: > Stability: 1.2 - Release candidate * Returns: {string\[]} A fresh array containing the sorted, lowercase names - and aliases of fetchable MAC implementations. - -Returns MAC names exposed by loaded OpenSSL providers that match the active -default property query. Duplicate names and numeric OID aliases are omitted. -On builds without OpenSSL `EVP_MAC` support, this function returns an empty -array. + and aliases of available MAC algorithms. -The returned names describe implementations that OpenSSL can fetch. They do not -guarantee that [`crypto.createMac()`][] can initialize the MAC without -additional options. A provider can require additional parameters or a key with -algorithm-specific properties, and it can expose parameters that this API does -not support. +A listed MAC can require additional options or a key of a specific length. +See [`crypto.createMac()`][] for the options that apply to each MAC family. After a successful FIPS mode change made with [`crypto.setFips()`][], subsequent calls reflect the new mode, and newly created `Mac` objects use it. Existing -`Mac` objects continue using the provider implementation selected when they -were created. +`Mac` objects continue using the implementation selected when they were created. ```mjs const { getMacs } = await import('node:crypto'); @@ -5801,47 +5773,33 @@ changes: description: The `outputLength` option was added for XOF hash functions. --> -* `algorithm` {string|undefined} +* `algorithm` {string} * `data` {string|Buffer|TypedArray|DataView} When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. * `options` {Object|string} - * `customization` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE - hash functions, specifies the customization byte string. **Default:** an - empty byte string. - * `functionName` {string|ArrayBuffer|Buffer|TypedArray|DataView} For cSHAKE - hash functions, specifies the NIST function-name byte string. **Default:** - an empty byte string. + * `customization` {string|ArrayBuffer|Buffer|TypedArray|DataView} The + customization byte string for digests that support it, such as cSHAKE. + * `functionName` {string|ArrayBuffer|Buffer|TypedArray|DataView} The NIST + function-name byte string for digests that support it, such as cSHAKE. * `outputEncoding` {string} [Encoding][encoding] used to encode the returned digest. **Default:** `'hex'`. - * `outputLength` {number} For XOF hash functions such as 'shake256', - specifies the desired output length in bytes. This option is required for - XOF hash functions without a default output length. + * `outputLength` {number} The requested digest length in bytes. Required for + XOF hash functions without a default output length, such as SHAKE. For a + fixed-length digest, an explicit value must match the digest size. * Returns: {string|Buffer} A utility for creating one-shot hash digests of data. It can be faster than -the object-based `crypto.createHash()` when hashing a smaller amount of data -(<= 5MB) that's readily available. If the data can be big or if it is streamed, -it's still recommended to use `crypto.createHash()` instead. +[`crypto.createHash()`][] for readily available data up to 5 MB. Use +[`crypto.createHash()`][] for large inputs or streamed data. The available algorithms depend on the version and configuration of OpenSSL on the platform. Examples are `'sha256'` and `'sha512'`. Use [`crypto.getHashes()`][] to obtain the list of hash algorithms available to the Node.js process. -The `functionName` and `customization` options apply only to cSHAKE-128 and -cSHAKE-256. They are supported only when Node.js is built with OpenSSL 4.0 or -later and the selected provider supports the corresponding digest parameters. -Strings are encoded as UTF-8, and neither strings nor byte values may contain -NUL bytes. Both options default to an empty byte string. For OpenSSL's built-in -providers, `functionName` is case-sensitive and must be `''`, `'TupleHash'`, -`'ParallelHash'`, or `'KMAC'`. Other providers can impose different -restrictions. With both options empty, cSHAKE produces the same output as the -corresponding SHAKE function for the same output length. `cshake-128` and -`cshake-256` default to output lengths of 32 and 64 bytes, respectively. - If `options` is a string, then it specifies the `outputEncoding`. Example: @@ -7168,8 +7126,8 @@ Calculates and returns the signature for `data` using the given private key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the key type. -`algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and -ML-DSA. +`algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, ML-DSA, +and SLH-DSA. [`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but the key type and signature scheme determine whether a listed digest can be @@ -7197,10 +7155,11 @@ passed: `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the maximum permissible value. -* `context` {ArrayBuffer|Buffer|TypedArray|DataView} For Ed25519[^openssl32] - (using Ed25519ctx from [RFC 8032][]), Ed448, ML-DSA, and SLH-DSA, - this option specifies the optional context to differentiate signatures - generated for different purposes with the same key. +* `context` {Buffer|TypedArray|DataView} An optional byte string of up to 255 + bytes for Ed25519[^openssl32], Ed448, ML-DSA, and SLH-DSA. It separates + signatures generated for different purposes with the same key. An empty + context is equivalent to omitting the option. For Ed25519, a non-empty + context selects Ed25519ctx from [RFC 8032][]. If the `callback` function is provided this function uses libuv's threadpool. @@ -7314,8 +7273,8 @@ Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the key type. -`algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and -ML-DSA. +`algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, ML-DSA, +and SLH-DSA. [`crypto.getHashes()`][] lists algorithms available to the hashing APIs, but the key type and signature scheme determine whether a listed digest can be @@ -7343,10 +7302,11 @@ passed: `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the maximum permissible value. -* `context` {ArrayBuffer|Buffer|TypedArray|DataView} For Ed25519[^openssl32] - (using Ed25519ctx from [RFC 8032][]), Ed448, ML-DSA, and SLH-DSA, - this option specifies the optional context to differentiate signatures - generated for different purposes with the same key. +* `context` {Buffer|TypedArray|DataView} An optional byte string of up to 255 + bytes for Ed25519[^openssl32], Ed448, ML-DSA, and SLH-DSA. Use the same + context that was used to sign the data. An empty context is equivalent to + omitting the option. For Ed25519, a non-empty context selects Ed25519ctx + from [RFC 8032][]. The `signature` argument is the previously calculated signature for the `data`. diff --git a/doc/api/debugger.md b/doc/api/debugger.md index c7490af82924..4699b11ee713 100644 --- a/doc/api/debugger.md +++ b/doc/api/debugger.md @@ -237,6 +237,11 @@ added: - v26.1.0 - v24.16.0 changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67201 + description: Add `--pid <pid>` and `--host <host>`/`--port <port>` to probe a process that's + already running. The report now includes a top-level `target` field to describe what was + probed, and a `locations` field showing which probe is bound to which location. - version: - v26.6.0 - v24.20.0 @@ -270,8 +275,10 @@ changes: `node inspect` supports a non-interactive probe mode for inspecting runtime values in an application via the flag `--probe`. -Currently, probe mode only supports launching a new process from the entry point -script specified on the command line. +There are two ways to use probe mode: + +* Launch a new process and probe it by specifying the entry point script. +* Attach to and probe a running process using `--pid <pid>` or `--host <host>`/`--port <port>`. The probe mode sets one or more source breakpoints, evaluates specified expressions whenever the execution reaches a breakpoint, and prints one @@ -281,10 +288,18 @@ printf-style debugging without having to modify the application code and clean up afterwards. It also supports structured JSON output for tool use. ```console +# To launch a new process and probe it: $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] [--probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] ...] [--json] [--preview] [--timeout=<ms>] [--port=<port>] [--] [<node-option> ...] <script> [<script-args> ...] + +# To activate the inspector in an already-running process and probe it: +$ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --pid <pid> [--host <host>] [--port <port>] + +# To probe a running process whose inspector is already listening for connections: +$ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --host <host> [--port <port>] +$ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --port <port> [--host <host>] ``` * `--probe <file>:<line>[:<col>]`: Source location of the probe. When execution @@ -300,17 +315,32 @@ $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--ma is treated as false. * `--max-hit <n>`: An optional per-probe limit on the number of times the probe can be hit. When not specified, there's no hit limit. When any probe reaches - its hit limit, the probing process will detach and report the results. The process - being probed will continue to run. If any other probe is never reached by the time - the session ends, it will be reported as a missed probe. -* `--timeout=<ms>`: A global wall-clock deadline for the entire probe session. - The default is `30000`. This can be used to probe a long-running application - that can be terminated externally. + its hit limit, the probing session finishes and reports the results. If the + probed process was launched by probe mode, it's then terminated. If the process + was already running before being attached for probing, it is resumed and left running. + If any other probe is never reached by the time the session ends, the missed probes will + be reported. +* `--timeout=<ms>`: A deadline in milliseconds. The default is `30000`. It is + applied first to the target responding to the inspector and binding the + probes, then to the probing session itself, so a run can take up to about + twice the limit to time out. If the target does not respond in time during startup, + the report ends with an `error` and the probing process exits with a non-zero + code. If the process was attached to instead of launched by probe mode, + `--timeout` is an alternative to `--max-hit` for ending a probing session + without terminating the probed process. * `--json`: If used, prints a structured JSON report instead of the default text report. * `--preview`: If used, non-primitive values will include CDP property previews for object-like JSON probe values. -* `--port=<port>`: Selects the local inspector port where the probing session - will listen. Defaults to `0`, which requests a random port. +* `--port=<port>`: When the probe mode launches the probed process, it specifies the port + the launched child process' inspector listens on and defaults to `0`, which requests a + random port. When the probe mode attaches to a running process, this specifies the port to connect to + and defaults to `9229`, while `0` is invalid. +* `--host <host>`: In attach mode, the host to connect to. Defaults to + `127.0.0.1`. It is an error to combine it with an entry point script. +* `--pid <pid>`: Attach to a running Node.js process by PID instead of + launching a child. This activates the inspector of the target process if it + is not active yet, then connects to `--host`:`--port`. See + [Attaching to a running process](#attaching-to-a-running-process). * `--` is optional unless the child needs its own Node.js flags. Additional rules about the composition of the options: @@ -339,6 +369,65 @@ $ node inspect --probe app.js:10 --expr "user" --json --preview -- --no-warnings app.js --arg-for-app=foo ``` +### Attaching to a running process + +When the entry point script is not specified and `--probe` is used, probe mode can attach +to a process that is already running instead of launching a child process. +This is useful for probing a long-running application, when users want to inspect runtime +values without restarting it. + +When `--pid` is specified, probe mode activates the inspector of the process by +sending `SIGUSR1` on POSIX platforms. The process must be a Node.js process, +otherwise it may be terminated by `SIGUSR1`. The probing process will retry +connecting using `--host` and `--port` until the timeout fires. +If `--pid` is not specified, the inspector in the target process must already be listening. +If the connection is refused, an error is reported immediately. + +```console +# Probing a process by PID, which may not already have the inspector listening. +# End the probing session when the specified probe is reached 5 times. +$ node inspect --probe app.js:42 --expr "req.url" --max-hit 5 --pid 12345 + +# Probing a process that's already listening for inspector connections at 127.0.0.1:9229. +# End the probing session when the specified timeout is reached. +$ node inspect --probe app.js:42 --expr "req.url" --timeout 50000 --host 127.0.0.1 --port 9229 +``` + +Probing by attaching to a process differs from launching one in several ways. + +* The scripts are already loaded in the process when the breakpoints are bound, + and the `locations` field for each probe in the report shows where it bound. + An empty list indicates that no loaded script matched the probe, e.g. + when there's a typo in the path or the line. +* When the probing session ends, it resumes and detaches from the probed process. + The target should continue running and **its inspector will remain activated**. + Probe mode does not kill a process it did not launch. +* If the target is waiting for `--inspect-brk` or `--inspect-wait` when the + session attaches to it, these would be released so that the probes can run. +* An attach session ends when one of the following happens: + * A probe reaches `--max-hit`. The report ends with `completed`. + * The target finishes on its own. The report ends with `completed`, or + with `miss` when some probes are never hit. The target is then allowed to + exit. + * The target exits with an uncaught exception. The report ends with `probe_target_exit` + and an `error` that describes the exception. The probing process exits with code 0. + * `--timeout` fires. The report ends with `timeout` and the hits recorded + so far, and the probing process exits with code 0. If a probe expression + is still running at that point, the session reports an `error` and exits + with code 1 instead. The expression is terminated after at most another + `--timeout`, unless it is blocked inside a native call, and the target + then resumes. + * The target does not respond during startup within `--timeout`, for + example because its main thread is blocked for synchronous work. The + report then ends with an `error`, and the probing process exits with code 1. +* If the target is killed during the session, the session ends with an + `error`. If it's attached via `--pid`, this is reported as + `probe_target_exit` with exit code 0. If it's attached via `--host` and `--port`, + an exit cannot be distinguished from a network failure, so it is reported as + `probe_failure` with a non-zero exit code. +* The target's stdout and stderr are not captured, so the terminal `error` + events have no `error.stderr` field. + ### Probe output format When the probe session ends, the probing process prints a final report of all the probe hits and results. @@ -380,12 +469,19 @@ When `--json` is used, the output shape looks like this: ```console $ node inspect --json --probe cli.js:5 --expr 'rss' cli.js -{"v":2,"probes":[{"expr":"rss","target":{"suffix":"cli.js","line":5}}],"results":[{"probe":0,"event":"hit","hit":1,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55443456,"description":"55443456"}},{"probe":0,"event":"hit","hit":2,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55574528,"description":"55574528"}},{"event":"completed"}]} +{"v":2,"target":{"argv":["cli.js"]},"probes":[{"expr":"rss","target":{"suffix":"cli.js","line":5},"locations":[{"url":"file:///path/to/cli.js","line":5,"column":3}]}],"results":[{"probe":0,"event":"hit","hit":1,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55443456,"description":"55443456"}},{"probe":0,"event":"hit","hit":2,"location":{"url":"file:///path/to/cli.js","line":5,"column":3},"result":{"type":"number","value":55574528,"description":"55574528"}},{"event":"completed"}]} ``` ```json { "v": 2, // Probe JSON schema version. + "target": { + // Describes what was probed. The shape depends on how the session was started: + // launch mode: { "argv": ["cli.js"] } + // --pid <pid>: { "pid": 12345, "host": "127.0.0.1", "port": 9229 } + // --host/--port: { "host": "127.0.0.1", "port": 9229 } + "argv": ["cli.js"] + }, "probes": [ { "expr": "rss", // The expression paired with --probe. @@ -397,7 +493,13 @@ $ node inspect --json --probe cli.js:5 --expr 'rss' cli.js // from the target and will be reported in each hit's `location` field. "suffix": "cli.js", "line": 5 - } + }, + // Locations where the probe's breakpoint is bound. The shape is the same as the `location` + // of a hit. There is one entry per matching script, and it's empty when no loaded script + // matches the target, or when the session ends before the probe is bound. + "locations": [ + { "url": "file:///path/to/cli.js", "line": 5, "column": 3 } + ] // `condition` is present only when the probe was given a --cond expression. // `maxHit` is present only when the probe was given a --max-hit limit. } @@ -477,18 +579,23 @@ $ node inspect --json --probe cli.js:5 --expr 'rss' cli.js ### Output and exit codes -Probe mode only prints the final probe report to stdout, and otherwise silences -stdout/stderr from the child process. When the probing session ends, +Probe mode only prints the final probe report to stdout. If the probed process is launched by +probe mode, the stdout/stderr of the child process is silenced. When the probing session ends, the probing process typically exits with code `0` and prints a final report to stdout. If the child process exits with a non-zero code before the probe session ends, or the probe session cannot complete for another reason, the final report records a terminal `error` event. -When `error.code` is `'probe_failure'` or `'probe_timeout'`, the probing process -exits with a non-zero code, indicating recorded hits may be incomplete. -In this case, `error.message` will contain recovery hints, and `error.probe`, -when present, is an index into the report's `probes` array that identifies -the possible culprit probe on a best-effort basis to help guide debugging. +When `error.code` is `'probe_failure'`, the probing process exits with a +non-zero code, indicating recorded hits may be incomplete. In this case, +`error.message` will contain recovery hints, and `error.probe`, when present, +is an index into the report's `probes` array that identifies the possible +culprit probe on a best-effort basis to help guide debugging. + +When `error.code` is `'probe_timeout'`, the probing process exits with a +non-zero code if it launched the process, and with `0` if it attached to a +running process, where the timeout is considered a normal end of the session. See +[Attaching to a running process](#attaching-to-a-running-process). Invalid arguments and fatal launch or connect failures may cause the probing process to exit with a non-zero code and print an error message diff --git a/doc/api/deprecations.md b/doc/api/deprecations.md index 95deb305b64e..2c435c593617 100644 --- a/doc/api/deprecations.md +++ b/doc/api/deprecations.md @@ -4615,6 +4615,9 @@ no longer supported. <!-- YAML changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67090 + description: End-of-Life. - version: v26.0.0 pr-url: https://github.com/nodejs/node/pull/62401 description: Runtime deprecation. @@ -4625,18 +4628,18 @@ changes: description: Documentation-only deprecation. --> -Type: Runtime +Type: End-of-Life -[`module.register()`][] is deprecated. Use [`module.registerHooks()`][] -instead. +The `module.register()` API and the `--experimental-loader` and `--loader` +flags have been removed. Use [`module.registerHooks()`][] instead. -The `module.register()` API provides off-thread async hooks for customizing ES modules; -the `module.registerHooks()` API provides similar hooks that are synchronous, in-thread, and -work for all types of modules. -Supporting async hooks has proven to be complex, involving worker threads orchestration, and there are issues -that have proven unresolvable. See [caveats of asynchronous customization hooks][]. Please migrate to -`module.registerHooks()` as soon as possible as `module.register()` will be -removed in a future version of Node.js. +The `module.register()` API provided off-thread async module customization +hooks for customizing ES modules. The `module.registerHooks()` API provides +similar hooks that are synchronous, in-thread and work for all types of modules. +To continue running async module customization off-thread, users can spawn their +own threads to run the async customizations, communicate from the in-thread +synchronous hooks and block for the results on the main thread, similar to how +`module.register()` worked internally. ### DEP0206: Calling `digest()` on an already-finalized `Hmac` instance @@ -4844,6 +4847,69 @@ Type: Documentation-only `node:sqlite`'s `StatementSync` class was renamed to `Statement`. `StatementSync` is kept as a deprecated alias. Use `Statement` instead. +### DEP0212: `util.TextDecoder` and `util.TextEncoder` + +<!-- YAML +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67461 + description: Documentation-only deprecation. +--> + +Type: Documentation-only + +`node:util`'s `util.TextDecoder` and `util.TextEncoder` are deprecated. +Use global `TextDecoder` and `TextEncoder` instead. + +### DEP0213: TLS renegotiation + +<!-- YAML +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67532 + description: Documentation-only deprecation + with `--pending-deprecation` support. +--> + +Type: Documentation-only (supports [`--pending-deprecation`][]) + +TLS renegotiation is deprecated and will be disabled by default in future. +This functionality will be largely removed in a subsequent release. Only a +client accepting server-initiated renegotiation requests is expected to +remain supported, and on an opt-in basis for legacy server compatibility. + +This only affects TLS 1.2. TLS 1.3 removed renegotiation from the standard, +and so this has never been supported. + +Avoid using TLS renegotiation. A server that needs a client certificate should +request it in the initial configuration, with the `requestCert` option of +[`tls.createServer()`][]. A client that needs to change the configuration of +an existing connection should create a new connection. + +This affects multiple TLS APIs: + +* Node.js TLS clients needing to initiate renegotiation locally, or accept + renegotiation requested by the server, should opt in by setting the + `allowRenegotiation` option of [`tls.connect()`][]. +* Node.js TLS servers needing to initiate renegotiation locally, or accept + renegotiation requested by the client, should opt in by setting the + `allowRenegotiation` option of [`tls.createServer()`][]. + If renegotiation by clients is removed in future, setting this option to + `true` on a server will throw an error. +* In either case, initiating renegotiation ([`tlsSocket.renegotiate()`][]) + should be avoided by using alternative mechanisms. When renegotiation is + disabled by default this method will only work on connections created + with the `allowRenegotiation` option, and will throw an error if not. + If initiating renegotiation is removed in future, this method will throw + an error. +* Using [`tlsSocket.disableRenegotiation()`][] to disable renegotiation will + no longer be necessary when it is disabled by default. This will become a + no-op in most configurations. +* The `tls.CLIENT_RENEG_LIMIT` and `tls.CLIENT_RENEG_WINDOW` properties which + limit renegotiation will become unused in default configurations. + If renegotiation by clients is removed in future these are likely to be + removed. + [DEP0142]: #dep0142-repl_builtinlibs [DEP0156]: #dep0156-aborted-property-and-abort-aborted-event-in-http [NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf @@ -4935,7 +5001,6 @@ Type: Documentation-only [`message.trailersDistinct`]: http.md#messagetrailersdistinct [`message.trailers`]: http.md#messagetrailers [`module.createRequire()`]: module.md#modulecreaterequirefilename -[`module.register()`]: module.md#moduleregisterspecifier-parenturl-options [`module.registerHooks()`]: module.md#moduleregisterhooksoptions [`os.networkInterfaces()`]: os.md#osnetworkinterfaces [`os.tmpdir()`]: os.md#ostmpdir @@ -4969,8 +5034,11 @@ Type: Documentation-only [`tls.SecureContext`]: tls.md#tlscreatesecurecontextoptions [`tls.TLSSocket`]: tls.md#class-tlstlssocket [`tls.checkServerIdentity()`]: tls.md#tlscheckserveridentityhostname-cert +[`tls.connect()`]: tls.md#tlsconnectoptions-callback [`tls.createSecureContext()`]: tls.md#tlscreatesecurecontextoptions [`tls.createServer()`]: tls.md#tlscreateserveroptions-secureconnectionlistener +[`tlsSocket.disableRenegotiation()`]: tls.md#tlssocketdisablerenegotiation +[`tlsSocket.renegotiate()`]: tls.md#tlssocketrenegotiateoptions-callback [`url.format()`]: url.md#urlformaturlobject [`url.format(urlString)`]: url.md#urlformaturlstring [`url.parse()`]: url.md#urlparseurlstring-parsequerystring-slashesdenotehost @@ -4991,7 +5059,6 @@ Type: Documentation-only [`zlib.bytesWritten`]: zlib.md#zlibbyteswritten [alloc]: buffer.md#static-method-bufferallocsize-fill-encoding [alloc_unsafe_size]: buffer.md#static-method-bufferallocunsafesize-alignment -[caveats of asynchronous customization hooks]: module.md#caveats-of-asynchronous-customization-hooks [from_arraybuffer]: buffer.md#static-method-bufferfromarraybuffer-byteoffset-length [from_string_encoding]: buffer.md#static-method-bufferfromstring-encoding [legacy URL API]: url.md#legacy-url-api diff --git a/doc/api/diagnostics_channel.md b/doc/api/diagnostics_channel.md index 25e544ccf27b..dac515cf2172 100644 --- a/doc/api/diagnostics_channel.md +++ b/doc/api/diagnostics_channel.md @@ -1699,6 +1699,25 @@ Emitted when server sends a response. > Stability: 1 - Experimental +##### Event: `'http2.client.request.headers'` + +* `headers` {HTTP/2 Headers Object | string\[]} +* `session` {http2.ClientHttp2Session} + +Emitted when `ClientHttp2Session#request()` is called, before the request +headers are validated and serialized. The `headers` object is a copy of the +one passed to `request()` by the caller (or a newly created object when no +headers were passed), and it can be mutated in place to add or modify request +headers before they are sent. Mutating it does not affect the headers +object passed by the caller. This allows subscribers such as tracing +instrumentation to inject context headers (e.g. `traceparent`) into outgoing +HTTP/2 requests. +Headers injected this way are subject to the same validation as headers +passed directly to `request()`. To take effect, headers must be mutated in +place. Unlike `'http2.client.stream.created'`, which is published after +the request headers have been serialized, mutations made by subscribers to +this channel affect the headers that are sent. + ##### Event: `'http2.client.stream.created'` * `stream` {ClientHttp2Stream} @@ -2002,6 +2021,20 @@ added: v16.18.0 Emitted when a new thread is created. +##### Event: `'worker_threads.main.registry'` + +* `threadIds` {number\[]} A snapshot of the registered worker thread IDs. + +Emitted only on the main thread whenever the worker thread registry changes, +including workers created by other workers. Each event contains a snapshot of +the registered worker thread IDs. The main thread's ID (`0`) is not included. + +The registry tracks workers through their internal messaging ports. Registration +can occur before a worker is online. Removal occurs when the parent thread +processes the worker's exit and can be delayed if the parent thread is blocked. +Consequently, a snapshot does not guarantee that every listed worker is ready or +still running. + #### SQLite <!-- YAML @@ -2040,6 +2073,53 @@ statement is garbage collected. Subscribers must not close the database or the statement, since both are still in use while the event is being delivered; see [`database.close()`][] and [`statement.close()`][]. +#### libuv Thread Pool + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +> Stability: 1 - Experimental + +##### Event: `'uv.threadpool.work.<type>'` + +Each kind of work submitted to the [libuv thread pool][] has a separate channel +named by appending its `type` to `'uv.threadpool.work.'`. + +Supported values for `<type>` are: + +* `'crypto'` + +* `'fs.cp'` + +* `'fs.readfile'` + +* `'fs.writefile'` + +* `'glob'` + +* `'histogram.qrde'` + +* `'node_api'` + +* `'readdir_recursive'` + +* `'node_sqlite3.BackupJob'` + +* `'zlib'` + +Messages contain: + +* `enqueued` {number} When the work was submitted to the pool. + +* `started` {number|null} When execution started, or `null` if cancelled. + +* `ended` {number|null} When execution ended, or `null` if cancelled. + +Emitted after the work finishes and before its completion callback. Timestamps +use the [`performance.now()`][] timeline. `started - enqueued` is queue time; +`ended - started` is execution time. + [BoundedChannel Channels]: #boundedchannel-channels [Test instrumentation and OpenTelemetry]: test.md#test-instrumentation-and-opentelemetry [TracingChannel Channels]: #tracingchannel-channels @@ -2066,9 +2146,11 @@ statement, since both are still in use while the event is being delivered; see [`error` event]: #errorevent [`locks.request()`]: worker_threads.md#locksrequestname-options-callback [`net.Server.listen()`]: net.md#serverlisten +[`performance.now()`]: perf_hooks.md#performancenow [`process.execve()`]: process.md#processexecvefile-args-env [`start` event]: #startevent [`statement.close()`]: sqlite.md#statementclose [`worker_threads.locks`]: worker_threads.md#worker_threadslocks [context loss]: async_context.md#troubleshooting-context-loss +[libuv thread pool]: https://docs.libuv.org/en/v1.x/threadpool.html [thenable object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#thenables diff --git a/doc/api/errors.md b/doc/api/errors.md index 8020ec838c88..12623b0344f2 100644 --- a/doc/api/errors.md +++ b/doc/api/errors.md @@ -733,13 +733,6 @@ by the `node:assert` module. An attempt was made to register something that is not a function as an `AsyncHooks` callback. -<a id="ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED"></a> - -### `ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED` - -An operation related to module loading is customized by an asynchronous loader -hook that never settled the promise before the loader thread exits. - <a id="ERR_ASYNC_RESOURCE_DOMAIN_REMOVED"></a> ### `ERR_ASYNC_RESOURCE_DOMAIN_REMOVED` @@ -1764,6 +1757,14 @@ provided. The `Http2Session` closed with a non-zero error code. +<a id="ERR_HTTP2_SESSION_MEMORY_EXCEEDED"></a> + +### `ERR_HTTP2_SESSION_MEMORY_EXCEEDED` + +A request was rejected before being sent because the `Http2Session` was using +more memory than its `maxSessionMemory` setting allows. Nothing was sent to the +peer, so the request can be retried. The session remains usable. + <a id="ERR_HTTP2_SETTINGS_CANCEL"></a> ### `ERR_HTTP2_SETTINGS_CANCEL` @@ -2364,19 +2365,6 @@ for more information. IP is blocked by `net.BlockList`. -<a id="ERR_LOADER_CHAIN_INCOMPLETE"></a> - -### `ERR_LOADER_CHAIN_INCOMPLETE` - -<!-- YAML -added: - - v18.6.0 - - v16.17.0 ---> - -An ESM loader hook returned without calling `next()` and without explicitly -signaling a short circuit. - <a id="ERR_LOAD_SQLITE_EXTENSION"></a> ### `ERR_LOAD_SQLITE_EXTENSION` @@ -3378,8 +3366,8 @@ disabled. ### `ERR_TLS_RENEGOTIATION_UNSUPPORTED` -An attempt was made to renegotiate TLS, but the TLS implementation does not -support caller-initiated renegotiation. +An attempt was made to renegotiate TLS, or to allow renegotiation on a server, +but the TLS implementation does not support it. <a id="ERR_TLS_REQUIRED_SERVER_NAME"></a> @@ -3936,6 +3924,17 @@ attempting a [`require()`][] operation or when loading the program entry point. > Stability: 0 - Deprecated. These error codes are either inconsistent, or have > been removed. +<a id="ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED"></a> + +### `ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED` + +<!-- YAML +removed: v27.0.0-alpha.0.2.0 +--> + +An operation related to module loading is customized by an asynchronous loader +hook that never settled the promise before the loader thread exits. + <a id="ERR_CANNOT_TRANSFER_OBJECT"></a> ### `ERR_CANNOT_TRANSFER_OBJECT` @@ -4174,6 +4173,20 @@ changes: An invalid transfer object was passed to `postMessage()`. +<a id="ERR_LOADER_CHAIN_INCOMPLETE"></a> + +### `ERR_LOADER_CHAIN_INCOMPLETE` + +<!-- YAML +added: + - v18.6.0 + - v16.17.0 +removed: v27.0.0-alpha.0.2.0 +--> + +An ESM loader hook returned without calling `next()` and without explicitly +signaling a short circuit. + <a id="ERR_MANIFEST_ASSERT_INTEGRITY"></a> ### `ERR_MANIFEST_ASSERT_INTEGRITY` diff --git a/doc/api/esm.md b/doc/api/esm.md index ef15a51dcfe5..bc4af89045f7 100644 --- a/doc/api/esm.md +++ b/doc/api/esm.md @@ -199,8 +199,7 @@ ES modules are resolved and cached as URLs. This means that special characters must be [percent-encoded][], such as `#` with `%23` and `?` with `%3F`. `file:`, `node:`, and `data:` URL schemes are supported. A specifier like -`'https://example.com/app.js'` is not supported natively in Node.js unless using -a [custom HTTPS loader][]. +`'https://example.com/app.js'` is not supported natively in Node.js. #### `file:` URLs @@ -493,8 +492,6 @@ resolutions are subject to the permitted exports resolutions within the package. * This can result in synchronous file-system operations, which can impact performance similarly to `require.resolve`. -* This feature is not available within custom loaders (it would - create a deadlock). **Non-standard API**: @@ -1316,8 +1313,8 @@ _isImports_, _conditions_) ### Customizing ESM specifier resolution algorithm [Module customization hooks][] provide a mechanism for customizing the ESM -specifier resolution algorithm. An example that provides CommonJS-style -resolution for ESM specifiers is [commonjs-extension-resolution-loader][]. +specifier resolution algorithm, for example to provide CommonJS-style +resolution for ESM specifiers. <!-- Note: The merve link should be kept in-sync with the deps version --> @@ -1360,8 +1357,6 @@ resolution for ESM specifiers is [commonjs-extension-resolution-loader][]. [`process.dlopen`]: process.md#processdlopenmodule-filename-flags [`require(esm)`]: modules.md#loading-ecmascript-modules-using-require [`url.fileURLToPath()`]: url.md#urlfileurltopathurl-options -[commonjs-extension-resolution-loader]: https://github.com/nodejs/loaders-test/tree/main/commonjs-extension-resolution-loader -[custom https loader]: module.md#import-from-https [import.meta.resolve]: #importmetaresolvespecifier [merve]: https://github.com/anonrig/merve/tree/v1.0.0 [percent-encoded]: url.md#percent-encoding-in-urls diff --git a/doc/api/fs.md b/doc/api/fs.md index 93e6e7c68a18..929ea3029576 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -265,7 +265,8 @@ added: v16.11.0 * `emitClose` {boolean} **Default:** `true` * `start` {integer} * `end` {integer} **Default:** `Infinity` - * `highWaterMark` {integer} **Default:** `64 * 1024` + * `highWaterMark` {integer} **Default:** `64 * 1024`, or the value set with + [`stream.setDefaultHighWaterMark()`][] * `signal` {AbortSignal|undefined} **Default:** `undefined` * Returns: {fs.ReadStream} @@ -781,7 +782,8 @@ added: v18.11.0 * `emitClose` {boolean} **Default:** `true` * `start` {integer} * `end` {integer} **Default:** `Infinity` - * `highWaterMark` {integer} **Default:** `64 * 1024` + * `highWaterMark` {integer} **Default:** `64 * 1024`, or the value set with + [`stream.setDefaultHighWaterMark()`][] * Returns: {readline.InterfaceConstructor} Convenience method to create a `readline` interface and stream over the file. @@ -3104,7 +3106,8 @@ changes: * `emitClose` {boolean} **Default:** `true` * `start` {integer} * `end` {integer} **Default:** `Infinity` - * `highWaterMark` {integer} **Default:** `64 * 1024` + * `highWaterMark` {integer} **Default:** `64 * 1024`, or the value set with + [`stream.setDefaultHighWaterMark()`][] * `fs` {Object|null} **Default:** `null` * `signal` {AbortSignal|null} **Default:** `null` * `windowsHandle` {bigint} A raw Win32 `HANDLE` value to read from, in place @@ -9787,6 +9790,7 @@ the file contents. [`path.matchesGlob()`]: path.md#pathmatchesglobpath-pattern [`statfs.bsize`]: #statfsbsize [`stream.getDefaultHighWaterMark()`]: stream.md#streamgetdefaulthighwatermarkobjectmode +[`stream.setDefaultHighWaterMark()`]: stream.md#streamsetdefaulthighwatermarkobjectmode-value [`stream/iter pipeTo()`]: stream_iter.md#pipetosource-transforms-writer-options [`stream/iter pull()`]: stream_iter.md#pullsource-transforms-options [`stream/iter pullSync()`]: stream_iter.md#pullsyncsource-transforms diff --git a/doc/api/globals.md b/doc/api/globals.md index f07ac97431b6..369b8ba93e15 100644 --- a/doc/api/globals.md +++ b/doc/api/globals.md @@ -1192,7 +1192,133 @@ only if the Node.js binary was compiled with including support for the added: v11.0.0 --> -The WHATWG `TextDecoder` class. See the [`TextDecoder`][] section. +An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API. + +```js +const decoder = new TextDecoder(); +const u8arr = new Uint8Array([72, 101, 108, 108, 111]); +console.log(decoder.decode(u8arr)); // Hello +``` + +### WHATWG supported encodings + +Per the [WHATWG Encoding Standard][], the encodings supported by the +`TextDecoder` API are outlined in the tables below. For each encoding, +one or more aliases may be used. + +Different Node.js build configurations support different sets of encodings. +(see [Internationalization][]) + +#### Encodings supported by default (with full ICU data) + +| Encoding | Aliases | +| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | +| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | +| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | +| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | +| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | +| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | +| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | +| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | +| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | +| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | +| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | +| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | +| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | +| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | +| `'koi8-u'` | `'koi8-ru'` | +| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | +| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | +| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | +| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | +| `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | +| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | +| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | +| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | +| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | +| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | +| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | +| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | +| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | +| `'gb18030'` | | +| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | +| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | +| `'iso-2022-jp'` | `'csiso2022jp'` | +| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | +| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | + +#### Encodings supported when Node.js is built with the `small-icu` option + +| Encoding | Aliases | +| ------------ | ------------------------------- | +| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | +| `'utf-16le'` | `'utf-16'` | +| `'utf-16be'` | | + +#### Encodings supported when ICU is disabled + +| Encoding | Aliases | +| ------------ | ------------------------------- | +| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | +| `'utf-16le'` | `'utf-16'` | + +The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] +is not supported. + +### `new TextDecoder([encoding[, options]])` + +* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance + supports. **Default:** `'utf-8'`. +* `options` {Object} + * `fatal` {boolean} `true` if decoding failures are fatal. + This option is not supported when ICU is disabled + (see [Internationalization][]). **Default:** `false`. + * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte + order mark in the decoded result. When `false`, the byte order mark will + be removed from the output. This option is only used when `encoding` is + `'utf-8'`, `'utf-16be'`, or `'utf-16le'`. **Default:** `false`. + +Creates a new `TextDecoder` instance. The `encoding` may specify one of the +supported encodings or an alias. + +The `TextDecoder` class is also available on the global object. + +### `textDecoder.decode([input[, options]])` + +* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView`, or + `TypedArray` instance containing the encoded data. +* `options` {Object} + * `stream` {boolean} `true` if additional chunks of data are expected. + **Default:** `false`. +* Returns: {string} + +Decodes the `input` and returns a string. If `options.stream` is `true`, any +incomplete byte sequences occurring at the end of the `input` are buffered +internally and emitted after the next call to `textDecoder.decode()`. + +If `textDecoder.fatal` is `true`, decoding errors that occur will result in a +`TypeError` being thrown. + +### `textDecoder.encoding` + +* Type: {string} + +The encoding supported by the `TextDecoder` instance. + +### `textDecoder.fatal` + +* Type: {boolean} + +The value will be `true` if decoding errors result in a `TypeError` being +thrown. + +### `textDecoder.ignoreBOM` + +* Type: {boolean} + +The value will be `true` if the decoding result will include the byte order +mark. ## Class: `TextDecoderStream` @@ -1214,7 +1340,51 @@ A browser-compatible implementation of [`TextDecoderStream`][]. added: v11.0.0 --> -The WHATWG `TextEncoder` class. See the [`TextEncoder`][] section. +An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All +instances of `TextEncoder` only support UTF-8 encoding. + +```js +const encoder = new TextEncoder(); +const uint8array = encoder.encode('this is some data'); +``` + +The `TextEncoder` class is also available on the global object. + +### `textEncoder.encode([input])` + +* `input` {string} The text to encode. **Default:** an empty string. +* Returns: {Uint8Array} + +UTF-8 encodes the `input` string and returns a `Uint8Array` containing the +encoded bytes. + +### `textEncoder.encodeInto(src, dest)` + +<!-- YAML +added: v12.11.0 +--> + +* `src` {string} The text to encode. +* `dest` {Uint8Array} The array to hold the encode result. +* Returns: {Object} + * `read` {number} The read Unicode code units of src. + * `written` {number} The written UTF-8 bytes of dest. + +UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object +containing the read Unicode code units and written UTF-8 bytes. + +```js +const encoder = new TextEncoder(); +const src = 'this is some data'; +const dest = new Uint8Array(10); +const { read, written } = encoder.encodeInto(src, dest); +``` + +### `textEncoder.encoding` + +* Type: {string} + +The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. ## Class: `TextEncoderStream` @@ -1476,9 +1646,11 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][]. [CommonJS modules]: modules.md [ECMAScript module]: esm.md [HTML Standard]: https://html.spec.whatwg.org/multipage/workers.html +[Internationalization]: intl.md [Navigator API]: https://html.spec.whatwg.org/multipage/system-state.html#the-navigator-object [RFC 5646]: https://www.rfc-editor.org/rfc/rfc5646.txt [Refable protocol]: process.md#processrefmayberefable +[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ [Web Crypto API]: webcrypto.md [`--experimental-eventsource`]: cli.md#--experimental-eventsource [`--experimental-web-worker`]: cli.md#--experimental-web-worker @@ -1510,9 +1682,7 @@ A browser-compatible implementation of [`WritableStreamDefaultWriter`][]. [`Request`]: #class-request [`Response`]: #class-response [`TextDecoderStream`]: webstreams.md#class-textdecoderstream -[`TextDecoder`]: util.md#class-utiltextdecoder [`TextEncoderStream`]: webstreams.md#class-textencoderstream -[`TextEncoder`]: util.md#class-utiltextencoder [`TransformStreamDefaultController`]: webstreams.md#class-transformstreamdefaultcontroller [`TransformStream`]: webstreams.md#class-transformstream [`URLPattern`]: url.md#class-urlpattern diff --git a/doc/api/http.md b/doc/api/http.md index af939001c9e5..42a7a59d69db 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -353,7 +353,10 @@ An object which contains arrays of sockets currently awaiting use by the agent when `keepAlive` is enabled. Do not modify. Sockets in the `freeSockets` list will be automatically destroyed and -removed from the array on `'timeout'`. +removed from the array on `'timeout'`. When a request would reuse a free +socket whose timeout has passed, for example because the event loop was blocked +and `'timeout'` could not be emitted in time, the agent destroys that socket +instead. ### `agent.getName([options])` @@ -2574,12 +2577,15 @@ Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. -### `response.writeContinue()` +### `response.writeContinue([callback])` <!-- YAML added: v0.3.0 --> +* `callback` {Function} Optional, called once the message has been written + to the socket. + Sends an HTTP/1.1 100 Continue message to the client, indicating that the request body should be sent. See the [`'checkContinue'`][] event on `Server`. @@ -2710,7 +2716,7 @@ been transmitted are equal or not. Attempting to set a header field name or value that contains invalid characters will result in a [`TypeError`][] being thrown. -### `response.writeInformation(statusCode[, headers][, callback])` +### `response.writeInformation(statusCode[, headers[, callback]])` <!-- YAML added: @@ -2741,14 +2747,18 @@ event on `http.ClientRequest`. response.writeInformation(110, { 'X-Progress': '50%' }); ``` -### `response.writeProcessing()` +### `response.writeProcessing([callback])` <!-- YAML added: v10.0.0 --> +* `callback` {Function} Optional, called once the message has been written + to the socket. + Sends an HTTP/1.1 102 Processing message to the client, indicating that -the request body should be sent. +the request has been received and is still being processed. This is +equivalent to `response.writeInformation(102, null, callback)`. ## Class: `http.IncomingMessage` @@ -3767,15 +3777,18 @@ changes: `readableHighWaterMark` and `writableHighWaterMark`. This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. **Default:** See [`stream.getDefaultHighWaterMark()`][]. - * `httpValidation` {string} Controls HTTP header value validation strictness - for incoming requests. Accepted values are: - * `'strict'`: Strictest validation; rejects any non-ASCII or control - characters in header values. - * `'relaxed'`: Allows a limited set of non-ASCII characters in header - values, aligning with the - [Fetch specification](https://fetch.spec.whatwg.org/). - * `'insecure'`: Disables all header value validation (equivalent to - `insecureHTTPParser: true`). + * `httpValidation` {string} Controls how strictly HTTP header values are + validated, both in incoming requests and in outgoing responses. Accepted + values are: + * `'strict'`: Rejects control characters other than horizontal tab, and + characters outside the `latin1` range. + * `'relaxed'`: Also allows control characters other than NUL, CR, and LF, + aligning with the [Fetch specification](https://fetch.spec.whatwg.org/). + * `'insecure'`: Equivalent to `insecureHTTPParser: true`. Incoming + requests are parsed with all [`--insecure-http-parser`][] leniency + flags, which disables their header value validation. Outgoing header + values are validated as in `'relaxed'` mode, so NUL, CR, and LF are + still rejected. Cannot be used together with `insecureHTTPParser`. **Default:** `'strict'`. * `insecureHTTPParser` {boolean} If set to `true`, it will use an HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. @@ -4097,15 +4110,18 @@ changes: request to. **Default:** `'localhost'`. * `hostname` {string} Alias for `host`. To support [`url.parse()`][], `hostname` will be used if both `host` and `hostname` are specified. - * `httpValidation` {string} Controls HTTP header value validation strictness - for outgoing requests. Accepted values are: - * `'strict'`: Strictest validation; rejects any non-ASCII or control - characters in header values. - * `'relaxed'`: Allows a limited set of non-ASCII characters in header - values, aligning with the - [Fetch specification](https://fetch.spec.whatwg.org/). - * `'insecure'`: Disables all header value validation (equivalent to - `insecureHTTPParser: true`). + * `httpValidation` {string} Controls how strictly HTTP header values are + validated, both in outgoing requests and in incoming responses. Accepted + values are: + * `'strict'`: Rejects control characters other than horizontal tab, and + characters outside the `latin1` range. + * `'relaxed'`: Also allows control characters other than NUL, CR, and LF, + aligning with the [Fetch specification](https://fetch.spec.whatwg.org/). + * `'insecure'`: Equivalent to `insecureHTTPParser: true`. Incoming + responses are parsed with all [`--insecure-http-parser`][] leniency + flags, which disables their header value validation. Outgoing header + values are validated as in `'relaxed'` mode, so NUL, CR, and LF are + still rejected. Cannot be used together with `insecureHTTPParser`. **Default:** `'strict'`. * `insecureHTTPParser` {boolean} If set to `true`, it will use an HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. @@ -5009,10 +5025,10 @@ const agent2 = new http.Agent({ proxyEnv: process.env }); [`response.writableFinished`]: #responsewritablefinished [`response.write()`]: #responsewritechunk-encoding-callback [`response.write(data, encoding)`]: #responsewritechunk-encoding-callback -[`response.writeContinue()`]: #responsewritecontinue +[`response.writeContinue()`]: #responsewritecontinuecallback [`response.writeEarlyHints()`]: #responsewriteearlyhintshints-callback [`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers -[`response.writeProcessing()`]: #responsewriteprocessing +[`response.writeProcessing()`]: #responsewriteprocessingcallback [`server.close()`]: #serverclosecallback [`server.headersTimeout`]: #serverheaderstimeout [`server.keepAliveTimeoutBuffer`]: #serverkeepalivetimeoutbuffer diff --git a/doc/api/http2.md b/doc/api/http2.md index ecaefb0e990d..7556c91783d1 100644 --- a/doc/api/http2.md +++ b/doc/api/http2.md @@ -1818,13 +1818,20 @@ used exclusively on HTTP/2 Servers. `Http2Stream` instances on the server provide additional methods such as `http2stream.pushStream()` and `http2stream.respond()` that are only relevant on the server. -#### `http2stream.additionalHeaders(headers)` +#### `http2stream.additionalHeaders(headers[, callback])` <!-- YAML added: v8.4.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67470 + description: Added the `callback` argument. --> * `headers` {HTTP/2 Headers Object} +* `callback` {Function} Optional, called once the `HEADERS` frame has been + written to the socket, or with an error if it could not be written. + * `err` {Error|null} Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. @@ -4904,6 +4911,45 @@ const server = http2.createServer((req, res) => { }); ``` +#### `response.setHeaders(headers)` + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +* `headers` {Headers|Map} + +Sets multiple header values for implicit headers. +`headers` must be an instance of [`Headers`][] or `Map`. +If a header already exists in the to-be-sent headers, +its value will be replaced. + +```js +const headers = new Headers({ foo: 'bar' }); +response.setHeaders(headers); +``` + +or + +```js +const headers = new Map([['foo', 'bar']]); +response.setHeaders(headers); +``` + +When headers have been set with [`response.setHeaders()`][], +they will be merged with any headers passed to [`response.writeHead()`][], +with the headers passed to [`response.writeHead()`][] given precedence. + +```js +// Returns content-type = text/plain +const server = http2.createServer((req, res) => { + const headers = new Headers({ 'Content-Type': 'text/html' }); + res.setHeaders(headers); + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end('ok'); +}); +``` + #### `response.setTimeout(msecs[, callback])` <!-- YAML @@ -5057,23 +5103,40 @@ Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory. `'drain'` will be emitted when the buffer is free again. -#### `response.writeContinue()` +#### `response.writeContinue([callback])` <!-- YAML added: v8.4.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67470 + description: Added the `callback` argument. --> +* `callback` {Function} Optional, called once the informational headers + have been written to the socket, or with an error if they could not be + written. It is not called if nothing is sent. + * `err` {Error|null} + Sends a status `100 Continue` to the client, indicating that the request body should be sent. See the [`'checkContinue'`][] event on `Http2Server` and `Http2SecureServer`. -#### `response.writeEarlyHints(hints)` +#### `response.writeEarlyHints(hints[, callback])` <!-- YAML added: v18.11.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67470 + description: Added the `callback` argument. --> * `hints` {Object} +* `callback` {Function} Optional, called once the informational headers + have been written to the socket, or with an error if they could not be + written. It is not called if nothing is sent. + * `err` {Error|null} Sends a status `103 Early Hints` to the client with a Link header, indicating that the user agent can preload/preconnect the linked resources. @@ -5097,12 +5160,16 @@ response.writeEarlyHints({ }); ``` -#### `response.writeInformation(statusCode[, headers])` +#### `response.writeInformation(statusCode[, headers[, callback]])` <!-- YAML added: - v26.2.0 - v24.18.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67470 + description: Added the `callback` argument. --> * `statusCode` {number} An HTTP 1xx informational status code, between `100` @@ -5110,6 +5177,10 @@ added: allowed in HTTP/2. * `headers` {Object} An optional object of headers to send with the informational response. +* `callback` {Function} Optional, called once the informational headers + have been written to the socket, or with an error if they could not be + written. It is not called if nothing is sent. + * `err` {Error|null} Sends an arbitrary HTTP 1xx informational response, equivalent in HTTP/2 to a `HEADERS` frame whose `:status` pseudo-header is a 1xx code. May be called @@ -5302,6 +5373,7 @@ you need to implement any fall-back behavior yourself. [`Duplex`]: stream.md#class-streamduplex [`ERR_HTTP2_STREAM_ABORTED`]: errors.md#err_http2_stream_aborted [`ERR_HTTP2_STREAM_ERROR`]: errors.md#err_http2_stream_error +[`Headers`]: globals.md#class-headers [`Http2ServerRequest`]: #class-http2http2serverrequest [`Http2ServerResponse`]: #class-http2http2serverresponse [`Http2Session` and Sockets]: #http2session-and-sockets @@ -5330,12 +5402,13 @@ you need to implement any fall-back behavior yourself. [`request.socket`]: #requestsocket [`response.end()`]: #responseenddata-encoding-callback [`response.setHeader()`]: #responsesetheadername-value +[`response.setHeaders()`]: #responsesetheadersheaders [`response.socket`]: #responsesocket [`response.writableEnded`]: #responsewritableended [`response.write()`]: #responsewritechunk-encoding-callback [`response.write(data, encoding)`]: http.md#responsewritechunk-encoding-callback -[`response.writeContinue()`]: #responsewritecontinue -[`response.writeEarlyHints()`]: #responsewriteearlyhintshints +[`response.writeContinue()`]: #responsewritecontinuecallback +[`response.writeEarlyHints()`]: #responsewriteearlyhintshints-callback [`response.writeHead()`]: #responsewriteheadstatuscode-statusmessage-headers [`server.close()`]: #serverclosecallback [`server.maxHeadersCount`]: http.md#servermaxheaderscount diff --git a/doc/api/https.md b/doc/api/https.md index d9de65813733..2d3426778eb8 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -474,7 +474,8 @@ Makes a request to a secure web server. The following additional `options` from [`tls.connect()`][] are also accepted: `ca`, `cert`, `ciphers`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, `pfx`, `rejectUnauthorized`, `secureOptions`, -`secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. +`secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`, +`allowRenegotiation`. `options` can be an object, a string, or a [`URL`][] object. If `options` is a string, it is automatically parsed with [`new URL()`][]. If it is a [`URL`][] diff --git a/doc/api/intl.md b/doc/api/intl.md index e16c353db14b..d073146f92c7 100644 --- a/doc/api/intl.md +++ b/doc/api/intl.md @@ -20,7 +20,7 @@ programs. Some of them are: * The [WHATWG URL parser][]'s [internationalized domain names][] (IDNs) support * [`require('node:buffer').transcode()`][] * More accurate [REPL][] line editing -* [`require('node:util').TextDecoder`][] +* [`TextDecoder`][] * [`RegExp` Unicode Property Escapes][] Node.js and the underlying V8 engine use @@ -57,7 +57,7 @@ option: | [WHATWG URL Parser][] | partial (no IDN support) | full | full | full | | [`require('node:buffer').transcode()`][] | none (function does not exist) | full | full | full | | [REPL][] | partial (inaccurate line editing) | full | full | full | -| [`require('node:util').TextDecoder`][] | partial (basic encodings support) | partial/full (depends on OS) | partial (Unicode-only) | full | +| [`TextDecoder`][] | partial (basic encodings support) | partial/full (depends on OS) | partial (Unicode-only) | full | | [`RegExp` Unicode Property Escapes][] | none (invalid `RegExp` error) | full | full | full | The "(not locale-aware)" designation denotes that the function carries out its @@ -231,8 +231,8 @@ to be helpful: [`String.prototype.normalize()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize [`String.prototype.toLowerCase()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase [`String.prototype.toUpperCase()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase +[`TextDecoder`]: globals.md#class-textdecoder [`require('node:buffer').transcode()`]: buffer.md#buffertranscodesource-fromenc-toenc -[`require('node:util').TextDecoder`]: util.md#class-utiltextdecoder [btest402]: https://github.com/srl295/btest402 [full-icu]: https://www.npmjs.com/package/full-icu [internationalized domain names]: https://en.wikipedia.org/wiki/Internationalized_domain_name diff --git a/doc/api/module.md b/doc/api/module.md index f86167e8d44f..c8ad7818a52e 100644 --- a/doc/api/module.md +++ b/doc/api/module.md @@ -176,56 +176,6 @@ isBuiltin('fs'); // true isBuiltin('wss'); // false ``` -## `module.register(specifier[, parentURL][, options])` - -<!-- YAML -added: - - v20.6.0 - - v18.19.0 -deprecated: - - v25.9.0 - - v24.15.0 -changes: - - version: v26.0.0 - pr-url: https://github.com/nodejs/node/pull/62401 - description: Runtime deprecation (DEP0205). - - version: - - v23.6.1 - - v22.13.1 - - v20.18.2 - pr-url: https://github.com/nodejs-private/node-private/pull/629 - description: Using this feature with the permission model enabled requires - passing `--allow-worker`. - - version: - - v20.8.0 - - v18.19.0 - pr-url: https://github.com/nodejs/node/pull/49655 - description: Add support for WHATWG URL instances. ---> - -> Stability: 0 - Deprecated: Use [`module.registerHooks()`][] instead. - -* `specifier` {string|URL} Customization hooks to be registered; this should be - the same string that would be passed to `import()`, except that if it is - relative, it is resolved relative to `parentURL`. -* `parentURL` {string|URL} If you want to resolve `specifier` relative to a base - URL, such as `import.meta.url`, you can pass that URL here. **Default:** - `'data:'` -* `options` {Object} - * `parentURL` {string|URL} If you want to resolve `specifier` relative to a - base URL, such as `import.meta.url`, you can pass that URL here. This - property is ignored if the `parentURL` is supplied as the second argument. - **Default:** `'data:'` - * `data` {any} Any arbitrary, cloneable JavaScript value to pass into the - [`initialize`][] hook. - * `transferList` {Object\[]} [transferable objects][] to be passed into the - `initialize` hook. - -Register a module that exports [hooks][] that customize Node.js module -resolution and loading behavior. See [Customization hooks][]. - -This feature requires `--allow-worker` if used with the [Permission Model][]. - ## `module.registerHooks(options)` <!-- YAML @@ -253,7 +203,7 @@ changes: Register [hooks][] that customize Node.js module resolution and loading behavior. See [Customization hooks][]. The returned object can be used to -[deregister the hooks][deregistration of synchronous customization hooks]. +[deregister the hooks][deregistration of customization hooks]. ## `module.stripTypeScriptTypes(code[, options])` @@ -464,10 +414,12 @@ no-op, and the directory is not created if it is missing. ### Limitations of the compile cache -Currently when using the compile cache with [V8 JavaScript code coverage][], the -coverage being collected by V8 may be less precise in functions that are -deserialized from the code cache. It's recommended to turn this off when -running tests to generate precise coverage. +V8 cannot collect block-level [V8 JavaScript code coverage][] for functions that +are deserialized from the code cache. The compile cache is therefore disabled +when coverage collection starts with the process, through +[`NODE_V8_COVERAGE=dir`][] or [`--experimental-test-coverage`][]. Coverage that +is started later, for example through the inspector, may be less precise in +functions that were already deserialized from the code cache. Compilation cache generated by one version of Node.js can not be reused by a different version of Node.js. Cache generated by different versions of Node.js will be stored @@ -525,7 +477,8 @@ The following constants are returned as the `status` field in the object returne <td><code>DISABLED</code></td> <td> Node.js cannot enable the compile cache because the environment variable - <code>NODE_DISABLE_COMPILE_CACHE=1</code> has been set. + <code>NODE_DISABLE_COMPILE_CACHE=1</code> has been set, or because V8 + coverage is being collected. </td> </tr> </table> @@ -668,30 +621,17 @@ changes: <!-- type=misc --> -Node.js currently supports two types of module customization hooks: - -1. [`module.registerHooks(options)`][`module.registerHooks()`]: takes synchronous hook - functions that are run directly on the thread where the modules are loaded. -2. [`module.register(specifier[, parentURL][, options])`][`register`]: takes specifier to a - module that exports asynchronous hook functions. The functions are run on a - separate loader thread. - -The asynchronous hooks incur extra overhead from inter-thread communication, -and have [several caveats][caveats of asynchronous customization hooks] especially -when customizing CommonJS modules in the module graph. -In most cases, it's recommended to use synchronous hooks via `module.registerHooks()` -for simplicity. - -### Synchronous customization hooks +Node.js supports module customization hooks registered with +[`module.registerHooks()`][]. > Stability: 1.2 - Release candidate <i id="enabling_module_customization_hooks"></i> -#### Registration of synchronous customization hooks +### Registration of customization hooks -To register synchronous customization hooks, use [`module.registerHooks()`][], which -takes [synchronous hook functions][] directly in-line. +To register customization hooks, use [`module.registerHooks()`][], which +takes [hook functions][] directly in-line. ```mjs // register-hooks.js @@ -711,7 +651,7 @@ registerHooks({ }); ``` -##### Registering hooks before application code runs with flags +#### Registering hooks before application code runs with flags The hooks can be registered before the application code is run by using the [`--import`][] or [`--require`][] flag: @@ -736,7 +676,7 @@ Using `--import` or `--require` ensures that the hooks are registered before any application code is loaded, including the entry point of the application and for any worker threads by default as well. -##### Registering hooks before application code runs programmatically +#### Registering hooks before application code runs programmatically Alternatively, `registerHooks()` can be called from the entry point. @@ -751,7 +691,7 @@ module. ```mjs import { registerHooks } from 'node:module'; -registerHooks({ /* implementation of synchronous hooks */ }); +registerHooks({ /* implementation of hooks */ }); // If loaded using static import, the hooks would not be applied when loading // my-app.mjs, because statically imported modules are all executed before its @@ -765,7 +705,7 @@ await import('./my-app.mjs'); ```cjs const { registerHooks } = require('node:module'); -registerHooks({ /* implementation of synchronous hooks */ }); +registerHooks({ /* implementation of hooks */ }); import('./my-app.mjs'); // Or, if my-app.mjs does not have top-level await or it's a CommonJS module, @@ -773,7 +713,7 @@ import('./my-app.mjs'); // require('./my-app.mjs'); ``` -##### Registering hooks before application code runs with a `data:` URL +#### Registering hooks before application code runs with a `data:` URL Alternatively, inline JavaScript code can be embedded in `data:` URLs to register the hooks before the application code runs. For example, @@ -782,7 +722,7 @@ the hooks before the application code runs. For example, node --import 'data:text/javascript,import {registerHooks} from "node:module"; registerHooks(/* hooks code */);' ./my-app.js ``` -#### Convention of hooks and chaining +### Convention of hooks and chaining Hooks are part of a chain, even if that chain consists of only one custom (user-provided) hook and the default hook, which is always present. @@ -833,14 +773,13 @@ hook to signal that the chain is intentionally ending at your hook. If a hook should be applied when loading other hook modules, the other hook modules should be loaded after the hook is registered. -#### Deregistration of synchronous customization hooks +### Deregistration of customization hooks The object returned by `registerHooks()` has a `deregister()` method that can be used to remove the hooks from the chain. Once `deregister()` is called, the hooks will no longer be invoked during module resolution or loading. -This is currently only available for synchronous hooks registered via `registerHooks()`, not for asynchronous -hooks registered via `module.register()`. +This is available for hooks registered via `registerHooks()`. ```mjs import { registerHooks } from 'node:module'; @@ -890,7 +829,7 @@ hooks.deregister(); require('./another-module.cjs'); ``` -#### Hook functions accepted by `module.registerHooks()` +### Hook functions accepted by `module.registerHooks()` <!-- YAML added: @@ -898,7 +837,7 @@ added: - v22.15.0 --> -The `module.registerHooks()` method accepts the following synchronous hook functions. +The `module.registerHooks()` method accepts the following hook functions. ```mjs function resolve(specifier, context, nextResolve) { @@ -910,16 +849,16 @@ function load(url, context, nextLoad) { } ``` -Synchronous hooks are run in the same thread and the same [realm][] where the modules -are loaded, the code in the hook function can pass values to the modules being referenced -directly via global variables or other shared states. +Hooks are run in the same [realm][] as the modules being loaded, so the code in the +hook function can pass values to the modules being referenced directly via global +variables or other shared states. -Unlike the asynchronous hooks, the synchronous hooks are not inherited into child worker -threads by default, though if the hooks are registered using a file preloaded by -[`--import`][] or [`--require`][], child worker threads can inherit the preloaded scripts -via `process.execArgv` inheritance. See [the documentation of `Worker`][] for details. +Hooks are not inherited into child worker threads by default. If the hooks are +registered using a file preloaded by [`--import`][] or [`--require`][], child worker threads +can inherit the preloaded scripts via `process.execArgv` inheritance. See +[the documentation of `Worker`][] for details. -#### Synchronous `resolve(specifier, context, nextResolve)` +### `resolve(specifier, context, nextResolve)` <!-- YAML changes: @@ -1007,7 +946,7 @@ function resolve(specifier, context, nextResolve) { registerHooks({ resolve }); ``` -#### Synchronous `load(url, context, nextLoad)` +### `load(url, context, nextLoad)` <!-- YAML changes: @@ -1076,7 +1015,7 @@ registerHooks({ load }); In a more advanced scenario, this can also be used to transform an unsupported source to a supported one (see [Examples](#examples) below). -##### Accepted final formats returned by `load` +#### Accepted final formats returned by `load` The final value of `format` must be one of the following: @@ -1100,523 +1039,7 @@ not possible to replace the value of a Node.js builtin (core) module. * The specific {TypedArray} object is a {Uint8Array}. If the source value of a text-based format (i.e., `'json'`, `'module'`) -is not a string, it is converted to a string using [`util.TextDecoder`][]. - -### Asynchronous customization hooks - -> Stability: 1.1 - Active Development - -#### Caveats of asynchronous customization hooks - -The asynchronous customization hooks have many caveats and it is uncertain if their -issues can be resolved. Users are encouraged to use the synchronous customization hooks -via `module.registerHooks()` instead to avoid these caveats. - -* Asynchronous hooks run on a separate thread, so the hook functions cannot directly - mutate the global state of the modules being customized. It's typical to use message - channels and atomics to pass data between the two or to affect control flows. - See [Communication with asynchronous module customization hooks](#communication-with-asynchronous-module-customization-hooks). -* Asynchronous hooks do not affect all `require()` calls in the module graph. - * Custom `require` functions created using `module.createRequire()` are not - affected. - * If the asynchronous `load` hook does not override the `source` for CommonJS modules - that go through it, the child modules loaded by those CommonJS modules via built-in - `require()` would not be affected by the asynchronous hooks either. -* There are several caveats that the asynchronous hooks need to handle when - customizing CommonJS modules. See [asynchronous `resolve` hook][] and - [asynchronous `load` hook][] for details. -* When `require()` calls inside CommonJS modules are customized by asynchronous hooks, - Node.js may need to load the source code of the CommonJS module multiple times to maintain - compatibility with existing CommonJS monkey-patching. If the module code changes between - loads, this may lead to unexpected behaviors. - * As a side effect, if both asynchronous hooks and synchronous hooks are registered and the - asynchronous hooks choose to customize the CommonJS module, the synchronous hooks may be - invoked multiple times for the `require()` calls in that CommonJS module. - -#### Registration of asynchronous customization hooks - -Asynchronous customization hooks are registered using [`module.register()`][`register`] which takes -a path or URL to another module that exports the [asynchronous hook functions][]. - -Similar to `registerHooks()`, `register()` can be called in a module preloaded by `--import` or -`--require`, or called directly within the entry point. - -```mjs -// Use module.register() to register asynchronous hooks in a dedicated thread. -import { register } from 'node:module'; -register('./hooks.mjs', import.meta.url); - -// If my-app.mjs is loaded statically here as `import './my-app.mjs'`, since ESM -// dependencies are evaluated before the module that imports them, -// it's loaded _before_ the hooks are registered above and won't be affected. -// To ensure the hooks are applied, dynamic import() must be used to load ESM -// after the hooks are registered. -import('./my-app.mjs'); -``` - -```cjs -const { register } = require('node:module'); -const { pathToFileURL } = require('node:url'); -// Use module.register() to register asynchronous hooks in a dedicated thread. -register('./hooks.mjs', pathToFileURL(__filename)); - -import('./my-app.mjs'); -``` - -In `hooks.mjs`: - -```mjs -// hooks.mjs -export async function resolve(specifier, context, nextResolve) { - /* implementation */ -} -export async function load(url, context, nextLoad) { - /* implementation */ -} -``` - -Unlike synchronous hooks, the asynchronous hooks would not run for these modules loaded in the file -that calls `register()`: - -```mjs -// register-hooks.js -import { register, createRequire } from 'node:module'; -register('./hooks.mjs', import.meta.url); - -// Asynchronous hooks does not affect modules loaded via custom require() -// functions created by module.createRequire(). -const userRequire = createRequire(import.meta.filename); -userRequire('./my-app-2.cjs'); // Hooks won't affect this -``` - -```cjs -// register-hooks.js -const { register, createRequire } = require('node:module'); -const { pathToFileURL } = require('node:url'); -register('./hooks.mjs', pathToFileURL(__filename)); - -// Asynchronous hooks does not affect modules loaded via built-in require() -// in the module calling `register()` -require('./my-app-2.cjs'); // Hooks won't affect this -// .. or custom require() functions created by module.createRequire(). -const userRequire = createRequire(__filename); -userRequire('./my-app-3.cjs'); // Hooks won't affect this -``` - -Asynchronous hooks can also be registered using a `data:` URL with the `--import` flag: - -```bash -node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("my-instrumentation", pathToFileURL("./"));' ./my-app.js -``` - -#### Chaining of asynchronous customization hooks - -Chaining of `register()` work similarly to `registerHooks()`. If synchronous and asynchronous -hooks are mixed, the synchronous hooks are always run first before the asynchronous -hooks start running, that is, in the last synchronous hook being run, its next -hook includes invocation of the asynchronous hooks. - -```mjs -// entrypoint.mjs -import { register } from 'node:module'; - -register('./foo.mjs', import.meta.url); -register('./bar.mjs', import.meta.url); -await import('./my-app.mjs'); -``` - -```cjs -// entrypoint.cjs -const { register } = require('node:module'); -const { pathToFileURL } = require('node:url'); - -const parentURL = pathToFileURL(__filename); -register('./foo.mjs', parentURL); -register('./bar.mjs', parentURL); -import('./my-app.mjs'); -``` - -If `foo.mjs` and `bar.mjs` define a `resolve` hook, they will be called like so -(note the right-to-left, starting with `./bar.mjs`, then `./foo.mjs`, then the Node.js default): - -Node.js default ← `./foo.mjs` ← `./bar.mjs` - -When using the asynchronous hooks, the registered hooks also affect subsequent -`register` calls, which takes care of loading hook modules. In the example above, -`bar.mjs` will be resolved and loaded via the hooks registered by `foo.mjs` -(because `foo`'s hooks will have already been added to the chain). This allows -for things like writing hooks in non-JavaScript languages, so long as -earlier registered hooks transpile into JavaScript. - -The `register()` method cannot be called from the thread running the hook module that -exports the asynchronous hooks or its dependencies. - -#### Communication with asynchronous module customization hooks - -Asynchronous hooks run on a dedicated thread, separate from the main -thread that runs application code. This means mutating global variables won't -affect the other thread(s), and message channels must be used to communicate -between the threads. - -The `register` method can be used to pass data to an [`initialize`][] hook. The -data passed to the hook may include transferable objects like ports. - -```mjs -import { register } from 'node:module'; -import { MessageChannel } from 'node:worker_threads'; - -// This example demonstrates how a message channel can be used to -// communicate with the hooks, by sending `port2` to the hooks. -const { port1, port2 } = new MessageChannel(); - -port1.on('message', (msg) => { - console.log(msg); -}); -port1.unref(); - -register('./my-hooks.mjs', { - parentURL: import.meta.url, - data: { number: 1, port: port2 }, - transferList: [port2], -}); -``` - -```cjs -const { register } = require('node:module'); -const { pathToFileURL } = require('node:url'); -const { MessageChannel } = require('node:worker_threads'); - -// This example showcases how a message channel can be used to -// communicate with the hooks, by sending `port2` to the hooks. -const { port1, port2 } = new MessageChannel(); - -port1.on('message', (msg) => { - console.log(msg); -}); -port1.unref(); - -register('./my-hooks.mjs', { - parentURL: pathToFileURL(__filename), - data: { number: 1, port: port2 }, - transferList: [port2], -}); -``` - -A hook can send messages to the thread that registered it at any time, as -above. It must not block on a reply from that thread: resolution and loading -are synchronous from the perspective of the thread that triggered them, so that -thread is blocked until the hook settles and cannot answer in the meantime. -Hooks can otherwise be fully asynchronous; it is only a reply over this -message channel that cannot be awaited. - -#### Asynchronous hooks accepted by `module.register()` - -<!-- YAML -added: v8.8.0 -changes: - - version: - - v20.6.0 - - v18.19.0 - pr-url: https://github.com/nodejs/node/pull/48842 - description: Added `initialize` hook to replace `globalPreload`. - - version: - - v18.6.0 - - v16.17.0 - pr-url: https://github.com/nodejs/node/pull/42623 - description: Add support for chaining loaders. - - version: v16.12.0 - pr-url: https://github.com/nodejs/node/pull/37468 - description: Removed `getFormat`, `getSource`, `transformSource`, and - `globalPreload`; added `load` hook and `getGlobalPreload` hook. ---> - -The [`register`][] method can be used to register a module that exports a set of -hooks. The hooks are functions that are called by Node.js to customize the -module resolution and loading process. The exported functions must have specific -names and signatures, and they must be exported as named exports. - -```mjs -export async function initialize({ number, port }) { - // Receives data from `register`. -} - -export async function resolve(specifier, context, nextResolve) { - // Take an `import` or `require` specifier and resolve it to a URL. -} - -export async function load(url, context, nextLoad) { - // Take a resolved URL and return the source code to be evaluated. -} -``` - -Asynchronous hooks are run in a separate thread, isolated from the main thread where -application code runs. That means it is a different [realm][]. The hooks thread -may be terminated by the main thread at any time, so do not depend on -asynchronous operations (like `console.log`) to complete. They are inherited into -child workers by default. - -#### `initialize()` - -<!-- YAML -added: - - v20.6.0 - - v18.19.0 ---> - -* `data` {any} The data from `register(loader, import.meta.url, { data })`. - -The `initialize` hook is only accepted by [`register`][]. `registerHooks()` does -not support nor need it since initialization done for synchronous hooks can be run -directly before the call to `registerHooks()`. - -The `initialize` hook provides a way to define a custom function that runs in -the hooks thread when the hooks module is initialized. Initialization happens -when the hooks module is registered via [`register`][]. - -This hook can receive data from a [`register`][] invocation, including -ports and other transferable objects. The return value of `initialize` can be a -{Promise}, in which case it will be awaited before the main application thread -execution resumes. - -Module customization code: - -```mjs -// path-to-my-hooks.js - -export async function initialize({ number, port }) { - port.postMessage(`increment: ${number + 1}`); -} -``` - -Caller code: - -```mjs -import assert from 'node:assert'; -import { register } from 'node:module'; -import { MessageChannel } from 'node:worker_threads'; - -// This example showcases how a message channel can be used to communicate -// between the main (application) thread and the hooks running on the hooks -// thread, by sending `port2` to the `initialize` hook. -const { port1, port2 } = new MessageChannel(); - -port1.on('message', (msg) => { - assert.strictEqual(msg, 'increment: 2'); -}); -port1.unref(); - -register('./path-to-my-hooks.js', { - parentURL: import.meta.url, - data: { number: 1, port: port2 }, - transferList: [port2], -}); -``` - -```cjs -const assert = require('node:assert'); -const { register } = require('node:module'); -const { pathToFileURL } = require('node:url'); -const { MessageChannel } = require('node:worker_threads'); - -// This example showcases how a message channel can be used to communicate -// between the main (application) thread and the hooks running on the hooks -// thread, by sending `port2` to the `initialize` hook. -const { port1, port2 } = new MessageChannel(); - -port1.on('message', (msg) => { - assert.strictEqual(msg, 'increment: 2'); -}); -port1.unref(); - -register('./path-to-my-hooks.js', { - parentURL: pathToFileURL(__filename), - data: { number: 1, port: port2 }, - transferList: [port2], -}); -``` - -#### Asynchronous `resolve(specifier, context, nextResolve)` - -<!-- YAML -changes: - - version: - - v21.0.0 - - v20.10.0 - - v18.19.0 - pr-url: https://github.com/nodejs/node/pull/50140 - description: The property `context.importAssertions` is replaced with - `context.importAttributes`. Using the old name is still - supported and will emit an experimental warning. - - version: - - v18.6.0 - - v16.17.0 - pr-url: https://github.com/nodejs/node/pull/42623 - description: Add support for chaining resolve hooks. Each hook must either - call `nextResolve()` or include a `shortCircuit` property set to `true` - in its return. - - version: - - v17.1.0 - - v16.14.0 - pr-url: https://github.com/nodejs/node/pull/40250 - description: Add support for import assertions. ---> - -* `specifier` {string} -* `context` {Object} - * `conditions` {string\[]} Export conditions of the relevant `package.json` - * `importAttributes` {Object} An object whose key-value pairs represent the - attributes for the module to import - * `parentURL` {string|undefined} The module importing this one, or undefined - if this is the Node.js entry point -* `nextResolve` {Function} The subsequent `resolve` hook in the chain, or the - Node.js default `resolve` hook after the last user-supplied `resolve` hook - * `specifier` {string} - * `context` {Object|undefined} When omitted, the defaults are provided. When provided, defaults - are merged in with preference to the provided properties. -* Returns: {Object|Promise} The asynchronous version takes either an object containing the - following properties, or a `Promise` that will resolve to such an object. - * `format` {string|null|undefined} A hint to the `load` hook (it might be ignored). It can be a - module format (such as `'commonjs'` or `'module'`) or an arbitrary value like `'css'` or - `'yaml'`. - * `importAttributes` {Object|undefined} The import attributes to use when - caching the module (optional; if excluded the input will be used) - * `shortCircuit` {undefined|boolean} A signal that this hook intends to - terminate the chain of `resolve` hooks. **Default:** `false` - * `url` {string} The absolute URL to which this input resolves - -The asynchronous version works similarly to the synchronous version, only that the -`nextResolve` function returns a `Promise`, and the `resolve` hook itself can return a `Promise`. - -> **Warning** In the case of the asynchronous version, despite support for returning -> promises and async functions, calls to `resolve` may still block the main thread which -> can impact performance. - -> **Warning** The `resolve` hook invoked for `require()` calls inside CommonJS modules -> customized by asynchronous hooks does not receive the original specifier passed to -> `require()`. Instead, it receives a URL already fully resolved using the default -> CommonJS resolution. - -> **Warning** In the CommonJS modules that are customized by the asynchronous customization hooks, -> `require.resolve()` and `require()` will use `"import"` export condition instead of -> `"require"`, which may cause unexpected behaviors when loading dual packages. - -```mjs -export async function resolve(specifier, context, nextResolve) { - // When calling `defaultResolve`, the arguments can be modified. For example, - // to change the specifier or add conditions. - if (specifier.includes('foo')) { - specifier = specifier.replace('foo', 'bar'); - return nextResolve(specifier, { - ...context, - conditions: [...context.conditions, 'another-condition'], - }); - } - - // The hook can also skips default resolution and provide a custom URL. - if (specifier === 'special-module') { - return { - url: 'file:///path/to/special-module.mjs', - format: 'module', - shortCircuit: true, // This is mandatory if not calling nextResolve(). - }; - } - - // If no customization is needed, defer to the next hook in the chain which would be the - // Node.js default resolve if this is the last user-specified loader. - return nextResolve(specifier); -} -``` - -#### Asynchronous `load(url, context, nextLoad)` - -<!-- YAML -changes: - - version: v22.6.0 - pr-url: https://github.com/nodejs/node/pull/56350 - description: Add support for `source` with format `commonjs-typescript` and `module-typescript`. - - version: v20.6.0 - pr-url: https://github.com/nodejs/node/pull/47999 - description: Add support for `source` with format `commonjs`. - - version: - - v18.6.0 - - v16.17.0 - pr-url: https://github.com/nodejs/node/pull/42623 - description: Add support for chaining load hooks. Each hook must either - call `nextLoad()` or include a `shortCircuit` property set to `true` in - its return. ---> - -* `url` {string} The URL returned by the `resolve` chain -* `context` {Object} - * `conditions` {string\[]} Export conditions of the relevant `package.json` - * `format` {string|null|undefined} The format optionally supplied by the - `resolve` hook chain. This can be any string value as an input; input values do not need to - conform to the list of acceptable return values described below. - * `importAttributes` {Object} -* `nextLoad` {Function} The subsequent `load` hook in the chain, or the - Node.js default `load` hook after the last user-supplied `load` hook - * `url` {string} - * `context` {Object|undefined} When omitted, defaults are provided. When provided, defaults are - merged in with preference to the provided properties. In the default `nextLoad`, if - the module pointed to by `url` does not have explicit module type information, - `context.format` is mandatory. - <!-- TODO(joyeecheung): make it at least optionally non-mandatory by allowing - JS-style/TS-style module detection when the format is simply unknown --> -* Returns: {Promise} The asynchronous version takes either an object containing the - following properties, or a `Promise` that will resolve to such an object. - * `format` {string} - * `shortCircuit` {undefined|boolean} A signal that this hook intends to - terminate the chain of `load` hooks. **Default:** `false` - * `source` {string|ArrayBuffer|TypedArray} The source for Node.js to evaluate - -> **Warning**: The asynchronous `load` hook and namespaced exports from CommonJS -> modules are incompatible. Attempting to use them together will result in an empty -> object from the import. This may be addressed in the future. This does not apply -> to the synchronous `load` hook, in which case exports can be used as usual. - -The asynchronous version works similarly to the synchronous version, though -when using the asynchronous `load` hook, omitting vs providing a `source` for -`'commonjs'` has very different effects: - -* When a `source` is provided, all `require` calls from this module will be - processed by the ESM loader with registered `resolve` and `load` hooks; all - `require.resolve` calls from this module will be processed by the ESM loader - with registered `resolve` hooks; only a subset of the CommonJS API will be - available (e.g. no `require.extensions`, no `require.cache`, no - `require.resolve.paths`) and monkey-patching on the CommonJS module loader - will not apply. -* If `source` is undefined or `null`, it will be handled by the CommonJS module - loader and `require`/`require.resolve` calls will not go through the - registered hooks. This behavior for nullish `source` is temporary — in the - future, nullish `source` will not be supported. - -These caveats do not apply to the synchronous `load` hook, in which case -the complete set of CommonJS APIs available to the customized CommonJS -modules, and `require`/`require.resolve` always go through the registered -hooks. - -The Node.js internal asynchronous `load` implementation, which is the value of `next` for the -last hook in the `load` chain, returns `null` for `source` when `format` is -`'commonjs'` for backward compatibility. Here is an example hook that would -opt-in to using the non-default behavior: - -```mjs -import { readFile } from 'node:fs/promises'; - -// Asynchronous version accepted by module.register(). This fix is not needed -// for the synchronous version accepted by module.registerHooks(). -export async function load(url, context, nextLoad) { - const result = await nextLoad(url, context); - if (result.format === 'commonjs') { - result.source ??= await readFile(new URL(result.responseURL ?? url)); - } - return result; -} -``` - -This doesn't apply to the synchronous `load` hook either, in which case the -`source` returned contains source code loaded by the next hook, regardless -of module format. +is not a string, it is converted to a string using [`TextDecoder`][]. ### Examples @@ -1624,59 +1047,6 @@ The various module customization hooks can be used together to accomplish wide-ranging customizations of the Node.js code loading and evaluation behaviors. -#### Import from HTTPS - -The hook below registers hooks to enable rudimentary support for such -specifiers. While this may seem like a significant improvement to Node.js core -functionality, there are substantial downsides to actually using these hooks: -performance is much slower than loading files from disk, there is no caching, -and there is no security. - -```mjs -// https-hooks.mjs -import { get } from 'node:https'; - -export function load(url, context, nextLoad) { - // For JavaScript to be loaded over the network, we need to fetch and - // return it. - if (url.startsWith('https://')) { - return new Promise((resolve, reject) => { - get(url, (res) => { - let data = ''; - res.setEncoding('utf8'); - res.on('data', (chunk) => data += chunk); - res.on('end', () => resolve({ - // This example assumes all network-provided JavaScript is ES module - // code. - format: 'module', - shortCircuit: true, - source: data, - })); - }).on('error', (err) => reject(err)); - }); - } - - // Let Node.js handle all other URLs. - return nextLoad(url); -} -``` - -```mjs -// main.mjs -import { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js'; - -console.log(VERSION); -``` - -With the preceding hooks module, running -`node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjs` -prints the current version of CoffeeScript per the module at the URL in -`main.mjs`. - -<!-- TODO(joyeecheung): add an example on how to implement it with a fetchSync based on -workers and Atomics.wait() - or all these examples are too much to be put in the API -documentation already and should be put into a repository instead? --> - #### Transpilation Sources that are in formats Node.js doesn't understand can be converted into @@ -1685,58 +1055,6 @@ JavaScript using the [`load` hook][load hook]. This is less performant than transpiling source files before running Node.js; transpiler hooks should only be used for development and testing purposes. -##### Asynchronous version - -```mjs -// coffeescript-hooks.mjs -import { readFile } from 'node:fs/promises'; -import { findPackageJSON } from 'node:module'; -import coffeescript from 'coffeescript'; - -const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/; - -export async function load(url, context, nextLoad) { - if (extensionsRegex.test(url)) { - // CoffeeScript files can be either CommonJS or ES modules. Use a custom format - // to tell Node.js not to detect its module type. - const { source: rawSource } = await nextLoad(url, { ...context, format: 'coffee' }); - // This hook converts CoffeeScript source code into JavaScript source code - // for all imported CoffeeScript files. - const transformedSource = coffeescript.compile(rawSource.toString(), url); - - // To determine how Node.js would interpret the transpilation result, - // search up the file system for the nearest parent package.json file - // and read its "type" field. - return { - format: await getPackageType(url), - shortCircuit: true, - source: transformedSource, - }; - } - - // Let Node.js handle all other URLs. - return nextLoad(url, context); -} - -async function getPackageType(url) { - // `url` is only a file path during the first iteration when passed the - // resolved url from the load() hook - // an actual file path from load() will contain a file extension as it's - // required by the spec - // this simple truthy check for whether `url` contains a file extension will - // work for most projects but does not cover some edge-cases (such as - // extensionless files or a url ending in a trailing space) - const pJson = findPackageJSON(url); - - return readFile(pJson, 'utf8') - .then(JSON.parse) - .then((json) => json?.type) - .catch(() => undefined); -} -``` - -##### Synchronous version - ```mjs // coffeescript-sync-hooks.mjs import { readFileSync } from 'node:fs'; @@ -1807,9 +1125,8 @@ able to return an `format` known to Node.js even in the absence of an explicit t (if undefined) or `ERR_UNKNOWN_MODULE_FORMAT` (if it's not a known format listed in the [load hook][] documentation). -With the preceding hooks modules, running -`node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffee` -or `node --import ./coffeescript-sync-hooks.mjs ./main.coffee` +With the preceding hooks module, running +`node --import ./coffeescript-sync-hooks.mjs ./main.coffee` causes `main.coffee` to be turned into JavaScript after its source code is loaded from disk but before Node.js executes it; and so on for any `.coffee`, `.litcoffee` or `.coffee.md` files referenced via `import` statements of any @@ -1822,25 +1139,6 @@ The previous two examples defined `load` hooks. This is an example of a which specifiers to override to other URLs (this is a very simplistic implementation of a small subset of the "import maps" specification). -##### Asynchronous version - -```mjs -// import-map-hooks.js -import fs from 'node:fs/promises'; - -const { imports } = JSON.parse(await fs.readFile('import-map.json')); - -export async function resolve(specifier, context, nextResolve) { - if (Object.hasOwn(imports, specifier)) { - return nextResolve(imports[specifier], context); - } - - return nextResolve(specifier, context); -} -``` - -##### Synchronous version - ```mjs // import-map-sync-hooks.js import fs from 'node:fs/promises'; @@ -1882,8 +1180,7 @@ import 'a-module'; console.log('some module!'); ``` -Running `node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.js` -or `node --import ./import-map-sync-hooks.js main.js` +Running `node --import ./import-map-sync-hooks.js main.js` should print `some module!`. ## Source Map Support @@ -2104,13 +1401,13 @@ returned object contains the following keys: [Conditional exports]: packages.md#conditional-exports [Customization hooks]: #customization-hooks [ES Modules]: esm.md -[Permission Model]: permissions.md#permission-model [Source Map]: https://tc39.es/ecma426/ [Source map format]: https://tc39.es/ecma426/#sec-source-map-format [V8 JavaScript code coverage]: https://v8project.blogspot.com/2017/12/javascript-code-coverage.html [V8 code cache]: https://v8.dev/blog/code-caching-for-devs [`"exports"`]: packages.md#exports [`--enable-source-maps`]: cli.md#--enable-source-maps +[`--experimental-test-coverage`]: cli.md#--experimental-test-coverage [`--import`]: cli.md#--importmodule [`--require`]: cli.md#-r---require-module [`NODE_COMPILE_CACHE=dir`]: cli.md#node_compile_cachedir @@ -2120,7 +1417,7 @@ returned object contains the following keys: [`NODE_V8_COVERAGE=dir`]: cli.md#node_v8_coveragedir [`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze [`SourceMap`]: #class-modulesourcemap -[`initialize`]: #initialize +[`TextDecoder`]: globals.md#class-textdecoder [`module.constants.compileCacheStatus`]: #moduleconstantscompilecachestatus [`module.enableCompileCache()`]: #moduleenablecompilecacheoptions [`module.flushCompileCache()`]: #moduleflushcompilecache @@ -2129,22 +1426,15 @@ returned object contains the following keys: [`module.registerHooks()`]: #moduleregisterhooksoptions [`module.setSourceMapsSupport()`]: #modulesetsourcemapssupportenabled-options [`os.tmpdir()`]: os.md#ostmpdir -[`register`]: #moduleregisterspecifier-parenturl-options -[`util.TextDecoder`]: util.md#class-utiltextdecoder [accepted final formats]: #accepted-final-formats-returned-by-load -[asynchronous `load` hook]: #asynchronous-loadurl-context-nextload -[asynchronous `resolve` hook]: #asynchronous-resolvespecifier-context-nextresolve -[asynchronous hook functions]: #asynchronous-hooks-accepted-by-moduleregister -[caveats of asynchronous customization hooks]: #caveats-of-asynchronous-customization-hooks -[deregistration of synchronous customization hooks]: #deregistration-of-synchronous-customization-hooks +[deregistration of customization hooks]: #deregistration-of-customization-hooks +[hook functions]: #hook-functions-accepted-by-moduleregisterhooks [hooks]: #customization-hooks -[load hook]: #synchronous-loadurl-context-nextload +[load hook]: #loadurl-context-nextload [module compile cache]: #module-compile-cache [realm]: https://tc39.es/ecma262/#realm -[resolve hook]: #synchronous-resolvespecifier-context-nextresolve +[resolve hook]: #resolvespecifier-context-nextresolve [source map include directives]: https://tc39.es/ecma426/#sec-linking-generated-code -[synchronous hook functions]: #hook-functions-accepted-by-moduleregisterhooks [the `module` object]: modules.md#the-module-object [the documentation of `Worker`]: worker_threads.md#new-workerfilename-options -[transferable objects]: worker_threads.md#portpostmessagevalue-transferlist [type-stripping]: typescript.md#type-stripping diff --git a/doc/api/os.md b/doc/api/os.md index a2592a2f20cc..8e9e4e9ed402 100644 --- a/doc/api/os.md +++ b/doc/api/os.md @@ -504,6 +504,33 @@ On POSIX systems, the operating system release is determined by calling available, `GetVersionExW()` will be used. See <https://en.wikipedia.org/wiki/Uname#Examples> for more information. +## `os.guessFileDescriptorType(fd)` + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +* `fd` {integer} The file descriptor number to try and guess the type of. + +* Returns: {string} + +Returns the type of the file descriptor passed in. If `fd` is not a non-negative +32-bit integer, an [`ERR_INVALID_FD`][] error is thrown. If `fd` does not refer +to an open file descriptor, `'UNKNOWN'` is returned. +A common use case for this function is checking whether standard input is passed into your process, +and if it is, if it can be consumed by the process. For example, on Unix systems, if the type is `TTY`, it means +you can prompt the user for new data while the process is running, and if it's `FILE` or `PIPE`, it means there is data +available, but you shouldn't try to prompt for more. + +Currently, the following types for a file descriptor can be returned: + +* `'TCP'` +* `'TTY'` +* `'UDP'` +* `'FILE'` +* `'PIPE'` +* `'UNKNOWN'` + ## OS constants The following constants are exported by `os.constants`. @@ -1370,6 +1397,7 @@ The following process scheduling constants are exported by [Android building]: https://github.com/nodejs/node/blob/HEAD/BUILDING.md#android [EUID]: https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID +[`ERR_INVALID_FD`]: errors.md#err_invalid_fd [`SystemError`]: errors.md#class-systemerror [`process.arch`]: process.md#processarch [`process.platform`]: process.md#processplatform diff --git a/doc/api/permissions.md b/doc/api/permissions.md index 2cf99bd167ab..4648c441769a 100644 --- a/doc/api/permissions.md +++ b/doc/api/permissions.md @@ -123,6 +123,8 @@ API call to drop permissions at runtime. This operation is **irreversible**. When called without a reference, the entire scope is dropped. When called with a reference, only the permission for that specific resource is revoked. +The reference must not be an empty string or an empty `Uint8Array`; otherwise +an `ERR_INVALID_ARG_VALUE` error is thrown. Dropping a permission only affects future access checks. It does not close or revoke access to resources that are already open, such as file descriptors, network sockets, child processes, or worker threads. Applications are @@ -285,6 +287,9 @@ both to the top-level `node:fs` functions and to the equivalent `FileHandle` methods, and currently includes `fsync`/`fdatasync`, `fchmod`, `fchown`, and `futimes` (and their synchronous variants). +In [audit mode](#audit-mode), these operations are not disabled and run normally. No +diagnostics channel message is published for them. + #### Environment variable permissions When the Permission Model is enforced, the process only has access to the diff --git a/doc/api/process.md b/doc/api/process.md index d47983a97b4e..fd71bea3b945 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -598,6 +598,32 @@ A few of the warning types that are most common include: that will be ignored rather than treated as an error. One example is use of the HTTP response status message when using the HTTP/2 compatibility API. +#### Heap size and pointer compression + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +When Node.js is built with V8 pointer compression enabled, the V8 heap of each +thread (the main thread and every [`Worker`][]) is limited to 4 GiB, regardless +of `--max-old-space-size`. Pointer compression reduces heap usage, typically by +about 40% and never by more than half, so a heap that is larger than 4 GiB +without pointer compression may or may not fit under that limit. + +In builds without pointer compression, Node.js emits a warning with the code +`'HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT'` when the heap of a thread that +survives a full garbage collection reaches: + +* 6.5 GiB: the heap is likely to exceed the limit with pointer compression. +* 8 GiB: the heap will exceed the limit with pointer compression. + +The warning is emitted at most once per thread, with the wording that matches +the heap size at the time. Memory outside the V8 heap, such as the contents of +{ArrayBuffer}s and {Buffer}s, does not count toward the limit. + +The warning can be silenced with +`--disable-warning=HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT`. + ### Event: `'worker'` <!-- YAML @@ -3252,7 +3278,8 @@ permissions. When a reference is provided, only the permission for that specific resource is dropped. For example, `process.permission.drop('fs.read', '/etc/myapp')` will revoke read access to that directory while keeping other read -permissions intact. +permissions intact. The `reference` must not be an empty string or an empty +`Uint8Array`; otherwise an `ERR_INVALID_ARG_VALUE` error is thrown. **Important:** You can only drop the exact resource that was explicitly granted. The reference passed to `drop()` must match the original grant: diff --git a/doc/api/quic.md b/doc/api/quic.md index dad86a144682..d977f7e03ad2 100644 --- a/doc/api/quic.md +++ b/doc/api/quic.md @@ -1365,6 +1365,11 @@ added: v23.8.0 will buffer before `writeSync()` returns `false`. When the buffered data exceeds this limit, the caller should wait for drain before writing more. **Default:** `65536` (64 KB). + * `waitUntilAvailable` {boolean} When true the promise will wait until flow + control will allow to open the stream. If set to false, the function + will return a rejected promise, if flow control will not allow to + open the stream immediately. + **Default:** `true` * `onheaders` {Function} Callback for received initial response headers. Called with `(headers)`. * `ontrailers` {Function} Callback for received trailing headers. @@ -1406,6 +1411,11 @@ added: v23.8.0 will buffer before `writeSync()` returns `false`. When the buffered data exceeds this limit, the caller should wait for drain before writing more. **Default:** `65536` (64 KB). + * `waitUntilAvailable` {boolean} When true the promise will wait until flow + control will allow to open the stream. If set to false, the function + will return a rejected promise, if flow control will not allow + to open the stream immediately. + **Default:** `true` * `onheaders` {Function} Callback for received initial response headers. Called with `(headers)`. * `ontrailers` {Function} Callback for received trailing headers. @@ -1959,10 +1969,10 @@ added: v23.8.0 * Type: {Promise} A promise that is fulfilled when the stream is fully closed. It resolves -when the stream closes cleanly (including idle timeout). It rejects with +when the stream closes without a QUIC error, including idle timeout and a +`RESET_STREAM` whose application code represents no error. It rejects with an `ERR_QUIC_APPLICATION_ERROR` or `ERR_QUIC_TRANSPORT_ERROR` when the -stream is closed due to a QUIC error (e.g., stream reset by the peer, -CONNECTION\_CLOSE with a non-zero error code). +stream is closed due to a QUIC error. ### `stream.destroy([error[, options]])` @@ -3294,8 +3304,10 @@ added: v23.8.0 --> * Type: {bigint|number} +* **Default:** `1200` -Specifies the maximum UDP packet payload size. +Specifies the maximum UDP packet payload size. The valid range is `1200` to +`65527`. #### `sessionOptions.maxStreamWindow` @@ -3496,10 +3508,11 @@ selects how the stream's async iterator reports this: * `'ignore'` - The truncation itself is ignored: only a stream or connection error is reported, and any clean abort/cancellation or similar simply ends - the stream. A non-zero peer reset, non-zero local stop-sending or connection - error still fails, but a truncation with no error at all (an idle timeout, - a graceful close, or a plain `stopSending()`) ends the read cleanly with the - data received. This matches `stream.closed`, which rejects only on an error. + the stream. A peer reset or local stop-sending with an application code that + represents an error, or a connection error, still fails, but a truncation + with no error at all (an idle timeout, a graceful close, or a plain + `stopSending()`) ends the read cleanly with the data received. This matches + `stream.closed`, which rejects only on an error. #### `sessionOptions.verifyPeer` (client only) @@ -4096,7 +4109,7 @@ added: v23.8.0 --> * `this` {quic.QuicStream} -* `error` {any} +* `error` {Error} ### Callback: `OnHeadersCallback` @@ -4790,7 +4803,7 @@ added: * `stream` {quic.QuicStream} * `session` {quic.QuicSession} -* `error` {any} The QUIC error associated with the reset. +* `error` {Error} The QUIC error associated with the reset. Published when a stream receives a RESET\_STREAM frame from the peer, indicating the peer has aborted its sending direction. This is a key signal diff --git a/doc/api/single-executable-applications.md b/doc/api/single-executable-applications.md index 6bedb213b8ae..6eab935d4f81 100644 --- a/doc/api/single-executable-applications.md +++ b/doc/api/single-executable-applications.md @@ -357,6 +357,77 @@ against its source, so it is used by the executable whenever the modules are loaded from the VFS, and ignored if they changed. The cache is platform-specific, like the code cache of the main script. +#### Source maps in the VFS + +[Source Map v3][] maps work in a SEA using `"useVfs": true` exactly as they do +on the real file system, provided the maps are bundled as assets (or inside +the `"vfsArchive"` archive) and source map support is enabled in the generated +executable. The `.map` file is read from inside the mount point, and the +`"sources"` of the map and the original sources are resolved against the mount +point too. As a result, [`module.findSourceMap()`][], source-mapped stack +traces, and the source line shown above an uncaught error all resolve against +the bundled assets rather than the real file system. + +Source maps are enabled in a SEA the same way as in a regular Node.js process +with [`--enable-source-maps`][]. The flag is not consumed when it is +passed as a command-line argument to the executable: with the default +`"execArgvExtension": "env"`, command-line arguments are handed to the +application. Set it in `"execArgv"` (or in [`NODE_OPTIONS`][]) instead: + +```json +{ + "main": "sea.js", + "output": "sea", + "useVfs": true, + "execArgv": ["--enable-source-maps"], + "assets": { + "sea.js.map": "dist/sea.js.map", + "original.js": "src/original.js" + } +} +``` + +The bundled source must end with a `sourceMappingURL` magic comment that points +at the map. A relative path resolves against the location of the script inside +the mount, so no mount-point path needs to be hard-coded: + +<!-- eslint-disable no-restricted-syntax, @stylistic/js/spaced-comment --> + +```cjs +// sea.js +'use strict'; + +function boom() { + throw new Error('boom from the original source'); +} + +boom(); +//# sourceMappingURL=sea.js.map +``` + +If the map embeds `sourcesContent`, the original source lines are taken from +the map itself. Otherwise the original sources must also be bundled (as +assets, or as entries in the `"vfsArchive"` archive) so that the error source +preview can be read back through the VFS, as in the configuration above. With +`--enable-source-maps` enabled, throwing the error above maps the stack frame +back to `original.js` and shows the original source line: + +```text +…/vfs/1/original.js:5 + throw new Error('boom from the original source'); + ^ + +Error: boom from the original source + at boom (…/vfs/1/original.js:5:5) +``` + +The `…` stands in for the reserved mount point, which is chosen at runtime and +cannot exist on the real file system. When the application is transpiled, the +bundler typically emits the map next to the bundled file; make sure to bundle +it with `"assets"` (or include it in the `"vfsArchive"` archive), because the +VFS never shadows the real file system and the `.map` file must therefore be +reachable inside the mount. + #### Snapshot limitations `"useVfs": true` cannot be used together with `"useSnapshot": true`. @@ -844,11 +915,15 @@ to help us document them. [Generating single executable preparation blobs]: #1-generating-single-executable-preparation-blobs [Mach-O]: https://en.wikipedia.org/wiki/Mach-O [PE]: https://en.wikipedia.org/wiki/Portable_Executable +[Source Map v3]: https://tc39.es/ecma426/ [Using native addons in the injected main script]: #using-native-addons-in-the-injected-main-script [VFS documentation]: vfs.md [Windows SDK]: https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/ +[`--enable-source-maps`]: cli.md#--enable-source-maps [`--vfs-load`]: cli.md#--vfs-loadsource +[`NODE_OPTIONS`]: cli.md#node_optionsoptions [`Worker`]: worker_threads.md#class-worker +[`module.findSourceMap()`]: module.md#modulefindsourcemappath [`node:zlib`]: zlib.md [`process.execPath`]: process.md#processexecpath [`require()`]: modules.md#requireid diff --git a/doc/api/sqlite.md b/doc/api/sqlite.md index 003b409fecd2..846382d823a0 100644 --- a/doc/api/sqlite.md +++ b/doc/api/sqlite.md @@ -5,6 +5,9 @@ <!-- YAML added: v22.5.0 changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67654 + description: SQLite is now stable. - version: - v25.7.0 - v24.15.0 @@ -17,7 +20,7 @@ changes: description: SQLite is no longer behind `--experimental-sqlite` but still experimental. --> -> Stability: 1.2 - Release candidate. +> Stability: 2 - Stable <!-- source_link=lib/sqlite.js --> diff --git a/doc/api/stream_iter.md b/doc/api/stream_iter.md index 893dcfbf4bc2..03c14e21afa3 100644 --- a/doc/api/stream_iter.md +++ b/doc/api/stream_iter.md @@ -94,6 +94,10 @@ are automatically UTF-8 encoded when passed to `from()`, `push()`, or `pipeTo()`. This removes ambiguity around encodings and enables zero-copy transfers between streams and native code. +Like [`Buffer.from()`][] for strings, small strings are encoded into a shared +pool: the resulting {Uint8Array} is a view of a larger {ArrayBuffer}, which +cannot be transferred. + ### Batching Each iteration yields a **batch** -- an {Array} of {Uint8Array} chunks @@ -119,6 +123,10 @@ async function run() { } ``` +Some iterators of this module return iterator results (`{ done, value }` +objects) that do not inherit from `Object.prototype`. Code should only rely on +their `done` and `value` properties, as `for await...of` does. + ### Transforms Transforms come in two forms: @@ -140,10 +148,13 @@ Both forms receive an `options` parameter with the following property: can check `signal.aborted` or listen for the `'abort'` event to perform early cleanup. -In `pull()`, stateless transforms receive a new `options` object for every -call, and stateful transforms one for the pipeline, so a transform can modify -its `options` without affecting other transforms. The object does not inherit -from `Object.prototype`. Transforms passed to [`pullSync()`][] receive no +Each transform of a pipeline receives its own `options` object, the same one +for every call of a stateless transform, so a transform can modify its +`options` without affecting other transforms. The object does not inherit +from `Object.prototype`. The signal is created when `options.signal` is +first read, so a pipeline whose transforms never read it does not create one; +until then, `signal` is an accessor property. It is the same signal for every +transform of the pipeline. Transforms passed to [`pullSync()`][] receive no `options`. The flush signal (`null`) is sent after the source ends, giving transforms @@ -598,6 +609,10 @@ Objects implementing `Symbol.for('Stream.toAsyncStreamable')` or precedence over the iteration protocols (`Symbol.asyncIterator`, `Symbol.iterator`). +The readable of a [`push()`][] stream without transforms, the iterables +returned by [`fromReadable()`][], and the results of `from()` itself already +yield normalized batches, so `from()` returns them unchanged. + ```mjs import { Buffer } from 'node:buffer'; import { from, text } from 'node:stream/iter'; @@ -663,7 +678,9 @@ added: * `writer` {Object} Destination with `write(chunk)` method. * `options` {Object} * `signal` {AbortSignal} Abort the pipeline. Aborting fails the destination - writer unless `preventFail` is `true`. + writer unless `preventFail` is `true`. The signal is passed to the + writer's `write()`, `writev()` and `end()` in an options object, the same + object for every call. * `preventClose` {boolean} If `true`, do not call `writer.end()` when the source ends. **Default:** `false`. * `preventFail` {boolean} If `true`, do not call `writer.fail()` on @@ -2400,6 +2417,7 @@ console.log(textSync(stream)); // 'hello world' [Iterable Streams API]: https://iter-streams.proposal.wintertc.org/ [`--experimental-stream-iter`]: cli.md#--experimental-stream-iter [`Broadcast.from()`]: #broadcastfrominput-options +[`Buffer.from()`]: buffer.md#static-method-bufferfromstring-encoding [`Share.from()`]: #static-method-sharefrominput-options [`SyncShare.fromSync()`]: #static-method-syncsharefromsyncinput-options [`array()`]: #arraysource-options @@ -2415,6 +2433,7 @@ console.log(textSync(stream)); // 'hello world' [`pipeTo()`]: #pipetosource-transforms-writer-options [`pull()`]: #pullsource-transforms-options [`pullSync()`]: #pullsyncsource-transforms +[`push()`]: #pushtransforms-options [`share()`]: #sharesource-options [`stream.Readable`]: stream.md#class-streamreadable [`stream.Writable`]: stream.md#class-streamwritable diff --git a/doc/api/test.md b/doc/api/test.md index db530c609add..b3b5277d244b 100644 --- a/doc/api/test.md +++ b/doc/api/test.md @@ -135,6 +135,9 @@ create it. the state file is a JSON file that contains an array of run attempts. Each run attempt is an object mapping successful tests to the attempt they have passed in. The key identifying a test in this map is the test file path, with the line and column where the test is defined. +When tests run with process isolation and a test is defined outside of the test file being run, +for example in a helper shared by several test files, +the key is prefixed with the path of that test file. in a case where a test defined in a specific location is run multiple times, for example within a function or a loop, a counter will be appended to the key, to disambiguate the test runs. @@ -2883,10 +2886,8 @@ Node.js builtin modules. Any references to the original module prior to mocking order to enable module mocking, Node.js must be started with the [`--experimental-test-module-mocks`][] command-line flag. -**Note**: [module customization hooks][] registered via the **synchronous** API effect resolution of -the `specifier` provided to `mock.module`. Customization hooks registered via the **asynchronous** -API are currently ignored (because the test runner's loader is synchronous, and node does not -support multi-chain / cross-chain loading). +**Note**: [module customization hooks][] registered with `module.registerHooks()` affect resolution of +the `specifier` provided to `mock.module`. The following example demonstrates how a mock is created for a module. @@ -5141,6 +5142,32 @@ The attempt number of the suite. This value is zero-based, so the first attempt the second attempt is `1`, and so on. This property is useful in conjunction with the `--test-rerun-failures` option to determine the attempt number of the current run. +### `context.tags` + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +> Stability: 1.0 - Early development + +* Type: {string\[]} + +A frozen array of the suite's flattened lowercased tags, in declaration +order, including any tags inherited from ancestor suites. Empty when the +suite has no tags. See [Test tags][]. + +### `context.workerId` + +<!-- YAML +added: v27.0.0-alpha.0.2.0 +--> + +* Type: {number|undefined} + +The unique identifier of the worker running the current test file. This value +is derived from the `NODE_TEST_WORKER_ID` environment variable, and is +`undefined` when not running in a test context. + ### `context.diagnostic(message)` <!-- YAML diff --git a/doc/api/tls.md b/doc/api/tls.md index 032aa4764175..7546d2618246 100644 --- a/doc/api/tls.md +++ b/doc/api/tls.md @@ -235,6 +235,11 @@ understanding of the implications and risks. TLSv1.3 does not support renegotiation. +Renegotiation is deprecated (see [DEP0213][]). A future version of Node.js will +disable it by default, for servers and clients. The `allowRenegotiation` option +of [`tls.createServer()`][] and [`tls.connect()`][] can be set to `false` to +disable it now, or to `true` to keep it enabled when that default changes. + ### Session resumption Establishing a TLS session can be relatively slow. The process can be sped @@ -901,6 +906,9 @@ connection is open. <!-- YAML added: v0.11.4 changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67532 + description: The `allowRenegotiation` option is now supported. - version: v12.2.0 pr-url: https://github.com/nodejs/node/pull/27497 description: The `enableTrace` option is now supported. @@ -927,6 +935,7 @@ changes: * `ALPNProtocols`: See [`tls.createServer()`][] * `SNICallback`: See [`tls.createServer()`][] * `ALPNCallback`: See [`tls.createServer()`][] + * `allowRenegotiation`: See [`tls.createServer()`][] * `session` {Buffer} A `Buffer` instance containing a TLS session. * `requestOCSP` {boolean} If `true`, specifies that the OCSP status request extension will be added to the client hello and an `'OCSPResponse'` event @@ -1119,11 +1128,18 @@ certificate at all. <!-- YAML added: v8.4.0 +deprecated: v27.0.0-alpha.0.2.0 --> +> Stability: 0 - Deprecated. See [DEP0213][]. + Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts to renegotiate will trigger an `'error'` event on the `TLSSocket`. +Set `allowRenegotiation: false` when creating the server or connection +instead. This method has no effect on a connection created that way, where the +peer's attempts to renegotiate are refused without an error. + ### `tlsSocket.enableTrace()` <!-- YAML @@ -1586,6 +1602,7 @@ Returns the numeric representation of the remote port. For example, `443`. <!-- YAML added: v0.11.8 +deprecated: v27.0.0-alpha.0.2.0 changes: - version: v18.0.0 pr-url: https://github.com/nodejs/node/pull/41678 @@ -1594,6 +1611,8 @@ changes: `ERR_INVALID_CALLBACK`. --> +> Stability: 0 - Deprecated. See [DEP0213][]. + * `options` {Object} * `rejectUnauthorized` {boolean} If not `false`, the server certificate is verified against the list of supplied CAs. An `'error'` event is emitted if @@ -1622,6 +1641,12 @@ When running as the server, the socket will be destroyed with an error after For TLSv1.3, renegotiation cannot be initiated, it is not supported by the protocol. +If the connection was created with `allowRenegotiation: false`, this method +returns `false` and `callback` is called with an +[`ERR_TLS_RENEGOTIATION_DISABLED`][] error. A future version of Node.js will +disable renegotiation by default, and this method will then only work on +connections created with `allowRenegotiation: true`. + ### `tlsSocket.servername` <!-- YAML @@ -1740,6 +1765,9 @@ was present (see [CVE-2021-44531][]). Applications that wish to accept <!-- YAML added: v0.11.3 changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67532 + description: The `allowRenegotiation` option is now supported. - version: - v15.1.0 - v14.18.0 @@ -1837,6 +1865,9 @@ changes: TLS connection. When a server offers a DH parameter with a size less than `minDHSize`, the TLS connection is destroyed and an error is thrown. **Default:** `1024`. + * `allowRenegotiation` {boolean} If `true`, the client accepts renegotiation + requested by the server. A future version of Node.js will change this default + to `false` (see [DEP0213][]). **Default:** `true`. * `highWaterMark` {number} Consistent with the readable stream `highWaterMark` parameter. **Default:** `16 * 1024`. * `timeout`: {number} If set and if a socket is created internally, will call @@ -2209,6 +2240,9 @@ permissible, use 2048 bits or larger for stronger security. <!-- YAML added: v0.3.2 changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67532 + description: The `allowRenegotiation` option is now supported. - version: v27.0.0-alpha.0.0.0 pr-url: https://github.com/nodejs/node/pull/64777 description: Using the `clientCertEngine` option now throws @@ -2246,6 +2280,13 @@ changes: --> * `options` {Object} + * `allowRenegotiation` {boolean} If `true`, connections to the server may be + renegotiated, either when requested by the client or through local calls to + [`tlsSocket.renegotiate()`][]. Renegotiation is deprecated (see + [DEP0213][]) and future versions will set this default to `false`. + Setting this to `true` throws [`ERR_TLS_RENEGOTIATION_UNSUPPORTED`][] + where the TLS library does not support renegotiation on servers. + **Default:** `true`. * `ALPNProtocols` {string\[]|Buffer|TypedArray|DataView} An array of strings, or a single `Buffer`, `TypedArray`, or `DataView` containing the supported ALPN protocols. Buffers should have the format `[len][name][len][name]...` @@ -2585,6 +2626,7 @@ added: v0.11.3 [CVE-2021-44531]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531 [Chrome's 'modern cryptography' setting]: https://www.chromium.org/Home/chromium-security/education/tls#TOC-Cipher-Suites +[DEP0213]: deprecations.md#dep0213-tls-renegotiation [DHE]: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange [ECDHE]: https://en.wikipedia.org/wiki/Elliptic_curve_Diffie%E2%80%93Hellman [IANA TLS Supported Groups registry]: https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8 @@ -2617,6 +2659,8 @@ added: v0.11.3 [`--use-openssl-ca`]: cli.md#--use-bundled-ca---use-openssl-ca [`--use-system-ca`]: cli.md#--use-system-ca [`Duplex`]: stream.md#class-streamduplex +[`ERR_TLS_RENEGOTIATION_DISABLED`]: errors.md#err_tls_renegotiation_disabled +[`ERR_TLS_RENEGOTIATION_UNSUPPORTED`]: errors.md#err_tls_renegotiation_unsupported [`NODE_EXTRA_CA_CERTS`]: cli.md#node_extra_ca_certsfile [`NODE_OPTIONS`]: cli.md#node_optionsoptions [`SSL_export_keying_material`]: https://www.openssl.org/docs/man3.0/man3/SSL_export_keying_material.html @@ -2652,6 +2696,7 @@ added: v0.11.3 [`tls.getCACertificates()`]: #tlsgetcacertificatestype [`tls.getCiphers()`]: #tlsgetciphers [`tls.rootCertificates`]: #tlsrootcertificates +[`tlsSocket.renegotiate()`]: #tlssocketrenegotiateoptions-callback [`x509.checkHost()`]: crypto.md#x509checkhostname-options [asn1.js]: https://www.npmjs.com/package/asn1.js [certificate object]: #certificate-object diff --git a/doc/api/url.md b/doc/api/url.md index 7759c03a15e7..519fcce50bed 100644 --- a/doc/api/url.md +++ b/doc/api/url.md @@ -1517,6 +1517,12 @@ added: - v15.7.0 - v14.18.0 changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67454 + description: The own enumerable properties of the `url` argument are now + only carried over when `url` is a WHATWG `URL` instance created + by this realm's `URL` constructor, rather than for any + duck-typed object. - version: - v19.9.0 - v18.17.0 @@ -1545,6 +1551,14 @@ changes: This utility function converts a URL object into an ordinary options object as expected by the [`http.request()`][] and [`https.request()`][] APIs. +If `url` is a WHATWG `URL` instance created by this realm's `URL` constructor, +the returned object will also contain all of its own enumerable properties. This +allows a `URL` object to be extended with additional request options (for +example `url.headers = { 'X-Foo': 'bar' }`). Objects that merely share the +shape of a `URL` (as accepted by the duck-typed `isURL()` check used by +`http.request()`) are **not** treated this way, so they cannot smuggle +connection/transport options such as `socketPath` into the request. + ```mjs import { urlToHttpOptions } from 'node:url'; const myURL = new URL('https://a:b@測試?abc#foo'); diff --git a/doc/api/util.md b/doc/api/util.md index c30831019d0e..2a2756377508 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -2928,195 +2928,27 @@ The full list of formats can be found in [modifiers][]. <!-- YAML added: v8.3.0 +deprecated: v27.0.0-alpha.0.2.0 changes: - version: v11.0.0 pr-url: https://github.com/nodejs/node/pull/22281 description: The class is now available on the global object. --> -An implementation of the [WHATWG Encoding Standard][] `TextDecoder` API. - -```js -const decoder = new TextDecoder(); -const u8arr = new Uint8Array([72, 101, 108, 108, 111]); -console.log(decoder.decode(u8arr)); // Hello -``` - -### WHATWG supported encodings - -Per the [WHATWG Encoding Standard][], the encodings supported by the -`TextDecoder` API are outlined in the tables below. For each encoding, -one or more aliases may be used. - -Different Node.js build configurations support different sets of encodings. -(see [Internationalization][]) - -#### Encodings supported by default (with full ICU data) - -| Encoding | Aliases | -| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `'ibm866'` | `'866'`, `'cp866'`, `'csibm866'` | -| `'iso-8859-2'` | `'csisolatin2'`, `'iso-ir-101'`, `'iso8859-2'`, `'iso88592'`, `'iso_8859-2'`, `'iso_8859-2:1987'`, `'l2'`, `'latin2'` | -| `'iso-8859-3'` | `'csisolatin3'`, `'iso-ir-109'`, `'iso8859-3'`, `'iso88593'`, `'iso_8859-3'`, `'iso_8859-3:1988'`, `'l3'`, `'latin3'` | -| `'iso-8859-4'` | `'csisolatin4'`, `'iso-ir-110'`, `'iso8859-4'`, `'iso88594'`, `'iso_8859-4'`, `'iso_8859-4:1988'`, `'l4'`, `'latin4'` | -| `'iso-8859-5'` | `'csisolatincyrillic'`, `'cyrillic'`, `'iso-ir-144'`, `'iso8859-5'`, `'iso88595'`, `'iso_8859-5'`, `'iso_8859-5:1988'` | -| `'iso-8859-6'` | `'arabic'`, `'asmo-708'`, `'csiso88596e'`, `'csiso88596i'`, `'csisolatinarabic'`, `'ecma-114'`, `'iso-8859-6-e'`, `'iso-8859-6-i'`, `'iso-ir-127'`, `'iso8859-6'`, `'iso88596'`, `'iso_8859-6'`, `'iso_8859-6:1987'` | -| `'iso-8859-7'` | `'csisolatingreek'`, `'ecma-118'`, `'elot_928'`, `'greek'`, `'greek8'`, `'iso-ir-126'`, `'iso8859-7'`, `'iso88597'`, `'iso_8859-7'`, `'iso_8859-7:1987'`, `'sun_eu_greek'` | -| `'iso-8859-8'` | `'csiso88598e'`, `'csisolatinhebrew'`, `'hebrew'`, `'iso-8859-8-e'`, `'iso-ir-138'`, `'iso8859-8'`, `'iso88598'`, `'iso_8859-8'`, `'iso_8859-8:1988'`, `'visual'` | -| `'iso-8859-8-i'` | `'csiso88598i'`, `'logical'` | -| `'iso-8859-10'` | `'csisolatin6'`, `'iso-ir-157'`, `'iso8859-10'`, `'iso885910'`, `'l6'`, `'latin6'` | -| `'iso-8859-13'` | `'iso8859-13'`, `'iso885913'` | -| `'iso-8859-14'` | `'iso8859-14'`, `'iso885914'` | -| `'iso-8859-15'` | `'csisolatin9'`, `'iso8859-15'`, `'iso885915'`, `'iso_8859-15'`, `'l9'` | -| `'koi8-r'` | `'cskoi8r'`, `'koi'`, `'koi8'`, `'koi8_r'` | -| `'koi8-u'` | `'koi8-ru'` | -| `'macintosh'` | `'csmacintosh'`, `'mac'`, `'x-mac-roman'` | -| `'windows-874'` | `'dos-874'`, `'iso-8859-11'`, `'iso8859-11'`, `'iso885911'`, `'tis-620'` | -| `'windows-1250'` | `'cp1250'`, `'x-cp1250'` | -| `'windows-1251'` | `'cp1251'`, `'x-cp1251'` | -| `'windows-1252'` | `'ansi_x3.4-1968'`, `'ascii'`, `'cp1252'`, `'cp819'`, `'csisolatin1'`, `'ibm819'`, `'iso-8859-1'`, `'iso-ir-100'`, `'iso8859-1'`, `'iso88591'`, `'iso_8859-1'`, `'iso_8859-1:1987'`, `'l1'`, `'latin1'`, `'us-ascii'`, `'x-cp1252'` | -| `'windows-1253'` | `'cp1253'`, `'x-cp1253'` | -| `'windows-1254'` | `'cp1254'`, `'csisolatin5'`, `'iso-8859-9'`, `'iso-ir-148'`, `'iso8859-9'`, `'iso88599'`, `'iso_8859-9'`, `'iso_8859-9:1989'`, `'l5'`, `'latin5'`, `'x-cp1254'` | -| `'windows-1255'` | `'cp1255'`, `'x-cp1255'` | -| `'windows-1256'` | `'cp1256'`, `'x-cp1256'` | -| `'windows-1257'` | `'cp1257'`, `'x-cp1257'` | -| `'windows-1258'` | `'cp1258'`, `'x-cp1258'` | -| `'x-mac-cyrillic'` | `'x-mac-ukrainian'` | -| `'gbk'` | `'chinese'`, `'csgb2312'`, `'csiso58gb231280'`, `'gb2312'`, `'gb_2312'`, `'gb_2312-80'`, `'iso-ir-58'`, `'x-gbk'` | -| `'gb18030'` | | -| `'big5'` | `'big5-hkscs'`, `'cn-big5'`, `'csbig5'`, `'x-x-big5'` | -| `'euc-jp'` | `'cseucpkdfmtjapanese'`, `'x-euc-jp'` | -| `'iso-2022-jp'` | `'csiso2022jp'` | -| `'shift_jis'` | `'csshiftjis'`, `'ms932'`, `'ms_kanji'`, `'shift-jis'`, `'sjis'`, `'windows-31j'`, `'x-sjis'` | -| `'euc-kr'` | `'cseuckr'`, `'csksc56011987'`, `'iso-ir-149'`, `'korean'`, `'ks_c_5601-1987'`, `'ks_c_5601-1989'`, `'ksc5601'`, `'ksc_5601'`, `'windows-949'` | - -#### Encodings supported when Node.js is built with the `small-icu` option - -| Encoding | Aliases | -| ------------ | ------------------------------- | -| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | -| `'utf-16le'` | `'utf-16'` | -| `'utf-16be'` | | - -#### Encodings supported when ICU is disabled - -| Encoding | Aliases | -| ------------ | ------------------------------- | -| `'utf-8'` | `'unicode-1-1-utf-8'`, `'utf8'` | -| `'utf-16le'` | `'utf-16'` | - -The `'iso-8859-16'` encoding listed in the [WHATWG Encoding Standard][] -is not supported. - -### `new TextDecoder([encoding[, options]])` - -* `encoding` {string} Identifies the `encoding` that this `TextDecoder` instance - supports. **Default:** `'utf-8'`. -* `options` {Object} - * `fatal` {boolean} `true` if decoding failures are fatal. - This option is not supported when ICU is disabled - (see [Internationalization][]). **Default:** `false`. - * `ignoreBOM` {boolean} When `true`, the `TextDecoder` will include the byte - order mark in the decoded result. When `false`, the byte order mark will - be removed from the output. This option is only used when `encoding` is - `'utf-8'`, `'utf-16be'`, or `'utf-16le'`. **Default:** `false`. - -Creates a new `TextDecoder` instance. The `encoding` may specify one of the -supported encodings or an alias. - -The `TextDecoder` class is also available on the global object. - -### `textDecoder.decode([input[, options]])` - -* `input` {ArrayBuffer|DataView|TypedArray} An `ArrayBuffer`, `DataView`, or - `TypedArray` instance containing the encoded data. -* `options` {Object} - * `stream` {boolean} `true` if additional chunks of data are expected. - **Default:** `false`. -* Returns: {string} - -Decodes the `input` and returns a string. If `options.stream` is `true`, any -incomplete byte sequences occurring at the end of the `input` are buffered -internally and emitted after the next call to `textDecoder.decode()`. - -If `textDecoder.fatal` is `true`, decoding errors that occur will result in a -`TypeError` being thrown. - -### `textDecoder.encoding` - -* Type: {string} - -The encoding supported by the `TextDecoder` instance. - -### `textDecoder.fatal` - -* Type: {boolean} - -The value will be `true` if decoding errors result in a `TypeError` being -thrown. - -### `textDecoder.ignoreBOM` - -* Type: {boolean} - -The value will be `true` if the decoding result will include the byte order -mark. +Deprecated alias for global [`TextDecoder`][]. ## Class: `util.TextEncoder` <!-- YAML added: v8.3.0 +deprecated: v27.0.0-alpha.0.2.0 changes: - version: v11.0.0 pr-url: https://github.com/nodejs/node/pull/22281 description: The class is now available on the global object. --> -An implementation of the [WHATWG Encoding Standard][] `TextEncoder` API. All -instances of `TextEncoder` only support UTF-8 encoding. - -```js -const encoder = new TextEncoder(); -const uint8array = encoder.encode('this is some data'); -``` - -The `TextEncoder` class is also available on the global object. - -### `textEncoder.encode([input])` - -* `input` {string} The text to encode. **Default:** an empty string. -* Returns: {Uint8Array} - -UTF-8 encodes the `input` string and returns a `Uint8Array` containing the -encoded bytes. - -### `textEncoder.encodeInto(src, dest)` - -<!-- YAML -added: v12.11.0 ---> - -* `src` {string} The text to encode. -* `dest` {Uint8Array} The array to hold the encode result. -* Returns: {Object} - * `read` {number} The read Unicode code units of src. - * `written` {number} The written UTF-8 bytes of dest. - -UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object -containing the read Unicode code units and written UTF-8 bytes. - -```js -const encoder = new TextEncoder(); -const src = 'this is some data'; -const dest = new Uint8Array(10); -const { read, written } = encoder.encodeInto(src, dest); -``` - -### `textEncoder.encoding` - -* Type: {string} - -The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. +Deprecated alias for global [`TextEncoder`][]. ## `util.toUSVString(string)` @@ -4161,9 +3993,7 @@ npx codemod@latest @nodejs/util-is [Custom inspection functions on objects]: #custom-inspection-functions-on-objects [Custom promisified functions]: #custom-promisified-functions [Customizing `util.inspect` colors]: #customizing-utilinspect-colors -[Internationalization]: intl.md [Module Namespace Object]: https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects -[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ [`'uncaughtException'`]: process.md#event-uncaughtexception [`'warning'`]: process.md#event-warning [`Array.isArray()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray @@ -4174,6 +4004,8 @@ npx codemod@latest @nodejs/util-is [`Object.assign()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign [`Object.freeze()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze [`Runtime.ScriptId`]: https://chromedevtools.github.io/devtools-protocol/1-3/Runtime/#type-ScriptId +[`TextDecoder`]: globals.md#class-textdecoder +[`TextEncoder`]: globals.md#class-textencoder [`assert.deepStrictEqual()`]: assert.md#assertdeepstrictequalactual-expected-message [`assert.partialDeepStrictEqual()`]: assert.md#assertpartialdeepstrictequalactual-expected-message [`console.error()`]: console.md#consoleerrordata-args diff --git a/doc/api/webcrypto.md b/doc/api/webcrypto.md index 98df2850931f..91b6db403a94 100644 --- a/doc/api/webcrypto.md +++ b/doc/api/webcrypto.md @@ -996,7 +996,7 @@ Using the method identified by `algorithm`, this method attempts to generate a digest of `data`. If successful, the returned promise is resolved with an {ArrayBuffer} containing the computed digest. -If `algorithm` is provided as a {string}, it must be one of: +The supported algorithm names are: * `'cSHAKE128'`[^modern-algos] * `'cSHAKE256'`[^modern-algos] @@ -1015,6 +1015,10 @@ If `algorithm` is provided as a {string}, it must be one of: If `algorithm` is provided as an {Object}, it must have a `name` property whose value is one of the above. +For cSHAKE, TurboSHAKE, and KangarooTwelve algorithms, `algorithm` must be a +{CShakeParams}, {TurboShakeParams}, or {KangarooTwelveParams} object, +respectively, with the required `outputLength` property. + ### `subtle.encapsulateBits(encapsulationAlgorithm, encapsulationKey)` <!-- YAML @@ -1869,8 +1873,7 @@ added: - v24.15.0 --> -* Type: {number} represents the requested output length in bits. Must be a - multiple of 8. +* Type: {number} The required output length in bits. Must be a multiple of 8. #### `cShakeParams.functionName` @@ -1886,9 +1889,9 @@ changes: * Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined} -The `functionName` member represents the NIST function-name byte string used to -domain-separate functions built on top of cSHAKE. Non-empty values require -OpenSSL 4.0 or later. Accepted values are: +The optional `functionName` member represents the NIST function-name byte string +used to domain-separate functions built on top of cSHAKE. It defaults to an empty +byte string. Accepted values are: * empty or `undefined` * the ASCII byte sequence `'KMAC'` @@ -1909,11 +1912,8 @@ changes: * Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined} -The `customization` member represents the customization data. Non-empty values -require OpenSSL 4.0 or later. Accepted values are: - -* empty or `undefined` -* up to 512 bytes of data without null bytes +The optional `customization` member is a byte string of at most 512 bytes without +null bytes. It defaults to an empty byte string. ### Class: `EcdhKeyDeriveParams` @@ -2335,8 +2335,8 @@ changes: * Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined} -The optional customization string for KangarooTwelve. It must not exceed 512 -bytes. +The optional customization byte string for KangarooTwelve. It must not exceed +512 bytes and defaults to an empty byte string. #### `kangarooTwelveParams.name` @@ -2356,7 +2356,8 @@ added: - v24.18.0 --> -* Type: {number} represents the requested output length in bits. +* Type: {number} The required output length in bits. Must be a nonzero + multiple of 8. ### Class: `KmacImportParams` @@ -2446,7 +2447,7 @@ changes: description: Renamed `kmacParams.length` to `kmacParams.outputLength`. --> -#### `kmacParams.algorithm` +#### `kmacParams.name` <!-- YAML added: v24.8.0 @@ -2462,8 +2463,7 @@ added: - v24.15.0 --> -* Type: {number} represents the requested output length in bits. Must be a - multiple of 8. +* Type: {number} The required output length in bits. Must be a multiple of 8. #### `kmacParams.customization` @@ -2473,7 +2473,7 @@ added: v24.8.0 * Type: {ArrayBuffer|TypedArray|DataView|Buffer|undefined} -The `customization` member represents the optional customization string. +The optional customization byte string. It defaults to an empty byte string. ### Class: `Pbkdf2Params` @@ -2770,7 +2770,8 @@ added: - v24.18.0 --> -* Type: {number} represents the requested output length in bits. +* Type: {number} The required output length in bits. Must be a nonzero + multiple of 8. [^secure-curves]: See [Secure Curves in the Web Cryptography API][] diff --git a/doc/api/webstreams.md b/doc/api/webstreams.md index 45e87152b86b..3917d732d8f7 100644 --- a/doc/api/webstreams.md +++ b/doc/api/webstreams.md @@ -1634,7 +1634,6 @@ added: v16.7.0 ```mjs import { arrayBuffer } from 'node:stream/consumers'; import { Readable } from 'node:stream'; -import { TextEncoder } from 'node:util'; const encoder = new TextEncoder(); const dataArray = encoder.encode('hello world from consumers!'); @@ -1648,7 +1647,6 @@ console.log(`from readable: ${data.byteLength}`); ```cjs const { arrayBuffer } = require('node:stream/consumers'); const { Readable } = require('node:stream'); -const { TextEncoder } = require('node:util'); const encoder = new TextEncoder(); const dataArray = encoder.encode('hello world from consumers!'); diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 08da7b35f152..62fadae2e47e 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -169,27 +169,16 @@ if (isMainThread) { added: - v23.7.0 - v22.14.0 +changes: + - version: v27.0.0-alpha.0.2.0 + pr-url: https://github.com/nodejs/node/pull/67090 + description: Always `false`, as Node.js no longer runs code in internal threads. --> * Type: {boolean} -Is `true` if this code is running inside of an internal [`Worker`][] thread (e.g the loader thread). - -```bash -node --experimental-loader ./loader.js main.js -``` - -```mjs -// loader.js -import { isInternalThread } from 'node:worker_threads'; -console.log(isInternalThread); // true -``` - -```cjs -// loader.js -const { isInternalThread } = require('node:worker_threads'); -console.log(isInternalThread); // true -``` +Always `false`. Node.js no longer runs user-visible code in internal [`Worker`][] +threads, so this is retained only for backward compatibility. ```mjs // main.js diff --git a/doc/api/zlib.md b/doc/api/zlib.md index acbdf38f9cf9..926d2ad76faa 100644 --- a/doc/api/zlib.md +++ b/doc/api/zlib.md @@ -844,7 +844,10 @@ ignored by the decompression classes. empty dictionary by default) * `info` {boolean} (If `true`, returns an object with `buffer` and `engine`.) * `maxOutputLength` {integer} Limits output size when using - [convenience methods][]. **Default:** [`buffer.kMaxLength`][] + [convenience methods][]. On streaming instances created via + `zlib.create*Decompress()`, this option bounds per-chunk internal buffer + growth rather than cumulative stream output. **Default:** + [`buffer.kMaxLength`][] * `rejectGarbageAfterEnd` {boolean} If `true`, decompression fails when trailing input is detected after the end of the compressed stream. This includes unreadable bytes and, when decompressing gzip, additional gzip @@ -879,7 +882,10 @@ Each Brotli-based class takes an `options` object. All options are optional. * `chunkSize` {integer} **Default:** `16 * 1024` * `params` {Object} Key-value object containing indexed [Brotli parameters][]. * `maxOutputLength` {integer} Limits output size when using - [convenience methods][]. **Default:** [`buffer.kMaxLength`][] + [convenience methods][]. On streaming instances created via + `zlib.create*Decompress()`, this option bounds per-chunk internal buffer + growth rather than cumulative stream output. **Default:** + [`buffer.kMaxLength`][] * `info` {boolean} If `true`, returns an object with `buffer` and `engine`. **Default:** `false` * `rejectGarbageAfterEnd` {boolean} If `true`, decompression fails when input remains after the first complete compressed stream. **Default:** `false` @@ -2294,7 +2300,10 @@ Each Zstd-based class takes an `options` object. All options are optional. must be a non-negative safe integer and must match the input size when compression finishes. Only applicable to Zstd compressors. * `maxOutputLength` {integer} Limits output size when using - [convenience methods][]. **Default:** [`buffer.kMaxLength`][] + [convenience methods][]. On streaming instances created via + `zlib.create*Decompress()`, this option bounds per-chunk internal buffer + growth rather than cumulative stream output. **Default:** + [`buffer.kMaxLength`][] * `info` {boolean} If `true`, returns an object with `buffer` and `engine`. **Default:** `false` * `dictionary` {Buffer|TypedArray|DataView|ArrayBuffer} Optional dictionary used to improve compression efficiency when compressing or decompressing data that @@ -2811,6 +2820,75 @@ with `callback(error, result)`. Every method has a `*Sync` counterpart, which accept the same arguments, but without a callback. +Unlike [convenience methods][], streaming decompressors (`zlib.createGunzip()`, +`zlib.createBrotliDecompress()`, `zlib.createZstdDecompress()`, and related +classes) do not enforce a cumulative output limit via `maxOutputLength`. To cap +total decoded bytes across a stream, count chunk lengths inside a +[`pipeline()`][] [`stream.Transform`][] stage: + +```mjs +import { Transform } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { createGunzip } from 'node:zlib'; + +function createDecodedByteLimit(maxTotalBytes) { + let total = 0; + return new Transform({ + transform(chunk, _encoding, callback) { + total += chunk.length; + if (total > maxTotalBytes) { + const err = new RangeError( + `Decoded output exceeded ${maxTotalBytes} bytes`, + ); + callback(err); + return; + } + callback(null, chunk); + }, + }); +} + +await pipeline( + source, + createGunzip(), + createDecodedByteLimit(64 * 1024), + destination, +); +``` + +```cjs +const { Transform } = require('node:stream'); +const { pipeline } = require('node:stream/promises'); +const { createGunzip } = require('node:zlib'); + +function createDecodedByteLimit(maxTotalBytes) { + let total = 0; + return new Transform({ + transform(chunk, _encoding, callback) { + total += chunk.length; + if (total > maxTotalBytes) { + const err = new RangeError( + `Decoded output exceeded ${maxTotalBytes} bytes`, + ); + callback(err); + return; + } + callback(null, chunk); + }, + }); +} + +pipeline( + source, + createGunzip(), + createDecodedByteLimit(64 * 1024), + destination, +).catch((err) => { + console.error('An error occurred:', err); + process.exitCode = 1; +}); +``` + ### `zlib.brotliCompress(buffer[, options], callback)` <!-- YAML diff --git a/doc/changelogs/CHANGELOG_V27.md b/doc/changelogs/CHANGELOG_V27.md index 51817a0eb6e9..d9b29df5d94b 100644 --- a/doc/changelogs/CHANGELOG_V27.md +++ b/doc/changelogs/CHANGELOG_V27.md @@ -8,6 +8,7 @@ </tr> <tr> <td> +<a href="#27.0.0-alpha.0.2.0">27.0.0-alpha.0.2.0</a><br/> <a href="#27.0.0-alpha.0.1.1">27.0.0-alpha.0.1.1</a><br/> <a href="#27.0.0-alpha.0.1.0">27.0.0-alpha.0.1.0</a><br/> <a href="#27.0.0-alpha.0.0.0">27.0.0-alpha.0.0.0</a><br/> @@ -44,6 +45,277 @@ * [io.js](CHANGELOG_IOJS.md) * [Archive](CHANGELOG_ARCHIVE.md) +<a id="27.0.0-alpha.0.2.0"></a> + +## 2026-11-25, Version 27.0.0-alpha.0.2.0 (Alpha), @aduh95 + +### Notable Changes + +* \[[`5e297a0843`](https://github.com/nodejs/node/commit/5e297a0843)] - **doc**: deprecate `util.TextDecoder` and `util.TextEncoder` (LiviaMedeiros) [#67461](https://github.com/nodejs/node/pull/67461) +* \[[`265bbc1b9c`](https://github.com/nodejs/node/commit/265bbc1b9c)] - **(SEMVER-MINOR)** **http2**: add missing setHeaders (jakecastelli) [#67597](https://github.com/nodejs/node/pull/67597) +* \[[`eb78e5be2f`](https://github.com/nodejs/node/commit/eb78e5be2f)] - **(SEMVER-MINOR)** **http2**: add callback to informational header methods (Yuya Inoue) [#67470](https://github.com/nodejs/node/pull/67470) +* \[[`40d7e2d235`](https://github.com/nodejs/node/commit/40d7e2d235)] - **(SEMVER-MINOR)** **lib**: graduate the `--process-timeout` option (James M Snell) [#67506](https://github.com/nodejs/node/pull/67506) +* \[[`bfded1531c`](https://github.com/nodejs/node/commit/bfded1531c)] - **module**: remove async module customization hooks (Geoffrey Booth) [#67090](https://github.com/nodejs/node/pull/67090) +* \[[`82d6f5dd1b`](https://github.com/nodejs/node/commit/82d6f5dd1b)] - **(SEMVER-MINOR)** **os**: expose `guessFileDescriptorType` (Vlad Frangu) [#58060](https://github.com/nodejs/node/pull/58060) +* \[[`7f6fae9285`](https://github.com/nodejs/node/commit/7f6fae9285)] - **sqlite**: mark as stable (Christian Aurich Zanettini Martins) [#67654](https://github.com/nodejs/node/pull/67654) +* \[[`a6fc41c2fc`](https://github.com/nodejs/node/commit/a6fc41c2fc)] - **(SEMVER-MINOR)** **src**: restore tty state on exit only if changed (Matteo Collina) [#66753](https://github.com/nodejs/node/pull/66753) +* \[[`66b97e61bc`](https://github.com/nodejs/node/commit/66b97e61bc)] - **(SEMVER-MINOR)** **tls**: docs-deprecate TLS renegotiation, add allowRenegotiation opt-in (Tim Perry) [#67532](https://github.com/nodejs/node/pull/67532) + +### Commits + +* \[[`b6567ea812`](https://github.com/nodejs/node/commit/b6567ea812)] - **benchmark**: throw on invalid type in fs and webstorage (Minho Yoo) [#66647](https://github.com/nodejs/node/pull/66647) +* \[[`9c88e74b3f`](https://github.com/nodejs/node/commit/9c88e74b3f)] - **buffer**: use typed arrays for 64-bit BigInt accessors (Gürgün Dayıoğlu) [#67549](https://github.com/nodejs/node/pull/67549) +* \[[`8dc536f7eb`](https://github.com/nodejs/node/commit/8dc536f7eb)] - **buffer**: share search range logic between indexOf implementations (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`9a8fe74549`](https://github.com/nodejs/node/commit/9a8fe74549)] - **buffer**: stop clamping indexOf byteOffset to int32 (Ved Chaudhari) [#67009](https://github.com/nodejs/node/pull/67009) +* \[[`aebf09250d`](https://github.com/nodejs/node/commit/aebf09250d)] - **build**: keep PGO settings out of addon builds (Vladimir Morozov) [#67638](https://github.com/nodejs/node/pull/67638) +* \[[`01470de44d`](https://github.com/nodejs/node/commit/01470de44d)] - **build**: re-run configure to regenerate out/Makefile (Christian Aurich Zanettini Martins) [#67534](https://github.com/nodejs/node/pull/67534) +* \[[`625c058354`](https://github.com/nodejs/node/commit/625c058354)] - **build**: trigger devcontainer build from daily (Ethan Arrowood) [#67153](https://github.com/nodejs/node/pull/67153) +* \[[`b3c164d592`](https://github.com/nodejs/node/commit/b3c164d592)] - **build**: fix AIX shared library exports generation (Stewart X Addison) [#67359](https://github.com/nodejs/node/pull/67359) +* \[[`6cd8f45028`](https://github.com/nodejs/node/commit/6cd8f45028)] - **build**: fix GCC warnings when building V8 with gnu++20 (Joyee Cheung) [#67279](https://github.com/nodejs/node/pull/67279) +* \[[`fa26784ff6`](https://github.com/nodejs/node/commit/fa26784ff6)] - **build,win**: update WinGet configurations to Python 3.15 (Mike McCready) [#67431](https://github.com/nodejs/node/pull/67431) +* \[[`72a6423a28`](https://github.com/nodejs/node/commit/72a6423a28)] - **child\_process**: copy split permission flag values (RafaelGSS) [#66725](https://github.com/nodejs/node/pull/66725) +* \[[`3791f4f89b`](https://github.com/nodejs/node/commit/3791f4f89b)] - **crypto**: wire up SLH-DSA with BoringSSL (Filip Skokan) [#67483](https://github.com/nodejs/node/pull/67483) +* \[[`d070e62c09`](https://github.com/nodejs/node/commit/d070e62c09)] - **crypto**: add TicketHmacCtx alias for TLS ticket key callbacks (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`9121206dd0`](https://github.com/nodejs/node/commit/9121206dd0)] - **crypto**: share digest length handling between HashInit overloads (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`ded11f3c27`](https://github.com/nodejs/node/commit/ded11f3c27)] - **crypto**: deduplicate WebCrypto SPKI/PKCS#8 exporter lookup (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`3bda549c05`](https://github.com/nodejs/node/commit/3bda549c05)] - **crypto**: share asymmetric WebCrypto key import logic (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`ea3518de0e`](https://github.com/nodejs/node/commit/ea3518de0e)] - **crypto**: use const STACK\_OF(SSL\_CIPHER)\* for SSL\_get\_ciphers (Lily Chen) [#67443](https://github.com/nodejs/node/pull/67443) +* \[[`91414a11aa`](https://github.com/nodejs/node/commit/91414a11aa)] - **deps**: update histogram to 0.12.1 (Node.js GitHub Bot) [#66818](https://github.com/nodejs/node/pull/66818) +* \[[`63548fb8f0`](https://github.com/nodejs/node/commit/63548fb8f0)] - **deps**: update nbytes to 0.1.5 (Node.js GitHub Bot) [#67688](https://github.com/nodejs/node/pull/67688) +* \[[`bc8732f31d`](https://github.com/nodejs/node/commit/bc8732f31d)] - **deps**: update zlib to 1.4-401d185 (Node.js GitHub Bot) [#67689](https://github.com/nodejs/node/pull/67689) +* \[[`ebad21ba08`](https://github.com/nodejs/node/commit/ebad21ba08)] - **deps**: update simdjson to 5.2.0 (Node.js GitHub Bot) [#67690](https://github.com/nodejs/node/pull/67690) +* \[[`f230732dec`](https://github.com/nodejs/node/commit/f230732dec)] - **deps**: update undici to 8.13.1 (Node.js GitHub Bot) [#67692](https://github.com/nodejs/node/pull/67692) +* \[[`ae38cb5715`](https://github.com/nodejs/node/commit/ae38cb5715)] - **deps**: update ada to 4.1.1 (Node.js GitHub Bot) [#67624](https://github.com/nodejs/node/pull/67624) +* \[[`c540b35c47`](https://github.com/nodejs/node/commit/c540b35c47)] - **deps**: upgrade npm to 12.2.3 (npm team) [#67584](https://github.com/nodejs/node/pull/67584) +* \[[`645be14fcb`](https://github.com/nodejs/node/commit/645be14fcb)] - **deps**: update zlib to 1.4-ec453dc (Node.js GitHub Bot) [#67475](https://github.com/nodejs/node/pull/67475) +* \[[`de52e06e41`](https://github.com/nodejs/node/commit/de52e06e41)] - **deps**: update libffi to 3.8.1 (Node.js GitHub Bot) [#67476](https://github.com/nodejs/node/pull/67476) +* \[[`a8944e6405`](https://github.com/nodejs/node/commit/a8944e6405)] - **deps**: update googletest to e882c36410197464e3429546e6a7d5e217bde51e (Node.js GitHub Bot) [#67477](https://github.com/nodejs/node/pull/67477) +* \[[`00fec20b5a`](https://github.com/nodejs/node/commit/00fec20b5a)] - **deps**: patch V8 to 15.6.75.60 (Node.js GitHub Bot) [#67479](https://github.com/nodejs/node/pull/67479) +* \[[`c2b046330f`](https://github.com/nodejs/node/commit/c2b046330f)] - **deps**: update inspector\_protocol to c0045057ce801744c5e88596a2f1bab1802e (Node.js GitHub Bot) [#66653](https://github.com/nodejs/node/pull/66653) +* \[[`dd2554d704`](https://github.com/nodejs/node/commit/dd2554d704)] - **dgram**: fix abort on negative zero buffer size (JuHyeong424) [#67662](https://github.com/nodejs/node/pull/67662) +* \[[`5c1e91cd31`](https://github.com/nodejs/node/commit/5c1e91cd31)] - **diagnostics\_channel**: use `DisposableStack` primordial (LiviaMedeiros) [#67533](https://github.com/nodejs/node/pull/67533) +* \[[`d5779fc1ea`](https://github.com/nodejs/node/commit/d5779fc1ea)] - _**Revert**_ "**diagnostics\_channel**: replace using with try-finally" (LiviaMedeiros) [#67533](https://github.com/nodejs/node/pull/67533) +* \[[`94e1e1ddfb`](https://github.com/nodejs/node/commit/94e1e1ddfb)] - **diagnostics\_channel**: add threadpool work event (Ilyas Shabi) [#65982](https://github.com/nodejs/node/pull/65982) +* \[[`92a0cc4a62`](https://github.com/nodejs/node/commit/92a0cc4a62)] - **dns**: share reply parsing skeleton between record parsers (James M Snell) [#67497](https://github.com/nodejs/node/pull/67497) +* \[[`598aa2941b`](https://github.com/nodejs/node/commit/598aa2941b)] - **doc**: fix http response.writeProcessing() description (Yuya Inoue) [#67705](https://github.com/nodejs/node/pull/67705) +* \[[`8317be4131`](https://github.com/nodejs/node/commit/8317be4131)] - **doc**: document stream/iter iterator results and from() identity (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`a955c27f2b`](https://github.com/nodejs/node/commit/a955c27f2b)] - **doc**: clarify crypto and Web Crypto options (Filip Skokan) [#67565](https://github.com/nodejs/node/pull/67565) +* \[[`42de61e1f0`](https://github.com/nodejs/node/commit/42de61e1f0)] - **doc**: add verification steps of V8 major upgrades (Chengzhong Wu) [#67559](https://github.com/nodejs/node/pull/67559) +* \[[`4b806e1644`](https://github.com/nodejs/node/commit/4b806e1644)] - **doc**: fix SEA implementation link in maintaining guide (Faris Basha TM) [#67555](https://github.com/nodejs/node/pull/67555) +* \[[`0ffcd35752`](https://github.com/nodejs/node/commit/0ffcd35752)] - **doc**: clarify cumulative output limits for zlib streams (sophia) [#67373](https://github.com/nodejs/node/pull/67373) +* \[[`99f0fc42e9`](https://github.com/nodejs/node/commit/99f0fc42e9)] - **doc**: fix http response.writeInformation() signature (Yuya Inoue) [#67492](https://github.com/nodejs/node/pull/67492) +* \[[`472f4b45a5`](https://github.com/nodejs/node/commit/472f4b45a5)] - **doc**: swap `util.TextDecoder` and `util.TextEncoder` with globals (LiviaMedeiros) [#67461](https://github.com/nodejs/node/pull/67461) +* \[[`922140626b`](https://github.com/nodejs/node/commit/922140626b)] - **doc**: use global `TextDecoder` and `TextEncoder` instead of `util` (LiviaMedeiros) [#67461](https://github.com/nodejs/node/pull/67461) +* \[[`5e297a0843`](https://github.com/nodejs/node/commit/5e297a0843)] - **doc**: deprecate `util.TextDecoder` and `util.TextEncoder` (LiviaMedeiros) [#67461](https://github.com/nodejs/node/pull/67461) +* \[[`e834c1bafa`](https://github.com/nodejs/node/commit/e834c1bafa)] - **doc,test**: clarify http1 insecure validation (Ethan Arrowood) [#67560](https://github.com/nodejs/node/pull/67560) +* \[[`43e6622ae6`](https://github.com/nodejs/node/commit/43e6622ae6)] - **esm**: avoid dictionary-mode objects in import() (Matteo Collina) [#67554](https://github.com/nodejs/node/pull/67554) +* \[[`f6d72af926`](https://github.com/nodejs/node/commit/f6d72af926)] - **fs**: report EROFS from recursive mkdir() (Yohannes Desta) [#67500](https://github.com/nodejs/node/pull/67500) +* \[[`e0921d226f`](https://github.com/nodejs/node/commit/e0921d226f)] - **fs**: stat src through symlinks in cpSync() when dereference is set (Yohannes Desta) [#67340](https://github.com/nodejs/node/pull/67340) +* \[[`ccd7a5d3aa`](https://github.com/nodejs/node/commit/ccd7a5d3aa)] - **fs**: read data when highWaterMark is 0 (Hamza Kargin) [#67669](https://github.com/nodejs/node/pull/67669) +* \[[`5062ac2f9a`](https://github.com/nodejs/node/commit/5062ac2f9a)] - **fs**: fix abort on negative zero write length (Christian Aurich Zanettini Martins) [#67524](https://github.com/nodejs/node/pull/67524) +* \[[`c63d98624d`](https://github.com/nodejs/node/commit/c63d98624d)] - **fs**: do not disable fd-based APIs in permission audit mode (Rafael Gonzaga) [#66726](https://github.com/nodejs/node/pull/66726) +* \[[`7756eff9bb`](https://github.com/nodejs/node/commit/7756eff9bb)] - **fs**: use try...finally for abort race (René) [#67545](https://github.com/nodejs/node/pull/67545) +* \[[`831385fd53`](https://github.com/nodejs/node/commit/831385fd53)] - **fs**: restore stack traces of fs/promises stat permission errors (Ved Chaudhari) [#67525](https://github.com/nodejs/node/pull/67525) +* \[[`4ce81ec9f8`](https://github.com/nodejs/node/commit/4ce81ec9f8)] - **fs**: validate opendir() bufferSize before opening the directory (Yohannes Desta) [#67183](https://github.com/nodejs/node/pull/67183) +* \[[`081f642b83`](https://github.com/nodejs/node/commit/081f642b83)] - **fs**: use GetAsyncReqWrap() in the remaining async/sync bindings (James M Snell) [#67497](https://github.com/nodejs/node/pull/67497) +* \[[`84b846ae46`](https://github.com/nodejs/node/commit/84b846ae46)] - **fs**: check permissions once in bindings with async and sync paths (James M Snell) [#67497](https://github.com/nodejs/node/pull/67497) +* \[[`c8b430f17f`](https://github.com/nodejs/node/commit/c8b430f17f)] - **fs**: respect setDefaultHighWaterMark in ReadStream (Hamza Kargin) [#66956](https://github.com/nodejs/node/pull/66956) +* \[[`56bc6f0fde`](https://github.com/nodejs/node/commit/56bc6f0fde)] - **fs**: use correct position when retrying writev (Christian Aurich Zanettini Martins) [#66203](https://github.com/nodejs/node/pull/66203) +* \[[`2ad4108aca`](https://github.com/nodejs/node/commit/2ad4108aca)] - **fs**: restore stack traces of fs/promises readFile and writeFile errors (Ved Chaudhari) [#66757](https://github.com/nodejs/node/pull/66757) +* \[[`399228bd0f`](https://github.com/nodejs/node/commit/399228bd0f)] - **fs,path**: fix glob globstar section bounds (Gürgün Dayıoğlu) [#66738](https://github.com/nodejs/node/pull/66738) +* \[[`5b15842d98`](https://github.com/nodejs/node/commit/5b15842d98)] - **http**: do not reuse expired free sockets (dennev) [#67292](https://github.com/nodejs/node/pull/67292) +* \[[`2f5991e1ca`](https://github.com/nodejs/node/commit/2f5991e1ca)] - **http**: compute body chunk length from decoded bytes (Paolo Insogna) [#67615](https://github.com/nodejs/node/pull/67615) +* \[[`f0a79a212f`](https://github.com/nodejs/node/commit/f0a79a212f)] - **http**: keep request option copies in fast mode (Gürgün Dayıoğlu) [#67395](https://github.com/nodejs/node/pull/67395) +* \[[`d605804cb6`](https://github.com/nodejs/node/commit/d605804cb6)] - **http**: share insecureHTTPParser/httpValidation option handling (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`67ae162800`](https://github.com/nodejs/node/commit/67ae162800)] - **http**: forward-port the pending-read fix for CVE-2026-105481 (emyei) [#67073](https://github.com/nodejs/node/pull/67073) +* \[[`1be7d94840`](https://github.com/nodejs/node/commit/1be7d94840)] - **http,http2**: copy header arrays in setHeader (Ethan Arrowood) [#67528](https://github.com/nodejs/node/pull/67528) +* \[[`265bbc1b9c`](https://github.com/nodejs/node/commit/265bbc1b9c)] - **(SEMVER-MINOR)** **http2**: add missing setHeaders (jakecastelli) [#67597](https://github.com/nodejs/node/pull/67597) +* \[[`b6d94f3048`](https://github.com/nodejs/node/commit/b6d94f3048)] - **http2**: don't fail response reads after clean RST\_STREAM (Tim Perry) [#67558](https://github.com/nodejs/node/pull/67558) +* \[[`6bde4f8f87`](https://github.com/nodejs/node/commit/6bde4f8f87)] - **http2**: fix eos() for HTTP/2 streams after clean end & close (Tim Perry) [#67553](https://github.com/nodejs/node/pull/67553) +* \[[`eb78e5be2f`](https://github.com/nodejs/node/commit/eb78e5be2f)] - **(SEMVER-MINOR)** **http2**: add callback to informational header methods (Yuya Inoue) [#67470](https://github.com/nodejs/node/pull/67470) +* \[[`656d78d2cd`](https://github.com/nodejs/node/commit/656d78d2cd)] - **http2**: allow client request header injection via diagnostics\_channel (Bryan English) [#67069](https://github.com/nodejs/node/pull/67069) +* \[[`f173879f53`](https://github.com/nodejs/node/commit/f173879f53)] - **http2**: enforce maxSessionMemory for client requests (Gabe De Mesa) [#67361](https://github.com/nodejs/node/pull/67361) +* \[[`e6eb31804e`](https://github.com/nodejs/node/commit/e6eb31804e)] - **http2**: do not end compat requests reset before END\_STREAM (Matteo Collina) [#67061](https://github.com/nodejs/node/pull/67061) +* \[[`bb6d44da72`](https://github.com/nodejs/node/commit/bb6d44da72)] - **http2**: send deferred RST\_STREAM on stream destroy (Yuya Inoue) [#67372](https://github.com/nodejs/node/pull/67372) +* \[[`c15d48a58f`](https://github.com/nodejs/node/commit/c15d48a58f)] - **http2**: flush final GOAWAY after pending writes (Emerson Gomes) [#66834](https://github.com/nodejs/node/pull/66834) +* \[[`930a71cb55`](https://github.com/nodejs/node/commit/930a71cb55)] - **https**: encode all TLS fields in agent names (Paolo Insogna) [#67641](https://github.com/nodejs/node/pull/67641) +* \[[`72859e1f20`](https://github.com/nodejs/node/commit/72859e1f20)] - **inspector**: support attaching to a running process in probe mode (Joyee Cheung) [#67201](https://github.com/nodejs/node/pull/67201) +* \[[`28cb3cbcc9`](https://github.com/nodejs/node/commit/28cb3cbcc9)] - **inspector**: disconnect handles before releasing interfaces (Fatih Güzel) [#67281](https://github.com/nodejs/node/pull/67281) +* \[[`cadf10a9ce`](https://github.com/nodejs/node/commit/cadf10a9ce)] - **lib**: use indexed append in ZIP central directory parser (Roberto Bianchi) [#67456](https://github.com/nodejs/node/pull/67456) +* \[[`8e620b994b`](https://github.com/nodejs/node/commit/8e620b994b)] - **lib**: implement source map scopes decoder (Chengzhong Wu) [#67594](https://github.com/nodejs/node/pull/67594) +* \[[`e18a140916`](https://github.com/nodejs/node/commit/e18a140916)] - **lib**: move source map VLQ decoding into its own module (Chengzhong Wu) [#67594](https://github.com/nodejs/node/pull/67594) +* \[[`40d7e2d235`](https://github.com/nodejs/node/commit/40d7e2d235)] - **(SEMVER-MINOR)** **lib**: graduate the --process-timeout option (James M Snell) [#67506](https://github.com/nodejs/node/pull/67506) +* \[[`eeea6e46c0`](https://github.com/nodejs/node/commit/eeea6e46c0)] - **lib**: replace `SafePromiseAll` with `SafePromiseAllReturn*` (Livia Medeiros) [#67602](https://github.com/nodejs/node/pull/67602) +* \[[`4b810e2c5e`](https://github.com/nodejs/node/commit/4b810e2c5e)] - **lib**: legitimize `SuppressedError` as primordial (Livia Medeiros) [#67551](https://github.com/nodejs/node/pull/67551) +* \[[`d4d048c5ca`](https://github.com/nodejs/node/commit/d4d048c5ca)] - **lib**: add ERM classes to primordials (LiviaMedeiros) [#67533](https://github.com/nodejs/node/pull/67533) +* \[[`d8abcaf38a`](https://github.com/nodejs/node/commit/d8abcaf38a)] - **lib**: avoid using \_\_proto\_\_: null in AbortController/AbortSignal (James M Snell) [#66678](https://github.com/nodejs/node/pull/66678) +* \[[`4ac51231d2`](https://github.com/nodejs/node/commit/4ac51231d2)] - **lib**: stop refreshing composite AbortSignals (Robert Nagy) [#67543](https://github.com/nodejs/node/pull/67543) +* \[[`4fd45e2bf7`](https://github.com/nodejs/node/commit/4fd45e2bf7)] - **lib**: end --eval crypto wrapper code with a newline (Lazizbek Ergashev) [#67162](https://github.com/nodejs/node/pull/67162) +* \[[`f82c9d3200`](https://github.com/nodejs/node/commit/f82c9d3200)] - **lib**: use indexed appends for dependent signals (Roberto Bianchi) [#67299](https://github.com/nodejs/node/pull/67299) +* \[[`780df00fde`](https://github.com/nodejs/node/commit/780df00fde)] - **lib**: avoid dead code elimination with node:bench (James M Snell) [#66664](https://github.com/nodejs/node/pull/66664) +* \[[`426c7589f7`](https://github.com/nodejs/node/commit/426c7589f7)] - **lib**: add gc options to node:bench (James M Snell) [#66664](https://github.com/nodejs/node/pull/66664) +* \[[`76b8e83ec5`](https://github.com/nodejs/node/commit/76b8e83ec5)] - **lib**: default bench operations to 1 (James M Snell) [#66664](https://github.com/nodejs/node/pull/66664) +* \[[`d15f18b498`](https://github.com/nodejs/node/commit/d15f18b498)] - **lib**: update node:bench reporters to include sys info (James M Snell) [#66664](https://github.com/nodejs/node/pull/66664) +* \[[`0ec38b2f68`](https://github.com/nodejs/node/commit/0ec38b2f68)] - **meta**: add christianaurichzm to .mailmap (Christian Aurich Zanettini Martins) [#67625](https://github.com/nodejs/node/pull/67625) +* \[[`81cd4ff151`](https://github.com/nodejs/node/commit/81cd4ff151)] - **meta**: add Fatih Güzel to .mailmap (Fatih Güzel) [#67622](https://github.com/nodejs/node/pull/67622) +* \[[`2e4e1d2da7`](https://github.com/nodejs/node/commit/2e4e1d2da7)] - **module**: disable the compile cache while V8 coverage is collected (Shelley Vohr) [#67120](https://github.com/nodejs/node/pull/67120) +* \[[`3fd2893a3a`](https://github.com/nodejs/node/commit/3fd2893a3a)] - **module**: avoid dictionary-mode objects on hot paths (Matteo Collina) [#67552](https://github.com/nodejs/node/pull/67552) +* \[[`21bc925b48`](https://github.com/nodejs/node/commit/21bc925b48)] - **module**: don't map a trailing generated-only segment (Jacky Zhao) [#66264](https://github.com/nodejs/node/pull/66264) +* \[[`4d330e28e4`](https://github.com/nodejs/node/commit/4d330e28e4)] - **module**: store source map mappings in a typed array (Jacky Zhao) [#66261](https://github.com/nodejs/node/pull/66261) +* \[[`bfded1531c`](https://github.com/nodejs/node/commit/bfded1531c)] - **module**: remove async module customization hooks (Geoffrey Booth) [#67090](https://github.com/nodejs/node/pull/67090) +* \[[`38d063ed3e`](https://github.com/nodejs/node/commit/38d063ed3e)] - **net**: validate onread buffers before each read (Fatih Güzel) [#67407](https://github.com/nodejs/node/pull/67407) +* \[[`bed7be9dbe`](https://github.com/nodejs/node/commit/bed7be9dbe)] - **net**: clear closed handles before emitting close (inoway46) [#67215](https://github.com/nodejs/node/pull/67215) +* \[[`fc28b7070c`](https://github.com/nodejs/node/commit/fc28b7070c)] - **os**: fix abort on negative zero pid or priority (Zelalem Habtamu) [#67651](https://github.com/nodejs/node/pull/67651) +* \[[`82d6f5dd1b`](https://github.com/nodejs/node/commit/82d6f5dd1b)] - **(SEMVER-MINOR)** **os**: expose `guessFileDescriptorType` (Vlad Frangu) [#58060](https://github.com/nodejs/node/pull/58060) +* \[[`05f33bf366`](https://github.com/nodejs/node/commit/05f33bf366)] - **path**: avoid building error label per argument in resolve (Rafael Gonzaga) [#66616](https://github.com/nodejs/node/pull/66616) +* \[[`ebde3933a4`](https://github.com/nodejs/node/commit/ebde3933a4)] - **permission**: reject empty reference in drop() (Rafael Gonzaga) [#66732](https://github.com/nodejs/node/pull/66732) +* \[[`79405fc722`](https://github.com/nodejs/node/commit/79405fc722)] - **permission**: drop fs grants regardless of the path's current type (Rafael Gonzaga) [#66766](https://github.com/nodejs/node/pull/66766) +* \[[`10394eea40`](https://github.com/nodejs/node/commit/10394eea40)] - **quic**: fix abort on handshake failure in connect() (Christian Aurich Zanettini Martins) [#67617](https://github.com/nodejs/node/pull/67617) +* \[[`70182bcbf4`](https://github.com/nodejs/node/commit/70182bcbf4)] - **quic**: honor enableEarlyData on servers (Efe Karasakal) [#67562](https://github.com/nodejs/node/pull/67562) +* \[[`27b8b0bbce`](https://github.com/nodejs/node/commit/27b8b0bbce)] - **quic**: add option waitUntilAvailable to creating streams (Marten Richter) [#65331](https://github.com/nodejs/node/pull/65331) +* \[[`ac7c1ac619`](https://github.com/nodejs/node/commit/ac7c1ac619)] - **quic**: fix h3 session close on early stream destroy (Ethan Arrowood) [#67446](https://github.com/nodejs/node/pull/67446) +* \[[`c6581d8809`](https://github.com/nodejs/node/commit/c6581d8809)] - **quic**: validate maxPayloadSize range (Christian Aurich Zanettini Martins) [#67531](https://github.com/nodejs/node/pull/67531) +* \[[`e4aacfd616`](https://github.com/nodejs/node/commit/e4aacfd616)] - **quic**: handle application-specific no-error codes (Efe Karasakal) [#67094](https://github.com/nodejs/node/pull/67094) +* \[[`a4d6596b44`](https://github.com/nodejs/node/commit/a4d6596b44)] - **quic**: create gen. getWriter for stream/iter (Marten Richter) [#66513](https://github.com/nodejs/node/pull/66513) +* \[[`8eae7e4a11`](https://github.com/nodejs/node/commit/8eae7e4a11)] - **quic**: fix edge cases where stream FIN would be lost (Tim Perry) [#66759](https://github.com/nodejs/node/pull/66759) +* \[[`73f7796c35`](https://github.com/nodejs/node/commit/73f7796c35)] - **quic**: fix per-session SSL leak (Tim Perry) [#66730](https://github.com/nodejs/node/pull/66730) +* \[[`a126f00a6b`](https://github.com/nodejs/node/commit/a126f00a6b)] - **repl**: redraw highlighted input once per chunk (Max Fisher) [#67422](https://github.com/nodejs/node/pull/67422) +* \[[`62757393e4`](https://github.com/nodejs/node/commit/62757393e4)] - **sea**: add source maps for SEA with VFS (Matteo Collina) [#67503](https://github.com/nodejs/node/pull/67503) +* \[[`7363c8efe1`](https://github.com/nodejs/node/commit/7363c8efe1)] - **sqlite**: skip query trace while an exception is pending (Jiawen Geng) [#67538](https://github.com/nodejs/node/pull/67538) +* \[[`b9238331b0`](https://github.com/nodejs/node/commit/b9238331b0)] - **sqlite**: finalize statements prepared during close (Jiawen Geng) [#67539](https://github.com/nodejs/node/pull/67539) +* \[[`cd86a6b002`](https://github.com/nodejs/node/commit/cd86a6b002)] - **sqlite**: bind empty ArrayBuffer as empty blob (Guilherme Araújo) [#67657](https://github.com/nodejs/node/pull/67657) +* \[[`7f6fae9285`](https://github.com/nodejs/node/commit/7f6fae9285)] - **sqlite**: mark as stable (Christian Aurich Zanettini Martins) [#67654](https://github.com/nodejs/node/pull/67654) +* \[[`e7b44ef89d`](https://github.com/nodejs/node/commit/e7b44ef89d)] - **sqlite**: avoid resetting a finalized statement (Guilherme Araújo) [#67557](https://github.com/nodejs/node/pull/67557) +* \[[`79a8d334f1`](https://github.com/nodejs/node/commit/79a8d334f1)] - **sqlite**: share SQLTagStore statement preparation (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`dabbbee0fb`](https://github.com/nodejs/node/commit/dabbbee0fb)] - **src**: speed up heap profile serialization (Ilyas Shabi) [#67685](https://github.com/nodejs/node/pull/67685) +* \[[`3949e0a04c`](https://github.com/nodejs/node/commit/3949e0a04c)] - **src**: cache trace category lookups on hot paths (Gürgün Dayıoğlu) [#67502](https://github.com/nodejs/node/pull/67502) +* \[[`6abd8c49e3`](https://github.com/nodejs/node/commit/6abd8c49e3)] - **src**: skip the async id stack when nobody sees it (Nigro Simone) [#66511](https://github.com/nodejs/node/pull/66511) +* \[[`76ab721fe7`](https://github.com/nodejs/node/commit/76ab721fe7)] - **src**: reserve simdjson padding in parsePackageJSON (Daniel Lemire) [#67623](https://github.com/nodejs/node/pull/67623) +* \[[`46872fa7be`](https://github.com/nodejs/node/commit/46872fa7be)] - **src**: fix hang when joining workers in process.exit() (Manzoor Wani) [#66171](https://github.com/nodejs/node/pull/66171) +* \[[`955056203b`](https://github.com/nodejs/node/commit/955056203b)] - **src**: do not shrink async resources on every pop (Nigro Simone) [#66344](https://github.com/nodejs/node/pull/66344) +* \[[`0258befb4a`](https://github.com/nodejs/node/commit/0258befb4a)] - **src**: share snapshot Serialize()/Deserialize() logic for binding data (James M Snell) [#67497](https://github.com/nodejs/node/pull/67497) +* \[[`ee149feeee`](https://github.com/nodejs/node/commit/ee149feeee)] - **src**: warn when heap would exceed pointer compression limit (James M Snell) [#67468](https://github.com/nodejs/node/pull/67468) +* \[[`9af13a6f03`](https://github.com/nodejs/node/commit/9af13a6f03)] - **src**: avoid aborting on filesystem errors in node --run (Jason Zhang) [#67270](https://github.com/nodejs/node/pull/67270) +* \[[`085941ad49`](https://github.com/nodejs/node/commit/085941ad49)] - **src**: write strings to streams without flattening (Guilherme Araújo) [#67435](https://github.com/nodejs/node/pull/67435) +* \[[`dcb440f177`](https://github.com/nodejs/node/commit/dcb440f177)] - **src**: give small stream reads their own buffer (Orgad Shaneh) [#67327](https://github.com/nodejs/node/pull/67327) +* \[[`7f58a90a8e`](https://github.com/nodejs/node/commit/7f58a90a8e)] - **src**: adopt FallthroughCallback signature of Dispatchable (Chengzhong Wu) [#66653](https://github.com/nodejs/node/pull/66653) +* \[[`a6fc41c2fc`](https://github.com/nodejs/node/commit/a6fc41c2fc)] - **(SEMVER-MINOR)** **src**: restore tty state on exit only if changed (Matteo Collina) [#66753](https://github.com/nodejs/node/pull/66753) +* \[[`83454d9ec2`](https://github.com/nodejs/node/commit/83454d9ec2)] - **src,permission**: throw remaining fs errors async (Rafael Gonzaga) [#67037](https://github.com/nodejs/node/pull/67037) +* \[[`b92011655a`](https://github.com/nodejs/node/commit/b92011655a)] - **stream**: reject operators on empty streams with aborted signal (Ved Chaudhari) [#67637](https://github.com/nodejs/node/pull/67637) +* \[[`76b0d6c519`](https://github.com/nodejs/node/commit/76b0d6c519)] - **stream**: retry read after construct when hwm is 0 (Hamza Kargin) [#67670](https://github.com/nodejs/node/pull/67670) +* \[[`3a8a88e1cc`](https://github.com/nodejs/node/commit/3a8a88e1cc)] - **stream**: fix stale byte stream queue size (Mattias Buelens) [#67499](https://github.com/nodejs/node/pull/67499) +* \[[`03eab40fa4`](https://github.com/nodejs/node/commit/03eab40fa4)] - **stream**: run a replaced write() in the flowing pipe (Nigro Simone) [#66596](https://github.com/nodejs/node/pull/66596) +* \[[`689049e37b`](https://github.com/nodejs/node/commit/689049e37b)] - **stream**: swap the order of stream/iter result fields (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`8d2339dd6e`](https://github.com/nodejs/node/commit/8d2339dd6e)] - **stream**: only release stream/iter reads cancellable while pending (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`1d13a1a839`](https://github.com/nodejs/node/commit/1d13a1a839)] - **stream**: lighten single-chunk stream/iter broadcast()/share() batches (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`954ce79d39`](https://github.com/nodejs/node/commit/954ce79d39)] - **stream**: skip batch entry for single-chunk stream/iter push() writes (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`008eb16631`](https://github.com/nodejs/node/commit/008eb16631)] - **stream**: avoid a promise per stream/iter from() read in pipelines (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`1503971247`](https://github.com/nodejs/node/commit/1503971247)] - **stream**: create the stream/iter share() read reaction once per consumer (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`479c587d2f`](https://github.com/nodejs/node/commit/479c587d2f)] - **stream**: keep stream/iter broadcast waiters in reused lists (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`6f74cc6cbc`](https://github.com/nodejs/node/commit/6f74cc6cbc)] - **stream**: create stream/iter pending promises without a result object (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`90b592d0d5`](https://github.com/nodejs/node/commit/90b592d0d5)] - **stream**: do not keep stream/iter from() sync sources busy for a tick (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`e2fccac744`](https://github.com/nodejs/node/commit/e2fccac744)] - **stream**: read a single stream/iter merge() source without a generator (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`e304a0708c`](https://github.com/nodejs/node/commit/e304a0708c)] - **stream**: normalize stream/iter fromSync() inputs without generators (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`ba74ca5c5b`](https://github.com/nodejs/node/commit/ba74ca5c5b)] - **stream**: create stream/iter from() value streams as class instances (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`ccefb83dfe`](https://github.com/nodejs/node/commit/ccefb83dfe)] - **stream**: pump stream/iter Broadcast.from() sources with fewer layers (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`28c874043c`](https://github.com/nodejs/node/commit/28c874043c)] - **stream**: read stream/iter share() sync sources at once (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`017564e942`](https://github.com/nodejs/node/commit/017564e942)] - **stream**: read stream/iter from() sync sources without a generator (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`d7be9e043e`](https://github.com/nodejs/node/commit/d7be9e043e)] - **stream**: apply stream/iter stateful transforms without async generators (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`6843a59eef`](https://github.com/nodejs/node/commit/6843a59eef)] - **stream**: read stream/iter share() consumers without a chain per read (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`a9ad2cddf6`](https://github.com/nodejs/node/commit/a9ad2cddf6)] - **stream**: encode small stream/iter strings into a pool (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`201cbb2566`](https://github.com/nodejs/node/commit/201cbb2566)] - **stream**: write to stream/iter writers with only write() inline (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`acd3794841`](https://github.com/nodejs/node/commit/acd3794841)] - **stream**: check stream/iter byte views by their byteLength alone (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`404e6719b5`](https://github.com/nodejs/node/commit/404e6719b5)] - **stream**: read stream/iter from() async sources in one reaction (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`1ca7ec5967`](https://github.com/nodejs/node/commit/1ca7ec5967)] - **stream**: read stream/iter consumer sources without a layer per signal (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`09dbcd02bf`](https://github.com/nodejs/node/commit/09dbcd02bf)] - **stream**: keep stream/iter pipeTo() fast paths with a signal (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`e447e75aa6`](https://github.com/nodejs/node/commit/e447e75aa6)] - **stream**: handle stream/iter pipeline aborts in one place (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`c4dfc6be36`](https://github.com/nodejs/node/commit/c4dfc6be36)] - **stream**: create stream/iter transform signals and options lazily (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`43a5b9c5b4`](https://github.com/nodejs/node/commit/43a5b9c5b4)] - **stream**: create stream/iter from() values without async generators (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`eb3a8d2348`](https://github.com/nodejs/node/commit/eb3a8d2348)] - **stream**: return stream/iter from() results unchanged from from() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`c35e05db05`](https://github.com/nodejs/node/commit/c35e05db05)] - **stream**: do not retain a promise per read in stream/iter share() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`a7f059af4f`](https://github.com/nodejs/node/commit/a7f059af4f)] - **stream**: read async sources more cheaply in stream/iter pipeTo() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`1cbc3f2178`](https://github.com/nodejs/node/commit/1cbc3f2178)] - **stream**: read sync sources synchronously in stream/iter pipeTo() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`4447330f73`](https://github.com/nodejs/node/commit/4447330f73)] - **stream**: check stream/iter pipe writes more cheaply (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`5ad6fdd626`](https://github.com/nodejs/node/commit/5ad6fdd626)] - **stream**: resolve stream/iter push() return() with its value (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`fd082ac61a`](https://github.com/nodejs/node/commit/fd082ac61a)] - **stream**: snapshot common stream/iter byte views in fewer fields (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`270a8c9917`](https://github.com/nodejs/node/commit/270a8c9917)] - **stream**: avoid allocations on every stream/iter push() write (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`3bc119fd14`](https://github.com/nodejs/node/commit/3bc119fd14)] - **stream**: read stream/iter push() readables without normalizing (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`6d34354830`](https://github.com/nodejs/node/commit/6d34354830)] - **stream**: append to arrays with indexed stores in stream/iter hot paths (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`62ff98de3c`](https://github.com/nodejs/node/commit/62ff98de3c)] - **stream**: use a RingBuffer for the stream/iter operation queue (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`fd139640db`](https://github.com/nodejs/node/commit/fd139640db)] - **stream**: use a RingBuffer for stream/iter broadcast pending reads (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`ae9d0de795`](https://github.com/nodejs/node/commit/ae9d0de795)] - **stream**: use a RingBuffer for stream/iter merge()'s ready queue (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`8a85d12057`](https://github.com/nodejs/node/commit/8a85d12057)] - **stream**: avoid quadratic batching in zlib/iter transforms (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`44bbda140c`](https://github.com/nodejs/node/commit/44bbda140c)] - **stream**: remove async generator layers from stream/iter pull() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`35af1d5545`](https://github.com/nodejs/node/commit/35af1d5545)] - **stream**: read stream/iter sources with one abort listener (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`d7786f1b3f`](https://github.com/nodejs/node/commit/d7786f1b3f)] - **stream**: run stream/iter transforms without async generators (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`17299c9b6c`](https://github.com/nodejs/node/commit/17299c9b6c)] - **stream**: normalize sync sources without an async generator in from() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`767b184c9b`](https://github.com/nodejs/node/commit/767b184c9b)] - **stream**: normalize async sources without a generator in from() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`eac3dfacb7`](https://github.com/nodejs/node/commit/eac3dfacb7)] - **stream**: wait without an async function in stream/iter from() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`a70e8eb4c3`](https://github.com/nodejs/node/commit/a70e8eb4c3)] - **stream**: avoid batch entries for single-chunk pipeTo() writes (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`4bb015c5dd`](https://github.com/nodejs/node/commit/4bb015c5dd)] - **stream**: yield bounded batches directly in stream/iter from() (James M Snell) [#66504](https://github.com/nodejs/node/pull/66504) +* \[[`55a6515165`](https://github.com/nodejs/node/commit/55a6515165)] - **stream**: stop reusing a detached onread buffer (Matteo Collina) [#67542](https://github.com/nodejs/node/pull/67542) +* \[[`a4928b2eb3`](https://github.com/nodejs/node/commit/a4928b2eb3)] - **stream**: keep async context of the pipeTo pump (Matteo Collina) [#67054](https://github.com/nodejs/node/pull/67054) +* \[[`5ad0b32169`](https://github.com/nodejs/node/commit/5ad0b32169)] - **stream**: deduplicate string chunk encoding in web stream adapters (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`52c421872a`](https://github.com/nodejs/node/commit/52c421872a)] - **stream**: use distinct webstreams brand checks (Matteo Collina) [#67433](https://github.com/nodejs/node/pull/67433) +* \[[`2e0a67f8a0`](https://github.com/nodejs/node/commit/2e0a67f8a0)] - **stream**: close Utf8Stream fd after pending write (Christian Aurich Zanettini Martins) [#67355](https://github.com/nodejs/node/pull/67355) +* \[[`3887bd6d6a`](https://github.com/nodejs/node/commit/3887bd6d6a)] - **stream**: drop rejection step for sync transforms (Matteo Collina) [#67339](https://github.com/nodejs/node/pull/67339) +* \[[`5d59d00c78`](https://github.com/nodejs/node/commit/5d59d00c78)] - **test**: make test-doc-api-json more robust (James M Snell) [#67701](https://github.com/nodejs/node/pull/67701) +* \[[`07fc4c9052`](https://github.com/nodejs/node/commit/07fc4c9052)] - **test**: update test426-fixtures to bc255a703449b2bc10989772d940df5bf37acf4 (Node.js GitHub Bot) [#67687](https://github.com/nodejs/node/pull/67687) +* \[[`7e7bd82177`](https://github.com/nodejs/node/commit/7e7bd82177)] - **test**: update WPT for WebCryptoAPI to 4ba9d1b8e4 (Node.js GitHub Bot) [#67686](https://github.com/nodejs/node/pull/67686) +* \[[`c8f38fac87`](https://github.com/nodejs/node/commit/c8f38fac87)] - **test**: keep response open in http2 response limits test (Yuya Inoue) [#67656](https://github.com/nodejs/node/pull/67656) +* \[[`c763009def`](https://github.com/nodejs/node/commit/c763009def)] - **test**: check the TLS server name on address-family fallback locally (Tamir Duberstein) [#67595](https://github.com/nodejs/node/pull/67595) +* \[[`ec98099704`](https://github.com/nodejs/node/commit/ec98099704)] - **test**: update Intl tests for CLDR 49 (Renegade334) [#66992](https://github.com/nodejs/node/pull/66992) +* \[[`70a5885fc1`](https://github.com/nodejs/node/commit/70a5885fc1)] - **test**: allow change events in fs watcher ref/unref test (Yuya Inoue) [#67644](https://github.com/nodejs/node/pull/67644) +* \[[`a5fd90f595`](https://github.com/nodejs/node/commit/a5fd90f595)] - **test**: update WPT for url to 2fa965b55c (Yagiz Nizipli) [#67624](https://github.com/nodejs/node/pull/67624) +* \[[`e23827687f`](https://github.com/nodejs/node/commit/e23827687f)] - **test**: use FIPS-compatible PBKDF2 inputs (Filip Skokan) [#67675](https://github.com/nodejs/node/pull/67675) +* \[[`577845d2cc`](https://github.com/nodejs/node/commit/577845d2cc)] - **test**: limit concurrency in gc-http-client tests (Matteo Collina) [#67607](https://github.com/nodejs/node/pull/67607) +* \[[`636d9c9243`](https://github.com/nodejs/node/commit/636d9c9243)] - **test**: restrict `os.tmpdir()` in favour of `common/tmpdir` (Livia Medeiros) [#67567](https://github.com/nodejs/node/pull/67567) +* \[[`57b70b3cf0`](https://github.com/nodejs/node/commit/57b70b3cf0)] - **test**: make test-v8-collect-gc-profile-minor-ms more robust (Joyee Cheung) [#67547](https://github.com/nodejs/node/pull/67547) +* \[[`8ec2579354`](https://github.com/nodejs/node/commit/8ec2579354)] - **test**: fix zipinfo non-ascii check in test-zlib-zip-interop (Ravi Arnan Irianto) [#66978](https://github.com/nodejs/node/pull/66978) +* \[[`9373f1f7df`](https://github.com/nodejs/node/commit/9373f1f7df)] - **test**: fix on zfs build host (Marcel) [#67517](https://github.com/nodejs/node/pull/67517) +* \[[`806f3418b5`](https://github.com/nodejs/node/commit/806f3418b5)] - **test**: reduce flakiness of `test-worker-memory` (Antoine du Hamel) [#67513](https://github.com/nodejs/node/pull/67513) +* \[[`bb659936f1`](https://github.com/nodejs/node/commit/bb659936f1)] - **test**: ignore `ECONNRESET` in `test-gc-net-timeout` (Antoine du Hamel) [#67514](https://github.com/nodejs/node/pull/67514) +* \[[`ef7b49853a`](https://github.com/nodejs/node/commit/ef7b49853a)] - **test**: deflake test-process-timeout-blocked (Christian Aurich Zanettini Martins) [#67481](https://github.com/nodejs/node/pull/67481) +* \[[`189e0f1d21`](https://github.com/nodejs/node/commit/189e0f1d21)] - **test**: remove unnecessary imports for `TextDecoder` and `TextEncoder` (LiviaMedeiros) [#67461](https://github.com/nodejs/node/pull/67461) +* \[[`1ef0527b74`](https://github.com/nodejs/node/commit/1ef0527b74)] - **test\_runner**: junit fixes (Aviv Keller) [#67160](https://github.com/nodejs/node/pull/67160) +* \[[`c871b8bdad`](https://github.com/nodejs/node/commit/c871b8bdad)] - **test\_runner**: scope rerun ids to the entry file (Moshe Atlow) [#67512](https://github.com/nodejs/node/pull/67512) +* \[[`4394bf9cfb`](https://github.com/nodejs/node/commit/4394bf9cfb)] - **test\_runner**: resolve entryFile against the cwd option (Moshe Atlow) [#67512](https://github.com/nodejs/node/pull/67512) +* \[[`3156f855c0`](https://github.com/nodejs/node/commit/3156f855c0)] - **test\_runner**: remove `failure` attribute from JUnit reporter (Aliaksandr) [#66072](https://github.com/nodejs/node/pull/66072) +* \[[`7be00a936d`](https://github.com/nodejs/node/commit/7be00a936d)] - **test\_runner**: add tags and workerId to SuiteContext (sangwook) [#67312](https://github.com/nodejs/node/pull/67312) +* \[[`3db2f0ac30`](https://github.com/nodejs/node/commit/3db2f0ac30)] - **tls**: fix abort on negative zero sessionTimeout (JuHyeong424) [#67661](https://github.com/nodejs/node/pull/67661) +* \[[`423b9df7d6`](https://github.com/nodejs/node/commit/423b9df7d6)] - **tls**: fix newSession after destroy and OCSP cert (Paolo Insogna) [#67650](https://github.com/nodejs/node/pull/67650) +* \[[`bf9adb50e5`](https://github.com/nodejs/node/commit/bf9adb50e5)] - **tls**: destroy sockets after fatal errors (inoway46) [#67215](https://github.com/nodejs/node/pull/67215) +* \[[`66b97e61bc`](https://github.com/nodejs/node/commit/66b97e61bc)] - **(SEMVER-MINOR)** **tls**: docs-deprecate TLS renegotiation, add allowRenegotiation opt-in (Tim Perry) [#67532](https://github.com/nodejs/node/pull/67532) +* \[[`add0fde1d1`](https://github.com/nodejs/node/commit/add0fde1d1)] - **tls**: normalize session buffer views (Matteo Collina) [#67251](https://github.com/nodejs/node/pull/67251) +* \[[`974f7da567`](https://github.com/nodejs/node/commit/974f7da567)] - **tls**: pop errors from failed session parsing (Lazizbek Ergashev) [#67212](https://github.com/nodejs/node/pull/67212) +* \[[`34ee914a08`](https://github.com/nodejs/node/commit/34ee914a08)] - **tools**: set GHA cache to readonly in stress-test workflow (René) [#67694](https://github.com/nodejs/node/pull/67694) +* \[[`a28558e322`](https://github.com/nodejs/node/commit/a28558e322)] - **tools**: cache Rust builds in GHA workflows (René) [#67694](https://github.com/nodejs/node/pull/67694) +* \[[`3e4242ee6f`](https://github.com/nodejs/node/commit/3e4242ee6f)] - **tools**: update sccache to 0.19.0 (René) [#67694](https://github.com/nodejs/node/pull/67694) +* \[[`98d2bf0f5c`](https://github.com/nodejs/node/commit/98d2bf0f5c)] - **tools**: update nixpkgs-unstable to 93a9ed0a866099a230ed5146a5bb7d16fd5 (Node.js GitHub Bot) [#67691](https://github.com/nodejs/node/pull/67691) +* \[[`d9540f53db`](https://github.com/nodejs/node/commit/d9540f53db)] - **tools**: pin Cachix version on x86\_64\_darwin (Antoine du Hamel) [#67738](https://github.com/nodejs/node/pull/67738) +* \[[`d8fc737bfc`](https://github.com/nodejs/node/commit/d8fc737bfc)] - **tools**: avoid early exit in release proposal linter (Antoine du Hamel) [#67666](https://github.com/nodejs/node/pull/67666) +* \[[`c3e7d57b70`](https://github.com/nodejs/node/commit/c3e7d57b70)] - **tools**: disallow constructing an Error without using it (Minho Yoo) [#66647](https://github.com/nodejs/node/pull/66647) +* \[[`93aaf93f92`](https://github.com/nodejs/node/commit/93aaf93f92)] - **tools**: avoid swallowing errors in GHA (Antoine du Hamel) [#67548](https://github.com/nodejs/node/pull/67548) +* \[[`7f45cb7070`](https://github.com/nodejs/node/commit/7f45cb7070)] - **tools**: fix incorrect environment variable in coverage-windows (René) [#67591](https://github.com/nodejs/node/pull/67591) +* \[[`b6eeb0bdc5`](https://github.com/nodejs/node/commit/b6eeb0bdc5)] - **tools**: apply http lint rule to lib/internal/http (Ethan Arrowood) [#67529](https://github.com/nodejs/node/pull/67529) +* \[[`6a63dc57ae`](https://github.com/nodejs/node/commit/6a63dc57ae)] - **tools**: remove duplicate variables (Antoine du Hamel) [#67511](https://github.com/nodejs/node/pull/67511) +* \[[`f53eeb214f`](https://github.com/nodejs/node/commit/f53eeb214f)] - **tools**: check notarization status when verifying macOS binaries (Ulises Gascon) [#67541](https://github.com/nodejs/node/pull/67541) +* \[[`4ad00d1994`](https://github.com/nodejs/node/commit/4ad00d1994)] - **tools**: add a workflow to send reminder about v8 backports (Joyee Cheung) [#67436](https://github.com/nodejs/node/pull/67436) +* \[[`41c0b95607`](https://github.com/nodejs/node/commit/41c0b95607)] - **tools**: update nixpkgs-unstable to 2074cc672349f14240fb7ea90d509e0b643 (Node.js GitHub Bot) [#67478](https://github.com/nodejs/node/pull/67478) +* \[[`dbeb6e49bb`](https://github.com/nodejs/node/commit/dbeb6e49bb)] - **url**: keep urlToHttpOptions() result in fast mode (Yaroslav Chuhai) [#67683](https://github.com/nodejs/node/pull/67683) +* \[[`6264df4160`](https://github.com/nodejs/node/commit/6264df4160)] - **url**: keep the next '=' across pairs in parseParams (Aayush) [#67653](https://github.com/nodejs/node/pull/67653) +* \[[`c35398dc10`](https://github.com/nodejs/node/commit/c35398dc10)] - **url**: restrict option copying in urlToHttpOptions to URL instances (Matteo Collina) [#67454](https://github.com/nodejs/node/pull/67454) +* \[[`6d694041e7`](https://github.com/nodejs/node/commit/6d694041e7)] - **url**: share URLPattern exec() and test() argument parsing (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`f4bdf9bdcf`](https://github.com/nodejs/node/commit/f4bdf9bdcf)] - **url**: validate href setter receiver first (Hilary Asogwa) [#67350](https://github.com/nodejs/node/pull/67350) +* \[[`a2049085ba`](https://github.com/nodejs/node/commit/a2049085ba)] - **util**: share helpers between debounce() and throttle() (James M Snell) [#67495](https://github.com/nodejs/node/pull/67495) +* \[[`cf06c8d50b`](https://github.com/nodejs/node/commit/cf06c8d50b)] - **util**: fix debounce/throttle abort listener leak (Ved Chaudhari) [#66839](https://github.com/nodejs/node/pull/66839) +* \[[`4df7015560`](https://github.com/nodejs/node/commit/4df7015560)] - **util**: use indexed writes in Set and Map inspection (Roberto Bianchi) [#67295](https://github.com/nodejs/node/pull/67295) +* \[[`50aa231615`](https://github.com/nodejs/node/commit/50aa231615)] - **util**: use `Map.prototype.getOrInsert()` in circular reference formatting (Livia Medeiros) [#67451](https://github.com/nodejs/node/pull/67451) +* \[[`c02610b788`](https://github.com/nodejs/node/commit/c02610b788)] - **util**: use indexed writes for inspected object properties (Roberto Bianchi) [#67297](https://github.com/nodejs/node/pull/67297) +* \[[`0278623793`](https://github.com/nodejs/node/commit/0278623793)] - **vfs**: normalize RealFSProvider mkdir return paths (Trivikram Kamat) [#66221](https://github.com/nodejs/node/pull/66221) +* \[[`65fc1c44a6`](https://github.com/nodejs/node/commit/65fc1c44a6)] - **vfs**: add callback readv and writev handlers (Daniel Cavalcante) [#66548](https://github.com/nodejs/node/pull/66548) +* \[[`34e370e58b`](https://github.com/nodejs/node/commit/34e370e58b)] - **worker**: add diagnostic channel 'worker\_threads.main.registry' (Paolo Insogna) [#67311](https://github.com/nodejs/node/pull/67311) + <a id="27.0.0-alpha.0.1.1"></a> ## 2026-11-16, Version 27.0.0-alpha.0.1.1 (Alpha), @aduh95 diff --git a/doc/contributing/maintaining/maintaining-V8.md b/doc/contributing/maintaining/maintaining-V8.md index 880a06425d0e..3f3394e52080 100644 --- a/doc/contributing/maintaining/maintaining-V8.md +++ b/doc/contributing/maintaining/maintaining-V8.md @@ -354,23 +354,39 @@ above. A better strategy is to 4. Refloat (cherry-pick) all the patches from list computed in 1) as necessary. Some of the patches may no longer be necessary. -To audit for floating patches: +To audit for floating patches, use `git node v8 list-patches` with the +target V8 release line. For example, before upgrading to V8 15.7: ```bash -git log --oneline deps/v8 +cd $NODE_DIR +git node v8 list-patches --target=15.7 ``` +It lists every V8 patch floated since the last V8 import, and whether the +target line already contains each one. See [`git-node-v8-list-patches`][] for +how to read the output. + To replace the copy of V8 in Node.js, use the [`git-node`][] tool. For example, -if you want to replace the copy of V8 in Node.js with the branch-head for V8 5.1 -branch: +if you want to replace the copy of V8 in Node.js with the branch-head for V8 +15.7 branch: ```bash cd $NODE_DIR -git node v8 major --branch=5.1-lkgr +git node v8 major --branch=15.7-lkgr ``` This should be followed up with manual refloating of all relevant patches. +After refloating, run `list-patches` on the upgrade branch to verify the +result: + +```bash +git node v8 list-patches --base=HEAD --check-diff +``` + +Check that the listed patches match the ones the earlier run marked to refloat, +and that each cherry-pick's diff matches its upstream commit. + ## Proposal: Using a fork repository to track upstream V8 The fact that Node.js keeps a vendored, potentially edited copy of V8 in deps/ @@ -419,6 +435,7 @@ This would require some tooling to: [V8TemplateUpstreamBug]: https://bugs.chromium.org/p/v8/issues/entry?template=Node.js%20upstream%20bug [`@node-core/utils`]: https://github.com/nodejs/node-core-utils#Install [`git-node-v8-backport`]: https://github.com/nodejs/node-core-utils/blob/main/docs/git-node.md#git-node-v8-backport-sha +[`git-node-v8-list-patches`]: https://github.com/nodejs/node-core-utils/blob/main/docs/git-node.md#git-node-v8-list-patches [`git-node-v8-minor`]: https://github.com/nodejs/node-core-utils/blob/main/docs/git-node.md#git-node-v8-minor [`git-node-v8`]: https://github.com/nodejs/node-core-utils/blob/HEAD/docs/git-node.md#git-node-v8 [`git-node`]: https://github.com/nodejs/node-core-utils/blob/HEAD/docs/git-node.md#git-node-v8 diff --git a/doc/contributing/maintaining/maintaining-single-executable-application-support.md b/doc/contributing/maintaining/maintaining-single-executable-application-support.md index 4f2bbdf6e6bc..335088de3b5b 100644 --- a/doc/contributing/maintaining/maintaining-single-executable-application-support.md +++ b/doc/contributing/maintaining/maintaining-single-executable-application-support.md @@ -67,15 +67,14 @@ To disable single executable application support, build Node.js with the When built with single executable application support, the Node.js process uses [`postject-api.h`][] to check if the `NODE_SEA_BLOB` section exists in the -binary. If it is found, it passes the buffer to -[`single_executable_application.js`][], which executes the contents of the -embedded script. +binary. If it is found, it passes the buffer to [`embedding.js`][], which +executes the contents of the embedded script. [Next-10 discussions]: https://github.com/nodejs/next-10/blob/main/meetings/summit-nov-2021.md#single-executable-applications [Node.js CLI options]: https://nodejs.org/api/cli.html [XCOFF]: https://www.ibm.com/docs/en/aix/7.2?topic=formats-xcoff-object-file-format +[`embedding.js`]: https://github.com/nodejs/node/blob/main/lib/internal/main/embedding.js [`postject-api.h`]: https://github.com/nodejs/node/blob/71951a0e86da9253d7c422fa2520ee9143e557fa/test/fixtures/postject-copy/node_modules/postject/dist/postject-api.h -[`single_executable_application.js`]: https://github.com/nodejs/node/blob/main/lib/internal/main/single_executable_application.js [boxednode]: https://github.com/mongodb-js/boxednode [pkg]: https://github.com/vercel/pkg [postject]: https://github.com/nodejs/postject diff --git a/doc/contributing/writing-tests.md b/doc/contributing/writing-tests.md index f9ca3c772017..3a0ee0969eaf 100644 --- a/doc/contributing/writing-tests.md +++ b/doc/contributing/writing-tests.md @@ -237,6 +237,33 @@ argument. It is not a good idea to simply pass `common.mustCall()` to those because `common.mustCall()` will ignore the error. Use `common.mustSucceed()` instead. +#### Temporary files + +Whenever test has to write files or directories, use the common +[tmpdir module](https://github.com/nodejs/node/tree/HEAD/test/common#tmpdir-module) +which handles creating and cleaning test-specific temporary directory. Do not +create files under OS's temporary directory (`os.tmpdir()`) or anywhere else +outside of the test-specific `tmpdir.path`. + +```js +const tmpdir = require('../common/tmpdir'); +tmpdir.refresh(); + +const tempFile = tmpdir.resolve('fileForWriteTest'); +``` + +If test spawns child processes that can not utilize this module but might +create files in OS's tmpdir, change the `TMPDIR` environment variable for them: + +```js +spawnSync('/usr/bin/sort', [tempFile], { + env: { ...process.env, TMPDIR: tmpdir.path }, +}); + +// or simply +process.env.TMPDIR = tmpdir.path; +``` + #### Countdown module The common [Countdown module](https://github.com/nodejs/node/tree/HEAD/test/common#countdown-module) diff --git a/doc/node-config-schema.json b/doc/node-config-schema.json index 0d2cb83b517d..8453ca49e7da 100644 --- a/doc/node-config-schema.json +++ b/doc/node-config-schema.json @@ -54,6 +54,10 @@ "type": "boolean", "description": "launch benchmark runner on startup" }, + "bench-gc": { + "type": "string", + "description": "run garbage collection before measured benchmark samples" + }, "bench-isolation": { "type": "string", "description": "configures the type of benchmark isolation used in the benchmark runner" @@ -191,6 +195,10 @@ "type": "boolean", "description": "allow worker threads when any permissions are set" }, + "bench-gc": { + "type": "string", + "description": "run garbage collection before measured benchmark samples" + }, "bench-isolation": { "type": "string", "description": "configures the type of benchmark isolation used in the benchmark runner" @@ -359,21 +367,6 @@ "type": "boolean", "description": "experimental support for importing source as text with import attributes" }, - "experimental-loader": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "array", - "minItems": 1, - "items": { - "type": "string" - } - } - ], - "description": "use the specified module as a custom loader" - }, "experimental-package-map": { "type": "string", "description": "use the specified file for package map resolution" diff --git a/doc/node.1 b/doc/node.1 index 14466702af00..7e20d47d1e0b 100644 --- a/doc/node.1 +++ b/doc/node.1 @@ -353,6 +353,17 @@ details. This flag cannot be combined with \fB--test\fR, \fB--watch\fR, \fB--watch-path\fR, \fB--check\fR, \fB--eval\fR, or \fB--interactive\fR. . +.It Fl -bench-gc Ns = Ns Ar mode +Overrides the garbage collection mode for every selected benchmark. When \fBmode\fR +is \fB'once'\fR, a full garbage collection runs before the first measured sample. +When \fBmode\fR is \fB'sample'\fR, a full garbage collection runs before every measured +sample. When \fBmode\fR is \fB'none'\fR, no garbage collection is forced. Without this +option, each benchmark uses its own \fBgc\fR value, which defaults to \fB'none'\fR. +Forcing garbage collection requires the \fB--expose-gc\fR flag. With process +isolation, \fB--expose-gc\fR is added to benchmark child processes automatically +when \fBmode\fR is \fB'once'\fR or \fB'sample'\fR. With \fB--bench-isolation=none\fR, +\fB--expose-gc\fR must be passed explicitly. +. .It Fl -bench-isolation Ns = Ns Ar mode Configures benchmark file isolation. When \fBmode\fR is \fB'process'\fR, each matching file runs in a separate child process. This is the default. Files are still run @@ -874,11 +885,6 @@ Enable experimental support for importing modules with .It Fl -experimental-inspector-network-resource Enable experimental support for inspector network resources. . -.It Fl -experimental-loader Ns = Ns Ar module -Specify the \fBmodule\fR containing exported asynchronous module customization hooks. -\fBmodule\fR may be any string accepted as an \fBimport\fR specifier. -This feature requires \fB--allow-worker\fR if used with the Permission Model. -. .It Fl -experimental-network-inspection Enable experimental support for the network inspection with Chrome DevTools. . @@ -1248,7 +1254,7 @@ Disable exposition of Navigator API on the global scope. Legacy alias for \fB--no-require-module\fR. . .It Fl -no-experimental-sqlite -Disable the experimental \fBnode:sqlite\fR module. +Disable the \fBnode:sqlite\fR module. . .It Fl -no-experimental-vfs Disable the experimental \fBnode:vfs\fR module and \fB--vfs-load\fR. @@ -2215,6 +2221,8 @@ one is included in the list below. .It \fB--allow-worker\fR .It +\fB--bench-gc\fR +.It \fB--bench-isolation\fR .It \fB--bench-name-pattern\fR @@ -2277,8 +2285,6 @@ one is included in the list below. .It \fB--experimental-json-modules\fR .It -\fB--experimental-loader\fR -.It \fB--experimental-modules\fR .It \fB--experimental-package-map\fR diff --git a/lib/bench.js b/lib/bench.js index 96e199773d90..9cee01524a64 100644 --- a/lib/bench.js +++ b/lib/bench.js @@ -18,6 +18,7 @@ const { run, runFile, } = require('internal/bench_runner/runner'); +const { doNotOptimize } = require('internal/bench_runner/benchmark'); if (process.env.NODE_BENCH_CONTEXT !== 'child' || typeof process.send !== 'function') { @@ -33,6 +34,7 @@ ObjectAssign(module.exports, { bench, createRunner, describe: suite, + doNotOptimize, run, runFile, suite, diff --git a/lib/buffer.js b/lib/buffer.js index ab494b9988ae..60876b4d421c 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -1114,7 +1114,7 @@ Buffer.prototype.compare = function compare(target, // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - byteOffset - an index into `buffer`; will be clamped to a safe integer // - end - absolute exclusive end of the search range // - encoding - an optional encoding, relevant if val is a string // - dir - true for indexOf, false for lastIndexOf @@ -1124,10 +1124,10 @@ function bidirectionalIndexOf(buffer, val, byteOffset, end, encoding, dir) { if (typeof byteOffset === 'string') { encoding = byteOffset; byteOffset = undefined; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; + } else if (byteOffset > NumberMAX_SAFE_INTEGER) { + byteOffset = NumberMAX_SAFE_INTEGER; + } else if (byteOffset < NumberMIN_SAFE_INTEGER) { + byteOffset = NumberMIN_SAFE_INTEGER; } // Coerce to Number. Values like null and [] become 0. byteOffset = +byteOffset; diff --git a/lib/child_process.js b/lib/child_process.js index 5ceed97b57b3..01ffe160111c 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -572,6 +572,11 @@ function hasPermissionFlagInEnv(nodeOptions) { ); } +function quoteNodeOption(flag, value) { + const quoted = RegExpPrototypeSymbolReplace(/["\\]/g, value, '\\$&'); + return `"${flag}=${quoted}"`; +} + function copyPermissionModelFlagsToEnv(env, key, args) { // Do not override if permission was already passed to file if (args.includes('--permission') || args.includes('--permission-audit') || @@ -586,15 +591,33 @@ function copyPermissionModelFlagsToEnv(env, key, args) { const flagsToCopy = getPermissionModelFlagsToCopy(); const copiedFlags = new SafeSet(); - for (const arg of process.execArgv) { + const execArgv = process.execArgv; + for (let i = 0; i < execArgv.length; i++) { + const arg = execArgv[i]; if (allowAllEnv && arg.startsWith('--allow-env')) { continue; } for (const flag of flagsToCopy) { - if (arg.startsWith(flag)) { - copiedFlags.add(flag); - env[key] = `${env[key] ? env[key] + ' ' + arg : arg}`; + if (!arg.startsWith(flag)) { + continue; + } + copiedFlags.add(flag); + if (ArrayIsArray(getOptionValue(flag))) { + let value; + if (arg === flag && i + 1 < execArgv.length) { + value = execArgv[++i]; + if (value[0] === '\\' && value[1] === '-') { + value = StringPrototypeSlice(value, 1); + } + } else if (arg[flag.length] === '=') { + value = StringPrototypeSlice(arg, flag.length + 1); + } + if (value !== undefined) { + env[key] = `${env[key] ? env[key] + ' ' : ''}${quoteNodeOption(flag, value)}`; + break; + } } + env[key] = `${env[key] ? env[key] + ' ' + arg : arg}`; } } @@ -608,10 +631,7 @@ function copyPermissionModelFlagsToEnv(env, key, args) { env[key] = `${env[key] ? env[key] + ' ' : ''}${flag}`; } else if (ArrayIsArray(value)) { for (const item of value) { - // Values may contain spaces or quotes (e.g. the implicitly allowed - // entry point), so quote them as NODE_OPTIONS expects. - const quoted = RegExpPrototypeSymbolReplace(/["\\]/g, item, '\\$&'); - env[key] = `${env[key] ? env[key] + ' ' : ''}"${flag}=${quoted}"`; + env[key] = `${env[key] ? env[key] + ' ' : ''}${quoteNodeOption(flag, item)}`; } } } diff --git a/lib/dgram.js b/lib/dgram.js index 653cf6a26305..5d96ada84081 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -250,7 +250,8 @@ function bufferSize(self, size, buffer) { throw new ERR_SOCKET_BAD_BUFFER_SIZE(); const ctx = {}; - const ret = self[kStateSymbol].handle.bufferSize(size, buffer, ctx); + // Coerce -0 to +0, which the binding does not treat as a Uint32. + const ret = self[kStateSymbol].handle.bufferSize(size >>> 0, buffer, ctx); if (ret === undefined) { throw new ERR_SOCKET_BUFFER_SIZE(ctx); } diff --git a/lib/diagnostics_channel.js b/lib/diagnostics_channel.js index bb0c7d66050c..61d310d383a9 100644 --- a/lib/diagnostics_channel.js +++ b/lib/diagnostics_channel.js @@ -7,6 +7,9 @@ const { ArrayPrototypePushApply, ArrayPrototypeSlice, ArrayPrototypeSplice, + DisposableStack, + DisposableStackPrototypeMove, + DisposableStackPrototypeUse, ObjectDefineProperty, ObjectGetPrototypeOf, ObjectSetPrototypeOf, @@ -20,7 +23,6 @@ const { } = primordials; const { - aggregateTwoErrors, codes: { ERR_INVALID_ARG_TYPE, }, @@ -94,25 +96,11 @@ function maybeMarkInactive(channel) { } } -function disposeStoreScopes(stack, error, hasError = false) { - for (let i = stack.length - 1; i >= 0; i--) { - try { - stack[i][SymbolDispose](); - } catch (err) { - error = hasError ? aggregateTwoErrors(err, error) : err; - hasError = true; - } - } - - if (hasError) throw error; -} - class RunStoresScope { #stack; constructor(activeChannel, data) { - // TODO: use native DisposableStack once supported in core - const stack = []; + using stack = new DisposableStack(); // Enter stores using withScope if (activeChannel._stores) { @@ -132,11 +120,7 @@ class RunStoresScope { } } - try { - ArrayPrototypePush(stack, store.withScope(newContext)); - } catch (err) { - disposeStoreScopes(stack, err, true); - } + DisposableStackPrototypeUse(stack, store.withScope(newContext)); } } @@ -144,17 +128,11 @@ class RunStoresScope { activeChannel.publish(data); // Transfer ownership of the stack - // TODO: Restore stack.move() when DisposableStack is restored in core to avoid broken behavior. - this.#stack = stack; + this.#stack = DisposableStackPrototypeMove(stack); } [SymbolDispose]() { - if (this.#stack !== undefined) { - const stack = this.#stack; - this.#stack = undefined; - - disposeStoreScopes(stack); - } + this.#stack[SymbolDispose](); } } @@ -230,12 +208,9 @@ class ActiveChannel { } runStores(data, fn, thisArg, ...args) { - const scope = this.withStoreScope(data); - try { - return ReflectApply(fn, thisArg, args); - } finally { - scope[SymbolDispose](); - } + // eslint-disable-next-line no-unused-vars + using scope = this.withStoreScope(data); + return ReflectApply(fn, thisArg, args); } } @@ -431,12 +406,9 @@ class BoundedChannel { run(context, fn, thisArg, ...args) { context ??= {}; - const scope = this.withScope(context); - try { - return ReflectApply(fn, thisArg, args); - } finally { - scope[SymbolDispose](); - } + // eslint-disable-next-line no-unused-vars + using scope = this.withScope(context); + return ReflectApply(fn, thisArg, args); } } @@ -562,8 +534,9 @@ class TracingChannel { } const { error } = this; - const scope = this.#callWindow.withScope(context); + // eslint-disable-next-line no-unused-vars + using scope = this.#callWindow.withScope(context); try { const result = ReflectApply(fn, thisArg, args); context.result = result; @@ -572,8 +545,6 @@ class TracingChannel { context.error = err; error.publish(context); throw err; - } finally { - scope[SymbolDispose](); } } @@ -597,9 +568,9 @@ class TracingChannel { context.error = err; error.publish(context); // Use continuation window for asyncStart/asyncEnd - const scope = continuationWindow.withScope(context); + // eslint-disable-next-line no-unused-vars + using scope = continuationWindow.withScope(context); // TODO: Is there a way to have asyncEnd _after_ the continuation? - scope[SymbolDispose](); } function onRejectWithRethrow(err) { @@ -610,14 +581,14 @@ class TracingChannel { function onResolve(result) { context.result = result; // Use continuation window for asyncStart/asyncEnd - const scope = continuationWindow.withScope(context); + // eslint-disable-next-line no-unused-vars + using scope = continuationWindow.withScope(context); // TODO: Is there a way to have asyncEnd _after_ the continuation? - scope[SymbolDispose](); return result; } - const scope = this.#callWindow.withScope(context); - + // eslint-disable-next-line no-unused-vars + using scope = this.#callWindow.withScope(context); try { const result = ReflectApply(fn, thisArg, args); // If the return value is not a thenable, return it directly with a warning. @@ -642,8 +613,6 @@ class TracingChannel { context.error = err; error.publish(context); throw err; - } finally { - scope[SymbolDispose](); } } @@ -668,28 +637,23 @@ class TracingChannel { } // Use continuation window for asyncStart/asyncEnd around callback - const scope = continuationWindow.withScope(context); - try { - return ReflectApply(callback, this, arguments); - } finally { - scope[SymbolDispose](); - } + // eslint-disable-next-line no-unused-vars + using scope = continuationWindow.withScope(context); + return ReflectApply(callback, this, arguments); } const callback = ArrayPrototypeAt(args, position); validateFunction(callback, 'callback'); ArrayPrototypeSplice(args, position, 1, wrappedCallback); - const scope = this.#callWindow.withScope(context); - + // eslint-disable-next-line no-unused-vars + using scope = this.#callWindow.withScope(context); try { return ReflectApply(fn, thisArg, args); } catch (err) { context.error = err; error.publish(context); throw err; - } finally { - scope[SymbolDispose](); } } } diff --git a/lib/eslint.config_partial.mjs b/lib/eslint.config_partial.mjs index fcd4dd4aa78c..d9183423ed1e 100644 --- a/lib/eslint.config_partial.mjs +++ b/lib/eslint.config_partial.mjs @@ -23,7 +23,7 @@ const noRestrictedSyntax = [ message: "`btoa` supports only latin-1 charset, use Buffer.from(str).toString('base64') instead", }, { - selector: 'NewExpression[callee.name=/Error$/]:not([callee.name=/^(AssertionError|NghttpError|AbortError|NodeAggregateError|QuicError|QuotaExceededError)$/])', + selector: 'NewExpression[callee.name=/Error$/]:not([callee.name=/^(AssertionError|NghttpError|AbortError|NodeAggregateError|QuicError|QuotaExceededError|SuppressedError)$/])', message: "Use an error exported by 'internal/errors' instead.", }, { @@ -412,16 +412,6 @@ export default [ name: 'SubtleCrypto', message: "Use `const { SubtleCrypto } = require('internal/crypto/webcrypto');` instead of the global.", }, - // DisposableStack and AsyncDisposableStack are not available in primordials because they can be - // disabled with --no-js-explicit-resource-management CLI flag. - { - name: 'DisposableStack', - message: 'Use `const { DisposableStack } = globalThis;` instead of the global.', - }, - { - name: 'AsyncDisposableStack', - message: 'Use `const { AsyncDisposableStack } = globalThis;` instead of the global.', - }, ], 'no-restricted-modules': [ 'error', @@ -447,6 +437,7 @@ export default [ { name: 'AggregateError' }, { name: 'Array' }, { name: 'ArrayBuffer' }, + { name: 'AsyncDisposableStack' }, { name: 'Atomics' }, { name: 'BigInt' }, { name: 'BigInt64Array' }, @@ -454,6 +445,7 @@ export default [ { name: 'Boolean' }, { name: 'DataView' }, { name: 'Date' }, + { name: 'DisposableStack' }, { name: 'decodeURI' }, { name: 'decodeURIComponent' }, { name: 'encodeURI' }, @@ -515,6 +507,7 @@ export default [ into: 'Safe', }, { name: 'String' }, + { name: 'SuppressedError' }, { name: 'Symbol' }, { name: 'SyntaxError' }, { name: 'TypeError' }, @@ -566,6 +559,7 @@ export default [ 'lib/http.js', 'lib/http2.js', 'lib/internal/http.js', + 'lib/internal/http/*.js', 'lib/internal/http2/*.js', 'lib/tls.js', 'lib/zlib.js', diff --git a/lib/fs.js b/lib/fs.js index a5fc9a7571c6..a6d262c5a2b7 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1120,6 +1120,8 @@ function write(fd, buffer, offsetOrOptions, length, position, callback) { if (typeof position !== 'number') position = null; validateOffsetLengthWrite(offset, length, buffer.byteLength); + // V8 does not report -0 as an int32, which the binding requires. + length |= 0; const h = vfsState.handlers; if (h !== null) { @@ -1210,6 +1212,8 @@ function writeSync(fd, buffer, offsetOrOptions, length, position) { if (typeof length !== 'number') length = buffer.byteLength - offset; validateOffsetLengthWrite(offset, length, buffer.byteLength); + // V8 does not report -0 as an int32, which the binding requires. + length |= 0; const h = vfsState.handlers; if (h !== null) { @@ -1612,7 +1616,9 @@ function fdatasync(fd, callback) { const req = new FSReqCallback(); req.oncomplete = callback; - if (permission.isEnabled()) { + // TODO(rafaelgss): publish a diagnostics channel event for fd-based APIs in + // audit mode. + if (permission.isEnabled() && !permission.isAuditMode()) { callback(new ERR_ACCESS_DENIED('fdatasync API is disabled when Permission Model is enabled.')); return; } @@ -1633,7 +1639,7 @@ function fdatasyncSync(fd) { if (result !== undefined) return; } - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fdatasync API is disabled when Permission Model is enabled.'); } binding.fdatasync(fd); @@ -1654,7 +1660,7 @@ function fsync(fd, callback) { const req = new FSReqCallback(); req.oncomplete = callback; - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { callback(new ERR_ACCESS_DENIED('fsync API is disabled when Permission Model is enabled.')); return; } @@ -1674,7 +1680,7 @@ function fsyncSync(fd) { if (result !== undefined) return; } - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fsync API is disabled when Permission Model is enabled.'); } binding.fsync(fd); @@ -2455,7 +2461,7 @@ function fchmod(fd, mode, callback) { const h = vfsState.handlers; if (h !== null && vfsVoid(h.fchmod(fd, mode), callback)) return; - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { callback(new ERR_ACCESS_DENIED('fchmod API is disabled when Permission Model is enabled.')); return; } @@ -2480,7 +2486,7 @@ function fchmodSync(fd, mode) { if (result !== undefined) return; } - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fchmod API is disabled when Permission Model is enabled.'); } binding.fchmod(fd, mode); @@ -2631,7 +2637,7 @@ function fchown(fd, uid, gid, callback) { const h = vfsState.handlers; if (h !== null && vfsVoid(h.fchown(fd), callback)) return; - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { callback(new ERR_ACCESS_DENIED('fchown API is disabled when Permission Model is enabled.')); return; } @@ -2658,7 +2664,7 @@ function fchownSync(fd, uid, gid) { if (result !== undefined) return; } - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fchown API is disabled when Permission Model is enabled.'); } @@ -2772,7 +2778,7 @@ function futimes(fd, atime, mtime, callback) { const h = vfsState.handlers; if (h !== null && vfsVoid(h.futimes(fd, atime, mtime), callback)) return; - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { callback(new ERR_ACCESS_DENIED('futimes API is disabled when Permission Model is enabled.')); return; } @@ -2801,7 +2807,7 @@ function futimesSync(fd, atime, mtime) { if (result !== undefined) return; } - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('futimes API is disabled when Permission Model is enabled.'); } diff --git a/lib/https.js b/lib/https.js index 38623d258a20..7481439bf1b5 100644 --- a/lib/https.js +++ b/lib/https.js @@ -30,7 +30,6 @@ const { ArrayPrototypeSplice, ArrayPrototypeUnshift, FunctionPrototypeCall, - JSONStringify, NumberParseInt, ObjectAssign, ObjectSetPrototypeOf, @@ -494,7 +493,7 @@ function Agent(options) { if (!(this instanceof Agent)) return new Agent(options); - options = { __proto__: null, ...options }; + options = { __proto__: kEmptyObject, ...options }; validateOpenSSLEngineOptions(options); options.defaultPort ??= 443; options.protocol ??= 'https:'; @@ -606,7 +605,7 @@ Agent.prototype.getName = function getName(options = kEmptyObject) { name += ':'; if (options.ciphers) - name += options.ciphers; + name += getTlsOptionKey(options.ciphers); name += ':'; if (options.key) { @@ -622,23 +621,23 @@ Agent.prototype.getName = function getName(options = kEmptyObject) { name += ':'; if (options.rejectUnauthorized !== undefined) - name += options.rejectUnauthorized; + name += getTlsOptionKey(options.rejectUnauthorized); name += ':'; if (options.servername && options.servername !== options.host) - name += options.servername; + name += getTlsOptionKey(options.servername); name += ':'; if (options.minVersion) - name += options.minVersion; + name += getTlsOptionKey(options.minVersion); name += ':'; if (options.maxVersion) - name += options.maxVersion; + name += getTlsOptionKey(options.maxVersion); name += ':'; if (options.secureProtocol) - name += options.secureProtocol; + name += getTlsOptionKey(options.secureProtocol); name += ':'; if (options.crl) @@ -646,27 +645,27 @@ Agent.prototype.getName = function getName(options = kEmptyObject) { name += ':'; if (options.honorCipherOrder !== undefined) - name += options.honorCipherOrder; + name += getTlsOptionKey(options.honorCipherOrder); name += ':'; if (options.ecdhCurve) - name += options.ecdhCurve; + name += getTlsOptionKey(options.ecdhCurve); name += ':'; if (options.dhparam) - name += options.dhparam; + name += getTlsOptionKey(options.dhparam); name += ':'; if (options.secureOptions !== undefined) - name += options.secureOptions; + name += getTlsOptionKey(options.secureOptions); name += ':'; if (options.sessionIdContext) - name += options.sessionIdContext; + name += getTlsOptionKey(options.sessionIdContext); name += ':'; if (options.sigalgs) - name += JSONStringify(options.sigalgs); + name += getTlsOptionKey(options.sigalgs); name += ':'; if (options.secureContext) @@ -700,6 +699,10 @@ Agent.prototype.getName = function getName(options = kEmptyObject) { if (options.session) name += getTlsOptionKey(options.session); + name += ':'; + if (options.allowRenegotiation !== undefined) + name += getTlsOptionKey(options.allowRenegotiation); + if (options[kPerRequestCheckServerIdentity]) name += `:${options[kPerRequestCheckServerIdentity]}`; diff --git a/lib/internal/abort_controller.js b/lib/internal/abort_controller.js index 7daa63e1f91d..b47af84a598b 100644 --- a/lib/internal/abort_controller.js +++ b/lib/internal/abort_controller.js @@ -4,7 +4,6 @@ // in https://github.com/mysticatea/abort-controller (MIT license) const { - ArrayPrototypePush, FunctionPrototypeCall, ObjectAssign, ObjectDefineProperties, @@ -34,6 +33,7 @@ const { const { kMaxEventTargetListeners } = require('events'); const { customInspectSymbol, + kEmptyObject, kEnumerableProperty, } = require('internal/util'); const { inspect } = require('internal/util/inspect'); @@ -164,25 +164,6 @@ function validateThisAbortSignal(obj) { throw new ERR_INVALID_THIS('AbortSignal'); } -function refreshCompositeSignal(signal) { - if (!signal[kComposite] || signal[kAborted] || !signal[kSourceSignals]?.size) { - return; - } - - for (const sourceSignalWeakRef of signal[kSourceSignals]) { - const sourceSignal = sourceSignalWeakRef.deref(); - if (sourceSignal === undefined) { - signal[kSourceSignals].delete(sourceSignalWeakRef); - continue; - } - - if (sourceSignal[kAborted]) { - abortSignal(signal, sourceSignal[kReason]); - return; - } - } -} - function followCompositeSignal(signal) { if (signal[kFollowing] || signal[kAborted] || !signal[kSourceSignals]?.size) { return; @@ -321,7 +302,6 @@ class AbortSignal extends EventTarget { */ get aborted() { validateThisAbortSignal(this); - refreshCompositeSignal(this); return !!this[kAborted]; } @@ -330,13 +310,11 @@ class AbortSignal extends EventTarget { */ get reason() { validateThisAbortSignal(this); - refreshCompositeSignal(this); return this[kReason]; } throwIfAborted() { validateThisAbortSignal(this); - refreshCompositeSignal(this); if (this[kAborted]) { throw this[kReason]; } @@ -377,7 +355,7 @@ class AbortSignal extends EventTarget { static any(signals) { const signalsArray = converters['sequence<AbortSignal>']( signals, - { __proto__: null, context: 'signals' }, + { __proto__: kEmptyObject, context: 'signals' }, ); const resultSignal = new AbortSignal(kDontThrowSymbol, false, undefined, false, true); @@ -402,7 +380,6 @@ class AbortSignal extends EventTarget { gcPersistentSignals.add(signal); } - refreshCompositeSignal(signal); if (signal[kAborted]) { abortSignal(resultSignal, signal[kReason]); return resultSignal; @@ -439,6 +416,9 @@ class AbortSignal extends EventTarget { // Preserve abort state even if sources are collected before this signal is // observed. Following uses weak references so unused signals can be collected. + // Since aborting a source synchronously aborts the composites that follow it, + // a composite's own abort state is always current and reading it doesn't + // need to check its sources. followCompositeSignal(resultSignal); return resultSignal; @@ -479,7 +459,7 @@ class AbortSignal extends EventTarget { if (aborted) { const reason = this.reason; return { - data: { aborted, reason }, + data: { __proto__: kEmptyObject, aborted, reason }, deserializeInfo: 'internal/abort_controller:ClonedAbortSignal', }; } @@ -490,10 +470,10 @@ class AbortSignal extends EventTarget { this.addEventListener('abort', () => { port1.postMessage(this.reason); port1.close(); - }, { once: true }); + }, { __proto__: kEmptyObject, once: true }); return { - data: { port: port2 }, + data: { __proto__: kEmptyObject, port: port2 }, deserializeInfo: 'internal/abort_controller:ClonedAbortSignal', }; } @@ -577,7 +557,7 @@ function abortSignal(signal, reason) { dependentSignal[kReason] = reason; dependentSignal[kAborted] = true; // 2. Append dependentSignal to dependentSignalsToAbort. - ArrayPrototypePush(dependentSignalsToAbort, dependentSignal); + dependentSignalsToAbort[dependentSignalsToAbort.length] = dependentSignal; } }); } @@ -686,12 +666,12 @@ function transferableAbortController() { * @returns {Promise<void>} */ async function aborted(signal, resource) { - converters.AbortSignal(signal, { __proto__: null, context: 'signal' }); + converters.AbortSignal(signal, { __proto__: kEmptyObject, context: 'signal' }); validateObject(resource, 'resource', kValidateObjectAllowObjects); if (signal.aborted) return PromiseResolve(); const abortPromise = PromiseWithResolvers(); - const opts = { __proto__: null, [kWeakHandler]: resource, once: true, [kResistStopPropagation]: true }; + const opts = { __proto__: kEmptyObject, [kWeakHandler]: resource, once: true, [kResistStopPropagation]: true }; signal.addEventListener('abort', abortPromise.resolve, opts); return abortPromise.promise; } diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 8a60b9a6ce52..eb403824edd1 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -52,6 +52,7 @@ const { pushAsyncContext: pushAsyncContext_, popAsyncContext: popAsyncContext_, executionAsyncResource: executionAsyncResource_, + lazyExecutionAsyncResource, clearAsyncIdStack, } = async_wrap; // Properties in active_hooks are used to keep track of the set of hooks being @@ -91,6 +92,7 @@ const { kInit, kBefore, kAfter, kDestroy, kTotals, kPromiseResolve, kCheck, kExecutionAsyncId, kAsyncIdCounter, kTriggerAsyncId, kDefaultTriggerAsyncId, kStackLength, kUsesExecutionAsyncResource, + kLazyScopes, } = async_wrap.constants; const { async_id_symbol, @@ -136,6 +138,12 @@ function executionAsyncResource() { async_hook_fields[kUsesExecutionAsyncResource] = 1; const index = async_hook_fields[kStackLength] - 1; + // A native callback that started before anybody used this function did not + // push its resource on the stack. + if (async_hook_fields[kLazyScopes] !== 0) { + const lazy = lazyExecutionAsyncResource(index + 1); + if (lazy !== undefined) return lookupPublicResource(lazy); + } if (index === -1) return topLevelResource; const resource = execution_async_resources[index] || executionAsyncResource_(index); @@ -550,7 +558,15 @@ function pushAsyncContext(asyncId, triggerAsyncId, resource) { // This is the equivalent of the native pop_async_ids() call. function popAsyncContext(asyncId) { const stackLength = async_hook_fields[kStackLength]; - if (stackLength === 0) return false; + if (stackLength === 0) { + // A native callback that skipped the stack still has its id checked. + if (async_hook_fields[kLazyScopes] !== 0 && + async_hook_fields[kCheck] > 0 && + async_id_fields[kExecutionAsyncId] !== asyncId) { + return popAsyncContext_(asyncId); + } + return false; + } if (async_hook_fields[kCheck] > 0 && async_id_fields[kExecutionAsyncId] !== asyncId) { // Do the same thing as the native code (i.e. crash hard). diff --git a/lib/internal/bench_runner/benchmark.js b/lib/internal/bench_runner/benchmark.js index cea0abc71e52..114feb388172 100644 --- a/lib/internal/bench_runner/benchmark.js +++ b/lib/internal/bench_runner/benchmark.js @@ -7,6 +7,7 @@ const { ArrayPrototypeReverse, ArrayPrototypeSlice, ArrayPrototypeSort, + Float64Array, JSONStringify, MathFloor, MathMax, @@ -42,6 +43,7 @@ const { validateInteger, validateNumber, validateObject, + validateOneOf, validateString, validateUint32, } = require('internal/validators'); @@ -50,11 +52,31 @@ const { structuredClone } = require('internal/worker/js_transferable'); const { bigint: hrtime } = process.hrtime; const kDefaultSamples = 30; const kDefaultWarmup = 10; +const kGcModes = ObjectFreeze(['none', 'once', 'sample']); const kEmptyDiagnosticChannels = ObjectFreeze([]); const kEmptyNamePath = ObjectFreeze([]); const kEmptyParams = ObjectFreeze({ __proto__: null }); const kEmptyTags = ObjectFreeze([]); +// doNotOptimize() stores values in reachable storage so that the optimizing +// compiler cannot prove the computation that produced them is unused. Numbers +// use a typed array so that storing a double does not allocate a HeapNumber. +const numberSink = new Float64Array(1); +const valueSink = [undefined]; + +function doNotOptimize(value) { + if (typeof value === 'number') { + numberSink[0] = value; + } else { + valueSink[0] = value; + } + return value; +} + +function clearSink() { + valueSink[0] = undefined; +} + function validateSkip(skip) { if (skip !== undefined && typeof skip !== 'boolean' && typeof skip !== 'string') { @@ -234,6 +256,7 @@ class Bench extends AsyncResource { const validated = validateNodeOptions( options, parent.tags, parent.diagnosticChannels); const { + gc = 'none', params, samples = kDefaultSamples, signal, @@ -241,6 +264,7 @@ class Bench extends AsyncResource { warmup = kDefaultWarmup, } = options; + validateOneOf(gc, 'options.gc', kGcModes); validateUint32(samples, 'options.samples', true); validateUint32(warmup, 'options.warmup'); validateAbortSignal(signal, 'options.signal'); @@ -258,6 +282,7 @@ class Bench extends AsyncResource { this.skip = validated.skip; this.tags = validated.tags; this.params = canonicalizeParams(params); + this.gc = gc; this.samples = samples; this.warmup = warmup; this.timeout = timeout; @@ -349,7 +374,7 @@ class BenchContext { this.#startTime = hrtime(); } - end(operations, options = kEmptyObject) { + end(operations = 1, options = kEmptyObject) { const endTime = hrtime(); if (this.#closed) { this.#invalid = true; @@ -415,7 +440,7 @@ class BenchContext { try { validateObject(sample, 'sample'); - const { detail, duration_ns, operations } = sample; + const { detail, duration_ns, operations = 1 } = sample; validateInteger( operations, 'sample.operations', 1, NumberMAX_SAFE_INTEGER); if (typeof duration_ns !== 'bigint') { @@ -573,6 +598,9 @@ module.exports = { Bench, BenchContext, Suite, + clearSink, + doNotOptimize, + kGcModes, normalizeArgs, summarizeSamples, }; diff --git a/lib/internal/bench_runner/cli.js b/lib/internal/bench_runner/cli.js index 5884046e146a..f0b6f84adb14 100644 --- a/lib/internal/bench_runner/cli.js +++ b/lib/internal/bench_runner/cli.js @@ -44,6 +44,9 @@ const { spawn } = require('child_process'); const { createWriteStream, statSync } = require('fs'); const { Glob } = require('internal/fs/glob'); const { getValidatedPath } = require('internal/fs/utils'); +const { + kGcModes, +} = require('internal/bench_runner/benchmark'); const { BenchmarksStream, } = require('internal/bench_runner/benchmarks_stream'); @@ -112,6 +115,7 @@ const kFilterArgs = [ '--experimental-default-config-file', ]; const kFilterArgValues = [ + '--bench-gc', '--bench-isolation', '--bench-name-pattern', '--bench-reporter', @@ -265,6 +269,7 @@ function parseCommandLine() { destinations, fileRunId: isChild && process.env.NODE_BENCH_FILE_RUN_ID ? process.env.NODE_BENCH_FILE_RUN_ID : undefined, + gc: getOptionValue('--bench-gc') || undefined, isChild, isolation: getOptionValue('--bench-isolation'), namePattern: parseNamePattern(getOptionValue('--bench-name-pattern')), @@ -438,6 +443,7 @@ function validateRecord(record) { } if (record.type === 'bench:plan') { const { + gc, samples, selected, skip, @@ -458,6 +464,7 @@ function validateRecord(record) { ArrayPrototypeSome(ObjectValues(record.data.params), (value) => typeof value !== 'string' && typeof value !== 'boolean' && (typeof value !== 'number' || !NumberIsFinite(value))) || + !ArrayPrototypeIncludes(kGcModes, gc) || !NumberIsSafeInteger(samples) || samples <= 0 || samples > 0xFFFFFFFF || !NumberIsSafeInteger(warmup) || warmup < 0 || warmup > 0xFFFFFFFF || @@ -604,6 +611,7 @@ async function loadBenchmarkFiles(files, options, modules, onRecord) { const stream = runBenchmarks({ __proto__: null, + gc: options.gc, namePattern: options.namePattern, samples: options.samples, warmup: options.warmup, @@ -711,7 +719,6 @@ function runFileOptionRequiresValue(arg) { } const kOptionAliases = new SafeMap([ - ['--loader', '--experimental-loader'], ['-C', '--conditions'], ['-r', '--require'], ]); @@ -749,6 +756,10 @@ function getChildArgs(path, options) { getInheritedChildArgs() : ArrayPrototypeSlice(options.execArgv); ArrayPrototypePush( args, '--experimental-bench', '--bench', '--bench-isolation=none'); + if (options.gc !== undefined) { + ArrayPrototypePush(args, `--bench-gc=${options.gc}`); + if (options.gc !== 'none') ArrayPrototypePush(args, '--expose-gc'); + } if (options.namePatternSource.length > 0) { ArrayPrototypePush( args, `--bench-name-pattern=${options.namePatternSource}`); diff --git a/lib/internal/bench_runner/environment.js b/lib/internal/bench_runner/environment.js new file mode 100644 index 000000000000..17e349c342a3 --- /dev/null +++ b/lib/internal/bench_runner/environment.js @@ -0,0 +1,61 @@ +'use strict'; + +const { + ArrayPrototypePush, + ArrayPrototypeSlice, +} = primordials; + +function groupCpus(cpus) { + const groups = []; + for (let i = 0; i < cpus.length; i++) { + // The reported speed is the current core frequency, which fluctuates + // with frequency scaling, so only the model is used for grouping. + const { model } = cpus[i]; + let group; + for (let j = 0; j < groups.length; j++) { + if (groups[j].model === model) { + group = groups[j]; + break; + } + } + if (group === undefined) { + group = { __proto__: null, model, count: 0 }; + ArrayPrototypePush(groups, group); + } + group.count++; + } + return groups; +} + +function collectEnvironment() { + const os = require('os'); + const total = os.totalmem(); + const constrained = process.constrainedMemory(); + return { + __proto__: null, + node: process.version, + v8: process.versions.v8, + platform: process.platform, + arch: process.arch, + os: { + __proto__: null, + type: os.type(), + release: os.release(), + machine: os.machine(), + }, + cpus: groupCpus(os.cpus()), + availableParallelism: os.availableParallelism(), + memory: { + __proto__: null, + total, + free: os.freemem(), + constrained: constrained > 0 && constrained < total ? constrained : null, + }, + loadavg: os.loadavg(), + execArgv: ArrayPrototypeSlice(process.execArgv), + }; +} + +module.exports = { + collectEnvironment, +}; diff --git a/lib/internal/bench_runner/harness.js b/lib/internal/bench_runner/harness.js index 46d35a0a2352..e9afe90ce508 100644 --- a/lib/internal/bench_runner/harness.js +++ b/lib/internal/bench_runner/harness.js @@ -47,6 +47,7 @@ const { validateBoolean, validateFunction, validateObject, + validateOneOf, validateUint32, } = require('internal/validators'); const { queueMicrotask } = require('internal/process/task_queues'); @@ -56,6 +57,8 @@ const { Bench, BenchContext, Suite, + clearSink, + kGcModes, normalizeArgs, summarizeSamples, } = require('internal/bench_runner/benchmark'); @@ -73,6 +76,23 @@ function createRunId() { return `${process.pid}:${String(hrtime())}:${nextRunId++}`; } +let garbageCollector; + +// The gc() function installed by --expose-gc is resolved from a new context +// so that it reflects the V8 flag rather than a user-replaceable global. +function getGarbageCollector(mode) { + if (garbageCollector === undefined) { + const { runInNewContext } = require('vm'); + const gc = runInNewContext('globalThis.gc'); + if (typeof gc !== 'function') { + throw new ERR_INVALID_STATE( + `the '${mode}' gc mode requires the --expose-gc flag`); + } + garbageCollector = () => { gc(); }; + } + return garbageCollector; +} + function eventLoopTurn() { return new Promise((resolve) => setImmediate(resolve)); } @@ -119,9 +139,11 @@ class Harness { validateObject(options, 'options'); const { autoRun = true, + gc, yieldBetweenSamples = true, } = options; validateBoolean(autoRun, 'options.autoRun'); + if (gc !== undefined) validateOneOf(gc, 'options.gc', kGcModes); validateBoolean( yieldBetweenSamples, 'options.yieldBetweenSamples'); this.#autoRun = autoRun; @@ -131,6 +153,7 @@ class Harness { this.entryFile = process.argv?.[1] ?? null; this.stream = new BenchmarksStream(); this.state = 'collecting'; + this.gc = gc; this.namePattern = null; this.outerSignal = undefined; this.samples = undefined; @@ -261,16 +284,22 @@ class Harness { validateObject(options, 'options'); const { + gc, namePattern, samples, signal, warmup, yieldBetweenSamples, } = options; + let nextGc = this.gc; let nextNamePattern = this.namePattern; let nextSamples = this.samples; let nextWarmup = this.warmup; let nextYieldBetweenSamples = this.#yieldBetweenSamples; + if (gc !== undefined) { + validateOneOf(gc, 'options.gc', kGcModes); + nextGc = gc; + } if (namePattern !== undefined) { if (typeof namePattern === 'string') { nextNamePattern = new RegExp(namePattern); @@ -296,6 +325,7 @@ class Harness { nextYieldBetweenSamples = yieldBetweenSamples; } + this.gc = nextGc; this.namePattern = nextNamePattern; this.samples = nextSamples; this.outerSignal = signal; @@ -434,6 +464,7 @@ class Harness { column: benchmark.loc.column, tags: ArrayPrototypeSlice(benchmark.tags), params: benchmark.params, + gc: this.gc ?? benchmark.gc, samples: this.samples ?? benchmark.samples, warmup: this.warmup ?? benchmark.warmup, timeout: benchmark.timeout === Infinity ? null : benchmark.timeout, @@ -922,6 +953,8 @@ class Harness { try { await this.#runWithStop(benchmark, controller, async (pause) => { try { + const gcMode = this.gc ?? benchmark.gc; + const gc = gcMode === 'none' ? null : getGarbageCollector(gcMode); await this.#runBenchHooks( benchmark, 'beforeEach', hookContext); checkDeadline(); @@ -933,8 +966,16 @@ class Harness { } const phase = i < warmup ? 'warmup' : 'measurement'; const index = phase === 'warmup' ? i : i - warmup; + if (gc !== null && i >= warmup && + (gcMode === 'sample' || i === warmup)) { + await pause(gc); + if (controller.signal.aborted) { + throw controller.signal.reason; + } + } const outcome = await this.#runSample( benchmark, controller.signal, phase, index); + clearSink(); if (!outcome.failed) { checkDeadline(); if (controller.signal.aborted) { @@ -1096,6 +1137,7 @@ function createRunner(options = kEmptyObject) { const harness = new Harness({ __proto__: null, autoRun: false, + gc: options.gc, yieldBetweenSamples: options.yieldBetweenSamples === undefined ? true : options.yieldBetweenSamples, }); diff --git a/lib/internal/bench_runner/reporter/json.js b/lib/internal/bench_runner/reporter/json.js index 3237a3e1b26c..4a46b83c5f84 100644 --- a/lib/internal/bench_runner/reporter/json.js +++ b/lib/internal/bench_runner/reporter/json.js @@ -9,6 +9,9 @@ const { String, } = primordials; const { isError } = require('internal/util'); +const { + collectEnvironment, +} = require('internal/bench_runner/environment'); function toJSONValue(value, seen) { if (typeof value === 'bigint') return String(value); @@ -56,7 +59,16 @@ function stringify(record) { } async function* jsonReporter(source) { + let environmentReported = false; for await (const record of source) { + if (!environmentReported) { + environmentReported = true; + yield `${stringify({ + __proto__: null, + type: 'bench:environment', + data: collectEnvironment(), + })}\n`; + } yield `${stringify(record)}\n`; } } diff --git a/lib/internal/bench_runner/reporter/spec.js b/lib/internal/bench_runner/reporter/spec.js index 34f5831553f3..cf3ba088548d 100644 --- a/lib/internal/bench_runner/reporter/spec.js +++ b/lib/internal/bench_runner/reporter/spec.js @@ -13,6 +13,13 @@ const { StringPrototypeReplaceAll, } = primordials; const Transform = require('internal/streams/transform'); +const { + collectEnvironment, +} = require('internal/bench_runner/environment'); + +// One operation per nanosecond is faster than almost any real operation can +// run, which usually means the optimizing compiler removed the measured work. +const kImplausibleRate = 1e9; const kHeader = 'benchmark | samples | mean rate | 95% CI | median rate | warning\n'; @@ -62,6 +69,50 @@ function formatRate(rate) { return `${formatted}${prefix} ops/s`; } +function formatBytes(bytes) { + const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']; + let unit = 0; + while (bytes >= 1024 && unit < units.length - 1) { + bytes /= 1024; + unit++; + } + return `${NumberPrototypeToFixed(bytes, unit === 0 ? 0 : 1)} ${units[unit]}`; +} + +function formatEnvironment(environment) { + const { cpus, memory, os } = environment; + let output = `node: ${environment.node} (V8 ${environment.v8}), ` + + `${environment.platform} ${environment.arch} ` + + `(${os.type} ${os.release})\n`; + + const groups = []; + for (let i = 0; i < cpus.length; i++) { + ArrayPrototypePush(groups, `${cpus[i].count} x ${cpus[i].model}`); + } + if (groups.length === 0) ArrayPrototypePush(groups, 'unknown'); + output += `cpu: ${ArrayPrototypeJoin(groups, ', ')} ` + + `(available parallelism: ${environment.availableParallelism})\n`; + + output += `memory: ${formatBytes(memory.total)} total, ` + + `${formatBytes(memory.free)} free`; + if (memory.constrained !== null) { + output += `, ${formatBytes(memory.constrained)} constrained`; + } + output += '\n'; + + const loadavg = []; + for (let i = 0; i < environment.loadavg.length; i++) { + ArrayPrototypePush( + loadavg, NumberPrototypeToFixed(environment.loadavg[i], 2)); + } + output += `load average: ${ArrayPrototypeJoin(loadavg, ', ')}\n`; + + if (environment.execArgv.length > 0) { + output += `exec argv: ${ArrayPrototypeJoin(environment.execArgv, ' ')}\n`; + } + return `${output}\n`; +} + function formatWarning(summary) { const warnings = []; if (NumberIsFinite(summary.coefficientOfVariation) && @@ -71,6 +122,10 @@ function formatWarning(summary) { if (NumberIsFinite(summary.skewness) && MathAbs(summary.skewness) > 1) { ArrayPrototypePush(warnings, 'skewed'); } + if (NumberIsFinite(summary.median) && + summary.median >= kImplausibleRate) { + ArrayPrototypePush(warnings, 'implausible'); + } return ArrayPrototypeJoin(warnings, ', '); } @@ -97,6 +152,7 @@ function formatResult(data) { class SpecReporter extends Transform { #diagnostics = []; + #environment; #reported = false; #results = []; @@ -105,7 +161,7 @@ class SpecReporter extends Transform { } #format(summary = undefined) { - let output = kHeader; + let output = formatEnvironment(this.#environment) + kHeader; for (let i = 0; i < this.#results.length; i++) { output += formatResult(this.#results[i]); } @@ -121,6 +177,7 @@ class SpecReporter extends Transform { } _transform({ type, data }, _encoding, callback) { + this.#environment ??= collectEnvironment(); switch (type) { case 'bench:complete': ArrayPrototypePush(this.#results, data); diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index 3f99fe6d161a..d8160a0f6621 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -1,7 +1,8 @@ 'use strict'; const { - BigInt, + BigInt64Array, + BigUint64Array, Float32Array, Float64Array, MathFloor, @@ -50,6 +51,8 @@ const float32Array = new Float32Array(1); const uInt8Float32Array = new Uint8Array(float32Array.buffer); const float64Array = new Float64Array(1); const uInt8Float64Array = new Uint8Array(float64Array.buffer); +const bigInt64Array = new BigInt64Array(float64Array.buffer); +const bigUint64Array = new BigUint64Array(float64Array.buffer); // Check endianness. float32Array[0] = -1; // 0xBF800000 @@ -97,80 +100,52 @@ function boundsError(value, length, type) { } // Read integers. -function readBigUInt64LE(offset = 0) { +function readBigInt64Bytes(buf, offset, backwards) { validateNumber(offset, 'offset'); - const first = this[offset]; - const last = this[offset + 7]; + const first = buf[offset]; + const last = buf[offset + 7]; if (first === undefined || last === undefined) - boundsError(offset, this.length - 8); - - const lo = first + - this[++offset] * 2 ** 8 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 24; - - const hi = this[++offset] + - this[++offset] * 2 ** 8 + - this[++offset] * 2 ** 16 + - last * 2 ** 24; + boundsError(offset, buf.length - 8); + + if (backwards) { + uInt8Float64Array[7] = first; + uInt8Float64Array[6] = buf[++offset]; + uInt8Float64Array[5] = buf[++offset]; + uInt8Float64Array[4] = buf[++offset]; + uInt8Float64Array[3] = buf[++offset]; + uInt8Float64Array[2] = buf[++offset]; + uInt8Float64Array[1] = buf[++offset]; + uInt8Float64Array[0] = last; + } else { + uInt8Float64Array[0] = first; + uInt8Float64Array[1] = buf[++offset]; + uInt8Float64Array[2] = buf[++offset]; + uInt8Float64Array[3] = buf[++offset]; + uInt8Float64Array[4] = buf[++offset]; + uInt8Float64Array[5] = buf[++offset]; + uInt8Float64Array[6] = buf[++offset]; + uInt8Float64Array[7] = last; + } +} - return BigInt(lo) + (BigInt(hi) << 32n); +function readBigUInt64LE(offset = 0) { + readBigInt64Bytes(this, offset, bigEndian); + return bigUint64Array[0]; } function readBigUInt64BE(offset = 0) { - validateNumber(offset, 'offset'); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) - boundsError(offset, this.length - 8); - - const hi = first * 2 ** 24 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - this[++offset]; - - const lo = this[++offset] * 2 ** 24 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - last; - - return (BigInt(hi) << 32n) + BigInt(lo); + readBigInt64Bytes(this, offset, !bigEndian); + return bigUint64Array[0]; } function readBigInt64LE(offset = 0) { - validateNumber(offset, 'offset'); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) - boundsError(offset, this.length - 8); - - const val = this[offset + 4] + - this[offset + 5] * 2 ** 8 + - this[offset + 6] * 2 ** 16 + - (last << 24); // Overflow - return (BigInt(val) << 32n) + - BigInt(first + - this[++offset] * 2 ** 8 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 24); + readBigInt64Bytes(this, offset, bigEndian); + return bigInt64Array[0]; } function readBigInt64BE(offset = 0) { - validateNumber(offset, 'offset'); - const first = this[offset]; - const last = this[offset + 7]; - if (first === undefined || last === undefined) - boundsError(offset, this.length - 8); - - const val = (first << 24) + // Overflow - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - this[++offset]; - return (BigInt(val) << 32n) + - BigInt(this[++offset] * 2 ** 24 + - this[++offset] * 2 ** 16 + - this[++offset] * 2 ** 8 + - last); + readBigInt64Bytes(this, offset, !bigEndian); + return bigInt64Array[0]; } function readUIntLE(offset, byteLength) { @@ -583,66 +558,53 @@ function readDoubleForwards(offset = 0) { } // Write integers. -function writeBigU_Int64LE(buf, value, offset, min, max) { +function writeBigU_Int64(buf, value, offset, min, max, backwards) { checkInt(value, min, max, buf, offset, 7); - let lo = Number(value & 0xffffffffn); - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - let hi = Number(value >> 32n & 0xffffffffn); - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; + // `& -1n` keeps the TypeError for non-BigInt values. + bigInt64Array[0] = value & -1n; + if (backwards) { + buf[offset++] = uInt8Float64Array[7]; + buf[offset++] = uInt8Float64Array[6]; + buf[offset++] = uInt8Float64Array[5]; + buf[offset++] = uInt8Float64Array[4]; + buf[offset++] = uInt8Float64Array[3]; + buf[offset++] = uInt8Float64Array[2]; + buf[offset++] = uInt8Float64Array[1]; + buf[offset++] = uInt8Float64Array[0]; + } else { + buf[offset++] = uInt8Float64Array[0]; + buf[offset++] = uInt8Float64Array[1]; + buf[offset++] = uInt8Float64Array[2]; + buf[offset++] = uInt8Float64Array[3]; + buf[offset++] = uInt8Float64Array[4]; + buf[offset++] = uInt8Float64Array[5]; + buf[offset++] = uInt8Float64Array[6]; + buf[offset++] = uInt8Float64Array[7]; + } return offset; } function writeBigUInt64LE(value, offset = 0) { - return writeBigU_Int64LE(this, value, offset, 0n, 0xffffffffffffffffn); -} - -function writeBigU_Int64BE(buf, value, offset, min, max) { - checkInt(value, min, max, buf, offset, 7); - - let lo = Number(value & 0xffffffffn); - buf[offset + 7] = lo; - lo = lo >> 8; - buf[offset + 6] = lo; - lo = lo >> 8; - buf[offset + 5] = lo; - lo = lo >> 8; - buf[offset + 4] = lo; - let hi = Number(value >> 32n & 0xffffffffn); - buf[offset + 3] = hi; - hi = hi >> 8; - buf[offset + 2] = hi; - hi = hi >> 8; - buf[offset + 1] = hi; - hi = hi >> 8; - buf[offset] = hi; - return offset + 8; + return writeBigU_Int64( + this, value, offset, 0n, 0xffffffffffffffffn, bigEndian); } function writeBigUInt64BE(value, offset = 0) { - return writeBigU_Int64BE(this, value, offset, 0n, 0xffffffffffffffffn); + return writeBigU_Int64( + this, value, offset, 0n, 0xffffffffffffffffn, !bigEndian); } function writeBigInt64LE(value, offset = 0) { - return writeBigU_Int64LE( - this, value, offset, -0x8000000000000000n, 0x7fffffffffffffffn); + return writeBigU_Int64( + this, value, offset, -0x8000000000000000n, 0x7fffffffffffffffn, + bigEndian); } function writeBigInt64BE(value, offset = 0) { - return writeBigU_Int64BE( - this, value, offset, -0x8000000000000000n, 0x7fffffffffffffffn); + return writeBigU_Int64( + this, value, offset, -0x8000000000000000n, 0x7fffffffffffffffn, + !bigEndian); } function writeUIntLE(value, offset, byteLength) { diff --git a/lib/internal/crypto/cfrg.js b/lib/internal/crypto/cfrg.js index 2e4bf9a82755..c797c4335585 100644 --- a/lib/internal/crypto/cfrg.js +++ b/lib/internal/crypto/cfrg.js @@ -10,7 +10,6 @@ const { kCryptoJobWebCrypto, kKeyFormatDER, kKeyFormatRawPublic, - kKeyTypePublic, kSignJobModeSign, kSignJobModeVerify, kWebCryptoKeyFormatPKCS8, @@ -39,7 +38,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -117,24 +116,11 @@ function cfrgImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - allowedUsages.public : - allowedUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.private); - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, allowedUsages); break; - } case 'jwk': { const isPublic = keyData.d === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/ec.js b/lib/internal/crypto/ec.js index bb857be74c84..7aedff11559a 100644 --- a/lib/internal/crypto/ec.js +++ b/lib/internal/crypto/ec.js @@ -50,7 +50,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -148,24 +148,11 @@ function ecImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - allowedUsages.public : - allowedUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, allowedUsages.private); - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, allowedUsages); break; - } case 'jwk': { const isPublic = keyData.d === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/ml_dsa.js b/lib/internal/crypto/ml_dsa.js index 581e9beb5d0f..38850d4a21e7 100644 --- a/lib/internal/crypto/ml_dsa.js +++ b/lib/internal/crypto/ml_dsa.js @@ -12,7 +12,6 @@ const { kKeyFormatDER, kKeyFormatRawPublic, kKeyFormatRawSeed, - kKeyTypePublic, kSignJobModeSign, kSignJobModeVerify, kWebCryptoKeyFormatRaw, @@ -42,7 +41,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -105,6 +104,21 @@ function mlDsaExportKey(key, format) { } } +const kPrivOnlyPkcs8Lengths = { + '__proto__': null, + 'ML-DSA-44': 2588, + 'ML-DSA-65': 4060, + 'ML-DSA-87': 4924, +}; + +function rejectPkcs8WithoutSeed(keyData, name) { + if (getBufferSourceByteLength(keyData) === kPrivOnlyPkcs8Lengths[name]) { + throw lazyDOMException( + 'Importing an ML-DSA PKCS#8 key without a seed is not supported', + 'NotSupportedError'); + } +} + function mlDsaImportKey( format, keyData, @@ -117,37 +131,12 @@ function mlDsaImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - kUsages.public : - kUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.private); - - const privOnlyLengths = { - '__proto__': null, - 'ML-DSA-44': 2588, - 'ML-DSA-65': 4060, - 'ML-DSA-87': 4924, - }; - if (getBufferSourceByteLength(keyData) === privOnlyLengths[name]) { - throw lazyDOMException( - 'Importing an ML-DSA PKCS#8 key without a seed is not supported', - 'NotSupportedError'); - } - - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, kUsages, + (data) => rejectPkcs8WithoutSeed(data, name)); break; - } case 'jwk': { const isPublic = keyData.priv === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/ml_kem.js b/lib/internal/crypto/ml_kem.js index 025790829f04..e0987b60f51b 100644 --- a/lib/internal/crypto/ml_kem.js +++ b/lib/internal/crypto/ml_kem.js @@ -13,7 +13,6 @@ const { kKeyFormatDER, kKeyFormatRawPublic, kKeyFormatRawSeed, - kKeyTypePublic, kWebCryptoKeyFormatPKCS8, kWebCryptoKeyFormatRaw, kWebCryptoKeyFormatSPKI, @@ -40,7 +39,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, importRawKey, validateJwk, @@ -105,6 +104,21 @@ function mlKemExportKey(key, format) { } } +const kPrivOnlyPkcs8Lengths = { + '__proto__': null, + 'ML-KEM-512': 1660, + 'ML-KEM-768': 2428, + 'ML-KEM-1024': 3196, +}; + +function rejectPkcs8WithoutSeed(keyData, name) { + if (getBufferSourceByteLength(keyData) === kPrivOnlyPkcs8Lengths[name]) { + throw lazyDOMException( + 'Importing an ML-KEM PKCS#8 key without a seed is not supported', + 'NotSupportedError'); + } +} + function mlKemImportKey( format, keyData, @@ -117,37 +131,12 @@ function mlKemImportKey( const usagesSet = toUsagesSet(usages); switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - kUsages.public : - kUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.public); - handle = importDerKey(keyData, true); - break; - } - case 'pkcs8': { - verifyAcceptableKeyUse(name, usagesSet, kUsages.private); - - const privOnlyLengths = { - '__proto__': null, - 'ML-KEM-512': 1660, - 'ML-KEM-768': 2428, - 'ML-KEM-1024': 3196, - }; - if (getBufferSourceByteLength(keyData) === privOnlyLengths[name]) { - throw lazyDOMException( - 'Importing an ML-KEM PKCS#8 key without a seed is not supported', - 'NotSupportedError'); - } - - handle = importDerKey(keyData, false); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, name, usagesSet, kUsages, + (data) => rejectPkcs8WithoutSeed(data, name)); break; - } case 'raw-public': case 'raw-seed': { const isPublic = format === 'raw-public'; diff --git a/lib/internal/crypto/rsa.js b/lib/internal/crypto/rsa.js index 8fa3ecdff1b8..9dd90803a056 100644 --- a/lib/internal/crypto/rsa.js +++ b/lib/internal/crypto/rsa.js @@ -12,7 +12,6 @@ const { SignJob, kCryptoJobWebCrypto, kKeyFormatDER, - kKeyTypePublic, kSignJobModeSign, kSignJobModeVerify, kKeyVariantRSA_OAEP, @@ -53,7 +52,7 @@ const { const { createKeyUsages, getKeyPairUsages, - importDerKey, + importAsymmetricKeyHandle, importJwkKey, validateJwk, validateKeyUsages, @@ -182,26 +181,11 @@ function rsaImportKey( let handle; switch (format) { case 'KeyObjectHandle': - verifyAcceptableKeyUse( - algorithm.name, - usagesSet, - keyData.getKeyType() === kKeyTypePublic ? - allowedUsages.public : - allowedUsages.private); - handle = keyData; - break; - case 'spki': { - verifyAcceptableKeyUse( - algorithm.name, usagesSet, allowedUsages.public); - handle = importDerKey(keyData, true); + case 'spki': + case 'pkcs8': + handle = importAsymmetricKeyHandle( + format, keyData, algorithm.name, usagesSet, allowedUsages); break; - } - case 'pkcs8': { - verifyAcceptableKeyUse( - algorithm.name, usagesSet, allowedUsages.private); - handle = importDerKey(keyData, false); - break; - } case 'jwk': { const isPublic = keyData.d === undefined; verifyAcceptableKeyUse( diff --git a/lib/internal/crypto/webcrypto.js b/lib/internal/crypto/webcrypto.js index 7ca945cb4f21..3ecb96f0dfc3 100644 --- a/lib/internal/crypto/webcrypto.js +++ b/lib/internal/crypto/webcrypto.js @@ -499,21 +499,20 @@ function deriveKeyImpl( )); } -function exportKeySpki(key) { - let exporter; - switch (getCryptoKeyAlgorithm(key).name) { +// Returns the SPKI/PKCS#8 export function for an asymmetric algorithm, or +// undefined if the algorithm does not support those formats. +function getAsymmetricKeyExporter(name) { + switch (name) { case 'RSASSA-PKCS1-v1_5': // Fall through case 'RSA-PSS': // Fall through case 'RSA-OAEP': - exporter = require('internal/crypto/rsa').rsaExportKey; - break; + return require('internal/crypto/rsa').rsaExportKey; case 'ECDSA': // Fall through case 'ECDH': - exporter = require('internal/crypto/ec').ecExportKey; - break; + return require('internal/crypto/ec').ecExportKey; case 'Ed25519': // Fall through case 'Ed448': @@ -521,25 +520,28 @@ function exportKeySpki(key) { case 'X25519': // Fall through case 'X448': - exporter = require('internal/crypto/cfrg').cfrgExportKey; - break; + return require('internal/crypto/cfrg').cfrgExportKey; case 'ML-DSA-44': // Fall through case 'ML-DSA-65': // Fall through case 'ML-DSA-87': - exporter = require('internal/crypto/ml_dsa').mlDsaExportKey; - break; + return require('internal/crypto/ml_dsa').mlDsaExportKey; case 'ML-KEM-512': // Fall through case 'ML-KEM-768': // Fall through case 'ML-KEM-1024': - exporter = require('internal/crypto/ml_kem').mlKemExportKey; - break; + return require('internal/crypto/ml_kem').mlKemExportKey; default: return undefined; } +} + +function exportKeySpki(key) { + const exporter = getAsymmetricKeyExporter(getCryptoKeyAlgorithm(key).name); + if (exporter === undefined) + return undefined; if (getCryptoKeyType(key) !== 'public') throw lazyDOMException('Key must be a public key', 'InvalidAccessError'); @@ -548,46 +550,9 @@ function exportKeySpki(key) { } function exportKeyPkcs8(key) { - let exporter; - switch (getCryptoKeyAlgorithm(key).name) { - case 'RSASSA-PKCS1-v1_5': - // Fall through - case 'RSA-PSS': - // Fall through - case 'RSA-OAEP': - exporter = require('internal/crypto/rsa').rsaExportKey; - break; - case 'ECDSA': - // Fall through - case 'ECDH': - exporter = require('internal/crypto/ec').ecExportKey; - break; - case 'Ed25519': - // Fall through - case 'Ed448': - // Fall through - case 'X25519': - // Fall through - case 'X448': - exporter = require('internal/crypto/cfrg').cfrgExportKey; - break; - case 'ML-DSA-44': - // Fall through - case 'ML-DSA-65': - // Fall through - case 'ML-DSA-87': - exporter = require('internal/crypto/ml_dsa').mlDsaExportKey; - break; - case 'ML-KEM-512': - // Fall through - case 'ML-KEM-768': - // Fall through - case 'ML-KEM-1024': - exporter = require('internal/crypto/ml_kem').mlKemExportKey; - break; - default: - return undefined; - } + const exporter = getAsymmetricKeyExporter(getCryptoKeyAlgorithm(key).name); + if (exporter === undefined) + return undefined; if (getCryptoKeyType(key) !== 'private') throw lazyDOMException('Key must be a private key', 'InvalidAccessError'); diff --git a/lib/internal/crypto/webcrypto_util.js b/lib/internal/crypto/webcrypto_util.js index 065520c59cb3..2b21d455cc57 100644 --- a/lib/internal/crypto/webcrypto_util.js +++ b/lib/internal/crypto/webcrypto_util.js @@ -139,6 +139,39 @@ function importDerKey(keyData, isPublic) { return handle; } +/** + * Imports a key in one of the formats shared by the asymmetric WebCrypto + * algorithms: 'KeyObjectHandle', 'spki', or 'pkcs8'. + * @param {string} format + * @param {any} keyData + * @param {string} name The algorithm name. + * @param {Set<string>} usagesSet + * @param {{ public: string[], private: string[] }} allowedUsages + * @param {(keyData: any) => void} [validatePkcs8] Additional validation run + * for 'pkcs8' key data after the key usages have been verified. + * @returns {KeyObjectHandle} + */ +function importAsymmetricKeyHandle( + format, keyData, name, usagesSet, allowedUsages, validatePkcs8) { + switch (format) { + case 'KeyObjectHandle': + verifyAcceptableKeyUse( + name, + usagesSet, + keyData.getKeyType() === kKeyTypePublic ? + allowedUsages.public : + allowedUsages.private); + return keyData; + case 'spki': + verifyAcceptableKeyUse(name, usagesSet, allowedUsages.public); + return importDerKey(keyData, true); + case 'pkcs8': + verifyAcceptableKeyUse(name, usagesSet, allowedUsages.private); + validatePkcs8?.(keyData); + return importDerKey(keyData, false); + } +} + function validateJwk(keyData, kty, extractable, usagesSet, expectedUse) { if (typeof keyData.kty !== 'string') throw lazyDOMException('Invalid keyData', 'DataError'); @@ -246,6 +279,7 @@ function importJwkSecretKey(keyData) { module.exports = { createKeyUsages, getKeyPairUsages, + importAsymmetricKeyHandle, importDerKey, importJwkKey, importJwkSecretKey, diff --git a/lib/internal/debugger/inspect.js b/lib/internal/debugger/inspect.js index c42fd78085fb..227f9e5390ec 100644 --- a/lib/internal/debugger/inspect.js +++ b/lib/internal/debugger/inspect.js @@ -271,10 +271,12 @@ const kInspectArgOptions = { 'cond': { type: 'string' }, 'expr': { type: 'string' }, 'help': { type: 'boolean', short: 'h' }, + 'host': { type: 'string' }, 'json': { type: 'boolean' }, - // Port, timeout, and max-hit use type 'string' because parseArgs has no - // numeric type; the values are parsed to integers by parseProbeTokens(). + // Port, timeout, max-hit, and pid use type 'string' because parseArgs has + // no numeric type; the values are parsed to integers by parseProbeTokens(). 'max-hit': { type: 'string' }, + 'pid': { type: 'string' }, 'port': { type: 'string' }, 'preview': { type: 'boolean' }, 'probe': { type: 'string' }, @@ -310,6 +312,10 @@ function parseInspectMode(args) { } return { mode: 'probe', tokens, args }; } + // These are only accepted in probe mode. + if (token.name === 'host' || token.name === 'pid') { + return { mode: 'probe', tokens, args }; + } } if (token.kind === 'option-terminator' || token.kind === 'positional') { break; diff --git a/lib/internal/debugger/inspect_client.js b/lib/internal/debugger/inspect_client.js index 1e5794ecc3a8..e305f95b55de 100644 --- a/lib/internal/debugger/inspect_client.js +++ b/lib/internal/debugger/inspect_client.js @@ -348,6 +348,9 @@ class Client extends EventEmitter { this._socket = socket; socket.on('data', this.handleChunk); + // A target that is terminated can reset the connection. Ignore the error and + // let the 'close' event handle it. + socket.on('error', (error) => debuglog('socket error %o', error)); socket.on('close', () => { this.emit('close'); }); diff --git a/lib/internal/debugger/inspect_helpers.js b/lib/internal/debugger/inspect_helpers.js index f77a4c8d1894..351e48e7e5fa 100644 --- a/lib/internal/debugger/inspect_helpers.js +++ b/lib/internal/debugger/inspect_helpers.js @@ -261,10 +261,10 @@ function writeInspectUsageAndExit(invokedAs, message, exitCode) { } out.write(`Usage: ${invokedAs} [--port=<port>] [<node-option> ...] [<script> [<script-args>] | <host>:<port> | -p <pid>] - ${invokedAs} --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] - [--probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] ...] - [--json] [--preview] [--timeout=<ms>] [--port=<port>] - [--] [<node-option> ...] <script> [<script-args> ...] + ${invokedAs} --probe <file>:<line>[:<col>] --expr <expr> + [<probe-option> ...] + [<script> [<script-args> ...] + | --pid <pid> | --host <host> | --port <port>] Interactive mode: Starts a live debugging session. @@ -284,11 +284,35 @@ Semantics: Non-interactive probe mode: Evaluates expressions whenever execution reaches specified source locations and prints all the evaluation results to stdout. -Example: +Usage: + # Launch a script and probe it: + $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] + [--probe <file>:<line>[:<col>] --expr <expr> [--cond <expr>] [--max-hit <n>] ...] + [--json] [--preview] [--timeout=<ms>] [--port=<port>] + [--] [<node-option> ...] <script> [<script-args> ...] + + # Activate the inspector in a running process and probe it: + $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --pid <pid> [--host <host>] [--port <port>] + + # Probe a running process whose inspector is already listening: + $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --host <host> [--port <port>] + $ node inspect --probe <file>:<line>[:<col>] --expr <expr> [...] --port <port> [--host <host>] + +Examples: + # Launch app.js with --no-warnings. Print "user" whenever line 10 runs, and + # "config.options" whenever column 15 of line 5 in src/utils.js runs: $ node inspect --probe app.js:10 --expr "user" --probe src/utils.js:5:15 --expr "config.options" --json --preview -- --no-warnings app.js --arg-for-app=foo + # Attach to the Node.js process with PID 12345, activating its inspector if + # needed, and detach once line 42 of app.js has run 5 times: + $ node inspect --probe app.js:42 --expr "req.url" --max-hit 5 --pid 12345 + + # Attach to the process whose inspector listens at 127.0.0.1:9229, and + # detach after 50 seconds: + $ node inspect --probe app.js:42 --expr "req.url" --timeout 50000 --host 127.0.0.1 --port 9229 + Options: --probe <file>:<line>[:<col>] Source location of the probe. <file> is matched as a @@ -305,13 +329,20 @@ Options: records a hit when <expr> is truthy at the location. A condition that throws is treated as false. --max-hit <n> Per-probe limit on evaluated hits. When not specified, - there's no hit limit. When any probe reaches its hit LIMIT, - the probing process will detach and report the results. - The probed process will continue to run. + there's no hit limit. When any probe reaches its hit limit, + the session finishes and reports the results. If the + process is launched by the probe mode, it is then + terminated, otherwise it is resumed and left to run. --json Output JSON if specified, otherwise human-readable text. --preview Include V8 object previews in JSON output. - --timeout <ms> Global session timeout (default: 30000). - --port <port> Inspector port for the debuggee (default: 0 = random). + --timeout <ms> Deadline in milliseconds (default: 30000), applied first to + startup and probe binding, then to the probing session. + --port <port> Inspector port of the probed process. Defaults to 0 (random) + when launching a script, and to 9229 when attaching to a + running process. + --host <host> Inspector host of the process to attach to (default: 127.0.0.1). + --pid <pid> PID of the Node.js process to attach to. Its inspector is + activated with SIGUSR1 if needed. Semantics: * Multiple --probe/--expr pairs are allowed. Same-location --probes share @@ -322,6 +353,10 @@ Semantics: * --probe utils.js:<line>[:<col>] matches every loaded utils.js. Pass a fuller path e.g. src/utils.js to narrow the match. * Use -- before any Node.js flags intended for the child process. +* When an entry point script is given, the probed process is launched. + Otherwise, --pid and/or --host:--port specifies the target to attach to. + The probing session ends when --max-hit or --timeout is reached, or + when the target process finishes. * Target errors are surfaced in the report as a terminal 'error' event. The probing process exits 0 unless it encounters an error itself. diff --git a/lib/internal/debugger/inspect_probe.js b/lib/internal/debugger/inspect_probe.js index 3b77a46f1ba1..b233048513e4 100644 --- a/lib/internal/debugger/inspect_probe.js +++ b/lib/internal/debugger/inspect_probe.js @@ -8,8 +8,10 @@ const { ArrayPrototypePush, ArrayPrototypeSlice, ArrayPrototypeSome, + DateNow, FunctionPrototypeBind, JSONStringify, + MathMax, NumberIsNaN, NumberParseInt, ObjectEntries, @@ -26,6 +28,7 @@ const { } = primordials; const { clearTimeout, setTimeout } = require('timers'); +const { setTimeout: _setTimeout } = require('timers/promises'); const { SideEffectFreeRegExpPrototypeSymbolReplace } = require('internal/util'); const debug = require('internal/util/debuglog').debuglog('inspect_probe'); @@ -45,6 +48,8 @@ const { } = internalBinding('errors'); const kProbeDefaultTimeout = 30000; +const kProbeConnectRetryDelay = 250; +const kProbeReapPollInterval = 50; const kProbeVersion = 2; const kProbeDisconnectSentinel = 'Waiting for the debugger to disconnect...'; const kProbeAttachedSentinel = 'Debugger attached.'; @@ -59,6 +64,11 @@ const kStartupTeardownAdvice = 'The target startup may have torn down the inspector. If startup does ' + 'not touch the inspector, this is likely a Node.js bug. Please file an issue.'; const kReviewProbeExprAdvice = 'If the failure repeats, review the probe expression.'; +const kTargetExitedDuringEvaluation = { + __proto__: null, + reason: 'Target process exited during probe evaluation', + advice: kReviewProbeExprAdvice, +}; const kDigitsRegex = /^\d+$/; const kInspectPortRegex = /^--inspect-port=(\d+)$/; @@ -82,6 +92,7 @@ const kInspectPortRegex = /^--inspect-port=(\d+)$/; * Per-breakpoint state keyed by V8 `breakpointId` from `Debugger.setBreakpointByUrl`. * @typedef {object} BreakpointDefinition * @property {number[]} probeIndices Indices into probes that bound to this breakpoint. + * @property {Location[]} locations Where the breakpoint is resolved so far. */ /** @@ -93,6 +104,7 @@ const kInspectPortRegex = /^--inspect-port=(\d+)$/; * Scoped to the location, so probes sharing a location all carry the same value. * @property {number} maxHit Per-probe hit limit from --max-hit. Infinity when unlimited. * @property {number} hits Count of hits observed. + * @property {Location[]} [locations] Shared with the BreakpointDefinition once it's bound. */ function probeReachedLimit(probe) { @@ -262,6 +274,15 @@ function formatHitLocation(location) { return `${location.url}:${location.line}:${location.column}`; } +function indentAndPush(lines, header, text) { + ArrayPrototypePush(lines, ` ${header}`); + const split = RegExpPrototypeSymbolSplit(/\r\n|\r|\n/g, text); + for (let i = 0; i < split.length; i++) { + if (split[i] === '' && i === split.length - 1) { continue; } + ArrayPrototypePush(lines, ` ${split[i]}`); + } +} + // Built human-readable text output for probe reports. function buildProbeTextReport(report) { const lines = []; @@ -304,17 +325,11 @@ function buildProbeTextReport(report) { if (result.event === 'error') { ArrayPrototypePush(lines, result.error.message); if (result.error.stderr !== undefined) { - ArrayPrototypePush(lines, ' [stderr]'); - const stderrLines = RegExpPrototypeSymbolSplit( - /\r\n|\r|\n/g, - result.error.stderr, - ); - for (let i = 0; i < stderrLines.length; i++) { - if (stderrLines[i] === '' && i === stderrLines.length - 1) { - continue; - } - ArrayPrototypePush(lines, ` ${stderrLines[i]}`); - } + indentAndPush(lines, '[stderr]', result.error.stderr); + } + const exception = result.error.details?.exception; + if (exception !== undefined) { + indentAndPush(lines, '[exception]', exception.exception?.description ?? exception.text); } } } @@ -323,7 +338,9 @@ function buildProbeTextReport(report) { } function parseProbeTokens(tokens, args) { - let port = 0; + let port; + let host; + let pid; let preview = false; let timeout = kProbeDefaultTimeout; let json = false; @@ -378,6 +395,21 @@ function parseProbeTokens(tokens, args) { } port = parseUnsignedInteger(token.value, 'inspector port', true); break; + case 'pid': + if (token.value === undefined) { + throw new ERR_DEBUGGER_STARTUP_ERROR(`Missing value for ${token.rawName}`); + } + pid = parseUnsignedInteger(token.value, 'pid'); + if (pid > 0x7fffffff) { + throw new ERR_DEBUGGER_STARTUP_ERROR(`Invalid pid: ${token.value}`); + } + break; + case 'host': + if (token.value === undefined || token.value === '') { + throw new ERR_DEBUGGER_STARTUP_ERROR(`Missing value for ${token.rawName}`); + } + host = token.value; + break; case 'preview': preview = true; break; @@ -455,14 +487,31 @@ function parseProbeTokens(tokens, args) { } const childArgv = ArrayPrototypeSlice(args, childStartIndex); + + // If the script is not specified, --pid, --host or --port indicates we should attach. + if (childArgv.length === 0 && (pid !== undefined || port !== undefined || host !== undefined)) { + host ??= '127.0.0.1'; + port ??= 9229; + if (port === 0) { + throw new ERR_DEBUGGER_STARTUP_ERROR('Cannot attach to port 0'); + } + return { host, port, preview, timeout, json, probes, childArgv, attach: true, pid }; + } + if (childArgv.length === 0) { - throw new ERR_DEBUGGER_STARTUP_ERROR('Probe mode requires a child script'); + throw new ERR_DEBUGGER_STARTUP_ERROR( + 'Probe mode requires an entry point script, or --pid, --port or --host to attach to a running process'); + } + + if (pid !== undefined || host !== undefined) { + throw new ERR_DEBUGGER_STARTUP_ERROR('--pid and --host cannot be used together with an entry point script'); } if (!sawSeparator && StringPrototypeStartsWith(childArgv[0], '-')) { throw new ERR_DEBUGGER_STARTUP_ERROR('Use -- before child Node.js flags in probe mode'); } + port ??= 0; let skipPortPreflight = port === 0; for (const arg of childArgv) { const inspectPortMatch = RegExpPrototypeExec(kInspectPortRegex, arg); @@ -486,13 +535,25 @@ function parseProbeTokens(tokens, args) { probes, childArgv, skipPortPreflight, + attach: false, }; } +function processExists(pid) { + try { + process.kill(pid, 0); + return true; + } catch (e) { + // EPERM means the process exists but belongs to another user. + return e.code !== 'ESRCH'; + } +} + class ProbeInspectorSession { constructor(options) { this.options = options; this.client = new InspectClient(); + // Null in attach mode. this.child = null; this.cleanupStarted = false; this.childStderr = ''; @@ -501,6 +562,13 @@ class ProbeInspectorSession { // True once the inspector WebSocket connects. Event handlers ignore // pre-connect exits/closes so launch/connect failures report through run(). this.connected = false; + // When the target process is attached to, a Debugger.paused event can arrive before all + // breakpoints are bound. Save the pause to handle later, only the first one needs to be stored + // since a paused target cannot pause again until resumed. + this.pendingPause = null; + // When the target process is only attached to and terminates due to an uncaught exception, + // this captures the details for the report. + this.uncaughtException = null; // True once breakpoints are bound and the target is released from --inspect-brk // via `Runtime.runIfWaitingForDebugger`. // Distinguishes "exited before user code ran" from "exited during the live session". @@ -513,6 +581,8 @@ class ProbeInspectorSession { this.scriptIdToUrl = new SafeMap(); this.results = []; this.timeout = null; + // When the current phase (startup, then the probe session) times out. + this.timeoutEnd = 0; // The currently-awaited CDP request, or null when no request is in flight. /** @type {{ method: string, probe: { index: number, location: Location } | null } | null} */ this.inFlight = null; @@ -527,9 +597,11 @@ class ProbeInspectorSession { ({ expr, target, condition, maxHit: maxHit ?? Infinity, hits: 0 })); this.onChildOutput = FunctionPrototypeBind(this.onChildOutput, this); this.onChildExit = FunctionPrototypeBind(this.onChildExit, this); + this.onExceptionThrown = FunctionPrototypeBind(this.onExceptionThrown, this); this.onClientClose = FunctionPrototypeBind(this.onClientClose, this); this.onPaused = FunctionPrototypeBind(this.onPaused, this); this.onScriptParsed = FunctionPrototypeBind(this.onScriptParsed, this); + this.onWaitingForDisconnect = FunctionPrototypeBind(this.onWaitingForDisconnect, this); } // Marking the probing process to exit with 0, recorded hits are trustworthy. @@ -551,21 +623,36 @@ class ProbeInspectorSession { this.timeout = null; } this.resolveCompletion({ exitCode, terminal }); + // Reject requests that are still waiting for a reply, which a closed socket never responds to. + // If the process is only attached to, this also releases the target, since V8 removes our + // breakpoints and resumes it if paused. + this.client.reset(); } + // Both exitCode and signal are null for an attached target, because its exit status is unknown. getProbeTargetExitEvent(exitCode, signal) { const pending = this.getPendingProbeIndices(); - const how = signal !== null ? `with signal ${signal}` : `with code ${exitCode}`; + let how = ''; + if (signal !== null) { + how = ` with signal ${signal}`; + } else if (exitCode !== null) { + how = ` with code ${exitCode}`; + } else if (this.uncaughtException !== null) { + how = ' with an uncaught exception'; + } const status = pending.length === 0 ? 'target completion' : `probes: ${formatPendingProbeLocations(this.probes, pending)}`; const error = { __proto__: null, code: 'probe_target_exit', - message: `Target exited ${how} before ${status}`, + message: `Target exited${how} before ${status}`, }; if (exitCode !== null) { error.exitCode = exitCode; } if (signal !== null) { error.signal = signal; } - error.stderr = trimProbeChildStderr(this.childStderr); + if (!this.options.attach) { error.stderr = trimProbeChildStderr(this.childStderr); } + if (this.uncaughtException !== null) { + error.details = { __proto__: null, exception: trimRemoteObject(this.uncaughtException) }; + } return { event: 'error', pending, error }; } @@ -600,10 +687,7 @@ class ProbeInspectorSession { if (!this.connected) { return; } if (this.finished) { return; } if (this.inFlight !== null && this.inFlight.probe !== null) { - this.recordInspectorFailure({ - reason: 'Target process exited during probe evaluation', - advice: kReviewProbeExprAdvice, - }); + this.recordInspectorFailure(kTargetExitedDuringEvaluation); return; } if (this.started && code === 0 && signal === null) { @@ -621,18 +705,48 @@ class ProbeInspectorSession { if (this.disconnectRequested) { return; } if (this.finished) { return; } - if (this.child.exitCode !== null || this.child.signalCode !== null) { + if (this.child !== null && (this.child.exitCode !== null || this.child.signalCode !== null)) { this.onChildExit(this.child.exitCode, this.child.signalCode); return; } - if (!this.started) { + this.reportLostConnection(); + } + + async reportLostConnection() { + const { pid } = this.options; + if (pid !== undefined) { + // When --pid is used, report a lost connection as a target exit. The socket closes as + // soon as the target is terminated, but the process stays visible until it is reaped + // so keep checking until the timeout before concluding that it is still running. + while (!this.finished && DateNow() < this.timeoutEnd && processExists(pid)) { + await _setTimeout(kProbeReapPollInterval); + } + if (this.finished) { return; } + if (!processExists(pid)) { + if (this.inFlight !== null && this.inFlight.probe !== null) { + this.recordInspectorFailure(kTargetExitedDuringEvaluation); + } else { + this.finishWithTrustedResult(this.getProbeTargetExitEvent(null, null)); + } + return; + } + this.recordInspectorFailure({ + reason: `Inspector connection lost while target process ${pid} is still running`, + advice: 'The target may have closed its inspector. If the failure persists, check the target.', + }); + return; + } + // The launched process should only drop the connection when its inspector is torn down, in this case + // the failure would be attributed to the startup or to the activity that was in flight. + // An attached target could also have been killed, which we cannot distinguish. + if (!this.options.attach && !this.started) { this.recordInspectorFailure({ reason: 'Inspector connection lost before probes started', advice: kStartupTeardownAdvice, }); return; } - if (this.inFlight !== null) { + if (!this.options.attach && this.inFlight !== null) { if (this.inFlight.probe !== null || this.lastProbeIndex !== null) { this.recordInspectorFailure({ reason: 'Inspector connection lost during probe activity', @@ -654,6 +768,29 @@ class ProbeInspectorSession { }); } + onExceptionThrown({ exceptionDetails }) { + debug('uncaught exception thrown in target: %s', exceptionDetails?.text); + this.uncaughtException = exceptionDetails; + } + + // Only emitted for an attached target, when it finishes on its own. + // TODO(joyeecheung): handle process.exit(1) from the target and targets that finish + // before the breakpoints are bound. + onWaitingForDisconnect() { + if (this.finished) { return; } + if (this.inFlight !== null && this.inFlight.probe !== null) { + this.recordInspectorFailure(kTargetExitedDuringEvaluation); + return; + } + if (this.uncaughtException !== null) { + this.finishWithTrustedResult(this.getProbeTargetExitEvent(null, null)); + return; + } + debug('target is waiting for the debugger to disconnect'); + const pending = this.getPendingProbeIndices(); + this.finishWithTrustedResult(pending.length === 0 ? { event: 'completed' } : { event: 'miss', pending }); + } + onPaused(params) { debug('paused: finished=%d, reason=%s hitBreakpoints=%j', this.finished, params.reason, params.hitBreakpoints); this.handlePaused(params).catch((error) => { @@ -671,7 +808,11 @@ class ProbeInspectorSession { // Ignore pauses that arrive before breakpoint setup is complete. Once // startup is marked complete, `Runtime.runIfWaitingForDebugger` may surface // the initial --inspect-brk pause, which the normal resume path handles. - if (!this.started) { return; } + if (!this.started) { + // An attached process is running, so queue its pauses in case there are more breakpoints to be bound. + if (this.options.attach) { this.pendingPause = params; } + return; + } const hitBreakpoints = params.hitBreakpoints; if (hitBreakpoints === undefined || hitBreakpoints.length === 0) { @@ -686,15 +827,7 @@ class ProbeInspectorSession { return; } - const { scriptId, lineNumber, columnNumber } = topFrame.location; - // `Debugger.scriptParsed` should always precede a pause for the same script. - // It should only be undefined if there's a bug (even in that case, just omit it). - const location = { - url: this.scriptIdToUrl.get(scriptId), - // CDP locations are 0-based, locations in public report are 1-based. - line: lineNumber + 1, - column: columnNumber + 1, - }; + const location = this.toReportLocation(topFrame.location); for (const breakpointId of hitBreakpoints) { // The breakpoint ID is stable even for scripts parsed after the initial resolution // so we can count on it here. @@ -710,8 +843,6 @@ class ProbeInspectorSession { // Finish proactively as soon as any probe reaches its hit limit. All probes // hit in this pause are recorded first, then the session ends. - // TODO(joyeecheung): When we implement attach mode, this teardown must - // resume-and-detach rather than kill, since the target is not ours. if (!this.finished && ArrayPrototypeSome(this.probes, probeReachedLimit)) { this.finishWithTrustedResult({ event: 'completed' }); return; @@ -723,9 +854,15 @@ class ProbeInspectorSession { async evaluateProbe(callFrameId, probeIndex, location) { if (this.finished) { return; } const probe = this.probes[probeIndex]; + const params = { callFrameId, expression: probe.expr, generatePreview: true }; + if (this.options.attach) { + // Apply the timeout because an attached process would keep running the expression + // even if the probing session has finished. + params.timeout = this.options.timeout; + } const evaluation = await this.callCdp( 'Debugger.evaluateOnCallFrame', - { callFrameId, expression: probe.expr, generatePreview: true }, + params, { __proto__: null, index: probeIndex, location }, ); this.lastProbeIndex = probeIndex; @@ -772,10 +909,7 @@ class ProbeInspectorSession { // Only the in-flight evaluation gets attribution. Other rejections // under disconnect are downstream noise. if (probe !== null) { - this.recordInspectorFailure({ - reason: 'Target process exited during probe evaluation', - advice: kReviewProbeExprAdvice, - }); + this.recordInspectorFailure(kTargetExitedDuringEvaluation); } throw kInspectorFailedSentinel; } @@ -868,7 +1002,7 @@ class ProbeInspectorSession { message: `${reason}${suffix}. ${advice}`, }; if (attribution !== null) { error.probe = attribution; } - error.stderr = trimProbeChildStderr(this.childStderr); + if (!this.options.attach) { error.stderr = trimProbeChildStderr(this.childStderr); } let details; if (failedCdpMethod !== null) { @@ -884,11 +1018,35 @@ class ProbeInspectorSession { this.finishWithUnreliableResult({ event: 'error', pending, error }); } + restartTimeoutFromNow() { + this.timeoutEnd = DateNow() + this.options.timeout; + } + startTimeout() { + this.restartTimeoutFromNow(); this.timeout = setTimeout(() => { debug('timeout fired: finished=%s, inFlight=%j, lastProbeIndex=%s', this.finished, this.inFlight, this.lastProbeIndex); if (this.finished) { return; } + if (this.options.attach) { + // TODO(joyeecheung): if an evaluation is still running on timeout, give it a short period + // to finish, and check that V8 terminates it before reporting. + if (this.inFlight !== null && this.inFlight.probe !== null) { + this.recordInspectorFailure({ + reason: 'Probe session timed out', + advice: 'The probe expression was still running when the timeout fired. The target resumes once it is ' + + 'terminated, after at most another `--timeout`. If the failure persists, review the probe expressions.', + }); + return; + } + // If the process is attached, timeout is considered a normal end of session, so it is not a failure. + const pending = this.getPendingProbeIndices(); + const waiting = pending.length === 0 ? '' : + ` waiting for probes: ${formatPendingProbeLocations(this.probes, pending)}`; + const message = `Session timed out after ${this.options.timeout}ms${waiting}, detaching from the target`; + this.finishWithTrustedResult({ event: 'timeout', pending, error: { code: 'probe_timeout', message } }); + return; + } if (this.inFlight !== null) { const hasProbeAttribution = this.inFlight.probe !== null || this.lastProbeIndex !== null; @@ -915,10 +1073,16 @@ class ProbeInspectorSession { } attachListeners() { - this.child.on('exit', this.onChildExit); + if (this.child !== null) { + this.child.on('exit', this.onChildExit); + } this.client.on('close', this.onClientClose); this.client.on('Debugger.paused', this.onPaused); this.client.on('Debugger.scriptParsed', this.onScriptParsed); + if (this.options.attach) { + this.client.on('NodeRuntime.waitingForDisconnect', this.onWaitingForDisconnect); + this.client.on('Runtime.exceptionThrown', this.onExceptionThrown); + } } onScriptParsed(params) { @@ -928,6 +1092,20 @@ class ProbeInspectorSession { // This map grows by the number of scripts parsed, which is limited, and is just a // small string -> string map. The lifetime is bounded by probe timeout etc. so cleanup is overkill. this.scriptIdToUrl.set(params.scriptId, params.url); + // Scripts parsed after bindBreakpoints() report the locations they resolve in resolvedBreakpoints. + // TODO(joyeecheung): we may be missing the location if scriptParsed arrives in the same batch as + // the setBreakpointByUrl response. Buffer unknown IDs instead. + for (const { breakpointId, location } of params.resolvedBreakpoints ?? []) { + const definition = this.breakpointDefinitions.get(breakpointId); + if (definition !== undefined) { ArrayPrototypePush(definition.locations, this.toReportLocation(location)); } + } + } + + // `Debugger.scriptParsed` should always precede a pause for the same script. + // The URL should only be undefined if there's a bug (even in that case, just omit it). + toReportLocation({ scriptId, lineNumber, columnNumber }) { + // CDP locations are 0-based, locations in public report are 1-based. + return { url: this.scriptIdToUrl.get(scriptId), line: lineNumber + 1, column: columnNumber + 1 }; } async bindBreakpoints() { @@ -974,7 +1152,9 @@ class ProbeInspectorSession { const result = await this.callCdp('Debugger.setBreakpointByUrl', params); debug('breakpoint set: id=%s urlRegex=%s locations=%j', result.breakpointId, params.urlRegex, result.locations); - this.breakpointDefinitions.set(result.breakpointId, { probeIndices }); + const locations = ArrayPrototypeMap(result.locations ?? [], (location) => this.toReportLocation(location)); + for (const probeIndex of probeIndices) { this.probes[probeIndex].locations = locations; } + this.breakpointDefinitions.set(result.breakpointId, { probeIndices, locations }); } } @@ -995,11 +1175,15 @@ class ProbeInspectorSession { code: exitCode, report: { v: kProbeVersion, - probes: ArrayPrototypeMap(this.probes, ({ expr, target, maxHit, condition }) => { + target: this.options.attach ? + { pid: this.options.pid, host: this.options.host, port: this.options.port } : + { argv: this.options.childArgv }, + probes: ArrayPrototypeMap(this.probes, ({ expr, target, maxHit, condition, locations }) => { const probe = { expr, target }; if (condition !== undefined) { probe.condition = condition; } // Omit an unlimited maxHit, as Infinity would serialize to null in JSON. if (maxHit !== Infinity) { probe.maxHit = maxHit; } + probe.locations = locations ?? []; return probe; }), results, @@ -1020,8 +1204,6 @@ class ProbeInspectorSession { if (this.child === null) { return; } - // TODO(joyeecheung): When we implement attach mode, this teardown must - // resume-and-detach rather than kill, since the target is not ours. if (this.child.exitCode === null && this.child.signalCode === null) { this.child.kill(); } @@ -1029,27 +1211,70 @@ class ProbeInspectorSession { async run() { try { - const { childArgv, host, port, skipPortPreflight } = this.options; - const { 0: child, 1: actualPort, 2: actualHost } = - await launchChildProcess(childArgv, - host, - port, - this.onChildOutput, - { skipPortPreflight }); - this.child = child; + const { attach, pid } = this.options; + let { host, port } = this.options; + if (attach) { + // When attaching, the timeout also covers the time spent by the target process to activate the inspector. + this.restartTimeoutFromNow(); + if (pid !== undefined) { + try { + process._debugProcess(pid); // Activates the inspector e.g. with SIGUSR1 on POSIX. + } catch (e) { + if (e.code !== 'ESRCH') { throw e; } + throw new ERR_DEBUGGER_STARTUP_ERROR(`Target process ${pid} does not exist`); + } + } + } else { + const { childArgv, skipPortPreflight } = this.options; + const { 0: child, 1: actualPort, 2: actualHost } = + await launchChildProcess(childArgv, host, port, this.onChildOutput, { skipPortPreflight }); + this.child = child; + host = actualHost; + port = actualPort; + } // On Debugger.enable, V8 emits Debugger.scriptParsed for all existing scripts. // Attach the listener early to make sure we don't miss any events. this.attachListeners(); - await this.client.connect(actualPort, actualHost); + // A --pid target may still be starting its inspector. Retry until the timeout. + // TODO(joyeecheung): A port that accepts connections but never answers HTTP can stall here, because the startup + // timeout only fires after it is connected. Limiting it requires InspectClient to abort its pending requests. + for (;;) { + try { + await this.client.connect(port, host); + break; + } catch (error) { + if (!attach) { throw error; } + if (pid === undefined) { + throw new ERR_DEBUGGER_STARTUP_ERROR(`Could not attach to ${host}:${port}: ${error.message}`); + } + if (!processExists(pid)) { + throw new ERR_DEBUGGER_STARTUP_ERROR(`Target process ${pid} exited before it could be attached`); + } + if (DateNow() >= this.timeoutEnd) { + throw new ERR_DEBUGGER_STARTUP_ERROR( + `Could not attach to ${host}:${port} within ${this.options.timeout}ms: ${error.message}`); + } + await _setTimeout(kProbeConnectRetryDelay); + } + } this.connected = true; + if (!attach) { + // If launching a new child process, start the timeout after it is connected. + this.restartTimeoutFromNow(); + } + // If the main thread of the target is blocked, it may never answer the requests below. + this.timeout = setTimeout(() => { + this.recordInspectorFailure({ + reason: `Timed out after ${this.options.timeout}ms waiting for the target to respond`, + advice: 'Its main thread may be blocked in synchronous work. Try increasing `--timeout`.', + }); + }, MathMax(this.timeoutEnd - DateNow(), 0)); + this.timeout.unref(); try { try { - await waitForDebugger( - this.client, - (method) => this.callCdp(method), - ); + if (!attach) { await waitForDebugger(this.client, (method) => this.callCdp(method)); } } catch (err) { // A close event may have completed the structured report while the // readiness helper was rejecting its disconnect race. @@ -1057,10 +1282,25 @@ class ProbeInspectorSession { throw err; } await this.callCdp('Runtime.enable'); + // The port may be occupied, for example, by a second process with inspector listening on the default port. + if (pid !== undefined) { + const { result } = await this.callCdp('Runtime.evaluate', { expression: 'process.pid' }); + if (result.value !== pid) { + throw new ERR_DEBUGGER_STARTUP_ERROR(`The inspector at ${host}:${port} belongs to process ${result.value}, ` + + `not to --pid ${pid}. Pass the port that the inspector of the target listens on with --port`); + } + } await this.callCdp('Debugger.enable'); + if (attach) { + // Get a NodeRuntime.waitingForDisconnect event when the target finishes, so the session can + // end and let it exit. + await this.callCdp('NodeRuntime.notifyWhenWaitingForDisconnect', { enabled: true }); + } await this.bindBreakpoints(); this.started = true; + clearTimeout(this.timeout); this.startTimeout(); + if (this.pendingPause !== null) { await this.handlePaused(this.pendingPause); } await this.callCdp('Runtime.runIfWaitingForDebugger'); } catch (err) { if (err !== kInspectorFailedSentinel) { throw err; } diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 786fc7e275eb..78d3de196a52 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -1143,8 +1143,6 @@ E('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError); E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError); E('ERR_ASSERTION', '%s', Error); E('ERR_ASYNC_CALLBACK', '%s must be a function', TypeError); -E('ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED', - 'Async loader request never settled', Error); E('ERR_ASYNC_RESOURCE_DOMAIN_REMOVED', 'The domain property on AsyncResource has been removed. ' + 'Use AsyncLocalStorage instead.', Error); @@ -1327,6 +1325,9 @@ E('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent', Error); E('ERR_HTTP2_SEND_FILE_NOSEEK', 'Offset or length can only be specified for regular files', Error); E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error); +E('ERR_HTTP2_SESSION_MEMORY_EXCEEDED', + 'The request was not sent because the session exceeded maxSessionMemory', + Error); E('ERR_HTTP2_SETTINGS_CANCEL', 'HTTP2 session settings canceled', Error); E('ERR_HTTP2_SOCKET_BOUND', 'The socket is already bound to an Http2Session', Error); @@ -1605,13 +1606,6 @@ E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks', Error); E('ERR_IP_BLOCKED', function(ip) { return `IP(${ip}) is blocked by net.BlockList`; }, Error); -E( - 'ERR_LOADER_CHAIN_INCOMPLETE', - '"%s" did not call the next hook in its chain and did not' + - ' explicitly signal a short circuit. If this is intentional, include' + - ' `shortCircuit: true` in the hook\'s return.', - Error, -); E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error); E('ERR_MISSING_ARGS', (...args) => { @@ -1789,13 +1783,14 @@ E('ERR_REQUIRE_ESM', 'all ES modules instead).\n'; return msg; }, Error); -E('ERR_REQUIRE_ESM_RACE_CONDITION', (filename, parentFilename, isForAsyncLoaderHookWorker) => { +E('ERR_REQUIRE_ESM_RACE_CONDITION', (filename, parentFilename) => { let raceMessage = `Cannot require() ES Module ${filename} because it is not yet fully loaded.\n`; raceMessage += 'This may be caused by a race condition if the module is simultaneously dynamically '; raceMessage += 'import()-ed via Promise.all().\n'; - raceMessage += 'Try await-ing the import() sequentially in a loop instead.\n'; - raceMessage += ` (From ${parentFilename ? `${parentFilename} in ` : ' '}`; - raceMessage += `${isForAsyncLoaderHookWorker ? 'loader hook worker thread' : 'non-loader-hook thread'})`; + raceMessage += 'Try await-ing the import() sequentially in a loop instead.'; + if (parentFilename) { + raceMessage += `\n (From ${parentFilename})`; + } return raceMessage; }, Error); E('ERR_SCRIPT_EXECUTION_INTERRUPTED', diff --git a/lib/internal/freeze_intrinsics.js b/lib/internal/freeze_intrinsics.js index 5dd425cb0934..3f1e397ec192 100644 --- a/lib/internal/freeze_intrinsics.js +++ b/lib/internal/freeze_intrinsics.js @@ -31,6 +31,8 @@ const { ArrayPrototype, ArrayPrototypeForEach, ArrayPrototypePush, + AsyncDisposableStack, + AsyncDisposableStackPrototype, AsyncFunctionPrototype, AsyncGeneratorFunctionPrototype, AsyncGeneratorFunctionPrototypePrototype, @@ -48,6 +50,8 @@ const { DataViewPrototype, Date, DatePrototype, + DisposableStack, + DisposableStackPrototype, Error, ErrorPrototype, EvalError, @@ -106,6 +110,8 @@ const { String, StringIteratorPrototype, StringPrototype, + SuppressedError, + SuppressedErrorPrototype, Symbol, SymbolPrototype, SyntaxError, @@ -171,6 +177,7 @@ module.exports = function() { EvalErrorPrototype, RangeErrorPrototype, ReferenceErrorPrototype, + SuppressedErrorPrototype, SyntaxErrorPrototype, TypeErrorPrototype, URIErrorPrototype, @@ -225,12 +232,14 @@ module.exports = function() { IteratorPrototype, // 27.1.3 WrapForValidIteratorPrototype, // 27.1.3.2.2.1 AsyncIteratorPrototype, // 27.1.4 - PromisePrototype, // 27.2 - GeneratorFunctionPrototype, // 27.3 - AsyncGeneratorFunctionPrototype, // 27.4 - // 27.5 GeneratorPrototype + DisposableStackPrototype, // 27.3.2.1 + AsyncDisposableStackPrototype, // 27.4.2.1 + PromisePrototype, // 27.5.4.4 + GeneratorFunctionPrototype, // 27.6.2.1 + AsyncGeneratorFunctionPrototype, // 27.7.3.3 + // 27.8 GeneratorPrototype GeneratorFunctionPrototypePrototype, - // 27.6 AsyncGeneratorPrototype + // 27.9 AsyncGeneratorPrototype AsyncGeneratorFunctionPrototypePrototype, AsyncFunctionPrototype, // 27.7 @@ -270,6 +279,7 @@ module.exports = function() { EvalError, RangeError, ReferenceError, + SuppressedError, SyntaxError, TypeError, URIError, @@ -329,14 +339,17 @@ module.exports = function() { Iterator, // 27.1.3 WrapForValidIteratorPrototype, // 27.1.3.2.2.1 ArrayIteratorPrototype, // 27.1.4 - Promise, // 27.2 - // 27.3 GeneratorFunction - // 27.5 Generator + // 27.2 SymbolDispose + DisposableStack, // 27.3 + AsyncDisposableStack, // 27.4 + Promise, // 27.5 + // 27.6 GeneratorFunction + // 27.8 Generator GeneratorFunctionPrototype, - // 27.4 AsyncGeneratorFunction - // 27.6 AsyncGenerator + // 27.7 AsyncGeneratorFunction + // 27.9 AsyncGenerator AsyncGeneratorFunctionPrototype, - // 27.7 AsyncFunction + // 27.10 AsyncFunction AsyncFunctionPrototype, // 28 Reflection diff --git a/lib/internal/fs/cp/cp.js b/lib/internal/fs/cp/cp.js index 1ec5a2d89cac..410ee26e001c 100644 --- a/lib/internal/fs/cp/cp.js +++ b/lib/internal/fs/cp/cp.js @@ -10,7 +10,7 @@ const { Promise, PromisePrototypeThen, PromiseReject, - SafePromiseAll, + SafePromiseAllReturnArrayLike, StringPrototypeSplit, } = primordials; const { @@ -131,7 +131,7 @@ function getStats(src, dest, opts) { const statFunc = opts.dereference ? (file) => stat(file, { bigint: true }) : (file) => lstat(file, { bigint: true }); - return SafePromiseAll([ + return SafePromiseAllReturnArrayLike([ statFunc(src), PromisePrototypeThen(statFunc(dest), undefined, (err) => { if (err.code === 'ENOENT') return null; diff --git a/lib/internal/fs/dir.js b/lib/internal/fs/dir.js index 32050f31ae6d..4ecdfd9c07e2 100644 --- a/lib/internal/fs/dir.js +++ b/lib/internal/fs/dir.js @@ -350,6 +350,13 @@ function opendir(path, options, callback) { encoding: 'utf8', }); + // Validate bufferSize before opening the directory. The Dir constructor + // validates it too, but an error thrown from opendirCallback can't be caught. + // Copy the options and validate the copy so that the values checked here are + // the ones Dir receives. + options = getOptions({ bufferSize: 32, ...options }); + validateUint32(options.bufferSize, 'options.bufferSize', true); + function opendirCallback(error, handle) { if (error) { callback(error); diff --git a/lib/internal/fs/promises.js b/lib/internal/fs/promises.js index b79e807fe6c4..53eb2f4938db 100644 --- a/lib/internal/fs/promises.js +++ b/lib/internal/fs/promises.js @@ -112,6 +112,7 @@ const { } = require('internal/util'); const { getOptionValue } = require('internal/options'); const EventEmitter = require('events'); +const { addAbortListener } = require('internal/events/abort_listener'); const { StringDecoder } = require('string_decoder'); const { kFSWatchStart, watch } = require('internal/fs/watchers'); const nonNativeWatcher = require('internal/fs/recursive_watch'); @@ -1218,13 +1219,19 @@ function rejectWithReason(signal, reject) { }; } -async function raceWithSignal(opPromise, signal) { +function raceWithSignal(opPromise, signal) { if (!signal) return opPromise; + return raceWithAbortSignal(opPromise, signal); +} + +async function raceWithAbortSignal(opPromise, signal) { const { promise: abortPromise, reject } = PromiseWithResolvers(); - // eslint-disable-next-line no-unused-vars - using _ = EventEmitter.addAbortListener(signal, - rejectWithReason(signal, reject)); - return await SafePromiseRace([opPromise, abortPromise]); + const listener = addAbortListener(signal, rejectWithReason(signal, reject)); + try { + return await SafePromiseRace([opPromise, abortPromise]); + } finally { + listener[SymbolDispose](); + } } async function writeFileHandle(filehandle, data, signal, encoding) { @@ -1569,6 +1576,8 @@ async function write(handle, buffer, offsetOrOptions, length, position) { if (typeof position !== 'number') position = null; validateOffsetLengthWrite(offset, length, buffer.byteLength); + // V8 does not report -0 as an int32, which the binding requires. + length |= 0; const bytesWritten = (await PromisePrototypeThen( binding.writeBuffer(handle.fd, buffer, offset, @@ -1679,7 +1688,9 @@ async function rmdir(path, options) { } async function fdatasync(handle) { - if (permission.isEnabled()) { + // TODO(rafaelgss): publish a diagnostics channel event for fd-based APIs in + // audit mode. + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fdatasync API is disabled when Permission Model is enabled.'); } return await PromisePrototypeThen( @@ -1690,7 +1701,7 @@ async function fdatasync(handle) { } async function fsync(handle) { - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fsync API is disabled when Permission Model is enabled.'); } return await PromisePrototypeThen( @@ -1964,7 +1975,7 @@ async function unlink(path) { } async function fchmod(handle, mode) { - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fchmod API is disabled when Permission Model is enabled.'); } mode = parseFileMode(mode, 'mode'); @@ -2026,7 +2037,7 @@ async function lchown(path, uid, gid) { async function fchown(handle, uid, gid) { validateInteger(uid, 'uid', -1, kMaxUserId); validateInteger(gid, 'gid', -1, kMaxUserId); - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('fchown API is disabled when Permission Model is enabled.'); } return await PromisePrototypeThen( @@ -2072,7 +2083,7 @@ async function utimes(path, atime, mtime) { } async function futimes(handle, atime, mtime) { - if (permission.isEnabled()) { + if (permission.isEnabled() && !permission.isAuditMode()) { throw new ERR_ACCESS_DENIED('futimes API is disabled when Permission Model is enabled.'); } atime = toUnixTimestamp(atime, 'atime'); @@ -2226,8 +2237,14 @@ async function writeFile(path, data, options) { if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) { path = getValidatedPath(path); - await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'), - parseFileMode(options.mode, 'mode', 0o666), data); + const flagsNumber = stringToFlags(flag, 'options.flag'); + const mode = parseFileMode(options.mode, 'mode', 0o666); + try { + await writeFileInOneRoundTrip(path, flagsNumber, mode, data); + } catch (err) { + ErrorCaptureStackTrace(err); + throw err; + } checkAborted(options.signal); // An abort during the write still wins. return; } @@ -2244,6 +2261,10 @@ async function writeFile(path, data, options) { /** * Open + write + close as one thread pool round trip. + * Throws synchronously if the permission model denies access, while the + * caller's frames are still on the stack. The caller is responsible for + * capturing the stack trace of a rejection, as no JS frames are on the stack + * when the job completes. * @param {string|Buffer} path Validated path * @param {number} flagsNumber * @param {number} mode @@ -2251,22 +2272,21 @@ async function writeFile(path, data, options) { * @returns {Promise<void>} */ function writeFileInOneRoundTrip(path, flagsNumber, mode, data) { - return new Promise((resolve, reject) => { - const job = new binding.WriteFileJob(path, flagsNumber, mode, data); + const job = new binding.WriteFileJob(path, flagsNumber, mode, data); + const promise = new Promise((resolve, reject) => { job.ondone = (err) => { if (err != null) { - ErrorCaptureStackTrace(err, writeFileInOneRoundTrip); reject(err); } else { resolve(); } }; - const accessError = job.run(path); - if (accessError !== undefined) { - ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip); - reject(accessError); - } }); + const accessError = job.run(path); + if (accessError !== undefined) { + throw accessError; + } + return promise; } function isCustomIterable(obj) { @@ -2309,7 +2329,15 @@ async function readFile(path, options) { // files of up to one chunk; larger and non-regular files (size 0) come // back as an open fd + size and are read by readFileHandle() as before. path = getValidatedPath(path); - const { 0: buffer, 1: fd, 2: size } = await readFileInOneRoundTrip(path, stringToFlags(flag)); + const flagsNumber = stringToFlags(flag); + let result; + try { + result = await readFileInOneRoundTrip(path, flagsNumber); + } catch (err) { + ErrorCaptureStackTrace(err); + throw err; + } + const { 0: buffer, 1: fd, 2: size } = result; if (fd === -1) { checkAborted(options.signal); // An abort during the read still wins. return options.encoding ? buffer.toString(options.encoding) : buffer; @@ -2323,28 +2351,31 @@ async function readFile(path, options) { } /** + * Throws synchronously if the permission model denies access, while the + * caller's frames are still on the stack. The caller is responsible for + * capturing the stack trace of a rejection, as no JS frames are on the stack + * when the job completes. * @param {string|Buffer} path Validated path * @param {number} flagsNumber * @returns {Promise<[Buffer|undefined, number, number|undefined]>} [buffer, -1] or [undefined, fd, size] */ function readFileInOneRoundTrip(path, flagsNumber) { - return new Promise((resolve, reject) => { - const job = new binding.ReadFileJob(path, flagsNumber, kReadFileBufferLength); + const job = new binding.ReadFileJob(path, flagsNumber, kReadFileBufferLength); + const promise = new Promise((resolve, reject) => { job.ondone = (err, buffer, fd, size, closeErr) => { const error = err ?? closeErr; if (error != null) { - ErrorCaptureStackTrace(error, readFileInOneRoundTrip); reject(error); } else { resolve([buffer, fd, size]); } }; - const accessError = job.run(path); - if (accessError !== undefined) { - ErrorCaptureStackTrace(accessError, readFileInOneRoundTrip); - reject(accessError); - } }); + const accessError = job.run(path); + if (accessError !== undefined) { + throw accessError; + } + return promise; } async function* _watch(filename, options = kEmptyObject) { diff --git a/lib/internal/fs/streams.js b/lib/internal/fs/streams.js index c8c86b59640a..e66a256f8118 100644 --- a/lib/internal/fs/streams.js +++ b/lib/internal/fs/streams.js @@ -33,6 +33,7 @@ const { validateThisInternalField, } = require('internal/validators'); const { errorOrDestroy } = require('internal/streams/destroy'); +const { getUserDefaultHighWaterMark } = require('internal/streams/state'); const fs = require('fs'); const { kRef, kUnref, FileHandle } = require('internal/fs/promises'); const { Buffer } = require('buffer'); @@ -193,7 +194,7 @@ function ReadStream(path, options) { // A little bit bigger buffer and water marks by default options = copyObject(getOptions(options, kEmptyObject)); if (options.highWaterMark === undefined) - options.highWaterMark = 64 * 1024; + options.highWaterMark = getUserDefaultHighWaterMark() ?? 64 * 1024; if (options.autoDestroy === undefined) { options.autoDestroy = false; @@ -274,6 +275,9 @@ ObjectDefineProperty(ReadStream.prototype, 'autoClose', { ReadStream.prototype._construct = _construct; ReadStream.prototype._read = function(n) { + if (n === 0) + n = 64 * 1024; + n = this.pos !== undefined ? MathMin(this.end - this.pos + 1, n) : MathMin(this.end - this.bytesRead + 1, n); @@ -473,7 +477,7 @@ function writeAll(data, size, pos, cb, retries = 0) { } function writevAll(chunks, size, pos, cb, retries = 0) { - this[kFs].writev(this.fd, chunks, this.pos, (er, bytesWritten, buffers) => { + this[kFs].writev(this.fd, chunks, pos, (er, bytesWritten, buffers) => { // No data currently available and operation should be retried later. if (er?.code === 'EAGAIN') { er = null; diff --git a/lib/internal/http.js b/lib/internal/http.js index 68d4a75a253e..1fa8bf24d828 100644 --- a/lib/internal/http.js +++ b/lib/internal/http.js @@ -20,7 +20,11 @@ const { const { URL } = require('internal/url'); const { Buffer } = require('buffer'); const { isIPv4 } = require('internal/net'); -const { ERR_PROXY_INVALID_CONFIG } = require('internal/errors').codes; +const { + ERR_INVALID_ARG_VALUE, + ERR_PROXY_INVALID_CONFIG, +} = require('internal/errors').codes; +const { validateBoolean, validateOneOf } = require('internal/validators'); let utcCache; let utcHeaderCache; @@ -301,6 +305,33 @@ function getGlobalAgent(proxyEnv, Agent) { }); } +/** + * Validates the `insecureHTTPParser` and `httpValidation` options shared by + * HTTP clients and servers, and sets them on `target`. + * @param {object} target + * @param {{ insecureHTTPParser?: boolean, httpValidation?: string }} options + */ +function setHttpParserOptions(target, options) { + const insecureHTTPParser = options.insecureHTTPParser; + if (insecureHTTPParser !== undefined) + validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); + target.insecureHTTPParser = insecureHTTPParser; + + const httpValidation = options.httpValidation; + if (httpValidation !== undefined) { + validateOneOf(httpValidation, 'options.httpValidation', + ['strict', 'relaxed', 'insecure']); + if (insecureHTTPParser !== undefined) { + throw new ERR_INVALID_ARG_VALUE( + 'options.httpValidation', + httpValidation, + 'cannot be used together with options.insecureHTTPParser', + ); + } + } + target.httpValidation = httpValidation; +} + module.exports = { kOutHeaders: Symbol('kOutHeaders'), kNeedDrain: Symbol('kNeedDrain'), @@ -318,4 +349,5 @@ module.exports = { getGlobalAgent, parseProxyUrl, redactProxyUrl, + setHttpParserOptions, }; diff --git a/lib/internal/http/agent.js b/lib/internal/http/agent.js index 3871c5b56a2f..20aef9f83760 100644 --- a/lib/internal/http/agent.js +++ b/lib/internal/http/agent.js @@ -22,6 +22,7 @@ 'use strict'; const { + MathTrunc, NumberIsFinite, NumberParseInt, ObjectKeys, @@ -56,10 +57,14 @@ const { const { onStreamRead, } = require('internal/stream_base_commons'); +const { kTimeout } = require('internal/timers'); const { kReadBytesOrError, streamBaseState, } = internalBinding('stream_wrap'); +// Call getLibuvNow() on the binding: its fast API call reads the binding +// from the receiver. +const timersBinding = internalBinding('timers'); const { validateNumber, validateOneOf, @@ -139,6 +144,20 @@ function installFreeSocketDataGuard(socket) { } } +// The data guard above only runs when the event loop polls for I/O. Data +// that reached the OS socket buffer after the last poll has not been seen +// by it yet, so check for it directly before handing an idle socket to a +// request. See: https://hackerone.com/reports/4038361 (CVE-2026-105481). +function hasPendingRead(socket) { + // A socket that is still connecting has nothing to read yet, and a + // pending connect error must be reported to the request rather than + // swallowed here. + if (socket.connecting) return false; + const handle = socket._handle; + return typeof handle?.hasPendingRead === 'function' && + handle.hasPendingRead() === true; +} + function removeFreeSocketDataGuard(socket) { if (socket[kFreeSocketDataGuard]) { socket.removeListener('connect', socket[kFreeSocketDataGuard]); @@ -158,7 +177,7 @@ function Agent(options) { EventEmitter.call(this); - this.options = { __proto__: null, ...options }; + this.options = { __proto__: kEmptyObject, ...options }; this.defaultPort = this.options.defaultPort || 80; this.protocol = this.options.protocol || 'http:'; @@ -216,6 +235,12 @@ function Agent(options) { const requests = this.requests[name]; if (requests?.length) { + if (hasPendingRead(socket)) { + // onClose() will create a new socket for the pending request. + debug('PENDING DATA on released socket - destroying'); + socket.destroy(); + return; + } const req = requests.shift(); const reqAsyncRes = req[kRequestAsyncResource]; if (reqAsyncRes) { @@ -375,7 +400,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, } // Here the agent options will override per-request options. - options = { __proto__: null, ...options, ...this.options }; + options = { __proto__: kEmptyObject, ...options, ...this.options }; if (options.socketPath) options.path = options.socketPath; @@ -390,9 +415,23 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, while (freeSockets.length && freeSockets[0].destroyed) { freeSockets.shift(); } - socket = this.scheduling === 'fifo' ? - freeSockets.shift() : - freeSockets.pop(); + const now = timersBinding.getLibuvNow(); + while (freeSockets.length) { + socket = this.scheduling === 'fifo' ? + freeSockets.shift() : + freeSockets.pop(); + if (socket.destroyed || isFreeSocketExpired(socket, now)) { + debug('free socket destroyed or expired'); + socket.destroy(); + socket.emit('agentRemove'); + } else if (hasPendingRead(socket)) { + debug('PENDING DATA on FREE socket - destroying poisoned socket'); + socket.destroy(); + } else { + break; + } + socket = undefined; + } if (!freeSockets.length) delete this.freeSockets[name]; } @@ -445,7 +484,7 @@ Agent.prototype.addRequest = function addRequest(req, options, port/* legacy */, Agent.prototype.createSocket = function createSocket(req, options, cb) { // Here the agent options will override per-request options. - options = { __proto__: null, ...options, ...this.options }; + options = { __proto__: kEmptyObject, ...options, ...this.options }; if (options.socketPath) options.path = options.socketPath; @@ -690,6 +729,19 @@ Agent.prototype.destroy = function destroy() { } }; +// A free socket is destroyed by its idle timeout timer, but timers cannot run +// while the event loop is blocked, so the socket can still be in the pool after +// its timeout has passed, when the server may have closed the connection. +// The timer records on the timers' clock when it was last started or refreshed, +// and the timer scheduler truncates delays to whole milliseconds. +// socket.timeout is checked too: a timer that has fired keeps its _idleTimeout +// when the timeout is cleared afterwards. +function isFreeSocketExpired(socket, now) { + const timer = socket[kTimeout]; + return socket.timeout > 0 && timer != null && timer._idleTimeout > 0 && + now - timer._idleStart >= MathTrunc(timer._idleTimeout); +} + function setRequestSocket(agent, req, socket) { req.onSocket(socket); const agentTimeout = agent.options.timeout || 0; diff --git a/lib/internal/http/client.js b/lib/internal/http/client.js index ecc872553113..4e7479d3377a 100644 --- a/lib/internal/http/client.js +++ b/lib/internal/http/client.js @@ -26,7 +26,6 @@ const { Boolean, Error, NumberIsFinite, - ObjectAssign, ObjectDefineProperty, ObjectHasOwn, ObjectKeys, @@ -72,6 +71,7 @@ const { getNextTraceEventId, kProxyConfig, checkShouldUseProxy, + setHttpParserOptions, } = require('internal/http'); const { ConnResetException, @@ -87,7 +87,6 @@ const { const { validateInteger, validateBoolean, - validateOneOf, validatePort, validateString, } = require('internal/validators'); @@ -365,7 +364,8 @@ function ClientRequest(input, options, cb) { pathIsFromURL = false; } - options = ObjectAssign({ __proto__: null }, input, options); + // Avoid creating a dictionary-mode object. + options = { __proto__: kEmptyObject, ...input, ...options }; } // Propagate the user's highWaterMark to OutgoingMessage so that @@ -413,7 +413,7 @@ function ClientRequest(input, options, cb) { const defaultPort = options.defaultPort || (this.agent?.defaultPort); - const optsWithoutSignal = { __proto__: null, ...options }; + const optsWithoutSignal = { __proto__: kEmptyObject, ...options }; const port = optsWithoutSignal.port = options.port || defaultPort || 80; const host = optsWithoutSignal.host = validateHost(options.hostname, 'hostname') || @@ -456,27 +456,7 @@ function ClientRequest(input, options, cb) { validateInteger(maxHeaderSize, 'maxHeaderSize', 0); this.maxHeaderSize = maxHeaderSize; - const insecureHTTPParser = options.insecureHTTPParser; - if (insecureHTTPParser !== undefined) { - validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); - } - - this.insecureHTTPParser = insecureHTTPParser; - - const httpValidation = options.httpValidation; - if (httpValidation !== undefined) { - validateOneOf(httpValidation, 'options.httpValidation', - ['strict', 'relaxed', 'insecure']); - if (insecureHTTPParser !== undefined) { - throw new ERR_INVALID_ARG_VALUE( - 'options.httpValidation', - httpValidation, - 'cannot be used together with options.insecureHTTPParser', - ); - } - } - - this.httpValidation = httpValidation; + setHttpParserOptions(this, options); if (options.joinDuplicateHeaders !== undefined) { validateBoolean(options.joinDuplicateHeaders, 'options.joinDuplicateHeaders'); diff --git a/lib/internal/http/outgoing.js b/lib/internal/http/outgoing.js index 92a325489f23..6dfdbb244417 100644 --- a/lib/internal/http/outgoing.js +++ b/lib/internal/http/outgoing.js @@ -835,7 +835,12 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) { if (headers === null) this[kOutHeaders] = headers = new OutgoingHeaders(); - headers[name.toLowerCase()] = [name, value]; + // Store a copy of an array value. appendHeader() pushes into the stored + // array, which must not be the caller's (it may also be frozen). + headers[name.toLowerCase()] = [ + name, + ArrayIsArray(value) ? value.slice() : value, + ]; return this; }; @@ -1076,6 +1081,23 @@ function strictContentLength(msg) { ); } +// Encodings for which `Buffer.byteLength()` is only an upper bound of the +// number of bytes `Buffer.from()` actually produces (e.g. base64 skips +// whitespace and stops at invalid characters, hex stops at the first +// invalid pair). +function decodeLossyEncodedChunk(chunk, encoding) { + if (typeof chunk === 'string' && typeof encoding === 'string') { + switch (encoding.toLowerCase()) { + case 'base64': + case 'base64url': + case 'hex': + return Buffer.from(chunk, encoding); + } + } + + return chunk; +} + function write_(msg, chunk, encoding, callback, fromEnd) { if (typeof callback !== 'function') callback = nop; @@ -1087,6 +1109,9 @@ function write_(msg, chunk, encoding, callback, fromEnd) { 'chunk', ['string', 'Buffer', 'Uint8Array'], chunk); } + // Compute lengths from the bytes that will actually be sent. + chunk = decodeLossyEncodedChunk(chunk, encoding); + let err; if (msg.finished) { err = new ERR_STREAM_WRITE_AFTER_END(); @@ -1318,6 +1343,8 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { this[kSocket].cork(); } + chunk = decodeLossyEncodedChunk(chunk, encoding); + if (maybePrepareFinalChunk(this, chunk, encoding)) { // If just one final write is required, with nothing to follow, we // attach finish to the write to avoid a separate send() & tick step diff --git a/lib/internal/http/server.js b/lib/internal/http/server.js index 9e13aeba63a6..fe870c471440 100644 --- a/lib/internal/http/server.js +++ b/lib/internal/http/server.js @@ -65,6 +65,7 @@ const { traceBegin, traceEnd, getNextTraceEventId, + setHttpParserOptions, } = require('internal/http'); const { defaultTriggerAsyncIdScope, @@ -99,7 +100,6 @@ const { const { validateInteger, validateBoolean, - validateOneOf, validateLinkHeaderValue, validateObject, validateFunction, @@ -538,24 +538,7 @@ function storeHTTPOptions(options) { validateBoolean(optimizeEmptyRequests, 'options.optimizeEmptyRequests'); this[kOptimizeEmptyRequests] = optimizeEmptyRequests || false; - const insecureHTTPParser = options.insecureHTTPParser; - if (insecureHTTPParser !== undefined) - validateBoolean(insecureHTTPParser, 'options.insecureHTTPParser'); - this.insecureHTTPParser = insecureHTTPParser; - - const httpValidation = options.httpValidation; - if (httpValidation !== undefined) { - validateOneOf(httpValidation, 'options.httpValidation', - ['strict', 'relaxed', 'insecure']); - if (insecureHTTPParser !== undefined) { - throw new ERR_INVALID_ARG_VALUE( - 'options.httpValidation', - httpValidation, - 'cannot be used together with options.insecureHTTPParser', - ); - } - } - this.httpValidation = httpValidation; + setHttpParserOptions(this, options); const requestTimeout = options.requestTimeout; if (requestTimeout !== undefined) { diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index 2eedfd39010a..113a2af560b1 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -39,6 +39,7 @@ const { ERR_HTTP2_NO_SOCKET_MANIPULATION, ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, ERR_HTTP2_STATUS_INVALID, + ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_INVALID_HTTP_TOKEN, ERR_STREAM_WRITE_AFTER_END, @@ -57,6 +58,7 @@ const { kSocket, kRequest, kProxySocket, + kIncomplete, assertValidPseudoHeader, getAuthority, } = require('internal/http2/util'); @@ -154,9 +156,12 @@ function onStreamTrailers(trailers, flags, rawTrailers) { } function onStreamEnd() { - // Cause the request stream to end as well. + // Cause the request stream to end as well. Skip when the body is + // incomplete (the peer never sent END_STREAM and the stream was torn down, + // e.g. reset, local close, or session teardown); destroying the readable on + // close emits 'end' spuriously, so it must not reach the compat request. const request = this[kRequest]; - if (request !== undefined) + if (request !== undefined && !this[kIncomplete]) this[kRequest].push(null); } @@ -291,15 +296,24 @@ function onStreamCloseRequest() { const state = req[kState]; state.closed = true; + this[kProxySocket] = null; + this[kRequest] = undefined; + + // The peer closed the stream before END_STREAM, so the request body is + // incomplete. Like http1's IncomingMessage on abort, destroy the request + // instead of ending it, so 'end' is not emitted for a truncated body. + // destroy() emits 'close'. + if (this[kIncomplete]) { + req.destroy(); + return; + } + req.push(null); // If the user didn't interact with incoming data and didn't pipe it, // dump it for compatibility with http1 if (!state.didRead && !req._readableState.resumeScheduled) req.resume(); - this[kProxySocket] = null; - this[kRequest] = undefined; - req.emit('close'); } @@ -674,6 +688,45 @@ class Http2ServerResponse extends Stream { this[kSetHeader](name, value); } + setHeaders(headers) { + if (this[kStream].headersSent) + throw new ERR_HTTP2_HEADERS_SENT(); + + if ( + !headers || + ArrayIsArray(headers) || + typeof headers.keys !== 'function' || + typeof headers.get !== 'function' + ) { + throw new ERR_INVALID_ARG_TYPE('headers', ['Headers', 'Map'], headers); + } + + // Headers object joins multiple cookies with a comma when using + // the getter to retrieve the value, + // unless iterating over the headers directly. + // We also cannot safely split by comma. + // To avoid setHeader overwriting the previous value we push + // set-cookie values in array and set them all at once. + let cookies = null; + + for (const { 0: key, 1: value } of headers) { + if (key === 'set-cookie') { + if (ArrayIsArray(value)) { + cookies ??= []; + cookies.push(...value); + } else { + cookies ??= []; + cookies.push(value); + } + continue; + } + this.setHeader(key, value); + } + if (cookies != null) { + this.setHeader('set-cookie', cookies); + } + } + [kSetHeader](name, value) { name = name.trim().toLowerCase(); assertValidHeader(name, value); @@ -687,7 +740,9 @@ class Http2ServerResponse extends Stream { else if (!checkIsHttpToken(name)) this.destroy(new ERR_INVALID_HTTP_TOKEN('Header name', name)); - this[kHeaders][name] = value; + // Store a copy of an array value. appendHeader() pushes into the stored + // array, which must not be the caller's (it may also be frozen). + this[kHeaders][name] = ArrayIsArray(value) ? value.slice() : value; } appendHeader(name, value) { @@ -957,7 +1012,7 @@ class Http2ServerResponse extends Stream { this[kStream].respond(headers, options); } - writeInformation(statusCode, headers) { + writeInformation(statusCode, headers, cb) { if (typeof statusCode !== 'number' || statusCode < 100 || statusCode > 199) { throw new ERR_HTTP2_STATUS_INVALID(statusCode); @@ -965,6 +1020,8 @@ class Http2ServerResponse extends Stream { if (statusCode === 101) { throw new ERR_HTTP2_STATUS_INVALID(statusCode); } + if (cb !== undefined) + validateFunction(cb, 'callback'); const stream = this[kStream]; @@ -981,16 +1038,15 @@ class Http2ServerResponse extends Stream { } outHeaders[HTTP2_HEADER_STATUS] = statusCode; - stream.additionalHeaders(outHeaders); + stream.additionalHeaders(outHeaders, cb); return true; } - // TODO doesn't support callbacks - writeContinue() { - return this.writeInformation(HTTP_STATUS_CONTINUE); + writeContinue(cb) { + return this.writeInformation(HTTP_STATUS_CONTINUE, undefined, cb); } - writeEarlyHints(hints) { + writeEarlyHints(hints, cb) { validateObject(hints, 'hints'); const headers = { __proto__: null }; @@ -1013,7 +1069,7 @@ class Http2ServerResponse extends Stream { headers.Link = linkHeaderValue; - return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers); + return this.writeInformation(HTTP_STATUS_EARLY_HINTS, headers, cb); } } diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index 04acb5d30f63..f24dbf2e2501 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -67,6 +67,7 @@ const { AsyncResource } = require('async_hooks'); const { AbortError, + ErrnoException, aggregateTwoErrors, codes: { ERR_HTTP2_ALTSVC_INVALID_ORIGIN, @@ -93,6 +94,7 @@ const { ERR_HTTP2_SEND_FILE, ERR_HTTP2_SEND_FILE_NOSEEK, ERR_HTTP2_SESSION_ERROR, + ERR_HTTP2_SESSION_MEMORY_EXCEEDED, ERR_HTTP2_SETTINGS_CANCEL, ERR_HTTP2_SOCKET_BOUND, ERR_HTTP2_SOCKET_UNBOUND, @@ -156,6 +158,7 @@ const { kStrictSingleValueFields, kSocket, kRequest, + kIncomplete, kProtocol, kProxySocket, MAX_ADDITIONAL_SETTINGS, @@ -188,6 +191,7 @@ const { FileHandle } = internalBinding('fs'); const binding = internalBinding('http2'); const { ShutdownWrap, + WriteWrap, kReadBytesOrError, streamBaseState, } = internalBinding('stream_wrap'); @@ -197,6 +201,7 @@ const { StreamPipe } = internalBinding('stream_pipe'); const { _connectionListener: httpConnectionListener } = http; const dc = require('diagnostics_channel'); +const onClientRequestHeadersChannel = dc.channel('http2.client.request.headers'); const onClientStreamCreatedChannel = dc.channel('http2.client.stream.created'); const onClientStreamStartChannel = dc.channel('http2.client.stream.start'); const onClientStreamErrorChannel = dc.channel('http2.client.stream.error'); @@ -348,6 +353,8 @@ const STREAM_FLAGS_HEADERS_SENT = 0x4; const STREAM_FLAGS_HEAD_REQUEST = 0x8; const STREAM_FLAGS_ABORTED = 0x10; const STREAM_FLAGS_HAS_TRAILERS = 0x20; +const STREAM_FLAGS_RST_DEFERRED = 0x40; +const STREAM_FLAGS_CLEAN_REQUEST_RESET = 0x80; const SESSION_FLAGS_PENDING = 0x0; const SESSION_FLAGS_READY = 0x1; @@ -605,7 +612,8 @@ function streamNaturalCloseSettled(stream) { return (stream._readableState.endEmitted || !!stream._readableState.errored) && (stream._writableState.finished || - !!stream._writableState.errored); + !!stream._writableState.errored || + !!(stream[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET)); } // Shared 'end'/'finish'/'error' listener for the natural-close path of @@ -626,7 +634,9 @@ function maybeDestroyNaturalClose() { // Clean code = NO_ERROR or CANCEL. // // Natural close defers destroy until 'end' and 'finish' - nghttp2 can -// fire on_stream_close ahead of our last frame leaving the socket. +// fire on_stream_close ahead of our last frame leaving the socket. On the +// client, a clean reset for a request after a response END_STREAM just defers +// until 'end', so the buffered response stays readable, with writes ignored. function onStreamClose(code, peerReset) { const stream = this[kOwner]; if (!stream || stream.destroyed) @@ -644,6 +654,8 @@ function onStreamClose(code, peerReset) { stream[kState].fd = -1; if (locallyInitiated) { + // nghttp2 has already closed the stream, a deferred RST_STREAM is moot. + stream[kState].flags &= ~STREAM_FLAGS_RST_DEFERRED; stream.destroy(); return true; } @@ -652,6 +664,10 @@ function onStreamClose(code, peerReset) { const cleanCode = code === NGHTTP2_NO_ERROR || code === NGHTTP2_CANCEL; if (!peerReadableEnded) { + // The peer closed the stream before END_STREAM, so the incoming message + // is incomplete. Bear in mind we must not 'end' the compat request. The + // decision is recorded in _destroy() via this._readableState.ended, which + // is the same signal as peerReadableEnded here. stream.destroy(cleanCode ? new ERR_HTTP2_STREAM_ABORTED() : new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)); @@ -660,7 +676,12 @@ function onStreamClose(code, peerReset) { // Peer END_STREAMed - reads will complete. Only the writable half can // still be in flight at the protocol layer. - if (peerReset) { + const keepResponse = cleanCode && + stream[kSession][kType] === NGHTTP2_SESSION_CLIENT; + if (peerReset && keepResponse) { + stream[kState].flags |= STREAM_FLAGS_CLEAN_REQUEST_RESET; + process.nextTick(settleWrite, stream); + } else if (peerReset) { if (!cleanCode && !stream._writableState.finished) { stream.destroy( new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code)); @@ -886,6 +907,13 @@ function requestOnConnect(headersList, options) { // For the first two, emit the error on the session, // For the third, emit the error on the stream, it will bubble up to the // session if not handled. + if (ret === false) { + // The session is over its `maxSessionMemory` budget. The request was never + // submitted to nghttp2, so nothing reached the peer; only this request is + // rejected and the session itself stays usable. + this.destroy(new ERR_HTTP2_SESSION_MEMORY_EXCEEDED()); + return; + } if (typeof ret === 'number') { let err; switch (ret) { @@ -1909,6 +1937,25 @@ class ClientHttp2Session extends Http2Session { this[kUpdateTimer](); + let headers = headersParam; + if (onClientRequestHeadersChannel.hasSubscribers && + (headers === undefined || + ArrayIsArray(headers) || + (!!headers && typeof headers === 'object'))) { + if (headers === undefined) { + headers = { __proto__: null }; + } else { + headers = ArrayIsArray(headers) ? + ArrayFrom(headers) : + ObjectAssign({ __proto__: null }, headers); + if (headersParam[kSensitiveHeaders] !== undefined) { + headers[kSensitiveHeaders] = + ArrayFrom(headersParam[kSensitiveHeaders]); + } + } + onClientRequestHeadersChannel.publish({ headers, session: this }); + } + let headersList; let headersObject; let rawHeaders; @@ -1916,23 +1963,23 @@ class ClientHttp2Session extends Http2Session { let authority; let method; - if (ArrayIsArray(headersParam)) { + if (ArrayIsArray(headers)) { ({ rawHeaders, headersList, scheme, authority, method, - } = prepareRequestHeadersArray(headersParam, this)); - } else if (!!headersParam && typeof headersParam === 'object') { + } = prepareRequestHeadersArray(headers, this)); + } else if (!!headers && typeof headers === 'object') { ({ headersObject, headersList, scheme, authority, method, - } = prepareRequestHeadersObject(headersParam, this)); - } else if (headersParam === undefined) { + } = prepareRequestHeadersObject(headers, this)); + } else if (headers === undefined) { ({ headersObject, headersList, @@ -2093,6 +2140,18 @@ function finishWrite(stream) { cb(err); } +// A write in flight may never get its native completion callback once the +// stream is closed; settle it so the Writable can make progress. +function settleWrite(stream, err) { + const state = stream[kState]; + if (state.writeCb !== null) { + const writeCb = state.writeCb; + state.writeCb = null; + state.writePending = 0; + writeCb(err); + } +} + // Runs on the tick after a write was dispatched: if the write turned out to // be the last chunk of an ending writable, shut the writable side down right // away so the final DATA frame can include the END_STREAM flag. @@ -2166,6 +2225,9 @@ function closeStream(stream, code, rstStreamStatus = kSubmitRstStream) { rstStreamStatus === kForceRstStream) { finishCloseStream.call(stream, code); } else { + // Remember that the RST_STREAM is still owed, so that destroying the + // stream before 'finish' can submit it. See Http2Stream#_destroy(). + state.flags |= STREAM_FLAGS_RST_DEFERRED; stream.once('finish', finishCloseStream.bind(stream, code)); } } @@ -2188,6 +2250,7 @@ function closeStream(stream, code, rstStreamStatus = kSubmitRstStream) { } function finishCloseStream(code) { + this[kState].flags &= ~STREAM_FLAGS_RST_DEFERRED; const rstStreamFn = submitRstStream.bind(this, code); // Defer until the stream has an ID assigned. if (this.pending) { @@ -2465,6 +2528,10 @@ class Http2Stream extends Duplex { if (this.destroyed) return; + // The server no longer wants the rest of the request; discard it quietly. + if (this[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET) + return cb(); + this[kUpdateTimer](); if (!this.headersSent) this[kProceed](); @@ -2552,6 +2619,8 @@ class Http2Stream extends Duplex { this.once('ready', () => this._final(cb)); return; } + if (this[kState].flags & STREAM_FLAGS_CLEAN_REQUEST_RESET) + return cb(); debugStreamObj(this, 'shutting down writable on _final'); shutdownWritable.call(this, cb); @@ -2681,8 +2750,24 @@ class Http2Stream extends Duplex { } const hasHandle = handle !== undefined; - if (!this.closed) + if (!this.closed) { closeStream(this, code, hasHandle ? kForceRstStream : kNoRstStream); + } else if (state.flags & STREAM_FLAGS_RST_DEFERRED) { + // close() deferred the RST_STREAM until 'finish', which will never be + // emitted now. Submit it here, otherwise nghttp2 keeps the stream open + // with a data provider that no longer has a stream to read from. + state.flags &= ~STREAM_FLAGS_RST_DEFERRED; + if (hasHandle) + handle.rstStream(code); + } + + // If the peer never sent END_STREAM, the readable side was torn down + // before reaching EOF, so the incoming message is incomplete. _destroy() + // always ends the readable below, so record it here for the compat layer + // (onStreamCloseRequest). Doing it in one place covers remote reset, + // local close, and unexpected session teardown alike. + if (!this._readableState.ended) + this[kIncomplete] = true; this.push(null); @@ -2735,14 +2820,7 @@ class Http2Stream extends Duplex { } } - // A write in flight may never get its native completion callback once the - // stream tears down; settle it so the Writable can clean up. - if (state.writeCb !== null) { - const writeCb = state.writeCb; - state.writeCb = null; - state.writePending = 0; - writeCb(err); - } + settleWrite(this, err); callback(err); } // The Http2Stream can be destroyed if it has closed and if the readable @@ -3445,14 +3523,17 @@ class ServerHttp2Stream extends Http2Stream { // such that HEADERS may only be sent *before* or *after* DATA frames. // If the block of headers being sent includes a status code, it MUST be // a 1xx informational code and it MUST be sent before the request/response - // headers are sent, or an error will be thrown. - additionalHeaders(headers) { + // headers are sent, or an error will be thrown. The optional callback is + // called once the HEADERS frame has been written to the socket. + additionalHeaders(headers, callback) { if (this.destroyed || this.closed) throw new ERR_HTTP2_INVALID_STREAM(); if (this.headersSent) throw new ERR_HTTP2_HEADERS_AFTER_RESPOND(); assertIsObject(headers, 'headers'); + if (callback !== undefined) + validateFunction(callback, 'callback'); headers = ObjectAssign({ __proto__: null }, headers); debugStreamObj(this, 'sending additional headers'); @@ -3478,12 +3559,32 @@ class ServerHttp2Stream extends Http2Stream { else this[kInfoHeaders].push(headers); - const ret = this[kHandle].info(headersList); - if (ret < 0) - this.destroy(new NghttpError(ret)); + let req; + if (callback !== undefined) { + req = new WriteWrap(); + req.oncomplete = onInfoHeadersComplete; + req.callback = callback; + } + + const ret = this[kHandle].info(headersList, req); + if (ret < 0) { + const err = new NghttpError(ret); + this.destroy(err); + if (callback !== undefined) + process.nextTick(callback, err); + } } } +// Called once an informational HEADERS frame has been written to the socket, +// or once it is known that it will not be. +function onInfoHeadersComplete(status) { + if (status < 0) + this.callback(new ErrnoException(status, 'write', this.error)); + else + this.callback(null); +} + ServerHttp2Stream.prototype[kProceed] = ServerHttp2Stream.prototype.respond; class ClientHttp2Stream extends Http2Stream { diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index f0f80aa175ef..4d5db68ac234 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -46,6 +46,7 @@ const kSocket = Symbol('socket'); const kProtocol = Symbol('protocol'); const kProxySocket = Symbol('proxySocket'); const kRequest = Symbol('request'); +const kIncomplete = Symbol('incomplete'); const { NGHTTP2_NV_FLAG_NONE, @@ -1003,6 +1004,7 @@ module.exports = { kStrictSingleValueFields, kSocket, kProtocol, + kIncomplete, kProxySocket, kRequest, MAX_ADDITIONAL_SETTINGS, diff --git a/lib/internal/main/eval_string.js b/lib/internal/main/eval_string.js index 998c3fb4ada5..4cacb63ee9dd 100644 --- a/lib/internal/main/eval_string.js +++ b/lib/internal/main/eval_string.js @@ -30,7 +30,7 @@ markBootstrapComplete(); const code = getOptionValue('--eval'); const print = getOptionValue('--print'); -const shouldLoadESM = getOptionValue('--import').length > 0 || getOptionValue('--experimental-loader').length > 0; +const shouldLoadESM = getOptionValue('--import').length > 0; const inputType = getOptionValue('--input-type'); const tsEnabled = getOptionValue('--strip-types'); if (inputType === 'module') { @@ -70,7 +70,7 @@ if (inputType === 'module') { evalFunction('[eval]', shouldDefineCrypto ? ( - print ? `let crypto=require("node:crypto");{${code}}` : `(crypto=>{{${code}}})(require('node:crypto'))` + print ? `let crypto=require("node:crypto");{${code}\n}` : `(crypto=>{{${code}\n}})(require('node:crypto'))` ) : code, getOptionValue('--inspect-brk'), print, diff --git a/lib/internal/main/worker_thread.js b/lib/internal/main/worker_thread.js index ed12eb946789..9895b86dbb4d 100644 --- a/lib/internal/main/worker_thread.js +++ b/lib/internal/main/worker_thread.js @@ -106,16 +106,14 @@ port.on('message', (message) => { mainThreadPort, } = message; - if (doEval !== 'internal') { - if (argv !== undefined) { - ArrayPrototypePushApply(process.argv, argv); - } - - const publicWorker = require('worker_threads'); - publicWorker.parentPort = publicPort; - publicWorker.workerData = workerData; + if (argv !== undefined) { + ArrayPrototypePushApply(process.argv, argv); } + const publicWorker = require('worker_threads'); + publicWorker.parentPort = publicPort; + publicWorker.workerData = workerData; + require('internal/worker').assignEnvironmentData(environmentData); setupMainThreadPort(mainThreadPort); @@ -141,24 +139,18 @@ port.on('message', (message) => { }; workerIo.sharedCwdCounter = cwdCounter; - const isLoaderHookWorker = (filename === 'internal/modules/esm/worker' && doEval === 'internal'); - if (!isLoaderHookWorker) { - // If we are in the loader hook worker, delay the module loader initializations until - // initializeAsyncLoaderHooksOnLoaderHookWorker() which needs to run preloads - // after the asynchronous loader hooks are registered. - initializeModuleLoaders({ shouldSpawnLoaderHookWorker: true, shouldPreloadModules: true }); - // Re-mount the inherited --vfs-load source so its reserved path (which a - // worker filename may point into) resolves in this thread too. With - // --import, mounting is deferred to after that loop in run_main, matching - // the main thread; finishVfsMounts() is idempotent so it runs once. - if (getOptionValue('--import').length === 0) { - finishVfsMounts(); - } - // Unlike the --vfs-load source, the SEA VFS needs no provider that a - // preload could register, so its mount is never deferred. - if (getOptionValue('[sea_vfs]')) { - require('internal/vfs/sea').initSeaVfsInWorker(); - } + initializeModuleLoaders({ shouldPreloadModules: true }); + // Re-mount the inherited --vfs-load source so its reserved path (which a + // worker filename may point into) resolves in this thread too. With + // --import, mounting is deferred to after that loop in run_main, matching + // the main thread; finishVfsMounts() is idempotent so it runs once. + if (getOptionValue('--import').length === 0) { + finishVfsMounts(); + } + // Unlike the --vfs-load source, the SEA VFS needs no provider that a + // preload could register, so its mount is never deferred. + if (getOptionValue('[sea_vfs]')) { + require('internal/vfs/sea').initSeaVfsInWorker(); } if (!hasStdin) @@ -168,14 +160,6 @@ port.on('message', (message) => { `(eval = ${doEval}) at cwd = ${process.cwd()}`); port.postMessage({ type: UP_AND_RUNNING }); switch (doEval) { - case 'internal': { - // Currently the only user of internal eval is the async loader hook thread. - assert(isLoaderHookWorker, `Unexpected internal eval ${filename}`); - const setupModuleWorker = require('internal/modules/esm/worker'); - setupModuleWorker(workerData, publicPort); - break; - } - case 'classic': if (webWorkerData?.source !== undefined) { // The source of a web Worker script loaded from a blob: or data: // URL. diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index f9c4a62f023a..f7c08348f3dc 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -1131,6 +1131,27 @@ function getExportsForCircularRequire(module) { return module.exports; } +/** + * Result of resolving a module request for CommonJS loading. One is created on + * every require() that misses the relative resolve cache, e.g. every require() + * of a builtin. A `{ __proto__: null }` literal would be created in dictionary + * mode, so use a class with a null-prototype prototype to keep a fast map. + */ +class CJSResolveResult { + /** + * @param {string|undefined} url + * @param {string|undefined} format + * @param {string} filename + * @param {string|undefined} parentURL + */ + constructor(url, format, filename, parentURL) { + this.url = url; + this.format = format; + this.filename = filename; + this.parentURL = parentURL; + } +} +ObjectSetPrototypeOf(CJSResolveResult.prototype, null); /** * Wraps result of Module._resolveFilename to include additional fields for hooks. @@ -1139,11 +1160,11 @@ function getExportsForCircularRequire(module) { * @param {Module|undefined} parent * @param {boolean} isMain * @param {ResolveFilenameOptions} options - * @returns {{url?: string, format?: string, parentURL?: string, filename: string}} + * @returns {CJSResolveResult} */ function wrapResolveFilename(specifier, parent, isMain, options) { const filename = Module._resolveFilename(specifier, parent, isMain, options).toString(); - return { __proto__: null, url: undefined, format: undefined, filename }; + return new CJSResolveResult(undefined, undefined, filename, undefined); } /** @@ -1164,7 +1185,7 @@ function defaultResolveImplForCJSLoading(specifier, parent, isMain, options) { if (!normalized) { throw new ERR_UNKNOWN_BUILTIN_MODULE(specifier); } - return { __proto__: null, url: specifier, format: 'builtin', filename: normalized }; + return new CJSResolveResult(specifier, 'builtin', normalized, undefined); } return wrapResolveFilename(specifier, parent, isMain, options); } @@ -1241,7 +1262,7 @@ function resolveForCJSWithHooks(specifier, parent, isMain, internalOptions) { const { url, format } = resolveResult; // Convert the URL from the hook chain back to a filename for internal use. const filename = convertURLToCJSFilename(url); - const result = { __proto__: null, url, format, filename, parentURL }; + const result = new CJSResolveResult(url, format, filename, parentURL); debug('resolveForCJSWithHooks', specifier, parent?.id, isMain, shouldSkipModuleHooks, '->', result); return result; } diff --git a/lib/internal/modules/customization_hooks.js b/lib/internal/modules/customization_hooks.js index c3d1970243fd..5ce0ab4418a0 100644 --- a/lib/internal/modules/customization_hooks.js +++ b/lib/internal/modules/customization_hooks.js @@ -282,7 +282,7 @@ function validateLoadSloppy(url, context, result) { function validateSourceStrict(url, context, result) { const { source, format } = result; - // To align with module.register(), the load hooks are still invoked for + // To align with the legacy module.register(), the load hooks are still invoked for // the builtins even though the default load step only provides null as source, // and any source content for builtins provided by the user hooks are ignored. if (!StringPrototypeStartsWith(url, 'node:') && @@ -302,7 +302,7 @@ function validateSourceStrict(url, context, result) { function validateSourcePermissive(url, context, result) { const { source, format } = result; if (format === 'commonjs' && source == null) { - // Accommodate the quirk in defaultLoad used by asynchronous loader hooks + // To retain the legacy behavior from the quirk in defaultLoad used by asynchronous loader hooks // which sets source to null for commonjs. // See: https://github.com/nodejs/node/issues/57327#issuecomment-2701382020 return; diff --git a/lib/internal/modules/esm/hooks.js b/lib/internal/modules/esm/hooks.js deleted file mode 100644 index 220dcd33754e..000000000000 --- a/lib/internal/modules/esm/hooks.js +++ /dev/null @@ -1,870 +0,0 @@ -'use strict'; - -const { - ArrayPrototypePush, - ArrayPrototypePushApply, - AtomicsLoad, - AtomicsWait, - AtomicsWaitAsync, - Int32Array, - ObjectAssign, - ObjectDefineProperty, - ObjectSetPrototypeOf, - Promise, - ReflectSet, - SafeSet, - StringPrototypeSlice, - StringPrototypeToUpperCase, -} = primordials; - -const { - ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED, - ERR_INTERNAL_ASSERTION, - ERR_INVALID_ARG_TYPE, - ERR_INVALID_ARG_VALUE, - ERR_INVALID_RETURN_PROPERTY_VALUE, - ERR_INVALID_RETURN_VALUE, - ERR_LOADER_CHAIN_INCOMPLETE, - ERR_WORKER_UNSERIALIZABLE_ERROR, -} = require('internal/errors').codes; -const { URLParse } = require('internal/url'); -const { canParse: URLCanParse } = internalBinding('url'); -const { receiveMessageOnPort } = require('worker_threads'); -const { - isAnyArrayBuffer, - isArrayBufferView, -} = require('internal/util/types'); -const { - validateObject, - validateString, -} = require('internal/validators'); -const { - constructSharedArrayBuffer, - kEmptyObject, -} = require('internal/util'); - -const { - defaultResolve, - throwIfInvalidParentURL, -} = require('internal/modules/esm/resolve'); -const { - getDefaultConditions, -} = require('internal/modules/esm/utils'); -const { hasWorkerCondition } = require('internal/modules/helpers'); -const { deserializeError } = require('internal/error_serdes'); -const { - SHARED_MEMORY_BYTE_LENGTH, - WORKER_TO_MAIN_THREAD_NOTIFICATION, -} = require('internal/modules/esm/shared_constants'); -let debug = require('internal/util/debuglog').debuglog('async_loader_worker', (fn) => { - debug = fn; -}); - -let importAssertionAlreadyWarned = false; - -function emitImportAssertionWarning() { - if (!importAssertionAlreadyWarned) { - importAssertionAlreadyWarned = true; - process.emitWarning('Use `importAttributes` instead of `importAssertions`', 'ExperimentalWarning'); - } -} - -function defineImportAssertionAlias(context) { - return ObjectDefineProperty(context, 'importAssertions', { - __proto__: null, - configurable: true, - get() { - emitImportAssertionWarning(); - return this.importAttributes; - }, - set(value) { - emitImportAssertionWarning(); - return ReflectSet(this, 'importAttributes', value); - }, - }); -} - -/** - * @typedef {object} ExportedHooks - * @property {Function} resolve Resolve hook. - * @property {Function} load Load hook. - */ - -/** - * @typedef {object} KeyedHook - * @property {Function} fn The hook function. - * @property {URL['href']} url The URL of the module. - * @property {KeyedHook?} next The next hook in the chain. - */ - -// [2] `validate...()`s throw the wrong error - -/** - * @typedef {{ format: ModuleFormat, source: ModuleSource }} LoadResult - */ - -/** - * @typedef {{ format: ModuleFormat, url: string, importAttributes: Record<string, string> }} ResolveResult - */ - -/** - * Interface for classes that implement asynchronous loader hooks that can be attached to the ModuleLoader - * via `ModuleLoader.#setAsyncLoaderHooks()`. - * @typedef {object} AsyncLoaderHooks - * @property {boolean} isForAsyncLoaderHookWorker Whether the instance is running on the loader hook worker thread. - * @property {(url: string, context: object, defaultLoad: Function) => Promise<LoadResult>} load - * Calling the asynchronous `load` hook asynchronously. - * @property {(url: string, context: object, defaultLoad: Function) => LoadResult} [loadSync] - * Calling the asynchronous `load` hook synchronously. - * @property {(originalSpecifier: string, parentURL: string, - * importAttributes: Record<string, string>) => Promise<ResolveResult>} resolve - * Calling the asynchronous `resolve` hook asynchronously. - * @property {(originalSpecifier: string, parentURL: string, - * importAttributes: Record<string, string>) => ResolveResult} [resolveSync] - * Calling the asynchronous `resolve` hook synchronously. - * @property {(specifier: string, parentURL: string) => any} register Register asynchronous loader hooks - * @property {() => void} waitForLoaderHookInitialization Force loading of hooks. - */ - -/** - * @implements {AsyncLoaderHooks} - * Instances of this class run directly on the loader hook worker thread and customize the module - * loading of the hooks worker itself. - */ -class AsyncLoaderHooksOnLoaderHookWorker { - #chains = { - /** - * Phase 1 of 2 in ESM loading. - * The output of the `resolve` chain of hooks is passed into the `load` chain of hooks. - * @private - * @property {KeyedHook[]} resolve Last-in-first-out collection of resolve hooks. - */ - resolve: [ - { - fn: defaultResolve, - url: 'node:internal/modules/esm/resolve', - }, - ], - - /** - * Phase 2 of 2 in ESM loading. - * @private - * @property {KeyedHook[]} load Last-in-first-out collection of loader hooks. - */ - load: [ - { - fn: require('internal/modules/esm/load').defaultLoad, - url: 'node:internal/modules/esm/load', - }, - ], - }; - - // Cache URLs we've already validated to avoid repeated validation - #validatedUrls = new SafeSet(); - - isForAsyncLoaderHookWorker = true; - - /** - * Import and register custom/user-defined module loader hook(s). - * @param {string} urlOrSpecifier - * @param {string} parentURL - * @param {any} [data] Arbitrary data to be passed from the custom - * loader (user-land) to the worker. - */ - async register(urlOrSpecifier, parentURL, data, isInternal) { - const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); - const keyedExports = isInternal ? - require(urlOrSpecifier) : - await cascadedLoader.import( - urlOrSpecifier, - parentURL, - kEmptyObject, - ); - await this.addCustomLoader(urlOrSpecifier, keyedExports, data); - } - - /** - * Collect custom/user-defined module loader hook(s). - * @param {string} url Custom loader specifier - * @param {Record<string, unknown>} exports - * @param {any} [data] Arbitrary data to be passed from the custom loader (user-land) - * to the worker. - * @returns {any | Promise<any>} User data, ignored unless it's a promise, in which case it will be awaited. - */ - addCustomLoader(url, exports, data) { - const { - initialize, - resolve, - load, - } = pluckHooks(exports); - - if (resolve) { - const next = this.#chains.resolve[this.#chains.resolve.length - 1]; - ArrayPrototypePush(this.#chains.resolve, { __proto__: null, fn: resolve, url, next }); - } - if (load) { - const next = this.#chains.load[this.#chains.load.length - 1]; - ArrayPrototypePush(this.#chains.load, { __proto__: null, fn: load, url, next }); - } - return initialize?.(data); - } - - /** - * Resolve the location of the module. - * - * Internally, this behaves like a backwards iterator, wherein the stack of - * hooks starts at the top and each call to `nextResolve()` moves down 1 step - * until it reaches the bottom or short-circuits. - * @param {string} originalSpecifier The specified URL path of the module to - * be resolved. - * @param {string} [parentURL] The URL path of the module's parent. - * @param {ImportAttributes} [importAttributes] Attributes from the import - * statement or expression. - * @returns {Promise<{ format: string, url: URL['href'] }>} - */ - async resolve( - originalSpecifier, - parentURL, - importAttributes = { __proto__: null }, - ) { - throwIfInvalidParentURL(parentURL); - - const chain = this.#chains.resolve; - const context = { - conditions: getDefaultConditions(), - importAttributes, - parentURL, - }; - const meta = { - chainFinished: null, - context, - hookErrIdentifier: '', - hookName: 'resolve', - shortCircuited: false, - }; - - const validateArgs = (hookErrIdentifier, suppliedSpecifier, ctx) => { - validateString( - suppliedSpecifier, - `${hookErrIdentifier} specifier`, - ); // non-strings can be coerced to a URL string - - if (ctx) { validateObject(ctx, `${hookErrIdentifier} context`); } - }; - const validateOutput = (hookErrIdentifier, output) => { - if (typeof output !== 'object' || output === null) { // [2] - throw new ERR_INVALID_RETURN_VALUE( - 'an object', - hookErrIdentifier, - output, - ); - } - }; - - const nextResolve = nextHookFactory(chain[chain.length - 1], meta, { validateArgs, validateOutput }); - - const resolution = await nextResolve(originalSpecifier, defineImportAssertionAlias(context)); - const { hookErrIdentifier } = meta; // Retrieve the value after all settled - - validateOutput(hookErrIdentifier, resolution); - - if (resolution?.shortCircuit === true) { meta.shortCircuited = true; } - - if (!meta.chainFinished && !meta.shortCircuited) { - throw new ERR_LOADER_CHAIN_INCOMPLETE(hookErrIdentifier); - } - - let resolvedImportAttributes; - const { - format, - url, - } = resolution; - - if (typeof url !== 'string') { - // non-strings can be coerced to a URL string - // validateString() throws a less-specific error - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a URL string', - hookErrIdentifier, - 'url', - url, - ); - } - - // Avoid expensive URL instantiation for known-good URLs - if (!this.#validatedUrls.has(url)) { - // No need to convert to string, since the type is already validated - if (!URLCanParse(url)) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a URL string', - hookErrIdentifier, - 'url', - url, - ); - } - - this.#validatedUrls.add(url); - } - - if (!('importAttributes' in resolution) && ('importAssertions' in resolution)) { - emitImportAssertionWarning(); - resolvedImportAttributes = resolution.importAssertions; - } else { - resolvedImportAttributes = resolution.importAttributes; - } - - if ( - resolvedImportAttributes != null && - typeof resolvedImportAttributes !== 'object' - ) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'an object', - hookErrIdentifier, - 'importAttributes', - resolvedImportAttributes, - ); - } - - if ( - format != null && - typeof format !== 'string' // [2] - ) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a string', - hookErrIdentifier, - 'format', - format, - ); - } - - return { - __proto__: null, - format, - importAttributes: resolvedImportAttributes, - url, - }; - } - - /** - * Provide source that is understood by one of Node's translators. - * - * Internally, this behaves like a backwards iterator, wherein the stack of - * hooks starts at the top and each call to `nextLoad()` moves down 1 step - * until it reaches the bottom or short-circuits. - * @param {URL['href']} url The URL/path of the module to be loaded - * @param {object} context Metadata about the module - * @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>} - */ - async load(url, context = kEmptyObject) { - const chain = this.#chains.load; - const meta = { - chainFinished: null, - context, - hookErrIdentifier: '', - hookName: 'load', - shortCircuited: false, - }; - - const validateArgs = (hookErrIdentifier, nextUrl, ctx) => { - if (typeof nextUrl !== 'string') { - // Non-strings can be coerced to a URL string - // validateString() throws a less-specific error - throw new ERR_INVALID_ARG_TYPE( - `${hookErrIdentifier} url`, - 'a URL string', - nextUrl, - ); - } - - // Avoid expensive URL instantiation for known-good URLs - if (!this.#validatedUrls.has(nextUrl)) { - // No need to convert to string, since the type is already validated - if (!URLCanParse(nextUrl)) { - throw new ERR_INVALID_ARG_VALUE( - `${hookErrIdentifier} url`, - nextUrl, - 'should be a URL string', - ); - } - - this.#validatedUrls.add(nextUrl); - } - - if (ctx) { validateObject(ctx, `${hookErrIdentifier} context`); } - }; - const validateOutput = (hookErrIdentifier, output) => { - if (typeof output !== 'object' || output === null) { // [2] - throw new ERR_INVALID_RETURN_VALUE( - 'an object', - hookErrIdentifier, - output, - ); - } - }; - - const nextLoad = nextHookFactory(chain[chain.length - 1], meta, { validateArgs, validateOutput }); - - const loaded = await nextLoad(url, defineImportAssertionAlias(context)); - const { hookErrIdentifier } = meta; // Retrieve the value after all settled - - validateOutput(hookErrIdentifier, loaded); - - if (loaded?.shortCircuit === true) { meta.shortCircuited = true; } - - if (!meta.chainFinished && !meta.shortCircuited) { - throw new ERR_LOADER_CHAIN_INCOMPLETE(hookErrIdentifier); - } - - const { - format, - source, - } = loaded; - let responseURL = loaded.responseURL; - - if (responseURL === undefined) { - responseURL = url; - } - - let responseURLObj; - if (typeof responseURL === 'string') { - responseURLObj = URLParse(responseURL); - } - - if (responseURLObj?.href !== responseURL) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'undefined or a fully resolved URL string', - hookErrIdentifier, - 'responseURL', - responseURL, - ); - } - - if (format == null) { - require('internal/modules/esm/load').throwUnknownModuleFormat(url, format); - } - - if (typeof format !== 'string') { // [2] - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a string', - hookErrIdentifier, - 'format', - format, - ); - } - - if ( - source != null && - typeof source !== 'string' && - !isAnyArrayBuffer(source) && - !isArrayBufferView(source) - ) { - throw new ERR_INVALID_RETURN_PROPERTY_VALUE( - 'a string, an ArrayBuffer, or a TypedArray', - hookErrIdentifier, - 'source', - source, - ); - } - - return { - __proto__: null, - format, - responseURL, - source, - }; - } - - waitForLoaderHookInitialization() { - // No-op - } -} -ObjectSetPrototypeOf(AsyncLoaderHooksOnLoaderHookWorker.prototype, null); - -/** - * There is only one loader hook thread for each non-loader-hook worker thread - * (i.e. the non-loader-hook thread and any worker threads that are not loader hook workers themselves), - * so there is only 1 MessageChannel. - */ -let MessageChannel; - -/** - * Abstraction over a worker thread that runs the asynchronous module loader hooks. - * Instances of this class run on the non-loader-hook thread and communicate with the loader hooks worker thread. - */ -class AsyncLoaderHookWorker { - /** - * Shared memory. Always use Atomics method to read or write to it. - * @type {Int32Array} - */ - #lock; - /** - * The InternalWorker instance, which lets us communicate with the loader thread. - */ - #worker; - - /** - * The last notification ID received from the worker. This is used to detect - * if the worker has already sent a notification before putting the main - * thread to sleep, to avoid a race condition. - * @type {number} - */ - #workerNotificationLastId = 0; - - /** - * Track how many async responses the main thread should expect. - * @type {number} - */ - #numberOfPendingAsyncResponses = 0; - - #isReady = false; - - constructor() { - const { InternalWorker } = require('internal/worker'); - MessageChannel ??= require('internal/worker/io').MessageChannel; - - const lock = constructSharedArrayBuffer(SHARED_MEMORY_BYTE_LENGTH); - this.#lock = new Int32Array(lock); - - this.#worker = new InternalWorker('internal/modules/esm/worker', { - stderr: false, - stdin: false, - stdout: false, - trackUnmanagedFds: false, - workerData: { - lock, - workerCondition: hasWorkerCondition(), - }, - }); - this.#worker.unref(); // ! Allows the process to eventually exit. - this.#worker.on('exit', process.exit); - } - - waitForWorker() { - if (!this.#isReady) { - const { kIsOnline } = require('internal/worker'); - if (!this.#worker[kIsOnline]) { - debug('wait for signal from worker'); - AtomicsWait(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 0); - const response = this.#worker.receiveMessageSync(); - if (response == null) { return; } - if (response.message.status === 'exit') { - process.exit(response.message.body); - } - - // ! This line catches initialization errors in the worker thread. - this.#unwrapMessage(response); - } - - this.#isReady = true; - } - } - - /** - * Invoke a remote method asynchronously. - * @param {string} method Method to invoke - * @param {any[]} [transferList] Objects in `args` to be transferred - * @param {any[]} args Arguments to pass to `method` - * @returns {Promise<any>} - */ - async makeAsyncRequest(method, transferList, ...args) { - this.waitForWorker(); - - MessageChannel ??= require('internal/worker/io').MessageChannel; - const asyncCommChannel = new MessageChannel(); - - // Pass work to the worker. - debug('post async message to worker', { method, args, transferList }); - const finalTransferList = [asyncCommChannel.port2]; - if (transferList) { - ArrayPrototypePushApply(finalTransferList, transferList); - } - this.#worker.postMessage({ - __proto__: null, - method, args, - port: asyncCommChannel.port2, - }, finalTransferList); - - if (this.#numberOfPendingAsyncResponses++ === 0) { - // On the next lines, the main thread will await a response from the worker thread that might - // come AFTER the last task in the event loop has run its course and there would be nothing - // left keeping the thread alive (and once the main thread dies, the whole process stops). - // However we want to keep the process alive until the worker thread responds (or until the - // event loop of the worker thread is also empty), so we ref the worker until we get all the - // responses back. - this.#worker.ref(); - } - - let response; - do { - debug('wait for async response from worker', { method, args }); - await AtomicsWaitAsync(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, this.#workerNotificationLastId).value; - this.#workerNotificationLastId = AtomicsLoad(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - response = receiveMessageOnPort(asyncCommChannel.port1); - } while (response == null); - debug('got async response from worker', { method, args }, this.#lock); - - if (--this.#numberOfPendingAsyncResponses === 0) { - // We got all the responses from the worker, its job is done (until next time). - this.#worker.unref(); - } - - const body = this.#unwrapMessage(response); - asyncCommChannel.port1.close(); - return body; - } - - /** - * Invoke a remote method synchronously. - * @param {string} method Method to invoke - * @param {any[]} [transferList] Objects in `args` to be transferred - * @param {any[]} args Arguments to pass to `method` - * @returns {any} - */ - makeSyncRequest(method, transferList, ...args) { - this.waitForWorker(); - - // Pass work to the worker. - debug('post sync message to worker', { method, args, transferList }); - this.#worker.postMessage({ __proto__: null, method, args }, transferList); - - let response; - do { - debug('wait for sync response from worker', { method, args }); - // Sleep until worker responds. - AtomicsWait(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, this.#workerNotificationLastId); - this.#workerNotificationLastId = AtomicsLoad(this.#lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - response = this.#worker.receiveMessageSync(); - debug('got sync message from worker', { method, args, response }); - } while (response == null); - - if (response.message.status === 'never-settle') { - const error = new ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED(); - error.details = { method, args }; - throw error; - } else if (response.message.status === 'exit') { - process.exit(response.message.body); - } - return this.#unwrapMessage(response); - } - - #unwrapMessage(response) { - if (response.message.status === 'never-settle') { - return new Promise(() => {}); - } - const { status, body } = response.message; - if (status === 'error') { - if (body == null || typeof body !== 'object') { throw body; } - if (body.serializationFailed || body.serialized == null) { - throw new ERR_WORKER_UNSERIALIZABLE_ERROR(); - } - - // eslint-disable-next-line no-restricted-syntax - throw deserializeError(body.serialized); - } else { - return body; - } - } -} -ObjectSetPrototypeOf(AsyncLoaderHookWorker.prototype, null); - -// TODO(JakobJingleheimer): Remove this when loaders go "stable". -let globalPreloadWarningWasEmitted = false; - -/** - * A utility function to pluck the hooks from a user-defined loader. - * @param {import('./loader.js').ModuleExports} exports - * @returns {ExportedHooks} - */ -function pluckHooks({ - globalPreload, - initialize, - resolve, - load, -}) { - const acceptedHooks = { __proto__: null }; - - if (resolve) { - acceptedHooks.resolve = resolve; - } - if (load) { - acceptedHooks.load = load; - } - - if (initialize) { - acceptedHooks.initialize = initialize; - } else if (globalPreload && !globalPreloadWarningWasEmitted) { - process.emitWarning( - '`globalPreload` has been removed; use `initialize` instead.', - 'UnsupportedWarning', - ); - globalPreloadWarningWasEmitted = true; - } - - return acceptedHooks; -} - - -/** - * A utility function to iterate through a hook chain, track advancement in the - * chain, and generate and supply the `next<HookName>` argument to the custom - * hook. - * @param {KeyedHook} current The (currently) first hook in the chain (this shifts - * on every call). - * @param {object} meta Properties that change as the current hook advances - * along the chain. - * @param {boolean} meta.chainFinished Whether the end of the chain has been - * reached AND invoked. - * @param {string} meta.hookErrIdentifier A user-facing identifier to help - * pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'". - * @param {string} meta.hookName The kind of hook the chain is (ex 'resolve') - * @param {boolean} meta.shortCircuited Whether a hook signaled a short-circuit. - * @param {function(string, unknown): void} validate A wrapper function - * containing all validation of a custom loader hook's intermediary output. Any - * validation within MUST throw. - * @returns {Function} The next hook in the chain. - */ -function nextHookFactory(current, meta, { validateArgs, validateOutput }) { - // First, prepare the current - const { hookName } = meta; - const { - fn: hook, - url: hookFilePath, - next, - } = current; - - // ex 'nextResolve' - const nextHookName = `next${ - StringPrototypeToUpperCase(hookName[0]) + - StringPrototypeSlice(hookName, 1) - }`; - - let nextNextHook; - if (next) { - nextNextHook = nextHookFactory(next, meta, { validateArgs, validateOutput }); - } else { - // eslint-disable-next-line node-core/func-name-matching - nextNextHook = function chainAdvancedTooFar() { - throw new ERR_INTERNAL_ASSERTION( - `ESM custom loader '${hookName}' advanced beyond the end of the chain.`, - ); - }; - } - - return ObjectDefineProperty( - async (arg0 = undefined, context) => { - // Update only when hook is invoked to avoid fingering the wrong filePath - meta.hookErrIdentifier = `${hookFilePath} '${hookName}'`; - - validateArgs(`${meta.hookErrIdentifier} hook's ${nextHookName}()`, arg0, context); - - const outputErrIdentifier = `${hookFilePath} '${hookName}' hook's ${nextHookName}()`; - - // Set when next<HookName> is actually called, not just generated. - if (!next) { meta.chainFinished = true; } - - if (context) { // `context` has already been validated, so no fancy check needed. - ObjectAssign(meta.context, context); - } - - const output = await hook(arg0, meta.context, nextNextHook); - validateOutput(outputErrIdentifier, output); - - if (output?.shortCircuit === true) { meta.shortCircuited = true; } - - return output; - }, - 'name', - { __proto__: null, value: nextHookName }, - ); -} - -/** - * @type {AsyncLoaderHookWorker} - * Worker instance used to run async loader hooks in a separate thread. This is a singleton for each - * non-loader-hook worker thread (i.e. the main thread and any worker threads that are not - * loader hook workers themselves). - */ -let asyncLoaderHookWorker; -/** - * Get the AsyncLoaderHookWorker instance. If it is not defined, then create a new one. - * @returns {AsyncLoaderHookWorker} - */ -function getAsyncLoaderHookWorker() { - asyncLoaderHookWorker ??= new AsyncLoaderHookWorker(); - return asyncLoaderHookWorker; -} - -/** - * @implements {AsyncLoaderHooks} - * Instances of this class are created in the non-loader-hook thread and communicate with the worker thread - * spawned to run the async loader hooks. - */ -class AsyncLoaderHooksProxiedToLoaderHookWorker { - - isForAsyncLoaderHookWorker = false; - - /** - * Instantiate a module loader that uses user-provided custom loader hooks. - */ - constructor() { - getAsyncLoaderHookWorker(); - } - - /** - * Register some loader specifier. - * @param {string} originalSpecifier The specified URL path of the loader to - * be registered. - * @param {string} parentURL The parent URL from where the loader will be - * registered if using it package name as specifier - * @param {any} [data] Arbitrary data to be passed from the custom loader - * (user-land) to the worker. - * @param {any[]} [transferList] Objects in `data` that are changing ownership - * @param {boolean} [isInternal] For internal loaders that should not be publicly exposed. - * @returns {{ format: string, url: URL['href'] }} - */ - register(originalSpecifier, parentURL, data, transferList, isInternal) { - return asyncLoaderHookWorker.makeSyncRequest('register', transferList, originalSpecifier, parentURL, - data, isInternal); - } - - /** - * Resolve the location of the module. - * @param {string} originalSpecifier The specified URL path of the module to - * be resolved. - * @param {string} [parentURL] The URL path of the module's parent. - * @param {ImportAttributes} importAttributes Attributes from the import - * statement or expression. - * @returns {{ format: string, url: URL['href'] }} - */ - resolve(originalSpecifier, parentURL, importAttributes) { - return asyncLoaderHookWorker.makeAsyncRequest('resolve', undefined, originalSpecifier, parentURL, importAttributes); - } - - resolveSync(originalSpecifier, parentURL, importAttributes) { - // This happens only as a result of `import.meta.resolve` calls, which must be sync per spec. - return asyncLoaderHookWorker.makeSyncRequest('resolve', undefined, originalSpecifier, parentURL, importAttributes); - } - - /** - * Provide source that is understood by one of Node's translators. - * @param {URL['href']} url The URL/path of the module to be loaded - * @param {object} [context] Metadata about the module - * @returns {Promise<{ format: ModuleFormat, source: ModuleSource }>} - */ - load(url, context) { - return asyncLoaderHookWorker.makeAsyncRequest('load', undefined, url, context); - } - loadSync(url, context) { - return asyncLoaderHookWorker.makeSyncRequest('load', undefined, url, context); - } - - waitForLoaderHookInitialization() { - asyncLoaderHookWorker.waitForWorker(); - } -} - -exports.AsyncLoaderHooksProxiedToLoaderHookWorker = AsyncLoaderHooksProxiedToLoaderHookWorker; -exports.AsyncLoaderHooksOnLoaderHookWorker = AsyncLoaderHooksOnLoaderHookWorker; -exports.AsyncLoaderHookWorker = AsyncLoaderHookWorker; diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js index 06f60f9f6725..66e7eb6d5ecf 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js @@ -8,7 +8,7 @@ const { } = require('internal/util'); const { defaultGetFormat } = require('internal/modules/esm/get_format'); -const { validateAttributes, emitImportAssertionWarning } = require('internal/modules/esm/assert'); +const { validateAttributes } = require('internal/modules/esm/assert'); const { loaderMethods } = require('internal/modules/helpers'); const { Buffer: { from: BufferFrom } } = require('buffer'); @@ -51,67 +51,6 @@ function getSourceSync(url, context) { } -/** - * Node.js default load hook. - * @param {string} url - * @param {LoadContext} context - * @returns {LoadReturn} - */ -function defaultLoad(url, context = kEmptyObject) { - let responseURL = url; - let { - importAttributes, - format, - source, - } = context; - - if (importAttributes == null && !('importAttributes' in context) && 'importAssertions' in context) { - emitImportAssertionWarning(); - importAttributes = context.importAssertions; - // Alias `importAssertions` to `importAttributes` - context = { - ...context, - importAttributes, - }; - } - - const urlInstance = new URL(url); - - throwIfUnsupportedURLScheme(urlInstance); - - if (urlInstance.protocol === 'node:') { - source = null; - format ??= 'builtin'; - } else if (format === 'addon') { - // Skip loading addon file content. It must be loaded with dlopen from file system. - source = null; - } else if (format !== 'commonjs') { - if (source == null) { - ({ responseURL, source } = getSourceSync(urlInstance, context)); - context = { __proto__: context, source }; - } - - if (format == null) { - // Now that we have the source for the module, run `defaultGetFormat` to detect its format. - format = defaultGetFormat(urlInstance, context); - - if (format === 'commonjs') { - // For backward compatibility reasons, we need to discard the source in - // order for the CJS loader to re-fetch it. - source = null; - } - } - } - - validateAttributes(url, format, importAttributes); - - return { - __proto__: null, - format, - responseURL, - source, - }; -} /** * @typedef LoadContext * @property {string} [format] A hint (possibly returned from `resolve`) @@ -212,7 +151,6 @@ function throwUnknownModuleFormat(url, format) { module.exports = { - defaultLoad, defaultLoadSync, getSourceSync, throwUnknownModuleFormat, diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index 2e0b0fef8e9d..ff99764566a4 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -1,18 +1,9 @@ 'use strict'; const { - ArrayPrototypeJoin, - ArrayPrototypeMap, - ArrayPrototypeReduce, FunctionPrototypeCall, - JSONStringify, ObjectSetPrototypeOf, - Promise, - PromisePrototypeThen, - RegExpPrototypeSymbolReplace, - encodeURIComponent, globalThis, - hardenRegExp, } = primordials; const { LoadCache, ResolveCache } = require('internal/modules/esm/module_map'); @@ -37,17 +28,15 @@ const { ERR_UNKNOWN_MODULE_FORMAT, } = require('internal/errors').codes; const { getOptionValue } = require('internal/options'); -const { isURL, pathToFileURL } = require('internal/url'); +const { pathToFileURL } = require('internal/url'); const { - getDeprecationWarningEmitter, kEmptyObject, } = require('internal/util'); const { compileSourceTextModule, SourceTextModuleTypes: { kUser }, getDefaultConditions, - shouldSpawnLoaderHookWorker, - requestTypes: { kImportInRequiredESM, kRequireInImportedCJS, kImportInImportedESM }, + requestTypes: { kImportInRequiredESM, kImportInImportedESM }, } = require('internal/modules/esm/utils'); /** * @typedef {import('./utils.js').ModuleRequestType} ModuleRequestType @@ -62,7 +51,6 @@ const { kUninstantiated, kErrored, kSourcePhase, - throwIfPromiseRejected, setImportMetaResolveInitializer, } = internalBinding('module_wrap'); const { @@ -83,10 +71,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { debug = fn; }); -const { isPromise } = require('internal/util/types'); - /** - * @typedef {import('./hooks.js').AsyncLoaderHookWorker} AsyncLoaderHookWorker * @typedef {import('./module_job.js').ModuleJobBase} ModuleJobBase * @typedef {import('url').URL} URL */ @@ -99,6 +84,26 @@ const { defaultLoadSync, throwUnknownModuleFormat } = require('internal/modules/ * @typedef {import('../cjs/loader.js').Module} CJSModule */ +/** + * A module request created from JS, with the same fields as the requests returned by + * `ModuleWrap.prototype.getModuleRequests()`. `import()` creates one per call, and a + * `{ __proto__: null }` literal would be created in dictionary mode, so use a class + * with a null-prototype prototype to keep a fast map. + */ +class ImportRequest { + /** + * @param {string} specifier + * @param {number} phase + * @param {Record<string, string>} attributes + */ + constructor(specifier, phase, attributes) { + this.specifier = specifier; + this.attributes = attributes; + this.phase = phase; + } +} +ObjectSetPrototypeOf(ImportRequest.prototype, null); + /** * @typedef {Record<string, any>} ModuleExports */ @@ -123,22 +128,12 @@ const { defaultLoadSync, throwUnknownModuleFormat } = require('internal/modules/ * responseURL?: string, * translatorKey: string, * isResolvedBySyncHooks: boolean, - * isSourceLoadedSynchronously: boolean, * }} TranslateContext */ /** - * @typedef {import('./hooks.js').AsyncLoaderHooks} AsyncLoaderHooks - * @typedef {import('./hooks.js').AsyncLoaderHooksOnLoaderHookWorker} AsyncLoaderHooksOnLoaderHookWorker - * @typedef {import('./hooks.js').AsyncLoaderHooksProxiedToLoaderHookWorker} AsyncLoaderHooksProxiedToLoaderHookWorker - */ - -/** - * This class covers the base machinery of module loading. There are two types of loader hooks: - * 1. Asynchronous loader hooks, which are run in a separate loader hook worker thread. - * This is configured in #asyncLoaderHooks. - * 2. Synchronous loader hooks, which are run in-thread. This is shared with the CJS loader and is - * stored in the cross-module syncResolveHooks and syncLoadHooks arrays. + * This class covers the base machinery of module loading. The `module.registerHooks()` hooks are + * shared with the CJS loader and stored in the cross-module syncResolveHooks and syncLoadHooks arrays. */ class ModuleLoader { /** @@ -156,57 +151,6 @@ class ModuleLoader { */ loadCache = new LoadCache(); - /** - * @see {AsyncLoaderHooks.isForAsyncLoaderHookWorker} - * Shortcut to this.#asyncLoaderHooks.isForAsyncLoaderHookWorker. - */ - isForAsyncLoaderHookWorker = false; - - /** - * Asynchronous loader hooks to pass requests to. - * - * Note that this value _MUST_ be set with `#setAsyncLoaderHooks` - * because it needs to copy `#asyncLoaderHooks.isForAsyncLoaderHookWorker` - * to this property. - * TODO(joyeecheung): this was a legacy of the previous setup of import.meta.resolve - * configuration; put this information in the environment directly instead. - * - * When the ModuleLoader is created on a loader hook thread, this is - * {@link AsyncLoaderHooksOnLoaderHookWorker}, and its methods directly call out - * to loader methods. Otherwise, this is {@link AsyncLoaderHooksProxiedToLoaderHookWorker}, - * and its methods post messages to the loader thread and possibly block on it. - * @see {ModuleLoader.#setAsyncLoaderHooks} - * @type {AsyncLoaderHooks} - */ - #asyncLoaderHooks; - - constructor(asyncLoaderHooks) { - this.#setAsyncLoaderHooks(asyncLoaderHooks); - } - - /** - * Change the currently activate async loader hooks for this module - * loader to be the provided `AsyncLoaderHooks`. - * - * If present, this class customizes its core functionality to the - * `AsyncLoaderHooks` object, including registration, loading, and resolving. - * There are some responsibilities that this class _always_ takes - * care of, like validating outputs, so that the AsyncLoaderHooks object - * does not have to do so. - * - * Calling this function alters how modules are loaded and should be - * invoked with care. - * @param {AsyncLoaderHooks} asyncLoaderHooks - */ - #setAsyncLoaderHooks(asyncLoaderHooks) { - this.#asyncLoaderHooks = asyncLoaderHooks; - if (asyncLoaderHooks) { - this.isForAsyncLoaderHookWorker = asyncLoaderHooks.isForAsyncLoaderHookWorker; - } else { - this.isForAsyncLoaderHookWorker = false; - } - } - /** * * @param {string} source Source code of the module. @@ -290,10 +234,6 @@ class ModuleLoader { if (job !== undefined) { mod[kRequiredModuleSymbol] = job.module; const parentFilename = urlToFilename(parent?.filename); - // This race should only be possible on the loader hook thread. See https://github.com/nodejs/node/issues/59666 - if (!job.module) { - throw new ERR_REQUIRE_ESM_RACE_CONDITION(filename, parentFilename, this.isForAsyncLoaderHookWorker); - } const status = job.module.getStatus(); debug('Module status', job, status); // hasAsyncGraph is available after module been instantiated. @@ -303,13 +243,10 @@ class ModuleLoader { if (status === kEvaluated) { return { wrap: job.module, namespace: job.module.getNamespace() }; } else if (status === kInstantiated) { - // When it's an async job cached by another import request, - // which has finished linking but has not started its - // evaluation because the async run() task would be later - // in line. Then start the evaluation now with runSync(), which - // is guaranteed to finish by the time the other run() get to it, - // and the other task would just get the cached evaluation results, - // similar to what would happen when both are async. + // The job was created by an earlier import() that has finished linking but has + // not started its evaluation, which is deferred to a later microtask. Evaluate + // it now with runSync(); the pending run() will then just find it already + // evaluated, similar to what would happen when both are async. mod[kRequiredModuleSymbol] = job.module; const { namespace } = job.runSync(parent); return { wrap: job.module, namespace: namespace || job.module.getNamespace() }; @@ -317,21 +254,14 @@ class ModuleLoader { // If the module was previously imported and errored, throw the error. throw job.module.getError(); } - // When the cached async job have already encountered a linking - // error that gets wrapped into a rejection, but is still later - // in line to throw on it, just unwrap and throw the linking error - // from require(). - if (job.instantiated) { - throwIfPromiseRejected(job.instantiated); - } if (status !== kEvaluating) { assert(status === kUninstantiated, `Unexpected module status ${status}`); - // If we get here, either there's a race where the job is still being instantiated - // by an in-flight import(), or the cached module previously encountered an + // If we get here, either the job was created by an in-flight import() that has not + // instantiated it yet, or the cached module previously encountered an // instantiation error during a prior load (e.g. due to a mismatched import). // TODO(joyeecheung): the current check is too broad. We should attempt to // get the potential instantiation error and throw it. - throw new ERR_REQUIRE_ESM_RACE_CONDITION(filename, parentFilename, false); + throw new ERR_REQUIRE_ESM_RACE_CONDITION(filename, parentFilename); } let message = `Cannot require() ES Module ${filename} in a cycle.`; if (parentFilename) { @@ -397,10 +327,6 @@ class ModuleLoader { * @param {ModuleJobBase} job The cached module job. */ #checkCachedJobForRequireESM(specifier, url, parentURL, job) { - // This race should only be possible on the loader hook thread. See https://github.com/nodejs/node/issues/59666 - if (!job.module) { - throw new ERR_REQUIRE_ESM_RACE_CONDITION(url, parentURL, this.isForAsyncLoaderHookWorker); - } // This module is being evaluated, which means it's imported in a previous link // in a cycle. if (job.module.getStatus() === kEvaluating) { @@ -422,7 +348,7 @@ class ModuleLoader { * Load a module and translate it into a ModuleWrap for require(esm). * This is run synchronously, and the translator always return a ModuleWrap synchronously. * @param {ResolveResult} resolveResult Result from the resolve step. - * @param {object} loadContext See {@link load} + * @param {{ format: string, importAttributes: object }} loadContext Context for the load step. * @param {string|undefined} parentURL URL of the parent module. Undefined if it's the entry point. * @param {ModuleRequest} request Module request. * @returns {ModuleWrap} @@ -460,8 +386,7 @@ class ModuleLoader { } /** - * Translate a loaded module source into a ModuleWrap. This is run synchronously, - * but the translator may return the ModuleWrap in a Promise. + * Translate a loaded module source into a ModuleWrap synchronously. * @param {string} url URL of the module to be translated. * @param {TranslateContext} translateContext Context for the translator * @param {string|undefined} parentURL URL of the module initiating the module loading for the first time. @@ -479,98 +404,47 @@ class ModuleLoader { const result = FunctionPrototypeCall(translator, this, url, translateContext, parentURL); assert(result instanceof ModuleWrap, `The ${format} module returned is not a ModuleWrap`); - if (format === 'commonjs' || format === 'commonjs-sync' || format === 'require-commonjs') { + if (format === 'commonjs' || format === 'commonjs-sync') { result.isCommonJS = true; } return result; } /** - * Load a module and translate it into a ModuleWrap for require() in imported CJS. - * This is run synchronously, and the translator always return a ModuleWrap synchronously. + * Load a module and translate it into a ModuleWrap for ordinary imported ESM. + * Loading and translation are synchronous; evaluation may be asynchronous. * @param {ResolveResult} resolveResult Result from the resolve step. - * @param {object} loadContext See {@link load} + * @param {{ format: string, importAttributes: object }} loadContext Context for the load step. * @param {string|undefined} parentURL URL of the parent module. Undefined if it's the entry point. * @returns {ModuleWrap} */ - loadAndTranslateForRequireInImportedCJS(resolveResult, loadContext, parentURL) { + loadAndTranslate(resolveResult, loadContext, parentURL) { const { url } = resolveResult; const loadResult = this.#loadSync(url, loadContext); - const formatFromLoad = loadResult.format; - - if (formatFromLoad === 'wasm') { // require(wasm) is not supported. - throw new ERR_UNKNOWN_MODULE_FORMAT(formatFromLoad, url); - } - - if (formatFromLoad === 'module' || formatFromLoad === 'module-typescript') { - if (!getOptionValue('--require-module')) { - throw new ERR_REQUIRE_ESM(url, true); - } - } - - let translatorKey = formatFromLoad; - if (formatFromLoad === 'commonjs') { - translatorKey = 'require-commonjs'; - } - if (formatFromLoad === 'commonjs-typescript') { - translatorKey = 'require-commonjs-typescript'; - } - const translateContext = { ...resolveResult, ...loadResult, - translatorKey, + translatorKey: loadResult.format, __proto__: null, }; - const wrap = this.#translate(url, translateContext, parentURL); - assert(wrap instanceof ModuleWrap, `Translator used for require(${url}) should not be async`); - return wrap; - } - - /** - * Load a module and translate it into a ModuleWrap for ordinary imported ESM. - * This may be run asynchronously if there are asynchronous module loader hooks registered. - * @param {ResolveResult} resolveResult Result from the resolve step. - * @param {object} loadContext See {@link load} - * @param {string|undefined} parentURL URL of the parent module. Undefined if it's the entry point. - * @returns {Promise<ModuleWrap>|ModuleWrap} - */ - loadAndTranslate(resolveResult, loadContext, parentURL) { - const { url } = resolveResult; - const maybePromise = this.load(url, loadContext); - const afterLoad = (loadResult) => { - const translateContext = { - ...resolveResult, - ...loadResult, - translatorKey: loadResult.format, - __proto__: null, - }; - return this.#translate(url, translateContext, parentURL); - }; - if (isPromise(maybePromise)) { - return PromisePrototypeThen(maybePromise, afterLoad); - } - return afterLoad(maybePromise); + return this.#translate(url, translateContext, parentURL); } /** * Given a resolved module request, obtain a ModuleJobBase from it - if it's already cached, * return the cached ModuleJobBase. Otherwise, load its source and translate it into a ModuleWrap first. - * This runs synchronously. On any thread that is not an async loader hook worker thread, - * the module should be linked by the time this returns. Otherwise it may still have - * pending module requests. + * This runs synchronously, so the module should be linked by the time this returns. * @param {string} parentURL See {@link getOrCreateModuleJob} * @param {ResolveResult} resolveResult * @param {ModuleRequest} request Module request. * @param {ModuleRequestType} requestType Type of the module request. - * @returns {ModuleJobBase} The (possibly pending) module job + * @returns {ModuleJobBase} The module job */ #getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType) { const { url, format } = resolveResult; if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) { - const type = requestType === kRequireInImportedCJS ? 'require' : 'import'; - process.send({ [`watch:${type}`]: [url] }); + process.send({ 'watch:import': [url] }); } // Relay Events from worker to main thread if (process.env.WATCH_REPORT_DEPENDENCIES && !process.send) { @@ -597,34 +471,19 @@ class ModuleLoader { const context = { format, importAttributes, __proto__: null }; - let moduleOrModulePromise; - if (requestType === kRequireInImportedCJS) { - moduleOrModulePromise = this.loadAndTranslateForRequireInImportedCJS(resolveResult, context, parentURL); - } else if (requestType === kImportInRequiredESM) { - moduleOrModulePromise = this.loadAndTranslateForImportInRequiredESM(resolveResult, context, parentURL, request); - } else { - moduleOrModulePromise = this.loadAndTranslate(resolveResult, context, parentURL); - } + const module = requestType === kImportInRequiredESM ? + this.loadAndTranslateForImportInRequiredESM(resolveResult, context, parentURL, request) : + this.loadAndTranslate(resolveResult, context, parentURL); - if (requestType === kImportInRequiredESM || requestType === kRequireInImportedCJS || - !this.isForAsyncLoaderHookWorker) { - assert(moduleOrModulePromise instanceof ModuleWrap, `Expected ModuleWrap for loading ${url}`); - } + assert(module instanceof ModuleWrap, `Expected ModuleWrap for loading ${url}`); const isMain = (parentURL === undefined); const inspectBrk = (isMain && getOptionValue('--inspect-brk')); - // Use ModuleJobSync for kImportInRequiredESM, which must always be linked synchronously, - // and whenever we're on the main thread (not the async loader hook worker), - // except for kRequireInImportedCJS (TODO: consolidate that case too). - // TODO(joyeecheung): use ModuleJobSync for kRequireInImportedCJS too. - const ModuleJobCtor = (requestType === kImportInRequiredESM || - (!this.isForAsyncLoaderHookWorker && requestType !== kRequireInImportedCJS)) ? - ModuleJobSync : ModuleJob; - job = new ModuleJobCtor( + job = new ModuleJobSync( this, url, importAttributes, - moduleOrModulePromise, + module, request.phase, isMain, inspectBrk, @@ -637,35 +496,16 @@ class ModuleLoader { } /** - * Get a (possibly not yet fully linked) module job from the cache, or create one and return its Promise. + * Get a module job from the cache, or create one. Loading and linking are synchronous. * @param {string} [parentURL] The URL of the module where the module request is initiated. * It's undefined if it's from the root module. * @param {ModuleRequest} request Module request. * @param {ModuleRequestType} requestType Type of the module request. - * @returns {Promise<ModuleJobBase>|ModuleJobBase} + * @returns {ModuleJobBase} */ getOrCreateModuleJob(parentURL, request, requestType) { - let maybePromise; - if (!this.isForAsyncLoaderHookWorker || - requestType === kRequireInImportedCJS || requestType === kImportInRequiredESM) { - // On the main thread, always resolve synchronously; - // `resolveSync` coordinates with the async loader hook worker if needed. - // On the async loader hook worker, require(esm) and require() in imported CJS - // must still be resolved synchronously. - maybePromise = this.resolveSync(parentURL, request); - assert(!isPromise(maybePromise)); - } else { - maybePromise = this.#resolve(parentURL, request); - } - - const afterResolve = (resolveResult) => { - return this.#getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType); - }; - - if (isPromise(maybePromise)) { - return PromisePrototypeThen(maybePromise, afterResolve); - } - return afterResolve(maybePromise); + const resolveResult = this.resolveSync(parentURL, request); + return this.#getOrCreateModuleJobAfterResolve(parentURL, resolveResult, request, requestType); } /** @@ -680,68 +520,31 @@ class ModuleLoader { * @returns {Promise<ModuleExports>} */ async import(specifier, parentURL, importAttributes, phase = kEvaluationPhase, isEntryPoint = false) { + // tracePromise() ignores the context when there are no subscribers, so only + // create it when there are: a `{ __proto__: null }` literal is created in + // dictionary mode, and import() can be called on a hot path. + const traceContext = onImport.hasSubscribers ? + { __proto__: null, parentURL, url: specifier } : + undefined; return onImport.tracePromise(async () => { - const request = { specifier, phase, attributes: importAttributes, __proto__: null }; - let moduleJob; - try { - moduleJob = await this.getOrCreateModuleJob(parentURL, request); - } catch (e) { - if (e?.code === 'ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED') { - return new Promise(() => {}); - } - throw e; - } + const request = new ImportRequest(specifier, phase, importAttributes); + const moduleJob = this.getOrCreateModuleJob(parentURL, request); + // Loading and linking are synchronous, but import() must still never evaluate the + // module before returning to its caller, so yield once before running the job. + await null; if (phase === kSourcePhase) { const module = await moduleJob.modulePromise; return module.getModuleSourceObject(); } const { module } = await moduleJob.run(isEntryPoint); return module.getNamespace(); - }, { - __proto__: null, - parentURL, - url: specifier, - }); - } - - /** - * @see {@link AsyncLoaderHooks.register} - * @returns {any} - */ - register(specifier, parentURL, data, transferList, isInternal) { - if (!this.#asyncLoaderHooks) { - // On the loader hook worker thread, the #asyncLoaderHooks must already have been initialized - // to be an instance of AsyncLoaderHooksOnLoaderHookWorker, so this branch can only ever - // be hit on a non-loader-hook thread that will talk to the loader hook worker thread. - const { AsyncLoaderHooksProxiedToLoaderHookWorker } = require('internal/modules/esm/hooks'); - this.#setAsyncLoaderHooks(new AsyncLoaderHooksProxiedToLoaderHookWorker()); - } - return this.#asyncLoaderHooks.register(`${specifier}`, `${parentURL}`, data, transferList, isInternal); - } - - /** - * Resolve a module request to a URL identifying the location of the module. Handles customization hooks, - * if any. - * @param {string} [parentURL] The URL of the module where the module request is initiated. - * It's undefined if it's from the root module. - * @param {ModuleRequest} request Module request. - * @returns {Promise<ResolveResult>|ResolveResult} - */ - #resolve(parentURL, request) { - if (this.isForAsyncLoaderHookWorker) { - const specifier = `${request.specifier}`; - const importAttributes = request.attributes ?? kEmptyObject; - // TODO(joyeecheung): invoke the synchronous hooks in the default step on loader thread. - return this.#asyncLoaderHooks.resolve(specifier, parentURL, importAttributes); - } - - return this.resolveSync(parentURL, request); + }, traceContext); } /** * Either return a cached resolution, or perform the default resolution which is synchronous, and * cache the result. - * @param {string} specifier See {@link resolve}. + * @param {string} specifier The module specifier. * @param {{ parentURL?: string, importAttributes: ImportAttributes, conditions?: string[]}} context * @returns {{ format: string, url: string }} */ @@ -759,48 +562,39 @@ class ModuleLoader { } /** - * This is the default resolve step for module.registerHooks(), which incorporates asynchronous hooks - * from module.register() which are run in a blocking fashion for it to be synchronous. + * This is the default resolve step for module.registerHooks(). * @param {{isResolvedByDefaultResolve: boolean}} out Output object to track whether the default resolve was used * without polluting the user-visible resolve result. - * @param {string|URL} specifier See {@link resolveSync}. + * @param {string|URL} specifier The module specifier. * @param {{ parentURL?: string, importAttributes: ImportAttributes, conditions?: string[]}} context - * See {@link resolveSync}. + * Resolution context. * @returns {{ format: string, url: string }} */ - #resolveAndMaybeBlockOnLoaderThread(out, specifier, context) { - if (this.#asyncLoaderHooks?.resolveSync) { - return this.#asyncLoaderHooks.resolveSync(specifier, context.parentURL, context.importAttributes); - } + #defaultResolve(out, specifier, context) { out.isResolvedByDefaultResolve = true; return this.#cachedDefaultResolve(specifier, context); } /** - * Similar to {@link resolve}, but the results are always synchronously returned. If there are any - * asynchronous resolve hooks from module.register(), it will block until the results are returned - * from the loader thread for this to be synchronous. - * This is here to support `import.meta.resolve()`, `require()` in imported CJS, and - * `module.registerHooks()` hooks. - * @param {string} [parentURL] See {@link resolve}. - * @param {ModuleRequest} request See {@link resolve}. - * @param {boolean} [shouldSkipSyncHooks] Whether to skip the synchronous hooks registered by module.registerHooks(). - * This is used to maintain compatibility for the re-invented require.resolve (in imported CJS customized - * by module.register()`) which invokes the CJS resolution separately from the hook chain. + * Resolve a module request to a URL identifying the location of the module. Handles + * `module.registerHooks()` hooks, if any. + * @param {string} [parentURL] The URL of the module where the module request is initiated. + * It's undefined if it's from the root module. + * @param {ModuleRequest} request Module request. * @returns {ResolveResult} */ - resolveSync(parentURL, request, shouldSkipSyncHooks = false) { + resolveSync(parentURL, request) { const specifier = `${request.specifier}`; const importAttributes = request.attributes ?? kEmptyObject; - // Use an output parameter to track the state and avoid polluting the user-visible resolve results. - const out = { isResolvedByDefaultResolve: false, __proto__: null }; let result; let isResolvedBySyncHooks = false; - if (!shouldSkipSyncHooks && syncResolveHooks.length) { - // Has module.registerHooks() hooks, chain the asynchronous hooks in the default step. + if (syncResolveHooks.length) { + // Use an output parameter to track the state and avoid polluting the user-visible resolve results. + const out = { isResolvedByDefaultResolve: false, __proto__: null }; + // Has module.registerHooks() hooks, chain the default resolver in the default step. result = resolveWithSyncHooks(specifier, parentURL, importAttributes, this.#defaultConditions, - this.#resolveAndMaybeBlockOnLoaderThread.bind(this, out)); + this.#defaultResolve.bind(this, out)); // If the default step ran, sync hooks did not short-circuit the resolution. isResolvedBySyncHooks = !out.isResolvedByDefaultResolve; } else { @@ -811,85 +605,34 @@ class ModuleLoader { importAttributes, __proto__: null, }; - result = this.#resolveAndMaybeBlockOnLoaderThread(out, specifier, context); + result = this.#cachedDefaultResolve(specifier, context); } result.isResolvedBySyncHooks = isResolvedBySyncHooks; return result; } /** - * Provide source that is understood by one of Node's translators. Handles customization hooks, - * if any. - * @typedef {{ - * format: ModuleFormat, - * source: ModuleSource, - * responseURL?: string, - * isSourceLoadedSynchronously: boolean, - * }} LoadResult + * Provide source that is understood by one of Node's translators. Handles + * `module.registerHooks()` hooks, if any. * @param {string} url The URL of the module to be loaded. - * @param {object} context Metadata about the module - * @returns {Promise<LoadResult> | LoadResult}} - */ - load(url, context) { - if (this.isForAsyncLoaderHookWorker) { - // TODO(joyeecheung): invoke the synchronous hooks in the default step on loader thread. - return this.#asyncLoaderHooks.load(url, context); - } - return this.#loadSync(url, context); - } - - /** - * This is the default load step for module.registerHooks(), which incorporates asynchronous hooks - * from module.register() which are run in a blocking fashion for it to be synchronous. - * @param {{isSourceLoadedSynchronously: boolean}} out - * Output object to track whether the source was loaded synchronously without polluting - * the user-visible load result. - * @param {string} url See {@link load} - * @param {object} context See {@link load} - * @returns {{ format: ModuleFormat, source: ModuleSource }} - */ - #loadAndMaybeBlockOnLoaderThread(out, url, context) { - if (this.#asyncLoaderHooks?.loadSync) { - out.isSourceLoadedSynchronously = false; - return this.#asyncLoaderHooks.loadSync(url, context); - } - out.isSourceLoadedSynchronously = true; - return defaultLoadSync(url, context); - } - - /** - * Similar to {@link load} but this is always run synchronously. If there are asynchronous hooks - * from module.register(), this blocks on the loader thread for it to return synchronously. - * - * This is here to support `require()` in imported CJS and `module.registerHooks()` hooks. - * @param {string} url See {@link load} - * @param {object} [context] See {@link load} - * @returns {LoadResult} + * @param {{ format: string, importAttributes: object }} context Metadata about the module + * @returns {{ format: ModuleFormat, source: ModuleSource, responseURL?: string }} */ #loadSync(url, context) { - // Use an output parameter to track the state and avoid polluting the user-visible resolve results. - const out = { - isSourceLoadedSynchronously: true, - __proto__: null, - }; - let result; if (syncLoadHooks.length) { - // Has module.registerHooks() hooks, chain the asynchronous hooks in the default step. + // Has module.registerHooks() hooks, chain the default loader in the default step. // TODO(joyeecheung): construct the ModuleLoadContext in the loaders directly instead // of converting them from plain objects in the hooks. - result = loadWithSyncHooks( + return loadWithSyncHooks( url, context.format, context.importAttributes, this.#defaultConditions, - this.#loadAndMaybeBlockOnLoaderThread.bind(this, out), + defaultLoadSync, validateLoadSloppy, ); - } else { - result = this.#loadAndMaybeBlockOnLoaderThread(out, url, context); } - result.isSourceLoadedSynchronously = out.isSourceLoadedSynchronously; - return result; + return defaultLoadSync(url, context); } validateLoadResult(url, format) { @@ -897,60 +640,9 @@ class ModuleLoader { throwUnknownModuleFormat(url, format); } } - - /** - * Block until the async loader hooks have been initialized. - * - * No-op when no hooks have been supplied. - */ - waitForAsyncLoaderHookInitialization() { - this.#asyncLoaderHooks?.waitForLoaderHookInitialization(); - } } ObjectSetPrototypeOf(ModuleLoader.prototype, null); -let emittedLoaderFlagWarning = false; -/** - * A loader instance is used as the main entry point for loading ES modules. Currently, this is a singleton; there is - * only one used for loading the main module and everything in its dependency graph, though separate instances of this - * class might be instantiated as part of bootstrap for other purposes. - * @param {AsyncLoaderHooksOnLoaderHookWorker|undefined} [asyncLoaderHooks] - * Only provided when run on the loader hook thread. - * @returns {ModuleLoader} - */ -function createModuleLoader(asyncLoaderHooks) { - // Don't spawn a new loader hook worker if we are already in a loader hook worker to avoid infinite recursion. - if (shouldSpawnLoaderHookWorker()) { - assert(asyncLoaderHooks === undefined, 'asyncLoaderHooks should only be provided on the loader hook thread itself'); - const userLoaderPaths = getOptionValue('--experimental-loader'); - if (userLoaderPaths.length > 0) { - if (!emittedLoaderFlagWarning) { - const readableURIEncode = (string) => ArrayPrototypeReduce( - [ - [/'/g, '%27'], // We need to URL-encode the single quote as it's the delimiter for the --import flag. - [/%22/g, '"'], // We can decode the double quotes to improve readability. - [/%2F/ig, '/'], // We can decode the slashes to improve readability. - ], - (str, { 0: regex, 1: replacement }) => RegExpPrototypeSymbolReplace(hardenRegExp(regex), str, replacement), - encodeURIComponent(string)); - process.emitWarning( - '`--experimental-loader` may be removed in the future; instead use `register()`:\n' + - `--import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; ${ArrayPrototypeJoin( - ArrayPrototypeMap(userLoaderPaths, (loader) => `register(${readableURIEncode(JSONStringify(loader))}, pathToFileURL("./"))`), - '; ', - )};'`, - 'ExperimentalWarning', - ); - emittedLoaderFlagWarning = true; - } - const { AsyncLoaderHooksProxiedToLoaderHookWorker } = require('internal/modules/esm/hooks'); - asyncLoaderHooks = new AsyncLoaderHooksProxiedToLoaderHookWorker(); - } - } - - return new ModuleLoader(asyncLoaderHooks); -} - let allowImportMetaResolveParentURL; /** * This is only called from the native ImportMetaObjectInitialize function to set up import.meta.resolve @@ -1000,20 +692,12 @@ let cascadedLoader; * require('internal/module/esm/loader').getOrInitializeCascadedLoader() * lazily only right before the loader is actually needed, and don't do it * in the top-level, to avoid circular dependencies. - * @param {AsyncLoaderHooksOnLoaderHookWorker|undefined} [asyncLoaderHooks] - * Only provided when run on the loader hook thread. * @returns {ModuleLoader} */ -function getOrInitializeCascadedLoader(asyncLoaderHooks) { +function getOrInitializeCascadedLoader() { if (!cascadedLoader) { - cascadedLoader = createModuleLoader(asyncLoaderHooks); - // import.meta.resolve is not allowed in the async loader hook worker thread. - // So only set up the import.meta.resolve initializer when we are initializing - // the non-loader-hook-thread cascaded loader. When the native land doesn't see it, - // it knows the loader is running on the loader hook thread. - if (!(asyncLoaderHooks?.isForAsyncLoaderHookWorker)) { - setImportMetaResolveInitializer(createImportMetaResolve.bind(null, cascadedLoader)); - } + cascadedLoader = new ModuleLoader(); + setImportMetaResolveInitializer(createImportMetaResolve.bind(null, cascadedLoader)); } return cascadedLoader; } @@ -1022,60 +706,8 @@ function isCascadedLoaderInitialized() { return cascadedLoader !== undefined; } -/** - * Register a single loader programmatically. - * @param {string|URL} specifier - * @param {string|URL} [parentURL] Base to use when resolving `specifier`; optional if - * `specifier` is absolute. Same as `options.parentUrl`, just inline - * @param {object} [options] Additional options to apply, described below. - * @param {string|URL} [options.parentURL] Base to use when resolving `specifier` - * @param {any} [options.data] Arbitrary data passed to the loader's `initialize` hook - * @param {any[]} [options.transferList] Objects in `data` that are changing ownership - * @returns {void} We want to reserve the return value for potential future extension of the API. - * @example - * ```js - * register('./myLoader.js'); - * register('ts-node/esm', { parentURL: import.meta.url }); - * register('./myLoader.js', { parentURL: import.meta.url }); - * register('ts-node/esm', import.meta.url); - * register('./myLoader.js', import.meta.url); - * register(new URL('./myLoader.js', import.meta.url)); - * register('./myLoader.js', { - * parentURL: import.meta.url, - * data: { banana: 'tasty' }, - * }); - * register('./myLoader.js', { - * parentURL: import.meta.url, - * data: someArrayBuffer, - * transferList: [someArrayBuffer], - * }); - * ``` - */ -const emitRegisterDeprecation = getDeprecationWarningEmitter( - 'DEP0205', - '`module.register()` is deprecated. Use `module.registerHooks()` instead.', - undefined, - false, -); - -function register(specifier, parentURL = undefined, options) { - emitRegisterDeprecation(); - - if (parentURL != null && typeof parentURL === 'object' && !isURL(parentURL)) { - options = parentURL; - parentURL = options.parentURL; - } - getOrInitializeCascadedLoader().register( - specifier, - parentURL ?? 'data:', - options?.data, - options?.transferList, - ); -} - module.exports = { - createModuleLoader, + ModuleLoader, getOrInitializeCascadedLoader, isCascadedLoaderInitialized, - register, }; diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index c8506b42ff3f..6c98644a7321 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -11,12 +11,10 @@ const { FunctionPrototype, ObjectAssign, ObjectSetPrototypeOf, - PromisePrototypeThen, PromiseResolve, RegExpPrototypeExec, RegExpPrototypeSymbolReplace, RegExpPrototypeSymbolSplit, - SafePromiseAllReturnArrayLike, SafePromiseAllReturnVoid, SafeSet, StringPrototypeIncludes, @@ -31,15 +29,11 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { const { ModuleWrap, kErrored, - kEvaluated, - kEvaluating, kDeferPhase, kEvaluationPhase, kInstantiated, - kUninstantiated, } = internalBinding('module_wrap'); const { - getPromiseDetails, privateSymbols: { entry_point_module_private_symbol, module_source_private_symbol: kModuleSource, @@ -49,7 +43,6 @@ const { * @typedef {import('./utils.js').ModuleRequestType} ModuleRequestType */ const { decorateErrorStack } = require('internal/util'); -const { isPromise } = require('internal/util/types'); const { getSourceMapsSupport, } = require('internal/source_map/source_map_cache'); @@ -63,7 +56,6 @@ const { getOptionValue } = require('internal/options'); const noop = FunctionPrototype; const { ERR_REQUIRE_ASYNC_MODULE, - ERR_REQUIRE_ESM_RACE_CONDITION, } = require('internal/errors').codes; const CJSGlobalLike = [ @@ -193,14 +185,7 @@ function findModulesWithTopLevelAwait(root) { if (job.module?.hasTopLevelAwait) { ArrayPrototypePush(found, job.module); } - let linked = job.linked; - if (isPromise(linked)) { - linked = getPromiseDetails(linked)?.[1]; - } - // If `require(esm)` comes from the deprecated async loader hook worker thread, - // linked may be pending at this point. In that case, this branch would be skipped - - // we just allow lossy reporting of TLA locations in an edge case when a deprecated - // feature is used in combination with another experimental flag. + const { linked } = job; if (ArrayIsArray(linked)) { for (let i = 0; i < linked.length; i++) { ArrayPrototypePush(stack, linked[i]); @@ -292,6 +277,23 @@ const handleCJSNamedExportError = (error, module, commonJsDeps) => { } }; +/** + * Result of evaluating a module job. `import()` gets one on every call, and a + * `{ __proto__: null }` literal would be created in dictionary mode, so use a class + * with a null-prototype prototype to keep a fast map. + */ +class ModuleJobResult { + /** + * @param {ModuleWrap} module + * @param {object|undefined} namespace + */ + constructor(module, namespace) { + this.module = module; + this.namespace = namespace; + } +} +ObjectSetPrototypeOf(ModuleJobResult.prototype, null); + class ModuleJobBase { constructor(loader, url, importAttributes, phase, isMain, inspectBrk) { assert(typeof phase === 'number'); @@ -309,7 +311,7 @@ class ModuleJobBase { * @param {ModuleRequestType} requestType Type of the module request. * @returns {ModuleJobBase[]} */ - syncLink(requestType) { + link(requestType) { // Store itself into the cache first before linking in case there are circular // references in the linking. Track whether we're overwriting an existing entry // so we know whether to remove the temporary entry in the finally block. @@ -323,11 +325,8 @@ class ModuleJobBase { try { for (let idx = 0; idx < moduleRequests.length; idx++) { const request = moduleRequests[idx]; - // TODO(joyeecheung): split this into two iterators, one for resolving and one for loading so - // that hooks can pre-fetch sources off-thread. const job = this.loader.getOrCreateModuleJob(this.url, request, requestType); - debug(`ModuleJobBase.syncLink() ${this.url} -> ${request.specifier}`, job); - assert(!isPromise(job)); + debug(`ModuleJobBase.link() ${this.url} -> ${request.specifier}`, job); assert(job.module instanceof ModuleWrap); if (this.shouldRunModule(request.phase)) { ArrayPrototypePush(evaluationDepJobs, job); @@ -374,9 +373,6 @@ class ModuleJobBase { if (this.phase < phase) { this.phase = phase; this.linked = this.link(requestType); - if (isPromise(this.linked)) { - PromisePrototypeThen(this.linked, undefined, noop); - } } } @@ -395,33 +391,23 @@ class ModuleJob extends ModuleJobBase { * @param {ModuleLoader} loader The ESM loader. * @param {string} url URL of the module to be wrapped in ModuleJob. * @param {ImportAttributes} importAttributes Import attributes from the import statement. - * @param {ModuleWrap|Promise<ModuleWrap>} moduleOrModulePromise Translated ModuleWrap for the module. + * @param {ModuleWrap} module Translated ModuleWrap for the module. * @param {number} phase The phase to load the module to. * @param {boolean} isMain Whether the module is the entry point. * @param {boolean} inspectBrk Whether this module should be evaluated with the * first line paused in the debugger (because --inspect-brk is passed). * @param {ModuleRequestType} requestType Type of the module request. */ - constructor(loader, url, importAttributes = { __proto__: null }, moduleOrModulePromise, + constructor(loader, url, importAttributes = { __proto__: null }, module, phase = kEvaluationPhase, isMain, inspectBrk, requestType) { super(loader, url, importAttributes, phase, isMain, inspectBrk); - // Expose the promise to the ModuleWrap directly for linking below. - if (isPromise(moduleOrModulePromise)) { - this.modulePromise = moduleOrModulePromise; - } else { - this.module = moduleOrModulePromise; - this.modulePromise = PromiseResolve(moduleOrModulePromise); - } + this.module = module; + this.modulePromise = PromiseResolve(module); if (this.shouldLinkModule(this.phase)) { - // Promise for the list of all dependencyJobs. + // The list of all dependencyJobs. this.linked = this.link(requestType); - // This promise is awaited later anyway, so silence - // 'unhandled rejection' warnings. - if (isPromise(this.linked)) { - PromisePrototypeThen(this.linked, undefined, noop); - } } // instantiated == deep dependency jobs wrappers are instantiated, @@ -429,59 +415,6 @@ class ModuleJob extends ModuleJobBase { this.instantiated = undefined; } - /** - * @param {ModuleRequestType} requestType Type of the module request. - * @returns {ModuleJobBase[]|Promise<ModuleJobBase[]>} - */ - link(requestType) { - if (this.loader.isForAsyncLoaderHookWorker) { - return this.#asyncLink(requestType); - } - return this.syncLink(requestType); - } - - /** - * @param {ModuleRequestType} requestType Type of the module request. - * @returns {Promise<ModuleJobBase[]>} - */ - async #asyncLink(requestType) { - assert(this.loader.isForAsyncLoaderHookWorker); - this.module = await this.modulePromise; - assert(this.module instanceof ModuleWrap); - const moduleRequests = this.module.getModuleRequests(); - // Create an ArrayLike to avoid calling into userspace with `.then` - // when returned from the async function. - // Modules should be aligned with the moduleRequests array in order. - const modulePromises = Array(moduleRequests.length); - const evaluationDepJobs = []; - this.commonJsDeps = Array(moduleRequests.length); - for (let idx = 0; idx < moduleRequests.length; idx++) { - const request = moduleRequests[idx]; - // Explicitly keeping track of dependency jobs is needed in order - // to flatten out the dependency graph below in `asyncInstantiate()`, - // so that circular dependencies can't cause a deadlock by two of - // these `link` callbacks depending on each other. - // TODO(joyeecheung): split this into two iterators, one for resolving and one for loading so - // that hooks can pre-fetch sources off-thread. - const dependencyJobPromise = this.loader.getOrCreateModuleJob(this.url, request, requestType); - const modulePromise = PromisePrototypeThen(dependencyJobPromise, (job) => { - debug(`ModuleJob.asyncLink() ${this.url} -> ${request.specifier}`, job); - if (this.shouldRunModule(request.phase)) { - ArrayPrototypePush(evaluationDepJobs, job); - } - return job.modulePromise; - }); - modulePromises[idx] = modulePromise; - } - const modules = await SafePromiseAllReturnArrayLike(modulePromises); - for (let idx = 0; idx < moduleRequests.length; idx++) { - this.commonJsDeps[idx] = modules[idx].isCommonJS; - } - - this.module.link(modules); - return evaluationDepJobs; - } - #instantiate() { if (this.instantiated === undefined) { this.instantiated = this.#asyncInstantiate(); @@ -491,8 +424,6 @@ class ModuleJob extends ModuleJobBase { async #asyncInstantiate() { const jobsInGraph = new SafeSet(); - // TODO(joyeecheung): if it's not on the async loader thread, consider this already - // linked. const addJobsToDependencyGraph = async (moduleJob) => { debug(`async addJobsToDependencyGraph() ${this.url}`, moduleJob); @@ -500,8 +431,7 @@ class ModuleJob extends ModuleJobBase { return; } jobsInGraph.add(moduleJob); - const dependencyJobs = isPromise(moduleJob.linked) ? await moduleJob.linked : moduleJob.linked; - return SafePromiseAllReturnVoid(dependencyJobs, addJobsToDependencyGraph); + return SafePromiseAllReturnVoid(moduleJob.linked, addJobsToDependencyGraph); }; await addJobsToDependencyGraph(this); @@ -520,46 +450,6 @@ class ModuleJob extends ModuleJobBase { } } - runSync(parent) { - assert(this.shouldRunModule(this.phase)); - assert(this.module instanceof ModuleWrap); - let status = this.module.getStatus(); - - debug('ModuleJob.runSync()', status, this.module); - if (status === kUninstantiated) { - // TODO(joyeecheung): Reject graphs with top-level await _before_ instantiation, so that - // the async graph error supersedes instantiation (mismatch export) errors in the graph. - // FIXME(joyeecheung): this cannot fully handle < kInstantiated. Make the linking - // fully synchronous instead. - if (this.module.getModuleRequests().length === 0) { - this.module.link([]); - } - this.module.instantiate(); - status = this.module.getStatus(); - } - if (status === kInstantiated || status === kErrored) { - this.throwIfAsyncGraph(parent); - if (status === kInstantiated) { - setHasStartedUserESMExecution(); - const namespace = this.module.evaluateSync(); - return { __proto__: null, module: this.module, namespace }; - } - throw this.module.getError(); - } else if (status === kEvaluating || status === kEvaluated) { - this.throwIfAsyncGraph(parent); - // kEvaluating can show up when this is being used to deal with CJS <-> CJS cycles. - // Allow it for now, since we only need to ban ESM <-> CJS cycles which would be - // detected earlier during the linking phase, though the CJS handling in the ESM - // loader won't be able to emit warnings on pending circular exports like what - // the CJS loader does. - // TODO(joyeecheung): remove the re-invented require() in the ESM loader and - // always handle CJS using the CJS loader to eliminate the quirks. - return { __proto__: null, module: this.module, namespace: this.module.getNamespace() }; - } - assert(status === kUninstantiated, `Unexpected module status ${status}.`); - throw new ERR_REQUIRE_ESM_RACE_CONDITION(); - } - async run(isEntryPoint = false) { debug('ModuleJob.run()', this.module); assert(this.shouldRunModule(this.phase)); @@ -576,21 +466,17 @@ class ModuleJob extends ModuleJobBase { explainCommonJSGlobalLikeNotDefinedError(e, this.module.url, this.module.hasTopLevelAwait); throw e; } - return { __proto__: null, module: this.module }; + return new ModuleJobResult(this.module, undefined); } } /** - * This is a fully synchronous job and does not spawn additional threads in any way. * Loading and linking are always synchronous. Evaluation via runSync() throws on an * asynchronous graph; evaluation via run() falls back to async for top-level await. * It also disallows CJS <-> ESM cycles. * - * Used for all ES module imports on the main thread, regardless of how the import was - * triggered (entry point, import(), require(esm), --import, etc.). - * Modules loaded by require() in imported CJS are handled by ModuleJob with the - * isForRequireInImportedCJS set to true instead. The two currently have different caching behaviors. - * TODO(joyeecheung): consolidate this with the isForRequireInImportedCJS variant of ModuleJob. + * Used for all ES module imports regardless of how the import was triggered + * (entry point, import(), require(esm), --import, etc.). */ class ModuleJobSync extends ModuleJobBase { /** @@ -617,15 +503,6 @@ class ModuleJobSync extends ModuleJobBase { } } - /** - * @param {ModuleRequestType} requestType Type of the module request. - * @returns {ModuleJobBase[]} - */ - link(requestType) { - // Synchronous linking is always used for ModuleJobSync. - return this.syncLink(requestType); - } - get modulePromise() { return PromiseResolve(this.module); } @@ -653,7 +530,7 @@ class ModuleJobSync extends ModuleJobBase { if (this.evaluationPromise) { await this.evaluationPromise; } - return { __proto__: null, module: this.module }; + return new ModuleJobResult(this.module, undefined); } if (status < kInstantiated) { // Either a fresh module - links were already resolved synchronously in the constructor - @@ -680,7 +557,7 @@ class ModuleJobSync extends ModuleJobBase { } await this.evaluationPromise; this.evaluationPromise = undefined; - return { __proto__: null, module: this.module }; + return new ModuleJobResult(this.module, undefined); } // No top-level `await`: evaluate synchronously try { @@ -689,7 +566,7 @@ class ModuleJobSync extends ModuleJobBase { explainCommonJSGlobalLikeNotDefinedError(evaluateError, this.module.url, this.module.hasTopLevelAwait); throw evaluateError; } - return { __proto__: null, module: this.module }; + return new ModuleJobResult(this.module, undefined); } // Evaluate this module synchronously, pausing at the first line of user land JS @@ -708,14 +585,11 @@ class ModuleJobSync extends ModuleJobBase { // TODO(joyeecheung): Reject graphs with top-level await _before_ instantiation, so that the // async graph error supersedes instantiation (mismatch export) errors in the graph. this.instantiateSync(); - // On the deprecated async loader hook worker thread, dependencies linked by an - // earlier import may not be walkable synchronously, so double-check with - // V8 now that the graph is instantiated. this.throwIfAsyncGraph(parent); setHasStartedUserESMExecution(); try { const namespace = this.#evaluateSync(); - return { __proto__: null, module: this.module, namespace }; + return new ModuleJobResult(this.module, namespace); } catch (e) { explainCommonJSGlobalLikeNotDefinedError(e, this.module.url, this.module.hasTopLevelAwait); throw e; diff --git a/lib/internal/modules/esm/module_map.js b/lib/internal/modules/esm/module_map.js index 207515573c79..05a6c3082d28 100644 --- a/lib/internal/modules/esm/module_map.js +++ b/lib/internal/modules/esm/module_map.js @@ -20,7 +20,8 @@ const { validateString } = require('internal/validators'); * Future resolutions of the same input (specifier, parent URL and import attributes) * must return the same result if the first attempt was successful, per * https://tc39.es/ecma262/#sec-HostLoadImportedModule. - * This cache is *not* used when custom loaders are registered. + * Only results of the default resolver are cached; results returned by + * `module.registerHooks()` resolve hooks are not. */ class ResolveCache extends SafeMap { /** diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index ac057127a717..1581a1b3942c 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -7,6 +7,7 @@ const { JSONStringify, ObjectGetOwnPropertyNames, ObjectPrototypeHasOwnProperty, + ObjectSetPrototypeOf, RegExpPrototypeExec, RegExpPrototypeSymbolReplace, SafeSet, @@ -946,12 +947,12 @@ function defaultResolve(specifier, context = kEmptyObject) { protocol = parsed.protocol; if (protocol === 'data:') { - return { __proto__: null, url: parsed.href }; + return ObjectSetPrototypeOf({ url: parsed.href }, null); } } protocol ??= parsed?.protocol; - if (protocol === 'node:') { return { __proto__: null, url: specifier }; } + if (protocol === 'node:') { return ObjectSetPrototypeOf({ url: specifier }, null); } const isMain = parentURL === undefined; @@ -989,13 +990,15 @@ function defaultResolve(specifier, context = kEmptyObject) { throw error; } - return { - __proto__: null, + // The result is cached by the loader and read on every later resolution of the same + // request, so null the prototype of a plain literal instead of using a + // `{ __proto__: null }` literal, which V8 would keep in dictionary mode. + return ObjectSetPrototypeOf({ // Do NOT cast `url` to a string: that will work even when there are real // problems, silencing them url: url.href, format: defaultGetFormatWithoutErrors(url, context), - }; + }, null); } /** diff --git a/lib/internal/modules/esm/shared_constants.js b/lib/internal/modules/esm/shared_constants.js deleted file mode 100644 index 4200bc87367d..000000000000 --- a/lib/internal/modules/esm/shared_constants.js +++ /dev/null @@ -1,25 +0,0 @@ -// This file contains the definition for the constant values that must be -// available to both the main thread and the loader thread. - -'use strict'; - -/* -The shared memory area is divided in 1 32-bit long section. It has to be 32-bit long as -`Atomics.notify` only works with `Int32Array` objects. - ---32-bits-- - ^ - | - | -WORKER_TO_MAIN_THREAD_NOTIFICATION - -WORKER_TO_MAIN_THREAD_NOTIFICATION is only used to send notifications, its value is going to -increase every time the worker sends a notification to the main thread. - -*/ - -module.exports = { - WORKER_TO_MAIN_THREAD_NOTIFICATION: 0, - - SHARED_MEMORY_BYTE_LENGTH: 1 * 4, -}; diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 583b6d1fe91d..100f791b98ee 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -17,13 +17,9 @@ const { globalThis, } = primordials; -const { - compileFunctionForCJSLoader, -} = internalBinding('contextify'); - const { BuiltinModule } = require('internal/bootstrap/realm'); const assert = require('internal/assert'); -const { dirname, extname } = require('path'); +const { dirname } = require('path'); const { assertBufferSource, loadBuiltinModule, @@ -45,22 +41,20 @@ const { findLongestRegisteredExtension, resolveForCJSWithHooks, loadSourceForCJSWithHooks, - populateCJSExportsFromESM, } = require('internal/modules/cjs/loader'); -const { fileURLToPath, pathToFileURL, URL } = require('internal/url'); +const { fileURLToPath, URL } = require('internal/url'); const { isAnyArrayBuffer } = require('internal/util/types'); let debug = require('internal/util/debuglog').debuglog('esm', (fn) => { debug = fn; }); -const { emitExperimentalWarning, kEmptyObject, setOwnProperty, isWindows } = require('internal/util'); +const { emitExperimentalWarning, setOwnProperty, isWindows } = require('internal/util'); const { ERR_INVALID_RETURN_PROPERTY_VALUE, ERR_UNKNOWN_BUILTIN_MODULE, ERR_WEBASSEMBLY_NOT_SUPPORTED, } = require('internal/errors').codes; -const { maybeCacheSourceMap } = require('internal/source_map/source_map_cache'); const moduleWrap = internalBinding('module_wrap'); -const { ModuleWrap, kEvaluationPhase } = moduleWrap; +const { ModuleWrap } = moduleWrap; const { getSourceSync } = require('internal/modules/esm/load'); @@ -101,108 +95,9 @@ translators.set('module', function moduleStrategy(url, translateContext, parentU return module; }); -const { requestTypes: { kRequireInImportedCJS } } = require('internal/modules/esm/utils'); const kShouldSkipModuleHooks = { __proto__: null, shouldSkipModuleHooks: true }; const kShouldNotSkipModuleHooks = { __proto__: null, shouldSkipModuleHooks: false }; -/** - * This may be eventually removed when module.register() reaches end-of-life. - * - * Loads a CommonJS module via the ESM Loader sync CommonJS translator. - * This translator creates its own version of the `require` function passed into CommonJS modules. - * Any monkey patches applied to the CommonJS Loader will not affect this module. - * Any `require` calls in this module will load all children in the same way. - * @param {import('internal/modules/cjs/loader').Module} module - The module to load. - * @param {string} source - The source code of the module. - * @param {string} url - The URL of the module. - * @param {string} filename - The filename of the module. - * @param {boolean} isMain - Whether the module is the entrypoint - * @param {TranslateContext} translateContext Context for the translator - */ -function loadCJSModuleWithSpecialRequire(module, source, url, filename, isMain, translateContext) { - // Use the full URL as the V8 resource name so that any search params - // (e.g. ?node-test-mock) are preserved in coverage reports. - const compileResult = compileFunctionForCJSLoader(source, url, false /* is_sea_main */, false); - - const { function: compiledWrapper, sourceMapURL, sourceURL } = compileResult; - // Cache the source map for the cjs module if present. - if (sourceMapURL) { - maybeCacheSourceMap(url, source, module, false, sourceURL, sourceMapURL); - } - const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); - const __dirname = dirname(filename); - // eslint-disable-next-line node-core/func-name-matching,func-style - const requireFn = function require(specifier) { - let importAttributes = kEmptyObject; - if (!StringPrototypeStartsWith(specifier, 'node:') && !BuiltinModule.normalizeRequirableId(specifier)) { - // TODO: do not depend on the monkey-patchable CJS loader here. - const path = CJSModule._resolveFilename(specifier, module); - switch (extname(path)) { - case '.json': - importAttributes = { __proto__: null, type: 'json' }; - break; - case '.node': - // If it gets here in the translators, the hooks must have already been invoked - // in the loader. Skip them in the synthetic module evaluation step. - return wrapModuleLoad(specifier, module, false, kShouldSkipModuleHooks); - default: - // fall through - } - specifier = `${pathToFileURL(path)}`; - } - - // NOTE: This re-invented require() is only used on the loader-hook worker thread. - // On the main thread, the authentic require() is used instead (fixed by #60380). - const request = { specifier, attributes: importAttributes, phase: kEvaluationPhase, __proto__: null }; - const job = cascadedLoader.getOrCreateModuleJob(url, request, kRequireInImportedCJS); - job.runSync(module); - let mod = cjsCache.get(job.url); - assert(job.module, `Imported CJS module ${url} failed to load module ${job.url} using require() due to race condition`); - - if (job.module.synthetic) { - assert(mod, `Imported CJS module ${url} failed to load module ${job.url} using require() due to missed cache`); - return mod.exports; - } - - // The module being required is a source text module. - if (!mod) { - mod = cjsEmplaceModuleCacheEntry(job.url); - cjsCache.set(job.url, mod); - } - // The module has been cached by the re-invented require. Update the exports object - // from the namespace object and return the evaluated exports. - if (!mod.loaded) { - debug('populateCJSExportsFromESM from require(esm) in imported CJS', url, mod, job.module); - populateCJSExportsFromESM(mod, job.module, job.module.getNamespace()); - mod.loaded = true; - } - return mod.exports; - }; - setOwnProperty(requireFn, 'resolve', function resolve(specifier) { - if (!StringPrototypeStartsWith(specifier, 'node:')) { - const { - filename, url: resolvedURL, - } = resolveForCJSWithHooks(specifier, module, false, kShouldNotSkipModuleHooks); - if (specifier !== filename) { - specifier = resolvedURL ?? `${pathToFileURL(filename)}`; - } - } - - const request = { specifier, __proto__: null, attributes: kEmptyObject }; - // Skip sync hooks in resolveSync since resolveForCJSWithHooks already ran them above. - const { url: resolvedURL } = cascadedLoader.resolveSync(url, request, /* shouldSkipSyncHooks */ true); - return urlToFilename(resolvedURL); - }); - setOwnProperty(requireFn, 'main', process.mainModule); - - FunctionPrototypeCall(compiledWrapper, module.exports, - module.exports, requireFn, module, filename, __dirname); - setOwnProperty(module, 'loaded', true); -} - -// TODO: can we use a weak map instead? -const cjsCache = new SafeMap(); - /** * Creates a ModuleWrap object for a CommonJS module. * @param {string} url - The URL of the module. @@ -226,7 +121,6 @@ function createCJSModuleWrap(url, translateContext, parentURL) { } const { exportNames, module } = cjsPreparseModuleExports(filename, source, sourceFormat); - cjsCache.set(url, module); const wrapperNames = [...exportNames]; if (!exportNames.has('default')) { @@ -244,19 +138,7 @@ function createCJSModuleWrap(url, translateContext, parentURL) { debug(`Loading CJSModule ${url}`); if (!module.loaded) { - // For backward-compatibility, it's possible for async hooks to return a nullish value for - // CJS source associated with a `file:` URL - that usually means the source is not - // customized (is loaded by default load) or the hook author wants it to be reloaded - // through CJS routine. In this case, the source is obtained by calling the - // Module._load(). - if (translateContext.translatorKey === 'commonjs-sync' || - translateContext.isSourceLoadedSynchronously || - translateContext.source == null) { - loadCJSModuleWithModuleLoad(module, source, url, filename, !!isMain, translateContext); - } else { // CommonJS with source customized by async hooks - // This may be eventually removed when module.register() reaches end-of-life. - loadCJSModuleWithSpecialRequire(module, source, url, filename, !!isMain, translateContext); - } + loadCJSModuleWithModuleLoad(module, source, url, filename, !!isMain, translateContext); } let exports; @@ -298,7 +180,6 @@ function createCJSNoSourceModuleWrap(url, parentURL) { const filename = urlToFilename(url); const module = cjsEmplaceModuleCacheEntry(filename); - cjsCache.set(url, module); if (isMain) { setOwnProperty(process, 'mainModule', module); @@ -333,25 +214,10 @@ translators.set('commonjs-sync', function requireCommonJS(url, translateContext, return createCJSModuleWrap(url, translateContext, parentURL); }); -// Handle CommonJS modules referenced by `require` calls using re-invented require. -// This path is only used by require() from imported CJS customized by the *async* -// loader hooks. -translators.set('require-commonjs', (url, translateContext, parentURL) => { - return createCJSModuleWrap(url, translateContext, parentURL); -}); - -// Handle TypeScript CommonJS modules referenced by `require` calls using re-invented require. -// This path is only used by require() from imported CJS customized by the *async* -// loader hooks. -translators.set('require-commonjs-typescript', (url, translateContext, parentURL) => { - translateContext.source = stripTypeScriptModuleTypes(stringify(translateContext.source), url); - return createCJSModuleWrap(url, translateContext, parentURL); -}); - // This goes through Module._load to accommodate monkey-patchers. /** * Loads a CommonJS module through Module._load to accommodate monkey-patchers. - * If the module was resolved by synchronous hooks (i.e. not by the default resolver), + * If the module was resolved by hooks (i.e. not by the default resolver), * passes the pre-resolved information and source to Module._load to avoid * re-resolving and re-loading. * @param {import('internal/modules/cjs/loader').Module} module - The module to load. @@ -483,7 +349,6 @@ translators.set('builtin', function builtinStrategy(url, translateContext) { // Slice 'node:' scheme const id = StringPrototypeSlice(url, 5); const module = loadBuiltinModule(id, url); - cjsCache.set(url, module); if (!StringPrototypeStartsWith(url, 'node:') || !module) { throw new ERR_UNKNOWN_BUILTIN_MODULE(url); } @@ -545,7 +410,6 @@ translators.set('json', function jsonStrategy(url, translateContext) { if (shouldCheckAndPopulateCJSModuleCache) { CJSModule._cache[modulePath] = module; } - cjsCache.set(url, module); return new ModuleWrap(url, undefined, ['default'], function() { debug(`Parsing JSONModule ${url}`); this.setExport('default', module.exports); diff --git a/lib/internal/modules/esm/utils.js b/lib/internal/modules/esm/utils.js index 8937b8a61298..b8c8b10d3867 100644 --- a/lib/internal/modules/esm/utils.js +++ b/lib/internal/modules/esm/utils.js @@ -296,14 +296,10 @@ async function importModuleDynamicallyCallback(referrerSymbol, specifier, phase, throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING(); } -let _shouldSpawnLoaderHookWorker = true; /** * Initializes handling of ES modules. - * @param {boolean} [shouldSpawnLoaderHookWorker] Whether the custom loader worker - * should be spawned later. */ -function initializeESM(shouldSpawnLoaderHookWorker = true) { - _shouldSpawnLoaderHookWorker = shouldSpawnLoaderHookWorker; +function initializeESM() { initializeDefaultConditions(); // Setup per-realm callbacks that locate data or callbacks that we keep // track of for different ESM modules. @@ -311,15 +307,6 @@ function initializeESM(shouldSpawnLoaderHookWorker = true) { setImportModuleDynamicallyCallback(importModuleDynamicallyCallback); } -/** - * Determine whether the custom loader worker should be spawned when initializing - * the singleton ESM loader. - * @returns {boolean} - */ -function shouldSpawnLoaderHookWorker() { - return _shouldSpawnLoaderHookWorker; -} - const SourceTextModuleTypes = { kInternal: 'internal', // TODO(joyeecheung): support internal ESM. kEmbedder: 'embedder', // Embedder ESM, also used by SEA @@ -391,12 +378,11 @@ function compileSourceTextModule(url, source, type, context = kEmptyObject) { const kImportInImportedESM = Symbol('kImportInImportedESM'); const kImportInRequiredESM = Symbol('kImportInRequiredESM'); -const kRequireInImportedCJS = Symbol('kRequireInImportedCJS'); /** - * @typedef {kImportInImportedESM | kImportInRequiredESM | kRequireInImportedCJS} ModuleRequestType + * @typedef {kImportInImportedESM | kImportInRequiredESM} ModuleRequestType */ -const requestTypes = { kImportInImportedESM, kImportInRequiredESM, kRequireInImportedCJS }; +const requestTypes = { kImportInImportedESM, kImportInRequiredESM }; module.exports = { embedder_module_hdo, @@ -404,7 +390,6 @@ module.exports = { initializeESM, getDefaultConditions, getConditionsSet, - shouldSpawnLoaderHookWorker, compileSourceTextModule, SourceTextModuleTypes, requestTypes, diff --git a/lib/internal/modules/esm/worker.js b/lib/internal/modules/esm/worker.js deleted file mode 100644 index 7d023059a4b0..000000000000 --- a/lib/internal/modules/esm/worker.js +++ /dev/null @@ -1,324 +0,0 @@ -'use strict'; - -const { - AtomicsAdd, - AtomicsNotify, - DataViewPrototypeGetBuffer, - Int32Array, - PromisePrototypeThen, - ReflectApply, - SafeSet, - TypedArrayPrototypeGetBuffer, -} = primordials; -const assert = require('internal/assert'); -const { clearImmediate, setImmediate } = require('timers'); -const { - hasUncaughtExceptionCaptureCallback, -} = require('internal/process/execution'); -const { - isArrayBuffer, - isDataView, - isTypedArray, -} = require('util/types'); - -const { getOptionValue } = require('internal/options'); -const { - loadPreloadModules, - initializeModuleLoaders, - initializeFrozenIntrinsics, -} = require('internal/process/pre_execution'); -const { receiveMessageOnPort } = require('internal/worker/io'); -const { - WORKER_TO_MAIN_THREAD_NOTIFICATION, -} = require('internal/modules/esm/shared_constants'); -const { isMarkedAsUntransferable } = require('internal/buffer'); -const { getCWDURL } = require('internal/util'); -const { isCascadedLoaderInitialized, getOrInitializeCascadedLoader } = require('internal/modules/esm/loader'); -const { AsyncLoaderHooksOnLoaderHookWorker } = require('internal/modules/esm/hooks'); -const { enableWorkerCondition } = require('internal/modules/helpers'); - -/** - * Register asynchronous module loader customization hooks. This should only be run in the loader - * hooks worker. In a non-loader-hooks thread, if any asynchronous loader hook is registered, the - * ModuleLoader#asyncLoaderHooks are initialized to be AsyncLoaderHooksProxiedToLoaderHookWorker - * which posts the messages to the async loader hook worker thread. - * When no asynchronous loader hook is registered, the loader hook worker is not spawned and module - * loading is entiredly done in-thread. - * @returns {Promise<AsyncLoaderHooksOnLoaderHookWorker>} - */ -async function initializeAsyncLoaderHooksOnLoaderHookWorker() { - const customLoaderURLs = getOptionValue('--experimental-loader'); - - // The worker thread spawned for handling asynchronous loader hooks should not - // further spawn other hook threads or there will be an infinite recursion. - const shouldSpawnLoaderHookWorker = false; - // The worker thread for async loader hooks will preload user modules itself in - // initializeAsyncLoaderHooksOnLoaderHookWorker(). - const shouldPreloadModules = false; - initializeModuleLoaders({ shouldSpawnLoaderHookWorker, shouldPreloadModules }); - - assert(!isCascadedLoaderInitialized(), - 'ModuleLoader should be initialized in initializeAsyncLoaderHooksOnLoaderHookWorker()'); - const asyncLoaderHooks = new AsyncLoaderHooksOnLoaderHookWorker(); - getOrInitializeCascadedLoader(asyncLoaderHooks); - - // We need the async loader hooks to be set _before_ we start invoking - // `--require`, otherwise loops can happen because a `--require` script - // might call `register(...)` before we've installed ourselves. These - // global values are magically set in `initializeModuleLoaders` just for us and - // we call them in the correct order. - // N.B. This block appears here specifically in order to ensure that - // `--require` calls occur before `--loader` ones do. - loadPreloadModules(); - initializeFrozenIntrinsics(); - - const parentURL = getCWDURL().href; - for (let i = 0; i < customLoaderURLs.length; i++) { - await asyncLoaderHooks.register(customLoaderURLs[i], parentURL); - } - - return asyncLoaderHooks; -} - -/** - * Transfers an ArrayBuffer, TypedArray, or DataView to a worker thread. - * @param {boolean} hasError - Whether an error occurred during transfer. - * @param {ArrayBuffer[] | TypedArray | DataView} source - The data to transfer. - * @returns {ArrayBuffer[]|undefined} - */ -function transferArrayBuffer(hasError, source) { - if (hasError || source == null) { return; } - let arrayBuffer; - if (isArrayBuffer(source)) { - arrayBuffer = source; - } else if (isTypedArray(source)) { - arrayBuffer = TypedArrayPrototypeGetBuffer(source); - } else if (isDataView(source)) { - arrayBuffer = DataViewPrototypeGetBuffer(source); - } - if (arrayBuffer && !isMarkedAsUntransferable(arrayBuffer)) { - return [arrayBuffer]; - } -} - -/** - * Wraps a message with a status and body, and serializes the body if necessary. - * @param {string} status - The status of the message. - * @param {any} body - The body of the message. - * @returns {{status: string, body: any}} - */ -function wrapMessage(status, body) { - if (status === 'success' || body === null || - (typeof body !== 'object' && - typeof body !== 'function' && - typeof body !== 'symbol')) { - return { status, body }; - } - - let serialized; - let serializationFailed; - try { - const { serializeError } = require('internal/error_serdes'); - serialized = serializeError(body); - } catch { - serializationFailed = true; - } - - return { - status, - body: { - serialized, - serializationFailed, - }, - }; -} - -/** - * Initializes the loader hooks worker thread with customized asynchronous module loading hooks. - * @param {SharedArrayBuffer} lock - The lock used to synchronize communication between the worker and the main thread. - * @param {MessagePort} syncCommPort - The message port used for synchronous communication between the worker and the - * main thread. - * @param {(err: Error, origin?: string) => void} errorHandler - The function to use for uncaught exceptions. - * @returns {Promise<void>} A promise that resolves when the worker thread has been initialized. - */ -async function customizedModuleWorker(lock, syncCommPort, errorHandler) { - let asyncLoaderHooks; - let initializationError; - let hasInitializationError = false; - - { - // If a custom hook is calling `process.exit`, we should wake up the main thread - // so it can detect the exit event. - const { exit } = process; - process.exit = function(code) { - syncCommPort.postMessage(wrapMessage('exit', code ?? process.exitCode)); - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - return ReflectApply(exit, this, arguments); - }; - } - - try { - asyncLoaderHooks = await initializeAsyncLoaderHooksOnLoaderHookWorker(); - } catch (exception) { - // If there was an error while parsing and executing a user loader, for example if because a - // loader contained a syntax error, then we need to send the error to the main thread so it can - // be thrown and printed. - hasInitializationError = true; - initializationError = exception; - } - - syncCommPort.on('message', handleMessage); - - if (hasInitializationError) { - syncCommPort.postMessage(wrapMessage('error', initializationError)); - } else { - syncCommPort.postMessage(wrapMessage('success')); - } - - // We're ready, so unlock the main thread. - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - let immediate; - /** - * Checks for messages on the syncCommPort and handles them asynchronously. - */ - function checkForMessages() { - immediate = setImmediate(checkForMessages).unref(); - // We need to let the event loop tick a few times to give the main thread a chance to send - // follow-up messages. - const response = receiveMessageOnPort(syncCommPort); - - if (response !== undefined) { - PromisePrototypeThen(handleMessage(response.message), undefined, errorHandler); - } - } - - const unsettledResponsePorts = new SafeSet(); - - process.on('beforeExit', () => { - for (const port of unsettledResponsePorts) { - port.postMessage(wrapMessage('never-settle')); - } - unsettledResponsePorts.clear(); - - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - - // Attach back the event handler. - syncCommPort.on('message', handleMessage); - // Also check synchronously for a message, in case it's already there. - clearImmediate(immediate); - checkForMessages(); - // We don't need the sync check after this tick, as we already have added the event handler. - clearImmediate(immediate); - // Add some work for next tick so the worker cannot exit. - setImmediate(() => {}); - }); - - /** - * Handles incoming messages from the main thread or other workers. - * @param {object} options - The options object. - * @param {string} options.method - The name of the hook. - * @param {Array} options.args - The arguments to pass to the method. - * @param {MessagePort} options.port - The message port to use for communication. - */ - async function handleMessage({ method, args, port }) { - // Each potential exception needs to be caught individually so that the correct error is sent to - // the main thread. - let hasError = false; - let shouldRemoveGlobalErrorHandler = false; - assert(typeof asyncLoaderHooks[method] === 'function', `${method} is not implemented in the loader worker`); - if (port == null && !hasUncaughtExceptionCaptureCallback()) { - // When receiving sync messages, we want to unlock the main thread when there's an exception. - process.on('uncaughtException', errorHandler); - shouldRemoveGlobalErrorHandler = true; - } - - // We are about to yield the execution with `await ReflectApply` below. In case the code - // following the `await` never runs, we remove the message handler so the `beforeExit` event - // can be triggered. - syncCommPort.off('message', handleMessage); - - // We keep checking for new messages to not miss any. - clearImmediate(immediate); - immediate = setImmediate(checkForMessages).unref(); - - unsettledResponsePorts.add(port ?? syncCommPort); - - let response; - try { - response = await ReflectApply(asyncLoaderHooks[method], asyncLoaderHooks, args); - } catch (exception) { - hasError = true; - response = exception; - } - - unsettledResponsePorts.delete(port ?? syncCommPort); - - // Send the method response (or exception) to the main thread. - try { - (port ?? syncCommPort).postMessage( - wrapMessage(hasError ? 'error' : 'success', response), - transferArrayBuffer(hasError, response?.source), - ); - } catch (exception) { - // Or send the exception thrown when trying to send the response. - (port ?? syncCommPort).postMessage(wrapMessage('error', exception)); - } - - if (shouldRemoveGlobalErrorHandler) { - process.off('uncaughtException', errorHandler); - } - - syncCommPort.off('message', handleMessage); - // We keep checking for new messages to not miss any. - clearImmediate(immediate); - immediate = setImmediate(checkForMessages).unref(); - // To prevent the main thread from terminating before this function completes after unlocking, - // the following process is executed at the end of the function. - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - } -} - -/** - * Initializes a worker thread for a module with customized hooks. - * ! Run everything possible within this function so errors get reported. - * @param {{lock: SharedArrayBuffer, workerCondition: boolean}} workerData - The lock used to - * synchronize with the main thread, and whether the spawning thread is a Web Worker. - * @param {MessagePort} syncCommPort - The communication port used to communicate with the main thread. - * @returns {object} - */ -module.exports = function setupModuleWorker(workerData, syncCommPort) { - const lock = new Int32Array(workerData.lock); - if (workerData.workerCondition) { - enableWorkerCondition(); - } - - /** - * Handles errors that occur in the worker thread. - * @param {Error} err - The error that occurred. - * @param {string} [origin] - The origin of the error. - */ - function errorHandler(err, origin = 'unhandledRejection') { - AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1); - AtomicsNotify(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION); - process.off('uncaughtException', errorHandler); - if (hasUncaughtExceptionCaptureCallback()) { - process._fatalException(err); - return; - } - internalBinding('errors').triggerUncaughtException( - err, - origin === 'unhandledRejection', - ); - } - - return PromisePrototypeThen( - customizedModuleWorker(lock, syncCommPort, errorHandler), - undefined, - errorHandler, - ); -}; diff --git a/lib/internal/modules/package_json_reader.js b/lib/internal/modules/package_json_reader.js index 71612c27cc5c..d043694c8c04 100644 --- a/lib/internal/modules/package_json_reader.js +++ b/lib/internal/modules/package_json_reader.js @@ -411,11 +411,9 @@ function findPackageJSON(specifier, base = 'data:') { defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve; try { - // TODO(@JakobJingleheimer): Detect whether findPackageJSON is being used within a loader - // (possibly piggyback on `isForAsyncLoaderHookWorker` from the loader?) and if so: - // - When inside, use the default resolve - // - (I think it's impossible to use the chain because of re-entry & a deadlock from atomics). - // - When outside, use cascadedLoader.resolveSync (not implemented yet, but the pieces exist). + // TODO(@JakobJingleheimer): This always uses the default resolver and so ignores any + // module.registerHooks() resolve hooks. Using cascadedLoader.resolveSync would apply them, + // but that needs to handle re-entry when findPackageJSON is called from inside a hook. resolvedTarget = defaultResolve(specifier, { parentURL: `${parentURL}` }).url; } catch (err) { if (err.code === 'ERR_UNSUPPORTED_DIR_IMPORT') { diff --git a/lib/internal/modules/run_main.js b/lib/internal/modules/run_main.js index b0d7d4845eaf..ec97f46f5a0f 100644 --- a/lib/internal/modules/run_main.js +++ b/lib/internal/modules/run_main.js @@ -51,17 +51,12 @@ function resolveMainPath(main) { * @returns {boolean} */ function shouldUseESMLoader(mainPath) { - /** - * @type {string[]} userLoaders A list of custom loaders registered by the user - * (or an empty list when none have been registered). - */ - const userLoaders = getOptionValue('--experimental-loader'); /** * @type {string[]} userImports A list of preloaded modules registered by the user * (or an empty list when none have been registered). */ const userImports = getOptionValue('--import'); - if (userLoaders.length > 0 || userImports.length > 0) { return true; } + if (userImports.length > 0) { return true; } // Determine the module format of the entry point. if (mainPath && StringPrototypeEndsWith(mainPath, '.mjs')) { return true; } @@ -96,8 +91,6 @@ async function asyncRunEntryPointWithESMLoader(callback) { for (let i = 0; i < userImports.length; i++) { await cascadedLoader.import(userImports[i], parentURL, kEmptyObject); } - } else { - cascadedLoader.waitForAsyncLoaderHookInitialization(); } // Any --import above may have registered a VFS provider, so mount now (no-op // if prepareExecution already mounted in the no-import case). @@ -175,11 +168,10 @@ function executeUserEntryPoint(main = process.argv[1]) { const mainPath = resolvedMain || main; const mainURL = getOptionValue('--entry-url') ? new URL(mainPath, getCWDURL()) : pathToFileURL(mainPath); - // When no async loader hooks or --import are registered, load the entry point + // When no --import preloads are registered, load the entry point // directly. The graph is loaded and linked synchronously, and evaluated // synchronously too unless it contains top-level await. - if (getOptionValue('--experimental-loader').length === 0 && - getOptionValue('--import').length === 0) { + if (getOptionValue('--import').length === 0) { const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader(); const job = cascadedLoader.importForEntryPoint(mainURL.href); if (job === undefined) { diff --git a/lib/internal/per_context/primordials.js b/lib/internal/per_context/primordials.js index 2e610f4ab508..582c91126b3f 100644 --- a/lib/internal/per_context/primordials.js +++ b/lib/internal/per_context/primordials.js @@ -187,12 +187,14 @@ function copyPrototype(src, dest, prefix) { 'AggregateError', 'Array', 'ArrayBuffer', + 'AsyncDisposableStack', 'BigInt', 'BigInt64Array', 'BigUint64Array', 'Boolean', 'DataView', 'Date', + 'DisposableStack', 'Error', 'EvalError', 'FinalizationRegistry', @@ -212,6 +214,7 @@ function copyPrototype(src, dest, prefix) { 'RegExp', 'Set', 'String', + 'SuppressedError', 'Symbol', 'SyntaxError', 'TypeError', diff --git a/lib/internal/process/permission.js b/lib/internal/process/permission.js index f3ed889e8c19..a07d75cb6e04 100644 --- a/lib/internal/process/permission.js +++ b/lib/internal/process/permission.js @@ -10,6 +10,11 @@ const permission = internalBinding('permission'); const { validateString } = require('internal/validators'); const { isUint8Array } = require('internal/util/types'); const { isURL, fileURLToPath } = require('internal/url'); +const { + codes: { + ERR_INVALID_ARG_VALUE, + }, +} = require('internal/errors'); let _permission; let _audit; @@ -65,7 +70,12 @@ module.exports = ObjectFreeze({ }, drop(scope, reference) { validateString(scope, 'scope'); - permission.drop(scope, normalizeReference(scope, reference, 'reference')); + reference = normalizeReference(scope, reference, 'reference'); + // An empty reference would otherwise drop the whole scope. + if (reference != null && reference.length === 0) { + throw new ERR_INVALID_ARG_VALUE('reference', reference, 'must not be empty'); + } + permission.drop(scope, reference); }, availableFlags() { if (_ffi === undefined) { diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js index 0f5aaf857aeb..b5933f4e9d61 100644 --- a/lib/internal/process/pre_execution.js +++ b/lib/internal/process/pre_execution.js @@ -51,7 +51,6 @@ function prepareMainThreadExecution(expandArgv1 = false, initializeModules = tru expandArgv1, initializeModules, isMainThread: true, - shouldSpawnLoaderHookWorker: initializeModules, shouldPreloadModules: initializeModules, }); } @@ -61,7 +60,6 @@ function prepareTestRunnerMainExecution(loadUserModules = true) { expandArgv1: false, initializeModules: true, isMainThread: true, - shouldSpawnLoaderHookWorker: loadUserModules, shouldPreloadModules: loadUserModules, }); } @@ -73,7 +71,6 @@ function prepareWorkerThreadExecution() { // Module loader initialization in workers are delayed until the worker thread // is ready for execution. initializeModules: false, - shouldSpawnLoaderHookWorker: false, shouldPreloadModules: false, }); } @@ -84,8 +81,8 @@ function prepareShadowRealmExecution() { patchProcessObject(false); setupDebugEnv(); - // Disable custom loaders in ShadowRealm. - initializeModuleLoaders({ shouldSpawnLoaderHookWorker: false, shouldPreloadModules: false }); + // Preload modules are not supported in ShadowRealm. + initializeModuleLoaders({ shouldPreloadModules: false }); const { privateSymbols: { host_defined_option_symbol, @@ -107,7 +104,7 @@ function prepareShadowRealmExecution() { } function prepareExecution(options) { - const { expandArgv1, initializeModules, isMainThread, shouldSpawnLoaderHookWorker, shouldPreloadModules } = options; + const { expandArgv1, initializeModules, isMainThread, shouldPreloadModules } = options; refreshRuntimeOptions(); @@ -172,7 +169,7 @@ function prepareExecution(options) { setupVmModules(); if (initializeModules) { - initializeModuleLoaders({ shouldSpawnLoaderHookWorker, shouldPreloadModules }); + initializeModuleLoaders({ shouldPreloadModules }); } // Mount here only when there is no --import: those preloads run later (inside @@ -319,15 +316,13 @@ function warnAboutRemovedProxyEnvVars() { } function initializeModuleLoaders(options) { - const { shouldSpawnLoaderHookWorker, shouldPreloadModules } = options; + const { shouldPreloadModules } = options; // Initialize certain special module.Module properties and the CJS conditions. const { initializeCJS } = require('internal/modules/cjs/loader'); initializeCJS(); // Initialize the ESM loader and a few module callbacks. - // If shouldSpawnLoaderHookWorker is true, later when the ESM loader is instantiated on-demand, - // it will spawn a loader worker thread to handle async custom loader hooks. const { initializeESM } = require('internal/modules/esm/utils'); - initializeESM(shouldSpawnLoaderHookWorker); + initializeESM(); const { hasStartedUserCJSExecution, @@ -340,9 +335,7 @@ function initializeModuleLoaders(options) { if (getEmbedderOptions().hasEmbedderPreload) { runEmbedderPreload(); } - // Do not enable preload modules if custom loaders are disabled. - // For example, loader workers are responsible for doing this themselves. - // And preload modules are not supported in ShadowRealm as well. + // Preload modules are not supported in ShadowRealm. if (shouldPreloadModules) { loadPreloadModules(); } diff --git a/lib/internal/quic/quic.js b/lib/internal/quic/quic.js index 683eba6925ea..92942c26e17b 100644 --- a/lib/internal/quic/quic.js +++ b/lib/internal/quic/quic.js @@ -17,13 +17,12 @@ const { ObjectDefineProperties, ObjectKeys, PromisePrototypeThen, - PromiseResolve, PromiseWithResolvers, SafeSet, + SuppressedError, Symbol, SymbolAsyncDispose, SymbolAsyncIterator, - SymbolDispose, SymbolIterator, TypedArrayPrototypeGetByteLength, Uint8Array, @@ -134,16 +133,9 @@ const { } = require('internal/blob'); const { - drainableProtocol, kValidatedSource, } = require('internal/streams/iter/types'); -const { - convertChunks, - getWriterSignal, - toWriterUint8Array, -} = require('internal/streams/iter/utils'); - const { from: streamFrom, fromSync: streamFromSync, @@ -232,6 +224,10 @@ const { QuicStreamState, } = require('internal/quic/state'); +const { + getWriter, +} = require('internal/streams/iter/writer'); + const assert = require('internal/assert'); const { @@ -699,7 +695,7 @@ const endpointRegistry = new SafeSet(); /** * @callback OnStreamErrorCallback * @this {QuicStream} - * @param {any} error + * @param {Error} error * @returns {void} */ @@ -767,16 +763,16 @@ setCallbacks({ /** * Called when the underlying session C++ handle is closed either normally * or with an error. - * @param {number} errorType - * @param {bigint} code - * @param {string} [reason] - * @param {string} [errorName] Symbolic name for a recognized transport - * error code, including a decoded TLS alert for CRYPTO_ERROR; otherwise - * undefined. + * @param {Array} [error] Raw `[type, code, reason, errorName]` data. + * `errorName` is the symbolic name for a recognized transport error, + * including a decoded TLS alert for CRYPTO_ERROR; otherwise undefined. */ - onSessionClose(errorType, code, reason, errorName) { - debug('session close callback', errorType, code, reason, errorName); - this[kOwner][kFinishClose](errorType, code, reason, errorName); + onSessionClose(error) { + if (error !== undefined) { + error = convertQuicError(error); + } + debug('session close callback', error); + this[kOwner][kFinishClose](error); }, /** @@ -968,20 +964,16 @@ setCallbacks({ }, onStreamClose(error) { - // Called when the stream C++ handle has been closed. The error is - // either undefined (clean close) or a raw array [type, code, reason] - // from QuicError::ToV8Value. Convert to a proper Node.js Error. + // Called when the stream C++ handle has been closed. The error is either + // undefined (clean close) or a raw [type, code, reason, errorName] array + // from the session-aware native error conversion. if (!this[kOwner]) return; if (error !== undefined) { error = convertQuicError(error); } else if (!this[kOwner].destroyed) { - // The stream is closing cleanly, but it may have been reset by the - // peer (ReceiveStreamReset) or locally (resetStream). The C++ side - // records the reset code in state.resetCode. If set, surface the - // reset as the close error so stream.closed rejects -- the reset - // was an abnormal termination even if the session closed cleanly. - const resetCode = getQuicStreamState(this[kOwner]).resetCode; - if (resetCode !== undefined && resetCode > 0n) { + const state = getQuicStreamState(this[kOwner]); + if (state.resetCodeIsError) { + const resetCode = state.resetCode; error = makeQuicError( 'ERR_QUIC_APPLICATION_ERROR', 'QUIC application error', @@ -1240,14 +1232,12 @@ function invokeOnerror(fn, error) { if (isPromise(result)) { PromisePrototypeThen(result, undefined, (err) => { process.nextTick(() => { - // eslint-disable-next-line no-restricted-syntax throw new SuppressedError(err, error, err?.message); }); }); } } catch (err) { process.nextTick(() => { - // eslint-disable-next-line no-restricted-syntax throw new SuppressedError(err, error, err?.message); }); } @@ -1621,6 +1611,7 @@ class QuicStream { pendingClose: undefined, destroyError: undefined, stopSendingCode: undefined, + stopSendingCodeIsError: undefined, truncatedReads: undefined, reader: undefined, destroying: false, @@ -1733,15 +1724,15 @@ class QuicStream { // If we cancelled ourselves, check our own stop-sending code (not the // result mirrored by the remote peer) - if (inner.stopSendingCode > 0n) { + if (inner.stopSendingCodeIsError) { throw new QuicError('Stream aborted before FIN was received', { __proto__: null, errorCode: inner.stopSendingCode }); } - // Non-zero reset is always an error: + // A reset carrying an application error always fails the read. const peerResetCode = inner.state.resetCode; - if (peerResetCode > 0n) { + if (inner.state.resetCodeIsError) { throw new QuicError( `The QUIC stream was reset by the peer with error code ${peerResetCode}`, { __proto__: null, @@ -2215,261 +2206,28 @@ class QuicStream { const handle = this.#handle; const stream = this; - let closed = false; - let ending = false; - let errored = false; - let error = null; - let totalBytesWritten = 0; - let drainWakeup = null; - let pendingWrite = null; - let pendingEnd = null; - - function raceWithSignal(promise, signal) { - if (signal === undefined) return promise; - signal.throwIfAborted(); - - const deferred = PromiseWithResolvers(); - const onAbort = () => deferred.reject(signal.reason); - signal.addEventListener('abort', onAbort, { - __proto__: null, - once: true, - }); - PromisePrototypeThen( - promise, - (value) => { - signal.removeEventListener('abort', onAbort); - deferred.resolve(value); - }, - (reason) => { - signal.removeEventListener('abort', onAbort); - deferred.reject(reason); - }); - return deferred.promise; - } - - function waitForDrain(signal) { - drainWakeup ??= PromiseWithResolvers(); - return raceWithSignal(drainWakeup.promise, signal); - } - // Drain callback - C++ fires this when send buffer has space - stream[kDrain] = () => { - if (drainWakeup) { - drainWakeup.resolve(true); - drainWakeup = null; - } + function setDrainCallback(fn) { + stream[kDrain] = fn; }; - const onStopSending = stream[kStopSending]; - stream[kStopSending] = (reason) => { - if (!closed && !errored) { - errored = true; - error = reason; - if (drainWakeup != null) { - markPromiseAsHandled(drainWakeup.promise); - drainWakeup.reject(error); - drainWakeup = null; - } - } - FunctionPrototypeCall(onStopSending, stream, reason); + function setStopSendingCallback(fn) { + const onStopSending = stream[kStopSending]; + stream[kStopSending] = (reason) => { + fn(reason); + FunctionPrototypeCall(onStopSending, stream, reason); + }; }; - - // A note on backpressure handling: per the stream/iter spec, the default - // backpressure policy for writers is strict. One async write may wait for - // capacity; additional writes are rejected until it settles. - - function writeConvertedSync(chunk, token) { - const isPending = pendingWrite === token && token !== undefined; - // If the stream is closed, errored, or write-ended, we cannot accept - // more data. Refuse the sync write. - if (closed || errored || stream.#inner.state.writeEnded || - (ending && !isPending) || - (pendingWrite !== null && !isPending)) { - return false; - } - const len = TypedArrayPrototypeGetByteLength(chunk); - if (len === 0) return true; - // Refuse the write only when there is no available capacity at - // all. When writeDesiredSize > 0 we allow the write even if the - // chunk is larger than the remaining capacity -- the C++ side - // will accept the data into the DataQueue and - // UpdateWriteDesiredSize() will drop writeDesiredSize toward 0, - // at which point the standard drain mechanism takes over. - // This follows the iter-streams model where writes beyond the - // budget succeed and backpressure applies to *subsequent* writes. - if (stream.#inner.state.writeDesiredSize === 0) return false; - const result = handle.write([chunk]); - if (result === undefined) return false; - totalBytesWritten += len; - return true; - } - - function writeSync(chunk) { - return writeConvertedSync(toWriterUint8Array(chunk)); - } - - function write(chunk, options = kEmptyObject) { - chunk = toWriterUint8Array(chunk); - const signal = getWriterSignal(options); - return writeAsync(chunk, signal); - } - - async function writeAsync(chunk, signal) { - if (errored) throw error; - if (closed || ending || stream.#inner.state.writeEnded) { - throw new ERR_INVALID_STATE.TypeError('Writer is closed'); - } - signal?.throwIfAborted(); - - if (writeConvertedSync(chunk)) return; - await writeWhenDrained(chunk, writeConvertedSync, signal); - } - - async function writeWhenDrained(chunks, writeConverted, signal) { - if (pendingWrite !== null) { - throw new ERR_INVALID_STATE.RangeError( - 'Backpressure violation: too many pending writes. ' + - 'Await each write() call to respect backpressure.'); - } - if (stream.#inner.state.writeDesiredSize !== 0) { - throw new ERR_INVALID_STATE('Stream write buffer is full'); - } - - const done = PromiseWithResolvers(); - const token = { __proto__: null, done }; - pendingWrite = token; - try { - while (true) { - await waitForDrain(signal); - if (errored) throw error; - if (closed || stream.#inner.state.writeEnded) { - throw new ERR_INVALID_STATE.TypeError('Writer is closed'); - } - signal?.throwIfAborted(); - if (writeConverted(chunks, token)) return; - if (stream.#inner.state.writeDesiredSize !== 0) { - throw new ERR_INVALID_STATE('Stream write buffer is full'); - } - } - } finally { - if (pendingWrite === token) pendingWrite = null; - done.resolve(); - } - } - - function writevConvertedSync(chunks, token) { - const isPending = pendingWrite === token && token !== undefined; - if (closed || errored || stream.#inner.state.writeEnded || - (ending && !isPending) || - (pendingWrite !== null && !isPending)) { - return false; - } - let len = 0; - for (const c of chunks) len += TypedArrayPrototypeGetByteLength(c); - if (len === 0) return true; - if (stream.#inner.state.writeDesiredSize === 0) return false; - const result = handle.write(chunks); - if (result === undefined) return false; - totalBytesWritten += len; - return true; - } - - function writevSync(chunks) { - return writevConvertedSync(convertChunks(chunks)); - } - - function writev(chunks, options = kEmptyObject) { - chunks = convertChunks(chunks); - const signal = getWriterSignal(options); - return writevAsync(chunks, signal); - } - - async function writevAsync(chunks, signal) { - if (errored) throw error; - if (closed || ending || stream.#inner.state.writeEnded) { - throw new ERR_INVALID_STATE.TypeError('Writer is closed'); - } - signal?.throwIfAborted(); - - if (writevConvertedSync(chunks)) return; - await writeWhenDrained(chunks, writevConvertedSync, signal); - } - - function endSync() { - // Per the streams/iter spec, endSync and end follow a try-fallback - // pattern. That is, callers should try endSync first and if it returns - // -1, then they should call and await end(). This is a signal that sync - // end is not currently possible. However, we always support sync end - // here unless the stream is already errored. - if (errored) return -1; - - // If we're already closed, just return the total bytes written. - if (closed) return totalBytesWritten; - - // Accepted writes and existing drain waiters must settle before ending. - if (ending || pendingWrite !== null || drainWakeup !== null) return -1; - - // Fantastic, we can end synchronously! - handle.endWrite(); - closed = true; - return totalBytesWritten; - } - - function end(options = kEmptyObject) { - const signal = getWriterSignal(options); - return endAsync(signal); - } - - async function endAsync(signal) { - if (errored) throw error; - if (closed) return totalBytesWritten; - signal?.throwIfAborted(); - - // Per the streams/iter spec, endSync and end follow a try-fallback - // pattern. That is, callers should try endSync first and if it returns - // -1, then they should call and await end(). This is a signal that sync - // end is not currently possible. However, we always support sync end - // here unless the stream is already errored. - // While the user should have already called endSync, we call it again - // here to actually process the end request. At worst it's called twice. - const n = endSync(); - - // A return value of -1 indicates that endSync was not yet able to - // process the end request, either because we are errored or because we - // are awaiting drain. If we're errored, throw the error. If we're waiting - // for drain, await it and then try ending again. - - if (n >= 0) return n; - if (errored) throw error; - - if (pendingEnd === null) { - ending = true; - pendingEnd = finishEnd(); - } - return raceWithSignal(pendingEnd, signal); - } - - async function finishEnd() { - if (pendingWrite !== null) { - await pendingWrite.done.promise; - } - if (errored) throw error; - - if (drainWakeup !== null) { - await drainWakeup.promise; - } - if (errored) throw error; - - if (!stream.#inner.state.writeEnded) handle.endWrite(); - closed = true; - ending = false; - return totalBytesWritten; - } - - function fail(reason) { - if (closed || errored) return; - errored = true; - error = reason; + function writeEnded() { + return stream.#inner.state.writeEnded; + }; + function writeDesiredSize() { + return stream.#inner.state.writeDesiredSize; + }; + function writeChunks(chunks) { + return handle.write(chunks); + }; + function resetStream(error) { // `writer.fail()` is always an error path, so the wire code on // RESET_STREAM must never be `0n` (which means "no error" in // most application protocols). Resolve the code in priority @@ -2486,61 +2244,32 @@ class QuicStream { error.errorCode : getQuicSessionState(stream.#inner.session).internalErrorCode; handle.resetStream(code); - if (drainWakeup != null) { - markPromiseAsHandled(drainWakeup.promise); - drainWakeup.reject(error); - drainWakeup = null; - } - } - - const writer = { - __proto__: null, - get canWrite() { - if (closed || ending || errored || stream.#inner.state.writeEnded) { - return null; - } - return stream.#inner.state.writeDesiredSize > 0; - }, - writeSync, - write, - writevSync, - writev, - endSync, - end, - fail, - [drainableProtocol]() { - if (closed || ending || errored) return null; - // If a drain is already pending, return the existing promise. - if (drainWakeup != null) return drainWakeup.promise; - if (stream.#inner.state.writeDesiredSize > 0) return null; - drainWakeup = PromiseWithResolvers(); - return drainWakeup.promise; - }, - [SymbolAsyncDispose]() { - if (ending) return pendingEnd; - if (!closed && !errored) fail(); - return PromiseResolve(); - }, - [SymbolDispose]() { - if (!closed && !errored) fail(); - }, + }; + function endWrite() { + handle.endWrite(); }; - // Non-writable stream - return a pre-closed writer. - // A remote unidirectional stream is read-only and has no writable - // side. isLocal distinguishes locally-initiated (writable) from - // remotely-initiated (read-only) uni streams. - if (!handle || this.destroyed || inner.state.writeEnded || + function nonWritableStream() { + return !handle || stream.destroyed || (inner.direction === kStreamDirectionUnidirectional && - !inner.isLocal)) { - closed = true; - return inner.writer = writer; - } - - // Initialize the outbound DataQueue for streaming writes - handle.initStreamingSource(); - initStreamingBackpressure(this); + !inner.isLocal); + }; + function initStreamingSource() { + handle.initStreamingSource(); + initStreamingBackpressure(stream); + }; + const writer = getWriter({ + setDrainCallback, + setStopSendingCallback, + writeDesiredSize, + writeEnded, + writeChunks, + resetStream, + endWrite, + nonWritableStream, + initStreamingSource, + }); return inner.writer = writer; } @@ -2593,7 +2322,7 @@ class QuicStream { if (this.destroyed) return; const abortCode = validateQuicErrorCode(code, 'code'); this.#inner.stopSendingCode = abortCode; - this.#handle.stopSending(abortCode); + this.#inner.stopSendingCodeIsError = this.#handle.stopSending(abortCode); } /** @@ -3499,6 +3228,7 @@ class QuicSession { incremental = false, budget = kDefaultBudget, headers, + waitUntilAvailable = true, onheaders, ontrailers, oninfo, @@ -3507,10 +3237,10 @@ class QuicSession { validateOneOf(priority, 'options.priority', ['default', 'low', 'high']); validateBoolean(incremental, 'options.incremental'); - + validateBoolean(waitUntilAvailable, 'options.waitUntilAvailable'); const validatedBody = validateBody(body); - const handle = this.#handle.openStream(direction, validatedBody); + const handle = this.#handle.openStream(direction, waitUntilAvailable, validatedBody); if (handle === undefined) { throw new ERR_QUIC_OPEN_STREAM_FAILED(); } @@ -3921,22 +3651,18 @@ class QuicSession { } /** - * @param {number} errorType - * @param {bigint} code - * @param {string} [reason] - * @param {string} [errorName] + * @param {Error} [error] */ - [kFinishClose](errorType, code, reason, errorName) { - // If code is zero, then we closed without an error. Yay! We can destroy + [kFinishClose](error) { + // If the error is undefined, then we closed without an error. Yay! We can destroy // safely without specifying an error. - if (code === 0n) { + if (error === undefined) { debug('finishing closing the session with no error'); this.destroy(); return; } - debug('finishing closing the session with an error', - errorType, code, reason, errorName); + debug('finishing closing the session with an error', error); // If the local side initiated this close with an error code (via // close({ code })), this is an intentional shutdown; not an error. @@ -3946,44 +3672,7 @@ class QuicSession { return; } - // Otherwise, errorType indicates the type of error that occurred, code indicates - // the specific error, and reason is an optional string describing the error. - // code !== 0n here (the early return above handles code === 0n). - // The errorType values map to ngtcp2_ccerr_type: - // 0 = NGTCP2_CCERR_TYPE_TRANSPORT - // 1 = NGTCP2_CCERR_TYPE_APPLICATION - // 2 = NGTCP2_CCERR_TYPE_VERSION_NEGOTIATION - // 3 = NGTCP2_CCERR_TYPE_IDLE_CLOSE - // 4 = NGTCP2_CCERR_TYPE_DROP_CONN - // 5 = NGTCP2_CCERR_TYPE_RETRY - // The DROP_CONN/RETRY cases are typically intercepted before reaching - // here (DROP_CONN tears the connection down without notifying us, RETRY - // is server-only). The default branch is a safety net so any - // unexpected value still completes the close path - without it the - // session would leak with `closed` hanging forever. - switch (errorType) { - case 0: /* Transport Error */ - this.destroy(makeQuicError('ERR_QUIC_TRANSPORT_ERROR', - 'QUIC transport error', - 'transport', code, reason, errorName)); - break; - case 1: /* Application Error */ - this.destroy(makeQuicError('ERR_QUIC_APPLICATION_ERROR', - 'QUIC application error', - 'application', code, reason, errorName)); - break; - case 2: /* Version Negotiation Error */ - this.destroy(new ERR_QUIC_VERSION_NEGOTIATION_ERROR()); - break; - case 3: /* Idle close */ - this.destroy(); - break; - default: - this.destroy(makeQuicError('ERR_QUIC_TRANSPORT_ERROR', - 'QUIC transport error', - 'transport', code, reason, errorName)); - break; - } + this.destroy(error); } [kKeylog](line) { diff --git a/lib/internal/quic/state.js b/lib/internal/quic/state.js index 0a47e2e7adc8..0617987471f0 100644 --- a/lib/internal/quic/state.js +++ b/lib/internal/quic/state.js @@ -112,6 +112,7 @@ const { IDX_STATE_STREAM_WRITE_DESIRED_SIZE, IDX_STATE_STREAM_BUDGET, IDX_STATE_STREAM_RESET_CODE, + IDX_STATE_STREAM_RESET_CODE_IS_ERROR, IDX_STATE_STREAM_SIZE, } = internalBinding('quic'); @@ -153,6 +154,7 @@ assert(IDX_STATE_STREAM_WANTS_RESET !== undefined); assert(IDX_STATE_STREAM_WANTS_STOP_SENDING !== undefined); assert(IDX_STATE_STREAM_WRITE_DESIRED_SIZE !== undefined); assert(IDX_STATE_STREAM_RESET_CODE !== undefined); +assert(IDX_STATE_STREAM_RESET_CODE_IS_ERROR !== undefined); const kEmptyObject = { __proto__: null }; @@ -873,6 +875,14 @@ class QuicStreamState { handle, this.#offset + IDX_STATE_STREAM_RESET_CODE, kIsLittleEndian); } + /** @type {boolean} */ + get resetCodeIsError() { + const handle = this.#handle; + if (handle === undefined) return undefined; + return DataViewPrototypeGetUint8( + handle, this.#offset + IDX_STATE_STREAM_RESET_CODE_IS_ERROR) !== 0; + } + /** @type {bigint} */ get writeDesiredSize() { const handle = this.#handle; @@ -924,6 +934,7 @@ class QuicStreamState { wantsStopSending, early, resetCode, + resetCodeIsError, writeDesiredSize, budget, } = this; @@ -943,6 +954,7 @@ class QuicStreamState { wantsStopSending, early, resetCode: `${resetCode}`, + resetCodeIsError, writeDesiredSize, budget, }; @@ -979,6 +991,7 @@ class QuicStreamState { wantsStopSending, early, resetCode, + resetCodeIsError, writeDesiredSize, budget, } = this; @@ -998,6 +1011,7 @@ class QuicStreamState { wantsStopSending, early, resetCode, + resetCodeIsError, writeDesiredSize, budget, }, opts)}`; diff --git a/lib/internal/readline/interface.js b/lib/internal/readline/interface.js index bc8f30427616..a9d03228f086 100644 --- a/lib/internal/readline/interface.js +++ b/lib/internal/readline/interface.js @@ -158,6 +158,9 @@ const kMultilineMove = Symbol('_multilineMove'); const kPreviousPrevRows = Symbol('_previousPrevRows'); const kAddNewLineOnTTY = Symbol('_addNewLineOnTTY'); const kColorize = Symbol('_colorize'); +const kRefreshPending = Symbol('_refreshPending'); +const kFlushPendingRefresh = Symbol('_flushPendingRefresh'); +const kWillDeferRefresh = Symbol('_willDeferRefresh'); function InterfaceConstructor(input, output, completer, terminal) { this[kSawReturnAt] = 0; @@ -166,6 +169,7 @@ function InterfaceConstructor(input, output, completer, terminal) { this.isCompletionEnabled = true; this[kSawKeyPress] = false; this[kColorize] = undefined; + this[kRefreshPending] = false; this[kPreviousKey] = null; this.escapeCodeTimeout = ESCAPE_CODE_TIMEOUT; this.tabSize = 8; @@ -502,7 +506,40 @@ class Interface extends InterfaceConstructor { return this.historyManager.addHistory(this[kIsMultiline], this[kLastCommandErrored]); } + [kFlushPendingRefresh]() { + if (this[kRefreshPending]) { + this[kRefreshLine](); + } + } + + // Performance optimization for pasted input. Input arrives in chunks: each + // 'data' event from the input stream may carry many characters at once (a + // paste often does), and emitKeypressEvents() turns a chunk into one + // keypress per character, with isCompletionEnabled set to false for all but + // the chunk's last character. Redrawing a colorized line on every one of + // those keypresses makes pasting quadratic, so plain characters inserted in + // the middle of a chunk only update the line buffer and leave a redraw + // pending, and the chunk's last keypress redraws the line. + // Returns true if this keypress inserts a plain character into a colorized + // line. Such a keypress either leaves the redraw pending or, as the last + // keypress of a chunk, redraws the whole line itself, so it does not need a + // pending redraw to be flushed first. Any other keypress must flush the + // pending redraw before it writes to the output. + [kWillDeferRefresh](s, key) { + if (this[kColorize] === undefined) return false; + if (typeof s !== 'string' || s === '' || key?.ctrl || key?.meta) { + return false; + } + const name = key?.name; + if (name === 'tab') { + // Tab triggers completion instead of inserting when completion is on. + return typeof this.completer !== 'function' || !this.isCompletionEnabled; + } + return name === undefined || name.length === 1 || name === 'space'; + } + [kRefreshLine]() { + this[kRefreshPending] = false; // line length const line = this[kPrompt] + this.line; const dispPos = this[kGetDisplayPos](line); @@ -562,6 +599,7 @@ class Interface extends InterfaceConstructor { */ close() { if (this.closed) return; + this[kFlushPendingRefresh](); this.pause(); if (this.terminal) { this[kSetRawMode](false); @@ -696,7 +734,9 @@ class Interface extends InterfaceConstructor { if (this[kColorize] === undefined) { this[kWriteToOutput](c); } else { - this[kRefreshLine](); + // More input from the same chunk follows synchronously; the line is + // redrawn once the chunk's last character is inserted. + this[kRefreshPending] = true; } return; } @@ -963,6 +1003,7 @@ class Interface extends InterfaceConstructor { } clearLine() { + this[kFlushPendingRefresh](); this[kMoveCursor](+Infinity); this[kWriteToOutput]('\r\n'); this[kSetLine](''); @@ -1283,6 +1324,9 @@ class Interface extends InterfaceConstructor { [kTtyWrite](s, key) { const previousKey = this[kPreviousKey]; key ||= kEmptyObject; + if (!this[kWillDeferRefresh](s, key)) { + this[kFlushPendingRefresh](); + } this[kPreviousKey] = key; let shouldResetPreviousCursorCols = true; @@ -1630,6 +1674,8 @@ module.exports = { kQuestionCancel, kQuestionReject, kRefreshLine, + kFlushPendingRefresh, + kWillDeferRefresh, kSawKeyPress, kSawReturnAt, kSetRawMode, diff --git a/lib/internal/source_map/scopes.js b/lib/internal/source_map/scopes.js new file mode 100644 index 000000000000..0d11943746fc --- /dev/null +++ b/lib/internal/source_map/scopes.js @@ -0,0 +1,595 @@ +'use strict'; + +// Decoder for the scopes proposal of ECMA-426. +// https://tc39.es/ecma426/branch/proposal-scopes/ + +const { + ArrayIsArray, + ArrayPrototypePop, + ArrayPrototypePush, +} = primordials; + +const { + StringCharIterator, + decodeUnsignedVLQ, + toSigned, +} = require('internal/source_map/vlq'); + +// https://tc39.es/ecma426/branch/proposal-scopes/#sec-scopes-grammar +const kTagOriginalScopeStart = 0x1; // 'B' +const kTagOriginalScopeEnd = 0x2; // 'C' +const kTagOriginalScopeVariables = 0x3; // 'D' +const kTagGeneratedRangeStart = 0x4; // 'E' +const kTagGeneratedRangeEnd = 0x5; // 'F' +const kTagGeneratedRangeBindings = 0x6; // 'G' +const kTagGeneratedRangeSubRangeBinding = 0x7; // 'H' +const kTagGeneratedRangeCallSite = 0x8; // 'I' +const kTagGeneratedRangeRelativeCallSite = 0x9; // 'J' + +// https://tc39.es/ecma426/branch/proposal-scopes/#table-scope-flags +const kScopeFlagHasName = 0x1; +const kScopeFlagHasKind = 0x2; +const kScopeFlagIsStackFrame = 0x4; + +// https://tc39.es/ecma426/branch/proposal-scopes/#table-range-flags +const kRangeFlagHasLine = 0x1; +const kRangeFlagHasDefinition = 0x2; +const kRangeFlagIsStackFrame = 0x4; +const kRangeFlagIsHidden = 0x8; + +const kStackFrameTypeNone = 'none'; +const kStackFrameTypeOriginal = 'original'; +const kStackFrameTypeHidden = 'hidden'; + +/** + * Decodes the comma separated item at the iterator's position, and moves the + * iterator past the item and its comma. + * @param {StringCharIterator} iterator + * @param {number[]} values receives the VLQUnsignedValue of each Vlq + * @returns {boolean} false if the item is malformed + */ +function decodeItem(iterator, values) { + values.length = 0; + while (iterator.hasNext() && iterator.peek() !== ',') { + const value = decodeUnsignedVLQ(iterator); + if (value === -1) return false; + ArrayPrototypePush(values, value); + } + iterator.next(); + return true; +} + +/** + * AccumulateIndex ( _accumulator_: an Index Accumulator Record, _increment_: an integer, ): a non-negative integer + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-AccumulateIndex + * @param {{ index: number }} accumulator + * @param {number} increment + * @returns {number} + */ +function accumulateIndex(accumulator, increment) { + // 1. Set _accumulator_.[[Index]] to _accumulator_.[[Index]] + _increment_. + accumulator.index += increment; + // 2. If _accumulator_.[[Index]] < 0, then + // a. Optionally report an error. + // b. Set _accumulator_.[[Index]] to 0. + if (accumulator.index < 0) accumulator.index = 0; + // 3. Return _accumulator_.[[Index]]. + return accumulator.index; +} + +/** + * AccumulatePosition ( _accumulator_: a Position Accumulator Record, _lineIncrement_: a non-negative integer, + * _columnIncrement_: a non-negative integer, ): a Position Record + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-AccumulatePosition + * @param {{ line: number, column: number }} accumulator + * @param {number} lineIncrement + * @param {number} columnIncrement + * @returns {{ line: number, column: number }} + */ +function accumulatePosition(accumulator, lineIncrement, columnIncrement) { + // 1. Set _accumulator_.[[Line]] to _accumulator_.[[Line]] + _lineIncrement_. + accumulator.line += lineIncrement; + if (lineIncrement === 0) { + // 2. If _lineIncrement_ = 0, then + // a. Set _accumulator_.[[Column]] to _accumulator_.[[Column]] + _columnIncrement_. + accumulator.column += columnIncrement; + } else { + // 3. Else, + // a. Set _accumulator_.[[Column]] to _columnIncrement_. + accumulator.column = columnIncrement; + } + // 4. Return { [[Line]]: _accumulator_.[[Line]], [[Column]]: _accumulator_.[[Column]] }. + return { line: accumulator.line, column: accumulator.column }; +} + +/** + * RelativeName ( _vlq_: a |Vlq| Parse Node, _accumulator_: an Index Accumulator Record, + * _names_: a List of Strings, ): a String or *null* + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-RelativeName + * @param {number} unsigned the VLQUnsignedValue of _vlq_ + * @param {{ index: number }} accumulator + * @param {string[]} names + * @returns {string | null} + */ +function relativeName(unsigned, accumulator, names) { + // 1. Let _relativeIndex_ be the VLQSignedValue of _vlq_. + // 2. Let _index_ be AccumulateIndex(_accumulator_, _relativeIndex_). + const index = accumulateIndex(accumulator, toSigned(unsigned)); + // 3. If _index_ >= the length of _names_, then + // a. Optionally report an error. + // b. Return *null*. + // 4. Return _names_[_index_]. + return index < names.length ? names[index] : null; +} + +/** + * BindingExpression ( _names_: a List of Strings, ): a String or *null* + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-BindingExpression + * @param {number} unsigned the VLQUnsignedValue of |Vlq| + * @param {string[]} names + * @returns {string | null} + */ +function bindingExpression(unsigned, names) { + // 1. Let _unadjustedBindingIndex_ be the VLQUnsignedValue of |Vlq|. + // 2. If _unadjustedBindingIndex_ = 0, return *null*. + // 3. Let _bindingIndex_ be _unadjustedBindingIndex_ - 1. + // 4. If _bindingIndex_ >= the length of _names_, then + // a. Optionally report an error. + // b. Return *null*. + if (unsigned === 0 || unsigned > names.length) return null; + // 5. Return _names_[_bindingIndex_]. + return names[unsigned - 1]; +} + +/** + * DecodeSourceScopes ( _scopes_: a String or *null*, _names_: a List of Strings, ): a List of Original Scope Records + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodeSourceScopes + * @param {string | null} encoded + * @param {string[]} names + * @param {number} sourceIndex index of the source, recorded on each Original + * Scope Record as `sourceIndex` to resolve SourceOfScope + * @param {object[]} flattened receives FlattenedScopes of the result + * @returns {object[]} the root Original Scope Records of the source + */ +function decodeOriginalScopes(encoded, names, sourceIndex, flattened) { + // 1. If _scopes_ is *null*, return << >>. + if (typeof encoded !== 'string') return []; + // 4. Let _scopePosition_ be a new Position Accumulator Record { [[Line]]: 0, [[Column]]: 0 }. + const position = { line: 0, column: 0 }; + // 5. Let _scopeNameIndex_ be a new Index Accumulator Record { [[Index]]: 0 }. + const nameIndex = { index: 0 }; + // 6. Let _scopeKindIndex_ be a new Index Accumulator Record { [[Index]]: 0 }. + const kindIndex = { index: 0 }; + // 7. Let _scopeVariableIndex_ be a new Index Accumulator Record { [[Index]]: 0 }. + const variableIndex = { index: 0 }; + const roots = []; + const stack = []; + // Non-recursive FlattenedScopes, so deeply nested scopes don't overflow the + // stack. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-FlattenedScopes + const preorder = []; + // 2. Let _parsedScopes_ be the root Parse Node when parsing _scopes_ using |Scopes| as the goal symbol. + // 9. Return the DecodedOriginalScopeTrees of _parsedScopes_ with arguments _state_ and _names_. + const iterator = new StringCharIterator(encoded); + const values = []; + while (iterator.hasNext()) { + // 3. If parsing failed, then + // a. Optionally report an error. + // b. Return << >>. + if (!decodeItem(iterator, values)) return []; + if (values.length === 0) continue; + const top = stack[stack.length - 1]; + switch (values[0]) { + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodedOriginalScopeTrees + // OriginalScopeTree : + // OriginalScopeStart OriginalScopeVariablesItem? OriginalScopeTreeList? `,` OriginalScopeEnd + case kTagOriginalScopeStart: { + if (values.length < 4) return []; + // 4. Let _flags_ be the VLQUnsignedValue of |OriginalScopeStart|'s |ScopeFlags| nonterminal. + const flags = values[1]; + // 1. Let _start_ be the DecodedPosition of |OriginalScopeStart| with argument _state_.[[ScopePosition]]. + const start = accumulatePosition(position, values[2], values[3]); + let next = 4; + let name = null; + let kind = null; + // 2. Let _name_ be the OriginalScopeName of |OriginalScopeStart| with arguments + // _state_.[[ScopeNameIndex]] and _names_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-OriginalScopeName + + // 2. If _flags_ & 0x1 != 0x1, return *null*. + if (flags & kScopeFlagHasName) { + if (next >= values.length) return []; + // 4. Return RelativeName(|ScopeNameOrKind|, _accumulator_, _names_). + name = relativeName(values[next++], nameIndex, names); + } + // 3. Let _kind_ be the OriginalScopeKind of |OriginalScopeStart| with arguments + // _state_.[[ScopeKindIndex]] and _names_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-OriginalScopeKind + + // 2. If _flags_ & 0x2 != 0x2, return *null*. + if (flags & kScopeFlagHasKind) { + if (next >= values.length) return []; + // 4. If _flags_ & 0x1 = 0x1, then + // a. Assert: |ScopeKind| is present. + // b. Return RelativeName(|ScopeKind|, _accumulator_, _names_). + // 5. Return RelativeName(|ScopeNameOrKind|, _accumulator_, _names_). + kind = relativeName(values[next++], kindIndex, names); + } + // 5. Let _originalScope_ be the Original Scope Record { [[Start]]: _start_, [[End]]: _start_, + + // [[Name]]: _name_, [[Kind]]: _kind_, [[Variables]]: << >>, [[Children]]: << >>, + // [[IsStackFrame]]: *false* }. + const scope = { + start, + end: start, + name, + kind, + // 6. If _flags_ & 0x4 = 0x4, set _originalScope_.[[IsStackFrame]] to *true*. + isStackFrame: (flags & kScopeFlagIsStackFrame) !== 0, + variables: [], + children: [], + sourceIndex, + }; + // 8. If |OriginalScopeTreeList| is present, then + // a. Set _originalScope_.[[Children]] to the DecodedOriginalScopeTrees of |OriginalScopeTreeList| + // with arguments _state_ and _names_. + ArrayPrototypePush(top ? top.children : roots, scope); + ArrayPrototypePush(stack, scope); + ArrayPrototypePush(preorder, scope); + break; + } + case kTagOriginalScopeEnd: + if (top === undefined || values.length < 3) return []; + // 9. Set _originalScope_.[[End]] to the DecodedPosition of |OriginalScopeEnd| with argument + // _state_.[[ScopePosition]]. + top.end = accumulatePosition(position, values[1], values[2]); + + // 10. Return << _originalScope_ >>. + ArrayPrototypePop(stack); + break; + case kTagOriginalScopeVariables: + if (top === undefined) return []; + // 7. If |OriginalScopeVariablesItem| is present, then + // a. Set _originalScope_.[[Variables]] to the OriginalScopeVariables of |OriginalScopeVariablesItem| + // with arguments _state_.[[ScopeVariableIndex]] and _names_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-OriginalScopeVariables + for (let j = 1; j < values.length; ++j) { + // ScopeVariable : Vlq + // 1. Let _variable_ be RelativeName(|Vlq|, _accumulator_, _names_). + const variable = relativeName(values[j], variableIndex, names); + + // 2. If _variable_ is *null*, return << "" >>. + + // 3. Return << _variable_ >>. + ArrayPrototypePush(top.variables, variable ?? ''); + } + break; + default: + // OriginalScopeTreeItem : + // VendorExtensionItem + // InvalidScopeItem + + // 1. Return << >>. + break; + } + } + if (stack.length !== 0) return []; + for (let i = 0; i < preorder.length; ++i) { + ArrayPrototypePush(flattened, preorder[i]); + } + return roots; +} + +/** + * ParentDefinition ( _state_: a Decode Range State Record, _parentRangeIndex_: a non-negative integer, ): + * an Original Scope Record + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-ParentDefinition + * @param {object[]} stack the open Generated Range Records, ending with the + * current one + * @param {number} parentRangeIndex + * @returns {object | null} + */ +function parentDefinition(stack, parentRangeIndex) { + // 1. Let _stack_ be _state_.[[DefinitionStack]]. + // 2. Let _length_ be the number of elements in _stack_. + // 3. Return _stack_[_length_ - _parentRangeIndex_ - 1]. + for (let i = stack.length - 2; i >= 0; --i) { + const definition = stack[i].definition; + if (definition === null) continue; + if (parentRangeIndex-- === 0) return definition; + } + return null; +} + +/** + * DecodeGeneratedRanges ( _ranges_: either a List of Strings, or *null*, _sources_: a List of Decoded Source Records, + * _names_: a List of Strings, ): a List of Generated Range Records, steps 3.a to 3.g + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodeGeneratedRanges + * @param {string} segment + * @param {object[][]} flattenedScopes FlattenedScopes of each source's + * [[RootScopes]], indexed by the source index local to this map + * @param {string[]} names + * @param {number} sourceBase index of this map's first source in the + * original scope records + * @returns {object[] | undefined} undefined if the segment is malformed + */ +function decodeRangesSegment(segment, flattenedScopes, names, sourceBase) { + // c. Let _rangePosition_ be a new Position Accumulator Record { [[Line]]: 0, [[Column]]: 0 }. + const position = { line: 0, column: 0 }; + // d. Let _rangeDefinitionSourceIndex_ be a new Index Accumulator Record { [[Index]]: 0 }. + const definitionSourceIndex = { index: 0 }; + // e. Let _rangeDefinitionScopeIndex_ be a new Index Accumulator Record { [[Index]]: 0 }. + const definitionScopeIndex = { index: 0 }; + const result = []; + const stack = []; + // a. Let _parsedRanges_ be the root Parse Node when parsing _segment_ using |Ranges| as the goal symbol. + // g. Let _segmentResult_ be the DecodedGeneratedRangeTrees of _parsedRanges_ with arguments _state_, + // _sources_ and _names_. + const iterator = new StringCharIterator(segment); + const values = []; + while (iterator.hasNext()) { + // b. If parsing failed, then + // i. Optionally report an error. + // ii. Return << >>. + if (!decodeItem(iterator, values)) return; + if (values.length === 0) continue; + const top = stack[stack.length - 1]; + switch (values[0]) { + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodedGeneratedRangeTrees + // GeneratedRangeTree : + // GeneratedRangeStart GeneratedRangeBindingsItem? GeneratedRangeCallSiteItem? GeneratedRangeItemList? + // `,` GeneratedRangeEnd + case kTagGeneratedRangeStart: { + if (values.length < 3) return; + // 3. Let _flags_ be the VLQUnsignedValue of |GeneratedRangeStart|'s |RangeFlags| nonterminal. + const flags = values[1]; + let next = 2; + // 1. Let _start_ be the DecodedPosition of |GeneratedRangeStart| with argument _state_.[[RangePosition]]. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodedPosition + // 1. If |RangeLine| is present, let _relativeLine_ be the VLQUnsignedValue of |RangeLine|, otherwise + // let _relativeLine_ be 0. + let line = 0; + if (flags & kRangeFlagHasLine) line = values[next++]; + if (next >= values.length) return; + // 2. Let _relativeColumn_ be the VLQUnsignedValue of |RangeColumn|. + // 3. Return AccumulatePosition(_accumulator_, _relativeLine_, _relativeColumn_). + const start = accumulatePosition(position, line, values[next++]); + // 2. Let _definition_ be the GeneratedRangeDefinition of |GeneratedRangeStart| with arguments _state_ + // and _sources_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-GeneratedRangeDefinition + let definition = null; + + // 2. If _flags_ & 0x2 != 0x2, return *null*. + if (flags & kRangeFlagHasDefinition) { + if (next + 1 >= values.length) return; + // RangeDefinition : + // DefinitionSourceIdx DefinitionScopeIdx + // 1. Let _sourceOffset_ be the VLQSignedValue of |DefinitionSourceIdx|. + const sourceOffset = toSigned(values[next++]); + // 2. Let _sourceIndex_ be AccumulateIndex(_state_.[[RangeDefinitionSourceIndex]], _sourceOffset_). + const sourceIndex = + accumulateIndex(definitionSourceIndex, sourceOffset); + let scopeOffset; + if (sourceOffset === 0) { + // 4. If _sourceOffset_ = 0, then + // a. Let _scopeOffset_ be the VLQSignedValue of |DefinitionScopeIdx|. + scopeOffset = toSigned(values[next++]); + } else { + // 5. Else, + // a. Set _state_.[[RangeDefinitionScopeIndex]].[[Index]] to 0. + definitionScopeIndex.index = 0; + // b. Let _scopeOffset_ be the VLQUnsignedValue of |DefinitionScopeIdx|. + scopeOffset = values[next++]; + } + // 6. Let _scopeIndex_ be AccumulateIndex(_state_.[[RangeDefinitionScopeIndex]], _scopeOffset_). + const scopeIndex = accumulateIndex(definitionScopeIndex, scopeOffset); + // 3. Let _source_ be _sources_[_sourceIndex_]. + // 7. Return ScopeForScopeIndex(_source_.[[RootScopes]], _scopeIndex_). + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-ScopeForScopeIndex + // 1. Return FlattenedScopes(_scopes_)[_index_]. + if (sourceIndex < flattenedScopes.length) { + definition = flattenedScopes[sourceIndex][scopeIndex] ?? null; + } + } + // 6. Else, + // a. If _flags_ & 0x8 = 0x8, optionally report an error. + // b. Let _stackFrameType_ be ~none~. + let stackFrameType = kStackFrameTypeNone; + if (flags & kRangeFlagIsStackFrame) { + // 4. If _flags_ & 0xc = 0xc, then + // a. Let _stackFrameType_ be ~hidden~. + // 5. Else if _flags_ & 0x4 = 0x4, then + // a. Let _stackFrameType_ be ~original~. + stackFrameType = (flags & kRangeFlagIsHidden) ? + kStackFrameTypeHidden : kStackFrameTypeOriginal; + } + const range = { + start, + end: start, + definition, + stackFrameType, + // 8. Else, + + // a. Let _bindings_ be << >>. + bindings: [], + // 10. Else, + // a. Let _callSite_ be *null*. + callSite: null, + children: [], + }; + // 11. If _definition_ is not *null*, then + // a. Append _definition_ to _state_.[[DefinitionStack]]. + // 12. If |GeneratedRangeItemList| is present, then + // a. Let _children_ be the DecodedGeneratedRangeTrees of |GeneratedRangeItemList| with arguments + // _state_, _sources_ and _names_. + ArrayPrototypePush(top ? top.children : result, range); + ArrayPrototypePush(stack, range); + break; + } + case kTagGeneratedRangeEnd: + if (top === undefined || values.length < 2 || values.length > 3) return; + // 15. Let _end_ be the DecodedPosition of |GeneratedRangeEnd| with argument _state_.[[RangePosition]]. + top.end = accumulatePosition(position, + values.length === 3 ? values[1] : 0, + values[values.length - 1]); + // 16. If _definition_ is not *null*, then + // a. Remove the last element of _state_.[[DefinitionStack]]. + ArrayPrototypePop(stack); + break; + case kTagGeneratedRangeBindings: + if (top === undefined) return; + // 7. If |GeneratedRangeBindingsItem| is present, then + // a. Let _bindings_ be the GeneratedRangeBindings of |GeneratedRangeBindingsItem| with arguments + // _start_ and _names_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-GeneratedRangeBindings + for (let j = 1; j < values.length; ++j) { + // BindingExpression : Vlq + // 1. Let _binding_ be the BindingExpression of |BindingExpression| with argument _names_. + + // 2. Return << << { [[From]]: _start_, [[Binding]]: _binding_ } >> >>. + ArrayPrototypePush(top.bindings, [{ + from: { line: top.start.line, column: top.start.column }, + binding: bindingExpression(values[j], names), + }]); + } + break; + case kTagGeneratedRangeSubRangeBinding: { + if (top === undefined || values.length < 2) return; + // 14. If |GeneratedRangeItemList| is present, then + // a. Let _subRangeBindings_ be the GeneratedSubRangeBindings of |GeneratedRangeItemList| with + // arguments _start_ and _names_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-GeneratedSubRangeBindings + // GeneratedSubRangeBinding : + // `H` VariableIndex BindingFromList + // 1. Let _variableIndex_ be the VLQUnsignedValue of |VariableIndex|. + // 2. Let _from_ be a new Position Accumulator Record { [[Line]]: _start_.[[Line]], + // [[Column]]: _start_.[[Column]] }. + const from = { line: top.start.line, column: top.start.column }; + // b. For each Sub-Range Binding Record _subRangeBinding_ of _subRangeBindings_, do + // i. Let _index_ be _subRangeBinding_.[[VariableIndex]]. + // ii. If _index_ < the length of _bindings_, then + // 1. Set _bindings_[_index_] to the list-concatenation of _bindings_[_index_] and + // _subRangeBinding_.[[Bindings]]. + // iii. Else, + // 1. Optionally report an error. + const bindings = top.bindings[values[1]]; + // 3. Let _bindings_ be the SubRangeBinding of |BindingFromList| with arguments _from_ and _names_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-SubRangeBinding + for (let j = 2; j + 2 < values.length; j += 3) { + // BindingFrom : BindingLine BindingColumn BindingExpression + const binding = { + // 1. Let _relativeLine_ be the VLQUnsignedValue of |BindingLine|. + // 2. Let _relativeColumn_ be the VLQUnsignedValue of |BindingColumn|. + // 3. Let _fromPosition_ be AccumulatePosition(_from_, _relativeLine_, _relativeColumn_). + from: accumulatePosition(from, values[j], values[j + 1]), + // 4. Let _binding_ be the BindingExpression of |BindingExpression| with argument _names_. + binding: bindingExpression(values[j + 2], names), + }; + + // 5. Return << { [[From]]: _fromPosition_, [[Binding]]: _binding_ } >>. + if (bindings !== undefined) ArrayPrototypePush(bindings, binding); + } + break; + } + case kTagGeneratedRangeCallSite: + if (top === undefined || values.length < 4) return; + // 9. If |GeneratedRangeCallSiteItem| is present, then + // a. Let _callSite_ be the GeneratedRangeCallSite of |GeneratedRangeCallSiteItem| with arguments + // _state_ and _sources_. + // https://tc39.es/ecma426/branch/proposal-scopes/#sec-GeneratedRangeCallSite + // GeneratedRangeCallSite : + // `I` CallSiteSourceIdx CallSiteLine CallSiteColumn + // 1. Let _sourceIndex_ be the VLQUnsignedValue of |CallSiteSourceIdx|. + // 2. Let _source_ be _sources_[_sourceIndex_]. + if (values[1] < flattenedScopes.length) { + // 3. Let _line_ be the VLQUnsignedValue of |CallSiteLine|. + // 4. Let _column_ be the VLQUnsignedValue of |CallSiteColumn|. + // 5. Return a new Original Position Record { [[Source]]: _source_, [[Line]]: _line_, + // [[Column]]: _column_ }. + top.callSite = { + sourceIndex: sourceBase + values[1], + line: values[2], + column: values[3], + }; + } + break; + case kTagGeneratedRangeRelativeCallSite: { + if (top === undefined || values.length < 2 || values.length > 4) return; + // `J` CallSiteRangeParentIdx CallSiteLineOffset CallSiteColumn + // 1. Let _parentDefinitionIndex_ be the VLQUnsignedValue of |CallSiteRangeParentIdx|. + // 2. Let _parentDefinition_ be ParentDefinition(_state_, _parentDefinitionIndex_). + // `J` CallSiteLineOffset CallSiteColumn + // `J` CallSiteColumnOffset + // 1. Let _parentDefinition_ be ParentDefinition(_state_, 0). + const parent = parentDefinition(stack, values.length === 4 ? values[1] : 0); + if (parent === null) break; + let line = parent.start.line; + let column; + if (values.length === 2) { + // `J` CallSiteColumnOffset + // 3. Let _line_ be _parentDefinition_.[[Start]].[[Line]]. + // 4. Let _column_ be _parentDefinition_.[[Start]].[[Column]] + the VLQUnsignedValue of + // |CallSiteColumnOffset|. + column = parent.start.column + values[1]; + } else { + // `J` CallSiteRangeParentIdx CallSiteLineOffset CallSiteColumn + // 4. Let _line_ be _parentDefinition_.[[Start]].[[Line]] + the VLQUnsignedValue of + // |CallSiteLineOffset|. + // 5. Let _column_ be the VLQUnsignedValue of |CallSiteColumn|. + // `J` CallSiteLineOffset CallSiteColumn + // 3. Let _line_ be _parentDefinition_.[[Start]].[[Line]] + the VLQUnsignedValue of + // |CallSiteLineOffset|. + // 4. Let _column_ be the VLQUnsignedValue of |CallSiteColumn|. + line += values[values.length - 2]; + column = values[values.length - 1]; + } + top.callSite = { sourceIndex: parent.sourceIndex, line, column }; + break; + } + default: + break; + } + } + if (stack.length !== 0) return; + return result; +} + +/** + * DecodeGeneratedRanges ( _ranges_: either a List of Strings, or *null*, _sources_: a List of Decoded Source Records, + * _names_: a List of Strings, ): a List of Generated Range Records + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodeGeneratedRanges + * @param {string[]} ranges + * @param {object[][]} flattenedScopes + * @param {string[]} names + * @param {number} sourceBase + * @returns {object[]} the root Generated Range Records + */ +function decodeGeneratedRanges(ranges, flattenedScopes, names, sourceBase) { + // 1. If _ranges_ is *null*, return << >>. + if (!ArrayIsArray(ranges)) return []; + + // 2. Let _result_ be << >>. + const result = []; + // 3. For each String _segment_ of _ranges_, do + for (let i = 0; i < ranges.length; ++i) { + if (typeof ranges[i] !== 'string') continue; + const segment = + decodeRangesSegment(ranges[i], flattenedScopes, names, sourceBase); + + // b. If parsing failed, then + // i. Optionally report an error. + // ii. Return << >>. + if (segment === undefined) return []; + // i. Append each element of _segmentResult_ to _result_. + for (let j = 0; j < segment.length; ++j) { + ArrayPrototypePush(result, segment[j]); + } + } + // 4. Return _result_. + return result; +} + +module.exports = { + decodeGeneratedRanges, + decodeOriginalScopes, +}; diff --git a/lib/internal/source_map/source_map.js b/lib/internal/source_map/source_map.js index 42e7bca3c4c5..1fbd7cd8283f 100644 --- a/lib/internal/source_map/source_map.js +++ b/lib/internal/source_map/source_map.js @@ -71,52 +71,70 @@ const { ArrayPrototypePush, ArrayPrototypeSlice, ArrayPrototypeSort, + Int32Array, + MathMax, ObjectFreeze, ObjectPrototypeHasOwnProperty, - StringPrototypeCharAt, Symbol, + TypedArrayPrototypeSet, + TypedArrayPrototypeSlice, + TypedArrayPrototypeSubarray, } = primordials; -const { validateObject } = require('internal/validators'); - -let base64Map; - -const VLQ_BASE_SHIFT = 5; -const VLQ_BASE_MASK = (1 << 5) - 1; -const VLQ_CONTINUATION_MASK = 1 << 5; - -const kMappings = Symbol('kMappings'); +const { + validateInt32, + validateObject, +} = require('internal/validators'); +const { + decodeGeneratedRanges, + decodeOriginalScopes, +} = require('internal/source_map/scopes'); +const { + StringCharIterator, + decodeSignedVLQ, +} = require('internal/source_map/vlq'); -class StringCharIterator { - /** - * @param {string} string - */ - constructor(string) { - this._string = string; - this._position = 0; - } +/** + * A source map, or an index map when `sections` is present. + * @see https://tc39.es/ecma426/#sec-source-map-format + * @see https://tc39.es/ecma426/#sec-index-source-map + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-source-map-format + * @typedef {object} SourceMapV3 + * @property {number} version The version field. + * @property {string} [file] The file field. + * @property {string} [sourceRoot] The sourceRoot field. + * @property {Array<string|null>} [sources] The sources field. + * @property {Array<string|null>} [sourcesContent] The sourcesContent field. + * @property {string[]} [names] The names field. + * @property {string} [mappings] The mappings field. + * @property {number[]} [ignoreList] The ignoreList field. + * @property {Array<string|null>} [scopes] The scopes field. + * @property {string[]} [ranges] The ranges field. + * @property {SourceMapV3Section[]} [sections] The sections field of an index + * map. + */ - /** - * @returns {string} - */ - next() { - return StringPrototypeCharAt(this._string, this._position++); - } +/** + * A section of an index map. + * @see https://tc39.es/ecma426/#sec-index-source-map + * @typedef {object} SourceMapV3Section + * @property {{ line: number, column: number }} offset The offset field. + * @property {SourceMapV3} map The map field. + */ - /** - * @returns {string} - */ - peek() { - return StringPrototypeCharAt(this._string, this._position); - } +const kFirstEntry = Symbol('kFirstEntry'); +const kScopes = Symbol('kScopes'); - /** - * @returns {boolean} - */ - hasNext() { - return this._position < this._string.length; - } -} +// Each entry is stored as kEntrySize consecutive Int32 fields: generated line, +// generated column, source index, original line, original column and name +// index. Large maps have millions of entries, and one array per entry costs +// several times more memory than the numbers it holds. +const kEntrySize = 6; +// Source index of an entry that has only a generated column. +const kNoSource = -1; +// Source index of an entry whose source index is outside `sources`. +const kUnknownSource = -2; +const kNoName = -1; /** * @class @@ -126,22 +144,25 @@ class StringCharIterator { */ class SourceMap { #payload; - #mappings = []; + #entries; + #entryCount = 0; + #sourceURLs = []; + // Names of each map, indexed by the entries through a single index space + // that starts at #nameBases[i] for #nameTables[i]. Kept as is instead of + // being copied into one array. + #nameTables = []; + #nameBases = []; + #nameCount = 0; #sources = {}; #sourceContentByURL = {}; #lineLengths = undefined; + // Decoded on first use. + #scopes = undefined; /** * @param {SourceMapV3} payload */ constructor(payload, { lineLengths } = { __proto__: null }) { - if (!base64Map) { - const base64Digits = - 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - base64Map = {}; - for (let i = 0; i < base64Digits.length; ++i) - base64Map[base64Digits[i]] = i; - } this.#payload = cloneSourceMapV3(payload); this.#parseMappingPayload(); if (ArrayIsArray(lineLengths) && lineLengths.length) { @@ -156,8 +177,40 @@ class SourceMap { return this.#payload; } - get [kMappings]() { - return this.#mappings; + get [kFirstEntry]() { + return this.#entryCount ? this.#entryAt(0) : {}; + } + + /** + * The decoded `scopes` and `ranges` fields. + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodeIndexSourceMap + * @returns {{ originalScopes: object[][], generatedRanges: object[] }} + * `originalScopes` holds the [[RootScopes]] of each source, and + * `generatedRanges` the [[Ranges]]. + */ + get [kScopes]() { + if (this.#scopes === undefined) { + const { sections } = this.#payload; + if (sections) { + // TODO(legendecas): Decode the ranges of index map sections once + // DecodeIndexSourceMap produces [[Ranges]]. + // Refs: https://github.com/tc39/ecma426/issues/294 + const originalScopes = []; + for (let i = 0; i < sections.length; ++i) { + const decoded = decodeScopes(sections[i].map, originalScopes.length); + // 9.b.xiv.2. For each Decoded Source Record _additionalSource_ of _decodedSection_.[[Sources]], do + // a. If _sourceMap_.[[Sources]] does not contain _additionalSource_, then + // i. Append _additionalSource_ to _sourceMap_.[[Sources]]. + for (let j = 0; j < decoded.originalScopes.length; ++j) { + ArrayPrototypePush(originalScopes, decoded.originalScopes[j]); + } + } + this.#scopes = { originalScopes, generatedRanges: [] }; + } else { + this.#scopes = decodeScopes(this.#payload, 0); + } + } + return this.#scopes; } /** @@ -168,20 +221,138 @@ class SourceMap { } #parseMappingPayload = () => { - if (this.#payload.sections) { - this.#parseSections(this.#payload.sections); + const { sections } = this.#payload; + let segments = 0; + if (sections) { + for (let i = 0; i < sections.length; ++i) { + segments += estimateSegments(sections[i]?.map?.mappings); + } + } else { + segments = estimateSegments(this.#payload.mappings); + } + this.#entries = new Int32Array(segments * kEntrySize); + if (sections) { + this.#parseSections(sections); } else { this.#parseMap(this.#payload, 0, 0); } - ArrayPrototypeSort(this.#mappings, compareSourceMapEntry); + this.#sortEntries(); }; + #sortEntries() { + const entries = this.#entries; + const count = this.#entryCount; + const compare = (a, b) => { + const lineDelta = entries[a * kEntrySize] - entries[b * kEntrySize]; + return lineDelta || + entries[a * kEntrySize + 1] - entries[b * kEntrySize + 1]; + }; + let sorted = true; + for (let i = 1; i < count; ++i) { + if (compare(i - 1, i) > 0) { + sorted = false; + break; + } + } + if (sorted) { + if (entries.length !== count * kEntrySize) { + this.#entries = + TypedArrayPrototypeSlice(entries, 0, count * kEntrySize); + } + return; + } + // Sorting indices keeps equal positions in insertion order, like the + // stable sort of entries this replaces. + const order = []; + for (let i = 0; i < count; ++i) { + ArrayPrototypePush(order, i); + } + ArrayPrototypeSort(order, compare); + const sortedEntries = new Int32Array(count * kEntrySize); + for (let i = 0; i < count; ++i) { + const offset = order[i] * kEntrySize; + TypedArrayPrototypeSet( + sortedEntries, + TypedArrayPrototypeSubarray(entries, offset, offset + kEntrySize), + i * kEntrySize, + ); + } + this.#entries = sortedEntries; + } + + #pushEntry(lineNumber, columnNumber, sourceIndex, sourceLineNumber, + sourceColumnNumber, nameIndex) { + const offset = this.#entryCount * kEntrySize; + if (offset === this.#entries.length) { + // Only reached when the parser finds more segments than + // estimateSegments(), which happens for malformed mappings. + const grown = + new Int32Array(MathMax(this.#entries.length * 2, kEntrySize * 16)); + TypedArrayPrototypeSet(grown, this.#entries); + this.#entries = grown; + } + const entries = this.#entries; + entries[offset] = lineNumber; + entries[offset + 1] = columnNumber; + entries[offset + 2] = sourceIndex; + entries[offset + 3] = sourceLineNumber; + entries[offset + 4] = sourceColumnNumber; + entries[offset + 5] = nameIndex; + this.#entryCount++; + } + + #nameAt(index) { + const bases = this.#nameBases; + // Find the last table starting at or before the index. + let low = 0; + let high = bases.length - 1; + while (low < high) { + const middle = (low + high + 1) >> 1; + if (bases[middle] <= index) { + low = middle; + } else { + high = middle - 1; + } + } + return this.#nameTables[low][index - bases[low]]; + } + + #entryAt(index) { + const entries = this.#entries; + const offset = index * kEntrySize; + const sourceIndex = entries[offset + 2]; + if (sourceIndex === kNoSource) { + return { + generatedLine: entries[offset], + generatedColumn: entries[offset + 1], + originalSource: undefined, + originalLine: undefined, + originalColumn: undefined, + name: undefined, + }; + } + const nameIndex = entries[offset + 5]; + return { + generatedLine: entries[offset], + generatedColumn: entries[offset + 1], + originalSource: sourceIndex === kUnknownSource ? + undefined : this.#sourceURLs[sourceIndex], + originalLine: entries[offset + 3], + originalColumn: entries[offset + 4], + name: nameIndex === kNoName ? undefined : this.#nameAt(nameIndex), + }; + } + /** - * @param {Array.<SourceMapV3.Section>} sections + * @param {Array.<SourceMapV3Section>} sections */ #parseSections = (sections) => { for (let i = 0; i < sections.length; ++i) { const section = sections[i]; + // The offsets seed the Int32Array entries below, so reject anything + // that would otherwise be implicitly coerced. + validateInt32(section.offset.line, 'section.offset.line', 0); + validateInt32(section.offset.column, 'section.offset.column', 0); this.#parseMap(section.map, section.offset.line, section.offset.column); } }; @@ -192,35 +363,30 @@ class SourceMap { * @returns {object} representing start of range if found, or empty object */ findEntry(lineOffset, columnOffset) { + const entries = this.#entries; let first = 0; - let count = this.#mappings.length; + let count = this.#entryCount; + if (!count) { + return {}; + } while (count > 1) { const step = count >> 1; const middle = first + step; - const mapping = this.#mappings[middle]; - if (lineOffset < mapping[0] || - (lineOffset === mapping[0] && columnOffset < mapping[1])) { + const line = entries[middle * kEntrySize]; + if (lineOffset < line || + (lineOffset === line && + columnOffset < entries[middle * kEntrySize + 1])) { count = step; } else { first = middle; count -= step; } } - const entry = this.#mappings[first]; - if (!first && entry && (lineOffset < entry[0] || - (lineOffset === entry[0] && columnOffset < entry[1]))) { - return {}; - } else if (!entry) { + if (!first && (lineOffset < entries[0] || + (lineOffset === entries[0] && columnOffset < entries[1]))) { return {}; } - return { - generatedLine: entry[0], - generatedColumn: entry[1], - originalSource: entry[2], - originalLine: entry[3], - originalColumn: entry[4], - name: entry[5], - }; + return this.#entryAt(first); } /** @@ -260,18 +426,24 @@ class SourceMap { const sources = []; const originalToCanonicalURLMap = {}; + const sourceBase = this.#sourceURLs.length; for (let i = 0; i < map.sources.length; ++i) { const url = map.sources[i]; originalToCanonicalURLMap[url] = url; ArrayPrototypePush(sources, url); + ArrayPrototypePush(this.#sourceURLs, url); this.#sources[url] = true; if (map.sourcesContent?.[i]) this.#sourceContentByURL[url] = map.sourcesContent[i]; } + const names = map.names ?? []; + const nameBase = this.#nameCount; + ArrayPrototypePush(this.#nameTables, names); + ArrayPrototypePush(this.#nameBases, nameBase); + this.#nameCount += names.length; const stringCharIterator = new StringCharIterator(map.mappings); - let sourceURL = sources[sourceIndex]; while (true) { if (stringCharIterator.peek() === ',') stringCharIterator.next(); @@ -285,73 +457,97 @@ class SourceMap { break; } - columnNumber += decodeVLQ(stringCharIterator); - if (isSeparator(stringCharIterator.peek())) { - ArrayPrototypePush(this.#mappings, [lineNumber, columnNumber]); + columnNumber += decodeSignedVLQ(stringCharIterator); + if (!stringCharIterator.hasNext() || + isSeparator(stringCharIterator.peek())) { + this.#pushEntry(lineNumber, columnNumber, kNoSource, 0, 0, kNoName); continue; } - const sourceIndexDelta = decodeVLQ(stringCharIterator); - if (sourceIndexDelta) { - sourceIndex += sourceIndexDelta; - sourceURL = sources[sourceIndex]; - } - sourceLineNumber += decodeVLQ(stringCharIterator); - sourceColumnNumber += decodeVLQ(stringCharIterator); + sourceIndex += decodeSignedVLQ(stringCharIterator); + sourceLineNumber += decodeSignedVLQ(stringCharIterator); + sourceColumnNumber += decodeSignedVLQ(stringCharIterator); - let name; - if (!isSeparator(stringCharIterator.peek())) { - nameIndex += decodeVLQ(stringCharIterator); - name = map.names?.[nameIndex]; + let entryNameIndex = kNoName; + if (stringCharIterator.hasNext() && + !isSeparator(stringCharIterator.peek())) { + nameIndex += decodeSignedVLQ(stringCharIterator); + if (nameIndex >= 0 && nameIndex < names.length) { + entryNameIndex = nameBase + nameIndex; + } } - ArrayPrototypePush( - this.#mappings, - [lineNumber, columnNumber, sourceURL, sourceLineNumber, - sourceColumnNumber, name], + this.#pushEntry( + lineNumber, + columnNumber, + sourceIndex >= 0 && sourceIndex < sources.length ? + sourceBase + sourceIndex : kUnknownSource, + sourceLineNumber, + sourceColumnNumber, + entryNameIndex, ); } } } /** - * @param {string} char - * @returns {boolean} + * DecodeSourceMap ( _json_: a JSON object, _baseURL_: an URL, ): a Decoded Source Map Record + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodeSourceMap + * @see https://tc39.es/ecma426/branch/proposal-scopes/#sec-DecodeSourceMapSources + * @param {SourceMapV3} map + * @param {number} sourceBase index of the first source of `map` among all + * sources of the source map + * @returns {{ originalScopes: object[][], generatedRanges: object[] }} */ -function isSeparator(char) { - return char === ',' || char === ';'; +function decodeScopes(map, sourceBase) { + // 10. Let _namesField_ be GetOptionalListOfStrings(_json_, *"names"*). + const names = ArrayIsArray(map.names) ? map.names : []; + // 11. Let _scopesField_ be GetOptionalListOfStrings(_json_, *"scopes"*). + const scopesField = ArrayIsArray(map.scopes) ? map.scopes : []; + // 13. Let _sources_ be DecodeSourceMapSources(_baseURL_, _sourceRootField_, _sourcesField_, + // _sourcesContentField_, _ignoreListField_, _namesField_, _scopesField_). + const originalScopes = []; + const flattenedScopes = []; + for (let i = 0; i < map.sources.length; ++i) { + const flattened = []; + // DecodeSourceMapSources + // 6.f. If _index_ < _encodedScopes_' length, then + // i. Let _decodedSourceScopes_ be DecodeSourceScopes(_encodedScopes_[_index_], _names_). + // ii. Set _decodedSource_.[[RootScopes]] to _decodedSourceScopes_. + ArrayPrototypePush(originalScopes, + decodeOriginalScopes(scopesField[i], names, sourceBase + i, flattened)); + ArrayPrototypePush(flattenedScopes, flattened); + } + // 12. Let _rangesField_ be GetOptionalListOfStrings(_json_, *"ranges"*). + const rangesField = ArrayIsArray(map.ranges) ? map.ranges : []; + // 14. Let _ranges_ be DecodeGeneratedRanges(_rangesField_, _sources_, _namesField_). + const generatedRanges = + decodeGeneratedRanges(rangesField, flattenedScopes, names, sourceBase); + return { originalScopes, generatedRanges }; } /** - * @param {SourceMap.StringCharIterator} stringCharIterator + * Estimates the number of segments in a mappings string, so entry storage + * can be allocated up front without a separate pass over the string. A + * segment takes four to five VLQ digits and a separator in typical maps. + * #pushEntry grows the storage if the estimate turns out to be too low, and + * #sortEntries trims it if it is too high. + * @param {string} mappings * @returns {number} */ -function decodeVLQ(stringCharIterator) { - // Read unsigned value. - let result = 0; - let shift = 0; - let digit; - do { - digit = base64Map[stringCharIterator.next()]; - result += (digit & VLQ_BASE_MASK) << shift; - shift += VLQ_BASE_SHIFT; - } while (digit & VLQ_CONTINUATION_MASK); - - // Fix the sign. - const negative = result & 1; - // Use unsigned right shift, so that the 32nd bit is properly shifted to the - // 31st, and the 32nd becomes unset. - result >>>= 1; - if (!negative) { - return result; +function estimateSegments(mappings) { + if (typeof mappings !== 'string') { + return 0; } + return (mappings.length + 3) >> 2; +} - // We need to OR here to ensure the 32nd bit (the sign bit in an Int32) is - // always set for negative numbers. If `result` were 1, (meaning `negate` is - // true and all other bits were zeros), `result` would now be 0. But -0 - // doesn't flip the 32nd bit as intended. All other numbers will successfully - // set the 32nd bit without issue, so doing this is a noop for them. - return -result | (1 << 31); +/** + * @param {string} char + * @returns {boolean} + */ +function isSeparator(char) { + return char === ',' || char === ';'; } /** @@ -370,22 +566,8 @@ function cloneSourceMapV3(payload) { return ObjectFreeze(payload); } -/** - * @param {Array} entry1 source map entry [lineNumber, columnNumber, sourceURL, - * sourceLineNumber, sourceColumnNumber] - * @param {Array} entry2 source map entry. - * @returns {number} - */ -function compareSourceMapEntry(entry1, entry2) { - const { 0: lineNumber1, 1: columnNumber1 } = entry1; - const { 0: lineNumber2, 1: columnNumber2 } = entry2; - if (lineNumber1 !== lineNumber2) { - return lineNumber1 - lineNumber2; - } - return columnNumber1 - columnNumber2; -} - module.exports = { - kMappings, + kFirstEntry, + kScopes, SourceMap, }; diff --git a/lib/internal/source_map/vlq.js b/lib/internal/source_map/vlq.js new file mode 100644 index 000000000000..467733b2631b --- /dev/null +++ b/lib/internal/source_map/vlq.js @@ -0,0 +1,122 @@ +'use strict'; + +const { + Int8Array, + StringPrototypeCharAt, + StringPrototypeCharCodeAt, + TypedArrayPrototypeFill, +} = primordials; + +// The base64 digit value of each char code below 128, or -1. +const kDigitValues = TypedArrayPrototypeFill(new Int8Array(128), -1); +{ + const digits = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (let i = 0; i < digits.length; ++i) { + kDigitValues[StringPrototypeCharCodeAt(digits, i)] = i; + } +} + +class StringCharIterator { + /** + * @param {string} string + */ + constructor(string) { + this._string = string; + this._position = 0; + } + + /** + * @returns {string} + */ + next() { + return StringPrototypeCharAt(this._string, this._position++); + } + + /** + * @returns {string} + */ + peek() { + return StringPrototypeCharAt(this._string, this._position); + } + + /** + * @returns {boolean} + */ + hasNext() { + return this._position < this._string.length; + } +} + +/** + * VLQUnsignedValue ( ): an non-negative integer + * @see https://tc39.es/ecma426/#sec-VLQUnsignedValue + * @param {StringCharIterator} iterator positioned at a Vlq, and moved past it + * @returns {number} the VLQUnsignedValue of the Vlq, or -1 if the iterator + * isn't at a Vlq or the value is out of range + */ +function decodeUnsignedVLQ(iterator) { + const string = iterator._string; + let position = iterator._position; + let result = 0; + let shift = 0; + let digit; + do { + // Past the end of the string, the char code is NaN. + const code = StringPrototypeCharCodeAt(string, position++); + digit = code < 128 ? kDigitValues[code] : -1; + if (digit === -1) { + iterator._position = position; + return -1; + } + const bits = digit & 0x1f; + // Vlq :: VlqDigitList + // 2. If _value_ is >= 2<sup>32</sup>, throw an error. + if (shift >= 30 && (shift > 30 || bits > 3)) { + iterator._position = position; + return -1; + } + // VlqDigitList :: ContinuationDigit VlqDigitList + // 3. Return _left_ + _right_ * 2<sup>5</sup>. + result |= bits << shift; + shift += 5; + } while (digit & 0x20); + iterator._position = position; + return result >>> 0; +} + +/** + * VLQSignedValue ( ): an integer + * @see https://tc39.es/ecma426/#sec-VLQSignedValue + * @param {number} unsigned the VLQUnsignedValue of the VlqDigitList + * @returns {number} + */ +function toSigned(unsigned) { + // 2. If _unsigned_ modulo 2 = 1, let _sign_ be -1. + // 3. Else, let _sign_ be 1. + // 4. Let _value_ be floor(_unsigned_ / 2). + const value = unsigned >>> 1; + if ((unsigned & 1) === 0) return value; + // 5. If _value_ is 0 and _sign_ is -1, return -2<sup>31</sup>. + // 7. Return _sign_ * _value_. + return value === 0 ? -2147483648 : -value; +} + +/** + * VLQSignedValue ( ): an integer + * @see https://tc39.es/ecma426/#sec-VLQSignedValue + * @param {StringCharIterator} iterator positioned at a Vlq, and moved past it + * @returns {number} the VLQSignedValue of the Vlq, or 0 if the iterator isn't + * at a Vlq or the value is out of range + */ +function decodeSignedVLQ(iterator) { + const unsigned = decodeUnsignedVLQ(iterator); + return unsigned === -1 ? 0 : toSigned(unsigned); +} + +module.exports = { + StringCharIterator, + decodeSignedVLQ, + decodeUnsignedVLQ, + toSigned, +}; diff --git a/lib/internal/stream_base_commons.js b/lib/internal/stream_base_commons.js index 7bf3a2bab638..1c5d935ff6a6 100644 --- a/lib/internal/stream_base_commons.js +++ b/lib/internal/stream_base_commons.js @@ -2,6 +2,7 @@ const { Array, + ArrayBufferPrototypeGetDetached, Symbol, } = primordials; @@ -188,6 +189,15 @@ function onStreamRead(arrayBuffer) { if (isUint8Array(nextBuf)) stream[kBuffer] = ret = nextBuf; } + // If the buffer that will be reused for the next read was detached during + // the callback (e.g. by transferring a view into a byte `ReadableStream`), + // it can no longer be safely written to. Stop reading instead of handing + // the stale address back to the native read path. + const reusableBuf = stream[kBuffer]; + if (isUint8Array(reusableBuf) && + ArrayBufferPrototypeGetDetached(reusableBuf.buffer)) { + result = false; + } } else { const offset = streamBaseState[kArrayBufferOffset]; const buf = new FastBuffer(arrayBuffer, offset, nread); diff --git a/lib/internal/streams/end-of-stream.js b/lib/internal/streams/end-of-stream.js index f310cd6936fb..a4eef74aa603 100644 --- a/lib/internal/streams/end-of-stream.js +++ b/lib/internal/streams/end-of-stream.js @@ -107,6 +107,16 @@ function getEosOnCloseError(stream, readable, readableFinished, writable, writab return null; } +// A stream can report itself closed or aborted at the protocol level (e.g. +// HTTP/2) while its complete body is still buffered and readable. +function isEndPending(stream, readable, readableFinished, writable, writableFinished) { + if (stream.destroyed) return false; + const rState = stream._readableState; + const rPending = readable && !readableFinished && + rState?.ended === true && !rState.errored; + return rPending && (!writable || writableFinished); +} + // Internal only: if eos() can settle immediately, invoke the callback before // returning cleanup. Callers must tolerate cleanup yet to be assigned. const kEosNodeSynchronousCallback = Symbol('kEosNodeSynchronousCallback'); @@ -156,13 +166,15 @@ function eos(stream, options, callback) { */ let immediateResult; if (isClosed(stream)) { - immediateResult = getEosOnCloseError( - stream, - readable, - readableFinished, - writable, - writableFinished, - ); + if (!isEndPending(stream, readable, readableFinished, writable, writableFinished)) { + immediateResult = getEosOnCloseError( + stream, + readable, + readableFinished, + writable, + writableFinished, + ); + } } else if (wState?.errorEmitted || rState?.errorEmitted) { if (!willEmitClose) { immediateResult = getEosErrored(stream); @@ -270,6 +282,12 @@ function eos(stream, options, callback) { } }; + const onaborted = () => { + if (!isEndPending(stream, readable, readableFinished, writable, writableFinished)) { + onclose(); + } + }; + const onrequest = () => { stream.req.on('finish', onfinish); }; @@ -291,7 +309,7 @@ function eos(stream, options, callback) { // Not all streams will emit 'close' after 'aborted'. if (!willEmitClose && typeof stream.aborted === 'boolean') { - stream.on('aborted', onclose); + stream.on('aborted', onaborted); } stream.on('end', onend); @@ -303,7 +321,7 @@ function eos(stream, options, callback) { cleanup = () => { callback = nop; - stream.removeListener('aborted', onclose); + stream.removeListener('aborted', onaborted); stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); diff --git a/lib/internal/streams/fast-utf8-stream.js b/lib/internal/streams/fast-utf8-stream.js index 004ff14781f1..e4d48c17c41d 100644 --- a/lib/internal/streams/fast-utf8-stream.js +++ b/lib/internal/streams/fast-utf8-stream.js @@ -114,6 +114,8 @@ class Utf8Stream extends EventEmitter { #hwm = 16387; // 16 KB #file = null; #destroyed = false; + #writeInFlight = false; + #closeAfterWrite = false; #minLength = 0; #maxLength = 0; #maxWrite = kMaxWrite; @@ -229,9 +231,15 @@ class Utf8Stream extends EventEmitter { this.#flushSync = (...args) => this.#flushBufferSync(...args); this.#actualWrite = (...args) => this.#actualWriteBuffer(...args); this.#fsWriteSync = () => this.#fs.writeSync(this.#fd, this.#writingBuf); - this.#fsWrite = () => this.#fs.write(this.#fd, this.#writingBuf, (...args) => { - return this.#release(...args); - }); + this.#fsWrite = () => { + this.#writeInFlight = true; + try { + this.#fs.write(this.#fd, this.#writingBuf, (err, n) => this.#writeDone(err, n)); + } catch (err) { + this.#writeInFlight = false; + throw err; + } + }; } else { this.#writingBuf = ''; this.#write = (...args) => this.#writeUtf8(...args); @@ -239,9 +247,15 @@ class Utf8Stream extends EventEmitter { this.#flushSync = (...args) => this.#flushSyncUtf8(...args); this.#actualWrite = (...args) => this.#actualWriteUtf8(...args); this.#fsWriteSync = () => this.#fs.writeSync(this.#fd, this.#writingBuf, 'utf8'); - this.#fsWrite = () => this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (...args) => { - return this.#release(...args); - }); + this.#fsWrite = () => { + this.#writeInFlight = true; + try { + this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (err, n) => this.#writeDone(err, n)); + } catch (err) { + this.#writeInFlight = false; + throw err; + } + }; } // TODO(@jasnell): Support passing in an AbortSignal to cancel the stream. @@ -683,13 +697,42 @@ class Utf8Stream extends EventEmitter { this.#bufs = []; this.#lens = []; + // fs.write() runs on the thread pool, so the fd cannot be closed while + // one is in flight: the write would fail with EBADF, or land in whatever + // file is opened next and reuses the fd number. #writeDone() closes it + // once the write completes. + if (this.#writeInFlight) { + this.#closeAfterWrite = true; + return; + } + + this.#closeFd(); + } + + #writeDone(err, n) { + this.#writeInFlight = false; + try { + this.#release(err, n); + } finally { + // #release() may have started another write, for the rest of a partial + // write or from an 'error' listener that then called destroy(). The + // close then waits for that one. + if (this.#closeAfterWrite && !this.#writeInFlight) { + this.#closeAfterWrite = false; + this.#closeFd(); + } + } + } + + #closeFd() { const done = (err) => { if (err) { this.emit('error', err); return; } - if (this.#ending && !this.#writing) { + // destroy() may have dropped buffered data or a failed write. + if (this.#ending && !this.#writing && this.#len === 0) { this.emit('finish'); } this.emit('close'); @@ -727,7 +770,7 @@ class Utf8Stream extends EventEmitter { // we do it here to avoid the overhead of calculating the buffer size // in releaseWritingBuf. this.#writingBuf = Buffer.from(this.#writingBuf); - this.#fs.write(this.#fd, this.#writingBuf, (...args) => this.#release(...args)); + this.#fsWrite(); } } @@ -743,7 +786,7 @@ class Utf8Stream extends EventEmitter { this.#release(err); } } else { - this.#fs.write(this.#fd, this.#writingBuf, 'utf8', (...args) => this.#release(...args)); + this.#fsWrite(); } } diff --git a/lib/internal/streams/iter/broadcast.js b/lib/internal/streams/iter/broadcast.js index 00ed899d6537..54a39f33c101 100644 --- a/lib/internal/streams/iter/broadcast.js +++ b/lib/internal/streams/iter/broadcast.js @@ -9,7 +9,6 @@ const { ArrayIsArray, ArrayPrototypePush, - ArrayPrototypeShift, FunctionPrototypeCall, ObjectSetPrototypeOf, PromisePrototypeThen, @@ -50,6 +49,7 @@ const { from, isAsyncIterable, isSyncIterable, + kNextSyncBatch, } = require('internal/streams/iter/from'); const { @@ -64,16 +64,20 @@ const { kNullOnceOption, kResolvedPromise, convertChunks, - createBatchEntry, + createEntry, + snapshotByteView, getProtocolMethod, getWriterSignal, getMinCursor, onSignalAbort, parsePullArgs, toWriterUint8Array, + raceSignal, validateBatchEntry, - yieldAbortable, validateBudget, + newPendingPromise, + takeReject, + takeResolve, } = require('internal/streams/iter/utils'); const { converters, @@ -94,6 +98,10 @@ const kOnCancel = Symbol('kOnCancel'); const kPendingWriteRemoved = Symbol('kPendingWriteRemoved'); const kNoBroadcastError = Symbol('kNoBroadcastError'); const kSetFactorySignal = Symbol('kSetFactorySignal'); +// Write a batch of from() (already a Uint8Array[]), without converting it: +// synchronously, returning whether it was written, or asynchronously. +const kWriteBatchSync = Symbol('kWriteBatchSync'); +const kWriteBatch = Symbol('kWriteBatch'); function raceEndWithSignal(promise, signal) { if (!signal) return promise; @@ -117,7 +125,12 @@ class BroadcastImpl { #buffer = new RingBuffer(); #bufferStart = 0; #consumers = new SafeSet(); - #waiters = new SafeSet(); // Consumers with pending resolve + // Consumers with a pending resolve, each at most once. A RingBuffer + // rather than a Set: adding, clearing and iterating a Set allocate, and + // this changes for every chunk that consumers wait for. + #waiters = new RingBuffer(4); + // The list #notifyConsumers() swaps in for #waiters (see there). + #spareWaiters = new RingBuffer(4); #ended = false; #error; #errored = false; @@ -194,7 +207,9 @@ class BroadcastImpl { cursor: this.#bufferStart, resolve: null, reject: null, - pending: [], + // Reads requested while another one is pending. Rarely used, so it + // starts small. + pending: new RingBuffer(1), detached: false, error: kNoBroadcastError, }, null); @@ -215,7 +230,7 @@ class BroadcastImpl { function detach() { state.detached = true; - self.#waiters.delete(state); + self.#deleteWaiter(state); if (state.resolve) { state.resolve(new IterResult(true, undefined)); } @@ -265,16 +280,19 @@ class BroadcastImpl { } if (state.resolve) { - const { promise, resolve, reject } = PromiseWithResolvers(); - ArrayPrototypePush(state.pending, - new PendingRequest(resolve, reject)); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); + state.pending.push(new PendingRequest(resolve, reject)); return promise; } - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); state.resolve = resolve; state.reject = reject; - self.#waiters.add(state); + self.#waiters.push(state); return promise; }, @@ -514,11 +532,30 @@ class BroadcastImpl { #notifyConsumers() { const waiters = this.#waiters; - if (waiters.size === 0) return; + if (waiters.length === 0) return; // Swap out the waiters list so consumers that re-wait during - // resolve don't get processed twice in this cycle. - this.#waiters = new SafeSet(); - for (const consumer of waiters) { + // resolve don't get processed twice in this cycle. This runs for every + // write that consumers are waiting for, so the two lists are swapped + // back and forth rather than a new one created each time; a nested + // call, while the spare list is in use, gets a new one. + this.#waiters = this.#spareWaiters ?? new RingBuffer(4); + this.#spareWaiters = null; + try { + this.#notifyWaiters(waiters); + } finally { + waiters.clear(); + this.#spareWaiters = waiters; + } + } + + #deleteWaiter(consumer) { + const index = this.#waiters.indexOf(consumer); + if (index !== -1) this.#waiters.removeAt(index); + } + + #notifyWaiters(waiters) { + let consumer; + while ((consumer = waiters.shift()) !== undefined) { if (consumer.resolve) { const bufferIndex = consumer.cursor - this.#bufferStart; if (bufferIndex < this.#buffer.length) { @@ -537,11 +574,11 @@ class BroadcastImpl { if (consumer.detached && this.#deleteConsumer(consumer)) { this.#tryTrimBuffer(); } else if (this.#promotePending(consumer)) { - this.#waiters.add(consumer); + this.#waiters.push(consumer); } } else { // Still waiting -- put back - this.#waiters.add(consumer); + this.#waiters.push(consumer); } } } @@ -563,7 +600,7 @@ class BroadcastImpl { } #promotePending(consumer) { - const next = ArrayPrototypeShift(consumer.pending); + const next = consumer.pending.shift(); if (next === undefined) return false; consumer.resolve = next.resolve; consumer.reject = next.reject; @@ -576,14 +613,14 @@ class BroadcastImpl { consumer.reject = null; } while (consumer.pending.length > 0) { - ArrayPrototypeShift(consumer.pending).resolve( + consumer.pending.shift().resolve( new IterResult(true, undefined)); } } #rejectPending(consumer, reason) { while (consumer.pending.length > 0) { - ArrayPrototypeShift(consumer.pending).reject(reason); + consumer.pending.shift().reject(reason); } } } @@ -627,7 +664,9 @@ class BroadcastWriter { const canWrite = this.canWrite; if (canWrite === null) return null; if (canWrite) return PromiseResolve(true); - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); ArrayPrototypePush(this.#pendingDrains, new PendingRequest(resolve, reject)); return promise; } @@ -646,18 +685,18 @@ class BroadcastWriter { const signal = getWriterSignal(options); // Fast path: no signal, writer open, buffer has space if (this.#canUseWriteFastPath(signal)) { - const batch = createBatchEntry([converted]); + const batch = snapshotByteView(converted); this.#broadcast[kWrite](batch); this.#totalBytes += batch.byteLength; return kResolvedPromise; } - return this.#writeBatchSlow(createBatchEntry([converted]), signal); + return this.#writeBatchSlow(snapshotByteView(converted), signal); } writev(chunks, options) { const converted = convertChunks(chunks); const signal = getWriterSignal(options); - const batch = createBatchEntry(converted); + const batch = createEntry(converted); // Fast path: no signal, writer open, buffer has space if (this.#canUseWriteFastPath(signal)) { if (this.#state === 'open' && this.#broadcast[kWrite](batch)) { @@ -702,7 +741,7 @@ class BroadcastWriter { writeSync(chunk) { const converted = toWriterUint8Array(chunk); if (this.#state !== 'open') return false; - const batch = createBatchEntry([converted]); + const batch = snapshotByteView(converted); if (this.#broadcast[kWrite](batch)) { this.#totalBytes += batch.byteLength; return true; @@ -713,7 +752,7 @@ class BroadcastWriter { writevSync(chunks) { const converted = convertChunks(chunks); if (this.#state !== 'open') return false; - const batch = createBatchEntry(converted); + const batch = createEntry(converted); if (this.#broadcast[kWrite](batch)) { this.#totalBytes += batch.byteLength; return true; @@ -721,6 +760,20 @@ class BroadcastWriter { return false; } + [kWriteBatchSync](chunks) { + if (this.#state !== 'open') return false; + const batch = createEntry(chunks); + if (this.#broadcast[kWrite](batch)) { + this.#totalBytes += batch.byteLength; + return true; + } + return false; + } + + [kWriteBatch](chunks, signal) { + return this.#writeBatchSlow(createEntry(chunks), signal); + } + end(options) { const signal = getWriterSignal(options); if (this.#state === 'errored') return PromiseReject(this.#error); @@ -804,7 +857,9 @@ class BroadcastWriter { * @returns {Promise<void>} */ #createPendingWrite(batch, signal) { - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); const entry = new PendingWrite(batch, resolve, reject); this.#pendingWrites.push(entry); if (signal) { @@ -839,6 +894,7 @@ class BroadcastWriter { } #resolvePendingDrains(canWrite) { + if (this.#pendingDrains.length === 0) return; const drains = this.#pendingDrains; this.#pendingDrains = []; for (let i = 0; i < drains.length; i++) { @@ -847,6 +903,7 @@ class BroadcastWriter { } #rejectPendingDrains(error) { + if (this.#pendingDrains.length === 0) return; const drains = this.#pendingDrains; this.#pendingDrains = []; for (let i = 0; i < drains.length; i++) { @@ -953,20 +1010,58 @@ const Broadcast = { }; result.broadcast[kOnCancel] = onCancel; + const w = result.writer; + // Batches of a sync source are read synchronously, as pipeTo() reads + // them, while the writes succeed synchronously. With a 'drop-oldest' or + // 'drop-newest' policy writes always do, so the whole source would be + // written before any consumer reads: read it asynchronously. + const policy = result.broadcast.backpressurePolicy; + const readSync = policy === 'strict' || policy === 'unbounded'; + // Read as for await...of does, stopping once the broadcast is + // cancelled or its signal aborts; see raceSignal(). + const abortState = { __proto__: null, aborted: false }; + const consume = async (iterator) => { + const nextSyncBatch = readSync ? iterator[kNextSyncBatch] : undefined; + // The first batch is read with next(), so that it is written after + // Broadcast.from() has returned and its consumers have been created. + let first = true; + for (;;) { + let chunks = nextSyncBatch !== undefined && !first ? + FunctionPrototypeCall(nextSyncBatch, iterator) : undefined; + first = false; + if (chunks === undefined) { + const result = await iterator.next(); + if (result.done || abortState.aborted) return; + chunks = result.value; + } else if (chunks === null) { + return; + } + try { + if (!w[kWriteBatchSync](chunks)) { + await w[kWriteBatch](chunks, signal); + } + } catch (error) { + // As for await closes the source when its body throws, ignoring + // errors from closing it. + if (!abortState.aborted) { + try { + await iterator.return?.(); + } catch { + // The error writing the batch is thrown. + } + } + throw error; + } + if (abortState.aborted) return; + } + }; + const pump = async () => { - const w = result.writer; try { + controller.signal.throwIfAborted(); if (isAsyncIterable(source)) { - for await (const chunks of yieldAbortable(source, controller.signal)) { - controller.signal.throwIfAborted(); - if (ArrayIsArray(chunks)) { - if (!w.writevSync(chunks)) { - await w.writev(chunks, signal ? { signal } : undefined); - } - } else if (!w.writeSync(chunks)) { - await w.write(chunks, signal ? { signal } : undefined); - } - } + await raceSignal(source[SymbolAsyncIterator](), controller.signal, + abortState, consume); } else if (isSyncIterable(source)) { for (const chunks of source) { controller.signal.throwIfAborted(); diff --git a/lib/internal/streams/iter/classic.js b/lib/internal/streams/iter/classic.js index c1ed8ad51f53..2fe90d58a463 100644 --- a/lib/internal/streams/iter/classic.js +++ b/lib/internal/streams/iter/classic.js @@ -69,6 +69,9 @@ const { onSignalAbort, validateBackpressure, toWriterUint8Array, + newPendingPromise, + takeReject, + takeResolve, } = require('internal/streams/iter/utils'); const { Buffer } = require('buffer'); @@ -160,14 +163,14 @@ async function normalizeBatch(raw) { for (let i = 0; i < raw.length; i++) { const value = raw[i]; if (isUint8Array(value)) { - ArrayPrototypePush(batch, value); + batch[batch.length] = value; } else { // normalizeAsyncValue may await for async protocols (e.g. // toAsyncStreamable on yielded objects). Stream events during // the suspension are queued, not lost -- errors will surface // on the next loop iteration after this yield completes. for await (const normalized of normalizeAsyncValue(value)) { - ArrayPrototypePush(batch, normalized); + batch[batch.length] = normalized; } } } @@ -229,7 +232,7 @@ function createBatchedAsyncIterator(stream, normalize) { stream._readableState?.length > 0) { const c = stream.read(); if (c === null) break; - ArrayPrototypePush(batch, c); + batch[batch.length] = c; } if (normalize !== null) { const result = await normalize(batch); @@ -773,7 +776,9 @@ function fromWritable(writable, options = kNullPrototype) { } function queueWrite(chunks, signal) { - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); const entry = new QueuedWrite(chunks, resolve, reject); pendingWrites.push(entry); installDrainListener(); @@ -1049,7 +1054,9 @@ function fromWritable(writable, options = kNullPrototype) { if (pendingWrites.length === 0 && !isFull()) { return PromiseResolve(true); } - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); ArrayPrototypePush(drainWaiters, new PendingRequest(resolve, reject)); installDrainListener(); return promise; diff --git a/lib/internal/streams/iter/consumers.js b/lib/internal/streams/iter/consumers.js index 0751d2cc95f6..d8fd1bee495d 100644 --- a/lib/internal/streams/iter/consumers.js +++ b/lib/internal/streams/iter/consumers.js @@ -14,14 +14,17 @@ const { ArrayBufferPrototypeSlice, ArrayPrototypeMap, ArrayPrototypePush, - ArrayPrototypeShift, ArrayPrototypeSlice, FunctionPrototypeCall, ObjectFreeze, + ObjectSetPrototypeOf, Promise, PromisePrototypeThen, + PromiseReject, + PromiseResolve, SafePromiseAllReturnVoid, SafeSet, + SuppressedError, Symbol, SymbolAsyncIterator, TypedArrayPrototypeGetBuffer, @@ -38,6 +41,7 @@ const { }, } = require('internal/errors'); const { TextDecoder } = require('internal/encoding'); +const { RingBuffer } = require('internal/streams/iter/ringbuffer'); const { validateFunction, } = require('internal/validators'); @@ -51,12 +55,15 @@ const { fromSync, isAsyncIterable, isSyncIterable, + kNextUncancellable, } = require('internal/streams/iter/from'); const { + IterResult, kNullOnceOption, concatBytes, getProtocolMethod, + raceSignal, recordChunk, validateRecordedChunks, yieldAbortable, @@ -107,19 +114,19 @@ function collectSync(source, limit) { // Normalize source via fromSync() - accepts strings, ArrayBuffers, protocols, etc. const normalized = fromSync(source); const chunks = []; - const checks = []; + const byteLengths = []; let totalBytes = 0; for (const batch of normalized) { for (let i = 0; i < batch.length; i++) { - totalBytes += recordChunk(chunks, checks, batch[i]); + totalBytes += recordChunk(chunks, byteLengths, batch[i]); if (limit !== undefined && totalBytes > limit) { throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes); } } } - return validateRecordedChunks(chunks, checks); + return validateRecordedChunks(chunks, byteLengths); } /** @@ -135,33 +142,62 @@ async function collectAsync(source, signal, limit) { // Normalize source via from() - accepts strings, ArrayBuffers, protocols, etc. const normalized = from(source); const chunks = []; - const checks = []; + const byteLengths = []; // Fast path: no signal and no limit if (!signal && limit === undefined) { for await (const batch of normalized) { for (let i = 0; i < batch.length; i++) { - recordChunk(chunks, checks, batch[i]); + recordChunk(chunks, byteLengths, batch[i]); } } - return validateRecordedChunks(chunks, checks); + return validateRecordedChunks(chunks, byteLengths); } - // Slow path: with signal or limit checks + // Slow path: with signal or limit byteLengths let totalBytes = 0; - const iterable = signal ? yieldAbortable(normalized, signal) : normalized; - - for await (const batch of iterable) { - signal?.throwIfAborted(); + function recordBatch(batch) { for (let i = 0; i < batch.length; i++) { - totalBytes += recordChunk(chunks, checks, batch[i]); + totalBytes += recordChunk(chunks, byteLengths, batch[i]); if (limit !== undefined && totalBytes > limit) { throw new ERR_OUT_OF_RANGE('totalBytes', `<= ${limit}`, totalBytes); } } } - return validateRecordedChunks(chunks, checks); + if (!signal) { + for await (const batch of normalized) recordBatch(batch); + return validateRecordedChunks(chunks, byteLengths); + } + + // Read as for await...of does, stopping once the signal aborts; see + // raceSignal(). + // A from() source is read with kNextUncancellable: on an abort, + // raceSignal() rejects and closes the source at once, and a read still + // pending is ignored. + const state = { __proto__: null, aborted: false }; + async function consume(iterator) { + const uncancellable = iterator[kNextUncancellable] !== undefined; + for (;;) { + const result = await (uncancellable ? + iterator[kNextUncancellable](true) : iterator.next()); + if (result.done || state.aborted) return; + try { + recordBatch(result.value); + } catch (error) { + // As for await closes the source when its body throws, ignoring + // errors from closing it. + try { + await iterator.return?.(); + } catch { + // The error recording the batch is thrown. + } + throw error; + } + } + } + await raceSignal(normalized[SymbolAsyncIterator](), signal, state, consume); + return validateRecordedChunks(chunks, byteLengths); } /** @@ -473,6 +509,84 @@ MergeEntry.prototype = ObjectFreeze({ __proto__: null }); * @param {...(AsyncIterable<Uint8Array[]>|object)} args * @returns {AsyncIterable<Uint8Array[]>} */ +/** + * The iterator of merge() of a single source without a signal: what an + * async generator doing `for await (const batch of source) yield batch;` + * gives, without its layer for every batch. Calls to next() are passed to + * the source's iterator, from from(), which queues them as an async + * generator does. return() and throw() wait for the last next() before + * closing the source, as the generator would queue them, and later calls + * wait for them in turn. The source is opened by the first next(). + */ +class MergeSourceIterator { + #source; + #iterator = null; + // The last next() of the source's iterator, and the promise of return() + // or throw() once one is called. + #last = null; + #closing = null; + + constructor(source) { + this.#source = source; + } + + next() { + if (this.#closing !== null) { + return PromisePrototypeThen(this.#closing, doneResult, doneResult); + } + try { + this.#iterator ??= this.#source[SymbolAsyncIterator](); + const next = PromiseResolve(this.#iterator.next()); + this.#last = next; + return next; + } catch (error) { + this.#closing = PromiseReject(error); + markPromiseAsHandled(this.#closing); + return this.#closing; + } + } + + return(value) { + return this.#close(() => new IterResult(true, value), false); + } + + throw(error) { + return this.#close(() => { throw error; }, true); + } + + // Close the source once the last next() has settled, if it was opened, + // then settle with `settle()`. Errors closing it are ignored if `quiet`, + // as for await ignores them when its body throws. + #close(settle, quiet) { + if (this.#closing !== null) { + return PromisePrototypeThen(this.#closing, settle, settle); + } + const iterator = this.#iterator; + if (iterator === null) { + this.#closing = PromiseResolve(); + return PromisePrototypeThen(this.#closing, settle); + } + const close = () => { + const closed = PromiseResolve(iterator.return?.()); + return quiet ? PromisePrototypeThen(closed, undefined, () => {}) : closed; + }; + const closing = PromisePrototypeThen(this.#last ?? PromiseResolve(), + close, close); + this.#closing = closing; + markPromiseAsHandled(closing); + return PromisePrototypeThen(closing, settle); + } + + [SymbolAsyncIterator]() { + return this; + } +} +ObjectSetPrototypeOf(MergeSourceIterator.prototype, null); + +function doneResult() { + return new IterResult(true, undefined); +} + function merge(...args) { let sources; let options; @@ -492,6 +606,28 @@ function merge(...args) { // Normalize each source via from() const normalized = ArrayPrototypeMap(sources, (source) => from(source)); + if (normalized.length === 1) { + // A single source is read without an async generator layer for every + // batch (see MergeSourceIterator). With a signal, the source is read through + // yieldAbortable(), which rejects a pending read when the signal aborts + // (also before the first read), closes the source, and then ends. An + // async iterable is made abortable before from(), so that an abort + // closes it even while from() is reading it. + const { signal } = options; + return { + __proto__: null, + [SymbolAsyncIterator]() { + if (signal === undefined) { + return new MergeSourceIterator(normalized[0]); + } + const source = isAsyncIterable(sources[0]) ? + from(yieldAbortable(sources[0], signal)) : + yieldAbortable(normalized[0], signal); + return source[SymbolAsyncIterator](); + }, + }; + } + return { __proto__: null, async *[SymbolAsyncIterator]() { @@ -501,21 +637,11 @@ function merge(...args) { if (normalized.length === 0) return; - if (normalized.length === 1) { - const source = signal !== undefined && isAsyncIterable(sources[0]) ? - from(yieldAbortable(sources[0], signal)) : - yieldAbortable(normalized[0], signal); - for await (const batch of source) { - yield batch; - } - return; - } - // Multiple sources - use a ready queue so that batches that settle // between consumer pulls are drained synchronously without an extra // async tick per batch. Each source has at most one pending .next() // at a time. Every batch from every source is preserved. - const ready = []; + const ready = new RingBuffer(); const pendingPulls = new SafeSet(); let activeCount = normalized.length; let waitResolve = null; @@ -540,8 +666,7 @@ function merge(...args) { if (result.done) { activeCount--; } else { - ArrayPrototypePush(ready, - new MergeEntry(iterator, result.value, undefined)); + ready.push(new MergeEntry(iterator, result.value, undefined)); } if (waitResolve) { waitResolve(); @@ -552,7 +677,7 @@ function merge(...args) { const onRejected = (iterator, reason) => { pendingPulls.delete(iterator); if (stopped) return; - ArrayPrototypePush(ready, new MergeEntry(undefined, undefined, reason)); + ready.push(new MergeEntry(undefined, undefined, reason)); if (waitResolve) { waitResolve(); waitResolve = null; @@ -579,7 +704,7 @@ function merge(...args) { // Drain ready queue synchronously while (ready.length > 0) { - const item = ArrayPrototypeShift(ready); + const item = ready.shift(); if (item.iterator === undefined) { throw item.reason; } @@ -645,7 +770,6 @@ async function cleanupIterators(iterators, primaryError, pendingPulls) { // Both a primary error and a cleanup error occurred. // Wrap in SuppressedError so neither is lost: // .error = primaryError, .suppressed = cleanupError. - // eslint-disable-next-line no-restricted-syntax throw new SuppressedError(primaryError, cleanupError); } // No primary error - the cleanup error is the only error. diff --git a/lib/internal/streams/iter/from.js b/lib/internal/streams/iter/from.js index c89b7ea6d080..c9f16d841860 100644 --- a/lib/internal/streams/iter/from.js +++ b/lib/internal/streams/iter/from.js @@ -9,16 +9,18 @@ const { ArrayBufferIsView, ArrayIsArray, ArrayPrototypeEvery, - ArrayPrototypePush, ArrayPrototypeSlice, DataViewPrototypeGetBuffer, DataViewPrototypeGetByteLength, DataViewPrototypeGetByteOffset, FunctionPrototypeCall, + ObjectFreeze, + ObjectGetOwnPropertyDescriptor, + ObjectGetPrototypeOf, ObjectSetPrototypeOf, PromisePrototypeThen, + PromiseReject, PromiseResolve, - PromiseWithResolvers, Symbol, SymbolAsyncIterator, SymbolIterator, @@ -40,6 +42,7 @@ const { lazyDOMException } = require('internal/util'); const { isAnyArrayBuffer, + isGeneratorObject, isPromise, isTypedArray, isUint8Array, @@ -53,7 +56,14 @@ const { const { IterResult, + kActive, + kDone, kResolvedPromise, + newPendingPromise, + takeReject, + takeResolve, + kStart, + createOperationQueue, getProtocolMethod, toUint8Array, } = require('internal/streams/iter/utils'); @@ -105,7 +115,9 @@ function throwIfNormalizationCancelled(context) { */ function waitForNormalization(value, context) { if (context === undefined) return value; - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); const onCancel = () => { if (context.resolve === onCancel) context.resolve = null; reject(context.reason); @@ -134,9 +146,84 @@ function waitForNormalization(value, context) { return promise; } +// The method of an iterator returned by from() for a sync iterable that reads +// the next batch synchronously when it can, for pipeTo(): see nextSyncBatch() +// in createSyncSourceNormalizer(). +const kNextSyncBatch = Symbol('kNextSyncBatch'); + +// The method of an iterator returned by from() for an async iterable that +// reads like next(), for internal callers that stop reading when they +// cancel the normalization (pipeTo(), pull() pipelines, consumers). It +// saves the read a promise of its own: see createAsyncSourceNormalizer(). +// With `releasable` true, a return() or throw() while a read is pending +// closes the source at once, as for next(), but does not settle the +// pending read early: the read settles when the source's next() does, +// rejecting with the cancellation reason, and the caller ignores it. +// Without it, the caller must not cancel while a read is pending (pipeTo() +// without a signal). The first call decides for all reads. +const kNextUncancellable = Symbol('kNextUncancellable'); + +// Methods of the iterator returned by yieldNormalizationAbortable(), used by +// createAsyncSourceNormalizer() for kNextUncancellable. +const kReadUncancellable = Symbol('kReadUncancellable'); +const kToIterResult = Symbol('kToIterResult'); +const kReadFailed = Symbol('kReadFailed'); +// A read of the source that a cancellation can interrupt, for +// createAsyncSourceNormalizer(): see kRead in yieldNormalizationAbortable(). +const kSetReadHandlers = Symbol('kSetReadHandlers'); +const kRead = Symbol('kRead'); +// The result kReadUncancellable gives once the source is done. +const kDoneSourceResult = ObjectFreeze({ __proto__: null, value: undefined, done: true }); + function createNormalizationIterator(createIterator) { const context = createNormalizationContext(); const iterator = createIterator(context); + if (iterator[kNextUncancellable] !== undefined) { + return ObjectSetPrototypeOf({ + next(value) { + return FunctionPrototypeCall(iterator.next, iterator, value); + }, + return(value) { + cancelNormalization( + context, lazyDOMException('Aborted', 'AbortError')); + return FunctionPrototypeCall(iterator.return, iterator, value); + }, + throw(error) { + cancelNormalization(context, error, true); + return FunctionPrototypeCall(iterator.throw, iterator, error); + }, + [kNextUncancellable](releasable) { + return iterator[kNextUncancellable](releasable); + }, + [SymbolAsyncIterator]() { + return this; + }, + [kValidatedSource]: true, + }, null); + } + if (iterator[kNextSyncBatch] !== undefined) { + return ObjectSetPrototypeOf({ + next(value) { + return FunctionPrototypeCall(iterator.next, iterator, value); + }, + return(value) { + cancelNormalization( + context, lazyDOMException('Aborted', 'AbortError')); + return FunctionPrototypeCall(iterator.return, iterator, value); + }, + throw(error) { + cancelNormalization(context, error, true); + return FunctionPrototypeCall(iterator.throw, iterator, error); + }, + [kNextSyncBatch]() { + return iterator[kNextSyncBatch](); + }, + [SymbolAsyncIterator]() { + return this; + }, + [kValidatedSource]: true, + }, null); + } return ObjectSetPrototypeOf({ next(value) { return FunctionPrototypeCall(iterator.next, iterator, value); @@ -153,6 +240,7 @@ function createNormalizationIterator(createIterator) { [SymbolAsyncIterator]() { return this; }, + [kValidatedSource]: true, }, null); } @@ -162,6 +250,7 @@ function createNormalizationSource(createIterator) { [SymbolAsyncIterator]() { return createNormalizationIterator(createIterator); }, + [kValidatedSource]: true, }; } @@ -317,56 +406,6 @@ function* yieldBoundedBatch(batch) { } } -/** - * Normalize a sync streamable source, yielding batches of Uint8Array. - * @param {Iterable} source - * @yields {Uint8Array[]} - */ -function* normalizeSyncSource(source) { - let batch = []; - - for (const value of source) { - // Fast path 1: value is already a Uint8Array[] batch - if (isUint8ArrayBatch(value)) { - if (batch.length > 0) { - yield batch; - batch = []; - } - yield* yieldBoundedBatch(value); - continue; - } - // Fast path 2: value is a single Uint8Array (very common) - if (isUint8Array(value)) { - ArrayPrototypePush(batch, value); - if (batch.length === FROM_BATCH_SIZE) { - yield batch; - batch = []; - } - continue; - } - // Slow path: normalize the value - if (batch.length > 0) { - yield batch; - batch = []; - } - let valueBatch = []; - for (const chunk of normalizeSyncValue(value)) { - ArrayPrototypePush(valueBatch, chunk); - if (valueBatch.length === FROM_BATCH_SIZE) { - yield valueBatch; - valueBatch = []; - } - } - if (valueBatch.length > 0) { - yield valueBatch; - } - } - - if (batch.length > 0) { - yield batch; - } -} - function yieldNormalizationAbortable(source, context) { if (context === undefined) return source; return { @@ -410,38 +449,211 @@ function yieldNormalizationAbortable(source, context) { } } + // Settle a pending next() with a result of the source's next(). Throws + // (to be handled by the caller) like the checks it replaces would. + function toIterResult(result) { + throwIfNormalizationCancelled(context); + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.next()', result); + } + if (result.done) { + reading = false; + throwIfNormalizationCancelled(context); + completed = true; + closed = true; + return new IterResult(true, result.value); + } + const value = result.value; + reading = false; + throwIfNormalizationCancelled(context); + return new IterResult(false, value); + } + + function onUncancellableResult(result) { + try { + return toIterResult(result); + } catch (error) { + reading = false; + throw error; + } + } + + // The handlers of kRead, set once by kSetReadHandlers, and whether a + // kRead is pending. + let onRead = null; + let onReadError = null; + let readPending = false; + + // Fail a kRead, closing the source first if the normalization has + // been cancelled. + function failRead(error) { + if (context.cancelled) { + PromisePrototypeThen(closeSource(true), () => { + reading = false; + onReadError(error); + }); + return; + } + reading = false; + onReadError(error); + } + + // context.resolve while a kRead is pending. + function onReadCancelled() { + if (!readPending) return; + readPending = false; + context.resolve = null; + failRead(context.reason); + } + + function onReadResult(result) { + if (!readPending) return; + readPending = false; + if (context.resolve === onReadCancelled) context.resolve = null; + let iterResult; + try { + iterResult = toIterResult(result); + } catch (error) { + failRead(error); + return; + } + onRead(iterResult); + } + + function onReadRejected(error) { + if (!readPending) return; + readPending = false; + if (context.resolve === onReadCancelled) context.resolve = null; + failRead(error); + } + + // Reject a pending next(), closing the source first if the + // normalization has been cancelled. + function rejectNext(reject, error) { + if (context.cancelled) { + PromisePrototypeThen(closeSource(true), () => { + reading = false; + reject(error); + }); + return; + } + reading = false; + reject(error); + } + return ObjectSetPrototypeOf({ - async next() { + // next() runs for every value of the source, so instead of being an + // async function awaiting waitForNormalization(), it waits for the + // source with a single promise, which a cancellation rejects + // directly. + next() { if (completed) { - return new IterResult(true, undefined); + return PromiseResolve(new IterResult(true, undefined)); } - throwIfNormalizationCancelled(context); + if (context.cancelled) return PromiseReject(context.reason); reading = true; + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); + let next; try { - const next = FunctionPrototypeCall(nextMethod, iterator); - const result = await waitForNormalization(next, context); - if ((typeof result !== 'object' && typeof result !== 'function') || - result === null) { - throw new ERR_INVALID_RETURN_VALUE( - 'an object', 'iterator.next()', result); - } - if (result.done) { - reading = false; - throwIfNormalizationCancelled(context); - completed = true; - closed = true; - return new IterResult(true, result.value); - } - const value = result.value; - reading = false; - throwIfNormalizationCancelled(context); - return new IterResult(false, value); + next = FunctionPrototypeCall(nextMethod, iterator); + } catch (error) { + rejectNext(reject, error); + return promise; + } + // The first of the source's result and a cancellation settles + // next(); whichever comes later is ignored. + let settled = false; + const onCancel = () => { + if (settled) return; + settled = true; + if (context.resolve === onCancel) context.resolve = null; + rejectNext(reject, context.reason); + }; + context.resolve = onCancel; + PromisePrototypeThen( + PromiseResolve(next), + (result) => { + if (settled) return; + settled = true; + if (context.resolve === onCancel) context.resolve = null; + let iterResult; + try { + iterResult = toIterResult(result); + } catch (error) { + rejectNext(reject, error); + return; + } + resolve(iterResult); + }, + (error) => { + if (settled) return; + settled = true; + if (context.resolve === onCancel) context.resolve = null; + rejectNext(reject, error); + }); + return promise; + }, + // Like next(), for a caller that ignores the read if it cancels the + // normalization while the read is pending (see kNextUncancellable), + // in two parts so that the caller handles the result in the same + // reaction: kReadUncancellable starts the read, returning a promise + // for the source's result, and the caller passes that result to + // kToIterResult, or calls kReadFailed if the promise rejects. + [kReadUncancellable]() { + if (completed) { + return PromiseResolve(kDoneSourceResult); + } + if (context.cancelled) return PromiseReject(context.reason); + reading = true; + let next; + try { + next = FunctionPrototypeCall(nextMethod, iterator); } catch (error) { - if (context.cancelled) await closeSource(true); reading = false; - throw error; + return PromiseReject(error); } + return PromiseResolve(next); + }, + [kToIterResult]: onUncancellableResult, + // Like next(), calling the handlers set by kSetReadHandlers instead + // of settling a promise of its own: onRead with the result, or + // onReadError with the error, possibly synchronously. A cancellation + // calls onReadError with its reason. The handlers are the same for + // every read, so that a read takes no closure, and the caller can + // handle the result in the same reaction. + [kSetReadHandlers](resultHandler, errorHandler) { + onRead = resultHandler; + onReadError = errorHandler; + }, + [kRead]() { + if (completed) { + onRead(new IterResult(true, undefined)); + return; + } + if (context.cancelled) { + onReadError(context.reason); + return; + } + reading = true; + let next; + try { + next = FunctionPrototypeCall(nextMethod, iterator); + } catch (error) { + failRead(error); + return; + } + readPending = true; + context.resolve = onReadCancelled; + PromisePrototypeThen(PromiseResolve(next), onReadResult, + onReadRejected); + }, + [kReadFailed]() { + reading = false; }, async return(value) { await closeSource( @@ -570,116 +782,767 @@ async function* normalizeAsyncValue( } /** - * Normalize an async streamable source, yielding batches of Uint8Array. - * @param {AsyncIterable|Iterable} source + * Normalize a value of an async source that is neither a Uint8Array nor a + * Uint8Array[] batch, yielding batches of Uint8Array. Chunks are batched, + * but whatever has been collected is yielded before waiting on async content + * (such as a nested async iterable), so data is not held back until it ends. + * @param {any} value + * @param {object} context + * @param {boolean} [allowNestedAsync] Whether nested async iterables and + * toAsyncStreamable are allowed (they are not in sync sources). * @yields {Uint8Array[]} */ -async function* normalizeAsyncSource(source, context) { - throwIfNormalizationCancelled(context); +async function* normalizeAsyncSourceValue(value, context, + allowNestedAsync = true) { + let batch = []; + for await (const chunk of + normalizeAsyncValue(value, allowNestedAsync, context, true)) { + if (chunk === kFlushBatch) { + if (batch.length > 0) { + yield batch; + batch = []; + } + continue; + } + batch[batch.length] = chunk; + if (batch.length === FROM_BATCH_SIZE) { + yield batch; + batch = []; + } + } + if (batch.length > 0) { + yield batch; + } +} + +/** + * Iterator normalizing an async iterable source into batches of Uint8Array. + * + * This is what an async generator looping over the source with for await + * would do, written out by hand: the source is read for every batch, and an + * async generator layer costs several promises and an async frame each + * time. Values that are already batches or Uint8Arrays (the common case) + * are handled with one promise per batch; any other value is normalized by + * normalizeAsyncSourceValue(). As with an async generator: + * - nothing happens until the first next(); + * - calls made while one is in progress are queued; + * - an error from the source ends the iteration without closing the source, + * and an error normalizing a value closes the source first; + * - return() closes the value being normalized and the source, propagating + * errors from closing them, and throw() closes them ignoring such errors. + * @param {AsyncIterable} source + * @param {object} context + * @returns {object} An object with next(), return() and throw(). + */ +function createAsyncSourceNormalizer(source, context) { + let state = kStart; + // The source iterator, from yieldNormalizationAbortable(). Its return() + // is an async function, so calling it cannot throw synchronously. + let iterator; + // The value being normalized: a sync iterator of the sub-batches of an + // oversized batch, or a normalizeAsyncSourceValue() generator. + let boundedBatches = null; + let valueBatches = null; + // Whether the source is read with kNextUncancellable: set by the + // kNextUncancellable method, for callers that ignore a read pending when + // they cancel the normalization. releasableReads: whether the caller + // can cancel while a read is pending, so that a cancellation releases it + // (pipeTo() without a signal cannot, and its reads skip that). + // readReleased: whether a cancellation has released such a read (see + // onUncancellableCancelled()). + let uncancellable = false; + let releasableReads = false; + let readReleased = false; + // Whether the source is read with kRead, and the settling functions of + // the read's promise while it is pending. + let readable = false; + let resolveRead = null; + let rejectRead = null; + const { run, settled } = createOperationQueue(); + + function finish(result) { + settled(); + return result; + } + + function fail(error) { + state = kDone; + settled(); + throw error; + } + + // Closing for a throw completion: wait, but ignore errors. + function closeQuietly(it) { + return PromisePrototypeThen(it.return(), undefined, () => {}); + } + + function onBodyError(error) { + // Like for await when its body throws: close the source, keep the error. + valueBatches = null; + boundedBatches = null; + state = kDone; + return PromisePrototypeThen( + closeQuietly(iterator), () => fail(error)); + } + + function onSourceResult(result) { + if (result.done) { + state = kDone; + return finish(new IterResult(true, undefined)); + } + try { + return handleValue(result.value, result); + } catch (error) { + return onBodyError(error); + } + } + + // `result` is the source's result for `value`. When the source is read + // with kRead or kReadUncancellable, it is an IterResult of + // yieldNormalizationAbortable(), passed on as it is for a batch passed on + // unchanged. + function handleValue(value, result) { + if (isUint8ArrayBatch(value)) { + if (value.length <= FROM_BATCH_SIZE) { + if (value.length === 0) return pullSource(); + if (readable || uncancellable) { + return finish(result); + } + return finish(new IterResult(false, value)); + } + boundedBatches = yieldBoundedBatch(value); + return pullValue(); + } + if (isUint8Array(value)) return finish(new IterResult(false, [value])); + valueBatches = normalizeAsyncSourceValue(value, context); + return pullValue(); + } + + function onValueResult(result) { + if (result.done) { + valueBatches = null; + return pullSource(); + } + return finish(new IterResult(false, result.value)); + } + + // A kReadUncancellable result: handled as the result of the source's + // next() is, in the same reaction. + function onUncancellableResult(result) { + let iterResult; + try { + iterResult = iterator[kToIterResult](result); + } catch (error) { + return fail(error); + } + return onSourceResult(iterResult); + } + + function onUncancellableError(error) { + iterator[kReadFailed](); + return fail(error); + } - // Prefer async iteration if available + // The same, for a releasable read. + function onReleasableResult(result) { + if (readReleased) throw context.reason; + context.resolve = null; + return onUncancellableResult(result); + } + + function onReleasableError(error) { + if (readReleased) throw context.reason; + context.resolve = null; + return onUncancellableError(error); + } + + // context.resolve while a releasable kNextUncancellable read is pending: + // the caller ignores that read, so it is released rather than waited for. + // The normalization ends, the source is closed at once, as for a + // cancelled kRead (errors ignored), and the operations queued behind the + // read, such as the return() that cancelled it, run now. The read settles + // when the source's next() does, rejecting with the cancellation reason. + function onUncancellableCancelled() { + context.resolve = null; + readReleased = true; + state = kDone; + markPromiseAsHandled(iterator.return()); + settled(); + } + + function readReleasable() { + const cancelledBefore = context.cancelled; + const read = iterator[kReadUncancellable](); + if (!cancelledBefore) { + // Cancelled while the source's next() was called, or later. + if (context.cancelled) { + onUncancellableCancelled(); + } else { + context.resolve = onUncancellableCancelled; + } + } + return PromisePrototypeThen(read, onReleasableResult, onReleasableError); + } + + // The kRead handlers: the result is handled in the reaction to the + // source's result, and settles the read's promise. + function onRead(result) { + const resolve = resolveRead; + const reject = rejectRead; + resolveRead = rejectRead = null; + let settledWith; + try { + settledWith = onSourceResult(result); + } catch (error) { + reject(error); + return; + } + resolve(settledWith); + } + + function onReadError(error) { + const reject = rejectRead; + resolveRead = rejectRead = null; + state = kDone; + settled(); + reject(error); + } + + function pullSource() { + if (uncancellable) { + if (releasableReads) return readReleasable(); + return PromisePrototypeThen(iterator[kReadUncancellable](), + onUncancellableResult, onUncancellableError); + } + if (readable) { + // One promise for the read, which a cancellation rejects, instead of + // next()'s promise and a reaction to it. + const promise = newPendingPromise(); + resolveRead = takeResolve(); + rejectRead = takeReject(); + iterator[kRead](); + return promise; + } + return PromisePrototypeThen(iterator.next(), onSourceResult, fail); + } + + function pullValue() { + if (boundedBatches !== null) { + const result = boundedBatches.next(); + if (!result.done) return finish(new IterResult(false, result.value)); + boundedBatches = null; + return pullSource(); + } + return PromisePrototypeThen( + valueBatches.next(), onValueResult, onBodyError); + } + + function doNext() { + if (state === kDone) { + return PromiseResolve(finish(new IterResult(true, undefined))); + } + if (state === kStart) { + try { + throwIfNormalizationCancelled(context); + const iterable = yieldNormalizationAbortable(source, context); + iterator = iterable[SymbolAsyncIterator](); + if (iterator[kSetReadHandlers] !== undefined) { + iterator[kSetReadHandlers](onRead, onReadError); + readable = true; + } + } catch (error) { + state = kDone; + settled(); + return PromiseReject(error); + } + state = kActive; + } + if (boundedBatches !== null || valueBatches !== null) { + return PromiseResolve(pullValue()); + } + return pullSource(); + } + + function doReturn(value) { + const result = new IterResult(true, value); + if (state !== kActive) { + state = kDone; + return PromiseResolve(finish(result)); + } + state = kDone; + boundedBatches = null; + const pending = valueBatches; + valueBatches = null; + // Close the value being normalized, then the source. If closing the + // value fails, the source is still closed and the error kept. + let closed; + if (pending === null) { + closed = iterator.return(); + } else { + closed = PromisePrototypeThen( + pending.return(), + () => iterator.return(), + (error) => PromisePrototypeThen(closeQuietly(iterator), () => { + throw error; + })); + } + return PromisePrototypeThen(closed, () => finish(result), fail); + } + + function doThrow(error) { + if (state !== kActive) { + state = kDone; + settled(); + return PromiseReject(error); + } + state = kDone; + boundedBatches = null; + const pending = valueBatches; + valueBatches = null; + const closed = pending === null ? closeQuietly(iterator) : + PromisePrototypeThen(closeQuietly(pending), () => closeQuietly(iterator)); + return PromisePrototypeThen(closed, () => fail(error)); + } + + return ObjectSetPrototypeOf({ + next() { return run(doNext); }, + return(value) { return run(doReturn, value); }, + throw(error) { return run(doThrow, error); }, + [kNextUncancellable](releasable = false) { + uncancellable = true; + releasableReads = releasable; + return run(doNext); + }, + }, null); +} + +/** + * Normalize an async streamable source, yielding batches of Uint8Array. + * @param {AsyncIterable|Iterable} source + * @param {object} context + * @returns {object} An async iterator. + */ +function normalizeAsyncSource(source, context) { + // Prefer async iteration if available. if (isAsyncIterable(source)) { - const iterable = yieldNormalizationAbortable(source, context); - for await (const value of iterable) { - // Fast path 1: value is already a Uint8Array[] batch - if (isUint8ArrayBatch(value)) { - yield* yieldBoundedBatch(value); - continue; + return createAsyncSourceNormalizer(source, context); + } + return createSyncSourceNormalizer(source, context); +} + +// A value of a sync source that is not a Uint8Array or a Uint8Array[] +// batch, returned by SyncSourceReader to be normalized asynchronously. +function SyncSourceValue(value) { + this.value = value; +} +SyncSourceValue.prototype = ObjectFreeze({ __proto__: null }); + +/** + * Read a sync iterable source for from(): returns Uint8Array[] batches, + * collecting single Uint8Arrays into batches of up to FROM_BATCH_SIZE + * chunks, and a SyncSourceValue for any other value, after the chunks + * collected before it. + * + * This is what a sync generator doing `for (const value of source)` would + * yield, written out by hand, as it runs for every batch: next(), return() + * and throw() behave as that generator's do. The source is closed, as + * for...of closes it, when the reader is returned or thrown into while it + * is reading the source, or when the normalization is found cancelled; + * errors closing it are ignored for throw() and cancellation. An error from + * the source's next() or [Symbol.iterator]() ends the reader without + * closing the source. + */ +// %GeneratorPrototype%.next, taken before user code runs. +const GeneratorPrototypeNext = + ObjectGetPrototypeOf(function*() {}).prototype.next; + +// How a SyncSourceReader calls the next() of its source's iterator. +const kNextOwn = 1; +const kNextGenerator = 2; + +// The states of a SyncSourceReader: not started, reading the source, done. +const kReaderStart = 0; +const kReaderActive = 1; +const kReaderDone = 2; + +class SyncSourceReader { + #source; + #context; + #iterator = null; + #next = null; + // kNextGenerator if the source's iterator is a generator whose next() is + // %GeneratorPrototype%.next, which is then called as a constant; kNextOwn + // if its next() is an own data property, which is then called as + // `iterator.next()`; otherwise 0, and #next is called with + // FunctionPrototypeCall(). Calls V8 can inline make reading single chunks + // faster. (Generators of different generator functions don't share a map, + // so for them `iterator.next()` would be a megamorphic load per chunk.) + #direct = 0; + #state = kReaderStart; + // Single Uint8Arrays read and not yet returned. + #batch = []; + // A value to return on the next call, after the batch returned before it. + #pending = undefined; + // A batch larger than FROM_BATCH_SIZE being returned in slices, and the + // offset of the next slice. + #large = null; + #offset = 0; + + constructor(source, context) { + this.#source = source; + this.#context = context; + } + + next() { + switch (this.#state) { + case kReaderDone: + return new IterResult(true, undefined); + case kReaderStart: + this.#start(); + break; + } + if (this.#pending !== undefined) { + const value = this.#pending; + this.#pending = undefined; + return new IterResult(false, value); + } + if (this.#large !== null) return new IterResult(false, this.#nextSlice()); + // Read into locals: the loop runs for every chunk of the source. + const iterator = this.#iterator; + const next = this.#next; + const direct = this.#direct; + const context = this.#context; + const batch = this.#batch; + for (;;) { + let value; + try { + const result = direct === kNextGenerator ? + FunctionPrototypeCall(GeneratorPrototypeNext, iterator) : + direct === kNextOwn ? iterator.next() : + FunctionPrototypeCall(next, iterator); + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.next()', result); + } + if (result.done) { + this.#state = kReaderDone; + if (batch.length > 0) { + return new IterResult(false, this.#takeBatch()); + } + return new IterResult(true, undefined); + } + value = result.value; + } catch (error) { + this.#state = kReaderDone; + throw error; + } + if (context?.cancelled) { + this.#close(true); + throw context.reason; } - // Fast path 2: value is a single Uint8Array (very common) - if (isUint8Array(value)) { - yield [value]; + // Fast path 1: value is a single Uint8Array (very common). Checking + // ArrayIsArray() first keeps batches from paying for isUint8Array(). + const isArray = ArrayIsArray(value); + if (!isArray && isUint8Array(value)) { + batch[batch.length] = value; + if (batch.length === FROM_BATCH_SIZE) { + return new IterResult(false, this.#takeBatch()); + } continue; } - // Slow path: normalize the value. Chunks are batched, but whatever has - // been collected is yielded before waiting on async content (such as a - // nested async iterable), so data is not held back until it ends. - let batch = []; - for await (const chunk of - normalizeAsyncValue(value, true, context, true)) { - if (chunk === kFlushBatch) { + // Fast path 2: value is already a Uint8Array[] batch + if (isArray && isUint8ArrayBatch(value)) { + if (value.length === 0) { if (batch.length > 0) { - yield batch; - batch = []; + return new IterResult(false, this.#takeBatch()); } continue; } - ArrayPrototypePush(batch, chunk); - if (batch.length === FROM_BATCH_SIZE) { - yield batch; - batch = []; + let ready = value; + if (value.length > FROM_BATCH_SIZE) { + this.#large = value; + this.#offset = 0; + ready = undefined; + } + // Flush any accumulated batch first + if (batch.length > 0) { + this.#pending = ready; + return new IterResult(false, this.#takeBatch()); } + return new IterResult(false, ready ?? this.#nextSlice()); } + // Slow path: flush, then have the value normalized + const sourceValue = new SyncSourceValue(value); if (batch.length > 0) { - yield batch; + this.#pending = sourceValue; + return new IterResult(false, this.#takeBatch()); } + return new IterResult(false, sourceValue); } - return; } - // Fall back to sync iteration - batch sync values together with a bound. - if (isSyncIterable(source)) { - let batch = []; + return() { + const state = this.#state; + this.#state = kReaderDone; + this.#pending = undefined; + this.#large = null; + if (state === kReaderActive) this.#close(false); + return new IterResult(true, undefined); + } - for (const value of source) { - throwIfNormalizationCancelled(context); - // Fast path 1: value is already a Uint8Array[] batch - if (isUint8ArrayBatch(value)) { - // Flush any accumulated batch first - if (batch.length > 0) { - yield batch; - batch = []; - } - yield* yieldBoundedBatch(value); - continue; + throw(error) { + const state = this.#state; + this.#state = kReaderDone; + this.#pending = undefined; + this.#large = null; + if (state === kReaderActive) this.#close(true); + throw error; + } + + #start() { + this.#state = kReaderActive; + try { + throwIfNormalizationCancelled(this.#context); + const source = this.#source; + if (!isSyncIterable(source)) { + throw new ERR_INVALID_ARG_TYPE( + 'source', ['Iterable', 'AsyncIterable'], source); } - // Fast path 2: value is a single Uint8Array (very common) - if (isUint8Array(value)) { - ArrayPrototypePush(batch, value); - if (batch.length === FROM_BATCH_SIZE) { - yield batch; - batch = []; + const iterator = source[SymbolIterator](); + const next = iterator.next; + this.#iterator = iterator; + this.#next = next; + if (isGeneratorObject(iterator) && next === GeneratorPrototypeNext) { + this.#direct = kNextGenerator; + } else if (typeof iterator === 'object' && iterator !== null) { + const descriptor = ObjectGetOwnPropertyDescriptor(iterator, 'next'); + if (descriptor !== undefined && descriptor.value === next) { + this.#direct = kNextOwn; } - continue; - } - // Slow path: normalize the value - must flush and yield individually - if (batch.length > 0) { - yield batch; - batch = []; } - let asyncBatch = []; - for await (const chunk of - normalizeAsyncValue(value, false, context, true)) { - if (chunk === kFlushBatch) { - if (asyncBatch.length > 0) { - yield asyncBatch; - asyncBatch = []; - } - continue; - } - ArrayPrototypePush(asyncBatch, chunk); - if (asyncBatch.length === FROM_BATCH_SIZE) { - yield asyncBatch; - asyncBatch = []; - } + } catch (error) { + this.#state = kReaderDone; + throw error; + } + } + + #takeBatch() { + const batch = this.#batch; + this.#batch = []; + return batch; + } + + #nextSlice() { + const large = this.#large; + const offset = this.#offset; + this.#offset = offset + FROM_BATCH_SIZE; + if (this.#offset >= large.length) this.#large = null; + return ArrayPrototypeSlice(large, offset, offset + FROM_BATCH_SIZE); + } + + // Close the source as for...of does: errors are ignored if `quiet` (an + // error is being thrown), and otherwise thrown, as is a result of + // return() that is not an object. + #close(quiet) { + this.#state = kReaderDone; + const iterator = this.#iterator; + let result; + try { + const returnMethod = iterator.return; + if (returnMethod === undefined || returnMethod === null) return; + result = FunctionPrototypeCall(returnMethod, iterator); + } catch (error) { + if (quiet) return; + throw error; + } + if (!quiet && + ((typeof result !== 'object' && typeof result !== 'function') || + result === null)) { + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.return()', result); + } + } +} + +/** + * Iterator normalizing a sync iterable source for from() into batches of + * Uint8Array, without an async generator layer for every batch (see + * createAsyncSourceNormalizer()). + * + * The source is read by a SyncSourceReader, which reads and closes it as + * for...of does, and this iterator only adds the asynchronous normalization + * of values that need it. Operations on the reader mirror those on the + * async generator this replaces: return() and throw() are passed to it, + * after closing the value being normalized, and an error normalizing a + * value is thrown into it, so that the source is closed as for an error in + * the body of a for...of loop. + * @param {Iterable} source + * @param {object} context + * @returns {object} An object with next(), return() and throw(). + */ +function createSyncSourceNormalizer(source, context) { + const reader = new SyncSourceReader(source, context); + let done = false; + // A normalizeAsyncSourceValue() generator for the value being normalized. + let valueBatches = null; + const { run, settled, idle } = createOperationQueue(); + + // Results are often produced synchronously. Once one is, the next call + // runs at once, as for the async source normalizer; calls queued while + // an operation was in progress run a microtask later. (An async generator + // would stay busy until the tick after a yield, and queue a call made + // synchronously after one: that costs a microtask per batch.) + function finish(result) { + settled(); + return result; + } + + function fail(error) { + done = true; + settled(); + throw error; + } + + // Throw `error` into the reader, closing the source as for...of does when + // its body throws: errors from closing it are ignored. + function throwIntoReader(error) { + try { + reader.throw(error); + } catch { + // The reader rethrows `error`. + } + } + + function onValueResult(result) { + if (result.done) { + valueBatches = null; + return produce(); + } + return finish(new IterResult(false, result.value)); + } + + function onValueError(error) { + valueBatches = null; + throwIntoReader(error); + return fail(error); + } + + // Produce the next result: an IterResult, or a promise for one when a + // value is normalized asynchronously. Throws, after settling, on error. + function produce() { + if (valueBatches !== null) { + return PromisePrototypeThen( + valueBatches.next(), onValueResult, onValueError); + } + let result; + try { + result = reader.next(); + } catch (error) { + return fail(error); + } + if (result.done) { + done = true; + return finish(new IterResult(true, undefined)); + } + const value = result.value; + if (ArrayIsArray(value)) return finish(new IterResult(false, value)); + valueBatches = normalizeAsyncSourceValue(value.value, context, false); + return PromisePrototypeThen( + valueBatches.next(), onValueResult, onValueError); + } + + function doNext() { + if (done) return PromiseResolve(finish(new IterResult(true, undefined))); + try { + return PromiseResolve(produce()); + } catch (error) { + return PromiseReject(error); + } + } + + function doReturn(value) { + const result = new IterResult(true, value); + if (done) return PromiseResolve(finish(result)); + done = true; + const pending = valueBatches; + valueBatches = null; + if (pending === null) { + try { + reader.return(); + } catch (error) { + settled(); + return PromiseReject(error); } - if (asyncBatch.length > 0) { - yield asyncBatch; + return PromiseResolve(finish(result)); + } + // Close the value being normalized, then the source. If closing the + // value fails, the source is still closed and the error kept. + return PromisePrototypeThen(pending.return(), () => { + try { + reader.return(); + } catch (error) { + return fail(error); } + return finish(result); + }, (error) => { + throwIntoReader(error); + return fail(error); + }); + } + + function doThrow(error) { + if (done) { + settled(); + return PromiseReject(error); } + done = true; + const pending = valueBatches; + valueBatches = null; + if (pending === null) { + throwIntoReader(error); + settled(); + return PromiseReject(error); + } + return PromisePrototypeThen( + PromisePrototypeThen(pending.return(), undefined, () => {}), + () => { + throwIntoReader(error); + return fail(error); + }); + } - // Yield any remaining batched values - if (batch.length > 0) { - yield batch; + // Read the next batch like next() but synchronously, when it is read + // synchronously from the source and no operation is running or queued: + // returns the batch, or null when done. Returns undefined, having started + // nothing but the normalization of a value, when next() must be used. + // Throws on error, like next() rejects. + function nextSyncBatch() { + if (!idle() || valueBatches !== null) return undefined; + if (done) return null; + let result; + try { + result = reader.next(); + } catch (error) { + done = true; + throw error; } - return; + if (result.done) { + done = true; + return null; + } + const value = result.value; + if (ArrayIsArray(value)) return value; + valueBatches = normalizeAsyncSourceValue(value.value, context, false); + return undefined; } - throw new ERR_INVALID_ARG_TYPE( - 'source', - ['Iterable', 'AsyncIterable'], - source, - ); + return ObjectSetPrototypeOf({ + next() { return run(doNext); }, + return(value) { return run(doReturn, value); }, + throw(error) { return run(doThrow, error); }, + [kNextSyncBatch]: nextSyncBatch, + }, null); } async function* normalizeAsyncStreamableResult(result, context) { @@ -692,6 +1555,173 @@ async function* normalizeAsyncStreamableResult(result, context) { // Public API: from() and fromSync() // ============================================================================= +/** + * The sync iterator of a SyncBatchSource: what a sync generator yielding + * the batches of a BatchIterator would give, written out by hand. + */ +class SyncBatchIterator { + #batch; + #index = 0; + + constructor(batch) { + this.#batch = batch; + } + + next() { + const batch = this.#batch; + const index = this.#index; + if (index >= batch.length) { + this.#index = batch.length; + return new IterResult(true, undefined); + } + if (index === 0 && batch.length <= FROM_BATCH_SIZE) { + this.#index = batch.length; + return new IterResult(false, batch); + } + this.#index = index + FROM_BATCH_SIZE; + return new IterResult( + false, ArrayPrototypeSlice(batch, index, index + FROM_BATCH_SIZE)); + } + + return(value) { + this.#index = this.#batch.length; + return new IterResult(true, value); + } + + throw(error) { + this.#index = this.#batch.length; + throw error; + } + + [SymbolIterator]() { + return this; + } +} +ObjectSetPrototypeOf(SyncBatchIterator.prototype, null); + +/** + * A sync iterable yielding the chunks of `batch`, a Uint8Array[], in + * batches of at most FROM_BATCH_SIZE chunks, for fromSync() of values that + * need no normalization: the sync counterpart of BatchSource. + */ +class SyncBatchSource { + #batch; + + constructor(batch) { + this.#batch = batch; + } + + [SymbolIterator]() { + return new SyncBatchIterator(this.#batch); + } +} +ObjectSetPrototypeOf(SyncBatchSource.prototype, null); + +/** + * The sync iterator of a SyncSource: what a sync generator normalizing the + * source with for...of would yield, written out by hand. The source is read by a SyncSourceReader, which + * collects single chunks into batches and closes the source as for...of + * does; other values are normalized with normalizeSyncValue(), and their + * chunks returned in batches of up to FROM_BATCH_SIZE. An error normalizing + * a value is thrown into the reader, which closes the source, as for an + * error in the body of a for...of loop. + */ +class SyncSourceIterator { + #reader; + // The normalizeSyncValue() generator of the value being normalized. + #valueChunks = null; + + constructor(source) { + this.#reader = new SyncSourceReader(source, undefined); + } + + next() { + if (this.#valueChunks !== null) { + const batch = this.#readValue(); + if (batch !== null) return new IterResult(false, batch); + } + for (;;) { + const result = this.#reader.next(); + if (result.done) return result; + const value = result.value; + if (ArrayIsArray(value)) return result; + this.#valueChunks = normalizeSyncValue(value.value); + const batch = this.#readValue(); + if (batch !== null) return new IterResult(false, batch); + } + } + + // The next batch of the chunks of the value being normalized, or null + // once there are no more. + #readValue() { + const batch = []; + try { + for (;;) { + const result = this.#valueChunks.next(); + if (result.done) { + this.#valueChunks = null; + break; + } + batch[batch.length] = result.value; + if (batch.length === FROM_BATCH_SIZE) return batch; + } + } catch (error) { + this.#valueChunks = null; + this.#reader.throw(error); + } + return batch.length > 0 ? batch : null; + } + + return(value) { + const valueChunks = this.#valueChunks; + this.#valueChunks = null; + if (valueChunks !== null) { + try { + valueChunks.return(); + } catch (error) { + this.#reader.throw(error); + } + } + this.#reader.return(); + return new IterResult(true, value); + } + + throw(error) { + const valueChunks = this.#valueChunks; + this.#valueChunks = null; + if (valueChunks !== null) { + try { + valueChunks.return(); + } catch { + // The error thrown in takes precedence. + } + } + this.#reader.throw(error); + } + + [SymbolIterator]() { + return this; + } +} +ObjectSetPrototypeOf(SyncSourceIterator.prototype, null); + +/** + * A sync iterable normalizing a sync iterable source for fromSync() into + * batches of Uint8Array, without generators. + */ +class SyncSource { + #source; + + constructor(source) { + this.#source = source; + } + + [SymbolIterator]() { + return new SyncSourceIterator(this.#source); + } +} +ObjectSetPrototypeOf(SyncSource.prototype, null); + /** * Create a SyncByteStreamReadable from a ByteInput or SyncStreamable. * @param {string|ArrayBuffer|ArrayBufferView|Iterable} input @@ -704,13 +1734,7 @@ function fromSync(input) { // Check for primitives first (ByteInput) if (isPrimitiveChunk(input)) { - const chunk = primitiveToUint8Array(input); - return { - __proto__: null, - *[SymbolIterator]() { - yield [chunk]; - }, - }; + return new SyncBatchSource([primitiveToUint8Array(input)]); } // Check toStreamable protocol (takes precedence over iteration protocols). @@ -726,32 +1750,12 @@ function fromSync(input) { // data volume. Sub-batching keeps peak memory bounded while preserving // the throughput benefit of batched processing. if (ArrayIsArray(input)) { - if (input.length === 0) { - return { - __proto__: null, - *[SymbolIterator]() { - // Empty - yield nothing - }, - }; - } + // An empty array yields nothing. + if (input.length === 0) return new SyncBatchSource(input); // Check if it's an array of Uint8Array (common case) if (isUint8Array(input[0])) { const allUint8 = ArrayPrototypeEvery(input, isUint8Array); - if (allUint8) { - const batch = input; - return { - __proto__: null, - *[SymbolIterator]() { - if (batch.length <= FROM_BATCH_SIZE) { - yield batch; - } else { - for (let i = 0; i < batch.length; i += FROM_BATCH_SIZE) { - yield ArrayPrototypeSlice(batch, i, i + FROM_BATCH_SIZE); - } - } - }, - }; - } + if (allUint8) return new SyncBatchSource(input); } } @@ -785,12 +1789,85 @@ function fromSync(input) { ); } - return { - __proto__: null, - *[SymbolIterator]() { - yield* normalizeSyncSource(input); - }, - }; + return new SyncSource(input); +} + +// BatchSource and BatchIterator are classes, rather than object literals +// with a null prototype, which V8 creates in dictionary mode: from() of a +// value is often called once per stream. Their prototypes do not inherit +// from Object.prototype either. +class BatchIterator { + #batch; + #index = 0; + + constructor(batch) { + this.#batch = batch; + } + + // The next batch, or null once done. + #nextBatch() { + const batch = this.#batch; + const index = this.#index; + if (index >= batch.length) { + this.#index = batch.length; + return null; + } + if (index === 0 && batch.length <= FROM_BATCH_SIZE) { + this.#index = batch.length; + return batch; + } + this.#index = index + FROM_BATCH_SIZE; + return ArrayPrototypeSlice(batch, index, index + FROM_BATCH_SIZE); + } + + next() { + const value = this.#nextBatch(); + return PromiseResolve(value === null ? + new IterResult(true, undefined) : new IterResult(false, value)); + } + + return(value) { + this.#index = this.#batch.length; + return PromiseResolve(new IterResult(true, value)); + } + + throw(error) { + this.#index = this.#batch.length; + return PromiseReject(error); + } + + [SymbolAsyncIterator]() { + return this; + } +} +ObjectSetPrototypeOf(BatchIterator.prototype, null); + +class BatchSource { + #batch; + + constructor(batch) { + this.#batch = batch; + } + + [SymbolAsyncIterator]() { + return new BatchIterator(this.#batch); + } +} +BatchSource.prototype[kValidatedSource] = true; +ObjectSetPrototypeOf(BatchSource.prototype, null); + +/** + * An async iterable yielding the chunks of `batch`, a Uint8Array[], in + * batches of at most FROM_BATCH_SIZE chunks, for from() of values that need + * no normalization. Each iterator does what an async generator yielding the + * batches would, without the generator object and the promises and frames + * of resuming it: next() gives the batches, then done; return() and throw() + * end the iteration, throw() rejecting with its argument. + * @param {Uint8Array[]} batch + * @returns {AsyncIterable<Uint8Array[]>} + */ +function createBatchSource(batch) { + return new BatchSource(batch); } /** @@ -805,13 +1882,7 @@ function from(input) { // Check for primitives first (ByteInput) if (isPrimitiveChunk(input)) { - const chunk = primitiveToUint8Array(input); - return { - __proto__: null, - async *[SymbolAsyncIterator]() { - yield [chunk]; - }, - }; + return createBatchSource([primitiveToUint8Array(input)]); } // Check toAsyncStreamable protocol (takes precedence over toStreamable and @@ -849,29 +1920,12 @@ function from(input) { // the throughput benefit of batched processing. if (ArrayIsArray(input)) { if (input.length === 0) { - return { - __proto__: null, - async *[SymbolAsyncIterator]() { - // Empty - yield nothing - }, - }; + return createBatchSource(input); } if (isUint8Array(input[0])) { const allUint8 = ArrayPrototypeEvery(input, isUint8Array); if (allUint8) { - const batch = input; - return { - __proto__: null, - async *[SymbolAsyncIterator]() { - if (batch.length <= FROM_BATCH_SIZE) { - yield batch; - } else { - for (let i = 0; i < batch.length; i += FROM_BATCH_SIZE) { - yield ArrayPrototypeSlice(batch, i, i + FROM_BATCH_SIZE); - } - } - }, - }; + return createBatchSource(input); } } } @@ -902,9 +1956,10 @@ module.exports = { isPrimitiveChunk, isSyncIterable, isUint8ArrayBatch, + kNextSyncBatch, + kNextUncancellable, normalizeAsyncSource, normalizeAsyncValue, - normalizeSyncSource, normalizeSyncValue, primitiveToUint8Array, }; diff --git a/lib/internal/streams/iter/pull.js b/lib/internal/streams/iter/pull.js index fc8fa9902c1f..06c204e78c67 100644 --- a/lib/internal/streams/iter/pull.js +++ b/lib/internal/streams/iter/pull.js @@ -17,8 +17,10 @@ const { PromisePrototypeThen, PromiseReject, PromiseResolve, + Symbol, SymbolAsyncIterator, SymbolIterator, + TypedArrayPrototypeGetByteLength, Uint8Array, } = primordials; @@ -26,6 +28,7 @@ const { codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, + ERR_INVALID_RETURN_VALUE, ERR_INVALID_STATE, ERR_OUT_OF_RANGE, }, @@ -36,11 +39,7 @@ const { isPromise, isUint8Array, } = require('internal/util/types'); -const { - AbortController, - AbortSignal, - abortSignal, -} = require('internal/abort_controller'); +const { kWeakHandler } = require('internal/event_target'); const { arrayBufferViewToUint8Array, @@ -49,19 +48,35 @@ const { isSyncIterable, isAsyncIterable, isUint8ArrayBatch, + kNextSyncBatch, + kNextUncancellable, } = require('internal/streams/iter/from'); const { IterResult, + PipelineAbort, + kActive, + kDone, kNullOnceOption, + kResolvedPromise, + newPendingPromise, + takeReject, + takeResolve, + kStart, + callWithByteView, + checkFixedBatchChunk, createBatchEntry, + createOperationQueue, + fixedBatchToEntry, isTransformObject, parsePullArgs, + raceSignal, + snapshotFixedBatch, + throwByteViewChanged, snapshotTransform, toUint8Array, validateBatchEntry, validateByteView, - yieldAbortable, } = require('internal/streams/iter/utils'); const { converters, @@ -255,7 +270,7 @@ function* processTransformResultSync(result) { const batch = []; for (const item of result) { for (const chunk of flattenTransformYieldSync(item)) { - ArrayPrototypePush(batch, chunk); + batch[batch.length] = chunk; } } if (batch.length > 0) { @@ -281,28 +296,28 @@ function appendTransformResultSync(target, result) { } if (isUint8ArrayBatch(result)) { if (result.length > 0) { - ArrayPrototypePush(target, result); + target[target.length] = result; } return; } if (isUint8Array(result)) { - ArrayPrototypePush(target, [result]); + target[target.length] = [result]; return; } if (typeof result === 'string') { - ArrayPrototypePush(target, [toUint8Array(result)]); + target[target.length] = [toUint8Array(result)]; return; } if (isAnyArrayBuffer(result)) { - ArrayPrototypePush(target, [new Uint8Array(result)]); + target[target.length] = [new Uint8Array(result)]; return; } if (ArrayBufferIsView(result)) { - ArrayPrototypePush(target, [arrayBufferViewToUint8Array(result)]); + target[target.length] = [arrayBufferViewToUint8Array(result)]; return; } for (const batch of processTransformResultSync(result)) { - ArrayPrototypePush(target, batch); + target[target.length] = batch; } } @@ -351,11 +366,11 @@ async function* processTransformResultAsync(result) { const batch = []; for await (const item of result) { if (isUint8Array(item)) { - ArrayPrototypePush(batch, item); + batch[batch.length] = item; continue; } for await (const chunk of flattenTransformYieldAsync(item)) { - ArrayPrototypePush(batch, chunk); + batch[batch.length] = chunk; } } if (batch.length > 0) { @@ -368,13 +383,13 @@ async function* processTransformResultAsync(result) { const batch = []; for (const item of result) { if (isUint8Array(item)) { - ArrayPrototypePush(batch, item); + batch[batch.length] = item; continue; } // Note: This iteration is synchronous, since async iterables // may not be nested within sync iterables. for (const chunk of flattenTransformYieldSync(item)) { - ArrayPrototypePush(batch, chunk); + batch[batch.length] = chunk; } } if (batch.length > 0) { @@ -401,24 +416,24 @@ function appendTransformResultAsync(target, result) { } if (isUint8ArrayBatch(result)) { if (result.length > 0) { - ArrayPrototypePush(target, result); + target[target.length] = result; } return; } if (isUint8Array(result)) { - ArrayPrototypePush(target, [result]); + target[target.length] = [result]; return; } if (typeof result === 'string') { - ArrayPrototypePush(target, [toUint8Array(result)]); + target[target.length] = [toUint8Array(result)]; return; } if (isAnyArrayBuffer(result)) { - ArrayPrototypePush(target, [new Uint8Array(result)]); + target[target.length] = [new Uint8Array(result)]; return; } if (ArrayBufferIsView(result)) { - ArrayPrototypePush(target, [arrayBufferViewToUint8Array(result)]); + target[target.length] = [arrayBufferViewToUint8Array(result)]; return; } return appendTransformResultAsyncSlow(target, result); @@ -426,7 +441,7 @@ function appendTransformResultAsync(target, result) { async function appendTransformResultAsyncSlow(target, result) { for await (const batch of processTransformResultAsync(result)) { - ArrayPrototypePush(target, batch); + target[target.length] = batch; } } @@ -524,7 +539,7 @@ function* applyStatefulSyncTransform(source, transform, receiver) { if (item === null) continue; const batch = []; for (const chunk of flattenTransformYieldSync(item)) { - ArrayPrototypePush(batch, chunk); + batch[batch.length] = chunk; } if (batch.length > 0) { yield batch; @@ -567,91 +582,157 @@ function* createSyncPipeline(source, transforms) { // Async Pipeline Implementation // ============================================================================= -// The options object passed to async transforms. Stateless transforms get a -// new one for every call, so it is constructed rather than created as a -// `{ __proto__: null, signal }` literal (a dictionary-mode object). The -// prototype is frozen and has no %Object.prototype% in its chain, and the -// non-enumerable `constructor` lets util.inspect() print the options as -// `TransformOptions { signal }`. -function TransformOptions(signal) { - this.signal = signal; +// The options object passed to an async transform: one for each transform of +// a pipeline, passed to every call of a stateless transform. Its `signal` is +// the pipeline's signal, created by `abort` when first read (see +// PipelineAbort): until then it is an accessor, which replaces itself with a +// data property holding the signal. The prototype is frozen and has no +// %Object.prototype% in its chain, and the non-enumerable `constructor` lets +// util.inspect() print the options as `TransformOptions { signal }`. +function TransformOptions(abort) { + ObjectDefineProperty(this, 'signal', { + __proto__: null, + configurable: true, + enumerable: true, + get() { + const signal = abort.signal; + ObjectDefineProperty(this, 'signal', { + __proto__: null, + configurable: true, + enumerable: true, + value: signal, + writable: true, + }); + return signal; + }, + set(value) { + ObjectDefineProperty(this, 'signal', { + __proto__: null, + configurable: true, + enumerable: true, + value, + writable: true, + }); + }, + }); } TransformOptions.prototype = ObjectFreeze(ObjectDefineProperty( { __proto__: null }, 'constructor', { __proto__: null, value: TransformOptions })); +// The options for each function of a fused run of stateless transforms. +function createRunOptions(run, abort) { + const options = []; + for (let i = 0; i < run.length; i++) { + options[i] = new TransformOptions(abort); + } + return options; +} + /** - * Apply a single stateless async transform to a source. + * Close an async iterator as for await does: for a throw completion + * (`quiet`), wait for it but ignore errors; otherwise reject on errors and + * on a result that is not an object. + * @param {object} iterator + * @param {boolean} quiet + * @returns {Promise<void>} + */ +function closeAsyncIterator(iterator, quiet) { + let promise; + try { + const returnMethod = iterator.return; + if (returnMethod === undefined || returnMethod === null) { + return kResolvedPromise; + } + promise = PromiseResolve(FunctionPrototypeCall(returnMethod, iterator)); + } catch (error) { + return quiet ? kResolvedPromise : PromiseReject(error); + } + if (quiet) return PromisePrototypeThen(promise, undefined, () => {}); + return PromisePrototypeThen(promise, (result) => { + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.return()', result); + } + }); +} + +/** + * Normalize the output of a fused run of stateless transforms for a batch. * @yields {Uint8Array[]} */ +async function* yieldFusedStatelessOutput(current) { + if (isUint8ArrayBatch(current)) { + if (current.length > 0) yield current; + } else if (isUint8Array(current)) { + yield [current]; + } else if (typeof current === 'string') { + yield [toUint8Array(current)]; + } else if (isAnyArrayBuffer(current)) { + yield [new Uint8Array(current)]; + } else if (ArrayBufferIsView(current)) { + yield [arrayBufferViewToUint8Array(current)]; + } else { + yield* processTransformResultAsync(current); + } +} + /** - * Apply a fused run of stateless async transforms to a source. - * All transforms in the run are applied in a tight synchronous loop per batch, - * avoiding the overhead of N async generator ticks for N transforms. - * - * INVARIANT: This function accepts a signal, NOT a pre-built options object. - * A fresh TransformOptions object is created for each - * transform invocation to prevent cross-transform mutation. - * @param {AsyncIterable<Uint8Array[]>} source - * @param {Array<Function>} run - Array of stateless transform functions - * @param {AbortSignal} signal - The pipeline's abort signal + * Apply a fused run of stateless transforms to a batch from transform + * `index` on, given the result of that transform, when the result has to be + * waited for or normalized asynchronously. + * @param {Array<Function>} run + * @param {number} index + * @param {any} result - The result of `run[index]` + * @param {TransformOptions[]} runOptions - The options of each function * @yields {Uint8Array[]} */ -async function* applyFusedStatelessAsyncTransforms(source, run, signal) { - for await (const chunks of source) { - let current = chunks; - for (let i = 0; i < run.length; i++) { - let result = run[i](current, new TransformOptions(signal)); - if (isPromise(result)) result = await result; - if (result === null) { - current = null; - break; - } - if (i === run.length - 1) { - current = result; - continue; - } - current = normalizeTransformResultFast(result); - if (current === undefined) { - const normalized = []; - const pendingResult = appendTransformResultAsync(normalized, result); - if (pendingResult !== undefined) await pendingResult; - current = normalized.length === 0 ? null : normalized[0]; - } - if (current === null) break; +async function* continueFusedStatelessBatch(run, index, result, runOptions) { + let current; + for (let i = index; i < run.length; i++) { + if (i !== index) result = run[i](current, runOptions[i]); + if (isPromise(result)) result = await result; + if (result === null) return; + if (i === run.length - 1) { + current = result; + break; } - if (current === null) continue; - // Normalize the final output - if (isUint8ArrayBatch(current)) { - if (current.length > 0) yield current; - } else if (isUint8Array(current)) { - yield [current]; - } else if (typeof current === 'string') { - yield [toUint8Array(current)]; - } else if (isAnyArrayBuffer(current)) { - yield [new Uint8Array(current)]; - } else if (ArrayBufferIsView(current)) { - yield [arrayBufferViewToUint8Array(current)]; - } else { - yield* processTransformResultAsync(current); + current = normalizeTransformResultFast(result); + if (current === undefined) { + const normalized = []; + const pendingResult = appendTransformResultAsync(normalized, result); + if (pendingResult !== undefined) await pendingResult; + current = normalized.length === 0 ? null : normalized[0]; } + if (current === null) return; } - // Flush each transform after all upstream data, including data emitted by - // earlier flushes, has been processed by that transform. + yield* yieldFusedStatelessOutput(current); +} + +/** + * Flush a fused run of stateless transforms once the source has ended: + * flush each transform after all upstream data, including data emitted by + * earlier flushes, has been processed by that transform. + * @param {Array<Function>} run + * @param {TransformOptions[]} runOptions - The options of each function + * @yields {Uint8Array[]} + */ +async function* flushFusedStatelessAsyncTransforms(run, runOptions) { let pending = []; for (let i = 0; i < run.length; i++) { const next = []; for (let j = 0; j < pending.length; j++) { const pendingResult = appendTransformResultAsync( next, - run[i](pending[j], new TransformOptions(signal))); + run[i](pending[j], runOptions[i])); if (pendingResult !== undefined) { await pendingResult; } } const flushResult = appendTransformResultAsync( next, - run[i](null, new TransformOptions(signal))); + run[i](null, runOptions[i])); if (flushResult !== undefined) { await flushResult; } @@ -662,23 +743,329 @@ async function* applyFusedStatelessAsyncTransforms(source, run, signal) { } } +// Returned by applyBatch() below when a batch is processed by a delegate. +const kDelegated = Symbol('kDelegated'); + /** - * Append a null flush signal after the source is exhausted. - * @yields {Uint8Array[]} + * Apply a fused run of stateless async transforms to a source. + * All transforms in the run are applied in a tight synchronous loop per batch, + * avoiding the overhead of N async generator ticks for N transforms. + * + * This is what an async generator looping over the source with for await + * would do, written out by hand, as an async generator layer costs several + * promises and an async frame for every batch: when the transforms return + * batches or chunks synchronously, a batch takes a single promise. Results + * that have to be waited for or normalized asynchronously, and the flush + * once the source has ended, are handled by async generators. As with an + * async generator looping over the source: + * - the source is opened by the first next(), and calls made while one is in + * progress are queued; + * - an error from the source ends the iteration without closing it, and an + * error from a transform closes it, ignoring errors from closing it; + * - return() and throw() are passed to the async generator handling a batch, + * if any, and close the source unless it has ended; return() propagates + * errors from closing it, throw() ignores them. + * + * Each function of the run is passed its own options object on every call. + * @param {AsyncIterable<Uint8Array[]>} source + * @param {Array<Function>} run - Array of stateless transform functions + * @param {PipelineAbort} abort - The pipeline's abort state + * @returns {AsyncIterator<Uint8Array[]>} */ +function applyFusedStatelessAsyncTransforms(source, run, abort) { + const runOptions = createRunOptions(run, abort); + let state = kStart; + let iterator; + let nextMethod; + // Whether the source has ended, and the run is being flushed. + let sourceDone = false; + // An async generator yielding the output of a batch, or of the flush. + let delegate = null; + const operations = createOperationQueue(); + + function finish(result) { + operations.settled(); + return result; + } + + function fail(error) { + state = kDone; + operations.settled(); + throw error; + } + + // Like for await when its body throws: close the source, keep the error. + function onBodyError(error) { + delegate = null; + state = kDone; + return PromisePrototypeThen( + closeAsyncIterator(iterator, true), () => fail(error)); + } + + function onDelegateError(error) { + if (!sourceDone) return onBodyError(error); + delegate = null; + return fail(error); + } + + function onDelegateResult(result) { + if (!result.done) return finish(new IterResult(false, result.value)); + delegate = null; + if (!sourceDone) return pullSource(); + state = kDone; + return finish(new IterResult(true, undefined)); + } + + function pullDelegate() { + return PromisePrototypeThen( + delegate.next(), onDelegateResult, onDelegateError); + } + + // Apply the run to a batch synchronously: returns the output batch, null + // if there is none, or kDelegated if `delegate` is to produce it. + function applyBatch(chunks) { + let current = chunks; + for (let i = 0; i < run.length; i++) { + const result = run[i](current, runOptions[i]); + if (isPromise(result)) { + delegate = continueFusedStatelessBatch(run, i, result, runOptions); + return kDelegated; + } + if (result === null) return null; + if (i === run.length - 1) { + current = result; + break; + } + current = normalizeTransformResultFast(result); + if (current === undefined) { + delegate = continueFusedStatelessBatch(run, i, result, runOptions); + return kDelegated; + } + if (current === null) return null; + } + if (isUint8ArrayBatch(current)) { + return current.length > 0 ? current : null; + } + if (isUint8Array(current)) return [current]; + if (typeof current === 'string') return [toUint8Array(current)]; + if (isAnyArrayBuffer(current)) return [new Uint8Array(current)]; + if (ArrayBufferIsView(current)) { + return [arrayBufferViewToUint8Array(current)]; + } + delegate = processTransformResultAsync(current); + return kDelegated; + } + + function onSourceResult(result) { + let value; + try { + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.next()', result); + } + if (result.done) { + sourceDone = true; + delegate = flushFusedStatelessAsyncTransforms(run, runOptions); + return pullDelegate(); + } + value = result.value; + } catch (error) { + return fail(error); + } + let batch; + try { + batch = applyBatch(value); + } catch (error) { + return onBodyError(error); + } + if (batch === kDelegated) return pullDelegate(); + if (batch === null) return pullSource(); + return finish(new IterResult(false, batch)); + } + + function pullSource() { + let promise; + try { + promise = PromiseResolve(FunctionPrototypeCall(nextMethod, iterator)); + } catch (error) { + return fail(error); + } + return PromisePrototypeThen(promise, onSourceResult, fail); + } + + function doNext() { + if (state === kDone) { + return PromiseResolve(finish(new IterResult(true, undefined))); + } + if (state === kStart) { + try { + iterator = source[SymbolAsyncIterator](); + nextMethod = iterator.next; + } catch (error) { + state = kDone; + operations.settled(); + return PromiseReject(error); + } + state = kActive; + } + try { + return PromiseResolve(delegate !== null ? pullDelegate() : pullSource()); + } catch (error) { + return PromiseReject(error); + } + } + + function doReturn(value) { + const result = new IterResult(true, value); + if (state !== kActive) { + state = kDone; + return PromiseResolve(finish(result)); + } + state = kDone; + const pending = delegate; + delegate = null; + const open = sourceDone ? null : iterator; + let closed; + if (pending === null) { + closed = open === null ? kResolvedPromise : + closeAsyncIterator(open, false); + } else { + // Close the delegate, then the source. If closing the delegate fails, + // the source is still closed and the error kept. + closed = PromisePrototypeThen( + closeAsyncIterator(pending, false), + () => (open === null ? undefined : closeAsyncIterator(open, false)), + (error) => { + if (open === null) throw error; + return PromisePrototypeThen(closeAsyncIterator(open, true), () => { + throw error; + }); + }); + } + return PromisePrototypeThen(closed, () => finish(result), fail); + } + + function doThrow(error) { + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseReject(error); + } + state = kDone; + const pending = delegate; + delegate = null; + // The delegate rethrows `error` (as yield* would see it do). + let closed = pending === null ? kResolvedPromise : + PromisePrototypeThen(pending.throw(error), undefined, () => {}); + if (!sourceDone) { + closed = PromisePrototypeThen( + closed, () => closeAsyncIterator(iterator, true)); + } + return PromisePrototypeThen(closed, () => fail(error)); + } + + return ObjectSetPrototypeOf({ + next() { return operations.run(doNext); }, + return(value) { return operations.run(doReturn, value); }, + throw(error) { return operations.run(doThrow, error); }, + [SymbolAsyncIterator]() { return this; }, + }, null); +} + /** - * Append a null flush signal after the source is exhausted. - * @yields {Uint8Array[]} + * The source of a stateful transform: what an async generator doing + * `yield* source; yield null;` would yield, written out by hand, as it is + * read for every batch. Reads are passed to + * the source's iterator, with one reaction each; once it is done, null is + * yielded once, as the flush signal. return() and throw() are passed on as + * yield* does. + * @param {AsyncIterable<Uint8Array[]>} source + * @returns {AsyncIterator<Uint8Array[]|null>} */ -async function* withFlushAsync(source) { - yield* source; - yield null; +function createFlushSource(source) { + let iterator = null; + // Whether the source is done, and the flush signal yielded; then the + // source is ended. + let sourceDone = false; + let done = false; + + function onResult(result) { + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + done = true; + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.next()', result); + } + if (result.done) { + sourceDone = true; + return new IterResult(false, null); + } + return new IterResult(false, result.value); + } + + function onError(error) { + done = true; + throw error; + } + + return ObjectSetPrototypeOf({ + next() { + if (done || sourceDone) { + done = true; + return PromiseResolve(new IterResult(true, undefined)); + } + try { + iterator ??= source[SymbolAsyncIterator](); + return PromisePrototypeThen(PromiseResolve(iterator.next()), + onResult, onError); + } catch (error) { + done = true; + return PromiseReject(error); + } + }, + return(value) { + const result = new IterResult(true, value); + if (done || sourceDone || iterator === null) { + done = true; + return PromiseResolve(result); + } + done = true; + return PromisePrototypeThen(closeAsyncIterator(iterator, false), + () => result); + }, + throw(error) { + if (done || sourceDone || iterator === null) { + done = true; + return PromiseReject(error); + } + try { + const throwMethod = iterator.throw; + if (throwMethod === undefined || throwMethod === null) { + // As yield*: close the source, then throw a TypeError. + done = true; + return PromisePrototypeThen(closeAsyncIterator(iterator, false), + () => { + throw new ERR_INVALID_STATE.TypeError( + 'The iterator does not provide ' + + 'a \'throw\' method'); + }); + } + return PromisePrototypeThen( + PromiseResolve(FunctionPrototypeCall(throwMethod, iterator, error)), + onResult, onError); + } catch (thrown) { + done = true; + return PromiseReject(thrown); + } + }, + [SymbolAsyncIterator]() { return this; }, + }, null); } -async function* applyStatefulAsyncTransform( - source, transform, receiver, options) { - const output = FunctionPrototypeCall( - transform, receiver, withFlushAsync(source), options); +// Iterate the output of a stateful transform as for await does, for outputs +// that are not async iterables: see createStatefulTransformIterator(). +async function* yieldStatefulOutput(output) { for await (const item of output) { if (item === null) continue; // Fast path: item is already a Uint8Array[] batch (e.g. compression transforms) @@ -696,7 +1083,7 @@ async function* applyStatefulAsyncTransform( // Slow path: flatten arbitrary transform yield const batch = []; for await (const chunk of flattenTransformYieldAsync(item)) { - ArrayPrototypePush(batch, chunk); + batch[batch.length] = chunk; } if (batch.length > 0) { yield batch; @@ -705,123 +1092,592 @@ async function* applyStatefulAsyncTransform( } /** - * Fast path for validated stateful transforms (e.g. compression). - * Skips withFlushAsync (transform handles done internally) and - * skips isUint8ArrayBatch validation (transform guarantees valid output). - * @yields {Uint8Array[]} + * A stateful transform applied to `source`: what an async generator doing + * `for await (const item of output)` over the transform's output would + * yield, written out by hand, as it runs for every batch. The transform is + * called on the first next(), with createFlushSource(source), or with + * `source` itself for a validated transform (e.g. compression), whose + * output needs no normalization. An output that is not an async iterable + * is read by the async generator instead (yieldStatefulOutput()). + * @param {AsyncIterable<Uint8Array[]>} source + * @param {Function} transform + * @param {object} receiver + * @param {TransformOptions} options + * @param {PipelineAbort} abort + * @param {boolean} validated + * @returns {AsyncIterator<Uint8Array[]>} */ -async function* applyValidatedStatefulAsyncTransform( - source, transform, receiver, options) { - const output = FunctionPrototypeCall( - transform, receiver, source, options); - for await (const batch of output) { - if (batch.length > 0) { - yield batch; +function createStatefulTransformIterator( + source, transform, receiver, options, abort, validated) { + let state = kStart; + let iterator; + let nextMethod; + + function pull() { + return PromisePrototypeThen( + PromiseResolve(FunctionPrototypeCall(nextMethod, iterator)), + onItem, onError); + } + + function onItem(result) { + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + state = kDone; + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.next()', result); + } + if (result.done) { + state = kDone; + // Without the flush signal there is no extra read to give the + // pipeline a chance to see an abort. + if (validated) abort.throwIfAborted(); + return new IterResult(true, undefined); + } + const item = result.value; + if (validated) { + return item.length > 0 ? new IterResult(false, item) : pull(); + } + if (item === null) return pull(); + if (isUint8ArrayBatch(item)) { + return item.length > 0 ? new IterResult(false, item) : pull(); + } + if (isUint8Array(item)) return new IterResult(false, [item]); + // Slow path: flatten arbitrary transform yield. An error doing so + // closes the output, as for await does when its body throws. + return PromisePrototypeThen(flattenItem(item), (batch) => { + return batch.length > 0 ? new IterResult(false, batch) : pull(); + }, (error) => { + state = kDone; + return PromisePrototypeThen(closeAsyncIterator(iterator, true), () => { + throw error; + }); + }); + } + + async function flattenItem(item) { + const batch = []; + for await (const chunk of flattenTransformYieldAsync(item)) { + batch[batch.length] = chunk; + } + return batch; + } + + function onError(error) { + state = kDone; + throw error; + } + + return ObjectSetPrototypeOf({ + next() { + if (state === kDone) { + return PromiseResolve(new IterResult(true, undefined)); + } + if (state === kStart) { + state = kActive; + try { + const output = FunctionPrototypeCall( + transform, receiver, + validated ? source : createFlushSource(source), options); + if (output != null && + typeof output[SymbolAsyncIterator] === 'function') { + iterator = output[SymbolAsyncIterator](); + } else { + // Iterated as for await would: sync iterables, and errors. + iterator = yieldStatefulOutput(output); + } + nextMethod = iterator.next; + } catch (error) { + state = kDone; + return PromiseReject(error); + } + } + try { + return pull(); + } catch (error) { + state = kDone; + return PromiseReject(error); + } + }, + return(value) { + const result = new IterResult(true, value); + if (state !== kActive) { + state = kDone; + return PromiseResolve(result); + } + state = kDone; + return PromisePrototypeThen(closeAsyncIterator(iterator, false), + () => result); + }, + throw(error) { + if (state !== kActive) { + state = kDone; + return PromiseReject(error); + } + state = kDone; + return PromisePrototypeThen(closeAsyncIterator(iterator, true), + () => { throw error; }); + }, + [SymbolAsyncIterator]() { return this; }, + }, null); +} + +/** + * The source of a pipeline, as its transforms read it: passes reads to the + * source's iterator as they are, so that reading costs nothing more, and + * lets the pipeline close the source's iterator when it is aborted, without + * waiting for a pending read to complete. The source's return() is called + * at most once. + */ +class PipelineSource { + #source; + #abort; + #iterator = null; + #closed = false; + // Whether a from() source is read with kNextUncancellable (see the + // constructor). + #uncancellable; + + // `uncancellable`: whether nothing but stream/iter code waits for the + // reads, so that a read pending when the pipeline aborts can be left to + // settle when the source's next() does. The pipeline rejects its own + // pending pull and ignores the read, and closing the source still calls + // its return() at once. This saves every read of a from() source a + // promise of its own. A stateful transform reads the source in user code + // (its generator waits for the read), so with one the reads stay + // cancellable, and an abort rejects them at once. + constructor(source, abort, uncancellable) { + this.#source = source; + this.#abort = abort; + this.#uncancellable = uncancellable; + } + + [SymbolAsyncIterator]() { + return this; + } + + // Whether the source is read with kNextUncancellable (known once it has + // been read). + get uncancellable() { + return this.#uncancellable && this.#iterator !== null; + } + + next() { + if (this.#abort.aborted) return PromiseReject(this.#abort.reason); + if (this.#closed) return PromiseResolve(new IterResult(true, undefined)); + if (this.#iterator === null) { + this.#iterator = this.#source[SymbolAsyncIterator](); + if (this.#iterator[kNextUncancellable] === undefined) { + this.#uncancellable = false; + } + } + if (this.#uncancellable) return this.#iterator[kNextUncancellable](true); + return this.#iterator.next(); + } + + return(value) { + const iterator = this.#iterator; + if (this.#closed || iterator === null) { + this.#closed = true; + return PromiseResolve(new IterResult(true, value)); + } + this.#closed = true; + const returnMethod = iterator.return; + if (returnMethod === undefined || returnMethod === null) { + return PromiseResolve(new IterResult(true, value)); } + return FunctionPrototypeCall(returnMethod, iterator, value); } - // Check abort after the transform completes - without the - // withFlushAsync wrapper there is no extra yield to give - // the outer pipeline a chance to see the abort. - options.signal?.throwIfAborted(); + + throw(error) { + // As for await closes the source when its body throws. + return PromisePrototypeThen(this.return(), () => { throw error; }); + } + + // Close the source's iterator for an abort, without waiting, ignoring + // errors from closing it. + close() { + const iterator = this.#iterator; + if (this.#closed || iterator === null) { + this.#closed = true; + return; + } + this.#closed = true; + try { + const returnMethod = iterator.return; + if (returnMethod !== undefined && returnMethod !== null) { + markPromiseAsHandled(PromiseResolve( + FunctionPrototypeCall(returnMethod, iterator))); + } + } catch { + // The abort takes precedence over errors closing the source. + } + } +} + +function hasTransformObject(transforms) { + for (let i = 0; i < transforms.length; i++) { + if (isTransformObject(transforms[i])) return true; + } + return false; } /** - * Create an async pipeline from source through transforms. - * @yields {Uint8Array[]} + * Build the chain of transform layers of a pipeline. + * @param {AsyncIterable<Uint8Array[]>} normalized + * @param {Array} transforms + * @param {PipelineAbort} abort - The pipeline's abort state + * @returns {AsyncIterable<Uint8Array[]>} */ -async function* createAsyncPipeline(source, transforms, signal) { - // Check for abort - signal?.throwIfAborted(); +function createAsyncTransformLayers(normalized, transforms, abort) { + // Apply transforms - fuse consecutive stateless transforms into a single + // layer to avoid unnecessary async ticks. + // + // Each transform gets its own options object, created here once and passed + // to every call of the transform: transforms may mutate the options + // object, and must not be able to change the options another transform + // sees. + let current = normalized; + let statelessRun = []; - // Fast path: no transforms, just yield normalized source directly - if (transforms.length === 0) { - yield* yieldAbortable(source, signal); - return; + for (let i = 0; i < transforms.length; i++) { + const transform = transforms[i]; + if (isTransformObject(transform)) { + // Flush any accumulated stateless run before the stateful transform + if (statelessRun.length > 0) { + current = applyFusedStatelessAsyncTransforms(current, statelessRun, + abort); + statelessRun = []; + } + const opts = new TransformOptions(abort); + current = createStatefulTransformIterator( + current, transform.transform, transform.receiver, opts, abort, + transform[kValidatedTransform] === true); + } else { + ArrayPrototypePush(statelessRun, transform); + } + } + // Flush remaining stateless run + if (statelessRun.length > 0) { + current = applyFusedStatelessAsyncTransforms(current, statelessRun, + abort); } + return current; +} - const normalized = yieldAbortable(source, signal); +/** + * The iterator of a pull() pipeline, also used by pipeTo() for transforms: an + * async iterator doing what an async generator would, written out by hand to + * avoid an async generator layer for every batch (see + * applyFusedStatelessAsyncTransforms()). + * + * The pipeline's abort state (a PipelineAbort) gives the transforms their + * signal. The pipeline is aborted when `signal` aborts, when the consumer + * stops early with return() or throw(), and with the error when it fails. + * An abort is handled here, once, instead of in every layer: + * - a pull that is pending rejects at once with the abort reason, after the + * source's return() is called, without waiting for it (any later result of + * the transforms is ignored); + * - the source is read through a PipelineSource, which rejects reads once + * the pipeline is aborted; + * - each batch, and the end, is passed on only if the pipeline has not been + * aborted. + * When `signal` aborts, the pull that observes it and every later pull reject + * with its reason, and the transforms are closed. When the consumer stops, + * later pulls report the end. + * + * A pending pull can only be rejected at once if it is a promise of its own, + * one more for every batch. Without a signal, pipeTo() never stops the + * pipeline while a pull is pending, so it passes `interruptible` as false + * and each pull is the promise of the reaction to the transforms' result. + * @param {AsyncIterable<Uint8Array[]>} source + * @param {Array} transforms + * @param {AbortSignal} [signal] + * @param {boolean} [interruptible] + * @returns {AsyncIterator<Uint8Array[]>} + */ +function createAsyncPipeline(source, transforms, signal, + interruptible = true) { + let state = kStart; + // Whether `signal` has aborted the pipeline: pulls then reject. + let signalAborted = signal !== undefined && signal.aborted; + let abort; + let pipelineSource; + let iterator; + let nextMethod; + // The settling functions of the pending pull, if any. The operation queue + // runs one pull at a time. + let resolvePull = null; + let rejectPull = null; + // See stop(). + let closeWithoutWaiting = false; + const operations = createOperationQueue(); + + const self = ObjectSetPrototypeOf({ + next() { return operations.run(doNext); }, + return(value) { + stop(lazyDOMException('Aborted', 'AbortError')); + return operations.run(doReturn, value); + }, + throw(error) { + stop(error); + return operations.run(doThrow, error); + }, + [SymbolAsyncIterator]() { return this; }, + }, null); - // Create internal controller for transform cancellation. - // Note: if signal was already aborted, we threw above - no need to check here. - const controller = new AbortController(); - let abortHandler; - if (signal) { - abortHandler = () => { - abortSignal(controller.signal, signal.reason); - }; - signal.addEventListener('abort', abortHandler, kNullOnceOption); + function onSignalAbort() { + if (state === kDone) return; + signalAborted = true; + // Close the transforms too; their errors are ignored, the pull rejects + // with the abort reason. + abortPipeline(signal.reason, true); } - let completed = false; - try { - // Apply transforms - fuse consecutive stateless transforms into a single - // generator layer to avoid unnecessary async generator ticks. - // - // INVARIANT: Each transform invocation MUST receive its own fresh options - // object (new TransformOptions(signal)). Transforms may mutate the options - // object, so sharing a single object across invocations would allow one - // transform to corrupt the options seen by another. The signal is shared - // across calls (mutations to it are acceptable), but the containing options - // object must be unique per call. This is enforced inside - // applyFusedStatelessAsyncTransforms and applyStatefulAsyncTransform, which - // accept the signal directly and create the options object per invocation. - // DO NOT pass a pre-built options object. - let current = normalized; - const transformSignal = controller.signal; - let statelessRun = []; - - for (let i = 0; i < transforms.length; i++) { - const transform = transforms[i]; - if (isTransformObject(transform)) { - // Flush any accumulated stateless run before the stateful transform - if (statelessRun.length > 0) { - current = applyFusedStatelessAsyncTransforms(current, statelessRun, - transformSignal); - statelessRun = []; - } - const opts = new TransformOptions(transformSignal); - if (transform[kValidatedTransform]) { - current = applyValidatedStatefulAsyncTransform( - current, transform.transform, transform.receiver, opts); + function removeSignalListener() { + if (signal !== undefined && state !== kStart) { + signal.removeEventListener('abort', onSignalAbort); + } + } + + // Abort the pipeline: the transforms' signal at once, then close the + // source and reject the pending pull, if any. The signal can abort while + // the source or a transform is called, so these wait for a microtask, for + // that call to return. A result of the transforms that comes later is + // ignored. + function abortPipeline(reason, closeTransforms) { + state = kDone; + removeSignalListener(); + abort.abort(reason); + const reject = rejectPull; + resolvePull = rejectPull = null; + PromisePrototypeThen(kResolvedPromise, () => { + pipelineSource.close(); + if (reject !== null) { + operations.settled(); + reject(reason); + } + if (closeTransforms) { + markPromiseAsHandled(closeAsyncIterator(iterator, true)); + } + }); + } + + // The consumer stops early: abort the pipeline at once, so that the + // transforms see their signal aborted before they are closed and a pending + // pull rejects; doReturn() or doThrow() then closes the transforms. + function stop(reason) { + if (state !== kActive) return; + if (rejectPull !== null) { + abortPipeline(reason, false); + state = kActive; + // The pending pull is waiting for a read of the source that is now + // ignored, and with uncancellable reads nothing settles that read + // early: closing the transforms would wait for it, as a transform + // layer's return() waits for its pending next(). The transforms are + // all stateless then (see PipelineSource), so nothing but stream/iter + // code waits for them, and doReturn() / doThrow() close them without + // waiting. The source has already been closed. + closeWithoutWaiting = pipelineSource.uncancellable; + } else { + abort.abort(reason); + } + } + + // The end of the pipeline, for an error: what an async generator would do + // in its `catch` block, then `finally`. + function failed(error) { + state = kDone; + removeSignalListener(); + abort.abort(error); + } + + // What a pull settles with, given the result of the transforms: a result, + // or a promise for one, or it throws. The pipeline is done if it throws or + // the result is done. + function handleResult(result) { + if ((typeof result !== 'object' && typeof result !== 'function') || + result === null) { + throw new ERR_INVALID_RETURN_VALUE( + 'an object', 'iterator.next()', result); + } + if (result.done) { + // A transform can abort while completing without producing a final + // batch, for example when an async flush resolves to null. In that + // case there is no batch with which to observe the abort. + abort.throwIfAborted(); + state = kDone; + removeSignalListener(); + return new IterResult(true, undefined); + } + if (abort.aborted) { + const error = abort.reason; + // Like for await when its body throws: close the transforms first. + return PromisePrototypeThen( + closeAsyncIterator(iterator, true), () => { throw error; }); + } + return new IterResult(false, result.value); + } + + function onResult(result) { + const resolve = resolvePull; + if (resolve === null) return; // Settled by an abort. + const reject = rejectPull; + let settled; + try { + settled = handleResult(result); + } catch (error) { + onError(error); + return; + } + if (isPromise(settled)) { + PromisePrototypeThen(settled, undefined, (error) => { + if (rejectPull === reject) onError(error); + }); + return; + } + resolvePull = rejectPull = null; + operations.settled(); + resolve(settled); + } + + function onError(error) { + const reject = rejectPull; + if (reject === null) return; // Settled by an abort. + resolvePull = rejectPull = null; + operations.settled(); + failed(error); + reject(error); + } + + // onResult() and onError() for a pull that is the promise of the reaction + // to the transforms' result (see `interruptible`). + function onDirectResult(result) { + let settled; + try { + settled = handleResult(result); + } catch (error) { + return onDirectError(error); + } + if (isPromise(settled)) { + return PromisePrototypeThen(settled, undefined, onDirectError); + } + operations.settled(); + return settled; + } + + function onDirectError(error) { + operations.settled(); + failed(error); + throw error; + } + + function doNext() { + if (signalAborted) { + operations.settled(); + return PromiseReject(signal.reason); + } + if (state === kDone) { + operations.settled(); + return PromiseResolve(new IterResult(true, undefined)); + } + if (state === kStart) { + state = kActive; + abort = new PipelineAbort(); + pipelineSource = new PipelineSource( + source, abort, !hasTransformObject(transforms)); + if (signal !== undefined) { + signal.addEventListener('abort', onSignalAbort, + { __proto__: null, once: true, + [kWeakHandler]: self }); + } + try { + if (transforms.length === 0) { + iterator = pipelineSource; } else { - current = applyStatefulAsyncTransform( - current, transform.transform, transform.receiver, opts); + iterator = createAsyncTransformLayers( + pipelineSource, transforms, abort)[SymbolAsyncIterator](); } - } else { - ArrayPrototypePush(statelessRun, transform); + nextMethod = iterator.next; + } catch (error) { + state = kDone; + removeSignalListener(); + operations.settled(); + abort.abort(error); + return PromiseReject(error); + } + } + if (!interruptible) { + let next; + try { + next = PromiseResolve(FunctionPrototypeCall(nextMethod, iterator)); + } catch (error) { + operations.settled(); + failed(error); + return PromiseReject(error); } + return PromisePrototypeThen(next, onDirectResult, onDirectError); } - // Flush remaining stateless run - if (statelessRun.length > 0) { - current = applyFusedStatelessAsyncTransforms(current, statelessRun, - transformSignal); + // The pull is pending from now on: the signal can abort while the + // transforms or the source are called. + const promise = newPendingPromise(); + resolvePull = takeResolve(); + rejectPull = takeReject(); + let next; + try { + next = PromiseResolve(FunctionPrototypeCall(nextMethod, iterator)); + } catch (error) { + onError(error); + return promise; } + PromisePrototypeThen(next, onResult, onError); + return promise; + } - for await (const batch of current) { - controller.signal.throwIfAborted(); - yield batch; + function doReturn(value) { + const result = new IterResult(true, value); + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseResolve(result); } - // A transform can abort while completing without producing a final batch, - // for example when an async flush resolves to null. In that case the loop - // body has no opportunity to observe the abort. - controller.signal.throwIfAborted(); - completed = true; - } catch (error) { - if (!controller.signal.aborted) { - abortSignal(controller.signal, error); + state = kDone; + removeSignalListener(); + if (closeWithoutWaiting) { + markPromiseAsHandled(closeAsyncIterator(iterator, false)); + operations.settled(); + return PromiseResolve(result); } - throw error; - } finally { - if (!completed && !controller.signal.aborted) { - // Consumer stopped early or generator return() was called. - // If a transform listener throws here, let it propagate. - controller.abort(lazyDOMException('Aborted', 'AbortError')); - } - // Clean up user signal listener to prevent holding controller alive - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); + return PromisePrototypeThen( + closeAsyncIterator(iterator, false), () => { + operations.settled(); + return result; + }, (error) => { + operations.settled(); + throw error; + }); + } + + function doThrow(error) { + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseReject(error); } + state = kDone; + removeSignalListener(); + if (closeWithoutWaiting) { + markPromiseAsHandled(closeAsyncIterator(iterator, true)); + operations.settled(); + return PromiseReject(error); + } + return PromisePrototypeThen( + closeAsyncIterator(iterator, true), () => { + operations.settled(); + throw error; + }); } + + return self; } // ============================================================================= @@ -873,81 +1729,15 @@ function pull(source, ...args) { return { __proto__: null, [SymbolAsyncIterator]() { - if (signal === undefined) { - const controller = new AbortController(); - async function* pipeline() { - yield* createAsyncPipeline(normalized, transforms, controller.signal); - } - const iterator = pipeline(); - return ObjectSetPrototypeOf({ - next(value) { - return iterator.next(value); - }, - return(value) { - controller.abort(lazyDOMException('Aborted', 'AbortError')); - return iterator.return(value); - }, - throw(error) { - abortSignal(controller.signal, error); - return iterator.throw(error); - }, - [SymbolAsyncIterator]() { - return this; - }, - }, null); + // Without transforms or a signal, the pipeline is the source. + if (transforms.length === 0 && signal === undefined) { + return normalized[SymbolAsyncIterator](); } - return createAbortablePullIterator(normalized, transforms, signal); + return createAsyncPipeline(normalized, transforms, signal); }, }; } -// Once `signal` aborts the pipeline, the pull that observed it rejects and -// so does every later pull, with the abort reason. That includes the case of -// an already-aborted signal, where the pipeline is never started. A plain -// async generator would instead complete after throwing, so later pulls -// would report a clean end of the stream. -function createAbortablePullIterator(source, transforms, signal) { - let aborted = signal.aborted; - let controller; - let iterator; - if (!aborted) { - controller = new AbortController(); - const iteratorSignal = AbortSignal.any([signal, controller.signal]); - async function* pipeline() { - yield* createAsyncPipeline(source, transforms, iteratorSignal); - } - iterator = pipeline(); - } - - function onRejected(error) { - if (signal.aborted) aborted = true; - throw error; - } - - return ObjectSetPrototypeOf({ - next(value) { - if (aborted) return PromiseReject(signal.reason); - return PromisePrototypeThen(iterator.next(value), undefined, onRejected); - }, - return(value) { - if (aborted) { - return PromiseResolve(new IterResult(true, value)); - } - controller.abort(lazyDOMException('Aborted', 'AbortError')); - return iterator.return(value); - }, - throw(error) { - if (aborted) return PromiseReject(error); - abortSignal(controller.signal, error); - return PromisePrototypeThen(iterator.throw(error), undefined, - onRejected); - }, - [SymbolAsyncIterator]() { - return this; - }, - }, null); -} - // Keep ownership of a bonded consumer outside the transform pipeline so it can // be detached even when the pipeline never starts or terminates early. function pullWithConsumerCleanup(source, transforms, signal) { @@ -1063,6 +1853,32 @@ function pipeToSync(source, ...args) { try { for (const batch of pipeline) { + // Single chunk, the common case: no batch entry needed. + if (batch.length === 1) { + const chunk = batch[0]; + if (callWithByteView(chunk, writer.writeSync, writer) === false) { + throw new ERR_OUT_OF_RANGE( + 'write', 'within byte budget', 'budget exhausted'); + } + totalBytes += TypedArrayPrototypeGetByteLength(chunk); + continue; + } + if (!hasWritevSync) { + // Chunks written one at a time: snapshot them without an object for + // every chunk. + const fixed = snapshotFixedBatch(batch); + for (let i = 0; i < batch.length; i++) { + const chunk = checkFixedBatchChunk(fixed, i); + const accepted = writer.writeSync(chunk); + checkFixedBatchChunk(fixed, i); + if (accepted === false) { + throw new ERR_OUT_OF_RANGE( + 'write', 'within byte budget', 'budget exhausted'); + } + totalBytes += fixed.byteLengths[i]; + } + continue; + } const entry = createBatchEntry(batch); if (hasWritevSync && batch.length > 1) { const accepted = writer.writevSync(validateBatchEntry(entry)); @@ -1155,6 +1971,11 @@ async function pipeTo(source, ...args) { const hasWriteSync = typeof writer.writeSync === 'function'; const normalized = from(source); + // The options passed to every write(), writev() and end(). + const writeOptions = signal ? { __proto__: null, signal } : undefined; + // Without transforms, whether `signal` has aborted the pipe: the batches + // are then no longer read or written (see raceSignal()). + const abortState = { __proto__: null, aborted: false }; let totalBytes = 0; const hasWritev = typeof writer.writev === 'function'; @@ -1175,9 +1996,7 @@ async function pipeTo(source, ...args) { } validateByteView(view); } - const result = writer.write( - validateByteView(view), - signal ? { __proto__: null, signal } : undefined); + const result = writer.write(validateByteView(view), writeOptions); if (result !== undefined) { await result; } @@ -1186,17 +2005,170 @@ async function pipeTo(source, ...args) { } } + // Write a FixedBatch with write(), for a writer without writeSync(), + // starting at `index`: returns undefined if every write() returned + // undefined, or a promise for writing the rest once one returns a + // promise. A write() that returns undefined is not awaited. + function writeFixedBatchAsync(fixed, index) { + const { chunks } = fixed; + for (let i = index; i < chunks.length; i++) { + const result = writer.write(checkFixedBatchChunk(fixed, i), writeOptions); + checkFixedBatchChunk(fixed, i); + if (result !== undefined) { + return PromisePrototypeThen(PromiseResolve(result), () => { + checkFixedBatchChunk(fixed, i); + totalBytes += fixed.byteLengths[i]; + return writeFixedBatchAsync(fixed, i + 1); + }); + } + totalBytes += fixed.byteLengths[i]; + } + } + + // Write a single chunk with write(), for a writer without writeSync(), + // as writeFixedBatchAsync() does, without a FixedBatch. + function writeChunkAsync(chunk) { + const byteLength = TypedArrayPrototypeGetByteLength(chunk); + const result = writer.write(chunk, writeOptions); + if (TypedArrayPrototypeGetByteLength(chunk) !== byteLength) { + throwByteViewChanged(); + } + if (result === undefined) { + totalBytes += byteLength; + return; + } + return PromisePrototypeThen(PromiseResolve(result), () => { + if (TypedArrayPrototypeGetByteLength(chunk) !== byteLength) { + throwByteViewChanged(); + } + totalBytes += byteLength; + }); + } + + // Write a FixedBatch with writeSync(), like the loop at the end of + // writeBatch(), falling back to the async path for the rest of the batch. + function writeFixedBatch(fixed) { + const { chunks } = fixed; + for (let i = 0; i < chunks.length; i++) { + const chunk = checkFixedBatchChunk(fixed, i); + if (!writer.writeSync(chunk)) { + checkFixedBatchChunk(fixed, i); + return writeBatchAsyncFallback(fixedBatchToEntry(fixed), i); + } + checkFixedBatchChunk(fixed, i); + totalBytes += fixed.byteLengths[i]; + } + } + + // Write the batches of a sync source as the for await...of loop below + // does, reading them synchronously when possible: an error reading a + // batch ends the loop, and an error writing one closes the source first, + // ignoring errors closing it. + async function pipeSyncSource(iterator) { + for (;;) { + if (abortState.aborted) return; + let batch = iterator[kNextSyncBatch](); + if (batch === undefined) { + const result = await iterator.next(); + if (result.done || abortState.aborted) return; + batch = result.value; + } else if (batch === null) { + return; + } + try { + const p = writeBatch(batch); + if (p) await p; + } catch (error) { + if (!abortState.aborted) { + try { + await iterator.return(); + } catch { + // The error writing the batch is thrown. + } + } + throw error; + } + } + } + + // Write the batches of a source read with next(), as the for await...of + // loop below does, stopping once `signal` aborts. A from() source is read + // with kNextUncancellable: on an abort, raceSignal() rejects and closes + // the source at once, and a read still pending is ignored. + async function pipeSourceWithSignal(iterator) { + const uncancellable = iterator[kNextUncancellable] !== undefined; + for (;;) { + const result = await (uncancellable ? + iterator[kNextUncancellable](true) : iterator.next()); + if (result.done || abortState.aborted) return; + try { + const p = writeBatch(result.value); + if (p) await p; + } catch (error) { + if (!abortState.aborted) { + try { + await iterator.return(); + } catch { + // The error writing the batch is thrown. + } + } + throw error; + } + } + } + + // Write the batches of an async source as the for await...of loop below + // does. Nothing cancels the normalization while a batch is read: return() + // is only called after an error writing one. + async function pipeAsyncSource(iterator) { + for (;;) { + const result = await iterator[kNextUncancellable](); + if (result.done) return; + try { + const p = writeBatch(result.value); + if (p) await p; + } catch (error) { + try { + await iterator.return(); + } catch { + // The error writing the batch is thrown. + } + throw error; + } + } + } + // Write a batch using try-fallback: sync first, async if needed. // Returns undefined on sync success, or a Promise when async fallback // is required. Callers must check: const p = writeBatch(b); if (p) await p; function writeBatch(batch) { + // A writer with only write() (and writev(), used for batches of several + // chunks): no batch entry. + if (!hasWriteSync && (!hasWritev || batch.length === 1)) { + if (batch.length === 1) return writeChunkAsync(batch[0]); + return writeFixedBatchAsync(snapshotFixedBatch(batch), 0); + } + // Single chunk, the common case: check the view around writeSync() + // without allocating a batch entry, and create one only to fall back to + // the async path. + if (batch.length === 1 && hasWriteSync) { + const chunk = batch[0]; + if (callWithByteView(chunk, writer.writeSync, writer)) { + totalBytes += TypedArrayPrototypeGetByteLength(chunk); + return; + } + return writeBatchAsyncFallback(createBatchEntry(batch), 0); + } + if (!hasWritev && hasWriteSync) { + return writeFixedBatch(snapshotFixedBatch(batch)); + } const entry = createBatchEntry(batch); if (hasWritev && batch.length > 1) { if (!hasWritevSync || !writer.writevSync(validateBatchEntry(entry))) { validateBatchEntry(entry); - const opts = signal ? { __proto__: null, signal } : undefined; - const writevResult = writer.writev(validateBatchEntry(entry), opts); + const writevResult = writer.writev( + validateBatchEntry(entry), writeOptions); if (writevResult === undefined) { validateBatchEntry(entry); totalBytes += entry.byteLength; @@ -1228,11 +2200,16 @@ async function pipeTo(source, ...args) { if (transforms.length === 0) { // Fast path: no transforms - iterate normalized source directly if (signal) { - for await (const batch of yieldAbortable(normalized, signal)) { - signal.throwIfAborted(); - const p = writeBatch(batch); - if (p) await p; - } + // Batches are read synchronously when possible, as without a signal, + // otherwise as pipeSourceWithSignal() says. + const iterator = normalized[SymbolAsyncIterator](); + await raceSignal(iterator, signal, abortState, + iterator[kNextSyncBatch] !== undefined ? + pipeSyncSource : pipeSourceWithSignal); + } else if (normalized[kNextSyncBatch] !== undefined) { + await pipeSyncSource(normalized); + } else if (normalized[kNextUncancellable] !== undefined) { + await pipeAsyncSource(normalized); } else { for await (const batch of normalized) { const p = writeBatch(batch); @@ -1240,11 +2217,13 @@ async function pipeTo(source, ...args) { } } } else { - const pipeline = createAsyncPipeline(normalized, transforms, signal); + const pipeline = createAsyncPipeline( + normalized, transforms, signal, signal !== undefined); if (signal) { + // The pipeline rejects its pending pull when `signal` aborts. for await (const batch of pipeline) { - signal.throwIfAborted(); + if (signal.aborted) throw signal.reason; const p = writeBatch(batch); if (p) await p; } @@ -1258,7 +2237,7 @@ async function pipeTo(source, ...args) { if (!options.preventClose) { if (!hasEndSync || writer.endSync() < 0) { - await writer.end?.(signal ? { __proto__: null, signal } : undefined); + await writer.end?.(writeOptions); } } } catch (error) { diff --git a/lib/internal/streams/iter/push.js b/lib/internal/streams/iter/push.js index c99253af43e8..66c66a0a6d2d 100644 --- a/lib/internal/streams/iter/push.js +++ b/lib/internal/streams/iter/push.js @@ -26,6 +26,7 @@ const { const { drainableProtocol, + kValidatedSource, } = require('internal/streams/iter/types'); const { @@ -35,14 +36,19 @@ const { kNullOnceOption, kPushDefaultBudget, kResolvedPromise, - createBatchEntry, + createEntry, onSignalAbort, toWriterUint8Array, convertChunks, getWriterSignal, parsePullArgs, + snapshotByteView, validateBatchEntry, validateBudget, + validateByteView, + newPendingPromise, + takeReject, + takeResolve, } = require('internal/streams/iter/utils'); const { converters, @@ -189,11 +195,13 @@ class PushQueue { * Returns true if write completed, false if buffer is full. * @returns {boolean} */ - writeSync(chunks) { + // `entry` is a BatchEntry, or for a single chunk a FixedByteView (see + // createEntry()). + writeSync(entry) { if (this.#writerState !== 'open') return false; if (this.#consumerState !== 'active') return false; - return this.#writeEntry(createBatchEntry(chunks)); + return this.#writeEntry(entry); } #writeEntry(entry) { @@ -245,7 +253,7 @@ class PushQueue { * failure. * @returns {Promise<void>} */ - async writeAsync(chunks, signal) { + async writeAsync(entry, signal) { // Check writer state before signal (spec order: state, then signal) if (this.#writerState === 'closed') { throw new ERR_INVALID_STATE.TypeError('Writer is closed'); @@ -264,7 +272,6 @@ class PushQueue { // Check for pre-aborted signal (after state checks per spec) signal?.throwIfAborted(); - const entry = createBatchEntry(chunks); if (this.#writeEntry(entry)) { return; } @@ -293,7 +300,9 @@ class PushQueue { * @returns {Promise<void>} */ #createPendingWrite(batch, signal) { - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); const entry = new PendingWrite(batch, resolve, reject); this.#pendingWrites.push(entry); @@ -428,7 +437,9 @@ class PushQueue { * @returns {Promise<void>} */ waitForDrain() { - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); ArrayPrototypePush(this.#pendingDrains, new PendingRequest(resolve, reject)); return promise; } @@ -466,7 +477,9 @@ class PushQueue { throw this.#writerError; } - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); this.#pendingReads.push(new PendingRequest(resolve, reject)); return promise; } @@ -499,16 +512,24 @@ class PushQueue { #drain() { try { if (this.#slots.length === 1) { - const result = validateBatchEntry(this.#slots.shift()); + const entry = this.#slots.shift(); + const result = entry.views === undefined ? + [validateByteView(entry)] : validateBatchEntry(entry); this.#bufferedBytes = 0; return result; } + // The chunks of every entry, validated straight into one batch. const result = []; for (let i = 0; i < this.#slots.length; i++) { - const batch = validateBatchEntry(this.#slots.get(i)); - for (let j = 0; j < batch.length; j++) { - ArrayPrototypePush(result, batch[j]); + const entry = this.#slots.get(i); + const views = entry.views; + if (views === undefined) { + result[result.length] = validateByteView(entry); + continue; + } + for (let j = 0; j < views.length; j++) { + result[result.length] = validateByteView(views[j]); } } this.#slots.clear(); @@ -577,7 +598,7 @@ class PushQueue { this.#bufferedBytes < this.#budget) { const pending = this.#pendingWrites.shift(); try { - validateBatchEntry(pending.batch); + checkEntry(pending.batch); this.#slots.push(pending.batch); this.#bufferedBytes += pending.batch.byteLength; this.#bytesWritten += pending.batch.byteLength; @@ -593,6 +614,7 @@ class PushQueue { } #resolvePendingDrains(canWrite) { + if (this.#pendingDrains.length === 0) return; const drains = this.#pendingDrains; this.#pendingDrains = []; for (let i = 0; i < drains.length; i++) { @@ -601,6 +623,7 @@ class PushQueue { } #rejectPendingDrains(error) { + if (this.#pendingDrains.length === 0) return; const drains = this.#pendingDrains; this.#pendingDrains = []; for (let i = 0; i < drains.length; i++) { @@ -628,6 +651,17 @@ class PushQueue { } } +// Check that the chunks of a buffered entry still have the byteLength they +// were accepted with, as validateBatchEntry() does, without collecting them. +function checkEntry(entry) { + const views = entry.views; + if (views === undefined) { + validateByteView(entry); + return; + } + for (let i = 0; i < views.length; i++) validateByteView(views[i]); +} + // ============================================================================= // PushWriter Implementation // ============================================================================= @@ -651,32 +685,30 @@ class PushWriter { } write(chunk, options) { - const bytes = toWriterUint8Array(chunk); + const entry = snapshotByteView(toWriterUint8Array(chunk)); const signal = getWriterSignal(options); if (!signal && this.#queue.canWriteSync()) { - this.#queue.writeSync([bytes]); + this.#queue.writeSync(entry); return kResolvedPromise; } - return this.#queue.writeAsync([bytes], signal); + return this.#queue.writeAsync(entry, signal); } writev(chunks, options) { - const bytes = convertChunks(chunks); + const entry = createEntry(convertChunks(chunks)); const signal = getWriterSignal(options); - if (!signal && this.#queue.writeSync(bytes)) { + if (!signal && this.#queue.writeSync(entry)) { return kResolvedPromise; } - return this.#queue.writeAsync(bytes, signal); + return this.#queue.writeAsync(entry, signal); } writeSync(chunk) { - const bytes = toWriterUint8Array(chunk); - return this.#queue.writeSync([bytes]); + return this.#queue.writeSync(snapshotByteView(toWriterUint8Array(chunk))); } writevSync(chunks) { - const bytes = convertChunks(chunks); - return this.#queue.writeSync(bytes); + return this.#queue.writeSync(createEntry(convertChunks(chunks))); } end(options) { @@ -734,14 +766,17 @@ class PushWriter { function createReadable(queue) { return { __proto__: null, + // The batches read are validated already: from() and pipeTo() can read + // them without normalizing them again. + [kValidatedSource]: true, [SymbolAsyncIterator]() { return ObjectSetPrototypeOf({ async next() { return queue.read(); }, - async return() { + async return(value) { queue.consumerReturn(); - return new IterResult(true, undefined); + return new IterResult(true, value); }, async throw(error) { queue.consumerThrow(error); diff --git a/lib/internal/streams/iter/share.js b/lib/internal/streams/iter/share.js index 937528b3929c..6496e548eb78 100644 --- a/lib/internal/streams/iter/share.js +++ b/lib/internal/streams/iter/share.js @@ -10,9 +10,8 @@ const { FunctionPrototypeCall, ObjectSetPrototypeOf, PromisePrototypeThen, + PromiseReject, PromiseResolve, - PromiseWithResolvers, - SafePromiseRace, SafeSet, Symbol, SymbolAsyncIterator, @@ -30,6 +29,7 @@ const { fromSync, isAsyncIterable, isSyncIterable, + kNextSyncBatch, } = require('internal/streams/iter/from'); const { @@ -40,7 +40,7 @@ const { const { IterResult, kMultiConsumerDefaultBudget, - createBatchEntry, + createEntry, getProtocolMethod, getMinCursor, onSignalAbort, @@ -48,6 +48,8 @@ const { splitBatchEntry, validateBatchEntry, validateBudget, + newResolveOnlyPromise, + takeResolve, } = require('internal/streams/iter/utils'); const { converters, @@ -74,9 +76,19 @@ const { markPromiseAsHandled } = internalBinding('util'); // ============================================================================= const kNoShareError = Symbol('kNoShareError'); -const kShareCancelled = Symbol('kShareCancelled'); +// Returned by #tryRead() when the consumer must wait for the source. +const kPull = Symbol('kPull'); const kSetFactorySignal = Symbol('kSetFactorySignal'); +// Clear `pending` from the pendingNext of the consumer `state` when it +// settles, unless a next() has been queued behind it. +function clearPendingNext(state, pending) { + const onSettled = () => { + if (state.pendingNext === pending) state.pendingNext = null; + }; + PromisePrototypeThen(pending, onSettled, onSettled); +} + class ShareImpl { #source; #options; @@ -89,8 +101,15 @@ class ShareImpl { #cancelled = false; #pulling = false; #pullWaiters = []; - #cancelPromise; - #resolveCancel; + // While the source is read: the promise that every consumer waiting for + // the read waits for, the function resolving it, and whether the batch + // read is to be discarded ('drop-newest'). A cancellation resolves it at + // once: racing the read with a promise settled by cancel() would add + // reactions to that promise on every read, which would be kept until the + // share is cancelled or collected. + #pullDone = null; + #resolvePull = null; + #pullDiscard = false; #cancelError = kNoShareError; #cachedMinCursor = 0; #cachedMinCursorConsumers = 0; @@ -101,9 +120,6 @@ class ShareImpl { constructor(source, options) { this.#source = source; this.#options = options; - const { promise, resolve } = PromiseWithResolvers(); - this.#cancelPromise = promise; - this.#resolveCancel = resolve; } get consumerCount() { @@ -151,7 +167,16 @@ class ShareImpl { reject: null, detached: false, error: kNoShareError, - pendingNext: PromiseResolve(), + // Set by #readAsync() for next(): the read waits for the source. + waiting: false, + // Created by #readAfterPull() on first use. + afterPull: undefined, + // The read #readAfterPull() returned, while it is pending. + waitingRead: null, + // The last pending next() of the consumer, if it is waiting for the + // source: the next one waits for it, as next() calls of an async + // generator do. + pendingNext: null, }, null); this.#consumers.add(state); @@ -168,82 +193,42 @@ class ShareImpl { return { __proto__: null, [SymbolAsyncIterator]() { - const getNext = async () => { - // Loop until we get data, source is exhausted, or - // consumer is detached. Multiple consumers may be woken - // after a single pull - those that find no data at their - // cursor must re-pull rather than terminating prematurely. - for (;;) { - if (state.detached) { - if (state.error !== kNoShareError) throw state.error; - return new IterResult(true, undefined); - } - - if (self.#cancelled) { - state.detached = true; - state.error = self.#cancelError; - self.#deleteConsumer(state); - if (state.error !== kNoShareError) throw state.error; - return new IterResult(true, undefined); - } - - // Check if data is available in buffer - const bufferIndex = state.cursor - self.#bufferStart; - if (bufferIndex < self.#buffer.length) { - const chunk = self.#readEntry(self.#buffer.get(bufferIndex)); - const cursor = state.cursor; - state.cursor++; - if (cursor === self.#cachedMinCursor && - --self.#cachedMinCursorConsumers === 0) { - self.#tryTrimBuffer(); - } - return new IterResult(false, chunk); - } - - if (self.#sourceExhausted) { - state.detached = true; - self.#deleteConsumer(state); - if (self.#sourceError !== kNoShareError) { - state.error = self.#sourceError; - throw state.error; - } - return new IterResult(true, undefined); - } - - // Need to pull from source - check buffer limit - let shouldBuffer; - try { - shouldBuffer = await self.#waitForBufferSpace(); - } catch (error) { - state.detached = true; - if (self.#deleteConsumer(state)) { - self.#tryTrimBuffer(); - } - throw error; - } - if (shouldBuffer === null) { - state.detached = true; - state.error = self.#cancelError; - self.#deleteConsumer(state); - if (state.error !== kNoShareError) throw state.error; - return new IterResult(true, undefined); - } - - await self.#pullFromSource(!shouldBuffer); - if (!shouldBuffer) { - await self.#waitForBufferSpaceAfterDrop(); + // A read that finds data, or the end, settles at once; one that + // waits for the source becomes pendingNext. + const read = () => { + let result; + try { + result = self.#tryRead(state); + // A sync source can be read at once, when there is room. + while (result === kPull && + self.#bufferedBytes < self.#options.budget && + self.#pullSync()) { + result = self.#tryRead(state); } + } catch (error) { + return PromiseReject(error); } + if (result !== kPull) return PromiseResolve(result); + return self.#readAsync(state); }; + const clearPending = (pending) => clearPendingNext(state, pending); return ObjectSetPrototypeOf({ next() { - const next = PromisePrototypeThen( - state.pendingNext, - getNext, - getNext); + let next; + if (state.pendingNext !== null) { + next = PromisePrototypeThen(state.pendingNext, read, read); + } else { + state.waiting = false; + next = read(); + // Settled at once: nothing for a later next() to wait for. + if (!state.waiting) return next; + } state.pendingNext = next; - markPromiseAsHandled(state.pendingNext); + markPromiseAsHandled(next); + // A read waiting for a pull of the source clears pendingNext + // itself (see #readAfterPull()). + if (next !== state.waitingRead) clearPending(next); return next; }, @@ -280,8 +265,7 @@ class ShareImpl { this.#cancelError = reason; } - this.#resolveCancel(kShareCancelled); - this.#resolveCancel = null; + if (this.#resolvePull !== null) this.#finishPull(); try { const returnMethod = this.#sourceIterator?.return; @@ -327,6 +311,169 @@ class ShareImpl { // Internal methods + // Read the consumer's next batch if it is buffered, or the end: returns + // its result, or kPull if the source must be read first. + #tryRead(state) { + if (state.detached) { + if (state.error !== kNoShareError) throw state.error; + return new IterResult(true, undefined); + } + + if (this.#cancelled) { + state.detached = true; + state.error = this.#cancelError; + this.#deleteConsumer(state); + if (state.error !== kNoShareError) throw state.error; + return new IterResult(true, undefined); + } + + // Check if data is available in buffer + const bufferIndex = state.cursor - this.#bufferStart; + if (bufferIndex < this.#buffer.length) { + const chunk = this.#readEntry(this.#buffer.get(bufferIndex)); + const cursor = state.cursor; + state.cursor++; + if (cursor === this.#cachedMinCursor && + --this.#cachedMinCursorConsumers === 0) { + this.#tryTrimBuffer(); + } + return new IterResult(false, chunk); + } + + if (this.#sourceExhausted) { + state.detached = true; + this.#deleteConsumer(state); + if (this.#sourceError !== kNoShareError) { + state.error = this.#sourceError; + throw state.error; + } + return new IterResult(true, undefined); + } + return kPull; + } + + // Read the consumer's next batch once the source has been read. Loops + // until it gets data, the source is exhausted, or the consumer is + // detached: multiple consumers may be woken after a single pull, and + // those that find no data at their cursor must pull again rather than + // terminate prematurely. + #readAsync(state) { + state.waiting = true; + if (this.#bufferedBytes < this.#options.budget) { + const read = this.#readAfterPull(state); + state.waitingRead = read; + return read; + } + return this.#readAsyncLoop(state); + } + + async #readAsyncLoop(state) { + for (;;) { + // Need to pull from source - check buffer limit + let shouldBuffer; + if (this.#bufferedBytes < this.#options.budget) { + shouldBuffer = true; + } else { + try { + shouldBuffer = await this.#waitForBufferSpace(); + } catch (error) { + state.detached = true; + if (this.#deleteConsumer(state)) { + this.#tryTrimBuffer(); + } + throw error; + } + } + if (shouldBuffer === null) { + state.detached = true; + state.error = this.#cancelError; + this.#deleteConsumer(state); + if (state.error !== kNoShareError) throw state.error; + return new IterResult(true, undefined); + } + + await this.#pullFromSource(!shouldBuffer); + if (!shouldBuffer) { + await this.#waitForBufferSpaceAfterDrop(); + } + + const result = this.#tryRead(state); + if (result !== kPull) return result; + } + } + + // The common case of #readAsyncLoop(), without an async function: there + // is room in the buffer, so read the source and then the consumer's batch. + // When the read settles with the result afterPull() returns, it is no + // longer pending: clear it from pendingNext, unless a next() has been + // queued behind it, without a reaction of its own. + #readAfterPull(state) { + // afterPull() is created by a method of its own: if it were created + // here, V8 would allocate the context it captures on every call, even + // when it already exists. + state.afterPull ??= this.#createAfterPull(state); + return PromisePrototypeThen(this.#pullFromSource(false), state.afterPull); + } + + #createAfterPull(state) { + return () => { + let result; + try { + result = this.#tryRead(state); + } catch (error) { + this.#clearWaitingRead(state); + throw error; + } + if (result === kPull) { + // Still pending: clear it when it settles. + const read = state.waitingRead; + state.waitingRead = null; + if (state.pendingNext === read) clearPendingNext(state, read); + return this.#readAsyncLoop(state); + } + this.#clearWaitingRead(state); + return result; + }; + } + + #clearWaitingRead(state) { + if (state.pendingNext === state.waitingRead) state.pendingNext = null; + state.waitingRead = null; + } + + // Read a batch of the source synchronously, if it can be read so (a sync + // source normalized by from()) and no read of it is pending. Returns + // whether the source was read: a batch buffered, or its end or error + // recorded. + #pullSync() { + if (this.#pulling || this.#sourceExhausted || this.#cancelled) { + return false; + } + try { + const iterator = this.#getSourceIterator(); + const nextSyncBatch = iterator[kNextSyncBatch]; + if (nextSyncBatch === undefined) return false; + const batch = FunctionPrototypeCall(nextSyncBatch, iterator); + if (batch === undefined) return false; + if (batch === null) { + this.#sourceExhausted = true; + } else { + this.#bufferBatch(batch); + } + } catch (error) { + this.#sourceError = error; + this.#sourceExhausted = true; + } + if (this.#sourceExhausted && this.#consumers.size === 0) { + this.#cleanupFactorySignal(); + } + for (let i = 0; i < this.#pullWaiters.length; i++) { + this.#pullWaiters[i](); + } + this.#pullWaiters = []; + return true; + } + async #waitForBufferSpace() { while (this.#bufferedBytes >= this.#options.budget) { if (this.#cancelled || @@ -341,7 +488,8 @@ class ShareImpl { 'buffered bytes', `< ${this.#options.budget}`, this.#bufferedBytes); case 'unbounded': { - const { promise, resolve } = PromiseWithResolvers(); + const promise = newResolveOnlyPromise(); + const resolve = takeResolve(); ArrayPrototypePush(this.#pullWaiters, resolve); await promise; break; @@ -373,7 +521,8 @@ class ShareImpl { !this.#cancelled && this.#sourceError === kNoShareError && !this.#sourceExhausted) { - const { promise, resolve } = PromiseWithResolvers(); + const promise = newResolveOnlyPromise(); + const resolve = takeResolve(); ArrayPrototypePush(this.#pullWaiters, resolve); await promise; } @@ -384,68 +533,94 @@ class ShareImpl { return PromiseResolve(); } - if (this.#pulling) { - const { promise, resolve } = PromiseWithResolvers(); - ArrayPrototypePush(this.#pullWaiters, resolve); - return promise; - } + if (this.#pulling) return this.#pullDone; this.#pulling = true; + const promise = newResolveOnlyPromise(); + const resolve = takeResolve(); + this.#pullDone = promise; + this.#resolvePull = resolve; + this.#pullDiscard = discard; - return (async () => { - try { - if (!this.#sourceIterator) { - if (isAsyncIterable(this.#source)) { - this.#sourceIterator = - this.#source[SymbolAsyncIterator](); - } else if (isSyncIterable(this.#source)) { - const syncIterator = - this.#source[SymbolIterator](); - this.#sourceIterator = ObjectSetPrototypeOf({ - async next() { - return syncIterator.next(); - }, - async return() { - return syncIterator.return?.() ?? - new IterResult(true, undefined); - }, - }, null); - } else { - throw new ERR_INVALID_ARG_TYPE( - 'source', ['AsyncIterable', 'Iterable'], this.#source); - } - } - - const result = await SafePromiseRace([ - this.#sourceIterator.next(), - this.#cancelPromise, - ]); + let next; + try { + next = this.#getSourceIterator().next(); + } catch (error) { + this.#onReadError(error); + return promise; + } + PromisePrototypeThen(PromiseResolve(next), this.#onReadResult, + this.#onReadError); + return promise; + } - if (this.#cancelled || result === kShareCancelled) return; + #getSourceIterator() { + if (!this.#sourceIterator) { + if (isAsyncIterable(this.#source)) { + this.#sourceIterator = + this.#source[SymbolAsyncIterator](); + } else if (isSyncIterable(this.#source)) { + const syncIterator = + this.#source[SymbolIterator](); + this.#sourceIterator = ObjectSetPrototypeOf({ + // Its result is passed to PromiseResolve(). + next() { + return syncIterator.next(); + }, + async return() { + return syncIterator.return?.() ?? + new IterResult(true, undefined); + }, + }, null); + } else { + throw new ERR_INVALID_ARG_TYPE( + 'source', ['AsyncIterable', 'Iterable'], this.#source); + } + } + return this.#sourceIterator; + } - if (result.done) { - this.#sourceExhausted = true; - } else if (!discard) { - this.#bufferBatch(result.value); - } - } catch (error) { - this.#sourceError = error; + // The handlers of a read of the source, created once per share. A read + // ended by a cancellation is ignored. + #onReadResult = (result) => { + if (this.#resolvePull === null || this.#cancelled) return; + try { + if (result.done) { this.#sourceExhausted = true; - } finally { - if (this.#sourceExhausted && this.#consumers.size === 0) { - this.#cleanupFactorySignal(); - } - this.#pulling = false; - for (let i = 0; i < this.#pullWaiters.length; i++) { - this.#pullWaiters[i](); - } - this.#pullWaiters = []; + } else if (!this.#pullDiscard) { + this.#bufferBatch(result.value); } - })(); + } catch (error) { + this.#sourceError = error; + this.#sourceExhausted = true; + } + this.#finishPull(); + }; + + #onReadError = (error) => { + if (this.#resolvePull === null || this.#cancelled) return; + this.#sourceError = error; + this.#sourceExhausted = true; + this.#finishPull(); + }; + + #finishPull() { + const resolve = this.#resolvePull; + this.#resolvePull = null; + this.#pullDone = null; + if (this.#sourceExhausted && this.#consumers.size === 0) { + this.#cleanupFactorySignal(); + } + this.#pulling = false; + for (let i = 0; i < this.#pullWaiters.length; i++) { + this.#pullWaiters[i](); + } + this.#pullWaiters = []; + resolve(); } #bufferBatch(batch) { - const entry = createBatchEntry(batch); + const entry = createEntry(batch); // 'drop-oldest' evicts whole entries. A single pulled batch can be much // larger than the budget (for example when from() combines many values // of a sync source), and evicting it would discard every chunk in it, @@ -773,7 +948,7 @@ class SyncShareImpl { } #bufferBatch(batch) { - const entry = createBatchEntry(batch); + const entry = createEntry(batch); // 'drop-oldest' evicts whole entries. A single pulled batch can be much // larger than the budget (for example when from() combines many values // of a sync source), and evicting it would discard every chunk in it, diff --git a/lib/internal/streams/iter/transform.js b/lib/internal/streams/iter/transform.js index c6c315cf6bd6..da4258dada03 100644 --- a/lib/internal/streams/iter/transform.js +++ b/lib/internal/streams/iter/transform.js @@ -10,8 +10,7 @@ const { ArrayPrototypeMap, - ArrayPrototypePush, - ArrayPrototypeShift, + ArrayPrototypeSlice, FunctionPrototypeCall, MathMax, NumberIsNaN, @@ -19,7 +18,6 @@ const { ObjectKeys, PromisePrototypeThen, PromiseResolve, - PromiseWithResolvers, StringPrototypeStartsWith, SymbolAsyncIterator, TypedArrayPrototypeFill, @@ -40,7 +38,12 @@ const { } = require('internal/errors'); const { isArrayBufferView, isAnyArrayBuffer } = require('internal/util/types'); const { kValidatedTransform } = require('internal/streams/iter/types'); -const { kNullOnceOption } = require('internal/streams/iter/utils'); +const { + kNullOnceOption, + newPendingPromise, + takeReject, + takeResolve, +} = require('internal/streams/iter/utils'); const { checkRangesOrGetDefault, kValidateObjectAllowArray, @@ -311,6 +314,8 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { let outOffset = 0; let chunkSize; let pending = []; + // Index of the first buffer of `pending` not yet taken by drainBatch(). + let pendingHead = 0; let pendingBytes = 0; // Current write operation state (read by the callback for looping). @@ -331,18 +336,16 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { if (have > 0) { if (bufferExhausted && outOffset === 0) { // Entire buffer filled from start - yield directly, no copy. - ArrayPrototypePush(pending, outBuf); + pending[pending.length] = outBuf; } else if (bufferExhausted) { // Tail of buffer filled and buffer is being replaced - // subarray is safe since outBuf reference is overwritten below. - ArrayPrototypePush(pending, - outBuf.subarray(outOffset, outOffset + have)); + pending[pending.length] = + outBuf.subarray(outOffset, outOffset + have); } else { // Partial fill, buffer will be reused - must copy. - ArrayPrototypePush(pending, - TypedArrayPrototypeSlice(outBuf, - outOffset, - outOffset + have)); + pending[pending.length] = + TypedArrayPrototypeSlice(outBuf, outOffset, outOffset + have); } pendingBytes += have; outOffset += have; @@ -417,7 +420,9 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { signal.addEventListener('abort', onAbort, kNullOnceOption); function continueInputAsync() { - const { promise, resolve, reject } = PromiseWithResolvers(); + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); resolveWrite = resolve; rejectWrite = reject; writeAvailOutBefore = chunkSize - outOffset; @@ -442,20 +447,33 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { function drainBatch() { if (pendingBytes <= BATCH_HWM) { - // Swap instead of splice - avoids copying the array. - const batch = pending; + // Take everything: swap instead of copying, unless batches have + // already been taken from the front. + const batch = pendingHead === 0 ? pending : + ArrayPrototypeSlice(pending, pendingHead); pending = []; + pendingHead = 0; pendingBytes = 0; return batch; } - const batch = []; + // Take up to BATCH_HWM bytes from the front by advancing pendingHead: + // shifting them off instead would copy the rest of the array, which + // makes draining a large output quadratic. + let end = pendingHead; let batchBytes = 0; - while (pending.length > 0 && batchBytes < BATCH_HWM) { - const buf = ArrayPrototypeShift(pending); - ArrayPrototypePush(batch, buf); - const len = TypedArrayPrototypeGetByteLength(buf); - batchBytes += len; - pendingBytes -= len; + while (end < pending.length && batchBytes < BATCH_HWM) { + batchBytes += TypedArrayPrototypeGetByteLength(pending[end]); + end++; + } + const batch = ArrayPrototypeSlice(pending, pendingHead, end); + pendingBytes -= batchBytes; + if (end === pending.length) { + pending = []; + pendingHead = 0; + } else { + // Do not keep the buffers taken alive. + for (let i = pendingHead; i < end; i++) pending[i] = undefined; + pendingHead = end; } return batch; } @@ -511,7 +529,7 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { processInputBatches(kEmpty, finishFlag)) { yield batch; } - while (pending.length > 0) { + while (pending.length > pendingHead) { yield drainBatch(); } } @@ -531,11 +549,12 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { } if (pendingBytes >= BATCH_HWM) { - while (pending.length > 0 && pendingBytes >= BATCH_HWM) { + while (pending.length > pendingHead && + pendingBytes >= BATCH_HWM) { yield drainBatch(); } } - if (pending.length > 0) { + if (pending.length > pendingHead) { yield drainBatch(); } } @@ -547,7 +566,7 @@ function makeZlibTransform(createHandleFn, processFlag, finishFlag) { processInputBatches(kEmpty, finishFlag)) { yield batch; } - while (pending.length > 0) { + while (pending.length > pendingHead) { yield drainBatch(); } } @@ -602,6 +621,8 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { let outBuf = Buffer.allocUnsafe(chunkSize); let outOffset = 0; let pending = []; + // Index of the first buffer of `pending` not yet taken by drainBatch(). + let pendingHead = 0; let pendingBytes = 0; function processSyncInput(input, flushFlag) { @@ -624,17 +645,15 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { if (have > 0) { if (bufferExhausted && outOffset === 0) { // Entire buffer filled - yield directly, no copy. - ArrayPrototypePush(pending, outBuf); + pending[pending.length] = outBuf; } else if (bufferExhausted) { // Tail filled, buffer being replaced - subarray is safe. - ArrayPrototypePush(pending, - outBuf.subarray(outOffset, outOffset + have)); + pending[pending.length] = + outBuf.subarray(outOffset, outOffset + have); } else { // Partial fill, buffer reused - must copy. - ArrayPrototypePush(pending, - TypedArrayPrototypeSlice(outBuf, - outOffset, - outOffset + have)); + pending[pending.length] = + TypedArrayPrototypeSlice(outBuf, outOffset, outOffset + have); } pendingBytes += have; outOffset += have; @@ -666,19 +685,33 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { function drainBatch() { if (pendingBytes <= BATCH_HWM) { - const batch = pending; + // Take everything: swap instead of copying, unless batches have + // already been taken from the front. + const batch = pendingHead === 0 ? pending : + ArrayPrototypeSlice(pending, pendingHead); pending = []; + pendingHead = 0; pendingBytes = 0; return batch; } - const batch = []; + // Take up to BATCH_HWM bytes from the front by advancing pendingHead: + // shifting them off instead would copy the rest of the array, which + // makes draining a large output quadratic. + let end = pendingHead; let batchBytes = 0; - while (pending.length > 0 && batchBytes < BATCH_HWM) { - const buf = ArrayPrototypeShift(pending); - const len = TypedArrayPrototypeGetByteLength(buf); - ArrayPrototypePush(batch, buf); - batchBytes += len; - pendingBytes -= len; + while (end < pending.length && batchBytes < BATCH_HWM) { + batchBytes += TypedArrayPrototypeGetByteLength(pending[end]); + end++; + } + const batch = ArrayPrototypeSlice(pending, pendingHead, end); + pendingBytes -= batchBytes; + if (end === pending.length) { + pending = []; + pendingHead = 0; + } else { + // Do not keep the buffers taken alive. + for (let i = pendingHead; i < end; i++) pending[i] = undefined; + pendingHead = end; } return batch; } @@ -688,7 +721,7 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { if (batch === null) { // Flush signal - finalize the engine. processSyncInput(Buffer.alloc(0), finishFlag); - while (pending.length > 0) { + while (pending.length > pendingHead) { yield drainBatch(); } continue; @@ -699,11 +732,12 @@ function makeZlibTransformSync(createHandleFn, processFlag, finishFlag) { } if (pendingBytes >= BATCH_HWM) { - while (pending.length > 0 && pendingBytes >= BATCH_HWM) { + while (pending.length > pendingHead && + pendingBytes >= BATCH_HWM) { yield drainBatch(); } } - if (pending.length > 0) { + if (pending.length > pendingHead) { yield drainBatch(); } } diff --git a/lib/internal/streams/iter/utils.js b/lib/internal/streams/iter/utils.js index 8c2835acd8bd..01e4ea0ce67c 100644 --- a/lib/internal/streams/iter/utils.js +++ b/lib/internal/streams/iter/utils.js @@ -3,16 +3,16 @@ const { Array, ArrayBufferPrototypeGetByteLength, - ArrayBufferPrototypeGetDetached, - ArrayBufferPrototypeGetResizable, - ArrayPrototypePush, ArrayPrototypeSlice, + FunctionPrototypeCall, ObjectDefineProperty, ObjectFreeze, + ObjectSetPrototypeOf, + Promise, + PromisePrototypeThen, + PromiseReject, PromiseResolve, PromiseWithResolvers, - SafePromisePrototypeFinally, - SafePromiseRace, SafeWeakSet, SymbolAsyncIterator, TypedArrayPrototypeGetBuffer, @@ -27,6 +27,8 @@ const { } = internalBinding('util'); const { TextEncoder } = require('internal/encoding'); +const { markAsUntransferable } = require('internal/buffer'); +const { utf8WriteStatic } = internalBinding('buffer'); const { codes: { ERR_INVALID_ARG_TYPE, @@ -35,6 +37,12 @@ const { } = require('internal/errors'); const { isSharedArrayBuffer, isUint8Array } = require('internal/util/types'); +const { kWeakHandler } = require('internal/event_target'); +const { + AbortController, + abortSignal, +} = require('internal/abort_controller'); +const { RingBuffer } = require('internal/streams/iter/ringbuffer'); const { validateInteger, @@ -55,9 +63,81 @@ const kNullOnceOption = ObjectFreeze({ __proto__: null, once: true }); // Cached resolved promise to avoid allocating a new one on every sync fast-path. const kResolvedPromise = PromiseResolve(); +// A pending promise and its resolving functions, for paths that create one +// per read or per batch. PromiseWithResolvers() also allocates an object to +// return the three in (about 85 of its 300 bytes without pointer +// compression). The executor runs synchronously, so the functions are taken +// from these slots right after the promise is created: +// const promise = newPendingPromise(); +// const resolve = takeResolve(); +// const reject = takeReject(); +let capturedResolve; +let capturedReject; +function captureResolvers(resolve, reject) { + capturedResolve = resolve; + capturedReject = reject; +} + +function newPendingPromise() { + return new Promise(captureResolvers); +} + +function takeResolve() { + const resolve = capturedResolve; + capturedResolve = undefined; + return resolve; +} + +function takeReject() { + const reject = capturedReject; + capturedReject = undefined; + return reject; +} + +// The same, for a promise that is only ever resolved: only takeResolve() +// follows it. +function captureResolve(resolve) { + capturedResolve = resolve; +} + +function newResolveOnlyPromise() { + return new Promise(captureResolve); +} + // Shared TextEncoder instance for string conversion. const encoder = new TextEncoder(); +// Small strings are encoded into a pool, like Buffer.from(string), instead +// of each into an ArrayBuffer of its own: writing many small strings, as a +// server-side renderer does, is otherwise mostly the cost of allocating +// them. The pool is untransferable, so that transferring the buffer of one +// chunk cannot detach the others. A string is pooled when its UTF-8 encoding +// fits in kMaxPooledByteLength bytes for certain: every UTF-16 code unit +// encodes to at most 3 bytes. +const kStringPoolSize = 64 * 1024; +const kMaxPooledLength = 8 * 1024 / 3; +let stringPool = null; +let stringPoolBuffer; +let stringPoolOffset = 0; + +function encodeString(string) { + const length = string.length; + if (length > kMaxPooledLength) return encoder.encode(string); + const maxByteLength = length * 3; + if (stringPool === null || + maxByteLength > kStringPoolSize - stringPoolOffset) { + stringPool = new Uint8Array(kStringPoolSize); + stringPoolBuffer = TypedArrayPrototypeGetBuffer(stringPool); + markAsUntransferable(stringPoolBuffer); + stringPoolOffset = 0; + } + const offset = stringPoolOffset; + const written = utf8WriteStatic(stringPool, string, offset, maxByteLength); + // Keep the chunks 8-byte aligned, as Buffer does. + stringPoolOffset = (offset + written + 7) & ~7; + return new Uint8Array(stringPoolBuffer, offset, written); +} + // Default high water marks for push and multi-consumer streams. These values // are somewhat arbitrary but have been tested across various workloads and // appear to yield the best overall throughput/latency balance. @@ -107,34 +187,109 @@ function onSignalAbort(signal, handler) { } } -function getOnAbort(reject, signal) { - return () => reject(signal.reason); +/** + * The abort state of a pipeline: what the AbortController of a pipeline in + * the specification holds, without creating an AbortController unless its + * signal is used. Most transforms never read the signal passed to them, so + * most pipelines never need one. When the signal is first read, it is + * created aborted with the same reason if the pipeline has been aborted: + * nothing can have listened to it before, so this cannot be told apart from + * a signal created with the pipeline. Code inside the pipeline checks + * `aborted` instead of reading the signal. + */ +class PipelineAbort { + aborted = false; + reason = undefined; + #controller = null; + + get signal() { + let controller = this.#controller; + if (controller === null) { + controller = this.#controller = new AbortController(); + if (this.aborted) abortSignal(controller.signal, this.reason); + } + return controller.signal; + } + + /** + * Abort the pipeline with `reason`, if it is not aborted already. Abort + * listeners on the signal, if it has been created, run synchronously, and + * errors they throw propagate. + * @param {any} reason + */ + abort(reason) { + if (this.aborted) return; + this.aborted = true; + this.reason = reason; + if (this.#controller !== null) { + abortSignal(this.#controller.signal, reason); + } + } + + throwIfAborted() { + if (this.aborted) throw this.reason; + } } /** - * Read one item from an async iterator, rejecting early if the signal aborts. - * @param {AsyncIterator} iterator - The iterator to read from. - * @param {AbortSignal|undefined} signal - Optional abort signal. - * @returns {Promise<IteratorResult<Uint8Array[]>>|IteratorResult<Uint8Array[]>} + * Wait for `consume(iterator)`, which reads `iterator` (a normalized source) + * to the end, unless `signal` aborts first. On an abort, `state.aborted` is + * set, the source is closed without waiting, ignoring errors, and the + * returned promise rejects with the abort reason at once, as a pull() + * pipeline with `signal` would reject its pending pull; `consume` must check + * `state.aborted` after each read and stop. Closing and rejecting wait for a + * microtask, as the signal can abort while the source is called. + * + * This takes one listener and one promise for the whole read, instead of a + * layer around the source adding a promise to every read. + * @param {AsyncIterator} iterator + * @param {AbortSignal} signal + * @param {{ aborted: boolean }} state + * @param {Function} consume + * @returns {Promise<any>} */ -function abortableNext(iterator, signal) { - if (signal === undefined) { - return iterator.next(); +function raceSignal(iterator, signal, state, consume) { + const { promise, resolve, reject } = PromiseWithResolvers(); + let settled = false; + function closeAndReject() { + try { + const returnMethod = iterator.return; + if (typeof returnMethod === 'function') { + markPromiseAsHandled(PromiseResolve( + FunctionPrototypeCall(returnMethod, iterator))); + } + } catch { + // The abort takes precedence over errors closing the source. + } + reject(signal.reason); } - signal.throwIfAborted(); - - const next = iterator.next(); - const { promise, reject } = PromiseWithResolvers(); - const onAbort = getOnAbort(reject, signal); + function onAbort() { + if (settled) return; + settled = true; + state.aborted = true; + PromisePrototypeThen(kResolvedPromise, closeAndReject); + } + // Added first, as the signal can abort while the source is read. signal.addEventListener('abort', onAbort, kNullOnceOption); - if (signal.aborted) { - onAbort(); + let consumed; + try { + consumed = consume(iterator); + } catch (error) { + consumed = PromiseReject(error); } - - return SafePromisePrototypeFinally(SafePromiseRace([next, promise]), () => { + PromisePrototypeThen(consumed, (value) => { + if (settled) return; + settled = true; + signal.removeEventListener('abort', onAbort); + resolve(value); + }, (error) => { + if (settled) return; + settled = true; signal.removeEventListener('abort', onAbort); + reject(error); }); + return promise; } /** @@ -150,39 +305,211 @@ function yieldAbortable(source, signal) { return { __proto__: null, - async *[SymbolAsyncIterator]() { - const iterator = source[SymbolAsyncIterator](); - let completed = false; - let aborted = false; + [SymbolAsyncIterator]() { + return createAbortableIterator(source, signal); + }, + }; +} +/** + * Iterator reading `source` until `signal` aborts, for yieldAbortable(). + * + * This is what an async generator looping over the source with + * abortableNext() would do, written out by hand: that costs an abort + * listener, a promise race and an async generator layer for every value. + * Instead, a single abort listener is added for the whole iteration, held + * weakly so that the signal does not keep the iterator alive, and each + * next() waits with a single promise that an abort rejects. As with the + * generator: + * - the source is opened by the first next(), unless the signal has aborted + * by then, and calls made while one is in progress are queued; + * - an abort before or while reading a value, or once it has been read, + * rejects with the abort reason; + * - unless the source has ended, an error (including an abort) closes it: + * if the signal is aborted, without waiting, otherwise waiting and + * rejecting with an error from closing it instead; + * - return() closes the source, propagating errors from closing it. + * @param {AsyncIterable} source + * @param {AbortSignal} signal + * @returns {AsyncIterator} + */ +function createAbortableIterator(source, signal) { + let state = kStart; + let iterator; + let completed = false; + // The settling functions of the pending next(), if any. + let resolveNext = null; + let rejectNext = null; + const operations = createOperationQueue(); + + const self = ObjectSetPrototypeOf({ + next() { return operations.run(doNext); }, + return(value) { return operations.run(doReturn, value); }, + throw(error) { return operations.run(doThrow, error); }, + [SymbolAsyncIterator]() { return this; }, + }, null); + + function onAbort() { + if (rejectNext === null) return; + const reject = rejectNext; + resolveNext = rejectNext = null; + fail(reject, signal.reason); + } + + // What the generator did in its `catch` and `finally` blocks for `error`. + function fail(reject, error) { + state = kDone; + signal.removeEventListener('abort', onAbort); + const aborted = signal.aborted; + if (!completed && typeof iterator.return === 'function') { + let closed; try { - while (true) { - const { done, value } = await abortableNext(iterator, signal); - if (done) { - completed = true; - return; - } - signal.throwIfAborted(); - yield value; + const result = iterator.return(); + if (aborted) { + // PromiseResolve(result) can reject if result is a thenable that + // rejects, so mark it as handled even though the abort takes + // precedence over the result of iterator.return(). + markPromiseAsHandled(PromiseResolve(result)); + } else { + closed = PromiseResolve(result); } + } catch (closeError) { + operations.settled(); + reject(closeError); + return; + } + if (closed !== undefined) { + PromisePrototypeThen(closed, () => { + operations.settled(); + reject(error); + }, (closeError) => { + operations.settled(); + reject(closeError); + }); + return; + } + } + operations.settled(); + reject(error); + } + + function onResult(result) { + if (resolveNext === null) return; // Settled by an abort. + const resolve = resolveNext; + const reject = rejectNext; + resolveNext = rejectNext = null; + let done; + let value; + try { + ({ done, value } = result); + if (!done) signal.throwIfAborted(); + } catch (error) { + fail(reject, error); + return; + } + if (done) { + completed = true; + state = kDone; + signal.removeEventListener('abort', onAbort); + operations.settled(); + resolve(new IterResult(true, undefined)); + return; + } + operations.settled(); + resolve(new IterResult(false, value)); + } + + function onError(error) { + if (rejectNext === null) return; // Settled by an abort. + const reject = rejectNext; + resolveNext = rejectNext = null; + fail(reject, error); + } + + function doNext() { + if (state === kDone) { + operations.settled(); + return PromiseResolve(new IterResult(true, undefined)); + } + if (state === kStart) { + // An abort before the first read ends the iteration without opening + // the source. + if (signal.aborted) { + state = kDone; + operations.settled(); + return PromiseReject(signal.reason); + } + try { + iterator = source[SymbolAsyncIterator](); } catch (error) { - aborted = signal.aborted; - throw error; - } finally { - if (!completed && typeof iterator.return === 'function') { - const result = iterator.return(); - if (aborted) { - // PromiseResolve(result) can reject if result is a thenable that - // rejects, so mark it as handled even though the abort takes - // precedence over the result of iterator.return(). - markPromiseAsHandled(PromiseResolve(result)); - } else { - await result; - } - } + state = kDone; + operations.settled(); + return PromiseReject(error); } - }, - }; + state = kActive; + signal.addEventListener('abort', onAbort, + { __proto__: null, [kWeakHandler]: self }); + } + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); + let next; + try { + signal.throwIfAborted(); + next = PromiseResolve(iterator.next()); + } catch (error) { + fail(reject, error); + return promise; + } + resolveNext = resolve; + rejectNext = reject; + PromisePrototypeThen(next, onResult, onError); + // The signal can abort while iterator.next() runs. + if (signal.aborted) onAbort(); + return promise; + } + + function doReturn(value) { + const result = new IterResult(true, value); + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseResolve(result); + } + state = kDone; + signal.removeEventListener('abort', onAbort); + if (typeof iterator.return !== 'function') { + operations.settled(); + return PromiseResolve(result); + } + let closed; + try { + closed = PromiseResolve(iterator.return()); + } catch (error) { + operations.settled(); + return PromiseReject(error); + } + return PromisePrototypeThen(closed, () => { + operations.settled(); + return result; + }, (error) => { + operations.settled(); + throw error; + }); + } + + function doThrow(error) { + if (state !== kActive) { + state = kDone; + operations.settled(); + return PromiseReject(error); + } + const { promise, reject } = PromiseWithResolvers(); + fail(reject, error); + return promise; + } + + return self; } /** @@ -192,6 +519,11 @@ function yieldAbortable(source, signal) { * @param {number} fallback - Cursor to return when set is empty * @returns {{ minCursor: number, minCursorConsumers: number }} */ +// The result of getMinCursor(), reused: it runs whenever the slowest +// consumer of a share or broadcast advances, which can be once per batch, +// and its callers read the result at once. +const minCursorResult = { __proto__: null, minCursor: 0, minCursorConsumers: 0 }; + function getMinCursor(consumers, fallback) { let minCursor = fallback; let minCursorConsumers = 0; @@ -203,7 +535,9 @@ function getMinCursor(consumers, fallback) { minCursorConsumers++; } } - return { __proto__: null, minCursor, minCursorConsumers }; + minCursorResult.minCursor = minCursor; + minCursorResult.minCursorConsumers = minCursorConsumers; + return minCursorResult; } /** @@ -214,7 +548,7 @@ function getMinCursor(consumers, fallback) { */ function toUint8Array(chunk) { if (typeof chunk === 'string') { - return encoder.encode(chunk); + return encodeString(chunk); } if (!isUint8Array(chunk)) { throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Uint8Array'], chunk); @@ -222,23 +556,22 @@ function toUint8Array(chunk) { return chunk; } -// Byte view snapshots and batch entries are created for every chunk and -// every batch, so like IterResult they are constructed rather than created -// as `{ __proto__: null, ... }` literals (which are dictionary-mode objects), +// Byte views are accepted with their byteLength, and rejected when used if +// it has changed: if they were detached (byteLength 0), resized with a +// length-tracking view, or shrunk out of bounds. What was accounted for a +// view is then what is there. The byteLength is read from the view alone, +// without its buffer: reading the buffer of a small typed array that V8 +// keeps on the heap moves its contents to a new ArrayBuffer. +// +// Byte views and batch entries are created for every chunk and every batch, +// so like IterResult they are constructed rather than created as +// `{ __proto__: null, ... }` literals (which are dictionary-mode objects), // and their prototype is an empty null-prototype object. -function ByteViewSnapshot(value, buffer, sharedBufferView) { +function FixedByteView(value, byteLength) { this.value = value; - this.buffer = buffer; - this.bufferByteLength = sharedBufferView === undefined ? - ArrayBufferPrototypeGetByteLength(buffer) : - TypedArrayPrototypeGetByteLength(sharedBufferView); - this.byteLength = TypedArrayPrototypeGetByteLength(value); - this.byteOffset = TypedArrayPrototypeGetByteOffset(value); - this.detached = sharedBufferView === undefined && - ArrayBufferPrototypeGetDetached(buffer); - this.sharedBufferView = sharedBufferView; -} -ByteViewSnapshot.prototype = ObjectFreeze({ __proto__: null }); + this.byteLength = byteLength; +} +FixedByteView.prototype = ObjectFreeze({ __proto__: null }); function BatchEntry(views, byteLength) { this.views = views; @@ -262,39 +595,103 @@ function PendingWrite(batch, resolve, reject) { PendingWrite.prototype = ObjectFreeze({ __proto__: null }); function snapshotByteView(value) { - const buffer = TypedArrayPrototypeGetBuffer(value); - const sharedBufferView = isSharedArrayBuffer(buffer) ? - new Uint8Array(buffer) : undefined; - return new ByteViewSnapshot(value, buffer, sharedBufferView); + return new FixedByteView(value, TypedArrayPrototypeGetByteLength(value)); +} + +function throwByteViewChanged() { + throw new ERR_INVALID_STATE.TypeError( + 'Byte view was resized or detached after being accepted'); } function validateByteView(snapshot) { - const { - value, - buffer, - bufferByteLength, - byteLength, - byteOffset, - detached, - sharedBufferView, - } = snapshot; - const currentBufferByteLength = sharedBufferView === undefined ? - ArrayBufferPrototypeGetByteLength(buffer) : - TypedArrayPrototypeGetByteLength(sharedBufferView); - const currentDetached = sharedBufferView === undefined && - ArrayBufferPrototypeGetDetached(buffer); - - if (TypedArrayPrototypeGetBuffer(value) !== buffer || - currentBufferByteLength !== bufferByteLength || - TypedArrayPrototypeGetByteLength(value) !== byteLength || - TypedArrayPrototypeGetByteOffset(value) !== byteOffset || - currentDetached !== detached) { - throw new ERR_INVALID_STATE.TypeError( - 'Byte view was resized or detached after being accepted'); + const { value } = snapshot; + if (TypedArrayPrototypeGetByteLength(value) !== snapshot.byteLength) { + throwByteViewChanged(); } return value; } +/** + * Call `method` on `receiver` with the byte view `value`, and throw if the + * call resized or detached it, as validateByteView() does for a snapshot + * taken just before the call, without allocating one. + * @param {Uint8Array} value + * @param {Function} method + * @param {object} receiver + * @returns {any} The result of the call. + */ +function callWithByteView(value, method, receiver) { + const byteLength = TypedArrayPrototypeGetByteLength(value); + const result = FunctionPrototypeCall(method, receiver, value); + if (TypedArrayPrototypeGetByteLength(value) !== byteLength) { + throwByteViewChanged(); + } + return result; +} + +// States of the hand-written async iterators that replace async generators +// on hot paths. +const kStart = 0; +const kActive = 1; +const kDone = 2; + +class QueuedOperation { + constructor(method, arg, resolve, reject) { + this.method = method; + this.arg = arg; + this.resolve = resolve; + this.reject = reject; + } +} + +/** + * Serializes the operations of a hand-written async iterator the way an + * async generator queues its requests: an operation started while another + * is in progress waits until it has settled. + * @returns {{ run: Function, settled: Function, idle: Function }} + */ +function createOperationQueue() { + let busy = false; + // Created on first use, then kept: queued operations, a RingBuffer of + // QueuedOperation, since as many can be queued as calls are made. + let queue = null; + + function drain() { + if (busy || queue === null || queue.length === 0) return; + const { method, arg, resolve, reject } = queue.shift(); + busy = true; + PromisePrototypeThen(method(arg), resolve, reject); + } + + return { + __proto__: null, + // Run `method(arg)`, which returns a promise and must call settled() + // once its result is known, now or after the operations before it. + run(method, arg) { + if (busy || (queue !== null && queue.length !== 0)) { + const promise = newPendingPromise(); + const resolve = takeResolve(); + const reject = takeReject(); + queue ??= new RingBuffer(); + queue.push(new QueuedOperation(method, arg, resolve, reject)); + return promise; + } + busy = true; + return method(arg); + }, + settled() { + busy = false; + if (queue !== null && queue.length !== 0) { + PromisePrototypeThen(kResolvedPromise, drain); + } + }, + // Whether no operation is running or queued. + idle() { + return !busy && (queue === null || queue.length === 0); + }, + }; +} + /** * Validate an explicit `budget` option. The spec only requires the default * budget to be at least 16384 bytes; any positive explicit budget is valid. @@ -305,50 +702,82 @@ function validateBudget(budget) { } /** - * Append a chunk to `chunks` for later concatenation, and the information - * needed to detect that it was resized or detached in the meantime to - * `checks`. This provides the same guarantee as snapshotByteView() and - * validateByteView() without allocating a snapshot for every chunk in the - * common case: a non-empty view of a fixed-length, non-shared ArrayBuffer can - * only change by the buffer being detached, which makes its byteLength 0, so - * its byteLength is all that needs to be recorded. + * Append a chunk to `chunks` for later concatenation, and its byteLength to + * `byteLengths`, to detect that it was resized or detached in the meantime + * as validateByteView() does, without an object for every chunk. * @param {Uint8Array[]} chunks - * @param {Array<number|object>} checks + * @param {number[]} byteLengths * @param {Uint8Array} value * @returns {number} The byteLength of `value`. */ -function recordChunk(chunks, checks, value) { - const buffer = TypedArrayPrototypeGetBuffer(value); +function recordChunk(chunks, byteLengths, value) { const byteLength = TypedArrayPrototypeGetByteLength(value); - ArrayPrototypePush(chunks, value); - if (byteLength === 0 || isSharedArrayBuffer(buffer) || - ArrayBufferPrototypeGetResizable(buffer)) { - ArrayPrototypePush(checks, snapshotByteView(value)); - } else { - ArrayPrototypePush(checks, byteLength); - } + chunks[chunks.length] = value; + byteLengths[byteLengths.length] = byteLength; return byteLength; } /** * Validate chunks recorded with recordChunk(). * @param {Uint8Array[]} chunks - * @param {Array<number|object>} checks + * @param {number[]} byteLengths * @returns {Uint8Array[]} `chunks` */ -function validateRecordedChunks(chunks, checks) { +function validateRecordedChunks(chunks, byteLengths) { for (let i = 0; i < chunks.length; i++) { - const check = checks[i]; - if (typeof check !== 'number') { - validateByteView(check); - } else if (TypedArrayPrototypeGetByteLength(chunks[i]) !== check) { - throw new ERR_INVALID_STATE.TypeError( - 'Byte view was resized or detached after being accepted'); + if (TypedArrayPrototypeGetByteLength(chunks[i]) !== byteLengths[i]) { + throwByteViewChanged(); } } return chunks; } +// A batch accepted for writing one chunk at a time: its chunks, and their +// byteLengths when accepted (see snapshotFixedBatch()). +function FixedBatch(chunks, byteLengths, byteLength) { + this.chunks = chunks; + this.byteLengths = byteLengths; + this.byteLength = byteLength; +} +FixedBatch.prototype = ObjectFreeze({ __proto__: null }); + +/** + * Snapshot a batch of Uint8Arrays like createBatchEntry(), without an object + * for every chunk: their byteLengths are recorded in an array. Check a chunk + * with checkFixedBatchChunk() before and after using it. + * @param {Uint8Array[]} chunks + * @returns {FixedBatch} + */ +function snapshotFixedBatch(chunks) { + const count = chunks.length; + const byteLengths = new Array(count); + let byteLength = 0; + for (let i = 0; i < count; i++) { + const length = TypedArrayPrototypeGetByteLength(chunks[i]); + byteLengths[i] = length; + byteLength += length; + } + return new FixedBatch(ArrayPrototypeSlice(chunks), byteLengths, byteLength); +} + +function checkFixedBatchChunk(batch, index) { + const chunk = batch.chunks[index]; + if (TypedArrayPrototypeGetByteLength(chunk) !== batch.byteLengths[index]) { + throwByteViewChanged(); + } + return chunk; +} + +// The batch entry of a FixedBatch, to continue writing it asynchronously. +function fixedBatchToEntry(batch) { + const { chunks, byteLengths } = batch; + const views = new Array(chunks.length); + for (let i = 0; i < chunks.length; i++) { + views[i] = new FixedByteView(chunks[i], byteLengths[i]); + } + return new BatchEntry(views, batch.byteLength); +} + function createBatchEntry(chunks) { const views = new Array(chunks.length); let byteLength = 0; @@ -360,6 +789,17 @@ function createBatchEntry(chunks) { return new BatchEntry(views, byteLength); } +// The entry a buffer (push(), broadcast(), share()) keeps for a written or +// read batch: for a single chunk, its FixedByteView, which has the +// byteLength a BatchEntry has, rather than a BatchEntry and an array of +// views. A batch of one chunk is the common case. The two are told apart +// by `views`, which a FixedByteView lacks; validateBatchEntry() and +// splitBatchEntry() take either. +function createEntry(chunks) { + if (chunks.length === 1) return snapshotByteView(chunks[0]); + return createBatchEntry(chunks); +} + /** * Split a batch entry into consecutive entries that are each smaller than * `limit` bytes, preserving chunk order. A single chunk of `limit` bytes or @@ -370,28 +810,32 @@ function createBatchEntry(chunks) { */ function splitBatchEntry(entry, limit) { const { views } = entry; - if (entry.byteLength < limit || views.length < 2) return undefined; + if (entry.byteLength < limit || views === undefined || views.length < 2) { + return undefined; + } const entries = []; let current = []; let byteLength = 0; for (let i = 0; i < views.length; i++) { const view = views[i]; if (current.length > 0 && byteLength + view.byteLength >= limit) { - ArrayPrototypePush(entries, new BatchEntry(current, byteLength)); + entries[entries.length] = new BatchEntry(current, byteLength); current = []; byteLength = 0; } - ArrayPrototypePush(current, view); + current[current.length] = view; byteLength += view.byteLength; } - ArrayPrototypePush(entries, new BatchEntry(current, byteLength)); + entries[entries.length] = new BatchEntry(current, byteLength); return entries; } function validateBatchEntry(entry) { - const chunks = new Array(entry.views.length); - for (let i = 0; i < entry.views.length; i++) { - chunks[i] = validateByteView(entry.views[i]); + const views = entry.views; + if (views === undefined) return [validateByteView(entry)]; + const chunks = new Array(views.length); + for (let i = 0; i < views.length; i++) { + chunks[i] = validateByteView(views[i]); } return chunks; } @@ -473,6 +917,9 @@ function convertChunks(chunks) { * @returns {AbortSignal|undefined} */ function getWriterSignal(options) { + // Writes are hot, and converting undefined or null creates an empty + // dictionary, which has no signal. + if (options === undefined || options === null) return undefined; return converters.WriteOptions(options, kWriteOptionsContext).signal; } @@ -596,15 +1043,29 @@ function validateBackpressure(value) { module.exports = { IterResult, + kActive, + kDone, + kStart, PendingRequest, PendingWrite, + PipelineAbort, kMultiConsumerDefaultBudget, kNullOnceOption, kPushDefaultBudget, kResolvedPromise, + newPendingPromise, + newResolveOnlyPromise, + takeReject, + takeResolve, + callWithByteView, concatBytes, + createOperationQueue, convertChunks, + checkFixedBatchChunk, createBatchEntry, + createEntry, + fixedBatchToEntry, + snapshotFixedBatch, recordChunk, splitBatchEntry, getProtocolMethod, @@ -615,6 +1076,7 @@ module.exports = { isTransformObject, onSignalAbort, parsePullArgs, + raceSignal, snapshotTransform, toUint8Array, toWriterUint8Array, @@ -622,6 +1084,8 @@ module.exports = { validateBatchEntry, validateBudget, validateRecordedChunks, + throwByteViewChanged, validateByteView, + snapshotByteView, yieldAbortable, }; diff --git a/lib/internal/streams/iter/writer.js b/lib/internal/streams/iter/writer.js new file mode 100644 index 000000000000..575e476b7052 --- /dev/null +++ b/lib/internal/streams/iter/writer.js @@ -0,0 +1,366 @@ +'use strict'; + +// TODO(@jasnell) Temporarily ignoring c8 coverage for this file while tests +// are still being developed. +/* c8 ignore start */ + +const { + PromisePrototypeThen, + PromiseResolve, + PromiseWithResolvers, + SymbolAsyncDispose, + SymbolDispose, + TypedArrayPrototypeGetByteLength, +} = primordials; + +const { + drainableProtocol, +} = require('internal/streams/iter/types'); + +const { + convertChunks, + getWriterSignal, + toWriterUint8Array, +} = require('internal/streams/iter/utils'); + +const { + markPromiseAsHandled, +} = internalBinding('util'); + +const { kEmptyObject } = require('internal/util'); + +const { + codes: { + ERR_INVALID_STATE, + }, +} = require('internal/errors'); + +function getWriter(obj) { + const { + setDrainCallback, + setStopSendingCallback, + writeDesiredSize, + writeEnded, + writeChunks, + resetStream, + endWrite, + nonWritableStream, + initStreamingSource, + } = obj; + // TODO, if this is not an internal function, + // the input should be checked for types + let closed = false; + let ending = false; + let errored = false; + let error = null; + let totalBytesWritten = 0; + let drainWakeup = null; + let pendingWrite = null; + let pendingEnd = null; + + function raceWithSignal(promise, signal) { + if (signal === undefined) return promise; + signal.throwIfAborted(); + + const deferred = PromiseWithResolvers(); + const onAbort = () => deferred.reject(signal.reason); + signal.addEventListener('abort', onAbort, { + __proto__: null, + once: true, + }); + PromisePrototypeThen( + promise, + (value) => { + signal.removeEventListener('abort', onAbort); + deferred.resolve(value); + }, + (reason) => { + signal.removeEventListener('abort', onAbort); + deferred.reject(reason); + }); + return deferred.promise; + } + + function waitForDrain(signal) { + drainWakeup ??= PromiseWithResolvers(); + return raceWithSignal(drainWakeup.promise, signal); + } + + // Drain callback - The implementation C++/js fires this when send buffer has space + setDrainCallback(() => { + if (drainWakeup) { + drainWakeup.resolve(true); + drainWakeup = null; + } + }); + + setStopSendingCallback((reason) => { + if (!closed && !errored) { + errored = true; + error = reason; + if (drainWakeup != null) { + markPromiseAsHandled(drainWakeup.promise); + drainWakeup.reject(error); + drainWakeup = null; + } + } + }); + + // A note on backpressure handling: per the stream/iter spec, the default + // backpressure policy for writers is strict. One async write may wait for + // capacity; additional writes are rejected until it settles. + + function writeConvertedSync(chunk, token) { + const isPending = pendingWrite === token && token !== undefined; + // If the stream is closed, errored, or write-ended, we cannot accept + // more data. Refuse the sync write. + if (closed || errored || writeEnded() || + (ending && !isPending) || + (pendingWrite !== null && !isPending)) { + return false; + } + const len = TypedArrayPrototypeGetByteLength(chunk); + if (len === 0) return true; + // Refuse the write only when there is no available capacity at + // all. If we can write we allow the write even if the + // chunk is larger than the remaining capacity -- the source + // will accept the data into the underlying queues e.g. DataQueue and + // UpdateWriteDesiredSize() will drop writeDesiredSize toward 0, + // at which point the standard drain mechanism takes over. + // This follows the iter-streams model where writes beyond the + // budget succeed and backpressure applies to *subsequent* writes. + if (writeDesiredSize() === 0) return false; + const result = writeChunks([chunk]); + if (result === undefined) return false; + totalBytesWritten += len; + return true; + } + + function writeSync(chunk) { + return writeConvertedSync(toWriterUint8Array(chunk)); + } + + function write(chunk, options = kEmptyObject) { + chunk = toWriterUint8Array(chunk); + const signal = getWriterSignal(options); + return writeAsync(chunk, signal); + } + + async function writeAsync(chunk, signal) { + if (errored) throw error; + if (closed || ending || writeEnded()) { + throw new ERR_INVALID_STATE.TypeError('Writer is closed'); + } + signal?.throwIfAborted(); + + if (writeConvertedSync(chunk)) return; + await writeWhenDrained(chunk, writeConvertedSync, signal); + } + + async function writeWhenDrained(chunks, writeConverted, signal) { + if (pendingWrite !== null) { + throw new ERR_INVALID_STATE.RangeError( + 'Backpressure violation: too many pending writes. ' + + 'Await each write() call to respect backpressure.'); + } + if (writeDesiredSize() !== 0) { + throw new ERR_INVALID_STATE('Stream write buffer is full'); + } + + const done = PromiseWithResolvers(); + const token = { __proto__: null, done }; + pendingWrite = token; + try { + while (true) { + await waitForDrain(signal); + if (errored) throw error; + if (closed || writeEnded()) { + throw new ERR_INVALID_STATE.TypeError('Writer is closed'); + } + signal?.throwIfAborted(); + if (writeConverted(chunks, token)) return; + if (writeDesiredSize() !== 0) { + throw new ERR_INVALID_STATE('Stream write buffer is full'); + } + } + } finally { + if (pendingWrite === token) pendingWrite = null; + done.resolve(); + } + } + + function writevConvertedSync(chunks, token) { + const isPending = pendingWrite === token && token !== undefined; + if (closed || errored || writeEnded() || + (ending && !isPending) || + (pendingWrite !== null && !isPending)) { + return false; + } + let len = 0; + for (const c of chunks) len += TypedArrayPrototypeGetByteLength(c); + if (len === 0) return true; + if (writeDesiredSize() === 0) return false; + const result = writeChunks(chunks); + if (result === undefined) return false; + totalBytesWritten += len; + return true; + } + + function writevSync(chunks) { + return writevConvertedSync(convertChunks(chunks)); + } + + function writev(chunks, options = kEmptyObject) { + chunks = convertChunks(chunks); + const signal = getWriterSignal(options); + return writevAsync(chunks, signal); + } + + async function writevAsync(chunks, signal) { + if (errored) throw error; + if (closed || ending || writeEnded()) { + throw new ERR_INVALID_STATE.TypeError('Writer is closed'); + } + signal?.throwIfAborted(); + + if (writevConvertedSync(chunks)) return; + await writeWhenDrained(chunks, writevConvertedSync, signal); + } + + function endSync() { + // Per the streams/iter spec, endSync and end follow a try-fallback + // pattern. That is, callers should try endSync first and if it returns + // -1, then they should call and await end(). This is a signal that sync + // end is not currently possible. However, we always support sync end + // here unless the stream is already errored. + if (errored) return -1; + + // If we're already closed, just return the total bytes written. + if (closed) return totalBytesWritten; + + // Accepted writes and existing drain waiters must settle before ending. + if (ending || pendingWrite !== null || drainWakeup !== null) return -1; + + // Fantastic, we can end synchronously! + endWrite(); + closed = true; + return totalBytesWritten; + } + + function end(options = kEmptyObject) { + const signal = getWriterSignal(options); + return endAsync(signal); + } + + async function endAsync(signal) { + if (errored) throw error; + if (closed) return totalBytesWritten; + signal?.throwIfAborted(); + + // Per the streams/iter spec, endSync and end follow a try-fallback + // pattern. That is, callers should try endSync first and if it returns + // -1, then they should call and await end(). This is a signal that sync + // end is not currently possible. However, we always support sync end + // here unless the stream is already errored. + // While the user should have already called endSync, we call it again + // here to actually process the end request. At worst it's called twice. + const n = endSync(); + + // A return value of -1 indicates that endSync was not yet able to + // process the end request, either because we are errored or because we + // are awaiting drain. If we're errored, throw the error. If we're waiting + // for drain, await it and then try ending again. + + if (n >= 0) return n; + if (errored) throw error; + + if (pendingEnd === null) { + ending = true; + pendingEnd = finishEnd(); + } + return raceWithSignal(pendingEnd, signal); + } + + async function finishEnd() { + if (pendingWrite !== null) { + await pendingWrite.done.promise; + } + if (errored) throw error; + + if (drainWakeup !== null) { + await drainWakeup.promise; + } + if (errored) throw error; + + if (!writeEnded()) endWrite(); + closed = true; + ending = false; + return totalBytesWritten; + } + + function fail(reason) { + if (closed || errored) return; + errored = true; + error = reason; + resetStream(error); + if (drainWakeup != null) { + markPromiseAsHandled(drainWakeup.promise); + drainWakeup.reject(error); + drainWakeup = null; + } + } + + const writer = { + __proto__: null, + get canWrite() { + if (closed || ending || errored || writeEnded()) { + return null; + } + return writeDesiredSize() > 0; + }, + writeSync, + write, + writevSync, + writev, + endSync, + end, + fail, + [drainableProtocol]() { + if (closed || ending || errored) return null; + // If a drain is already pending, return the existing promise. + if (drainWakeup != null) return drainWakeup.promise; + if (writeDesiredSize() > 0) return null; + drainWakeup = PromiseWithResolvers(); + return drainWakeup.promise; + }, + [SymbolAsyncDispose]() { + if (ending) return pendingEnd; + if (!closed && !errored) fail(); + return PromiseResolve(); + }, + [SymbolDispose]() { + if (!closed && !errored) fail(); + }, + }; + + // Non-writable stream - return a pre-closed writer. + // A remote unidirectional stream is read-only and has no writable + // side. isLocal distinguishes locally-initiated (writable) from + // remotely-initiated (read-only) uni streams. + if (nonWritableStream() || writeEnded()) { + closed = true; + return writer; + } + + // Initialize the outbound DataQueue for streaming writes + initStreamingSource(); + return writer; +} + +// ============================================================================ + +module.exports = { + getWriter, +}; + +/* c8 ignore stop */ diff --git a/lib/internal/streams/operators.js b/lib/internal/streams/operators.js index 87b82b65b56b..1cd4d7aa8951 100644 --- a/lib/internal/streams/operators.js +++ b/lib/internal/streams/operators.js @@ -153,6 +153,10 @@ function map(fn, options) { pump(); try { + if (signal.aborted) { + throw new AbortError(); + } + while (true) { while (queue.length > 0) { const val = await queue[0]; @@ -293,6 +297,13 @@ async function toArray(options) { validateAbortSignal(options.signal, 'options.signal'); } + if (options?.signal?.aborted) { + const err = new AbortError(undefined, { cause: options.signal.reason }); + this.once('error', () => {}); // The error is already propagated + await finished(this.destroy(err)); + throw err; + } + const result = []; for await (const val of this) { if (options?.signal?.aborted) { diff --git a/lib/internal/streams/readable.js b/lib/internal/streams/readable.js index 9bd7ea636919..d01e2f2e3866 100644 --- a/lib/internal/streams/readable.js +++ b/lib/internal/streams/readable.js @@ -337,7 +337,10 @@ function ReadableState(options, stream, isDuplex) { ReadableState.prototype[kOnConstructed] = function onConstructed(stream) { if ((this[kState] & kNeedReadable) !== 0) { - maybeReadMore(stream, this); + if (this.highWaterMark === 0) + process.nextTick(nReadingNextTick, stream); + else + maybeReadMore(stream, this); } }; diff --git a/lib/internal/streams/state.js b/lib/internal/streams/state.js index 46e0ff9c9553..c68dba2a4d88 100644 --- a/lib/internal/streams/state.js +++ b/lib/internal/streams/state.js @@ -11,6 +11,7 @@ const { ERR_INVALID_ARG_VALUE } = require('internal/errors').codes; // TODO (fix): For some reason Windows CI fails with bigger hwm. let defaultHighWaterMarkBytes = process.platform === 'win32' ? 16 * 1024 : 64 * 1024; let defaultHighWaterMarkObjectMode = 16; +let defaultHighWaterMarkBytesSet = false; function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : @@ -27,9 +28,14 @@ function setDefaultHighWaterMark(objectMode, value) { defaultHighWaterMarkObjectMode = value; } else { defaultHighWaterMarkBytes = value; + defaultHighWaterMarkBytesSet = true; } } +function getUserDefaultHighWaterMark() { + return defaultHighWaterMarkBytesSet ? defaultHighWaterMarkBytes : undefined; +} + function getHighWaterMark(state, options, duplexKey, isDuplex) { const hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { @@ -47,5 +53,6 @@ function getHighWaterMark(state, options, duplexKey, isDuplex) { module.exports = { getHighWaterMark, getDefaultHighWaterMark, + getUserDefaultHighWaterMark, setDefaultHighWaterMark, }; diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js index f8c61f819615..3f62489c0f70 100644 --- a/lib/internal/streams/writable.js +++ b/lib/internal/streams/writable.js @@ -503,14 +503,16 @@ function _write(stream, chunk, encoding, cb) { return writeOrBuffer(stream, state, chunk, encoding, cb); } -Writable.prototype.write = function(chunk, encoding, cb) { +function write(chunk, encoding, cb) { if (encoding != null && typeof encoding === 'function') { cb = encoding; encoding = null; } return _write(this, chunk, encoding, cb) === true; -}; +} + +Writable.prototype.write = write; Writable.prototype.cork = function() { const state = this._writableState; @@ -587,8 +589,10 @@ function writeOrBuffer(stream, state, chunk, encoding, callback) { } // Steady state of a flowing pipe into a byte-mode Writable: one Buffer, -// nothing queued, and no user write callback. Returns undefined when the -// caller must use write() instead. Otherwise the same boolean as write(). +// nothing queued, no user write callback, and write() not replaced. pipe() +// calls dest.write(), so a write() set on the instance, a subclass or the +// prototype has to run. Returns undefined when the caller must use write() +// instead. Otherwise the same boolean as write(). const kWriteFlowBlock = kObjectMode | kDestroyed | kErrored | kSync | kEnding | kFinished | kWriting | kCorked | kBuffered | kEnded | kNeedDrain | kWriteCb | kExpectWriteCb | kBufferProcessing | @@ -596,7 +600,8 @@ const kWriteFlowBlock = kObjectMode | kDestroyed | kErrored | kSync | function writeKnownBuffer(stream, chunk) { const state = stream._writableState; - if (state == null || state.length !== 0 || !(chunk instanceof Buffer)) + if (state == null || state.length !== 0 || !(chunk instanceof Buffer) || + stream.write !== write) return undefined; const bits = state[kState]; diff --git a/lib/internal/test_runner/coverage.js b/lib/internal/test_runner/coverage.js index 3d0fcde700a4..fdfd4d4cdd26 100644 --- a/lib/internal/test_runner/coverage.js +++ b/lib/internal/test_runner/coverage.js @@ -31,7 +31,7 @@ const { isWindows, setupCoverageHooks } = require('internal/util'); const { tmpdir } = require('os'); const { join, resolve, relative } = require('path'); const { fileURLToPath, pathToFileURL, URL } = require('internal/url'); -const { kMappings, SourceMap } = require('internal/source_map/source_map'); +const { kFirstEntry, SourceMap } = require('internal/source_map/source_map'); const { codes: { ERR_OPERATION_FAILED, @@ -521,7 +521,7 @@ class TestCoverage { if (!startEntry.originalSource && endEntry.originalSource && lines[0].line === 1 && startOffset === 0 && lines[0].startOffset === 0) { // Edge case when the first line is not mappable - const { 2: originalSource, 3: originalLine, 4: originalColumn } = sourceMap[kMappings][0]; + const { originalSource, originalLine, originalColumn } = sourceMap[kFirstEntry]; startEntry = { __proto__: null, originalSource, originalLine, originalColumn }; } diff --git a/lib/internal/test_runner/harness.js b/lib/internal/test_runner/harness.js index 53f6771a0912..b143ac28dfdb 100644 --- a/lib/internal/test_runner/harness.js +++ b/lib/internal/test_runner/harness.js @@ -68,6 +68,7 @@ function createTestTree(rootTestOptions, globalOptions) { teardown: null, snapshotManager: null, previousRuns: null, + rerunEntryFile: null, isFilteringByName, isFilteringByOnly, isFilteringByTags, @@ -219,6 +220,10 @@ function setupFailureStateFile(rootTest, globalOptions) { if (!process.env.NODE_TEST_CONTEXT) { const reporter = reportReruns(rootTest.harness.previousRuns, globalOptions); compose(rootTest.reporter, reporter).pipe(new PassThrough()); + } else { + // The state is written by the parent process, which scopes the tests of a + // child process running a single file to that file. + rootTest.harness.rerunEntryFile = rootTest.entryFile; } } diff --git a/lib/internal/test_runner/mock/loader.js b/lib/internal/test_runner/mock/loader.js index d64ffdfa0965..266525c8d52a 100644 --- a/lib/internal/test_runner/mock/loader.js +++ b/lib/internal/test_runner/mock/loader.js @@ -60,12 +60,11 @@ function load(url, context, nextLoad) { // Treat builtins as commonjs because customization hooks do not allow a // core module to be replaced. - // Also collapse 'commonjs-sync' and 'require-commonjs' to 'commonjs'. + // Also collapse 'commonjs-sync' to 'commonjs'. let format = original.format; switch (original.format) { case 'builtin': // Deliberate fallthrough - case 'commonjs-sync': // Deliberate fallthrough - case 'require-commonjs': + case 'commonjs-sync': format = 'commonjs'; break; case 'json': diff --git a/lib/internal/test_runner/reporter/junit.js b/lib/internal/test_runner/reporter/junit.js index e5a3fa961eac..940fd92a72e6 100644 --- a/lib/internal/test_runner/reporter/junit.js +++ b/lib/internal/test_runner/reporter/junit.js @@ -16,21 +16,34 @@ const { } = primordials; const { inspectWithNoCustomRetry } = require('internal/errors'); +const { kEmptyObject } = require('internal/util'); +const { stripVTControlCharacters } = require('internal/util/inspect'); const { hostname } = require('os'); -const inspectOptions = { __proto__: null, colors: false, breakLength: Infinity }; +const inspectOptions = { __proto__: kEmptyObject, colors: false, breakLength: Infinity }; const HOSTNAME = hostname(); +// Characters that are not allowed anywhere in an XML 1.0 document, not even +// as character references: C0 controls other than tab, LF and CR, lone +// surrogates, and U+FFFE/U+FFFF. +const kInvalidXMLChars = /[^\t\n\r\x20-\uD7FF\uE000-\uFFFD\u{10000}-\u{10FFFF}]/gu; + +function sanitize(s = '') { + // Drop ANSI escape sequences entirely (e.g. colored assertion diffs), then + // replace any remaining illegal characters with U+FFFD. + return RegExpPrototypeSymbolReplace(kInvalidXMLChars, stripVTControlCharacters(s), '\uFFFD'); +} + function escapeAttribute(s = '') { return RegExpPrototypeSymbolReplace(/"/g, RegExpPrototypeSymbolReplace(/\n/g, escapeContent(s), ' '), '"'); } function escapeContent(s = '') { - return RegExpPrototypeSymbolReplace(/</g, RegExpPrototypeSymbolReplace(/(&)(?!#\d{1,7};)/g, s, '&'), '<'); + return RegExpPrototypeSymbolReplace(/</g, RegExpPrototypeSymbolReplace(/&/g, sanitize(s), '&'), '<'); } function escapeComment(s = '') { - return RegExpPrototypeSymbolReplace(/--/g, s, '--'); + return RegExpPrototypeSymbolReplace(/--/g, sanitize(s), '--'); } function treeToXML(tree) { @@ -64,17 +77,56 @@ function isSkipped(node) { return (node?.children && ArrayPrototypeSome(node.children, (c) => c.tag === 'skipped')) || node?.attrs?.skipped; } +function setSuiteAttrs(node, tests) { + node.tag = 'testsuite'; + node.attrs.disabled = 0; + node.attrs.errors = 0; + node.attrs.tests = tests; + node.attrs.failures = ArrayPrototypeFilter(node.children, isFailure).length; + node.attrs.skipped = ArrayPrototypeFilter(node.children, isSkipped).length; +} + +// Give a test that started but never reported a result (e.g. because a test +// child process exited before all of its output was read) a valid element. +// A leaf is reported as a failure so that lost results don't look green. +function closeIncomplete(node) { + const tests = ArrayPrototypeFilter(node.children, (c) => c.comment == null).length; + if (tests > 0) { + setSuiteAttrs(node, tests); + node.attrs.hostname = HOSTNAME; + return; + } + const message = 'test did not report a result'; + node.tag = 'testcase'; + node.attrs.classname = 'test'; + node.attrs.failure = message; + ArrayPrototypePush(node.children, { + __proto__: kEmptyObject, nesting: node.nesting + 1, tag: 'failure', + attrs: { __proto__: kEmptyObject, type: 'incomplete', message }, + }); +} + module.exports = async function* junitReporter(source) { yield '<?xml version="1.0" encoding="utf-8"?>\n'; yield '<testsuites>\n'; let currentSuite = null; const roots = []; + // Close any unfinished tests nested at `nesting` or deeper, so that later + // results are not attached to a test whose own result never arrived. + function closeUnfinished(nesting) { + while (currentSuite != null && currentSuite.nesting >= nesting) { + closeIncomplete(currentSuite); + currentSuite = currentSuite.parent; + } + } + function startTest(event) { + closeUnfinished(event.data.nesting); const originalSuite = currentSuite; currentSuite = { - __proto__: null, - attrs: { __proto__: null, name: event.data.name }, + __proto__: kEmptyObject, + attrs: { __proto__: kEmptyObject, name: event.data.name }, nesting: event.data.nesting, parent: currentSuite, children: [], @@ -95,11 +147,11 @@ module.exports = async function* junitReporter(source) { } case 'test:pass': case 'test:fail': { - if (!currentSuite) { - startTest({ __proto__: null, data: { __proto__: null, name: 'root', nesting: 0 } }); - } - if (currentSuite.attrs.name !== event.data.name || + closeUnfinished(event.data.nesting + 1); + if (currentSuite == null || + currentSuite.attrs.name !== event.data.name || currentSuite.nesting !== event.data.nesting) { + // No matching test:start was seen; start the test now. startTest(event); } const currentTest = currentSuite; @@ -109,12 +161,7 @@ module.exports = async function* junitReporter(source) { currentTest.attrs.time = NumberPrototypeToFixed(event.data.details.duration_ms / 1000, 6); const nonCommentChildren = ArrayPrototypeFilter(currentTest.children, (c) => c.comment == null); if (nonCommentChildren.length > 0) { - currentTest.tag = 'testsuite'; - currentTest.attrs.disabled = 0; - currentTest.attrs.errors = 0; - currentTest.attrs.tests = nonCommentChildren.length; - currentTest.attrs.failures = ArrayPrototypeFilter(currentTest.children, isFailure).length; - currentTest.attrs.skipped = ArrayPrototypeFilter(currentTest.children, isSkipped).length; + setSuiteAttrs(currentTest, nonCommentChildren.length); // A suite's `test:start` is emitted lazily (when its first subtest // reports), so derive the start time from the end minus the measured // duration rather than stamping the (late) test:start moment. @@ -129,27 +176,30 @@ module.exports = async function* junitReporter(source) { } if (event.data.skip) { ArrayPrototypePush(currentTest.children, { - __proto__: null, nesting: event.data.nesting + 1, tag: 'skipped', - attrs: { __proto__: null, type: 'skipped', message: event.data.skip }, + __proto__: kEmptyObject, nesting: event.data.nesting + 1, tag: 'skipped', + attrs: { __proto__: kEmptyObject, type: 'skipped', message: event.data.skip }, }); } if (event.data.todo) { ArrayPrototypePush(currentTest.children, { - __proto__: null, nesting: event.data.nesting + 1, tag: 'skipped', - attrs: { __proto__: null, type: 'todo', message: event.data.todo }, + __proto__: kEmptyObject, nesting: event.data.nesting + 1, tag: 'skipped', + attrs: { __proto__: kEmptyObject, type: 'todo', message: event.data.todo }, }); } if (event.type === 'test:fail') { const error = event.data.details?.error; currentTest.children.push({ - __proto__: null, + __proto__: kEmptyObject, nesting: event.data.nesting + 1, tag: 'failure', - attrs: { __proto__: null, type: error?.failureType || error?.code, message: error?.message.trim() ?? '' }, + attrs: { + __proto__: kEmptyObject, + type: error?.failureType || error?.code, + message: error?.message.trim() ?? '', + }, children: [inspectWithNoCustomRetry(error, inspectOptions)], }); currentTest.failures = 1; - currentTest.attrs.failure = error?.message ?? ''; } } break; @@ -158,13 +208,14 @@ module.exports = async function* junitReporter(source) { case 'test:log': { const parent = currentSuite?.children ?? roots; ArrayPrototypePush(parent, { - __proto__: null, nesting: event.data.nesting, comment: event.data.message, + __proto__: kEmptyObject, nesting: event.data.nesting, comment: event.data.message, }); break; } default: break; } } + closeUnfinished(0); for (const suite of roots) { yield treeToXML(suite); } diff --git a/lib/internal/test_runner/reporter/rerun.js b/lib/internal/test_runner/reporter/rerun.js index ba2a1fe39141..fcb497a04ce0 100644 --- a/lib/internal/test_runner/reporter/rerun.js +++ b/lib/internal/test_runner/reporter/rerun.js @@ -5,8 +5,8 @@ const { ArrayPrototypePush, JSONStringify, } = primordials; -const { relative } = require('path'); const { writeFileSync } = require('fs'); +const { getRerunTestId } = require('internal/test_runner/utils'); function reportReruns(previousRuns, globalOptions) { return async function reporter(source) { @@ -16,7 +16,7 @@ function reportReruns(previousRuns, globalOptions) { const roots = []; function getTestId(data) { - return `${relative(globalOptions.cwd, data.file)}:${data.line}:${data.column}`; + return getRerunTestId(globalOptions.cwd, data, data.entryFile); } function startTest(data) { diff --git a/lib/internal/test_runner/runner.js b/lib/internal/test_runner/runner.js index b37198df6d76..09c820eb9116 100644 --- a/lib/internal/test_runner/runner.js +++ b/lib/internal/test_runner/runner.js @@ -19,7 +19,7 @@ const { PromiseWithResolvers, RegExpPrototypeSymbolReplace, SafeMap, - SafePromiseAll, + SafePromiseAllReturnArrayLike, SafePromiseAllReturnVoid, SafePromiseAllSettledReturnVoid, SafeSet, @@ -305,7 +305,7 @@ class FileTest extends Test { __proto__: null, line: 1, column: 1, - file: resolve(this.name), + file: resolve(this.config.cwd, this.name), }; this.timeout = null; } @@ -624,7 +624,7 @@ function runTestFile(path, filesWatcher, opts) { }); }); - const { 0: { 0: code, 1: signal } } = await SafePromiseAll([ + const { 0: { 0: code, 1: signal } } = await SafePromiseAllReturnArrayLike([ once(child, 'exit', { __proto__: null, signal: t.signal }), finished(child.stdout, { __proto__: null, signal: t.signal }), ]); diff --git a/lib/internal/test_runner/test.js b/lib/internal/test_runner/test.js index 1b0956e4253c..ee13ac907e4f 100644 --- a/lib/internal/test_runner/test.js +++ b/lib/internal/test_runner/test.js @@ -29,7 +29,6 @@ const { ReflectApply, RegExpPrototypeExec, SafeMap, - SafePromiseAll, SafePromiseAllReturnVoid, SafePromiseRace, SafeSet, @@ -70,6 +69,7 @@ const { createDeferredCallback, createSeededGenerator, countCompletedTest, + getRerunTestId, isTestFailureError, reporterScope, testChannel, @@ -97,7 +97,6 @@ const { } = require('timers'); const { TIMEOUT_MAX } = require('internal/timers'); const { fileURLToPath } = require('internal/url'); -const { relative } = require('path'); const { availableParallelism } = require('os'); const { innerOk } = require('internal/assert/utils'); const { bigint: hrtime } = process.hrtime; @@ -536,6 +535,15 @@ class SuiteContext { return this.#suite.attempt ?? 0; } + get tags() { + return this.#suite.tags; + } + + get workerId() { + const envWorkerId = process.env.NODE_TEST_WORKER_ID; + return Number(envWorkerId) || undefined; + } + diagnostic(message) { this.#suite.diagnostic(message); } @@ -828,7 +836,7 @@ class Test extends AsyncResource { } if (this.loc != null && this.root.harness.previousRuns != null) { - const baseIdentifier = `${relative(this.config.cwd, this.loc.file)}:${this.loc.line}:${this.loc.column}`; + const baseIdentifier = getRerunTestId(this.config.cwd, this.loc, this.root.harness.rerunEntryFile); let testIdentifier = baseIdentifier; const disambiguator = this.root.testDisambiguator.get(baseIdentifier); if (disambiguator !== undefined) { @@ -1525,6 +1533,8 @@ class Test extends AsyncResource { destination.on('unpipe', () => { if (!destination.closed && typeof destination.close === 'function') { destination.close(resolve); + } else if (destination.writableLength > 0) { + destination.write('', resolve); } else { resolve(); } @@ -1945,7 +1955,7 @@ class Suite extends Test { stopPromise = stopTest(this.timeout, this.signal); const subtests = this.skipped || this.error ? [] : this.subtests; - const promise = SafePromiseAll(subtests, (subtests) => subtests.start()); + const promise = SafePromiseAllReturnVoid(subtests, (subtests) => subtests.start()); await SafePromiseRace([promise, stopPromise]); await after(); diff --git a/lib/internal/test_runner/utils.js b/lib/internal/test_runner/utils.js index 4f3728fe0926..1624a357b4ac 100644 --- a/lib/internal/test_runner/utils.js +++ b/lib/internal/test_runner/utils.js @@ -197,6 +197,16 @@ function parsePreviousRuns(rerunFailuresFilePath) { return JSONParse(data); } +// A location outside of the entry file is shared by every test file that +// reaches it, so it is scoped to the entry file when there is one. +function getRerunTestId(cwd, { file, line, column }, entryFile) { + const id = `${relative(cwd, file)}:${line}:${column}`; + if (entryFile == null || entryFile === file) { + return id; + } + return `${relative(cwd, entryFile)}::${id}`; +} + async function getReportersMap(reporters, destinations) { return SafePromiseAllReturnArrayLike(reporters, async (name, i) => { const destination = kBuiltinDestinations.get(destinations[i]) ?? @@ -741,6 +751,7 @@ module.exports = { testStorage, shouldColorizeTestFiles, getCoverageReport, + getRerunTestId, setupGlobalSetupTeardownFunctions, parsePreviousRuns, testChannel, diff --git a/lib/internal/tls/secure-context.js b/lib/internal/tls/secure-context.js index 7c427cfbeb0a..a4336c98026c 100644 --- a/lib/internal/tls/secure-context.js +++ b/lib/internal/tls/secure-context.js @@ -328,7 +328,8 @@ function configSecureContext(context, options = kEmptyObject, name = 'options') if (sessionTimeout !== undefined && sessionTimeout !== null) { validateInt32(sessionTimeout, `${name}.sessionTimeout`, 0); - context.setSessionTimeout(sessionTimeout); + // Coerce -0 to +0, which the binding does not treat as an Int32. + context.setSessionTimeout(sessionTimeout | 0); } } diff --git a/lib/internal/tls/wrap.js b/lib/internal/tls/wrap.js index 4e295d9f8ca5..cb55387f9b7d 100644 --- a/lib/internal/tls/wrap.js +++ b/lib/internal/tls/wrap.js @@ -34,6 +34,8 @@ const { const { assertCrypto, + getDeprecationWarningEmitter, + isPendingDeprecation, kEmptyObject, } = require('internal/util'); @@ -101,10 +103,20 @@ const { const { InternalX509Certificate, } = require('internal/crypto/x509'); +const emitRenegotiationDeprecation = getDeprecationWarningEmitter( + 'DEP0213', + 'TLS renegotiation is deprecated and will be disabled by default. Only ' + + "clients setting allowRenegotiation to accept a server's request will " + + 'remain supported.', + undefined, + false, + isPendingDeprecation, +); const traceTls = getOptionValue('--trace-tls'); const tlsKeylog = getOptionValue('--tls-keylog'); const { appendFile } = require('fs'); const kConnectOptions = Symbol('connect-options'); +const kAllowRenegotiation = Symbol('allowRenegotiation'); const kDisableRenegotiation = Symbol('disable-renegotiation'); const kErrorEmitted = Symbol('error-emitted'); const kHandshakeTimeout = Symbol('handshake-timeout'); @@ -175,6 +187,9 @@ function getSessionForReuse(session, options) { if (options?.isServer) return session; + if (!Buffer.isBuffer(session) && isArrayBufferView(session)) + session = Buffer.from(session.buffer, session.byteOffset, session.byteLength); + const wrappedSession = unwrapSessionState(session); if (wrappedSession !== undefined) { const servername = getSessionServerIdentity(options); @@ -231,6 +246,15 @@ function onhandshakestart(now) { owner._emitTLSError(new ERR_TLS_RENEGOTIATION_DISABLED()); } +function validateAllowRenegotiation(allowRenegotiation, isServer) { + if (allowRenegotiation === undefined) + return; + validateBoolean(allowRenegotiation, 'options.allowRenegotiation'); + // BoringSSL servers always refuse renegotiation. + if (allowRenegotiation && isServer && isBoringSSL) + throw new ERR_TLS_RENEGOTIATION_UNSUPPORTED(); +} + function onhandshakedone() { debug('server onhandshakedone'); @@ -382,6 +406,12 @@ function requestOCSP(socket, info) { let ctx = socket._handle.sni_context; + // A context selected by the SNI callback may not have a certificate, for + // example when it only provides the CAs. The handshake then uses the + // default certificate, so report that one. + if (ctx && !(ctx.context ?? ctx).getCertificate()) + ctx = undefined; + if (!ctx) { ctx = socket.server._sharedCreds; @@ -467,6 +497,9 @@ function onnewsession(sessionId, session) { return; once = true; + if (owner.destroyed) + return; + if (owner._handle === null) return owner.destroy(new ERR_SOCKET_CLOSED()); @@ -601,8 +634,10 @@ function onerror(err) { // Ignore server's authorization errors owner.destroy(); } else { - // Emit error - owner._emitTLSError(err); + // A failed TLS connection cannot make progress on pending writes. + // Preserve connection details until the error has been handled. + owner._closeAfterHandlingError = true; + owner.destroy(err); } } @@ -652,6 +687,9 @@ function TLSSocket(socket, opts) { if (tlsOptions.ALPNProtocols) tls.convertALPNProtocols(tlsOptions.ALPNProtocols, tlsOptions); + validateAllowRenegotiation(tlsOptions.allowRenegotiation, + tlsOptions.isServer); + this._tlsOptions = tlsOptions; this._secureEstablished = false; this._securePending = false; @@ -748,7 +786,7 @@ exports.TLSSocket = TLSSocket; const proxiedMethods = [ 'ref', 'unref', 'hasRef', 'open', 'bind', 'listen', 'connect', 'bind6', 'connect6', 'getsockname', 'getpeername', 'setNoDelay', 'setKeepAlive', - 'setSimultaneousAccepts', 'setBlocking', + 'setSimultaneousAccepts', 'setBlocking', 'hasPendingRead', // PipeWrap 'setPendingInstances', @@ -974,6 +1012,9 @@ TLSSocket.prototype._init = function(socket, wrap) { if (requestCert || rejectUnauthorized) ssl.setVerifyMode(requestCert, rejectUnauthorized); + if (options.allowRenegotiation === false) + ssl.disableRenegotiation(); + // Only call .onkeylog if there is a keylog listener. ssl.onkeylog = onkeylog; @@ -1111,6 +1152,8 @@ TLSSocket.prototype.renegotiate = function(options, callback) { validateFunction(callback, 'callback'); } + emitRenegotiationDeprecation(); + debug('%s renegotiate()', this._tlsOptions.isServer ? 'server' : 'client', 'destroyed?', this.destroyed, @@ -1119,6 +1162,13 @@ TLSSocket.prototype.renegotiate = function(options, callback) { if (this.destroyed) return; + if (this._tlsOptions.allowRenegotiation === false) { + if (callback) { + process.nextTick(callback, new ERR_TLS_RENEGOTIATION_DISABLED()); + } + return false; + } + let requestCert = !!this._requestCert; let rejectUnauthorized = !!this._rejectUnauthorized; @@ -1225,6 +1275,13 @@ TLSSocket.prototype._finishInit = function() { 'alpn', this.alpnProtocol, 'servername', this.servername); + // A second completed handshake is a renegotiation. + if (this._secureEstablished && + (this._tlsOptions.isServer || + this._tlsOptions.allowRenegotiation !== true)) { + emitRenegotiationDeprecation(); + } + this._secureEstablished = true; if (this._tlsOptions.handshakeTimeout > 0) this.setTimeout(0, this._handleTimeout); @@ -1409,6 +1466,7 @@ function tlsConnectionListener(rawSocket) { ALPNCallback: this.ALPNCallback, SNICallback: this[kSNICallback] || SNICallback, enableTrace: this[kEnableTrace], + allowRenegotiation: this[kAllowRenegotiation], pauseOnConnect: this.pauseOnConnect, pskCallback: this[kPskCallback], pskIdentityHint: this[kPskIdentityHint], @@ -1529,6 +1587,9 @@ function Server(options, listener) { validateNumber(this[kHandshakeTimeout], 'options.handshakeTimeout'); + validateAllowRenegotiation(options.allowRenegotiation, true); + this[kAllowRenegotiation] = options.allowRenegotiation; + if (this[kSNICallback]) { validateFunction(this[kSNICallback], 'options.SNICallback'); } @@ -1898,6 +1959,7 @@ exports.connect = function connect(...args) { ALPNProtocols: options.ALPNProtocols, requestOCSP: options.requestOCSP, enableTrace: options.enableTrace, + allowRenegotiation: options.allowRenegotiation, pskCallback: options.pskCallback, highWaterMark: options.highWaterMark, onread: options.onread, diff --git a/lib/internal/url.js b/lib/internal/url.js index 0fe819fe129c..1c4f45a4ea92 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -1022,8 +1022,9 @@ class URL { } set href(value) { + const context = this.#context; value = `${value}`; - const href = bindingUrl.update(this.#context.href, updateActions.kHref, value); + const href = bindingUrl.update(context.href, updateActions.kHref, value); if (!href) { throw new ERR_INVALID_URL(value); } this.#updateContext(href, true); } @@ -1365,13 +1366,18 @@ function parseParams(qs) { const out = []; // Native indexOf/slice/push outperform primordials on this tight loop. const encoded = qs.indexOf('+', i) !== -1 || qs.indexOf('%', i) !== -1; + // The next '=' at or after `i`, kept across pairs so that a run of pairs + // with no '=' does not rescan the rest of the string for each pair. + let eq = -2; while (i < len) { let amp = qs.indexOf('&', i); if (amp === -1) { amp = len; } if (amp !== i) { - const eq = qs.indexOf('=', i); + if (eq !== -1 && eq < i) { + eq = qs.indexOf('=', i); + } if (eq === -1 || eq > amp) { out.push(encoded ? decodeFormComponent(qs, i, amp) : qs.slice(i, amp), ''); } else { @@ -1474,8 +1480,13 @@ function urlToHttpOptions(url) { validateObject(url, 'url', kValidateObjectAllowObjects); const { hostname, pathname, port, username, password, search } = url; const options = { - __proto__: null, - ...url, // In case the url object was extended by the user. + __proto__: kEmptyObject, + // Only spread own enumerable properties for genuine WHATWG URL instances so + // that a URL object can still be extended with additional request options + // (e.g. `url.headers = ...`). Arbitrary duck-typed objects accepted by + // `isURL()` must not be able to smuggle transport/connection options (e.g. + // `socketPath`) into a request and bypass hostname-based SSRF defenses. + ...(isURLInstance(url) ? url : undefined), protocol: url.protocol, hostname: hostname && hostname[0] === '[' ? StringPrototypeSlice(hostname, 1, -1) : diff --git a/lib/internal/util.js b/lib/internal/util.js index 2f72e636ab90..57da765aac71 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -50,6 +50,7 @@ const { const { codes: { + ERR_INVALID_FD, ERR_NO_CRYPTO, ERR_NO_TYPESCRIPT, ERR_UNKNOWN_SIGNAL, @@ -700,7 +701,11 @@ const kEnumerableProperty = ObjectFreeze({ enumerable: true, }); -const kEmptyObject = ObjectFreeze({ __proto__: null }); +// A `{ __proto__: null }` literal always starts in dictionary mode in V8 and +// stays there, which makes every property lookup on it (e.g. reading an option +// off the default `options = kEmptyObject`) a hash table probe. Null the +// prototype of a plain literal instead so the object keeps a fast map. +const kEmptyObject = ObjectFreeze(ObjectSetPrototypeOf({}, null)); /** * Mimics `obj[key] = value` but ignoring potential prototype inheritance. @@ -857,7 +862,12 @@ function getCIDR(address, netmask, family) { } const handleTypes = ['TCP', 'TTY', 'UDP', 'FILE', 'PIPE', 'UNKNOWN']; + function guessHandleType(fd) { + if (typeof fd !== 'number' || fd >> 0 !== fd || fd < 0) { + throw new ERR_INVALID_FD(fd); + } + const type = _guessHandleType(fd); return handleTypes[type]; } diff --git a/lib/internal/util/debounce.js b/lib/internal/util/debounce.js index 3038dfeb83fe..ad6ca24f2b47 100644 --- a/lib/internal/util/debounce.js +++ b/lib/internal/util/debounce.js @@ -2,10 +2,10 @@ const { ArrayPrototypePush, - ObjectDefineProperties, PromiseReject, PromiseWithResolvers, ReflectApply, + SymbolDispose, } = primordials; const { @@ -19,6 +19,10 @@ const { validateObject, } = require('internal/validators'); const { addAbortListener } = require('internal/events/abort_listener'); +const { + createAbortError, + defineWrapperProperties, +} = require('internal/util/wrapped_function'); const { kEmptyObject } = require('internal/util'); const { TIMEOUT_MAX } = require('internal/timers'); const { clearTimeout, setTimeout } = require('timers'); @@ -60,6 +64,7 @@ function debounce(fn, wait, options = kEmptyObject) { let args; let abortError; + let abortListener; let pendingCalls = []; let refed = true; let timeout; @@ -76,27 +81,36 @@ function debounce(fn, wait, options = kEmptyObject) { if (timeout === undefined) return; clearTimeout(timeout); timeout = undefined; + stopListeningForAbort(); args = undefined; rejectPending(error); } function cancel(reason) { if (timeout === undefined) return; - const error = reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: reason }); - cancelWithError(error); + cancelWithError(createAbortError(reason)); } function abort() { if (abortError === undefined) { - abortError = signal.reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: signal.reason }); + abortError = createAbortError(signal.reason); } cancelWithError(abortError); } + function listenForAbort() { + if (signal !== undefined && abortListener === undefined) { + abortListener = addAbortListener(signal, abort); + } + } + + function stopListeningForAbort() { + if (abortListener !== undefined) { + abortListener[SymbolDispose](); + abortListener = undefined; + } + } + function ref() { refed = true; timeout?.ref(); @@ -143,6 +157,7 @@ function debounce(fn, wait, options = kEmptyObject) { function onTimeout() { timeout = undefined; + stopListeningForAbort(); invokePending(); } @@ -151,6 +166,7 @@ function debounce(fn, wait, options = kEmptyObject) { clearTimeout(timeout); timeout = undefined; + stopListeningForAbort(); invokePending(); } @@ -170,6 +186,7 @@ function debounce(fn, wait, options = kEmptyObject) { } else { timeout = setTimeout(onTimeout, wait); if (!refed) timeout.unref(); + listenForAbort(); } if (signal?.aborted) { @@ -187,50 +204,20 @@ function debounce(fn, wait, options = kEmptyObject) { return call.promise; } - function createFn(value) { - return { - __proto__: null, - configurable: true, - enumerable: true, - writable: true, - value, - }; - } - - ObjectDefineProperties(debounced, { + defineWrapperProperties(debounced, fn, { __proto__: null, - cancel: createFn(cancel), - flush: createFn(flush), - ref: createFn(ref), - unref: createFn(unref), - pending: { - __proto__: null, - enumerable: false, - get() { - return pendingCalls.length === 0 ? null : pendingCalls[pendingCalls.length - 1].promise; - }, - }, - pendingCount: { - __proto__: null, - enumerable: false, - get() { return pendingCalls.length; }, - }, - length: { - __proto__: null, - configurable: true, - value: fn.length, - }, - name: { - __proto__: null, - configurable: true, - value: fn.name, + cancel, + flush, + ref, + unref, + }, { + __proto__: null, + pending() { + return pendingCalls.length === 0 ? null : pendingCalls[pendingCalls.length - 1].promise; }, + pendingCount() { return pendingCalls.length; }, }); - if (signal !== undefined) { - addAbortListener(signal, abort); - } - return debounced; } diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 7ee103196585..3128d5e50301 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -1173,17 +1173,8 @@ function formatValue(ctx, value, recurseTimes, typedArray) { // Using an array here is actually better for the average case than using // a Set. `seen` will only check for the depth and will never grow too large. if (ctx.seen.includes(value)) { - let index = 1; - if (ctx.circular === undefined) { - ctx.circular = new SafeMap(); - ctx.circular.set(value, index); - } else { - index = ctx.circular.get(value); - if (index === undefined) { - index = ctx.circular.size + 1; - ctx.circular.set(value, index); - } - } + ctx.circular ??= new SafeMap(); + const index = ctx.circular.getOrInsert(value, ctx.circular.size + 1); return ctx.stylize(`[Circular *${index}]`, 'special'); } @@ -1434,14 +1425,12 @@ function formatRaw(ctx, value, recurseTimes, typedArray) { const tempValue = { [extraKeys[i]]: value.buffer[extraKeys[i]] }; formatted = formatExtraProperties(ctx, tempValue, recurseTimes, extraKeys[i], typedArray); } - ArrayPrototypePush(output, formatted); + output[output.length] = formatted; } } for (i = 0; i < keys.length; i++) { - ArrayPrototypePush( - output, - formatProperty(ctx, value, recurseTimes, keys[i], extrasType), - ); + output[output.length] = + formatProperty(ctx, value, recurseTimes, keys[i], extrasType); } if (protoProps !== undefined) { ArrayPrototypePushApply(output, protoProps); @@ -2409,11 +2398,11 @@ function formatSet(value, ctx, ignored, recurseTimes) { let i = 0; for (const v of value) { if (i >= maxLength) break; - ArrayPrototypePush(output, formatValue(ctx, v, recurseTimes)); + output[output.length] = formatValue(ctx, v, recurseTimes); i++; } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + output[output.length] = remainingText(remaining); } ctx.indentationLvl -= 2; return output; @@ -2428,14 +2417,12 @@ function formatMap(value, ctx, ignored, recurseTimes) { let i = 0; for (const { 0: k, 1: v } of value) { if (i >= maxLength) break; - ArrayPrototypePush( - output, - `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`, - ); + output[output.length] = + `${formatValue(ctx, k, recurseTimes)} => ${formatValue(ctx, v, recurseTimes)}`; i++; } if (remaining > 0) { - ArrayPrototypePush(output, remainingText(remaining)); + output[output.length] = remainingText(remaining); } ctx.indentationLvl -= 2; return output; diff --git a/lib/internal/util/throttle.js b/lib/internal/util/throttle.js index bc1b4f01bdea..17eb8cc01860 100644 --- a/lib/internal/util/throttle.js +++ b/lib/internal/util/throttle.js @@ -3,12 +3,12 @@ const { ArrayPrototypePush, ArrayPrototypeSlice, - ObjectDefineProperties, PromisePrototypeThen, PromiseReject, PromiseResolve, PromiseWithResolvers, ReflectApply, + SymbolDispose, } = primordials; const { @@ -26,6 +26,10 @@ const { validateOneOf, } = require('internal/validators'); const { addAbortListener } = require('internal/events/abort_listener'); +const { + createAbortError, + defineWrapperProperties, +} = require('internal/util/wrapped_function'); const { kEmptyObject } = require('internal/util'); const { TIMEOUT_MAX } = require('internal/timers'); const { clearTimeout, setTimeout } = require('timers'); @@ -79,6 +83,7 @@ function throttle(fn, limit, interval, options = kEmptyObject) { } let abortError; + let abortListener; let activeCount = 0; let pendingCalls = []; let pendingIndex = 0; @@ -100,6 +105,7 @@ function throttle(fn, limit, interval, options = kEmptyObject) { if (pendingIndex === pendingCalls.length) { pendingCalls = []; pendingIndex = 0; + stopListeningForAbort(); } else if (pendingIndex > 1024 && pendingIndex * 2 >= pendingCalls.length) { pendingCalls = ArrayPrototypeSlice(pendingCalls, pendingIndex); pendingIndex = 0; @@ -113,6 +119,7 @@ function throttle(fn, limit, interval, options = kEmptyObject) { const start = pendingIndex; pendingCalls = []; pendingIndex = 0; + stopListeningForAbort(); for (let i = start; i < calls.length; i++) { calls[i].reject(error); } @@ -135,21 +142,29 @@ function throttle(fn, limit, interval, options = kEmptyObject) { } function cancel(reason) { - const error = reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: reason }); - cancelWithError(error); + cancelWithError(createAbortError(reason)); } function abort() { if (abortError === undefined) { - abortError = signal.reason === undefined ? - new AbortError() : - new AbortError(undefined, { __proto__: null, cause: signal.reason }); + abortError = createAbortError(signal.reason); } cancelWithError(abortError); } + function listenForAbort() { + if (signal !== undefined && abortListener === undefined) { + abortListener = addAbortListener(signal, abort); + } + } + + function stopListeningForAbort() { + if (abortListener !== undefined) { + abortListener[SymbolDispose](); + abortListener = undefined; + } + } + function ref() { refed = true; timeout?.ref(); @@ -306,64 +321,31 @@ function throttle(fn, limit, interval, options = kEmptyObject) { invoke(call); } else { ArrayPrototypePush(pendingCalls, call); + listenForAbort(); schedule(); } return call.promise; } - function createFn(value) { - return { - __proto__: null, - configurable: true, - enumerable: true, - writable: true, - value, - }; - } - - ObjectDefineProperties(throttled, { + defineWrapperProperties(throttled, fn, { __proto__: null, - cancel: createFn(cancel), - hasImmediateCapacity: createFn(hasImmediateCapacity), - ref: createFn(ref), - unref: createFn(unref), - pending: { - __proto__: null, - enumerable: false, - get() { - return pendingCount() === 0 ? null : - pendingCalls[pendingCalls.length - 1].promise; - }, - }, - pendingCount: { - __proto__: null, - enumerable: false, - get: pendingCount, - }, - activeCount: { - __proto__: null, - enumerable: false, - get() { - return activeCount; - }, - }, - length: { - __proto__: null, - configurable: true, - value: fn.length, + cancel, + hasImmediateCapacity, + ref, + unref, + }, { + __proto__: null, + pending() { + return pendingCount() === 0 ? null : + pendingCalls[pendingCalls.length - 1].promise; }, - name: { - __proto__: null, - configurable: true, - value: fn.name, + pendingCount, + activeCount() { + return activeCount; }, }); - if (signal !== undefined) { - addAbortListener(signal, abort); - } - return throttled; } diff --git a/lib/internal/util/wrapped_function.js b/lib/internal/util/wrapped_function.js new file mode 100644 index 000000000000..27b3c796edea --- /dev/null +++ b/lib/internal/util/wrapped_function.js @@ -0,0 +1,69 @@ +'use strict'; + +// Helpers shared by util.debounce() and util.throttle(). + +const { + ObjectDefineProperties, +} = primordials; + +const { + AbortError, +} = require('internal/errors'); + +/** + * Creates the AbortError used to reject calls that were cancelled or aborted. + * @param {any} reason + * @returns {AbortError} + */ +function createAbortError(reason) { + return reason === undefined ? + new AbortError() : + new AbortError(undefined, { __proto__: null, cause: reason }); +} + +/** + * Defines the control methods, state getters, `length`, and `name` on a + * function returned by util.debounce() or util.throttle(). + * @param {Function} wrapper The function returned to the user. + * @param {Function} fn The wrapped user function. + * @param {{ [name: string]: Function }} methods Enumerable, writable methods. + * @param {{ [name: string]: Function }} getters Non-enumerable getters. + * @returns {Function} `wrapper`. + */ +function defineWrapperProperties(wrapper, fn, methods, getters) { + const descriptors = { + __proto__: null, + length: { + __proto__: null, + configurable: true, + value: fn.length, + }, + name: { + __proto__: null, + configurable: true, + value: fn.name, + }, + }; + for (const name in methods) { + descriptors[name] = { + __proto__: null, + configurable: true, + enumerable: true, + writable: true, + value: methods[name], + }; + } + for (const name in getters) { + descriptors[name] = { + __proto__: null, + enumerable: false, + get: getters[name], + }; + } + return ObjectDefineProperties(wrapper, descriptors); +} + +module.exports = { + createAbortError, + defineWrapperProperties, +}; diff --git a/lib/internal/vfs/providers/real.js b/lib/internal/vfs/providers/real.js index a3a5d6329a93..86046c715905 100644 --- a/lib/internal/vfs/providers/real.js +++ b/lib/internal/vfs/providers/real.js @@ -458,12 +458,16 @@ class RealFSProvider extends VirtualProvider { mkdirSync(vfsPath, options) { const realPath = this.#resolvePath(vfsPath); - return fs.mkdirSync(realPath, options); + const created = fs.mkdirSync(realPath, options); + if (created === undefined) return undefined; + return this.#resolvedToVfsPath(created, vfsPath, 'mkdir'); } async mkdir(vfsPath, options) { const realPath = this.#resolvePath(vfsPath); - return fs.promises.mkdir(realPath, options); + const created = await fs.promises.mkdir(realPath, options); + if (created === undefined) return undefined; + return this.#resolvedToVfsPath(created, vfsPath, 'mkdir'); } rmdirSync(vfsPath) { @@ -566,7 +570,13 @@ class RealFSProvider extends VirtualProvider { // because fs.realpathSync (a JS impl) preserves case but fs.promises.realpath // (native) canonicalizes the drive letter and other components. #resolvedToVfsPath(resolved, vfsPath, syscall) { - const rel = path.relative(this.#rootPath, resolved); + // Both sides are put in the Windows long-path form first, because the + // native bindings answer in it (\\?\C:\dir) and path.relative() reads + // that as a different root than a plain rootPath, which would make every + // comparison look like an escape. A no-op elsewhere, and idempotent, so + // a rootPath already in that form is covered too. + const rel = path.relative(path.toNamespacedPath(this.#rootPath), + path.toNamespacedPath(resolved)); if (rel === '') return '/'; if (rel === '..' || StringPrototypeStartsWith(rel, '..' + path.sep) || diff --git a/lib/internal/vfs/setup.js b/lib/internal/vfs/setup.js index 1ed74f5d566c..2f4e9f31ab89 100644 --- a/lib/internal/vfs/setup.js +++ b/lib/internal/vfs/setup.js @@ -658,12 +658,24 @@ function createVfsHandlers() { return vfd.entry.read(buffer, offset, length, position) .then(({ bytesRead }) => bytesRead); }, + readv(fd, buffers, position) { + const vfd = getVirtualFd(fd); + if (!vfd) return undefined; + return vfd.entry.readv(buffers, position) + .then(({ bytesRead }) => bytesRead); + }, write(fd, buffer, offset, length, position) { const vfd = getVirtualFd(fd); if (!vfd) return undefined; return vfd.entry.write(buffer, offset, length, position) .then(({ bytesWritten }) => bytesWritten); }, + writev(fd, buffers, position) { + const vfd = getVirtualFd(fd); + if (!vfd) return undefined; + return vfd.entry.writev(buffers, position) + .then(({ bytesWritten }) => bytesWritten); + }, fstat(fd, options) { const vfd = getVirtualFd(fd); if (!vfd) return undefined; diff --git a/lib/internal/webstreams/adapters.js b/lib/internal/webstreams/adapters.js index fc5ada12be3c..443bea0386c8 100644 --- a/lib/internal/webstreams/adapters.js +++ b/lib/internal/webstreams/adapters.js @@ -167,6 +167,24 @@ const noop = () => {}; // `failed`/`failure` latch a write that could not proceed. The callback // runs in the async context of the Node.js write that set it, as the // reaction to writer.write() did (see settle()). +/** + * Encodes a string chunk written to a Node.js Writable as a Uint8Array for a + * WritableStream. + * @param {string} chunk + * @param {string} encoding + * @returns {Uint8Array} + */ +function encodeStringChunk(chunk, encoding) { + if (normalizeEncoding(encoding) === 'utf8') + return encoder.encode(chunk); + const buffer = Buffer.from(chunk, encoding); + return new Uint8Array( + TypedArrayPrototypeGetBuffer(buffer), + TypedArrayPrototypeGetByteOffset(buffer), + TypedArrayPrototypeGetByteLength(buffer), + ); +} + function createWriteTracker(getDestination) { return { promise: null, @@ -493,20 +511,8 @@ function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj }, write(chunk, encoding, callback) { - if (typeof chunk === 'string' && decodeStrings && !objectMode) { - const enc = normalizeEncoding(encoding); - - if (enc === 'utf8') { - chunk = encoder.encode(chunk); - } else { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - } + if (typeof chunk === 'string' && decodeStrings && !objectMode) + chunk = encodeStringChunk(chunk, encoding); writeTracker.callback = callback; dispatchWrite(writer, chunk, writeTracker); @@ -948,20 +954,8 @@ function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options = }, write(chunk, encoding, callback) { - if (typeof chunk === 'string' && decodeStrings && !objectMode) { - const enc = normalizeEncoding(encoding); - - if (enc === 'utf8') { - chunk = encoder.encode(chunk); - } else { - chunk = Buffer.from(chunk, encoding); - chunk = new Uint8Array( - TypedArrayPrototypeGetBuffer(chunk), - TypedArrayPrototypeGetByteOffset(chunk), - TypedArrayPrototypeGetByteLength(chunk), - ); - } - } + if (typeof chunk === 'string' && decodeStrings && !objectMode) + chunk = encodeStringChunk(chunk, encoding); writeTracker.callback = callback; dispatchWrite(writer, chunk, writeTracker); diff --git a/lib/internal/webstreams/readablestream.js b/lib/internal/webstreams/readablestream.js index 3181355959b6..7e083286cf12 100644 --- a/lib/internal/webstreams/readablestream.js +++ b/lib/internal/webstreams/readablestream.js @@ -20,7 +20,7 @@ const { PromiseReject, PromiseResolve, PromiseWithResolvers, - SafePromiseAll, + SafePromiseAllReturnVoid, Symbol, SymbolAsyncIterator, SymbolDispose, @@ -49,6 +49,14 @@ const { const AsyncContextFrame = require('internal/async_context_frame'); +// The pipe checks the async context frame on every pump step; the +// intrinsics reduce to a field access in optimized code, which the +// AsyncContextFrame wrappers would put behind another inlining level. +const { + getContinuationPreservedEmbedderData: currentContextFrame, + setContinuationPreservedEmbedderData: setContextFrame, +} = internalBinding('async_context_frame'); + const { isArrayBufferView, isDataView, @@ -112,7 +120,6 @@ const { extractHighWaterMark, extractSizeAlgorithm, getNonWritablePropertyDescriptor, - isBrandCheck, kDeferredStart, kEmptyQueue, kParkedAlgorithmResult, @@ -1385,18 +1392,44 @@ function createReadableByteStream(start, pull, cancel) { return stream; } -const isReadableStream = - isBrandCheck('ReadableStream'); -const isReadableByteStreamController = - isBrandCheck('ReadableByteStreamController'); -const isReadableStreamDefaultController = - isBrandCheck('ReadableStreamDefaultController'); -const isReadableStreamBYOBRequest = - isBrandCheck('ReadableStreamBYOBRequest'); -const isReadableStreamDefaultReader = - isBrandCheck('ReadableStreamDefaultReader'); -const isReadableStreamBYOBReader = - isBrandCheck('ReadableStreamBYOBReader'); +// Separate functions rather than closures from one factory: closures of +// the same function literal share their feedback, which made these loads +// megamorphic across all the stream classes. +function isReadableStream(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'ReadableStream'; +} + +function isReadableByteStreamController(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'ReadableByteStreamController'; +} + +function isReadableStreamDefaultController(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'ReadableStreamDefaultController'; +} + +function isReadableStreamBYOBRequest(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'ReadableStreamBYOBRequest'; +} + +function isReadableStreamDefaultReader(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'ReadableStreamDefaultReader'; +} + +function isReadableStreamBYOBReader(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'ReadableStreamBYOBReader'; +} // ---- ReadableStream Implementation @@ -1753,7 +1786,7 @@ function readableStreamPipeTo( } shutdownWithAnAction( - () => SafePromiseAll(actions, (action) => action()), + () => SafePromiseAllReturnVoid(actions, (action) => action()), true, error); } @@ -1766,6 +1799,20 @@ function readableStreamPipeTo( let readRequest; let readyHook; + // The pump re-enters from the ready hook and from the chunk steps, which + // run in the async context of whoever cleared the backpressure or + // enqueued the chunk. Resume it in the context of the pipeTo() call, as + // the promise-based pump did. + const pipeContextFrame = currentContextFrame(); + function pumpInPipeContext(prior) { + setContextFrame(pipeContextFrame); + try { + pump(); + } finally { + setContextFrame(prior); + } + } + // Ready promise rejection is handled by the destination-errored // watcher. function ignoreReadyRejection() {} @@ -1800,6 +1847,12 @@ function readableStreamPipeTo( function pump() { if (shuttingDown) return; + const contextFrame = currentContextFrame(); + if (contextFrame !== pipeContextFrame) { + pumpInPipeContext(contextFrame); + return; + } + if (dest[kState].backpressure) { parkOnReady(); return; @@ -3860,15 +3913,15 @@ function readableByteStreamControllerFillReadRequestFromQueue(controller, readRe } function readableByteStreamControllerProcessReadRequestsUsingQueue(controller) { - const { - stream, - queueTotalSize, - } = controller[kState]; + const state = controller[kState]; + const { stream } = state; const { reader } = stream[kState]; assert(isReadableStreamDefaultReader(reader)); while (reader[kState].readRequests.length > 0) { - if (queueTotalSize === 0) { + // Filling a read request dequeues a chunk, so re-read the queue size + // on every iteration. + if (state.queueTotalSize === 0) { return; } readableByteStreamControllerFillReadRequestFromQueue( diff --git a/lib/internal/webstreams/transformstream.js b/lib/internal/webstreams/transformstream.js index ba6d51f813f6..e9cf0d9978ed 100644 --- a/lib/internal/webstreams/transformstream.js +++ b/lib/internal/webstreams/transformstream.js @@ -55,7 +55,6 @@ const { extractHighWaterMark, extractSizeAlgorithm, getNonWritablePropertyDescriptor, - isBrandCheck, kParkedAlgorithmResult, kResolvedPromise, kState, @@ -372,10 +371,20 @@ ObjectDefineProperties(TransformStreamDefaultController.prototype, { [SymbolToStringTag]: getNonWritablePropertyDescriptor(TransformStreamDefaultController.name), }); -const isTransformStream = - isBrandCheck('TransformStream'); -const isTransformStreamDefaultController = - isBrandCheck('TransformStreamDefaultController'); +// Separate functions rather than closures from one factory: closures of +// the same function literal share their feedback, which made these loads +// megamorphic across all the stream classes. +function isTransformStream(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'TransformStream'; +} + +function isTransformStreamDefaultController(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'TransformStreamDefaultController'; +} // Raw callback (see createRawCallback*): invoked inside the try/catch of // transformStreamDefaultControllerPerformTransform. @@ -597,11 +606,11 @@ function transformStreamDefaultControllerError(controller, error) { // Mirrors the reference implementation's // `promiseCall(transformAlgorithm, ...).then(undefined, rejectionSteps)`: -// the returned promise settles one microtask after the (coerced) result -// does, and a rejection errors the transform stream before propagating. -// The raw transform callback plus the shared resolved promise for -// non-thenable results replace the previous async wrapper's two implicit -// promises per chunk. +// a rejection errors the transform stream before propagating. A +// non-thenable result cannot reject, so it maps to the shared resolved +// promise without the rejection step; the write then completes one +// microtask earlier than in the reference implementation, with the +// relative order of all stream events unchanged. function transformStreamDefaultControllerPerformTransform(controller, chunk) { const controllerState = controller[kState]; const transformAlgorithm = controllerState.transformAlgorithm; @@ -617,10 +626,9 @@ function transformStreamDefaultControllerPerformTransform(controller, chunk) { } if (result === null || (typeof result !== 'object' && typeof result !== 'function')) { - result = kResolvedPromise; - } else { - result = PromiseResolve(result); + return kResolvedPromise; } + result = PromiseResolve(result); controllerState.performTransformRejected ??= (error) => { transformStreamError(controller[kState].stream, error); throw error; diff --git a/lib/internal/webstreams/util.js b/lib/internal/webstreams/util.js index 2d9ba0ae4038..79a512b05dda 100644 --- a/lib/internal/webstreams/util.js +++ b/lib/internal/webstreams/util.js @@ -138,14 +138,6 @@ function canCopyArrayBuffer(toBuffer, toIndex, fromBuffer, fromIndex, count) { fromIndex + count <= ArrayBufferPrototypeGetByteLength(fromBuffer); } -function isBrandCheck(brand) { - return (value) => { - return value != null && - value[kState] !== undefined && - value[kType] === brand; - }; -} - // Backing store for the spec's [[queue]]: a power-of-two ring buffer // instead of a plain array. Entries are pushed at the tail and consumed // at the head, so a plain array either moves every element or forces the @@ -497,7 +489,6 @@ module.exports = { extractHighWaterMark, extractSizeAlgorithm, getNonWritablePropertyDescriptor, - isBrandCheck, isPromisePending, kDeferredStart, kEmptyQueue, diff --git a/lib/internal/webstreams/writablestream.js b/lib/internal/webstreams/writablestream.js index f332fd19fd0a..1cf10984d3d4 100644 --- a/lib/internal/webstreams/writablestream.js +++ b/lib/internal/webstreams/writablestream.js @@ -63,7 +63,6 @@ const { extractHighWaterMark, extractSizeAlgorithm, getNonWritablePropertyDescriptor, - isBrandCheck, isPromisePending, kDeferredStart, kEmptyQueue, @@ -573,12 +572,26 @@ function createWritableStream(start, write, close, abort, highWaterMark = 1, siz return stream; } -const isWritableStream = - isBrandCheck('WritableStream'); -const isWritableStreamDefaultWriter = - isBrandCheck('WritableStreamDefaultWriter'); -const isWritableStreamDefaultController = - isBrandCheck('WritableStreamDefaultController'); +// Separate functions rather than closures from one factory: closures of +// the same function literal share their feedback, which made these loads +// megamorphic across all the stream classes. +function isWritableStream(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'WritableStream'; +} + +function isWritableStreamDefaultWriter(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'WritableStreamDefaultWriter'; +} + +function isWritableStreamDefaultController(value) { + return value != null && + value[kState] !== undefined && + value[kType] === 'WritableStreamDefaultController'; +} // The state record classes null out their prototype chain to keep // Object.prototype out of property lookups; every field ever assigned diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 728132f779e3..00b0293e85dc 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -44,7 +44,6 @@ const { const workerIo = require('internal/worker/io'); const { drainMessagePort, - receiveMessageOnPort, MessageChannel, messageTypes, kPort, @@ -73,7 +72,6 @@ const { const { ownsProcessState, isMainThread, - isInternalThread, resourceLimits: resourceLimitsRaw, threadId, threadName, @@ -94,7 +92,6 @@ const kOnCouldNotSerializeErr = Symbol('kOnCouldNotSerializeErr'); const kOnErrorMessage = Symbol('kOnErrorMessage'); const kParentSideStdio = Symbol('kParentSideStdio'); const kLoopStartTime = Symbol('kLoopStartTime'); -const kIsInternal = Symbol('kIsInternal'); const kIsOnline = Symbol('kIsOnline'); const kWebWorkerData = Symbol('kWebWorkerData'); @@ -203,13 +200,7 @@ class Worker extends EventEmitter { constructor(filename, options = kEmptyObject) { throwIfBuildingSnapshot('Creating workers'); super(); - const isInternal = arguments[2] === kIsInternal; - debug( - `[${threadId}] create new worker`, - filename, - options, - `isInternal: ${isInternal}`, - ); + debug(`[${threadId}] create new worker`, filename, options); if (options.execArgv) validateArray(options.execArgv, 'options.execArgv'); @@ -220,10 +211,7 @@ class Worker extends EventEmitter { } let url, doEval; - if (isInternal) { - doEval = 'internal'; - url = `node:${filename}`; - } else if (options.eval) { + if (options.eval) { if (typeof filename !== 'string') { throw new ERR_INVALID_ARG_VALUE( 'options.eval', @@ -286,7 +274,6 @@ class Worker extends EventEmitter { options.execArgv, parseResourceLimits(options.resourceLimits), !!(options.trackUnmanagedFds ?? true), - isInternal, name); if (this[kHandle].invalidExecArgv) { throw new ERR_WORKER_INVALID_EXEC_ARGV(this[kHandle].invalidExecArgv); @@ -361,7 +348,6 @@ class Worker extends EventEmitter { type: messageTypes.LOAD_SCRIPT, filename, doEval, - isInternal, cwdCounter: cwdCounter || workerIo.sharedCwdCounter, workerData: options.workerData, webWorkerData: options[kWebWorkerData], @@ -642,20 +628,6 @@ class Worker extends EventEmitter { } } -/** - * A worker which has an internal module for entry point (e.g. internal/module/esm/worker). - * Internal workers bypass the permission model. - */ -class InternalWorker extends Worker { - constructor(filename, options) { - super(filename, options, kIsInternal); - } - - receiveMessageSync() { - return receiveMessageOnPort(this[kPublicPort]); - } -} - function pipeWithoutWarning(source, dest) { const sourceMaxListeners = source._maxListeners; const destMaxListeners = dest._maxListeners; @@ -723,7 +695,6 @@ module.exports = { ownsProcessState, kIsOnline, isMainThread, - isInternalThread, SHARE_ENV, resourceLimits: !isMainThread ? makeResourceLimits(resourceLimitsRaw) : {}, @@ -732,7 +703,6 @@ module.exports = { assignEnvironmentData, threadId, threadName, - InternalWorker, Worker, kPublicPort, kWebWorkerData, diff --git a/lib/internal/worker/messaging.js b/lib/internal/worker/messaging.js index d1573b870ef1..df590efe5379 100644 --- a/lib/internal/worker/messaging.js +++ b/lib/internal/worker/messaging.js @@ -1,6 +1,7 @@ 'use strict'; const { + ArrayFrom, AtomicsNotify, AtomicsStore, AtomicsWaitAsync, @@ -30,6 +31,8 @@ const { MessageChannel } = require('internal/worker/io'); const { validateNumber } = require('internal/validators'); +const registryChannel = require('diagnostics_channel').channel('worker_threads.main.registry'); + const messageTypes = { REGISTER_MAIN_THREAD_PORT: 'registerMainThreadPort', UNREGISTER_MAIN_THREAD_PORT: 'unregisterMainThreadPort', @@ -72,12 +75,26 @@ function handleMessageFromThread(message) { // Never block the thread on this port port.unref(); + + if (registryChannel.hasSubscribers) { + registryChannel.publish({ + __proto__: null, + threadIds: ArrayFrom(threadsPorts.keys()), + }); + } } break; case messageTypes.UNREGISTER_MAIN_THREAD_PORT: threadsPorts.get(message.threadId).close(); threadsPorts.delete(message.threadId); + + if (registryChannel.hasSubscribers) { + registryChannel.publish({ + __proto__: null, + threadIds: ArrayFrom(threadsPorts.keys()), + }); + } break; case messageTypes.SEND_MESSAGE_TO_WORKER: { diff --git a/lib/internal/zip/headers.js b/lib/internal/zip/headers.js index bf6f7901516a..3bcb81f23dd5 100644 --- a/lib/internal/zip/headers.js +++ b/lib/internal/zip/headers.js @@ -6,7 +6,6 @@ // which walks the central directory into an array of headers. const { - ArrayPrototypePush, MathMax, Number, } = primordials; @@ -604,7 +603,7 @@ function readCentralDirectory(buffer, count) { if (header.diskNumber !== 0) { throw new ERR_ZIP_UNSUPPORTED_FEATURE('multi-disk archives are not supported'); } - ArrayPrototypePush(result, header); + result[index] = header; pos += header.byteLength; } if (pos !== buffer.length) { diff --git a/lib/module.js b/lib/module.js index 1217172afb3c..60ba0803dc55 100644 --- a/lib/module.js +++ b/lib/module.js @@ -6,7 +6,6 @@ const { setSourceMapsSupport, } = require('internal/source_map/source_map_cache'); const { Module } = require('internal/modules/cjs/loader'); -const { register } = require('internal/modules/esm/loader'); const { SourceMap, } = require('internal/source_map/source_map'); @@ -21,7 +20,6 @@ const { } = require('internal/modules/package_json_reader'); const { stripTypeScriptTypes } = require('internal/modules/typescript'); -Module.register = register; Module.constants = constants; Module.enableCompileCache = enableCompileCache; Module.findPackageJSON = findPackageJSON; diff --git a/lib/net.js b/lib/net.js index ae7cca8ed6e6..30a89119ace4 100644 --- a/lib/net.js +++ b/lib/net.js @@ -368,12 +368,13 @@ function closeSocketHandle(self, isException, isCleanupPending = false) { if (self._handle) { self._handle.close(() => { debug('emit close'); - self.emit('close', isException); if (isCleanupPending) { + // The handle is closed and must not be used by close listeners. self._handle.onread = noop; self._handle = null; self._sockname = null; } + self.emit('close', isException); }); } } diff --git a/lib/os.js b/lib/os.js index 5e53879bd6d5..612e7171f7af 100644 --- a/lib/os.js +++ b/lib/os.js @@ -40,7 +40,7 @@ const { }, hideStackFrames, } = require('internal/errors'); -const { getCIDR } = require('internal/util'); +const { getCIDR, guessHandleType: guessFileDescriptorType } = require('internal/util'); const { validateInt32 } = require('internal/validators'); const { @@ -260,7 +260,9 @@ function setPriority(pid, priority) { const ctx = {}; - if (_setPriority(pid, priority, ctx) !== 0) + // V8 does not report -0 as an int32, so coerce it to 0 before it reaches + // the binding. + if (_setPriority(pid | 0, priority | 0, ctx) !== 0) throw new ERR_SYSTEM_ERROR(ctx); } @@ -275,7 +277,9 @@ function getPriority(pid) { validateInt32(pid, 'pid'); const ctx = {}; - const priority = _getPriority(pid, ctx); + // V8 does not report -0 as an int32, so coerce it to 0 before it reaches + // the binding. + const priority = _getPriority(pid | 0, ctx); if (priority === undefined) throw new ERR_SYSTEM_ERROR(ctx); @@ -329,6 +333,7 @@ module.exports = { uptime: getUptime, version: getOSVersion, machine: getMachine, + guessFileDescriptorType, }; ObjectFreeze(constants.signals); diff --git a/lib/path.js b/lib/path.js index 658b5d6901df..b371f422b6b3 100644 --- a/lib/path.js +++ b/lib/path.js @@ -50,6 +50,11 @@ const { CHAR_COLON, CHAR_QUESTION_MARK, } = require('internal/constants'); +const { + codes: { + ERR_INVALID_ARG_TYPE, + }, +} = require('internal/errors'); const { validateObject, validateString, @@ -196,7 +201,9 @@ const win32 = { let path; if (i >= 0) { path = args[i]; - validateString(path, `paths[${i}]`); + if (typeof path !== 'string') { + throw new ERR_INVALID_ARG_TYPE(`paths[${i}]`, 'string', path); + } // Skip empty entries if (path.length === 0) { @@ -1254,7 +1261,9 @@ const posix = { for (let i = args.length - 1; i >= 0 && !resolvedAbsolute; i--) { const path = args[i]; - validateString(path, `paths[${i}]`); + if (typeof path !== 'string') { + throw new ERR_INVALID_ARG_TYPE(`paths[${i}]`, 'string', path); + } // Skip empty entries if (path.length === 0) { diff --git a/lib/repl.js b/lib/repl.js index 4c227a0c17da..712f0602a804 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -150,6 +150,8 @@ const { kMultilinePrompt, kAddNewLineOnTTY, kLastCommandErrored, + kFlushPendingRefresh, + kWillDeferRefresh, } = require('internal/readline/interface'); const parentModule = module; @@ -696,6 +698,11 @@ class REPLServer extends Interface { ['key', [d, key], self.isCompletionEnabled]); return; } + // Redraw a line whose refresh was deferred within the current input + // chunk before anything else writes to the terminal. + if (!self[kWillDeferRefresh](d, key)) { + self[kFlushPendingRefresh](); + } if (!self.editorMode || !self.terminal) { // Before exiting, make sure to clear the line. if (key.ctrl && key.name === 'd' && diff --git a/lib/worker_threads.js b/lib/worker_threads.js index 622bef3f55c1..b6a0887784d1 100644 --- a/lib/worker_threads.js +++ b/lib/worker_threads.js @@ -3,7 +3,6 @@ const { defineLazyProperties } = require('internal/util'); const { - isInternalThread, isMainThread, SHARE_ENV, resourceLimits, @@ -33,7 +32,7 @@ const { } = require('internal/buffer'); module.exports = { - isInternalThread, + isInternalThread: false, isMainThread, MessagePort, MessageChannel, diff --git a/node.gyp b/node.gyp index 9c0b270ea5fe..9eb2d6519402 100644 --- a/node.gyp +++ b/node.gyp @@ -492,6 +492,7 @@ 'test/cctest/test_quic_tokens.cc', ], 'node_cctest_inspector_sources': [ + 'test/cctest/inspector/test_main_thread_interface.cc', 'test/cctest/inspector/test_network_requests_buffer.cc', 'test/cctest/inspector/test_node_protocol.cc', 'test/cctest/test_inspector_socket.cc', @@ -560,6 +561,9 @@ 'conditions': [ ['clang==0 and OS!="win"', { 'cflags': [ '-Wno-restrict', ], + 'cflags_cc': [ + '-Wno-invalid-constexpr', + ], }], # TODO(joyeecheung): investigate if it breaks addons. # ['OS=="mac"', { @@ -669,6 +673,12 @@ }, }, }], + ['node_shared=="true" and OS in "aix os400"', { + 'dependencies': ['generate_node_exp'], + 'ldflags': [ + '-Wl,-bE:<(PRODUCT_DIR)/<(node_core_target_name).exp', + ], + }], [ 'node_shared=="false"', { # Keep this whole-archive section in sync with the `node_lib` target below. 'xcode_settings': { @@ -1167,6 +1177,23 @@ 'ldflags': [ '-Wl,-brtl' ], }, }], + ['OS in "aix os400"', { + 'conditions': [ + ['node_use_node_snapshot=="true"', { + 'variables': { + 'expfile_extra_inputs': [ + '<(obj_dir)/<(node_lib_target_name)/gen/node_snapshot.o', + ], + }, + }, { + 'variables': { + 'expfile_extra_inputs': [ + '<(obj_dir)/<(node_lib_target_name)/src/node_snapshot_stub.o', + ], + }, + }], + ], + }], [ 'node_shared=="true" and OS=="win"', { 'sources': [ 'src/res/node.rc', @@ -1714,6 +1741,33 @@ ], # end targets 'conditions': [ + ['OS in "aix os400" and node_shared=="true"', { + 'targets': [ + { + 'target_name': 'generate_node_exp', + 'type': 'none', + 'dependencies': [ + '<(node_lib_target_name)', + ], + 'actions': [ + { + 'action_name': 'generate_node_exp_action', + 'inputs': [ + '<(PRODUCT_DIR)/<(node_lib_target_name).exp', + ], + 'outputs': [ + '<(PRODUCT_DIR)/<(node_core_target_name).exp', + ], + 'action': [ + '<(python)', 'tools/copyfile.py', + '<@(_inputs)', + '<@(_outputs)', + ], + }, + ], + }, + ], + }], ['OS=="win" and node_shared=="true"', { 'targets': [ { diff --git a/node.gypi b/node.gypi index 32e7dca2fd94..a866ba57624e 100644 --- a/node.gypi +++ b/node.gypi @@ -300,20 +300,24 @@ [ 'force_load=="true"', { 'variables': { 'exp_filename': '<(PRODUCT_DIR)/<(_target_name).exp', + 'expfile_extra_inputs%': [], }, 'actions': [ { 'action_name': 'expfile', 'inputs': [ '<(obj_dir)', + '<@(expfile_extra_inputs)', ], 'outputs': [ '<(exp_filename)', ], 'action': [ 'sh', 'tools/create_expfile.sh', - '<@(_inputs)', + '<(obj_dir)', '<@(_outputs)', + '<(_target_name)', + '<@(expfile_extra_inputs)', ], } ], diff --git a/src/api/callback.cc b/src/api/callback.cc index 7f74e011ff65..e9f08f504bb4 100644 --- a/src/api/callback.cc +++ b/src/api/callback.cc @@ -120,8 +120,27 @@ InternalCallbackScope::InternalCallbackScope( prior_context_frame_.Reset(isolate, prior_context_frame); } - env->async_hooks()->push_async_context( - async_context_.async_id, async_context_.trigger_async_id, object); + AsyncHooks* hooks = env->async_hooks(); + if (hooks->fields()[AsyncHooks::kTotals] == 0 && + hooks->fields()[AsyncHooks::kUsesExecutionAsyncResource] == 0) + [[likely]] { + // Nobody can see the id stack: swap the ids in place, they are all that + // executionAsyncId() and triggerAsyncId() read. + AliasedFloat64Array& ids = hooks->async_id_fields(); + prior_async_id_ = ids[AsyncHooks::kExecutionAsyncId]; + prior_trigger_async_id_ = ids[AsyncHooks::kTriggerAsyncId]; + ids[AsyncHooks::kExecutionAsyncId] = async_context_.async_id; + ids[AsyncHooks::kTriggerAsyncId] = async_context_.trigger_async_id; + lazy_depth_ = hooks->fields()[AsyncHooks::kStackLength]; + lazy_resource_ = object; + lazy_prev_ = hooks->lazy_top_; + hooks->lazy_top_ = this; + hooks->fields()[AsyncHooks::kLazyScopes] += 1; + lazy_ids_ = true; + } else { + hooks->push_async_context( + async_context_.async_id, async_context_.trigger_async_id, object); + } pushed_ids_ = true; @@ -132,6 +151,13 @@ InternalCallbackScope::InternalCallbackScope( } } +Local<Object> InternalCallbackScope::lazy_resource(Isolate* isolate) const { + if (std::holds_alternative<Local<Object>*>(lazy_resource_)) { + return *std::get<Local<Object>*>(lazy_resource_); + } + return std::get<Global<Object>*>(lazy_resource_)->Get(isolate); +} + InternalCallbackScope::~InternalCallbackScope() { Close(); env_->PopAsyncCallbackScope(); @@ -162,7 +188,20 @@ void InternalCallbackScope::Close() { } if (pushed_ids_) { - env_->async_hooks()->pop_async_context(async_context_.async_id); + AsyncHooks* hooks = env_->async_hooks(); + if (lazy_ids_) { + // clear_async_id_stack() may have dropped the chain already. + if (hooks->lazy_top_ == this) { + hooks->CheckLazyClose(async_context_.async_id, lazy_depth_); + hooks->lazy_top_ = lazy_prev_; + hooks->fields()[AsyncHooks::kLazyScopes] -= 1; + } + AliasedFloat64Array& ids = hooks->async_id_fields(); + ids[AsyncHooks::kExecutionAsyncId] = prior_async_id_; + ids[AsyncHooks::kTriggerAsyncId] = prior_trigger_async_id_; + } else { + hooks->pop_async_context(async_context_.async_id); + } async_context_frame::set(env_, prior_context_frame_.Get(isolate)); } diff --git a/src/api/environment.cc b/src/api/environment.cc index 4a7b70168e6d..841cb805accb 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -1179,7 +1179,8 @@ void DefaultProcessExitHandlerInternal(Environment* env, ExitCode exit_code) { // And make sure V8Platform don not call into Libuv threadpool, see Dispose // in node_v8_platform-inl.h uv_library_shutdown(); - DisposePlatform(); + // The isolate is not disposed on this path, see NodePlatform::Shutdown(). + DisposePlatform(env->isolate()); #if HAVE_OPENSSL crypto::CleanupCachedRootCertificates(); diff --git a/src/async_wrap.cc b/src/async_wrap.cc index 7b7930187bd5..3869656eb21e 100644 --- a/src/async_wrap.cc +++ b/src/async_wrap.cc @@ -25,6 +25,7 @@ #include "env-inl.h" #include "node_errors.h" #include "node_external_reference.h" +#include "node_internals.h" #include "tracing/traced_value.h" #include "util-inl.h" @@ -110,8 +111,7 @@ void AsyncWrap::EmitPromiseResolve(Environment* env, double async_id) { } void AsyncWrap::EmitTraceAsyncStart() const { - if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( - TRACING_CATEGORY_NODE1(async_hooks))) { + if (TRACE_EVENT_CATEGORY_ENABLED(TRACING_CATEGORY_NODE1(async_hooks))) { tracing::AsyncWrapArgs data(env()->execution_async_id(), get_trigger_async_id()); TRACE_EVENT_NESTABLE_ASYNC_BEGIN1(TRACING_CATEGORY_NODE1(async_hooks), @@ -290,6 +290,17 @@ void AsyncWrap::PopAsyncContext(const FunctionCallbackInfo<Value>& args) { args.GetReturnValue().Set(env->async_hooks()->pop_async_context(async_id)); } +// The resource of the innermost scope that skipped the id stack, if nothing +// was pushed on the stack after it (depth is the stack length JS sees). +static void LazyExecutionAsyncResource( + const v8::FunctionCallbackInfo<v8::Value>& args) { + Environment* env = Environment::GetCurrent(args); + uint32_t depth = args[0].As<v8::Uint32>()->Value(); + InternalCallbackScope* scope = env->async_hooks()->lazy_top_; + if (scope != nullptr && scope->lazy_depth() == depth) { + args.GetReturnValue().Set(scope->lazy_resource(env->isolate())); + } +} void AsyncWrap::ExecutionAsyncResource( const FunctionCallbackInfo<Value>& args) { @@ -396,6 +407,10 @@ void AsyncWrap::CreatePerIsolateProperties(IsolateData* isolate_data, SetMethod(isolate, target, "pushAsyncContext", PushAsyncContext); SetMethod(isolate, target, "popAsyncContext", PopAsyncContext); SetMethod(isolate, target, "executionAsyncResource", ExecutionAsyncResource); + SetMethod(isolate, + target, + "lazyExecutionAsyncResource", + LazyExecutionAsyncResource); SetMethod(isolate, target, "clearAsyncIdStack", ClearAsyncIdStack); SetMethod(isolate, target, "queueDestroyAsyncId", QueueDestroyAsyncId); SetMethod(isolate, target, "setPromiseHooks", SetPromiseHooks); @@ -470,6 +485,7 @@ void AsyncWrap::CreatePerContextProperties(Local<Object> target, SET_HOOKS_CONSTANT(kDefaultTriggerAsyncId); SET_HOOKS_CONSTANT(kUsesExecutionAsyncResource); SET_HOOKS_CONSTANT(kStackLength); + SET_HOOKS_CONSTANT(kLazyScopes); #undef SET_HOOKS_CONSTANT FORCE_SET_TARGET_FIELD(target, "constants", constants); @@ -502,6 +518,7 @@ void AsyncWrap::RegisterExternalReferences( registry->Register(PushAsyncContext); registry->Register(PopAsyncContext); registry->Register(ExecutionAsyncResource); + registry->Register(LazyExecutionAsyncResource); registry->Register(ClearAsyncIdStack); registry->Register(QueueDestroyAsyncId); registry->Register(SetPromiseHooks); diff --git a/src/cares_wrap.cc b/src/cares_wrap.cc index 5cfae82f47b1..95ce32434a06 100644 --- a/src/cares_wrap.cc +++ b/src/cares_wrap.cc @@ -402,24 +402,33 @@ Maybe<int> ParseGeneralReply(Environment* env, return Just<int>(ARES_SUCCESS); } -Maybe<int> ParseMxReply(Environment* env, - const unsigned char* buf, - int len, - Local<Array> ret, - bool need_type = false) { - HandleScope handle_scope(env->isolate()); - - auto tmpl = env->mx_record_template(); +// Returns the per-isolate dictionary template for a record type, creating and +// caching it on first use. +template <size_t N> +Local<DictionaryTemplate> GetRecordTemplate( + Environment* env, + Local<DictionaryTemplate> (Environment::*getter)() const, + void (Environment::*setter)(Local<DictionaryTemplate>), + const std::string_view (&names)[N]) { + Local<DictionaryTemplate> tmpl = (env->*getter)(); if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "exchange", - "priority", - "type", - }; tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_mx_record_template(tmpl); + (env->*setter)(tmpl); } + return tmpl; +} +// Parses a DNS reply and calls `fn(rr, index)` for each answer record of the +// given type, where `index` is the record's position in the answer section. +// `fn` returns false if a JS exception is pending. Returns the parse status, +// ARES_ENODATA if no answer has the requested type and `allow_empty` is false, +// or Nothing if `fn` failed. +template <typename Fn> +Maybe<int> ForEachAnswer(const unsigned char* buf, + int len, + ares_dns_rec_type_t type, + Fn&& fn, + bool allow_empty = false) { ares_dns_record_t* dnsrec = nullptr; int status = ares_dns_parse(buf, len, 0, &dnsrec); if (status != ARES_SUCCESS) { @@ -429,177 +438,153 @@ Maybe<int> ParseMxReply(Environment* env, DeleteFnPtr<ares_dns_record_t, ares_dns_record_destroy> free_me(dnsrec); const size_t rr_count = ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); - uint32_t offset = ret->Length(); - uint32_t count = 0; - - MaybeLocal<Value> values[] = { - Undefined(env->isolate()), // exchange - Undefined(env->isolate()), // priority - Undefined(env->isolate()), // type - }; - + bool found = false; for (size_t i = 0; i < rr_count; i++) { const ares_dns_rr_t* rr = ares_dns_record_rr_get(dnsrec, ARES_SECTION_ANSWER, i); - if (ares_dns_rr_get_type(rr) != ARES_REC_TYPE_MX) continue; - - const char* exchange = ares_dns_rr_get_str(rr, ARES_RR_MX_EXCHANGE); - unsigned short priority = // NOLINT(runtime/int) - ares_dns_rr_get_u16(rr, ARES_RR_MX_PREFERENCE); - values[0] = OneByteString(env->isolate(), exchange); - values[1] = Integer::New(env->isolate(), priority); - values[2] = env->dns_mx_string(); - Local<Value> record; - if (!NewDictionaryInstance(env->context(), tmpl, values).ToLocal(&record) || - ret->Set(env->context(), offset + count++, record).IsNothing()) { - return Nothing<int>(); - } + if (ares_dns_rr_get_type(rr) != type) continue; + found = true; + if (!fn(rr, i)) return Nothing<int>(); } - if (count == 0) return Just<int>(ARES_ENODATA); + if (!found && !allow_empty) return Just<int>(ARES_ENODATA); return Just<int>(ARES_SUCCESS); } +// Creates a record object from `tmpl` and `values` and appends it to `ret` at +// `index`. Returns false if a JS exception is pending. +template <size_t N> +bool AppendRecord(Environment* env, + Local<DictionaryTemplate> tmpl, + MaybeLocal<Value> (&values)[N], + Local<Array> ret, + uint32_t index) { + Local<Object> record; + return NewDictionaryInstance(env->context(), tmpl, values).ToLocal(&record) && + ret->Set(env->context(), index, record).IsJust(); +} + +Maybe<int> ParseMxReply(Environment* env, + const unsigned char* buf, + int len, + Local<Array> ret, + bool need_type = false) { + HandleScope handle_scope(env->isolate()); + static constexpr std::string_view names[] = { + "exchange", + "priority", + "type", + }; + auto tmpl = GetRecordTemplate(env, + &Environment::mx_record_template, + &Environment::set_mx_record_template, + names); + + const uint32_t offset = ret->Length(); + uint32_t count = 0; + return ForEachAnswer( + buf, len, ARES_REC_TYPE_MX, [&](const ares_dns_rr_t* rr, size_t) { + const char* exchange = ares_dns_rr_get_str(rr, ARES_RR_MX_EXCHANGE); + unsigned short priority = // NOLINT(runtime/int) + ares_dns_rr_get_u16(rr, ARES_RR_MX_PREFERENCE); + MaybeLocal<Value> values[] = { + OneByteString(env->isolate(), exchange), + Integer::New(env->isolate(), priority), + env->dns_mx_string(), + }; + return AppendRecord(env, tmpl, values, ret, offset + count++); + }); +} + Maybe<int> ParseCaaReply(Environment* env, const unsigned char* buf, int len, Local<Array> ret, bool need_type = false) { HandleScope handle_scope(env->isolate()); - - auto tmpl = env->caa_record_template(); - if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "critical", - "type", - }; - tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_caa_record_template(tmpl); - } - - ares_dns_record_t* dnsrec = nullptr; - int status = ares_dns_parse(buf, len, 0, &dnsrec); - if (status != ARES_SUCCESS) { - ares_dns_record_destroy(dnsrec); - return Just<int>(status); - } - DeleteFnPtr<ares_dns_record_t, ares_dns_record_destroy> free_me(dnsrec); - - MaybeLocal<Value> values[] = { - Undefined(env->isolate()), // critical - Undefined(env->isolate()), // type + static constexpr std::string_view names[] = { + "critical", + "type", }; + auto tmpl = GetRecordTemplate(env, + &Environment::caa_record_template, + &Environment::set_caa_record_template, + names); - const size_t rr_count = ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); - uint32_t offset = ret->Length(); + const uint32_t offset = ret->Length(); uint32_t count = 0; - for (size_t i = 0; i < rr_count; i++) { - const ares_dns_rr_t* rr = - ares_dns_record_rr_get(dnsrec, ARES_SECTION_ANSWER, i); - if (ares_dns_rr_get_type(rr) != ARES_REC_TYPE_CAA) continue; - - unsigned char critical = ares_dns_rr_get_u8(rr, ARES_RR_CAA_CRITICAL); - values[0] = Integer::New(env->isolate(), critical); - values[1] = env->dns_caa_string(); - Local<Object> caa_record; - if (!NewDictionaryInstance(env->context(), tmpl, values) - .ToLocal(&caa_record)) { - return Nothing<int>(); - } + return ForEachAnswer( + buf, len, ARES_REC_TYPE_CAA, [&](const ares_dns_rr_t* rr, size_t) { + unsigned char critical = ares_dns_rr_get_u8(rr, ARES_RR_CAA_CRITICAL); + MaybeLocal<Value> values[] = { + Integer::New(env->isolate(), critical), + env->dns_caa_string(), + }; + Local<Object> caa_record; + if (!NewDictionaryInstance(env->context(), tmpl, values) + .ToLocal(&caa_record)) { + return false; + } - const char* tag = ares_dns_rr_get_str(rr, ARES_RR_CAA_TAG); - size_t value_len = 0; - const unsigned char* value = - ares_dns_rr_get_bin(rr, ARES_RR_CAA_VALUE, &value_len); - - // This additional property is not part of the template as it is - // variable based on the record. - if (caa_record - ->Set(env->context(), - OneByteString(env->isolate(), tag), - OneByteString(env->isolate(), value, value_len)) - .IsNothing()) { - return Nothing<int>(); - } + const char* tag = ares_dns_rr_get_str(rr, ARES_RR_CAA_TAG); + size_t value_len = 0; + const unsigned char* value = + ares_dns_rr_get_bin(rr, ARES_RR_CAA_VALUE, &value_len); - if (ret->Set(env->context(), offset + count++, caa_record).IsNothing()) { - return Nothing<int>(); - } - } - - if (count == 0) return Just<int>(ARES_ENODATA); - return Just<int>(ARES_SUCCESS); + // This additional property is not part of the template as it is + // variable based on the record. + return caa_record + ->Set(env->context(), + OneByteString(env->isolate(), tag), + OneByteString(env->isolate(), value, value_len)) + .IsJust() && + ret->Set(env->context(), offset + count++, caa_record).IsJust(); + }); } Maybe<int> ParseTlsaReply(Environment* env, unsigned char* buf, int len, Local<Array> ret) { - EscapableHandleScope handle_scope(env->isolate()); - - auto tmpl = env->tlsa_record_template(); - if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "certUsage", - "selector", - "match", - "data", - }; - tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_tlsa_record_template(tmpl); - } - - ares_dns_record_t* dnsrec = nullptr; - - int status = ares_dns_parse(buf, len, 0, &dnsrec); - if (status != ARES_SUCCESS) { - ares_dns_record_destroy(dnsrec); - return Just<int>(status); - } - - DeleteFnPtr<ares_dns_record_t, ares_dns_record_destroy> free_me(dnsrec); - - uint32_t offset = ret->Length(); - size_t rr_count = ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); - - MaybeLocal<Value> values[] = { - Undefined(env->isolate()), // certUsage - Undefined(env->isolate()), // selector - Undefined(env->isolate()), // match - Undefined(env->isolate()), // data + HandleScope handle_scope(env->isolate()); + static constexpr std::string_view names[] = { + "certUsage", + "selector", + "match", + "data", }; + auto tmpl = GetRecordTemplate(env, + &Environment::tlsa_record_template, + &Environment::set_tlsa_record_template, + names); - for (size_t i = 0; i < rr_count; i++) { - const ares_dns_rr_t* rr = - ares_dns_record_rr_get(dnsrec, ARES_SECTION_ANSWER, i); - - if (ares_dns_rr_get_type(rr) != ARES_REC_TYPE_TLSA) continue; - - unsigned char certusage = ares_dns_rr_get_u8(rr, ARES_RR_TLSA_CERT_USAGE); - unsigned char selector = ares_dns_rr_get_u8(rr, ARES_RR_TLSA_SELECTOR); - unsigned char match = ares_dns_rr_get_u8(rr, ARES_RR_TLSA_MATCH); - size_t data_len; - const unsigned char* data = - ares_dns_rr_get_bin(rr, ARES_RR_TLSA_DATA, &data_len); - if (!data || data_len == 0) continue; - - Local<ArrayBuffer> data_ab = ArrayBuffer::New(env->isolate(), data_len); - memcpy(data_ab->Data(), data, data_len); - - values[0] = Integer::NewFromUnsigned(env->isolate(), certusage); - values[1] = Integer::NewFromUnsigned(env->isolate(), selector); - values[2] = Integer::NewFromUnsigned(env->isolate(), match); - values[3] = data_ab; - - Local<Object> tlsa_rec; - if (!NewDictionaryInstance(env->context(), tmpl, values) - .ToLocal(&tlsa_rec) || - ret->Set(env->context(), offset + i, tlsa_rec).IsNothing()) { - return Nothing<int>(); - } - } - - return Just<int>(ARES_SUCCESS); + const uint32_t offset = ret->Length(); + return ForEachAnswer( + buf, + len, + ARES_REC_TYPE_TLSA, + [&](const ares_dns_rr_t* rr, size_t i) { + unsigned char certusage = + ares_dns_rr_get_u8(rr, ARES_RR_TLSA_CERT_USAGE); + unsigned char selector = ares_dns_rr_get_u8(rr, ARES_RR_TLSA_SELECTOR); + unsigned char match = ares_dns_rr_get_u8(rr, ARES_RR_TLSA_MATCH); + size_t data_len; + const unsigned char* data = + ares_dns_rr_get_bin(rr, ARES_RR_TLSA_DATA, &data_len); + if (!data || data_len == 0) return true; + + Local<ArrayBuffer> data_ab = ArrayBuffer::New(env->isolate(), data_len); + memcpy(data_ab->Data(), data, data_len); + + MaybeLocal<Value> values[] = { + Integer::NewFromUnsigned(env->isolate(), certusage), + Integer::NewFromUnsigned(env->isolate(), selector), + Integer::NewFromUnsigned(env->isolate(), match), + data_ab, + }; + return AppendRecord(env, tmpl, values, ret, offset + i); + }, + /* allow_empty */ true); } Maybe<int> ParseTxtReply(Environment* env, @@ -608,68 +593,39 @@ Maybe<int> ParseTxtReply(Environment* env, Local<Array> ret, bool need_type = false) { HandleScope handle_scope(env->isolate()); - - auto tmpl = env->txt_record_template(); - if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "entries", - "type", - }; - tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_txt_record_template(tmpl); - } - - ares_dns_record_t* dnsrec = nullptr; - int status = ares_dns_parse(buf, len, 0, &dnsrec); - if (status != ARES_SUCCESS) { - ares_dns_record_destroy(dnsrec); - return Just<int>(status); - } - DeleteFnPtr<ares_dns_record_t, ares_dns_record_destroy> free_me(dnsrec); - - const size_t rr_count = ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); - uint32_t offset = ret->Length(); - uint32_t count = 0; - - MaybeLocal<Value> values[] = { - Undefined(env->isolate()), // entries - Undefined(env->isolate()), // type + static constexpr std::string_view names[] = { + "entries", + "type", }; + auto tmpl = GetRecordTemplate(env, + &Environment::txt_record_template, + &Environment::set_txt_record_template, + names); - for (size_t i = 0; i < rr_count; i++) { - const ares_dns_rr_t* rr = - ares_dns_record_rr_get(dnsrec, ARES_SECTION_ANSWER, i); - if (ares_dns_rr_get_type(rr) != ARES_REC_TYPE_TXT) continue; - - // Each TXT record is a chunk consisting of one or more character-strings. - LocalVector<Value> chunks(env->isolate()); - size_t str_count = ares_dns_rr_get_abin_cnt(rr, ARES_RR_TXT_DATA); - chunks.reserve(str_count); - for (size_t j = 0; j < str_count; j++) { - size_t str_len = 0; - const unsigned char* str = - ares_dns_rr_get_abin(rr, ARES_RR_TXT_DATA, j, &str_len); - chunks.push_back(OneByteString(env->isolate(), str, str_len)); - } - - Local<Array> txt_chunk = - Array::New(env->isolate(), chunks.data(), chunks.size()); - if (need_type) { - values[0] = txt_chunk; - values[1] = env->dns_txt_string(); - Local<Object> elem; - if (!NewDictionaryInstance(env->context(), tmpl, values).ToLocal(&elem) || - ret->Set(env->context(), offset + count++, elem).IsNothing()) { - return Nothing<int>(); - } - } else if (ret->Set(env->context(), offset + count++, txt_chunk) - .IsNothing()) { - return Nothing<int>(); - } - } + const uint32_t offset = ret->Length(); + uint32_t count = 0; + return ForEachAnswer( + buf, len, ARES_REC_TYPE_TXT, [&](const ares_dns_rr_t* rr, size_t) { + // Each TXT record is a chunk consisting of one or more + // character-strings. + LocalVector<Value> chunks(env->isolate()); + size_t str_count = ares_dns_rr_get_abin_cnt(rr, ARES_RR_TXT_DATA); + chunks.reserve(str_count); + for (size_t j = 0; j < str_count; j++) { + size_t str_len = 0; + const unsigned char* str = + ares_dns_rr_get_abin(rr, ARES_RR_TXT_DATA, j, &str_len); + chunks.push_back(OneByteString(env->isolate(), str, str_len)); + } - if (count == 0) return Just<int>(ARES_ENODATA); - return Just<int>(ARES_SUCCESS); + Local<Array> txt_chunk = + Array::New(env->isolate(), chunks.data(), chunks.size()); + if (need_type) { + MaybeLocal<Value> values[] = {txt_chunk, env->dns_txt_string()}; + return AppendRecord(env, tmpl, values, ret, offset + count++); + } + return ret->Set(env->context(), offset + count++, txt_chunk).IsJust(); + }); } Maybe<int> ParseSrvReply(Environment* env, @@ -678,64 +634,35 @@ Maybe<int> ParseSrvReply(Environment* env, Local<Array> ret, bool need_type = false) { HandleScope handle_scope(env->isolate()); - - auto tmpl = env->srv_record_template(); - if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "name", - "port", - "priority", - "weight", - "type", - }; - tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_srv_record_template(tmpl); - } - - ares_dns_record_t* dnsrec = nullptr; - int status = ares_dns_parse(buf, len, 0, &dnsrec); - if (status != ARES_SUCCESS) { - ares_dns_record_destroy(dnsrec); - return Just<int>(status); - } - DeleteFnPtr<ares_dns_record_t, ares_dns_record_destroy> free_me(dnsrec); - - MaybeLocal<Value> values[] = { - Undefined(env->isolate()), // name - Undefined(env->isolate()), // port - Undefined(env->isolate()), // priority - Undefined(env->isolate()), // weight - Undefined(env->isolate()), // type + static constexpr std::string_view names[] = { + "name", + "port", + "priority", + "weight", + "type", }; + auto tmpl = GetRecordTemplate(env, + &Environment::srv_record_template, + &Environment::set_srv_record_template, + names); - const size_t rr_count = ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); - uint32_t offset = ret->Length(); + const uint32_t offset = ret->Length(); uint32_t count = 0; - for (size_t i = 0; i < rr_count; i++) { - const ares_dns_rr_t* rr = - ares_dns_record_rr_get(dnsrec, ARES_SECTION_ANSWER, i); - if (ares_dns_rr_get_type(rr) != ARES_REC_TYPE_SRV) continue; - - const char* target = ares_dns_rr_get_str(rr, ARES_RR_SRV_TARGET); - values[0] = OneByteString(env->isolate(), target); - values[1] = - Integer::New(env->isolate(), ares_dns_rr_get_u16(rr, ARES_RR_SRV_PORT)); - values[2] = Integer::New(env->isolate(), - ares_dns_rr_get_u16(rr, ARES_RR_SRV_PRIORITY)); - values[3] = Integer::New(env->isolate(), - ares_dns_rr_get_u16(rr, ARES_RR_SRV_WEIGHT)); - values[4] = env->dns_srv_string(); - - Local<Object> srv_record; - if (!NewDictionaryInstance(env->context(), tmpl, values) - .ToLocal(&srv_record) || - ret->Set(env->context(), offset + count++, srv_record).IsNothing()) { - return Nothing<int>(); - } - } - - if (count == 0) return Just<int>(ARES_ENODATA); - return Just<int>(ARES_SUCCESS); + return ForEachAnswer( + buf, len, ARES_REC_TYPE_SRV, [&](const ares_dns_rr_t* rr, size_t) { + const char* target = ares_dns_rr_get_str(rr, ARES_RR_SRV_TARGET); + MaybeLocal<Value> values[] = { + OneByteString(env->isolate(), target), + Integer::New(env->isolate(), + ares_dns_rr_get_u16(rr, ARES_RR_SRV_PORT)), + Integer::New(env->isolate(), + ares_dns_rr_get_u16(rr, ARES_RR_SRV_PRIORITY)), + Integer::New(env->isolate(), + ares_dns_rr_get_u16(rr, ARES_RR_SRV_WEIGHT)), + env->dns_srv_string(), + }; + return AppendRecord(env, tmpl, values, ret, offset + count++); + }); } Maybe<int> ParseNaptrReply(Environment* env, @@ -744,93 +671,59 @@ Maybe<int> ParseNaptrReply(Environment* env, Local<Array> ret, bool need_type = false) { HandleScope handle_scope(env->isolate()); - - auto tmpl = env->naptr_record_template(); - if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "flags", - "service", - "regexp", - "replacement", - "order", - "preference", - "type", - }; - tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_naptr_record_template(tmpl); - } - - ares_dns_record_t* dnsrec = nullptr; - int status = ares_dns_parse(buf, len, 0, &dnsrec); - if (status != ARES_SUCCESS) { - ares_dns_record_destroy(dnsrec); - return Just<int>(status); - } - DeleteFnPtr<ares_dns_record_t, ares_dns_record_destroy> free_me(dnsrec); - - MaybeLocal<Value> values[] = { - Undefined(env->isolate()), // flags - Undefined(env->isolate()), // service - Undefined(env->isolate()), // regexp - Undefined(env->isolate()), // replacement - Undefined(env->isolate()), // order - Undefined(env->isolate()), // preference - Undefined(env->isolate()), // type + static constexpr std::string_view names[] = { + "flags", + "service", + "regexp", + "replacement", + "order", + "preference", + "type", }; + auto tmpl = GetRecordTemplate(env, + &Environment::naptr_record_template, + &Environment::set_naptr_record_template, + names); - const size_t rr_count = ares_dns_record_rr_cnt(dnsrec, ARES_SECTION_ANSWER); - uint32_t offset = ret->Length(); + const uint32_t offset = ret->Length(); uint32_t count = 0; - for (size_t i = 0; i < rr_count; i++) { - const ares_dns_rr_t* rr = - ares_dns_record_rr_get(dnsrec, ARES_SECTION_ANSWER, i); - if (ares_dns_rr_get_type(rr) != ARES_REC_TYPE_NAPTR) continue; - - values[0] = OneByteString(env->isolate(), - ares_dns_rr_get_str(rr, ARES_RR_NAPTR_FLAGS)); - values[1] = OneByteString(env->isolate(), - ares_dns_rr_get_str(rr, ARES_RR_NAPTR_SERVICES)); - values[2] = OneByteString(env->isolate(), - ares_dns_rr_get_str(rr, ARES_RR_NAPTR_REGEXP)); - values[3] = OneByteString( - env->isolate(), ares_dns_rr_get_str(rr, ARES_RR_NAPTR_REPLACEMENT)); - values[4] = Integer::New(env->isolate(), - ares_dns_rr_get_u16(rr, ARES_RR_NAPTR_ORDER)); - values[5] = Integer::New(env->isolate(), - ares_dns_rr_get_u16(rr, ARES_RR_NAPTR_PREFERENCE)); - if (need_type) { - values[6] = env->dns_naptr_string(); - } - - Local<Object> naptr_record; - if (!NewDictionaryInstance(env->context(), tmpl, values) - .ToLocal(&naptr_record) || - ret->Set(env->context(), offset + count++, naptr_record).IsNothing()) { - return Nothing<int>(); - } - } - - if (count == 0) return Just<int>(ARES_ENODATA); - return Just<int>(ARES_SUCCESS); + return ForEachAnswer( + buf, len, ARES_REC_TYPE_NAPTR, [&](const ares_dns_rr_t* rr, size_t) { + MaybeLocal<Value> values[] = { + OneByteString(env->isolate(), + ares_dns_rr_get_str(rr, ARES_RR_NAPTR_FLAGS)), + OneByteString(env->isolate(), + ares_dns_rr_get_str(rr, ARES_RR_NAPTR_SERVICES)), + OneByteString(env->isolate(), + ares_dns_rr_get_str(rr, ARES_RR_NAPTR_REGEXP)), + OneByteString(env->isolate(), + ares_dns_rr_get_str(rr, ARES_RR_NAPTR_REPLACEMENT)), + Integer::New(env->isolate(), + ares_dns_rr_get_u16(rr, ARES_RR_NAPTR_ORDER)), + Integer::New(env->isolate(), + ares_dns_rr_get_u16(rr, ARES_RR_NAPTR_PREFERENCE)), + need_type ? MaybeLocal<Value>(env->dns_naptr_string()) + : MaybeLocal<Value>(Undefined(env->isolate())), + }; + return AppendRecord(env, tmpl, values, ret, offset + count++); + }); } Local<DictionaryTemplate> getSoaRecordTemplate(Environment* env) { - auto tmpl = env->soa_record_template(); - if (tmpl.IsEmpty()) { - static constexpr std::string_view names[] = { - "nsname", - "hostmaster", - "serial", - "refresh", - "retry", - "expire", - "minttl", - "type", - }; - tmpl = DictionaryTemplate::New(env->isolate(), names); - env->set_soa_record_template(tmpl); - } - return tmpl; + static constexpr std::string_view names[] = { + "nsname", + "hostmaster", + "serial", + "refresh", + "retry", + "expire", + "minttl", + "type", + }; + return GetRecordTemplate(env, + &Environment::soa_record_template, + &Environment::set_soa_record_template, + names); } Maybe<int> ParseSoaReply(Environment* env, diff --git a/src/compile_cache.h b/src/compile_cache.h index ec405cf55b80..1bd2ca082860 100644 --- a/src/compile_cache.h +++ b/src/compile_cache.h @@ -49,7 +49,7 @@ struct CompileCacheEntry { V(FAILED) /* Failed to enable the cache */ \ V(ENABLED) /* Was not enabled before, and now enabled. */ \ V(ALREADY_ENABLED) /* Was already enabled. */ \ - V(DISABLED) /* Has been disabled by NODE_DISABLE_COMPILE_CACHE. */ + V(DISABLED) /* Disabled by the environment or by V8 coverage. */ enum class CompileCacheEnableStatus : uint8_t { #define V(status) status, diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc index 759353f08f03..630606b3c7ae 100644 --- a/src/crypto/crypto_common.cc +++ b/src/crypto/crypto_common.cc @@ -30,6 +30,7 @@ namespace node { using ncrypto::ClearErrorOnReturn; using ncrypto::EVPKeyPointer; using ncrypto::KeyAlgorithm; +using ncrypto::MarkPopErrorOnReturn; using ncrypto::SSLPointer; using ncrypto::SSLSessionPointer; using ncrypto::StackOfX509; @@ -49,6 +50,7 @@ using v8::Value; namespace crypto { SSLSessionPointer GetTLSSession(const unsigned char* buf, size_t length) { + MarkPopErrorOnReturn mark_pop_error_on_return; return SSLSessionPointer(d2i_SSL_SESSION(nullptr, &buf, length)); } diff --git a/src/crypto/crypto_context.cc b/src/crypto/crypto_context.cc index 21decb34e111..bd6f9c596898 100644 --- a/src/crypto/crypto_context.cc +++ b/src/crypto/crypto_context.cc @@ -2516,13 +2516,7 @@ int SecureContext::TicketKeyCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc) { static const int kTicketPartSize = 16; @@ -2615,13 +2609,7 @@ int SecureContext::TicketCompatibilityCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc) { SecureContext* sc = static_cast<SecureContext*>( SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl))); diff --git a/src/crypto/crypto_context.h b/src/crypto/crypto_context.h index 5073897251a8..8b6f0fe18817 100644 --- a/src/crypto/crypto_context.h +++ b/src/crypto/crypto_context.h @@ -35,6 +35,15 @@ void InstallCertVerifyCallback(SSL_CTX* ctx); ncrypto::BIOPointer LoadBIO(Environment* env, v8::Local<v8::Value> v); +// The HMAC context type passed to TLS session ticket key callbacks. +#if NCRYPTO_USE_OPENSSL_PROVIDER +using TicketHmacCtx = EVP_MAC_CTX; +#elif NCRYPTO_USE_BORINGSSL +using TicketHmacCtx = HMAC_CTX; +#else +#error "Unsupported crypto backend" +#endif + class SecureContext final : public BaseObject { public: using GetSessionCb = SSL_SESSION* (*)(SSL*, const unsigned char*, int, int*); @@ -161,26 +170,14 @@ class SecureContext final : public BaseObject { unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc); static int TicketCompatibilityCallback(SSL* ssl, unsigned char* name, unsigned char* iv, EVP_CIPHER_CTX* ectx, -#if NCRYPTO_USE_OPENSSL_PROVIDER - EVP_MAC_CTX* hctx, -#elif NCRYPTO_USE_BORINGSSL - HMAC_CTX* hctx, -#else -#error "Unsupported crypto backend" -#endif + TicketHmacCtx* hctx, int enc); SecureContext(Environment* env, v8::Local<v8::Object> wrap); diff --git a/src/crypto/crypto_hash.cc b/src/crypto/crypto_hash.cc index b0ea75e88b27..77b7e7d41693 100644 --- a/src/crypto/crypto_hash.cc +++ b/src/crypto/crypto_hash.cc @@ -709,13 +709,8 @@ void Hash::New(const FunctionCallbackInfo<Value>& args) { } } -bool Hash::HashInit(const EVP_MD* digest, Maybe<unsigned int> xof_md_len) { - mdctx_ = EVPMDCtxPointer::New(); - if (!mdctx_.digestInit(digest)) [[unlikely]] { - mdctx_.reset(); - return false; - } - +bool Hash::FinishHashInit(const EVP_MD* digest, + Maybe<unsigned int> xof_md_len) { md_len_ = mdctx_.getDigestSize(); if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() && ShouldRejectMissingXofLength(digest, md_len_)) { @@ -738,35 +733,26 @@ bool Hash::HashInit(const EVP_MD* digest, Maybe<unsigned int> xof_md_len) { return true; } -bool Hash::HashInit(const EVP_MD* digest, - const CShakeOptions& options, - Maybe<unsigned int> xof_md_len) { +bool Hash::HashInit(const EVP_MD* digest, Maybe<unsigned int> xof_md_len) { mdctx_ = EVPMDCtxPointer::New(); - if (!options.Initialize(&mdctx_, digest)) [[unlikely]] { + if (!mdctx_.digestInit(digest)) [[unlikely]] { mdctx_.reset(); return false; } - md_len_ = mdctx_.getDigestSize(); - if (mdctx_.hasXofFlag() && !xof_md_len.IsJust() && - ShouldRejectMissingXofLength(digest, md_len_)) { - MarkInvalidXofLength(); + return FinishHashInit(digest, xof_md_len); +} + +bool Hash::HashInit(const EVP_MD* digest, + const CShakeOptions& options, + Maybe<unsigned int> xof_md_len) { + mdctx_ = EVPMDCtxPointer::New(); + if (!options.Initialize(&mdctx_, digest)) [[unlikely]] { mdctx_.reset(); return false; } - if (xof_md_len.IsJust() && xof_md_len.FromJust() != md_len_) { - // This is a little hack to cause createHash to fail when an incorrect - // hashSize option was passed for a non-XOF hash function. - if (!mdctx_.hasXofFlag()) [[unlikely]] { - MarkInvalidXofLength(); - mdctx_.reset(); - return false; - } - md_len_ = xof_md_len.FromJust(); - } - - return true; + return FinishHashInit(digest, xof_md_len); } bool Hash::HashUpdate(const char* data, size_t len) { diff --git a/src/crypto/crypto_hash.h b/src/crypto/crypto_hash.h index 322ff83da695..558c67822f4c 100644 --- a/src/crypto/crypto_hash.h +++ b/src/crypto/crypto_hash.h @@ -57,6 +57,11 @@ class Hash final : public BaseObject { Hash(Environment* env, v8::Local<v8::Object> wrap); private: + // Determines the digest length after mdctx_ has been initialized, applying + // and validating the requested XOF output length. Resets mdctx_ and returns + // false on failure. + bool FinishHashInit(const EVP_MD* digest, v8::Maybe<unsigned int> xof_md_len); + ncrypto::EVPMDCtxPointer mdctx_{}; unsigned int md_len_ = 0; ByteSource digest_; diff --git a/src/crypto/crypto_tls.cc b/src/crypto/crypto_tls.cc index a0e883f00b49..c5cc3db68c03 100644 --- a/src/crypto/crypto_tls.cc +++ b/src/crypto/crypto_tls.cc @@ -700,6 +700,16 @@ void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { if (where & SSL_CB_HANDSHAKE_START) { Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_START);"); +#ifndef OPENSSL_IS_BORINGSSL + // The TLS library answers a peer's attempt to renegotiate with a + // no_renegotiation alert when renegotiation is disabled, and then reports + // the handshake as done without having done one. + c->flags_.renegotiation_refused = + c->flags_.established && + (SSL_get_options(ssl) & SSL_OP_NO_RENEGOTIATION) != 0; + if (c->flags_.renegotiation_refused) return; +#endif + // Start is tracked to limit number and frequency of renegotiation attempts, // since excessive renegotiation may be an attack. Local<Value> callback; @@ -717,6 +727,10 @@ void TLSWrap::SSLInfoCallback(const SSL* ssl_, int where, int ret) { if (where & SSL_CB_HANDSHAKE_DONE && !SSL_renegotiate_pending(ssl)) { Debug(c, "SSLInfoCallback(SSL_CB_HANDSHAKE_DONE);"); CHECK(!SSL_renegotiate_pending(ssl)); + if (c->flags_.renegotiation_refused) { + c->flags_.renegotiation_refused = false; + return; + } Local<Value> callback; c->flags_.established = true; @@ -887,13 +901,17 @@ void TLSWrap::ClearOut() { int length = 0; int read; - // Emits out[0, length). Returns false if JS destroyed the SSL context. + // Emits out[0, length). Returns false if reading cannot continue. auto emit = [&]() { char* current = out; while (length > 0) { int avail = length; uv_buf_t buf = EmitAlloc(avail); + if (buf.base == nullptr || buf.len == 0) { + EmitRead(UV_ENOBUFS, buf); + return false; + } if (static_cast<int>(buf.len) < avail) avail = buf.len; memcpy(buf.base, current, avail); @@ -1457,6 +1475,19 @@ void TLSWrap::EnableKeylogCallback(const FunctionCallbackInfo<Value>& args) { # define HAVE_SSL_TRACE 1 #endif +void TLSWrap::DisableRenegotiation(const FunctionCallbackInfo<Value>& args) { + TLSWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); + if (!wrap->ssl_) return; +#if NCRYPTO_USE_OPENSSL_PROVIDER + SSL_set_options(wrap->ssl_.get(), SSL_OP_NO_RENEGOTIATION); +#elif NCRYPTO_USE_BORINGSSL + SSL_set_renegotiate_mode(wrap->ssl_.get(), ssl_renegotiate_never); +#else +#error "Unsupported crypto backend" +#endif +} + void TLSWrap::EnableTrace(const FunctionCallbackInfo<Value>& args) { TLSWrap* wrap; ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); @@ -2453,6 +2484,7 @@ void TLSWrap::Initialize( SetProtoMethod(isolate, t, "certCbDone", CertCbDone); SetProtoMethod(isolate, t, "clientHelloDone", ClientHelloDone); SetProtoMethod(isolate, t, "destroySSL", DestroySSL); + SetProtoMethod(isolate, t, "disableRenegotiation", DisableRenegotiation); SetProtoMethod(isolate, t, "enableCertCb", EnableCertCb); SetProtoMethod(isolate, t, "enableALPNCb", EnableALPNCb); SetProtoMethod(isolate, t, "enableKeylogCallback", EnableKeylogCallback); @@ -2528,6 +2560,7 @@ void TLSWrap::RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(CertCbDone); registry->Register(ClientHelloDone); registry->Register(DestroySSL); + registry->Register(DisableRenegotiation); registry->Register(EnableCertCb); registry->Register(EnableALPNCb); registry->Register(EnableKeylogCallback); diff --git a/src/crypto/crypto_tls.h b/src/crypto/crypto_tls.h index f49a4904f15f..7f5ac201a62c 100644 --- a/src/crypto/crypto_tls.h +++ b/src/crypto/crypto_tls.h @@ -238,6 +238,8 @@ class TLSWrap : public AsyncWrap, static void CertCbDone(const v8::FunctionCallbackInfo<v8::Value>& args); static void ClientHelloDone(const v8::FunctionCallbackInfo<v8::Value>& args); static void DestroySSL(const v8::FunctionCallbackInfo<v8::Value>& args); + static void DisableRenegotiation( + const v8::FunctionCallbackInfo<v8::Value>& args); static void EnableCertCb(const v8::FunctionCallbackInfo<v8::Value>& args); static void EnableALPNCb(const v8::FunctionCallbackInfo<v8::Value>& args); static void EnableKeylogCallback( @@ -358,6 +360,9 @@ class TLSWrap : public AsyncWrap, bool has_active_write_issued_by_prev_listener : 1; bool alpn_callback_enabled : 1; bool servername_pinned : 1; + // The handshake in progress is the peer's attempt to renegotiate, which + // the TLS library is refusing. + bool renegotiation_refused : 1; }; Flags flags_{}; diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index 060f77fc3627..f0661f2692e3 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -346,7 +346,7 @@ class CryptoJob : public AsyncWrap, public ThreadPoolWork { CryptoJobMode mode, AdditionalParams&& params) : AsyncWrap(env, object, type), - ThreadPoolWork(env, "crypto"), + ThreadPoolWork(env, ThreadPoolWorkType::kCrypto), mode_(mode), params_(std::move(params)) { // If the CryptoJob is async, then the instance will be diff --git a/src/encoding_binding.cc b/src/encoding_binding.cc index 8a445088b54a..5b8f8f0bcdc2 100644 --- a/src/encoding_binding.cc +++ b/src/encoding_binding.cc @@ -20,7 +20,6 @@ using v8::BackingStoreInitializationMode; using v8::BackingStoreOnFailureMode; using v8::Context; using v8::FunctionCallbackInfo; -using v8::HandleScope; using v8::Isolate; using v8::Local; using v8::Object; @@ -67,10 +66,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, } InternalFieldInfoBase* BindingData::Serialize(int index) { - DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = internal_field_info_; - internal_field_info_ = nullptr; - return info; + return TakeInternalFieldInfo(index, &internal_field_info_); } // The following code is adapted from Cloudflare workers. @@ -185,13 +181,8 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - // Recreate the buffer in the constructor. - InternalFieldInfo* casted_info = static_cast<InternalFieldInfo*>(info); - BindingData* binding = - realm->AddBindingData<BindingData>(holder, casted_info); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>( + context, holder, static_cast<InternalFieldInfo*>(info)); } void BindingData::EncodeInto(const FunctionCallbackInfo<Value>& args) { diff --git a/src/env-inl.h b/src/env-inl.h index c2abf1c29a8a..dec640a3de03 100644 --- a/src/env-inl.h +++ b/src/env-inl.h @@ -1021,6 +1021,12 @@ inline void Environment::RemoveHeapProfileNearHeapLimitCallback( } } +inline void Environment::set_pointer_compression_heap_warning_thresholds( + uint64_t likely_bytes, uint64_t certain_bytes) { + pointer_compression_heap_likely_threshold_ = likely_bytes; + pointer_compression_heap_certain_threshold_ = certain_bytes; +} + } // namespace node // These two files depend on each other. Including base_object-inl.h after this diff --git a/src/env.cc b/src/env.cc index 5f8e22073fa7..a1d6a69dce43 100644 --- a/src/env.cc +++ b/src/env.cc @@ -8,6 +8,7 @@ #include "node_buffer.h" #include "node_context_data.h" #include "node_contextify.h" +#include "node_diagnostics_channel.h" #include "node_dotenv.h" #include "node_errors.h" #include "node_file_utils.h" @@ -171,12 +172,25 @@ void AsyncHooks::push_async_context( } } +void AsyncHooks::CheckLazyClose(double async_id, uint32_t depth) { + if (fields_[kCheck] > 0 && (async_id_fields_[kExecutionAsyncId] != async_id || + fields_[kStackLength] != depth)) [[unlikely]] { + FailWithCorruptedAsyncStack(async_id); + } +} + // Remember to keep this code aligned with popAsyncContext() in JS. bool AsyncHooks::pop_async_context(double async_id) { // In case of an exception then this may have already been reset, if the // stack was multiple MakeCallback()'s deep. - if (fields_[kStackLength] == 0) [[unlikely]] + if (fields_[kStackLength] == 0) [[unlikely]] { + // A scope that skipped the stack still has its id checked. + if (fields_[kLazyScopes] > 0 && fields_[kCheck] > 0 && + async_id_fields_[kExecutionAsyncId] != async_id) { + FailWithCorruptedAsyncStack(async_id); + } return false; + } // Ask for the async_id to be restored as a check that the stack // hasn't been corrupted. @@ -205,7 +219,6 @@ bool AsyncHooks::pop_async_context(double async_id) { } else { native_execution_async_resources_.resize(offset); } - native_execution_async_resources_.shrink_to_fit(); } if (js_execution_async_resources()->Length() > offset) [[unlikely]] { @@ -235,6 +248,8 @@ void AsyncHooks::clear_async_id_stack() { async_id_fields_[kExecutionAsyncId] = 0; async_id_fields_[kTriggerAsyncId] = 0; fields_[kStackLength] = 0; + lazy_top_ = nullptr; + fields_[kLazyScopes] = 0; } void AsyncHooks::InstallPromiseHooks(Local<Context> ctx) { @@ -1268,6 +1283,7 @@ Environment::~Environment() { if (heap_profile_near_heap_limit_callback_added_) { RemoveHeapProfileNearHeapLimitCallback(0); } + RemovePointerCompressionHeapWarningCallback(); isolate()->GetHeapProfiler()->RemoveBuildEmbedderGraphCallback( BuildEmbedderGraph, this); @@ -1321,6 +1337,30 @@ Environment::~Environment() { isolate_data_->RemoveEnvironment(); } +void Environment::InitializeThreadPoolWorkChannels() { + if (isolate_data()->is_building_snapshot()) return; + + auto* binding = + principal_realm()->GetBindingData<diagnostics_channel::BindingData>(); + CHECK_NOT_NULL(binding); + for (size_t i = 0; i < threadpool_work_channels_.size(); i++) { + ThreadPoolWorkChannel* entry = &threadpool_work_channels_[i]; + if (entry->channel.get() != nullptr) continue; + + std::string name = "uv.threadpool.work."; + name += kThreadPoolWorkNames[i]; + BaseObjectPtr<diagnostics_channel::Channel> channel = + diagnostics_channel::Channel::Get(this, name); + if (!channel) continue; + + binding->SetChannelStatusCallback( + channel->index(), [entry](bool active) { entry->active = active; }); + entry->channel = + BaseObjectWeakPtr<diagnostics_channel::Channel>(channel.get()); + entry->active = channel->HasSubscribers(); + } +} + void Environment::InitializeLibuv() { HandleScope handle_scope(isolate()); Context::Scope context_scope(context()); @@ -1400,10 +1440,20 @@ CompileCacheEnableResult Environment::EnableCompileCache( const std::string& key_root) { CompileCacheEnableResult result; std::string disable_env; + const char* disabled_reason = nullptr; if (credentials::SafeGetenv( "NODE_DISABLE_COMPILE_CACHE", &disable_env, this)) { + disabled_reason = "Disabled by NODE_DISABLE_COMPILE_CACHE"; +#if HAVE_INSPECTOR + } else if (coverage_connection() != nullptr) { + // V8 cannot collect block coverage for functions deserialized from the + // cache. + disabled_reason = "Disabled because V8 coverage is being collected"; +#endif // HAVE_INSPECTOR + } + if (disabled_reason != nullptr) { result.status = CompileCacheEnableStatus::DISABLED; - result.message = "Disabled by NODE_DISABLE_COMPILE_CACHE"; + result.message = disabled_reason; Debug(this, DebugCategory::COMPILE_CACHE, "[compile cache] %s.\n", @@ -2343,6 +2393,84 @@ void Environment::TracePromises(PromiseHookType type, PrintCurrentStackTrace(isolate); } +bool Environment::ShouldWarnAboutPointerCompressionHeap() const { +#if defined(V8_COMPRESS_POINTERS) + // The cage already enforces the limit, so there is nothing to warn about. + return false; +#else + // 32-bit address spaces cannot hold a 4 GiB heap in the first place. + // --no-warnings and --disable-warning are not checked here: like every + // other process warning, they only suppress the default stderr output, and + // 'warning' listeners still receive the event. + return sizeof(void*) == 8; +#endif +} + +void Environment::AddPointerCompressionHeapWarningCallback() { + if (pointer_compression_heap_warning_callback_added_) return; + pointer_compression_heap_warning_callback_added_ = true; + // Only full GCs: the heap that survives a mark-compact is the closest + // approximation of the live heap, and young-generation GCs are frequent. + isolate_->AddGCEpilogueCallback( + PointerCompressionHeapWarningCallback, this, v8::kGCTypeMarkSweepCompact); +} + +void Environment::RemovePointerCompressionHeapWarningCallback() { + if (!pointer_compression_heap_warning_callback_added_) return; + pointer_compression_heap_warning_callback_added_ = false; + isolate_->RemoveGCEpilogueCallback(PointerCompressionHeapWarningCallback, + this); +} + +void Environment::PointerCompressionHeapWarningCallback( + Isolate* isolate, v8::GCType type, v8::GCCallbackFlags flags, void* data) { + Environment* env = static_cast<Environment*>(data); + if (env->pointer_compression_heap_warning_scheduled_) return; + + v8::HeapStatistics stats; + isolate->GetHeapStatistics(&stats); + const uint64_t used = stats.used_heap_size(); + if (used < env->pointer_compression_heap_likely_threshold_ && + used < env->pointer_compression_heap_certain_threshold_) { + return; + } + // The wording is decided once, when the warning is first triggered. + const bool certain = used >= env->pointer_compression_heap_certain_threshold_; + + // JavaScript cannot run inside a GC callback, and V8 does not allow + // removing a GC callback while it is iterating over them, so do both from + // an immediate instead. + env->pointer_compression_heap_warning_scheduled_ = true; + env->SetImmediate( + [used, certain](Environment* env) { + env->RemovePointerCompressionHeapWarningCallback(); + constexpr uint64_t kMiB = 1024 * 1024; + std::string thread = + env->is_main_thread() + ? std::string("the main thread") + : SPrintF("worker thread %d", env->thread_id()); + std::string outcome = + certain ? "Pointer compression reduces heap usage by at most " + "half, so this heap will exceed that limit, and the " + "application will run out of memory" + : "Pointer compression typically reduces heap usage by " + "about 40%, so this heap is likely to exceed that " + "limit, and the application may run out of memory"; + std::string message = SPrintF( + "The V8 heap of %s is using %d MiB after garbage collection. " + "When pointer compression is enabled, the heap of each thread is " + "limited to %d MiB. %s in Node.js builds that enable pointer " + "compression.", + thread, + used / kMiB, + kPointerCompressionCageSize / kMiB, + outcome); + USE(ProcessEmitWarningGeneric( + env, message, "Warning", kPointerCompressionHeapWarningCode)); + }, + CallbackFlags::kUnrefed); +} + // V8 only invokes the most recently registered near-heap-limit callback. // To allow the snapshot and profile handlers to coexist on the same // isolate, both register through this single V8-facing entry point. It fans @@ -2545,8 +2673,8 @@ size_t Environment::HeapProfileNearHeapLimitCallback( Debug(env, DebugCategory::DIAGNOSTICS, "Writing %s...\n", *name); - std::ostringstream out; - if (!node::SerializeHeapProfile(env->isolate(), out)) { + std::string profile; + if (!node::SerializeHeapProfile(env->isolate(), profile)) { Debug(env, DebugCategory::DIAGNOSTICS, "No sampling heap profile active; uninstalling callback.\n"); @@ -2554,7 +2682,6 @@ size_t Environment::HeapProfileNearHeapLimitCallback( return new_limit; } - std::string profile = std::move(out).str(); uv_buf_t buffer = uv_buf_init(profile.data(), profile.size()); const int err = WriteFileSync(filename.c_str(), buffer); if (err != 0) { diff --git a/src/env.h b/src/env.h index 45867eab08e0..9ea546e8e149 100644 --- a/src/env.h +++ b/src/env.h @@ -63,6 +63,7 @@ #include <ostream> #include <set> #include <string> +#include <string_view> #include <unordered_map> #include <unordered_set> #include <variant> @@ -83,6 +84,42 @@ void FreeRootCertStore(RootCertStore* root_certs); } // namespace crypto #endif // HAVE_OPENSSL +namespace diagnostics_channel { +class Channel; +} + +struct ThreadPoolWorkChannel { + BaseObjectWeakPtr<diagnostics_channel::Channel> channel; + bool active = false; +}; + +enum class ThreadPoolWorkType : uint8_t { + kCrypto, + kFsCp, + kFsReadFile, + kFsWriteFile, + kGlob, + kHistogramQrde, + kNodeApi, + kReadDirRecursive, + kSQLiteBackup, + kZlib, + kCount, +}; + +inline constexpr std::array<std::string_view, + static_cast<size_t>(ThreadPoolWorkType::kCount)> + kThreadPoolWorkNames = {"crypto", + "fs.cp", + "fs.readfile", + "fs.writefile", + "glob", + "histogram.qrde", + "node_api", + "readdir_recursive", + "node_sqlite3.BackupJob", + "zlib"}; + namespace shadow_realm { class ShadowRealm; } @@ -322,11 +359,12 @@ class EnabledDebugList; class StreamReadSlab { public: // Sized to match the read buffer size that libuv suggests for stream - // reads: a slab typically serves a single large read (still avoiding the - // copy that right-sizing the buffer would need), or many small ones. - // Larger slabs amortize allocations further, but stay alive (pinned by - // chunk views) long enough to be promoted to V8's old generation, where - // their external memory is only reclaimed by major GCs. + // reads: a slab serves a single large read (still avoiding the copy that + // right-sizing the buffer would need), or is reused for small reads that + // are copied out of it. Larger slabs amortize allocations further, but + // stay alive (pinned by chunk views) long enough to be promoted to V8's + // old generation, where their external memory is only reclaimed by major + // GCs. static constexpr size_t kSlabSize = 64 * 1024; // Reserve `suggested` bytes. Starts a new slab if the current one does @@ -375,6 +413,8 @@ extern std::shared_ptr<KVStore> system_environment; struct EnvSerializeInfo; +class InternalCallbackScope; + class AsyncHooks : public MemoryRetainer { public: SET_MEMORY_INFO_NAME(AsyncHooks) @@ -393,6 +433,7 @@ class AsyncHooks : public MemoryRetainer { kCheck, kStackLength, kUsesExecutionAsyncResource, + kLazyScopes, kFieldsCount, }; @@ -509,6 +550,13 @@ class AsyncHooks : public MemoryRetainer { const SerializeInfo* info_ = nullptr; std::array<v8::Global<v8::Function>, 4> js_promise_hooks_; + + public: + // Innermost InternalCallbackScope that swapped the ids without the stack, + // for executionAsyncResource(). Counted in fields_[kLazyScopes]. + InternalCallbackScope* lazy_top_ = nullptr; + // Close of a scope that skipped the stack: the same check as pop. + void CheckLazyClose(double async_id, uint32_t depth); }; class ImmediateInfo : public MemoryRetainer { @@ -744,6 +792,11 @@ class Environment final : public MemoryRetainer { void RunDeserializeRequests(); // Should be called before InitializeInspector() void InitializeDiagnostics(); + void InitializeThreadPoolWorkChannels(); + inline ThreadPoolWorkChannel* threadpool_work_channel( + ThreadPoolWorkType type) { + return &threadpool_work_channels_[static_cast<size_t>(type)]; + } #if HAVE_INSPECTOR // If the environment is created for a worker, pass parent_handle and @@ -1117,6 +1170,10 @@ class Environment final : public MemoryRetainer { static void BuildEmbedderGraph(v8::Isolate* isolate, v8::EmbedderGraph* graph, void* data); + static void PointerCompressionHeapWarningCallback(v8::Isolate* isolate, + v8::GCType type, + v8::GCCallbackFlags flags, + void* data); inline std::shared_ptr<EnvironmentOptions> options(); inline std::shared_ptr<ExclusiveAccess<HostPort>> inspector_host_port(); @@ -1208,6 +1265,28 @@ class Environment final : public MemoryRetainer { inline void AddHeapProfileNearHeapLimitCallback(); inline void RemoveHeapProfileNearHeapLimitCallback(size_t heap_limit); + // The heap of a single isolate cannot grow beyond the 4 GiB pointer + // compression cage in builds that enable pointer compression. In builds + // that do not, warn once per Environment when the heap that survives a full + // garbage collection suggests that it would not fit: + // - Pointer compression shrinks a heap by at most half (only tagged slots + // shrink), so a heap of twice the cage size or more will not fit. + // - V8 reports typical savings of about 40%, so a heap of about 6.5 GiB or + // more (4 GiB / 0.6) is likely not to fit. + static constexpr uint64_t kPointerCompressionCageSize = uint64_t{1} << 32; + static constexpr uint64_t kPointerCompressionHeapLikelyThreshold = + uint64_t{13} << 29; // 6.5 GiB + static constexpr uint64_t kPointerCompressionHeapCertainThreshold = + 2 * kPointerCompressionCageSize; // 8 GiB + static constexpr const char* kPointerCompressionHeapWarningCode = + "HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT"; + bool ShouldWarnAboutPointerCompressionHeap() const; + void AddPointerCompressionHeapWarningCallback(); + void RemovePointerCompressionHeapWarningCallback(); + // Used by tests to trigger the warning without allocating a large heap. + inline void set_pointer_compression_heap_warning_thresholds( + uint64_t likely_bytes, uint64_t certain_bytes); + v8::CpuProfilingResult StartCpuProfile(const CpuProfileOptions& options); v8::CpuProfile* StopCpuProfile(v8::ProfilerId profile_id); @@ -1264,6 +1343,9 @@ class Environment final : public MemoryRetainer { AliasedInt32Array timeout_info_; TickInfo tick_info_; permission::Permission permission_; + std::array<ThreadPoolWorkChannel, + static_cast<size_t>(ThreadPoolWorkType::kCount)> + threadpool_work_channels_; const uint64_t timer_base_; std::shared_ptr<KVStore> env_vars_; int ipc_channel_fd_ = -1; @@ -1314,6 +1396,15 @@ class Environment final : public MemoryRetainer { uint32_t heap_profile_near_heap_limit_ = 0; bool heap_profile_near_heap_limit_callback_added_ = false; + bool pointer_compression_heap_warning_callback_added_ = false; + // Set once the warning has been scheduled, so that later GCs that run + // before the callback is removed do not schedule it again. + bool pointer_compression_heap_warning_scheduled_ = false; + uint64_t pointer_compression_heap_likely_threshold_ = + kPointerCompressionHeapLikelyThreshold; + uint64_t pointer_compression_heap_certain_threshold_ = + kPointerCompressionHeapCertainThreshold; + uint32_t module_id_counter_ = 0; uint32_t script_id_counter_ = 0; uint32_t function_id_counter_ = 0; diff --git a/src/env_properties.h b/src/env_properties.h index c7a26ce3a58d..2f3d814ff497 100644 --- a/src/env_properties.h +++ b/src/env_properties.h @@ -442,6 +442,7 @@ V(lock_query_template, v8::DictionaryTemplate) \ V(message_port_constructor_template, v8::FunctionTemplate) \ V(module_wrap_constructor_template, v8::FunctionTemplate) \ + V(module_request_template, v8::DictionaryTemplate) \ V(mx_record_template, v8::DictionaryTemplate) \ V(naptr_record_template, v8::DictionaryTemplate) \ V(object_stats_template, v8::DictionaryTemplate) \ @@ -465,6 +466,7 @@ V(srv_record_template, v8::DictionaryTemplate) \ V(streambaseoutputstream_constructor_template, v8::ObjectTemplate) \ V(tcp_constructor_template, v8::FunctionTemplate) \ + V(threadpool_work_template, v8::DictionaryTemplate) \ V(tlsa_record_template, v8::DictionaryTemplate) \ V(tty_constructor_template, v8::FunctionTemplate) \ V(txt_record_template, v8::DictionaryTemplate) \ diff --git a/src/glob/glob_matcher.cc b/src/glob/glob_matcher.cc index e0cca5cf43e6..53d59fb8a358 100644 --- a/src/glob/glob_matcher.cc +++ b/src/glob/glob_matcher.cc @@ -673,12 +673,9 @@ class PathMatcher { } const ptrdiff_t file_length = static_cast<ptrdiff_t>(file.size()) - static_cast<ptrdiff_t>(file_tail_match); - { - size_t i = sections.size() - 1; - for (Section& s : sections) { - s.after = file_length - (static_cast<ptrdiff_t>(sections[i--].non_gs) + - static_cast<ptrdiff_t>(s.end - s.begin)); - } + // leave room for this section and every section after it + for (Section& s : sections) { + s.after = file_length - static_cast<ptrdiff_t>(non_gs - s.non_gs); } return MatchBodySections( file, pattern, sections, fi, 0, 0, file_tail_match != 0); diff --git a/src/glob/node_glob.cc b/src/glob/node_glob.cc index 9337775c79da..74fadb417c18 100644 --- a/src/glob/node_glob.cc +++ b/src/glob/node_glob.cc @@ -178,10 +178,7 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - Realm* realm = Realm::GetCurrent(context); - HandleScope scope(realm->isolate()); - BindingData* binding = realm->AddBindingData<BindingData>(holder, info); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>(context, holder, info); } void BindingData::MemoryInfo(MemoryTracker* tracker) const { @@ -431,7 +428,7 @@ GlobRequest::GlobRequest(Environment* env, const std::vector<CompiledPatternPtr>& excludes, std::unique_ptr<JsExcludeFilter> filter) : AsyncWrap(env, object, AsyncWrap::PROVIDER_GLOBREQUEST), - ThreadPoolWork(env, "glob"), + ThreadPoolWork(env, ThreadPoolWorkType::kGlob), filter_(std::move(filter)), walk_(env, options, includes, excludes), with_file_types_(options.with_file_types) { diff --git a/src/histogram-inl.h b/src/histogram-inl.h index 87f92c492efb..bf2e4eae9058 100644 --- a/src/histogram-inl.h +++ b/src/histogram-inl.h @@ -98,6 +98,7 @@ uint64_t Histogram::ResetCount() const { int64_t Histogram::Min() const { RwLock::ScopedReadLock lock(mutex_); + if (histogram_->total_count == 0) return std::numeric_limits<int64_t>::max(); return hdr_min(histogram_.get()); } @@ -108,11 +109,15 @@ int64_t Histogram::Max() const { double Histogram::Mean() const { RwLock::ScopedReadLock lock(mutex_); + if (histogram_->total_count == 0) + return std::numeric_limits<double>::quiet_NaN(); return hdr_mean(histogram_.get()); } double Histogram::Stddev() const { RwLock::ScopedReadLock lock(mutex_); + if (histogram_->total_count == 0) + return std::numeric_limits<double>::quiet_NaN(); return hdr_stddev(histogram_.get()); } diff --git a/src/histogram.cc b/src/histogram.cc index 6efe2d6985cc..ada84685f40c 100644 --- a/src/histogram.cc +++ b/src/histogram.cc @@ -970,7 +970,7 @@ class QrdeJob final : public ThreadPoolWork { Histogram::RecordedSnapshotSource snapshot_source, std::vector<double> probabilities, QrdeDequantization dequantization) - : ThreadPoolWork(env, "histogram.qrde"), + : ThreadPoolWork(env, ThreadPoolWorkType::kHistogramQrde), histogram_(std::move(histogram)), snapshot_source_(std::move(snapshot_source)), probabilities_(std::move(probabilities)), @@ -1291,11 +1291,10 @@ constexpr uint64_t kEwmaThreshold = 4; Histogram::MeanCIResult Histogram::MeanCI(double confidence) const { RwLock::ScopedReadLock lock(mutex_); int64_t count = histogram_->total_count; + double nan = std::numeric_limits<double>::quiet_NaN(); + if (count == 0) return {nan, nan, nan}; double mean = hdr_mean(histogram_.get()); - if (count < 2) { - double nan = std::numeric_limits<double>::quiet_NaN(); - return {mean, nan, nan}; - } + if (count < 2) return {mean, nan, nan}; double stddev = hdr_stddev(histogram_.get()); if (stddev == 0.0) return {mean, mean, mean}; diff --git a/src/inspector/main_thread_interface.cc b/src/inspector/main_thread_interface.cc index 0fca7483e95c..d4822598e17b 100644 --- a/src/inspector/main_thread_interface.cc +++ b/src/inspector/main_thread_interface.cc @@ -200,6 +200,10 @@ class ThreadSafeDelegate : public InspectorSessionDelegate { MainThreadInterface::MainThreadInterface(Agent* agent) : agent_(agent) {} MainThreadInterface::~MainThreadInterface() { + Disconnect(); +} + +void MainThreadInterface::Disconnect() { if (handle_) handle_->Reset(); } diff --git a/src/inspector/main_thread_interface.h b/src/inspector/main_thread_interface.h index 3311f9df014a..99fee99596c6 100644 --- a/src/inspector/main_thread_interface.h +++ b/src/inspector/main_thread_interface.h @@ -80,6 +80,7 @@ class MainThreadInterface : explicit MainThreadInterface(Agent* agent); ~MainThreadInterface(); + void Disconnect(); void DispatchMessages(); void Post(std::unique_ptr<Request> request); bool WaitForFrontendEvent(); diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index cfa2f2adb9d1..a86fde0e14f6 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -335,21 +335,28 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel, std::vector<uint8_t> cbor_buffer; ConvertJSONToCBOR(crdtp::SpanFrom(raw_message), &cbor_buffer); - Dispatchable dispatchable(crdtp::SpanFrom(cbor_buffer)); + // TODO(legendecas): The fallthrough callback captures a raw `this`. That is + // safe only while every command in node_protocol_config.json is + // synchronous. An async command stores the callback and may invoke it + // after this session is gone, so add a lifetime guard before adding one. + Dispatchable dispatchable( + crdtp::SpanFrom(cbor_buffer), + std::string_view(), + [this](int call_id, + crdtp::span<uint8_t> method, + crdtp::span<uint8_t> serialized_message, + std::string_view associated_data) { + per_process::Debug(DebugCategory::INSPECTOR_SERVER, + "[inspector] method not found\n"); + node_dispatcher_->SendMethodNotFound(call_id, method); + }); crdtp::span<uint8_t> method = dispatchable.Method(); if (v8_inspector::V8InspectorSession::canDispatchMethod( StringView(method.data(), method.size()))) { session_->dispatchProtocolMessage(message); return; } - UberDispatcher::DispatchResult result = - node_dispatcher_->Dispatch(dispatchable); - if (!result.MethodFound()) { - per_process::Debug(DebugCategory::INSPECTOR_SERVER, - "[inspector] method not found\n"); - // Fall through to send a method not found error. - } - result.Run(); + node_dispatcher_->Dispatch(dispatchable); } void schedulePauseOnNextStatement(const std::string& reason) { @@ -442,13 +449,6 @@ class ChannelImpl final : public v8_inspector::V8Inspector::Channel, sendMessageToFrontend(json); } - // crdtp::FrontendChannel - void FallThrough(int call_id, - crdtp::span<uint8_t> method, - crdtp::span<uint8_t> message) override { - DCHECK(false); - } - std::unique_ptr<protocol::RuntimeAgent> runtime_agent_; #ifndef V8_USE_PERFETTO std::unique_ptr<protocol::TracingAgent> tracing_agent_; @@ -535,6 +535,11 @@ class NodeInspectorClient : public V8InspectorClient { } } + ~NodeInspectorClient() override { + // Close the handle before the interface can lose its last strong reference. + if (interface_) interface_->Disconnect(); + } + void runMessageLoopOnPause(int context_group_id) override { waiting_for_resume_ = true; runMessageLoop(); diff --git a/src/json_utils.h b/src/json_utils.h index e75556578522..6d220b4c8588 100644 --- a/src/json_utils.h +++ b/src/json_utils.h @@ -5,7 +5,7 @@ #include "node_concepts.h" -#include <iomanip> +#include <charconv> #include <limits> #include <ostream> #include <string> @@ -26,31 +26,44 @@ std::string Reindent(const std::string& str, int indentation); // JSON compiler definitions. class JSONWriter { public: - JSONWriter(std::ostream& out, bool compact) - : out_(out), compact_(compact) {} + JSONWriter(std::ostream& out, bool compact) : out_(&out), compact_(compact) {} + JSONWriter(std::string& out, bool compact) + : string_out_(&out), compact_(compact) {} private: + inline void write(char ch) { + if (string_out_ != nullptr) + *string_out_ += ch; + else + *out_ << ch; + } + inline void write(std::string_view str) { + if (string_out_ != nullptr) + string_out_->append(str); + else + *out_ << str; + } inline void indent() { indent_ += 2; } inline void deindent() { indent_ -= 2; } inline void advance() { if (compact_) return; - for (int i = 0; i < indent_; i++) out_ << ' '; + for (int i = 0; i < indent_; i++) write(' '); } inline void write_one_space() { if (compact_) return; - out_ << ' '; + write(' '); } inline void write_new_line() { if (compact_) return; - out_ << '\n'; + write('\n'); } public: inline void json_start() { - if (state_ == kAfterValue) out_ << ','; + if (state_ == kAfterValue) write(','); write_new_line(); advance(); - out_ << '{'; + write('{'); indent(); state_ = kObjectStart; } @@ -59,31 +72,31 @@ class JSONWriter { write_new_line(); deindent(); advance(); - out_ << '}'; + write('}'); state_ = kAfterValue; } template <typename T> inline void json_objectstart(T key) { - if (state_ == kAfterValue) out_ << ','; + if (state_ == kAfterValue) write(','); write_new_line(); advance(); write_string(key); - out_ << ':'; + write(':'); write_one_space(); - out_ << '{'; + write('{'); indent(); state_ = kObjectStart; } template <typename T> inline void json_arraystart(T key) { - if (state_ == kAfterValue) out_ << ','; + if (state_ == kAfterValue) write(','); write_new_line(); advance(); write_string(key); - out_ << ':'; + write(':'); write_one_space(); - out_ << '['; + write('['); indent(); state_ = kObjectStart; } @@ -91,10 +104,10 @@ class JSONWriter { write_new_line(); deindent(); advance(); - out_ << '}'; + write('}'); if (indent_ == 0) { // Top-level object is complete, so end the line. - out_ << '\n'; + write('\n'); } state_ = kAfterValue; } @@ -103,16 +116,16 @@ class JSONWriter { write_new_line(); deindent(); advance(); - out_ << ']'; + write(']'); state_ = kAfterValue; } template <typename T, typename U> inline void json_keyvalue(const T& key, const U& value) { - if (state_ == kAfterValue) out_ << ','; + if (state_ == kAfterValue) write(','); write_new_line(); advance(); write_string(key); - out_ << ':'; + write(':'); write_one_space(); write_value(value); state_ = kAfterValue; @@ -120,7 +133,7 @@ class JSONWriter { template <typename U> inline void json_element(const U& value) { - if (state_ == kAfterValue) out_ << ','; + if (state_ == kAfterValue) write(','); write_new_line(); advance(); write_value(value); @@ -136,30 +149,53 @@ class JSONWriter { private: template <NumericValue T> inline void write_value(T number) { - if constexpr (std::is_same<T, bool>::value) - out_ << (number ? "true" : "false"); - else - out_ << number; + if constexpr (std::is_same_v<T, bool>) { + write(number ? "true" : "false"); + } else if constexpr (std::is_same_v<T, char> || + std::is_same_v<T, signed char> || + std::is_same_v<T, unsigned char>) { + write(static_cast<char>(number)); + } else { + if (out_ != nullptr) { + *out_ << number; + return; + } + // Enough for any integer, or a floating-point value with six digits + // and an exponent. Match the default ostream precision. + char buffer[128]; + std::to_chars_result result; + if constexpr (std::is_floating_point_v<T>) { + result = std::to_chars(buffer, + buffer + sizeof(buffer), + number, + std::chars_format::general, + 6); + } else { + result = std::to_chars(buffer, buffer + sizeof(buffer), number); + } + string_out_->append(buffer, result.ptr); + } } - inline void write_value(Null null) { out_ << "null"; } + inline void write_value(Null null) { write("null"); } inline void write_value(std::string_view str) { write_string(str); } inline void write_value(const ForeignJSON& json) { - out_ << Reindent(json.as_string, indent_); + write(Reindent(json.as_string, indent_)); } inline void write_string(std::string_view str) { - out_ << '"'; + write('"'); if (NeedsJsonEscape(str)) // only create temporary std::string if necessary - out_ << EscapeJsonChars(str); + write(EscapeJsonChars(str)); else - out_ << str; - out_ << '"'; + write(str); + write('"'); } enum JSONState { kObjectStart, kAfterValue }; - std::ostream& out_; + std::ostream* out_ = nullptr; + std::string* string_out_ = nullptr; bool compact_; int indent_ = 0; int state_ = kObjectStart; diff --git a/src/module_wrap.cc b/src/module_wrap.cc index 9892f38d96bd..f95313efb58c 100644 --- a/src/module_wrap.cc +++ b/src/module_wrap.cc @@ -28,6 +28,7 @@ using v8::ArrayBufferView; using v8::Boolean; using v8::Context; using v8::Data; +using v8::DictionaryTemplate; using v8::EscapableHandleScope; using v8::Exception; using v8::FixedArray; @@ -570,9 +571,13 @@ static Local<Object> createImportAttributesContainer( Local<FixedArray> raw_attributes, const int elements_per_attribute) { CHECK_EQ(raw_attributes->Length() % elements_per_attribute, 0); - size_t num_attributes = raw_attributes->Length() / elements_per_attribute; - LocalVector<Name> names(isolate, num_attributes); - LocalVector<Value> values(isolate, num_attributes); + Local<Context> context = realm->context(); + + // v8::Object::New() with a prototype argument always creates the object in + // dictionary mode. Null the prototype of an ordinary object instead, so that + // the attributes, which the loader reads for every import, get a fast map. + Local<Object> attributes = Object::New(isolate); + attributes->SetPrototype(context, Null(isolate)).Check(); for (int i = 0; i < raw_attributes->Length(); i += elements_per_attribute) { Local<Data> key = raw_attributes->Get(i); @@ -580,15 +585,12 @@ static Local<Object> createImportAttributesContainer( DCHECK(DataIsString(key)); DCHECK(DataIsString(value)); - int idx = i / elements_per_attribute; - names[idx] = key.As<String>(); - values[idx] = value.As<String>(); + attributes + ->CreateDataProperty(context, key.As<String>(), value.As<String>()) + .Check(); } - Local<Object> attributes = Object::New( - isolate, Null(isolate), names.data(), values.data(), num_attributes); - attributes->SetIntegrityLevel(realm->context(), v8::IntegrityLevel::kFrozen) - .Check(); + attributes->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen).Check(); return attributes; } @@ -598,6 +600,21 @@ static Local<Array> createModuleRequestsContainer( Local<Context> context = realm->context(); LocalVector<Value> requests(isolate, raw_requests->Length()); + // v8::Object::New() with names and values always creates the object in + // dictionary mode. Use a DictionaryTemplate instead so that the requests, + // which the loader reads for every import while linking, get a fast map. + Environment* env = realm->env(); + Local<DictionaryTemplate> tmpl = env->module_request_template(); + if (tmpl.IsEmpty()) { + static constexpr std::string_view names[] = { + "specifier", + "attributes", + "phase", + }; + tmpl = DictionaryTemplate::New(isolate, names); + env->set_module_request_template(tmpl); + } + for (int i = 0; i < raw_requests->Length(); i++) { DCHECK(raw_requests->Get(i)->IsModuleRequest()); Local<ModuleRequest> module_request = @@ -612,20 +629,14 @@ static Local<Array> createModuleRequestsContainer( createImportAttributesContainer(realm, isolate, raw_attributes, 3); ModuleImportPhase phase = module_request->GetPhase(); - Local<Name> names[] = { - realm->isolate_data()->specifier_string(), - realm->isolate_data()->attributes_string(), - realm->isolate_data()->phase_string(), - }; - Local<Value> values[] = { + MaybeLocal<Value> values[] = { specifier, attributes, Integer::New(isolate, to_phase_constant(phase)), }; - DCHECK_EQ(arraysize(names), arraysize(values)); Local<Object> request = - Object::New(isolate, Null(isolate), names, values, arraysize(names)); + NewDictionaryInstanceNullProto(context, tmpl, values).ToLocalChecked(); request->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen).Check(); requests[i] = request; @@ -1362,7 +1373,7 @@ static Maybe<void> DefaultImportMetaObjectInitializer(Realm* realm, } // Set a lazy getter of import.meta.resolve - only if the initializer is set, - // which is only the case when run on a non-loader-hook thread. + // which happens once the cascaded loader has been initialized. Local<Function> import_meta_resolve_initializer = realm->host_import_meta_resolve_initializer(); if (!import_meta_resolve_initializer.IsEmpty() && diff --git a/src/node.cc b/src/node.cc index 8f1a3eaf4980..6c9b51bfb5e8 100644 --- a/src/node.cc +++ b/src/node.cc @@ -186,7 +186,7 @@ const char* conf_section_name = STRINGIFY(NODE_OPENSSL_CONF_NAME); #ifdef __POSIX__ void SignalExit(int signo, siginfo_t* info, void* ucontext) { - ResetStdio(); + ResetStdio(true); raise(signo); } #endif // __POSIX__ @@ -242,6 +242,9 @@ void Environment::InitializeDiagnostics() { if (heap_snapshot_near_heap_limit_ > 0) { AddHeapSnapshotNearHeapLimitCallback(); } + if (ShouldWarnAboutPointerCompressionHeap()) { + AddPointerCompressionHeapWarningCallback(); + } if (options_->trace_uncaught) isolate_->SetCaptureStackTraceForUncaughtExceptions(true); if (options_->trace_promises) { @@ -447,7 +450,7 @@ void TrapWebAssemblyOrContinue(int signo, siginfo_t* info, void* ucontext) { sa.sa_handler = SIG_DFL; CHECK_EQ(sigaction(signo, &sa, nullptr), 0); - ResetStdio(); + ResetStdio(true); raise(signo); } } @@ -497,6 +500,14 @@ static struct { } stdio[1 + STDERR_FILENO]; #endif // __POSIX__ +// Set once Node.js changes the terminal mode itself. Accessed from signal +// handlers, so it must be lock-free. +static std::atomic<bool> terminal_mode_changed{false}; + +void SetTerminalModeChanged() { + terminal_mode_changed.store(true, std::memory_order_relaxed); +} + void ResetSignalHandlers() { #ifdef __POSIX__ // Restore signal dispositions, the parent process may have changed them. @@ -541,7 +552,7 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) { init_process_flags.store(flags); if (!(flags & ProcessInitializationFlags::kNoStdioInitialization)) { - atexit(ResetStdio); + atexit([]() { ResetStdio(); }); } #ifdef __POSIX__ @@ -665,7 +676,7 @@ static void PlatformInit(ProcessInitializationFlags::Flags flags) { } // Safe to call more than once and from signal handlers. -void ResetStdio() { +void ResetStdio(bool force_terminal_restore) { if (init_process_flags.load() & ProcessInitializationFlags::kNoStdioInitialization) { return; @@ -673,6 +684,15 @@ void ResetStdio() { uv_tty_reset_mode(); #ifdef __POSIX__ + // Only write back the terminal attributes recorded at startup when Node.js + // changed the terminal mode itself, or when exiting because of a signal. + // Another process sharing the terminal (e.g. a pager in `node -h | less`) + // may have changed them in the meantime, and a process that never touched + // the terminal has nothing to restore. + const bool restore_terminal = + force_terminal_restore || + terminal_mode_changed.load(std::memory_order_relaxed); + for (auto& s : stdio) { const int fd = &s - stdio; @@ -704,7 +724,7 @@ void ResetStdio() { CHECK_NE(err, -1); } - if (s.isatty) { + if (s.isatty && restore_terminal) { sigset_t sa; int err; diff --git a/src/node_api.cc b/src/node_api.cc index b7854c2fe424..64d26a7a502e 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -1219,7 +1219,7 @@ class Work : public node::AsyncResource, public node::ThreadPoolWork { env->isolate, async_resource, node::Utf8Value(env->isolate, async_resource_name).ToStringView()), - ThreadPoolWork(env->node_env(), "node_api"), + ThreadPoolWork(env->node_env(), node::ThreadPoolWorkType::kNodeApi), _env(env), _data(data), _execute(execute), diff --git a/src/node_blob.cc b/src/node_blob.cc index ab4267fb81f0..bdc10ab2ad79 100644 --- a/src/node_blob.cc +++ b/src/node_blob.cc @@ -584,10 +584,7 @@ void BlobBindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - BlobBindingData* binding = realm->AddBindingData<BlobBindingData>(holder); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BlobBindingData>(context, holder); } bool BlobBindingData::PrepareForSerialization(Local<Context> context, @@ -600,9 +597,7 @@ bool BlobBindingData::PrepareForSerialization(Local<Context> context, InternalFieldInfoBase* BlobBindingData::Serialize(int index) { DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = - InternalFieldInfoBase::New<InternalFieldInfo>(type()); - return info; + return InternalFieldInfoBase::New<InternalFieldInfo>(type()); } void Blob::RegisterExternalReferences(ExternalReferenceRegistry* registry) { diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 448ef5b6049e..e7accbbe8d3f 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1013,33 +1013,23 @@ int64_t IndexOfOffset(size_t length, } } -void IndexOfString(const FunctionCallbackInfo<Value>& args) { - Environment* env = Environment::GetCurrent(args); - Isolate* isolate = env->isolate(); - - CHECK(args[1]->IsString()); - CHECK(args[2]->IsNumber()); - CHECK(args[3]->IsInt32()); - CHECK(args[4]->IsBoolean()); - CHECK(args[5]->IsNumber()); - - enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value()); - - THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); - ArrayBufferViewContents<char> buffer(args[0]); - - Local<String> needle = args[1].As<String>(); - int64_t offset_i64 = args[2].As<Integer>()->Value(); - bool is_forward = args[4]->IsTrue(); - int64_t end_i64 = args[5].As<Integer>()->Value(); - - const char* haystack = buffer.data(); - // Round down to the nearest multiple of 2 in case of UCS2. - const size_t haystack_length = (enc == UCS2) ? - buffer.length() &~ 1 : buffer.length(); // NOLINT(whitespace/operators) - - size_t needle_length; - if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return; +// Resolves the range searched by IndexOfString() and IndexOfBuffer(). Returns +// false if the result is known without searching, in which case +// `*early_result` holds the value to return. Otherwise, sets `*offset` to the +// position to start searching from and `*search_end` to the exclusive upper +// bound of the search range. If `align_ucs2_offset` is true, forward UCS-2 +// searches start at an even byte offset. +bool GetIndexOfSearchRange(size_t haystack_length, + size_t needle_length, + int64_t offset_i64, + int64_t end_i64, + bool is_forward, + enum encoding enc, + bool align_ucs2_offset, + size_t* offset_out, + size_t* search_end_out, + double* early_result) { + *early_result = -1; // search_end is the exclusive upper bound of the search range. size_t search_end = static_cast<size_t>(std::min( @@ -1055,33 +1045,79 @@ void IndexOfString(const FunctionCallbackInfo<Value>& args) { // Match String#indexOf() and String#lastIndexOf() behavior, // but clamp to search_end. int64_t clamped = std::min(opt_offset, static_cast<int64_t>(search_end)); - args.GetReturnValue().Set(static_cast<double>(clamped)); - return; - } - - if (haystack_length == 0) { - return args.GetReturnValue().Set(-1); + *early_result = static_cast<double>(clamped); + return false; } - if (opt_offset <= -1) { - return args.GetReturnValue().Set(-1); + if (haystack_length == 0 || opt_offset <= -1) { + return false; } size_t offset = static_cast<size_t>(opt_offset); // For backward search, clamp start to within the search range. if (!is_forward && offset >= search_end) { - if (search_end == 0) return args.GetReturnValue().Set(-1); + if (search_end == 0) return false; offset = search_end - 1; } else if (is_forward && offset >= search_end) { - return args.GetReturnValue().Set(-1); + return false; } - if (enc == UCS2 && is_forward) { + if (align_ucs2_offset && enc == UCS2 && is_forward) { offset += offset % sizeof(uint16_t); - if (offset >= search_end) return args.GetReturnValue().Set(-1); + if (offset >= search_end) return false; } CHECK_LT(offset, haystack_length); if ((is_forward && needle_length + offset > search_end) || needle_length > search_end) { - return args.GetReturnValue().Set(-1); + return false; + } + + *offset_out = offset; + *search_end_out = search_end; + return true; +} + +void IndexOfString(const FunctionCallbackInfo<Value>& args) { + Environment* env = Environment::GetCurrent(args); + Isolate* isolate = env->isolate(); + + CHECK(args[1]->IsString()); + CHECK(args[2]->IsNumber()); + CHECK(args[3]->IsInt32()); + CHECK(args[4]->IsBoolean()); + CHECK(args[5]->IsNumber()); + + enum encoding enc = static_cast<enum encoding>(args[3].As<Int32>()->Value()); + + THROW_AND_RETURN_UNLESS_BUFFER(env, args[0]); + ArrayBufferViewContents<char> buffer(args[0]); + + Local<String> needle = args[1].As<String>(); + int64_t offset_i64 = args[2].As<Integer>()->Value(); + bool is_forward = args[4]->IsTrue(); + int64_t end_i64 = args[5].As<Integer>()->Value(); + + const char* haystack = buffer.data(); + // Round down to the nearest multiple of 2 in case of UCS2. + const size_t haystack_length = + (enc == UCS2) ? buffer.length() & ~1 + : buffer.length(); // NOLINT(whitespace/operators) + + size_t needle_length; + if (!StringBytes::Size(isolate, needle, enc).To(&needle_length)) return; + + size_t offset; + size_t search_end; + double early_result; + if (!GetIndexOfSearchRange(haystack_length, + needle_length, + offset_i64, + end_i64, + is_forward, + enc, + true, + &offset, + &search_end, + &early_result)) { + return args.GetReturnValue().Set(early_result); } size_t result = search_end; @@ -1172,43 +1208,20 @@ void IndexOfBuffer(const FunctionCallbackInfo<Value>& args) { const char* needle = needle_contents.data(); const size_t needle_length = needle_contents.length(); - // search_end is the exclusive upper bound of the search range. - size_t search_end = static_cast<size_t>(std::min( - std::max(end_i64, int64_t{0}), static_cast<int64_t>(haystack_length))); - if (enc == UCS2) search_end &= ~static_cast<size_t>(1); - - int64_t opt_offset = IndexOfOffset(haystack_length, - offset_i64, - needle_length, - is_forward); - - if (needle_length == 0) { - // Match String#indexOf() and String#lastIndexOf() behavior, - // but clamp to search_end. - int64_t clamped = std::min(opt_offset, static_cast<int64_t>(search_end)); - args.GetReturnValue().Set(static_cast<double>(clamped)); - return; - } - - if (haystack_length == 0) { - return args.GetReturnValue().Set(-1); - } - - if (opt_offset <= -1) { - return args.GetReturnValue().Set(-1); - } - size_t offset = static_cast<size_t>(opt_offset); - // For backward search, clamp start to within the search range. - if (!is_forward && offset >= search_end) { - if (search_end == 0) return args.GetReturnValue().Set(-1); - offset = search_end - 1; - } else if (is_forward && offset >= search_end) { - return args.GetReturnValue().Set(-1); - } - CHECK_LT(offset, haystack_length); - if ((is_forward && needle_length + offset > search_end) || - needle_length > search_end) { - return args.GetReturnValue().Set(-1); + size_t offset; + size_t search_end; + double early_result; + if (!GetIndexOfSearchRange(haystack_length, + needle_length, + offset_i64, + end_i64, + is_forward, + enc, + false, + &offset, + &search_end, + &early_result)) { + return args.GetReturnValue().Set(early_result); } size_t result = search_end; diff --git a/src/node_contextify.cc b/src/node_contextify.cc index 989ce5d6750c..ed76490bf282 100644 --- a/src/node_contextify.cc +++ b/src/node_contextify.cc @@ -1014,8 +1014,7 @@ void ContextifyScript::New(const FunctionCallbackInfo<Value>& args) { ContextifyScript* contextify_script = New(env, args.This()); - if (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( - TRACING_CATEGORY_NODE2(vm, script)) != 0) { + if (TRACE_EVENT_CATEGORY_ENABLED(TRACING_CATEGORY_NODE2(vm, script))) { Utf8Value fn(isolate, filename); TRACE_EVENT_BEGIN1(TRACING_CATEGORY_NODE2(vm, script), "ContextifyScript::New", diff --git a/src/node_diagnostics_channel.cc b/src/node_diagnostics_channel.cc index 2cc3309542ff..b569214571b7 100644 --- a/src/node_diagnostics_channel.cc +++ b/src/node_diagnostics_channel.cc @@ -3,6 +3,7 @@ #include "base_object-inl.h" #include "env-inl.h" #include "node_external_reference.h" +#include "node_internals.h" #include "util-inl.h" #include "v8.h" @@ -109,6 +110,7 @@ void BindingData::LinkNativeChannel(const FunctionCallbackInfo<Value>& args) { } } } + realm->env()->InitializeThreadPoolWorkChannels(); } bool BindingData::PrepareForSerialization(Local<Context> context, @@ -117,6 +119,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, internal_field_info_ = InternalFieldInfoBase::New<InternalFieldInfo>(type()); internal_field_info_->subscribers = subscribers_.Serialize(context, creator); internal_field_info_->subscribers_capacity = subscribers_.Length(); + channel_status_callbacks_.clear(); link_callback_.Reset(); channel_wrap_template_.Reset(); DetachChannels(); @@ -125,10 +128,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, } InternalFieldInfoBase* BindingData::Serialize(int index) { - DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = internal_field_info_; - internal_field_info_ = nullptr; - return info; + return TakeInternalFieldInfo(index, &internal_field_info_); } void BindingData::Deserialize(Local<Context> context, @@ -136,11 +136,8 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - BindingData* binding = realm->AddBindingData<BindingData>( - holder, static_cast<InternalFieldInfo*>(info)); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>( + context, holder, static_cast<InternalFieldInfo*>(info)); } void BindingData::SetChannelStatusCallback(uint32_t index, diff --git a/src/node_diagnostics_channel.h b/src/node_diagnostics_channel.h index b1da5fcee3da..596ee7fe1689 100644 --- a/src/node_diagnostics_channel.h +++ b/src/node_diagnostics_channel.h @@ -90,6 +90,8 @@ class Channel : public BaseObject { static BaseObjectPtr<Channel> Get(Environment* env, std::string_view name); + uint32_t index() const { return index_; } + inline bool HasSubscribers() const { return binding_data_ != nullptr && binding_data_->subscribers_[index_] > 0; } diff --git a/src/node_dir.cc b/src/node_dir.cc index ca7fc340bcdb..957444eea331 100644 --- a/src/node_dir.cc +++ b/src/node_dir.cc @@ -61,8 +61,7 @@ static const char* get_dir_func_name_by_type(uv_fs_type req_type) { #define TRACE_NAME(name) "fs_dir.sync." #name #define GET_TRACE_ENABLED \ - (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( \ - TRACING_CATEGORY_NODE2(fs_dir, sync)) != 0) + TRACE_EVENT_CATEGORY_ENABLED(TRACING_CATEGORY_NODE2(fs_dir, sync)) #define FS_DIR_SYNC_TRACE(syscall) \ if (GET_TRACE_ENABLED) { \ TRACE_EVENT0(TRACING_CATEGORY_NODE2(fs_dir, sync), TRACE_NAME(syscall)); \ diff --git a/src/node_file.cc b/src/node_file.cc index b96771217b83..e9423a378daa 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -103,6 +103,18 @@ constexpr char kPathSeparator = '/'; const char* const kPathSeparator = "\\/"; #endif +// Returns the request wrap of an asynchronous fs call, which bindings receive +// as the argument at `index`, or nullptr for a synchronous call (when fewer +// arguments were passed). +static FSReqBase* GetAsyncReqWrap(const FunctionCallbackInfo<Value>& args, + int index, + bool use_bigint = false) { + if (args.Length() <= index) return nullptr; + FSReqBase* req_wrap_async = GetReqWrap(args, index, use_bigint); + CHECK_NOT_NULL(req_wrap_async); + return req_wrap_async; +} + inline int64_t GetOffset(Local<Value> value) { return IsSafeJsInt(value) ? value.As<Integer>()->Value() : -1; } @@ -153,8 +165,21 @@ static const char* get_fs_func_name_by_type(uv_fs_type req_type) { #define TRACE_NAME(name) "fs.sync." #name #define GET_TRACE_ENABLED \ - (*TRACE_EVENT_API_GET_CATEGORY_GROUP_ENABLED( \ - TRACING_CATEGORY_NODE2(fs, sync)) != 0) + TRACE_EVENT_CATEGORY_ENABLED(TRACING_CATEGORY_NODE2(fs, sync)) +// Checks a permission for an fs binding. A denial is reported through +// `req_wrap_async` for an asynchronous call, or thrown for a synchronous call +// (when `req_wrap_async` is nullptr). +#define FS_THROW_IF_INSUFFICIENT_PERMISSIONS( \ + env, req_wrap_async, perm, resource) \ + do { \ + if ((req_wrap_async) != nullptr) { \ + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( \ + env, req_wrap_async, perm, resource); \ + } else { \ + THROW_IF_INSUFFICIENT_PERMISSIONS(env, perm, resource); \ + } \ + } while (0) + #define FS_SYNC_TRACE_BEGIN(syscall, ...) \ if (GET_TRACE_ENABLED) \ TRACE_EVENT_BEGIN( \ @@ -1040,9 +1065,8 @@ void Access(const FunctionCallbackInfo<Value>& args) { CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - if (argc > 2) { // access(path, mode, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + if (req_wrap_async != nullptr) { // access(path, mode, req) ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( env, req_wrap_async, @@ -1081,9 +1105,8 @@ void Close(const FunctionCallbackInfo<Value>& args) { } env->RemoveUnmanagedFd(fd); - if (argc > 1) { // close(fd, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 1); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 1); + if (req_wrap_async != nullptr) { // close(fd, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_CLOSE, req_wrap_async) AsyncCall( env, req_wrap_async, args, "close", UTF8, AfterNoArgs, uv_fs_close, fd); @@ -1173,16 +1196,16 @@ static void Stat(const FunctionCallbackInfo<Value>& args) { ToNamespacedPath(env, &path); bool use_bigint = args[1]->IsTrue(); - if (!args[2]->IsUndefined()) { // stat(path, use_bigint, req, - // do_not_throw_if_no_entry) + FSReqBase* req_wrap_async = + !args[2]->IsUndefined() ? GetAsyncReqWrap(args, 2, use_bigint) : nullptr; + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + path.ToStringView()); + if (req_wrap_async != nullptr) { // stat(path, use_bigint, req, + // do_not_throw_if_no_entry) bool do_not_throw_if_no_entry = args[3]->IsFalse(); - FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_STAT, req_wrap_async, "path", TRACE_STR_COPY(*path)) if (do_not_throw_if_no_entry) { @@ -1205,8 +1228,6 @@ static void Stat(const FunctionCallbackInfo<Value>& args) { *path); } } else { // stat(path, use_bigint, undefined, do_not_throw_if_no_entry) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, path.ToStringView()); bool do_not_throw_if_no_entry = args[3]->IsFalse(); FSReqWrapSync req_wrap_sync("stat", *path); FS_SYNC_TRACE_BEGIN(stat); @@ -1337,14 +1358,13 @@ static void StatFs(const FunctionCallbackInfo<Value>& args) { ToNamespacedPath(env, &path); bool use_bigint = args[1]->IsTrue(); - if (argc > 2) { // statfs(path, use_bigint, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2, use_bigint); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2, use_bigint); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + path.ToStringView()); + if (req_wrap_async != nullptr) { // statfs(path, use_bigint, req) FS_ASYNC_TRACE_BEGIN1( UV_FS_STATFS, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -1356,8 +1376,6 @@ static void StatFs(const FunctionCallbackInfo<Value>& args) { uv_fs_statfs, *path); } else { // statfs(path, use_bigint) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, path.ToStringView()); FSReqWrapSync req_wrap_sync("statfs", *path); FS_SYNC_TRACE_BEGIN(statfs); int result = @@ -1385,24 +1403,32 @@ static void Symlink(const FunctionCallbackInfo<Value>& args) { BufferValue target(isolate, args[0]); CHECK_NOT_NULL(*target); auto target_view = target.ToStringView(); - // To avoid bypass the symlink target should be allowed to read and write - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, target_view); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, target_view); BufferValue path(isolate, args[1]); CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, path.ToStringView()); CHECK(args[2]->IsInt32()); int flags = args[2].As<Int32>()->Value(); - if (argc > 3) { // symlink(target, path, flags, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // symlink(target, path, flags, req) + // To avoid bypass the symlink target should be allowed to read and write + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + target_view); + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + target_view); + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN2(UV_FS_SYMLINK, req_wrap_async, "target", @@ -1422,6 +1448,15 @@ static void Symlink(const FunctionCallbackInfo<Value>& args) { *path, flags); } else { // symlink(target, path, flags, undefined, ctx) + // To avoid bypass the symlink target should be allowed to read and write + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, permission::PermissionScope::kFileSystemRead, target_view); + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, permission::PermissionScope::kFileSystemWrite, target_view); + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FSReqWrapSync req_wrap_sync("symlink", *target, *path); FS_SYNC_TRACE_BEGIN(symlink); SyncCallAndThrowOnError( @@ -1449,26 +1484,25 @@ static void Link(const FunctionCallbackInfo<Value>& args) { const auto dest_view = dest.ToStringView(); - if (argc > 2) { // link(src, dest, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); - // To avoid bypass the link target should be allowed to read and write - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - src_view); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - src_view); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + // To avoid bypass the link target should be allowed to read and write + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + src_view); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + src_view); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - dest_view); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + dest_view); + if (req_wrap_async != nullptr) { // link(src, dest, req) FS_ASYNC_TRACE_BEGIN2(UV_FS_LINK, req_wrap_async, "src", @@ -1487,14 +1521,6 @@ static void Link(const FunctionCallbackInfo<Value>& args) { *src, *dest); } else { // link(src, dest) - // To avoid bypass the link target should be allowed to read and write - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, src_view); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, src_view); - - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, dest_view); FSReqWrapSync req_wrap_sync("link", *src, *dest); FS_SYNC_TRACE_BEGIN(link); SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_link, *src, *dest); @@ -1512,14 +1538,16 @@ static void ReadLink(const FunctionCallbackInfo<Value>& args) { BufferValue path(isolate, args[0]); CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, path.ToStringView()); const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8); - if (argc > 2) { // readlink(path, encoding, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + if (req_wrap_async != nullptr) { // readlink(path, encoding, req) + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_READLINK, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -1531,6 +1559,8 @@ static void ReadLink(const FunctionCallbackInfo<Value>& args) { uv_fs_readlink, *path); } else { // readlink(path, encoding) + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, permission::PermissionScope::kFileSystemRead, path.ToStringView()); FSReqWrapSync req_wrap_sync("readlink", *path); FS_SYNC_TRACE_BEGIN(readlink); int err = @@ -1564,24 +1594,23 @@ static void Rename(const FunctionCallbackInfo<Value>& args) { CHECK_NOT_NULL(*new_path); ToNamespacedPath(env, &new_path); - if (argc > 2) { // rename(old_path, new_path, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - view_old_path); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - view_old_path); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - new_path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + view_old_path); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + view_old_path); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + new_path.ToStringView()); + if (req_wrap_async != nullptr) { // rename(old_path, new_path, req) FS_ASYNC_TRACE_BEGIN2(UV_FS_RENAME, req_wrap_async, "old_path", @@ -1600,14 +1629,6 @@ static void Rename(const FunctionCallbackInfo<Value>& args) { *old_path, *new_path); } else { // rename(old_path, new_path) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, view_old_path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, view_old_path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - permission::PermissionScope::kFileSystemWrite, - new_path.ToStringView()); FSReqWrapSync req_wrap_sync("rename", *old_path, *new_path); FS_SYNC_TRACE_BEGIN(rename); SyncCallAndThrowOnError( @@ -1630,9 +1651,8 @@ static void FTruncate(const FunctionCallbackInfo<Value>& args) { CHECK(IsSafeJsInt(args[1])); const int64_t len = args[1].As<Integer>()->Value(); - if (argc > 2) { // ftruncate(fd, len, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + if (req_wrap_async != nullptr) { // ftruncate(fd, len, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_FTRUNCATE, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -1662,9 +1682,8 @@ static void Fdatasync(const FunctionCallbackInfo<Value>& args) { return; } - if (argc > 1) { // fdatasync(fd, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 1); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 1); + if (req_wrap_async != nullptr) { // fdatasync(fd, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_FDATASYNC, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -1693,9 +1712,8 @@ static void Fsync(const FunctionCallbackInfo<Value>& args) { return; } - if (argc > 1) { - FSReqBase* req_wrap_async = GetReqWrap(args, 1); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 1); + if (req_wrap_async != nullptr) { FS_ASYNC_TRACE_BEGIN0(UV_FS_FSYNC, req_wrap_async) AsyncCall( env, req_wrap_async, args, "fsync", UTF8, AfterNoArgs, uv_fs_fsync, fd); @@ -1717,14 +1735,13 @@ static void Unlink(const FunctionCallbackInfo<Value>& args) { CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - if (argc > 1) { // unlink(path, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 1); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 1); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); + if (req_wrap_async != nullptr) { // unlink(path, req) FS_ASYNC_TRACE_BEGIN1( UV_FS_UNLINK, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -1736,10 +1753,6 @@ static void Unlink(const FunctionCallbackInfo<Value>& args) { uv_fs_unlink, *path); } else { // unlink(path) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - permission::PermissionScope::kFileSystemWrite, - path.ToStringView()); FSReqWrapSync req_wrap_sync("unlink", *path); FS_SYNC_TRACE_BEGIN(unlink); SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_unlink, *path); @@ -1756,12 +1769,14 @@ static void RMDir(const FunctionCallbackInfo<Value>& args) { BufferValue path(env->isolate(), args[0]); CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, path.ToStringView()); - if (argc > 1) { - FSReqBase* req_wrap_async = GetReqWrap(args, 1); // rmdir(path, req) - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 1); + if (req_wrap_async != nullptr) { // rmdir(path, req) + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_RMDIR, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -1773,6 +1788,10 @@ static void RMDir(const FunctionCallbackInfo<Value>& args) { uv_fs_rmdir, *path); } else { // rmdir(path) + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FSReqWrapSync req_wrap_sync("rmdir", *path); FS_SYNC_TRACE_BEGIN(rmdir); SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_rmdir, *path); @@ -1976,7 +1995,8 @@ int MKDirpSync(uv_loop_t* loop, case UV_EACCES: case UV_ENOSPC: case UV_ENOTDIR: - case UV_EPERM: { + case UV_EPERM: + case UV_EROFS: { return err; } case UV_ENOENT: { @@ -2059,7 +2079,8 @@ int MKDirpAsync( case UV_EACCES: case UV_ENOSPC: case UV_ENOTDIR: - case UV_EPERM: { + case UV_EPERM: + case UV_EROFS: { req_wrap->continuation_data()->Done(err); break; } @@ -2134,18 +2155,19 @@ static void MKDir(const FunctionCallbackInfo<Value>& args) { CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, path.ToStringView()); - CHECK(args[1]->IsInt32()); const int mode = args[1].As<Int32>()->Value(); CHECK(args[2]->IsBoolean()); bool mkdirp = args[2]->IsTrue(); - if (argc > 3) { // mkdir(path, mode, recursive, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // mkdir(path, mode, recursive, req) + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_UNLINK, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -2158,6 +2180,10 @@ static void MKDir(const FunctionCallbackInfo<Value>& args) { *path, mode); } else { // mkdir(path, mode, recursive) + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FSReqWrapSync req_wrap_sync("mkdir", *path); FS_SYNC_TRACE_BEGIN(mkdir); if (mkdirp) { @@ -2196,14 +2222,13 @@ static void RealPath(const FunctionCallbackInfo<Value>& args) { const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8); - if (argc > 2) { // realpath(path, encoding, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + path.ToStringView()); + if (req_wrap_async != nullptr) { // realpath(path, encoding, req) FS_ASYNC_TRACE_BEGIN1( UV_FS_REALPATH, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -2215,8 +2240,6 @@ static void RealPath(const FunctionCallbackInfo<Value>& args) { uv_fs_realpath, *path); } else { // realpath(path, encoding, undefined, ctx) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, path.ToStringView()); FSReqWrapSync req_wrap_sync("realpath", *path); FS_SYNC_TRACE_BEGIN(realpath); int err = @@ -2271,14 +2294,13 @@ static void ReadDir(const FunctionCallbackInfo<Value>& args) { bool with_types = args[2]->IsTrue(); - if (argc > 3) { // readdir(path, encoding, withTypes, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + path.ToStringView()); + if (req_wrap_async != nullptr) { // readdir(path, encoding, withTypes, req) req_wrap_async->set_with_file_types(with_types); FS_ASYNC_TRACE_BEGIN1( UV_FS_SCANDIR, req_wrap_async, "path", TRACE_STR_COPY(*path)) @@ -2292,8 +2314,6 @@ static void ReadDir(const FunctionCallbackInfo<Value>& args) { *path, 0 /*flags*/); } else { // readdir(path, encoding, withTypes) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, path.ToStringView()); FSReqWrapSync req_wrap_sync("scandir", *path); FS_SYNC_TRACE_BEGIN(readdir); int err = SyncCallAndThrowOnError( @@ -2743,7 +2763,7 @@ class ReadDirRecursiveWork final : public ThreadPoolWork { public: ReadDirRecursiveWork(Environment* env, std::shared_ptr<ReadDirRecursiveRequest> request) - : ThreadPoolWork(env, "readdir_recursive"), + : ThreadPoolWork(env, ThreadPoolWorkType::kReadDirRecursive), request_(std::move(request)) {} void DoThreadPoolWork() override { request_->walk()->Run(); } @@ -2779,9 +2799,9 @@ static void ReadDirRecursive(const FunctionCallbackInfo<Value>& args) { // can do those: lib walks the tree in JS when the permission model is on. CHECK(!env->permission()->enabled()); - if (argc > 3) { // readdirRecursive(path, encoding, withTypes, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != + nullptr) { // readdirRecursive(path, encoding, withTypes, req) req_wrap_async->Init("scandir", nullptr, 0, encoding); FS_ASYNC_TRACE_BEGIN1( UV_FS_SCANDIR, req_wrap_async, "path", TRACE_STR_COPY(*path)) @@ -2894,9 +2914,8 @@ static void Open(const FunctionCallbackInfo<Value>& args) { CHECK(args[2]->IsInt32()); const int mode = args[2].As<Int32>()->Value(); - if (argc > 3) { // open(path, flags, mode, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // open(path, flags, mode, req) if (AsyncCheckOpenPermissions(env, req_wrap_async, path, flags).IsNothing()) return; req_wrap_async->set_is_plain_open(true); @@ -3006,19 +3025,18 @@ static void CopyFile(const FunctionCallbackInfo<Value>& args) { CHECK_NOT_NULL(*dest); ToNamespacedPath(env, &dest); - if (argc > 3) { // copyFile(src, dest, flags, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemRead, - src.ToStringView()); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - dest.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemRead, + src.ToStringView()); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + dest.ToStringView()); + if (req_wrap_async != nullptr) { // copyFile(src, dest, flags, req) FS_ASYNC_TRACE_BEGIN2(UV_FS_COPYFILE, req_wrap_async, "src", @@ -3038,12 +3056,6 @@ static void CopyFile(const FunctionCallbackInfo<Value>& args) { *dest, flags); } else { // copyFile(src, dest, flags) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemRead, src.ToStringView()); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - permission::PermissionScope::kFileSystemWrite, - dest.ToStringView()); FSReqWrapSync req_wrap_sync("copyfile", *src, *dest); FS_SYNC_TRACE_BEGIN(copyfile); SyncCallAndThrowOnError( @@ -3163,9 +3175,8 @@ static void WriteBuffers(const FunctionCallbackInfo<Value>& args) { iovs[i] = uv_buf_init(Buffer::Data(chunk), Buffer::Length(chunk)); } - if (argc > 3) { // writeBuffers(fd, chunks, pos, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // writeBuffers(fd, chunks, pos, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -3421,9 +3432,8 @@ static void Read(const FunctionCallbackInfo<Value>& args) { char* buf = buffer_data + off; uv_buf_t uvbuf = uv_buf_init(buf, len); - if (argc > 5) { // read(fd, buffer, offset, len, pos, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 5); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 5); + if (req_wrap_async != nullptr) { // read(fd, buffer, offset, len, pos, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_READ, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -3791,7 +3801,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork { uint64_t limit, bool track_fd) : AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK), - ThreadPoolWork(env, "fs.readfile"), + ThreadPoolWork(env, ThreadPoolWorkType::kFsReadFile), path_(std::move(path)), limit_(limit), flags_(flags), @@ -3979,7 +3989,7 @@ class WriteFileJob final : public AsyncWrap, public ThreadPoolWork { int mode, Local<ArrayBufferView> view) : AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK), - ThreadPoolWork(env, "fs.writefile"), + ThreadPoolWork(env, ThreadPoolWorkType::kFsWriteFile), path_(std::move(path)), flags_(flags), mode_(mode) { @@ -4053,9 +4063,8 @@ static void ReadBuffers(const FunctionCallbackInfo<Value>& args) { iovs[i] = uv_buf_init(Buffer::Data(buffer), Buffer::Length(buffer)); } - if (argc > 3) { // readBuffers(fd, buffers, pos, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // readBuffers(fd, buffers, pos, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_READ, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -4093,15 +4102,17 @@ static void Chmod(const FunctionCallbackInfo<Value>& args) { BufferValue path(env->isolate(), args[0]); CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, path.ToStringView()); CHECK(args[1]->IsInt32()); int mode = args[1].As<Int32>()->Value(); - if (argc > 2) { // chmod(path, mode, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + if (req_wrap_async != nullptr) { // chmod(path, mode, req) + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_CHMOD, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -4114,6 +4125,10 @@ static void Chmod(const FunctionCallbackInfo<Value>& args) { *path, mode); } else { // chmod(path, mode) + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FSReqWrapSync req_wrap_sync("chmod", *path); FS_SYNC_TRACE_BEGIN(chmod); SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_chmod, *path, mode); @@ -4138,9 +4153,8 @@ static void FChmod(const FunctionCallbackInfo<Value>& args) { CHECK(args[1]->IsInt32()); const int mode = args[1].As<Int32>()->Value(); - if (argc > 2) { // fchmod(fd, mode, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + if (req_wrap_async != nullptr) { // fchmod(fd, mode, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_FCHMOD, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -4178,14 +4192,13 @@ static void Chown(const FunctionCallbackInfo<Value>& args) { CHECK(IsSafeJsInt(args[2])); const auto gid = FromV8Value<uv_gid_t, true>(args[2]); - if (argc > 3) { // chown(path, uid, gid, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); + if (req_wrap_async != nullptr) { // chown(path, uid, gid, req) FS_ASYNC_TRACE_BEGIN1( UV_FS_CHOWN, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -4199,10 +4212,6 @@ static void Chown(const FunctionCallbackInfo<Value>& args) { uid, gid); } else { // chown(path, uid, gid) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - permission::PermissionScope::kFileSystemWrite, - path.ToStringView()); FSReqWrapSync req_wrap_sync("chown", *path); FS_SYNC_TRACE_BEGIN(chown); SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_chown, *path, uid, gid); @@ -4230,9 +4239,8 @@ static void FChown(const FunctionCallbackInfo<Value>& args) { CHECK(IsSafeJsInt(args[2])); const auto gid = FromV8Value<uv_gid_t, true>(args[2]); - if (argc > 3) { // fchown(fd, uid, gid, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // fchown(fd, uid, gid, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_FCHOWN, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -4268,14 +4276,13 @@ static void LChown(const FunctionCallbackInfo<Value>& args) { CHECK(IsSafeJsInt(args[2])); const auto gid = FromV8Value<uv_gid_t, true>(args[2]); - if (argc > 3) { // lchown(path, uid, gid, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - path.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); + if (req_wrap_async != nullptr) { // lchown(path, uid, gid, req) FS_ASYNC_TRACE_BEGIN1( UV_FS_LCHOWN, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -4289,10 +4296,6 @@ static void LChown(const FunctionCallbackInfo<Value>& args) { uid, gid); } else { // lchown(path, uid, gid) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - permission::PermissionScope::kFileSystemWrite, - path.ToStringView()); FSReqWrapSync req_wrap_sync("lchown", *path); FS_SYNC_TRACE_BEGIN(lchown); SyncCallAndThrowOnError(env, &req_wrap_sync, uv_fs_lchown, *path, uid, gid); @@ -4309,8 +4312,6 @@ static void UTimes(const FunctionCallbackInfo<Value>& args) { BufferValue path(env->isolate(), args[0]); CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, path.ToStringView()); CHECK(args[1]->IsNumber()); const double atime = args[1].As<Number>()->Value(); @@ -4318,9 +4319,13 @@ static void UTimes(const FunctionCallbackInfo<Value>& args) { CHECK(args[2]->IsNumber()); const double mtime = args[2].As<Number>()->Value(); - if (argc > 3) { // utimes(path, atime, mtime, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // utimes(path, atime, mtime, req) + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_UTIME, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -4334,6 +4339,10 @@ static void UTimes(const FunctionCallbackInfo<Value>& args) { atime, mtime); } else { // utimes(path, atime, mtime) + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FSReqWrapSync req_wrap_sync("utime", *path); FS_SYNC_TRACE_BEGIN(utimes); SyncCallAndThrowOnError( @@ -4359,9 +4368,8 @@ static void FUTimes(const FunctionCallbackInfo<Value>& args) { CHECK(args[2]->IsNumber()); const double mtime = args[2].As<Number>()->Value(); - if (argc > 3) { // futimes(fd, atime, mtime, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // futimes(fd, atime, mtime, req) FS_ASYNC_TRACE_BEGIN0(UV_FS_FUTIME, req_wrap_async) AsyncCall(env, req_wrap_async, @@ -4391,8 +4399,6 @@ static void LUTimes(const FunctionCallbackInfo<Value>& args) { BufferValue path(env->isolate(), args[0]); CHECK_NOT_NULL(*path); ToNamespacedPath(env, &path); - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, permission::PermissionScope::kFileSystemWrite, path.ToStringView()); CHECK(args[1]->IsNumber()); const double atime = args[1].As<Number>()->Value(); @@ -4400,9 +4406,13 @@ static void LUTimes(const FunctionCallbackInfo<Value>& args) { CHECK(args[2]->IsNumber()); const double mtime = args[2].As<Number>()->Value(); - if (argc > 3) { // lutimes(path, atime, mtime, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 3); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 3); + if (req_wrap_async != nullptr) { // lutimes(path, atime, mtime, req) + ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FS_ASYNC_TRACE_BEGIN1( UV_FS_LUTIME, req_wrap_async, "path", TRACE_STR_COPY(*path)) AsyncCall(env, @@ -4416,6 +4426,10 @@ static void LUTimes(const FunctionCallbackInfo<Value>& args) { atime, mtime); } else { // lutimes(path, atime, mtime) + THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + permission::PermissionScope::kFileSystemWrite, + path.ToStringView()); FSReqWrapSync req_wrap_sync("lutime", *path); FS_SYNC_TRACE_BEGIN(lutimes); SyncCallAndThrowOnError( @@ -4447,14 +4461,13 @@ static void Mkdtemp(const FunctionCallbackInfo<Value>& args) { const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8); - if (argc > 2) { // mkdtemp(tmpl, encoding, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); - ASYNC_THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - req_wrap_async, - permission::PermissionScope::kFileSystemWrite, - tmpl.ToStringView()); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + FS_THROW_IF_INSUFFICIENT_PERMISSIONS( + env, + req_wrap_async, + permission::PermissionScope::kFileSystemWrite, + tmpl.ToStringView()); + if (req_wrap_async != nullptr) { // mkdtemp(tmpl, encoding, req) FS_ASYNC_TRACE_BEGIN1( UV_FS_MKDTEMP, req_wrap_async, "path", TRACE_STR_COPY(*tmpl)) AsyncCall(env, @@ -4466,10 +4479,6 @@ static void Mkdtemp(const FunctionCallbackInfo<Value>& args) { uv_fs_mkdtemp, *tmpl); } else { // mkdtemp(tmpl, encoding) - THROW_IF_INSUFFICIENT_PERMISSIONS( - env, - permission::PermissionScope::kFileSystemWrite, - tmpl.ToStringView()); FSReqWrapSync req_wrap_sync("mkdtemp", *tmpl); FS_SYNC_TRACE_BEGIN(mkdtemp); int result = @@ -4504,9 +4513,8 @@ static void Mkstemp(const FunctionCallbackInfo<Value>& args) { const enum encoding encoding = ParseEncoding(isolate, args[1], UTF8); - if (argc > 2) { // mkstemp(tmpl, encoding, req) - FSReqBase* req_wrap_async = GetReqWrap(args, 2); - CHECK_NOT_NULL(req_wrap_async); + FSReqBase* req_wrap_async = GetAsyncReqWrap(args, 2); + if (req_wrap_async != nullptr) { // mkstemp(tmpl, encoding, req) if (AsyncCheckOpenPermissions(env, req_wrap_async, tmpl, kMkstempFlags) .IsNothing()) { return; @@ -4618,8 +4626,8 @@ static void CpSyncCheckPaths(const FunctionCallbackInfo<Value>& args) { std::error_code error_code; auto src_status = dereference - ? std::filesystem::symlink_status(src_path, error_code) - : std::filesystem::status(src_path, error_code); + ? std::filesystem::status(src_path, error_code) + : std::filesystem::symlink_status(src_path, error_code); if (error_code) { #ifdef _WIN32 @@ -4637,9 +4645,7 @@ static void CpSyncCheckPaths(const FunctionCallbackInfo<Value>& args) { bool dest_exists = !error_code && dest_status.type() != std::filesystem::file_type::not_found; - bool src_is_dir = - (src_status.type() == std::filesystem::file_type::directory) || - (dereference && src_status.type() == std::filesystem::file_type::symlink); + bool src_is_dir = src_status.type() == std::filesystem::file_type::directory; auto src_path_str = ConvertPathToUTF8(src_path); auto dest_path_str = ConvertPathToUTF8(dest_path); @@ -5381,7 +5387,7 @@ class CpDirJob final : public AsyncWrap, public ThreadPoolWork { std::string&& dest_display, CpDirOptions options) : AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK), - ThreadPoolWork(env, "fs.cp"), + ThreadPoolWork(env, ThreadPoolWorkType::kFsCp), src_(std::move(src)), dest_(std::move(dest)), dest_display_(std::move(dest_display)), @@ -5632,12 +5638,8 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - InternalFieldInfo* casted_info = static_cast<InternalFieldInfo*>(info); - BindingData* binding = - realm->AddBindingData<BindingData>(holder, casted_info); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>( + context, holder, static_cast<InternalFieldInfo*>(info)); } bool BindingData::PrepareForSerialization(Local<Context> context, @@ -5659,10 +5661,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, } InternalFieldInfoBase* BindingData::Serialize(int index) { - DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = internal_field_info_; - internal_field_info_ = nullptr; - return info; + return TakeInternalFieldInfo(index, &internal_field_info_); } #ifdef _WIN32 diff --git a/src/node_http2.cc b/src/node_http2.cc index 3505d96eba6e..92ca4e7d452f 100644 --- a/src/node_http2.cc +++ b/src/node_http2.cc @@ -848,19 +848,22 @@ void Http2Session::Close(uint32_t code, bool socket_closed) { return; set_closing(); + pending_close_code_ = code; + pending_close_socket_closed_ = socket_closed; + // Do not flush GOAWAY from inside nghttp2_session_mem_recv() callbacks. // ConsumeHTTP2Data() finishes the close once mem_recv returns. if (is_receiving()) { set_close_pending(); - pending_close_code_ = code; - pending_close_socket_closed_ = socket_closed; return; } FinishClose(code, socket_closed); } -void Http2Session::FinishClose(uint32_t code, bool socket_closed) { +void Http2Session::FinishClose(uint32_t code, + bool socket_closed, + int write_status) { CHECK(is_closing()); // Stop reading on the i/o stream @@ -869,15 +872,20 @@ void Http2Session::FinishClose(uint32_t code, bool socket_closed) { stream_->ReadStop(); } - // If the socket is not closed, then attempt to send a closing GOAWAY + // If the socket is still writable, attempt to send a closing GOAWAY // frame. There is no guarantee that this GOAWAY will be received by // the peer but the HTTP/2 spec recommends sending it anyway. We'll // make a best effort. - if (!socket_closed) { + if (!socket_closed && write_status == 0) { Debug(this, "terminating session with code %d", code); CHECK_EQ(nghttp2_session_terminate_session(session_.get(), code), 0); - SendPendingData(); - } else if (stream_ != nullptr) { + if (SendPendingData() != 0) { + // An earlier write still owns the outgoing buffers. Keep the session + // alive until its completion lets us flush the terminal GOAWAY. + set_close_pending(); + return; + } + } else if (socket_closed && stream_ != nullptr) { // so that the previous listener of the socket, typically, JS code of a // (tls) socket will be notified of any activity later stream_->RemoveStreamListener(this); @@ -912,10 +920,12 @@ void Http2Session::FinishClose(uint32_t code, bool socket_closed) { EmitStatistics(); } -void Http2Session::MaybeFinishPendingClose() { - if (!is_close_pending() || is_destroyed()) return; +void Http2Session::MaybeFinishPendingClose(int status) { + if (!is_close_pending() || is_destroyed() || is_receiving() || is_sending()) { + return; + } set_close_pending(false); - FinishClose(pending_close_code_, pending_close_socket_closed_); + FinishClose(pending_close_code_, pending_close_socket_closed_, status); } // Locates an existing known stream by ID. nghttp2 has a similar method @@ -1310,6 +1320,9 @@ int Http2Session::OnFrameNotSent(nghttp2_session* handle, Debug(session, "frame type %d was not sent, code: %d", frame->hd.type, error_code); + if (frame->hd.type == NGHTTP2_HEADERS) + session->HandleInfoHeadersFrame(frame, UV_ECANCELED); + if (error_code == NGHTTP2_ERR_SESSION_CLOSING || error_code == NGHTTP2_ERR_STREAM_CLOSED || error_code == NGHTTP2_ERR_STREAM_CLOSING) { @@ -1351,6 +1364,9 @@ int Http2Session::OnFrameSent(nghttp2_session* handle, Http2Session* session = static_cast<Http2Session*>(user_data); session->statistics_.frame_sent += 1; + if (frame->hd.type == NGHTTP2_HEADERS) + session->HandleInfoHeadersFrame(frame, 0); + // If nghttp2 has internally terminated the session (e.g. due to a protocol // error like oversized frames, padding errors, or HPACK compression // failures), it calls nghttp2_session_terminate_session() directly which @@ -1890,9 +1906,16 @@ void Http2Session::OnStreamAfterWrite(WriteWrap* w, int status) { CHECK(is_write_in_progress()); set_write_in_progress(false); + // ClearOutgoing() may synchronously finish a pending close. + const bool close_pending = is_close_pending(); // Inform all pending writes about their completion. ClearOutgoing(status); + if (close_pending || is_close_pending()) { + MaybeFinishPendingClose(status); + return; + } + if (is_reading_stopped() && !is_write_in_progress() && nghttp2_session_want_read(session_.get())) { @@ -1988,6 +2011,12 @@ void Http2Session::ClearOutgoing(int status) { set_sending(false); + // Completing a request can start the next write. Take the requests that + // belong to the write that has just finished before completing any of them, + // so that the ones of the next write are left alone. + std::vector<OutgoingInfoReq> info_reqs; + info_reqs.swap(outgoing_info_reqs_); + if (!outgoing_buffers_.empty()) { outgoing_storage_.clear(); outgoing_length_ = 0; @@ -2005,9 +2034,14 @@ void Http2Session::ClearOutgoing(int status) { } } + for (const OutgoingInfoReq& req : info_reqs) { + WriteWrap::FromObject(req.req_wrap) + ->Done(req.status != 0 ? req.status : status); + } + // Now that we've finished sending queued data, if there are any pending // RstStreams we should try sending again and then flush them one by one. - if (!pending_rst_streams_.empty()) { + if (status == 0 && !pending_rst_streams_.empty()) { std::vector<int32_t> current_pending_rst_streams; pending_rst_streams_.swap(current_pending_rst_streams); @@ -2022,6 +2056,24 @@ void Http2Session::ClearOutgoing(int status) { } } +// Called when nghttp2 has serialized a HEADERS frame, or has given up on +// sending it. Informational HEADERS frames are always sent before any other +// HEADERS frame of the same stream, and in the order they were submitted in, +// so if the stream still has informational headers pending, this frame is the +// oldest of them. Its request is completed in ClearOutgoing(), once the +// current write to the underlying stream has finished. +void Http2Session::HandleInfoHeadersFrame(const nghttp2_frame* frame, + int status) { + BaseObjectPtr<Http2Stream> stream = FindStream(frame->hd.stream_id); + if (!stream || stream->info_reqs_.empty()) return; + BaseObjectPtr<AsyncWrap> req_wrap = std::move(stream->info_reqs_.front()); + stream->info_reqs_.pop(); + if (req_wrap) { + outgoing_info_reqs_.push_back( + {std::move(req_wrap), std::move(stream), status}); + } +} + void Http2Session::PushOutgoingBuffer(NgHttp2StreamWrite&& write) { outgoing_length_ += write.buf.len; outgoing_buffers_.emplace_back(std::move(write)); @@ -2129,6 +2181,7 @@ uint8_t Http2Session::SendPendingData() { set_write_in_progress(false); ClearOutgoing(res.err); MaybeNotifyGracefulCloseComplete(); + MaybeFinishPendingClose(res.err); } MaybeStopReading(); @@ -2296,6 +2349,9 @@ bool Http2Session::HasWritesOnSocketForStream(Http2Stream* stream) { for (const NgHttp2StreamWrite& wr : outgoing_buffers_) { if (wr.stream.get() == stream) return true; } + for (const OutgoingInfoReq& req : outgoing_info_reqs_) { + if (req.stream.get() == stream) return true; + } return false; } @@ -2400,6 +2456,7 @@ Http2Stream::~Http2Stream() { void Http2Stream::MemoryInfo(MemoryTracker* tracker) const { tracker->TrackField("current_headers", current_headers_); tracker->TrackField("queue", queue_); + tracker->TrackField("info_reqs", info_reqs_); } std::string Http2Stream::diagnostic_name() const { @@ -2524,6 +2581,7 @@ void Http2Stream::CompleteDestroyCleanup() { WriteWrap::FromObject(head.req_wrap)->Done(UV_ECANCELED); queue_.pop(); } + CancelPendingInfoRequests(); // We can destroy the stream now if there are no writes for it // already on the socket. Otherwise, we'll wait for the garbage collector @@ -2570,7 +2628,15 @@ int Http2Stream::SubmitResponse(const Http2Headers& headers, int options) { // Submit informational headers for a stream. -int Http2Stream::SubmitInfo(const Http2Headers& headers) { +void Http2Stream::CancelPendingInfoRequests() { + while (!info_reqs_.empty()) { + BaseObjectPtr<AsyncWrap> req_wrap = std::move(info_reqs_.front()); + info_reqs_.pop(); + if (req_wrap) WriteWrap::FromObject(req_wrap)->Done(UV_ECANCELED); + } +} + +int Http2Stream::SubmitInfo(const Http2Headers& headers, WriteWrap* req_wrap) { CHECK(!this->is_destroyed()); Http2Scope h2scope(this); Debug(this, "sending %d informational headers", headers.length()); @@ -2583,6 +2649,12 @@ int Http2Stream::SubmitInfo(const Http2Headers& headers) { headers.length(), nullptr); CHECK_NE(ret, NGHTTP2_ERR_NOMEM); + if (ret == 0) { + info_reqs_.emplace(req_wrap != nullptr ? req_wrap->GetAsyncWrap() + : nullptr); + } else if (req_wrap != nullptr) { + req_wrap->Dispose(); + } return ret; } @@ -2912,7 +2984,10 @@ ssize_t Http2Stream::Provider::Stream::OnRead(nghttp2_session* handle, Http2Session* session = static_cast<Http2Session*>(user_data); Debug(session, "reading outbound data for stream %d", id); BaseObjectPtr<Http2Stream> stream = session->FindStream(id); - if (!stream) return 0; + // The stream was destroyed without nghttp2 being told. Returning 0 here + // would make nghttp2 send empty DATA frames forever, so have it reset + // the stream instead. + if (!stream) return NGHTTP2_ERR_TEMPORAL_CALLBACK_FAILURE; if (stream->statistics_.first_byte_sent == 0) stream->statistics_.first_byte_sent = uv_hrtime(); CHECK_EQ(id, stream->id()); @@ -3145,6 +3220,19 @@ void Http2Session::Request(const FunctionCallbackInfo<Value>& args) { return; } + // maxSessionMemory is documented to reject new streams while the limit is + // exceeded. CanAddStream() enforces that for peer-initiated streams; apply + // the same memory check to locally initiated requests so that a session + // whose socket is not draining cannot queue frames without bound. Like the + // response header check, queued request bodies are not counted, so large + // uploads do not prevent unrelated requests on the same session. + if (!session->has_available_session_memory(sizeof(Http2Stream), + /* exclude_outbound */ true)) + [[unlikely]] { + Debug(session, "not submitting request: session memory limit exceeded"); + return args.GetReturnValue().Set(false); + } + Debug(session, "request submitted"); int32_t ret = 0; @@ -3275,7 +3363,16 @@ void Http2Stream::Info(const FunctionCallbackInfo<Value>& args) { Local<Array> headers = args[0].As<Array>(); - args.GetReturnValue().Set(stream->SubmitInfo(Http2Headers(env, headers))); + // The optional request object is completed once the HEADERS frame has been + // written to the socket. + WriteWrap* req_wrap = nullptr; + if (args[1]->IsObject()) { + AsyncHooks::DefaultTriggerAsyncIdScope trigger_scope(stream); + req_wrap = stream->CreateWriteWrap(args[1].As<Object>()); + } + + args.GetReturnValue().Set( + stream->SubmitInfo(Http2Headers(env, headers), req_wrap)); } // Submits trailing headers on the Http2Stream diff --git a/src/node_http2.h b/src/node_http2.h index 48dab9537707..972b829425e2 100644 --- a/src/node_http2.h +++ b/src/node_http2.h @@ -347,8 +347,12 @@ class Http2Stream : public AsyncWrap, // Initiate a response on this stream. int SubmitResponse(const Http2Headers& headers, int options); - // Submit informational headers for this stream - int SubmitInfo(const Http2Headers& headers); + // Submit informational headers for this stream. If a request is given, it + // is completed once the HEADERS frame has been written to the socket. + int SubmitInfo(const Http2Headers& headers, WriteWrap* req_wrap = nullptr); + + // Cancels the requests of informational headers that have not been sent. + void CancelPendingInfoRequests(); // Submit trailing headers for this stream int SubmitTrailers(const Http2Headers& headers); @@ -585,6 +589,11 @@ class Http2Stream : public AsyncWrap, std::queue<NgHttp2StreamWrite> queue_; size_t available_outbound_length_ = 0; + // One entry per informational HEADERS frame that has been submitted to + // nghttp2 but not serialized yet, in submission order. An entry is empty + // if no completion callback was requested for that frame. + std::queue<BaseObjectPtr<AsyncWrap>> info_reqs_; + Http2StreamListener stream_listener_; friend class Http2Session; @@ -1068,11 +1077,21 @@ class Http2Session : public AsyncWrap, struct custom_settings_state remote_custom_settings_; std::vector<NgHttp2StreamWrite> outgoing_buffers_; + // Requests of informational HEADERS frames that are part of the current + // write. The stream is retained until the request has been completed, + // because the request refers to it. A status of 0 means that the status of + // the write to the underlying stream is used. + struct OutgoingInfoReq { + BaseObjectPtr<AsyncWrap> req_wrap; + BaseObjectPtr<Http2Stream> stream; + int status; + }; + std::vector<OutgoingInfoReq> outgoing_info_reqs_; std::vector<uint8_t> outgoing_storage_; size_t outgoing_length_ = 0; std::vector<int32_t> pending_rst_streams_; - // Saved arguments for Close() deferred while nghttp2_session_mem_recv() - // callbacks are active. + // Saved arguments for Close() deferred while receiving data or waiting for + // an outgoing write to finish. uint32_t pending_close_code_ = NGHTTP2_NO_ERROR; bool pending_close_socket_closed_ = false; // Count streams that have been rejected while being opened. Exceeding a fixed @@ -1089,8 +1108,9 @@ class Http2Session : public AsyncWrap, void CopyDataIntoOutgoing(const uint8_t* src, size_t src_length); void ClearOutgoing(int status); - void FinishClose(uint32_t code, bool socket_closed); - void MaybeFinishPendingClose(); + void HandleInfoHeadersFrame(const nghttp2_frame* frame, int status); + void FinishClose(uint32_t code, bool socket_closed, int write_status = 0); + void MaybeFinishPendingClose(int status = 0); void MaybeNotifyGracefulCloseComplete(); diff --git a/src/node_internals.h b/src/node_internals.h index bb45d73e9090..282c5fb533cf 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -46,6 +46,10 @@ struct sockaddr; namespace node { +namespace diagnostics_channel { +class Channel; +} + namespace builtins { class BuiltinLoader; } @@ -108,7 +112,14 @@ std::string FormatErrorMessage(v8::Isolate* isolate, const std::string& reason, v8::Local<v8::Message> message, bool add_source_line = true); -void ResetStdio(); // Safe to call more than once and from signal handlers. +// Restores the stdio file descriptors to their startup state. Safe to call +// more than once and from signal handlers. The terminal attributes are only +// restored when Node.js changed the terminal mode itself (see +// SetTerminalModeChanged()) or when |force_terminal_restore| is true. +void ResetStdio(bool force_terminal_restore = false); +// Records that Node.js changed the terminal mode, e.g. through +// tty.ReadStream.prototype.setRawMode(). Safe to call from any thread. +void SetTerminalModeChanged(); #ifdef __POSIX__ void SignalExit(int signal, siginfo_t* info, void* ucontext); #endif @@ -270,6 +281,10 @@ class InternalCallbackScope { inline bool Failed() const { return failed_; } inline void MarkAsFailed() { failed_ = true; } + // For executionAsyncResource() inside a scope that skipped the id stack. + inline uint32_t lazy_depth() const { return lazy_depth_; } + v8::Local<v8::Object> lazy_resource(v8::Isolate* isolate) const; + private: Environment* env_; async_context async_context_; @@ -279,6 +294,12 @@ class InternalCallbackScope { bool failed_ = false; bool pushed_ids_ = false; bool closed_ = false; + bool lazy_ids_ = false; + uint32_t lazy_depth_ = 0; + double prior_async_id_ = 0; + double prior_trigger_async_id_ = 0; + InternalCallbackScope* lazy_prev_ = nullptr; + std::variant<v8::Local<v8::Object>*, v8::Global<v8::Object>*> lazy_resource_; v8::Global<v8::Value> prior_context_frame_; std::optional<v8::Isolate::AllowJavascriptExecutionScope> allow_js_; }; @@ -305,8 +326,10 @@ class DebugSealHandleScope { class ThreadPoolWork { public: - explicit inline ThreadPoolWork(Environment* env, const char* type) - : env_(env), type_(type) { + explicit inline ThreadPoolWork(Environment* env, ThreadPoolWorkType type) + : env_(env), + type_(kThreadPoolWorkNames[static_cast<size_t>(type)].data()), + channel_(env->threadpool_work_channel(type)) { CHECK_NOT_NULL(env); } inline virtual ~ThreadPoolWork() = default; @@ -320,9 +343,19 @@ class ThreadPoolWork { Environment* env() const { return env_; } private: + inline bool IsObserved() const { return enqueued_at_ != 0; } + + inline void PublishDiagnostics(diagnostics_channel::Channel& channel); + Environment* env_; uv_work_t work_req_; const char* type_; + ThreadPoolWorkChannel* channel_ = nullptr; + + // libuv synchronizes these marks between the loop and worker threads. + uint64_t enqueued_at_ = 0; + uint64_t work_start_ = 0; + uint64_t work_end_ = 0; }; // Functions defined in node.cc that are exposed via the bootstrapper object diff --git a/src/node_modules.cc b/src/node_modules.cc index ee9be4557ac1..6aaca483a0cf 100644 --- a/src/node_modules.cc +++ b/src/node_modules.cc @@ -67,9 +67,7 @@ bool BindingData::PrepareForSerialization(v8::Local<v8::Context> context, InternalFieldInfoBase* BindingData::Serialize(int index) { DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = - InternalFieldInfoBase::New<InternalFieldInfo>(type()); - return info; + return InternalFieldInfoBase::New<InternalFieldInfo>(type()); } void BindingData::Deserialize(v8::Local<v8::Context> context, @@ -77,10 +75,7 @@ void BindingData::Deserialize(v8::Local<v8::Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - BindingData* binding = realm->AddBindingData<BindingData>(holder); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>(context, holder); } Local<Array> BindingData::PackageConfig::Serialize(Realm* realm) const { @@ -365,12 +360,17 @@ void BindingData::ParsePackageJSONBinding( PackageConfig package_config{}; package_config.file_path = json_path.ToStringView(); + // Reserve room for the padding that simdjson::pad() appends in + // ParsePackageJSON(), so that it does not reallocate and copy the input. if (args[0]->IsString()) { Utf8Value source(isolate, args[0]); - package_config.raw_json = source.ToString(); + package_config.raw_json.reserve(source.length() + + simdjson::SIMDJSON_PADDING); + package_config.raw_json.assign(*source, source.length()); } else { ArrayBufferViewContents<char> view(args[0]); - package_config.raw_json = std::string(view.data(), view.length()); + package_config.raw_json.reserve(view.length() + simdjson::SIMDJSON_PADDING); + package_config.raw_json.assign(view.data(), view.length()); } if (!ParsePackageJSON( diff --git a/src/node_options.cc b/src/node_options.cc index 2aee993404ee..facbe07d566b 100644 --- a/src/node_options.cc +++ b/src/node_options.cc @@ -384,6 +384,10 @@ void EnvironmentOptions::CheckOptions(std::vector<std::string>* errors, debug_options_.allow_attaching_debugger = false; } + if (!bench_gc.empty() && bench_gc != "none" && bench_gc != "once" && + bench_gc != "sample") { + errors->push_back("invalid value for --bench-gc"); + } if (has_bench_samples && bench_samples == 0) { errors->push_back("--bench-samples must be greater than 0"); } @@ -855,11 +859,6 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { true); AddOption("--experimental-global-webcrypto", "", NoOp{}, kAllowedInEnvvar); AddOption("--experimental-json-modules", "", NoOp{}, kAllowedInEnvvar); - AddOption("--experimental-loader", - "use the specified module as a custom loader", - &EnvironmentOptions::userland_loaders, - kAllowedInEnvvar); - AddAlias("--loader", "--experimental-loader"); AddOption("--experimental-modules", "", NoOp{}, kAllowedInEnvvar); AddOption("--experimental-wasm-modules", "", NoOp{}, kAllowedInEnvvar); AddOption("--experimental-import-text", @@ -1149,6 +1148,12 @@ EnvironmentOptionsParser::EnvironmentOptionsParser() { false, OptionNamespaces::kBenchRunnerNamespace); Implies("--bench", "[has_bench_options]"); + AddOption("--bench-gc", + "run garbage collection before measured benchmark samples", + &EnvironmentOptions::bench_gc, + kAllowedInEnvvar, + OptionNamespaces::kBenchRunnerNamespace); + Implies("--bench-gc", "[has_bench_options]"); AddOption("--bench-isolation", "configures the type of benchmark isolation used in the benchmark " "runner", diff --git a/src/node_options.h b/src/node_options.h index 14f0cc024ef8..6f7be1dfd0d4 100644 --- a/src/node_options.h +++ b/src/node_options.h @@ -99,11 +99,6 @@ class DebugOptions : public Options { break_first_line = true; } - void DisableWaitOrBreakFirstLine() { - inspect_wait = false; - break_first_line = false; - } - bool wait_for_connect() const { return break_first_line || break_node_first_line || inspect_wait; } @@ -147,6 +142,7 @@ class EnvironmentOptions : public Options { std::string heap_snapshot_signal; std::string redirect_warnings; std::string diagnostic_dir; + std::string bench_gc; std::string bench_isolation = "process"; std::string bench_name_pattern; std::string test_rerun_failures_path; @@ -184,7 +180,6 @@ class EnvironmentOptions : public Options { std::vector<std::string> experimental_test_tag_filter; std::vector<std::string> coverage_include_pattern; std::vector<std::string> coverage_exclude_pattern; - std::vector<std::string> userland_loaders; std::vector<std::string> watch_mode_paths; std::vector<std::string> preload_cjs_modules; std::vector<std::string> preload_esm_modules; diff --git a/src/node_platform.cc b/src/node_platform.cc index ff4b139a72e7..5dfa8c851186 100644 --- a/src/node_platform.cc +++ b/src/node_platform.cc @@ -22,6 +22,9 @@ struct PlatformWorkerData { Mutex* platform_workers_mutex; ConditionVariable* platform_workers_ready; int* pending_platform_workers; + Mutex* running_workers_mutex; + ConditionVariable* worker_exited; + int* running_workers; int id; PlatformDebugLogLevel debug_log_level; }; @@ -83,6 +86,11 @@ static void PlatformWorkerThread(void* data) { pending_worker_tasks->Lock().NotifyOfOutstandingCompletion(); } } + + // See WorkerThreadsTaskRunner::Shutdown(). + Mutex::ScopedLock lock(*worker_data->running_workers_mutex); + (*worker_data->running_workers)--; + worker_data->worker_exited->Signal(lock); } static int GetActualThreadPoolSize(int thread_pool_size) { @@ -261,6 +269,9 @@ WorkerThreadsTaskRunner::WorkerThreadsTaskRunner( &platform_workers_mutex, &platform_workers_ready, &pending_platform_workers, + &running_workers_mutex_, + &worker_exited_, + &running_workers_, i, debug_log_level_}); std::unique_ptr<uv_thread_t> t { new uv_thread_t() }; @@ -270,6 +281,8 @@ WorkerThreadsTaskRunner::WorkerThreadsTaskRunner( } worker_data.release(); threads_.push_back(std::move(t)); + Mutex::ScopedLock running_lock(running_workers_mutex_); + running_workers_++; } // Wait for platform workers to initialize before continuing with the @@ -300,9 +313,22 @@ void WorkerThreadsTaskRunner::BlockingDrain() { pending_worker_tasks_.Lock().BlockingDrain(); } -void WorkerThreadsTaskRunner::Shutdown() { +void WorkerThreadsTaskRunner::Shutdown( + const std::function<void()>& on_stalled) { pending_worker_tasks_.Lock().Stop(); delayed_task_scheduler_->Stop(); + if (on_stalled) { + /* Workers take no new tasks after Stop(), so this only waits for the + * tasks that are already running. */ + constexpr uint64_t kStalledTimeoutNs = 10 * 1000 * 1000; + Mutex::ScopedLock lock(running_workers_mutex_); + while (running_workers_ > 0) { + if (worker_exited_.TimedWait(lock, kStalledTimeoutNs) == UV_ETIMEDOUT) { + Mutex::ScopedUnlock unlock(lock); + on_stalled(); + } + } + } for (size_t i = 0; i < threads_.size(); i++) { CHECK_EQ(0, uv_thread_join(threads_[i].get())); } @@ -523,10 +549,27 @@ void NodePlatform::AddIsolateFinishedCallback(Isolate* isolate, it->second.second->AddShutdownCallback(cb, data); } -void NodePlatform::Shutdown() { +void NodePlatform::Shutdown(Isolate* isolate) { if (has_shut_down_) return; has_shut_down_ = true; - worker_thread_task_runner_->Shutdown(); + std::shared_ptr<PerIsolatePlatformData> per_isolate; + if (isolate != nullptr) { + Mutex::ScopedLock lock(per_isolate_mutex_); + auto it = per_isolate_.find(isolate); + if (it != per_isolate_.end()) per_isolate = it->second.second; + } + if (per_isolate) { + worker_thread_task_runner_->Shutdown([&]() { + /* V8 posts a foreground task when a worker has to wait for a GC, but + * the isolate will not run its tasks or be torn down anymore, so do the + * GC here. Discarding the tasks lets the next request be told apart. */ + if (per_isolate->DiscardForegroundTasks()) { + isolate->LowMemoryNotification(); + } + }); + } else { + worker_thread_task_runner_->Shutdown(); + } { Mutex::ScopedLock lock(per_isolate_mutex_); @@ -604,6 +647,13 @@ void NodePlatform::DrainTasks(Isolate* isolate) { } while (per_isolate->FlushForegroundTasksInternal()); } +bool PerIsolatePlatformData::DiscardForegroundTasks() { + // Destroy the tasks after releasing the queue lock. + std::vector<std::unique_ptr<TaskQueueEntry>> tasks = + foreground_tasks_.Lock().PopAll(); + return !tasks.empty(); +} + bool PerIsolatePlatformData::FlushForegroundTasksInternal() { bool did_work = false; diff --git a/src/node_platform.h b/src/node_platform.h index 52e3e629bc00..2e89d1facb7d 100644 --- a/src/node_platform.h +++ b/src/node_platform.h @@ -134,6 +134,8 @@ class PerIsolatePlatformData // posted during flushing of the queue are postponed until the next // flushing. bool FlushForegroundTasksInternal(); + // Drops the queued foreground tasks. Returns true if there were any. + bool DiscardForegroundTasks(); const uv_loop_t* event_loop() const { return loop_; } @@ -202,7 +204,9 @@ class WorkerThreadsTaskRunner { double delay_in_seconds); void BlockingDrain(); - void Shutdown(); + /* `on_stalled` runs on the calling thread whenever the workers have not + * finished their current tasks for a while. */ + void Shutdown(const std::function<void()>& on_stalled = nullptr); int NumberOfWorkerThreads() const; @@ -221,6 +225,10 @@ class WorkerThreadsTaskRunner { std::unique_ptr<DelayedTaskScheduler> delayed_task_scheduler_; std::vector<std::unique_ptr<uv_thread_t>> threads_; + // Number of platform worker threads that have not exited yet. + Mutex running_workers_mutex_; + ConditionVariable worker_exited_; + int running_workers_ = 0; PlatformDebugLogLevel debug_log_level_ = PlatformDebugLogLevel::kNone; }; @@ -232,7 +240,9 @@ class NodePlatform : public MultiIsolatePlatform { ~NodePlatform() override; void DrainTasks(v8::Isolate* isolate) override; - void Shutdown(); + /* Pass the isolate that the calling thread is running when it will not be + * disposed first, so that tasks waiting for it to collect garbage can end. */ + void Shutdown(v8::Isolate* isolate = nullptr); // v8::Platform implementation. int NumberOfWorkerThreads() override; diff --git a/src/node_process_methods.cc b/src/node_process_methods.cc index 6a35e5c5e4c4..2db5e3678b52 100644 --- a/src/node_process_methods.cc +++ b/src/node_process_methods.cc @@ -752,10 +752,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, } InternalFieldInfoBase* BindingData::Serialize(int index) { - DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = internal_field_info_; - internal_field_info_ = nullptr; - return info; + return TakeInternalFieldInfo(index, &internal_field_info_); } void BindingData::Deserialize(Local<Context> context, @@ -763,13 +760,8 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - v8::HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - // Recreate the buffer in the constructor. - InternalFieldInfo* casted_info = static_cast<InternalFieldInfo*>(info); - BindingData* binding = - realm->AddBindingData<BindingData>(holder, casted_info); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>( + context, holder, static_cast<InternalFieldInfo*>(info)); } static void SetEmitWarningSync(const FunctionCallbackInfo<Value>& args) { diff --git a/src/node_profiling.cc b/src/node_profiling.cc index bc595ebdbbd4..07757d39217c 100644 --- a/src/node_profiling.cc +++ b/src/node_profiling.cc @@ -45,14 +45,14 @@ static void BuildHeapProfileNode(Isolate* isolate, writer->json_arrayend(); } -bool SerializeHeapProfile(Isolate* isolate, std::ostringstream& out_stream) { +bool SerializeHeapProfile(Isolate* isolate, std::string& out) { HandleScope scope(isolate); HeapProfiler* profiler = isolate->GetHeapProfiler(); std::unique_ptr<AllocationProfile> profile(profiler->GetAllocationProfile()); if (!profile) { return false; } - JSONWriter writer(out_stream, true); + JSONWriter writer(out, true); writer.json_start(); writer.json_arraystart("samples"); diff --git a/src/node_profiling.h b/src/node_profiling.h index 1176eb8952db..08f40ee04f6b 100644 --- a/src/node_profiling.h +++ b/src/node_profiling.h @@ -7,7 +7,7 @@ #include "v8.h" #include <cstdint> -#include <sstream> +#include <string> namespace node { @@ -21,7 +21,7 @@ struct HeapProfileOptions { HeapProfileOptions ParseHeapProfileOptions( const v8::FunctionCallbackInfo<v8::Value>& args); -bool SerializeHeapProfile(v8::Isolate* isolate, std::ostringstream& out_stream); +bool SerializeHeapProfile(v8::Isolate* isolate, std::string& out); struct CpuProfileOptions { int sampling_interval_us = 0; diff --git a/src/node_realm-inl.h b/src/node_realm-inl.h index 62f77384a387..61a09b6ee2c8 100644 --- a/src/node_realm-inl.h +++ b/src/node_realm-inl.h @@ -108,6 +108,15 @@ inline T* Realm::AddBindingData(v8::Local<v8::Object> target, Args&&... args) { return item.get(); } +template <std::derived_from<BaseObject> T, typename... Args> +void Realm::DeserializeBindingData(v8::Local<v8::Context> context, + v8::Local<v8::Object> holder, + Args&&... args) { + v8::HandleScope scope(v8::Isolate::GetCurrent()); + Realm* realm = Realm::GetCurrent(context); + CHECK_NOT_NULL(realm->AddBindingData<T>(holder, std::forward<Args>(args)...)); +} + inline BindingDataStore* Realm::binding_data_store() { return &binding_data_store_; } diff --git a/src/node_realm.h b/src/node_realm.h index 8bba26f50a92..810d48c8e3ee 100644 --- a/src/node_realm.h +++ b/src/node_realm.h @@ -128,6 +128,13 @@ class Realm : public MemoryRetainer { // GetBindingData<T>(args) later. template <std::derived_from<BaseObject> T, typename... Args> T* AddBindingData(v8::Local<v8::Object> target, Args&&... args); + // Recreates binding data of type T on `holder` in the realm of `context` + // when deserializing a snapshot. Used to implement the static Deserialize() + // method of snapshotable binding data. + template <std::derived_from<BaseObject> T, typename... Args> + static void DeserializeBindingData(v8::Local<v8::Context> context, + v8::Local<v8::Object> holder, + Args&&... args); template <typename T, typename U> static inline T* GetBindingData(const v8::PropertyCallbackInfo<U>& info); template <typename T> diff --git a/src/node_snapshotable.cc b/src/node_snapshotable.cc index faf95133bf47..c2ac34e662ce 100644 --- a/src/node_snapshotable.cc +++ b/src/node_snapshotable.cc @@ -1701,10 +1701,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, } InternalFieldInfoBase* BindingData::Serialize(int index) { - DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = internal_field_info_; - internal_field_info_ = nullptr; - return info; + return TakeInternalFieldInfo(index, &internal_field_info_); } void BindingData::Deserialize(Local<Context> context, @@ -1712,13 +1709,8 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - v8::HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - // Recreate the buffer in the constructor. - InternalFieldInfo* casted_info = static_cast<InternalFieldInfo*>(info); - BindingData* binding = - realm->AddBindingData<BindingData>(holder, casted_info); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>( + context, holder, static_cast<InternalFieldInfo*>(info)); } void BindingData::MemoryInfo(MemoryTracker* tracker) const { diff --git a/src/node_snapshotable.h b/src/node_snapshotable.h index a9050877a04d..95efa51b5276 100644 --- a/src/node_snapshotable.h +++ b/src/node_snapshotable.h @@ -8,6 +8,8 @@ #include "base_object.h" #include "util.h" +#include <utility> + namespace node { class Environment; @@ -140,6 +142,15 @@ void SerializeSnapshotableObjects(Realm* realm, #define DCHECK_IS_SNAPSHOT_SLOT(index) DCHECK_EQ(index, BaseObject::kSlot) +// Implements SnapshotableObject::Serialize() for objects that allocate their +// InternalFieldInfo in PrepareForSerialization(): ownership of `*info` is +// handed over to the caller and the field is reset. +template <typename Info> +InternalFieldInfoBase* TakeInternalFieldInfo(int index, Info** info) { + DCHECK_IS_SNAPSHOT_SLOT(index); + return std::exchange(*info, nullptr); +} + namespace mksnapshot { class BindingData : public SnapshotableObject { public: diff --git a/src/node_sqlite.cc b/src/node_sqlite.cc index 8341b27a4fa0..2f4050cb8c16 100644 --- a/src/node_sqlite.cc +++ b/src/node_sqlite.cc @@ -337,7 +337,12 @@ void JSValueToSQLiteResult(Isolate* isolate, } else if (value->IsArrayBufferView() || value->IsArrayBuffer() || value->IsSharedArrayBuffer()) { ArrayBufferViewContents<uint8_t> buf(value); - sqlite3_result_blob64(ctx, buf.data(), buf.length(), SQLITE_TRANSIENT); + if (buf.length() == 0) { + // Empty buffers may lack a data pointer, which SQLite treats as NULL. + sqlite3_result_zeroblob(ctx, 0); + } else { + sqlite3_result_blob64(ctx, buf.data(), buf.length(), SQLITE_TRANSIENT); + } } else if (value->IsBigInt()) { bool lossless; int64_t as_int = value.As<BigInt>()->Int64Value(&lossless); @@ -622,7 +627,7 @@ class BackupJob : public ThreadPoolWork { std::string dest_db, int pages, Local<Function> progressFunc) - : ThreadPoolWork(env, "node_sqlite3.BackupJob"), + : ThreadPoolWork(env, ThreadPoolWorkType::kSQLiteBackup), env_(env), source_(source), pages_(pages), @@ -1739,11 +1744,18 @@ void Database::FinalizeBackups() { } void Database::FinalizeStatements() { - for (auto stmt : statements_) { + // Finalizing a statement can run JavaScript: closing a virtual-table cursor + // calls the generator's return(). That code can prepare another statement, + // which inserts into this set. Erase each statement first and keep going + // until the set is empty, so a statement created from that JavaScript is + // finalized before the connection is released. Holding an iterator across + // the insertion would also be undefined for std::unordered_set. + while (!statements_.empty()) { + auto it = statements_.begin(); + Statement* stmt = *it; + statements_.erase(it); stmt->Finalize(); } - - statements_.clear(); } void Database::TrackStatement(Statement* statement) { @@ -3357,6 +3369,16 @@ int Database::TraceCallback(unsigned int type, return 0; } + // The profile callback also runs when a statement fails and when it is + // reset, both of which can happen while a JavaScript exception is already + // pending: a throwing SQL function, or a row value that cannot be converted. + // Publishing here would enter V8 with that exception still set. Debug + // builds then abort in Invoke, and release builds drop the user's error or + // replace it with an empty ERR_SQLITE_ERROR. + if (!env->can_call_into_js() || env->isolate()->HasPendingException()) { + return 0; + } + // Entered before building the payload below, because allocating it can // trigger a garbage collection that SQLite is not prepared for. CallbackDepthGuard guard(db); @@ -3632,11 +3654,16 @@ bool Statement::BindValue(const Local<Value>& value, const int index) { } else if (value->IsArrayBufferView() || value->IsArrayBuffer() || value->IsSharedArrayBuffer()) { ArrayBufferViewContents<uint8_t> buf(value); - r = sqlite3_bind_blob64(statement_.get(), - index, - buf.data(), - static_cast<sqlite3_uint64>(buf.length()), - SQLITE_TRANSIENT); + if (buf.length() == 0) { + // Empty buffers may lack a data pointer, which SQLite treats as NULL. + r = sqlite3_bind_zeroblob(statement_.get(), index, 0); + } else { + r = sqlite3_bind_blob64(statement_.get(), + index, + buf.data(), + static_cast<sqlite3_uint64>(buf.length()), + SQLITE_TRANSIENT); + } } else if (value->IsBoolean()) { r = sqlite3_bind_int(statement_.get(), index, value->IsTrue() ? 1 : 0); } else if (value->IsBigInt()) { @@ -3835,9 +3862,10 @@ MaybeLocal<Object> StatementExecutionHelper::Run(Environment* env, // Declared before the reset below so that it outlives it: sqlite3_reset() // can run JavaScript through an aggregate's xFinal. SteppingStatementGuard stepping(db, stmt); + // Throwing can run JS that closes the database and frees `stmt`. bool needs_reset = true; auto reset = OnScopeLeave([&]() { - if (needs_reset) sqlite3_reset(stmt); + if (needs_reset) sqlite3_reset(statement->statement_.get()); }); int step_r = sqlite3_step(stmt); @@ -3923,9 +3951,10 @@ MaybeLocal<Value> StatementExecutionHelper::Get(Environment* env, // Declared before the reset below so that it outlives it: sqlite3_reset() // can run JavaScript through an aggregate's xFinal. SteppingStatementGuard stepping(db, stmt); + // Throwing can run JS that closes the database and frees `stmt`. bool needs_reset = true; auto reset = OnScopeLeave([&]() { - if (needs_reset) sqlite3_reset(stmt); + if (needs_reset) sqlite3_reset(statement->statement_.get()); }); int r = sqlite3_step(stmt); @@ -4375,7 +4404,8 @@ bool SQLTagStore::ResetAndBindStatement( return true; } -void SQLTagStore::Run(const FunctionCallbackInfo<Value>& args) { +void SQLTagStore::PrepareForExecution(const FunctionCallbackInfo<Value>& args, + BaseObjectPtr<Statement>* out) { SQLTagStore* session; ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); Environment* env = Environment::GetCurrent(args); @@ -4396,6 +4426,17 @@ void SQLTagStore::Run(const FunctionCallbackInfo<Value>& args) { return; } + *out = std::move(stmt); +} + +void SQLTagStore::Run(const FunctionCallbackInfo<Value>& args) { + BaseObjectPtr<Statement> stmt; + PrepareForExecution(args, &stmt); + if (!stmt) { + return; + } + Environment* env = Environment::GetCurrent(args); + Local<Object> result; if (StatementExecutionHelper::Run(env, stmt.get()).ToLocal(&result)) { args.GetReturnValue().Set(result); @@ -4403,25 +4444,12 @@ void SQLTagStore::Run(const FunctionCallbackInfo<Value>& args) { } void SQLTagStore::Iterate(const FunctionCallbackInfo<Value>& args) { - SQLTagStore* session; - ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); - Environment* env = Environment::GetCurrent(args); - - THROW_AND_RETURN_ON_BAD_STATE( - env, !session->database_->IsOpen(), "database is not open"); - THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get()); - - BaseObjectPtr<Statement> stmt = PrepareStatement(args); - + BaseObjectPtr<Statement> stmt; + PrepareForExecution(args, &stmt); if (!stmt) { return; } - - THROW_AND_RETURN_IF_STEPPING(env, stmt.get()); - - if (!ResetAndBindStatement(env, stmt.get(), args)) { - return; - } + Environment* env = Environment::GetCurrent(args); BaseObjectPtr<StatementIterator> iter = StatementExecutionHelper::Iterate(env, BaseObjectPtr<Statement>(stmt)); @@ -4434,25 +4462,12 @@ void SQLTagStore::Iterate(const FunctionCallbackInfo<Value>& args) { } void SQLTagStore::Get(const FunctionCallbackInfo<Value>& args) { - SQLTagStore* session; - ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); - Environment* env = Environment::GetCurrent(args); - - THROW_AND_RETURN_ON_BAD_STATE( - env, !session->database_->IsOpen(), "database is not open"); - THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get()); - - BaseObjectPtr<Statement> stmt = PrepareStatement(args); - + BaseObjectPtr<Statement> stmt; + PrepareForExecution(args, &stmt); if (!stmt) { return; } - - THROW_AND_RETURN_IF_STEPPING(env, stmt.get()); - - if (!ResetAndBindStatement(env, stmt.get(), args)) { - return; - } + Environment* env = Environment::GetCurrent(args); Local<Value> result; if (StatementExecutionHelper::Get(env, stmt.get()).ToLocal(&result)) { @@ -4461,25 +4476,12 @@ void SQLTagStore::Get(const FunctionCallbackInfo<Value>& args) { } void SQLTagStore::All(const FunctionCallbackInfo<Value>& args) { - SQLTagStore* session; - ASSIGN_OR_RETURN_UNWRAP(&session, args.This()); - Environment* env = Environment::GetCurrent(args); - - THROW_AND_RETURN_ON_BAD_STATE( - env, !session->database_->IsOpen(), "database is not open"); - THROW_AND_RETURN_IF_IN_AUTHORIZER(env, session->database_.get()); - - BaseObjectPtr<Statement> stmt = PrepareStatement(args); - + BaseObjectPtr<Statement> stmt; + PrepareForExecution(args, &stmt); if (!stmt) { return; } - - THROW_AND_RETURN_IF_STEPPING(env, stmt.get()); - - if (!ResetAndBindStatement(env, stmt.get(), args)) { - return; - } + Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); bool needs_reset = true; diff --git a/src/node_sqlite.h b/src/node_sqlite.h index 2bba70c3bbae..c14a7c3cdead 100644 --- a/src/node_sqlite.h +++ b/src/node_sqlite.h @@ -534,6 +534,13 @@ class SQLTagStore : public BaseObject { Environment* env, Statement* stmt, const v8::FunctionCallbackInfo<v8::Value>& args); + // Performs the state checks, statement preparation, and parameter binding + // shared by Run(), Iterate(), Get(), and All(). On success, `*out` is set to + // the prepared statement. On failure, a JavaScript exception is pending and + // `*out` is left empty. + static void PrepareForExecution( + const v8::FunctionCallbackInfo<v8::Value>& args, + BaseObjectPtr<Statement>* out); BaseObjectWeakPtr<Database> database_; LRUCache<std::string, BaseObjectPtr<Statement>> sql_tags_; friend class StatementExecutionHelper; diff --git a/src/node_task_runner.cc b/src/node_task_runner.cc index 136dec24fa02..b9716846abfc 100644 --- a/src/node_task_runner.cc +++ b/src/node_task_runner.cc @@ -233,7 +233,9 @@ FindPackageJson(const std::filesystem::path& cwd) { directory_path = directory_path.parent_path()) { // Append "path/node_modules/.bin" to the env var, if it is a directory. auto node_modules_bin = directory_path / "node_modules" / ".bin"; - if (std::filesystem::is_directory(node_modules_bin)) { + // Skip directories that can't be inspected (e.g. permission denied). + std::error_code error_code; + if (std::filesystem::is_directory(node_modules_bin, error_code)) { path_env_var += ConvertPathToUTF8(node_modules_bin) + env_var_separator; } @@ -279,7 +281,15 @@ static void PrintScripts(FILE* out, void RunTask(const std::shared_ptr<InitializationResultImpl>& result, std::string_view command_id, const std::vector<std::string_view>& positional_args) { - auto cwd = std::filesystem::current_path(); + std::error_code error_code; + auto cwd = std::filesystem::current_path(error_code); + if (error_code) { + fprintf(stderr, + "Can't determine the current working directory: %s\n", + error_code.message().c_str()); + result->exit_code_ = ExitCode::kGenericUserError; + return; + } auto package_json = FindPackageJson(cwd); if (!package_json.has_value()) { diff --git a/src/node_url.cc b/src/node_url.cc index 0c5c9e65136a..d8a710b7427b 100644 --- a/src/node_url.cc +++ b/src/node_url.cc @@ -97,9 +97,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, InternalFieldInfoBase* BindingData::Serialize(int index) { DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = - InternalFieldInfoBase::New<InternalFieldInfo>(type()); - return info; + return InternalFieldInfoBase::New<InternalFieldInfo>(type()); } void BindingData::Deserialize(Local<Context> context, @@ -107,10 +105,7 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - BindingData* binding = realm->AddBindingData<BindingData>(holder); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>(context, holder); } #ifndef LARGEST_ASCII_CHAR_CODE_TO_ENCODE diff --git a/src/node_url_pattern.cc b/src/node_url_pattern.cc index 63f01d58170f..eac1d62f34d4 100644 --- a/src/node_url_pattern.cc +++ b/src/node_url_pattern.cc @@ -560,46 +560,72 @@ bool URLPattern::Test(Environment* env, // V8 Methods -void URLPattern::Exec(const FunctionCallbackInfo<Value>& args) { - URLPattern* url_pattern; - ASSIGN_OR_RETURN_UNWRAP(&url_pattern, args.This()); - auto env = Environment::GetCurrent(args); +namespace { +// The arguments of URLPattern.prototype.exec() and test(). When the input is +// a string, `input` refers to `input_storage`, so instances must not be copied +// or moved. +struct URLPatternMatchArgs { + URLPatternMatchArgs() = default; + URLPatternMatchArgs(const URLPatternMatchArgs&) = delete; + URLPatternMatchArgs& operator=(const URLPatternMatchArgs&) = delete; + + std::optional<std::string_view> base_url_view() const { + return base_url ? std::optional<std::string_view>(*base_url) : std::nullopt; + } ada::url_pattern_input input; - std::optional<std::string> baseURL{}; - std::string input_base; + std::string input_storage; + std::optional<std::string> base_url; +}; + +// Parses the `input` and `baseURL` arguments of exec() and test(). Returns +// false if a JavaScript exception is pending. +bool ParseURLPatternMatchArgs(Environment* env, + const FunctionCallbackInfo<Value>& args, + URLPatternMatchArgs* out) { if (args.Length() == 0 || args[0]->IsNullOrUndefined()) { - input = ada::url_pattern_init{}; + out->input = ada::url_pattern_init{}; } else if (args[0]->IsString()) { Utf8Value input_value(env->isolate(), args[0].As<String>()); - input_base = input_value.ToString(); - input = std::string_view(input_base); + out->input_storage = input_value.ToString(); + out->input = std::string_view(out->input_storage); } else if (args[0]->IsObject()) { - auto maybeInput = URLPatternInit::FromJsObject(env, args[0].As<Object>()); - if (!maybeInput.has_value()) return; - input = std::move(*maybeInput); + auto maybeInput = + URLPattern::URLPatternInit::FromJsObject(env, args[0].As<Object>()); + if (!maybeInput.has_value()) return false; + out->input = std::move(*maybeInput); } else { THROW_ERR_INVALID_ARG_TYPE( env, "URLPattern input needs to be a string or an object"); - return; + return false; } if (args.Length() > 1 && !args[1]->IsUndefined()) { if (args[1]->IsNull()) { - baseURL = std::string("null"); + out->base_url = std::string("null"); } else if (args[1]->IsString()) { Utf8Value base_url_value(env->isolate(), args[1].As<String>()); - baseURL = base_url_value.ToStringView(); + out->base_url = base_url_value.ToStringView(); } else { THROW_ERR_INVALID_ARG_TYPE(env, "baseURL must be a string"); - return; + return false; } } + return true; +} +} // namespace +void URLPattern::Exec(const FunctionCallbackInfo<Value>& args) { + URLPattern* url_pattern; + ASSIGN_OR_RETURN_UNWRAP(&url_pattern, args.This()); + auto env = Environment::GetCurrent(args); + + URLPatternMatchArgs match_args; + if (!ParseURLPatternMatchArgs(env, args, &match_args)) return; + + std::optional<std::string_view> base_url = match_args.base_url_view(); Local<Value> result; - std::optional<std::string_view> baseURL_opt = - baseURL ? std::optional<std::string_view>(*baseURL) : std::nullopt; - if (!url_pattern->Exec(env, input, baseURL_opt).ToLocal(&result)) { + if (!url_pattern->Exec(env, match_args.input, base_url).ToLocal(&result)) { THROW_ERR_OPERATION_FAILED(env, "Failed to exec URLPattern"); return; } @@ -611,40 +637,11 @@ void URLPattern::Test(const FunctionCallbackInfo<Value>& args) { ASSIGN_OR_RETURN_UNWRAP(&url_pattern, args.This()); auto env = Environment::GetCurrent(args); - ada::url_pattern_input input; - std::optional<std::string> baseURL{}; - std::string input_base; - if (args.Length() == 0 || args[0]->IsNullOrUndefined()) { - input = ada::url_pattern_init{}; - } else if (args[0]->IsString()) { - Utf8Value input_value(env->isolate(), args[0].As<String>()); - input_base = input_value.ToString(); - input = std::string_view(input_base); - } else if (args[0]->IsObject()) { - auto maybeInput = URLPatternInit::FromJsObject(env, args[0].As<Object>()); - if (!maybeInput.has_value()) return; - input = std::move(*maybeInput); - } else { - THROW_ERR_INVALID_ARG_TYPE( - env, "URLPattern input needs to be a string or an object"); - return; - } - - if (args.Length() > 1 && !args[1]->IsUndefined()) { - if (args[1]->IsNull()) { - baseURL = std::string("null"); - } else if (args[1]->IsString()) { - Utf8Value base_url_value(env->isolate(), args[1].As<String>()); - baseURL = base_url_value.ToStringView(); - } else { - THROW_ERR_INVALID_ARG_TYPE(env, "baseURL must be a string"); - return; - } - } + URLPatternMatchArgs match_args; + if (!ParseURLPatternMatchArgs(env, args, &match_args)) return; - std::optional<std::string_view> baseURL_opt = - baseURL ? std::optional<std::string_view>(*baseURL) : std::nullopt; - args.GetReturnValue().Set(url_pattern->Test(env, input, baseURL_opt)); + std::optional<std::string_view> base_url = match_args.base_url_view(); + args.GetReturnValue().Set(url_pattern->Test(env, match_args.input, base_url)); } #define URL_PATTERN_COMPONENT_GETTERS(uppercase_name, lowercase_name) \ diff --git a/src/node_util.cc b/src/node_util.cc index e19ba77e264d..2fceb403f609 100644 --- a/src/node_util.cc +++ b/src/node_util.cc @@ -209,7 +209,9 @@ static uint32_t GetUVHandleTypeCode(const uv_handle_type type) { case UV_UNKNOWN_HANDLE: return 5; default: - ABORT(); + // The type is known by libuv, just not exposed to JS land, so report it + // as `UNKNOWN`. + return 5; } } diff --git a/src/node_v8.cc b/src/node_v8.cc index 14b74f4b6d42..9758826ae8b3 100644 --- a/src/node_v8.cc +++ b/src/node_v8.cc @@ -166,20 +166,12 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - // Recreate the buffer in the constructor. - InternalFieldInfo* casted_info = static_cast<InternalFieldInfo*>(info); - BindingData* binding = - realm->AddBindingData<BindingData>(holder, casted_info); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>( + context, holder, static_cast<InternalFieldInfo*>(info)); } InternalFieldInfoBase* BindingData::Serialize(int index) { - DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = internal_field_info_; - internal_field_info_ = nullptr; - return info; + return TakeInternalFieldInfo(index, &internal_field_info_); } void BindingData::MemoryInfo(MemoryTracker* tracker) const { @@ -230,6 +222,22 @@ void SetHeapProfileNearHeapLimit(const FunctionCallbackInfo<Value>& args) { env->set_heap_profile_near_heap_limit(limit); } +// Only used by tests, so that the pointer compression heap warning can be +// exercised without allocating a large heap. Takes the "likely" and the +// "certain" thresholds in bytes. +void SetPointerCompressionHeapWarningThresholds( + const FunctionCallbackInfo<Value>& args) { + CHECK(args[0]->IsNumber()); + CHECK(args[1]->IsNumber()); + Environment* env = Environment::GetCurrent(args); + double likely = args[0].As<v8::Number>()->Value(); + double certain = args[1].As<v8::Number>()->Value(); + CHECK_GE(likely, 0); + CHECK_GE(certain, 0); + env->set_pointer_compression_heap_warning_thresholds( + static_cast<uint64_t>(likely), static_cast<uint64_t>(certain)); +} + void UpdateHeapStatisticsBuffer(const FunctionCallbackInfo<Value>& args) { BindingData* data = Realm::GetBindingData<BindingData>(args); HeapStatistics s; @@ -323,12 +331,12 @@ void StartHeapProfile(const FunctionCallbackInfo<Value>& args) { void StopHeapProfile(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); - std::ostringstream out_stream; - bool success = node::SerializeHeapProfile(isolate, out_stream); + std::string profile; + bool success = node::SerializeHeapProfile(isolate, profile); if (success) { isolate->GetHeapProfiler()->StopSamplingHeapProfiler(); Local<Value> result; - if (ToV8Value(env->context(), out_stream.str(), isolate).ToLocal(&result)) { + if (ToV8Value(env->context(), profile, isolate).ToLocal(&result)) { args.GetReturnValue().Set(result); } } else { @@ -750,6 +758,10 @@ void Initialize(Local<Object> target, target, "setHeapProfileNearHeapLimit", SetHeapProfileNearHeapLimit); + SetMethod(context, + target, + "setPointerCompressionHeapWarningThresholds", + SetPointerCompressionHeapWarningThresholds); SetMethod(context, target, "updateHeapStatisticsBuffer", @@ -862,6 +874,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(GetHashSeed); registry->Register(SetHeapSnapshotNearHeapLimit); registry->Register(SetHeapProfileNearHeapLimit); + registry->Register(SetPointerCompressionHeapWarningThresholds); registry->Register(GCProfiler::New); registry->Register(GCProfiler::Start); registry->Register(GCProfiler::Stop); diff --git a/src/node_v8_platform-inl.h b/src/node_v8_platform-inl.h index 0538b5feeb59..82539c846af8 100644 --- a/src/node_v8_platform-inl.h +++ b/src/node_v8_platform-inl.h @@ -32,12 +32,12 @@ struct V8Platform { } // Make sure V8Platform don not call into Libuv threadpool, // see DefaultProcessExitHandlerInternal in environment.cc - inline void Dispose() { + inline void Dispose(v8::Isolate* isolate = nullptr) { if (!initialized_) return; initialized_ = false; StopTracingAgent(); - platform_->Shutdown(); + platform_->Shutdown(isolate); platform_.reset(); // Destroy tracing after the platform (and platform threads) have been // stopped. @@ -67,7 +67,7 @@ struct V8Platform { std::unique_ptr<NodePlatform> platform_; #else // !NODE_USE_V8_PLATFORM inline void Initialize(int thread_pool_size) {} - inline void Dispose() {} + inline void Dispose(v8::Isolate* isolate = nullptr) {} inline void DrainVMTasks(v8::Isolate* isolate) {} inline void StartTracingAgent() { if (!per_process::cli_options->trace_event_categories.empty()) { @@ -86,8 +86,9 @@ namespace per_process { extern struct V8Platform v8_platform; } -inline void DisposePlatform() { - per_process::v8_platform.Dispose(); +// See NodePlatform::Shutdown() for `isolate`. +inline void DisposePlatform(v8::Isolate* isolate = nullptr) { + per_process::v8_platform.Dispose(isolate); } } // namespace node diff --git a/src/node_version.h b/src/node_version.h index 90f5d927c1d5..494e9420545d 100644 --- a/src/node_version.h +++ b/src/node_version.h @@ -29,11 +29,11 @@ #define NODE_VERSION_IS_LTS 0 #define NODE_VERSION_LTS_CODENAME "" -#define NODE_VERSION_IS_RELEASE 0 +#define NODE_VERSION_IS_RELEASE 1 #define NODE_ALPHA_MAJOR_VERSION 0 -#define NODE_ALPHA_MINOR_VERSION 1 -#define NODE_ALPHA_PATCH_VERSION 2 +#define NODE_ALPHA_MINOR_VERSION 2 +#define NODE_ALPHA_PATCH_VERSION 0 #ifndef NODE_STRINGIFY #define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) diff --git a/src/node_watchdog.cc b/src/node_watchdog.cc index c403f8cb0715..50ae9d7075b0 100644 --- a/src/node_watchdog.cc +++ b/src/node_watchdog.cc @@ -137,7 +137,7 @@ std::string FormatProcessTimeoutHeader(const std::string& duration) { [[noreturn]] void ForceProcessTimeoutExit(const std::string& message) { FPrintF(stderr, "%s", message); fflush(stderr); - ResetStdio(); + ResetStdio(true); std::_Exit(static_cast<int>(ExitCode::kProcessTimeout)); } // LCOV_EXCL_STOP @@ -305,7 +305,7 @@ std::string FormatProcessTimeoutDiagnostics(Environment* env) { // Running Workers keep the event loop alive through the Environment's own // task queue handle rather than through a HandleWrap. env->ForEachWorker([&](worker::Worker* worker) { - if (worker->is_internal() || !worker->has_ref() || worker->is_stopped()) { + if (!worker->has_ref() || worker->is_stopped()) { return; } std::string details = SPrintF("thread %d", worker->thread_id()); diff --git a/src/node_worker.cc b/src/node_worker.cc index 308d987680d7..c767f9ff52db 100644 --- a/src/node_worker.cc +++ b/src/node_worker.cc @@ -64,8 +64,7 @@ Worker::Worker(Environment* env, std::shared_ptr<PerIsolateOptions> per_isolate_opts, std::vector<std::string>&& exec_argv, std::shared_ptr<KVStore> env_vars, - const SnapshotData* snapshot_data, - const bool is_internal) + const SnapshotData* snapshot_data) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_WORKER), per_isolate_opts_(per_isolate_opts), exec_argv_(exec_argv), @@ -74,8 +73,7 @@ Worker::Worker(Environment* env, name_(name), env_vars_(env_vars), embedder_preload_(env->embedder_preload()), - snapshot_data_(snapshot_data), - is_internal_(is_internal) { + snapshot_data_(snapshot_data) { Debug(this, "Creating new worker instance with thread id %llu", thread_id_.id); @@ -524,7 +522,6 @@ void Worker::New(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); THROW_IF_INSUFFICIENT_PERMISSIONS( env, permission::PermissionScope::kWorkerThreads, ""); - bool is_internal = args[5]->IsTrue(); Isolate* isolate = args.GetIsolate(); CHECK(args.IsConstructCall()); @@ -549,9 +546,9 @@ void Worker::New(const FunctionCallbackInfo<Value>& args) { url.append(value.out(), value.length()); } - if (!args[6]->IsNullOrUndefined()) { + if (!args[5]->IsNullOrUndefined()) { Utf8Value value( - isolate, args[6]->ToString(env->context()).FromMaybe(Local<String>())); + isolate, args[5]->ToString(env->context()).FromMaybe(Local<String>())); name.append(value.out(), value.length()); } @@ -709,16 +706,6 @@ void Worker::New(const FunctionCallbackInfo<Value>& args) { // is inherited but the load behavior must not be. per_isolate_opts->per_env->vfs_load = false; - // Internal workers should not wait for inspector frontend to connect or - // break on the first line of internal scripts. Module loader threads are - // essential to load user codes and must not be blocked by the inspector - // for internal scripts. - // Still, `--inspect-node` can break on the first line of internal scripts. - if (is_internal) { - per_isolate_opts->per_env->get_debug_options() - ->DisableWaitOrBreakFirstLine(); - } - const SnapshotData* snapshot_data = env->isolate_data()->snapshot_data(); Worker* worker = new Worker(env, @@ -728,8 +715,7 @@ void Worker::New(const FunctionCallbackInfo<Value>& args) { per_isolate_opts, std::move(exec_argv_out), env_vars, - snapshot_data, - is_internal); + snapshot_data); CHECK(args[3]->IsFloat64Array()); Local<Float64Array> limit_info = args[3].As<Float64Array>(); @@ -1136,15 +1122,14 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo<Value>& args) { bool scheduled = w->RequestInterrupt([taker = std::move(taker), env](Environment* worker_env) mutable { - std::ostringstream out_stream; - bool success = - node::SerializeHeapProfile(worker_env->isolate(), out_stream); + std::string profile; + bool success = node::SerializeHeapProfile(worker_env->isolate(), profile); if (success) { worker_env->isolate()->GetHeapProfiler()->StopSamplingHeapProfiler(); } env->SetImmediateThreadsafe( [taker = std::move(taker), - out_stream = std::move(out_stream), + profile = std::move(profile), success = success](Environment* env) mutable { Isolate* isolate = env->isolate(); HandleScope handle_scope(isolate); @@ -1156,8 +1141,7 @@ void Worker::StopHeapProfile(const FunctionCallbackInfo<Value>& args) { }; if (success) { Local<Value> result; - if (!ToV8Value(env->context(), out_stream.str(), isolate) - .ToLocal(&result)) { + if (!ToV8Value(env->context(), profile, isolate).ToLocal(&result)) { return; } argv[1] = result; @@ -1474,13 +1458,6 @@ void IsMainThreadGetter(Local<v8::Name>, info.GetReturnValue().Set(Environment::GetCurrent(info)->is_main_thread()); } -void IsInternalThreadGetter(Local<v8::Name>, - const v8::PropertyCallbackInfo<Value>& info) { - Worker* worker = - Environment::GetCurrent(info)->isolate_data()->worker_context(); - info.GetReturnValue().Set(worker != nullptr && worker->is_internal()); -} - void OwnsProcessStateGetter(Local<v8::Name>, const v8::PropertyCallbackInfo<Value>& info) { info.GetReturnValue().Set( @@ -1506,7 +1483,6 @@ void CreateWorkerPerIsolateProperties(IsolateData* isolate_data, lazy("threadId", ThreadIdGetter); lazy("threadName", ThreadNameGetter); lazy("isMainThread", IsMainThreadGetter); - lazy("isInternalThread", IsInternalThreadGetter); lazy("ownsProcessState", OwnsProcessStateGetter); lazy("resourceLimits", ResourceLimitsGetter); } @@ -1615,7 +1591,7 @@ void CreateWorkerPerContextProperties(Local<Object> target, Local<Value> unused, Local<Context> context, void* priv) { - // threadId, threadName, isMainThread, isInternalThread, ownsProcessState + // threadId, threadName, isMainThread, ownsProcessState // and resourceLimits are lazy properties of the per-isolate template (see // CreateWorkerPerIsolateProperties). NODE_DEFINE_CONSTANT(target, kMaxYoungGenerationSizeMb); @@ -1630,7 +1606,6 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(ThreadIdGetter); registry->Register(ThreadNameGetter); registry->Register(IsMainThreadGetter); - registry->Register(IsInternalThreadGetter); registry->Register(OwnsProcessStateGetter); registry->Register(ResourceLimitsGetter); registry->Register(Worker::New); diff --git a/src/node_worker.h b/src/node_worker.h index 03e546534c1b..4261db0c18fc 100644 --- a/src/node_worker.h +++ b/src/node_worker.h @@ -36,8 +36,7 @@ class Worker : public AsyncWrap { std::shared_ptr<PerIsolateOptions> per_isolate_opts, std::vector<std::string>&& exec_argv, std::shared_ptr<KVStore> env_vars, - const SnapshotData* snapshot_data, - const bool is_internal); + const SnapshotData* snapshot_data); ~Worker() override; // Run the worker. This is only called from the worker thread. @@ -64,7 +63,6 @@ class Worker : public AsyncWrap { bool is_stopped() const; const SnapshotData* snapshot_data() const { return snapshot_data_; } - bool is_internal() const { return is_internal_; } std::string_view name() const { return name_; } uint64_t thread_id() const { return thread_id_.id; } // Whether the Worker keeps the parent's event loop alive, see @@ -146,7 +144,6 @@ class Worker : public AsyncWrap { Environment* env_ = nullptr; const SnapshotData* snapshot_data_ = nullptr; - const bool is_internal_; friend class WorkerThreadData; }; diff --git a/src/node_zlib.cc b/src/node_zlib.cc index c87703800fd0..72947b8b7839 100644 --- a/src/node_zlib.cc +++ b/src/node_zlib.cc @@ -501,7 +501,7 @@ class CompressionStream : public AsyncWrap, CompressionStream(Environment* env, Local<Object> wrap) : AsyncWrap(env, wrap, AsyncWrap::PROVIDER_ZLIB), - ThreadPoolWork(env, "zlib"), + ThreadPoolWork(env, ThreadPoolWorkType::kZlib), write_result_(nullptr) { MakeWeak(); } diff --git a/src/permission/fs_permission.cc b/src/permission/fs_permission.cc index 0baf1291a966..b1a7de5ef836 100644 --- a/src/permission/fs_permission.cc +++ b/src/permission/fs_permission.cc @@ -176,21 +176,21 @@ void FSPermission::Drop(Environment* env, } void FSPermission::RevokeAccess(PermissionScope perm, const std::string& res) { - const std::string path = WildcardIfDir(res); - if (perm == PermissionScope::kFileSystemRead) { - auto it = - std::find(granted_paths_in_.begin(), granted_paths_in_.end(), path); - if (it != granted_paths_in_.end()) { - granted_paths_in_.erase(it); - RebuildTree(PermissionScope::kFileSystemRead); - } - } else if (perm == PermissionScope::kFileSystemWrite) { - auto it = - std::find(granted_paths_out_.begin(), granted_paths_out_.end(), path); - if (it != granted_paths_out_.end()) { - granted_paths_out_.erase(it); - RebuildTree(PermissionScope::kFileSystemWrite); - } + if (perm != PermissionScope::kFileSystemRead && + perm != PermissionScope::kFileSystemWrite) { + return; + } + std::string wildcard = res; + if (wildcard.back() != node::kPathSeparator) { + wildcard += node::kPathSeparator; + } + wildcard += '*'; + auto& paths = perm == PermissionScope::kFileSystemRead ? granted_paths_in_ + : granted_paths_out_; + if (std::erase_if(paths, [&](const std::string& p) { + return p == res || p == wildcard; + }) > 0) { + RebuildTree(perm); } } diff --git a/src/permission/permission.cc b/src/permission/permission.cc index 53d3a7657440..4b1899e9d09e 100644 --- a/src/permission/permission.cc +++ b/src/permission/permission.cc @@ -116,23 +116,26 @@ static void Drop(const FunctionCallbackInfo<Value>& args) { "owns the process state"); } - if (args.Length() > 1 && !args[1]->IsUndefined()) { + if (args.Length() > 1 && !args[1]->IsNullOrUndefined()) { // BufferValue copies raw bytes out of a Buffer/TypedArray as-is instead // of forcing a (potentially lossy) UTF-8 string conversion, since paths // are not guaranteed to be valid UTF-8. BufferValue resource(env->isolate(), args[1]); - if (resource.length() > 0) { - // A wildcard would drop more than one variable at once. Dropping the - // whole scope, without a reference, is the only way to do that. - if (scope == PermissionScope::kEnv && - resource.ToStringView().back() == '*') { - return THROW_ERR_INVALID_ARG_VALUE( - env, - "Wildcards are not supported when dropping environment variables"); - } - env->permission()->Drop(env, scope, resource.ToStringView()); - return; + if (resource.length() == 0) { + // An empty reference must not fall through to dropping the whole scope. + return THROW_ERR_INVALID_ARG_VALUE( + env, "The \"reference\" argument must not be empty"); } + // A wildcard would drop more than one variable at once. Dropping the + // whole scope, without a reference, is the only way to do that. + if (scope == PermissionScope::kEnv && + resource.ToStringView().back() == '*') { + return THROW_ERR_INVALID_ARG_VALUE( + env, + "Wildcards are not supported when dropping environment variables"); + } + env->permission()->Drop(env, scope, resource.ToStringView()); + return; } env->permission()->Drop(env, scope, ""); diff --git a/src/quic/application.h b/src/quic/application.h index 4fd748763742..e199660b66e3 100644 --- a/src/quic/application.h +++ b/src/quic/application.h @@ -60,6 +60,12 @@ class Session::Application : public MemoryRetainer { // and is not necessarily 0. virtual error_code GetNoErrorCode() const = 0; + // Returns whether an application error code means "no error". + // Applications may override this when unknown codes have special semantics. + virtual bool IsNoErrorCode(error_code code) const { + return code == GetNoErrorCode(); + } + // The "internal error code" is the application-level error code used // to signal a non-specific failure when no more specific code has // been provided by the caller. For example, `writer.fail(reason)` on diff --git a/src/quic/data.cc b/src/quic/data.cc index 1a1d75b38a66..0de12774516a 100644 --- a/src/quic/data.cc +++ b/src/quic/data.cc @@ -442,17 +442,6 @@ const char* QuicError::name() const { } MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const { - if ((type() == Type::TRANSPORT && code() == NGTCP2_NO_ERROR) || - (type() == Type::APPLICATION && - (code() == 0 || code() == NGHTTP3_H3_NO_ERROR)) || - type() == Type::IDLE_CLOSE) { - // Application code 0 is the default no-error code for raw QUIC - // applications (DefaultApplication::GetNoErrorCode() returns 0). - // NGHTTP3_H3_NO_ERROR (0x100) is the HTTP/3 no-error code. - // Idle close is always clean — the session timed out normally. - return Undefined(env->isolate()); - } - Local<Value> type_str; if (!node::ToV8Value(env->context(), TypeName(type())).ToLocal(&type_str)) { return {}; @@ -467,7 +456,7 @@ MaybeLocal<Value> QuicError::ToV8Value(Environment* env) const { // Note that per the QUIC specification, the reason, if present, is // expected to be UTF-8 encoded. The spec uses the term "SHOULD" here, - // which means that is is entirely possible that some QUIC implementation + // which means that is entirely possible that some QUIC implementation // could choose a different encoding, in which case the conversion here // will produce garbage. That's ok though, we're going to use the default // assumption that the impl is following the guidelines. diff --git a/src/quic/data.h b/src/quic/data.h index 740d962638fc..004ba7734ed3 100644 --- a/src/quic/data.h +++ b/src/quic/data.h @@ -285,12 +285,13 @@ class QuicError final : public MemoryRetainer { std::string ToString() const; - // Returns an array containing [type, code, reason, error_name], where type - // is a string representation of the error type, code is a bigint - // representation of the error code, and reason is a string representation - // of the error reason, or undefined if the reason is empty. error_name is - // the symbolic name of a recognized transport error, or undefined. This is - // expected to be used to construct a JS error object. + // Returns an array containing [type, code, reason, error_name]. type is a + // string representation of the error type, code is a bigint representation + // of the error code, reason is a string or undefined, and error_name is the + // symbolic name of a recognized transport error or undefined. This lossless + // representation is used to construct a JS error object; whether the code + // means "no error" depends on the negotiated application and is determined + // by Session. v8::MaybeLocal<v8::Value> ToV8Value(Environment* env) const; inline v8::MaybeLocal<v8::Value> ToV8Value(Realm* realm) const { return ToV8Value(realm->env()); diff --git a/src/quic/endpoint.cc b/src/quic/endpoint.cc index 13ca955fa2a4..04c9b9d3b49f 100644 --- a/src/quic/endpoint.cc +++ b/src/quic/endpoint.cc @@ -1268,11 +1268,18 @@ BaseObjectPtr<Session> Endpoint::Connect( return {}; } + AddSession(config.scid, session); + + // Send the first flight before marking the session as wrapped. If the + // session closes during that send (no usable cipher suite or group, an + // expired handshake timeout), FinishClose() has to destroy it directly + // instead of calling into JavaScript, which has no QuicSession for it yet. + { Session::SendPendingDataScope send_scope(session); } + if (session->is_destroyed()) return {}; + // Marking a session as "wrapped" means that the reference has been // (or will be) passed out to JavaScript. - Session::SendPendingDataScope send_scope(session); session->set_wrapped(); - AddSession(config.scid, session); return session; } diff --git a/src/quic/http3.cc b/src/quic/http3.cc index ad0d6e383fe3..d77accd10cdc 100644 --- a/src/quic/http3.cc +++ b/src/quic/http3.cc @@ -37,6 +37,9 @@ constexpr size_t kSessionTicketAppDataHeaderSize = 6; // type + version + crc constexpr size_t kSessionTicketAppDataPayloadSize = kSessionTicketAppDataSize - kSessionTicketAppDataHeaderSize; +// RFC 9297 defines H3_DATAGRAM_ERROR, but nghttp3 does not expose it. +constexpr error_code kH3DatagramError = 0x33; + inline void WriteBE32(uint8_t* buf, uint32_t val) { buf[0] = static_cast<uint8_t>((val >> 24) & 0xff); buf[1] = static_cast<uint8_t>((val >> 16) & 0xff); @@ -186,6 +189,22 @@ class Http3ApplicationImpl final : public Session::Application { error_code GetNoErrorCode() const override { return NGHTTP3_H3_NO_ERROR; } + bool IsNoErrorCode(error_code code) const override { + if (code == NGHTTP3_H3_NO_ERROR) return true; + if (code == kH3DatagramError) return false; + + switch (code) { +#define V(name) case NGHTTP3_##name: + HTTP3_APPLICATION_ERRORS(V) +#undef V + return false; + default: + // RFC 9114 Section 8 requires unknown HTTP/3 error codes to be + // treated as equivalent to H3_NO_ERROR. + return true; + } + } + // HTTP/3 defines H3_INTERNAL_ERROR (0x102) for non-specific failures // initiated by the implementation; this is the right code to send // on RESET_STREAM when a stream is being aborted without an @@ -543,7 +562,14 @@ class Http3ApplicationImpl final : public Session::Application { } void StreamRemoved(stream_id id) override { - if (conn_) nghttp3_conn_set_stream_user_data(*this, id, nullptr); + if (!conn_) return; + // Once the Stream is gone, nothing can supply its body data. Stop + // nghttp3 from writing to it. Otherwise a response whose headers were + // submitted but not yet sent makes nghttp3 call on_read_data_callback + // for a stream that no longer exists, which fails and closes the + // whole session. + nghttp3_conn_shutdown_stream_write(*this, id); + nghttp3_conn_set_stream_user_data(*this, id, nullptr); } bool SendHeaders(Stream& stream, diff --git a/src/quic/session.cc b/src/quic/session.cc index e0de45d13fde..66899f43ad68 100644 --- a/src/quic/session.cc +++ b/src/quic/session.cc @@ -629,6 +629,20 @@ Maybe<Session::Options> Session::Options::From(Environment* env, #undef SET + // ngtcp2 only asserts this range. With assertions compiled out, a value + // below the minimum gives the congestion controller an initial window it + // cannot work with: zero makes it divide by zero as soon as the connection + // is created. + if (options.max_payload_size < NGTCP2_MAX_UDP_PAYLOAD_SIZE || + options.max_payload_size > NGTCP2_MAX_TX_UDP_PAYLOAD_SIZE) { + THROW_ERR_INVALID_ARG_VALUE(env, + "The maxPayloadSize option must be between " + "%d and %d", + NGTCP2_MAX_UDP_PAYLOAD_SIZE, + NGTCP2_MAX_TX_UDP_PAYLOAD_SIZE); + return Nothing<Options>(); + } + // RFC 9000 Section 10.2 requires the draining period to be at least 3x PTO. static const uint8_t kMinDrainingPeriodMultiplier = 3; options.draining_period_multiplier = std::max( @@ -1167,17 +1181,26 @@ struct Session::Impl final : public MemoryRetainer { } DCHECK(args[0]->IsUint32()); + DCHECK(args[1]->IsBoolean()); + + auto direction = FromV8Value<Direction>(args[0]); + if (!args[1].As<v8::Boolean>()->Value()) { + // This is waitUntilAvailable + if (!session->CanImmediatelyOpenStream(direction)) { + return THROW_ERR_INVALID_STATE( + env, "No new stream available within flow control"); + } + } // GetDataQueueFromSource handles type validation. std::shared_ptr<DataQueue> data_source; - if (!Stream::GetDataQueueFromSource(env, args[1]).To(&data_source)) + if (!Stream::GetDataQueueFromSource(env, args[2]).To(&data_source)) [[unlikely]] { return THROW_ERR_INVALID_ARG_VALUE(env, "Invalid data source"); } session->impl_->handshake_deferred_ = false; SendPendingDataScope send_scope(session); - auto direction = FromV8Value<Direction>(args[0]); Local<Object> stream; if (session->OpenStream(direction, std::move(data_source)).ToLocal(&stream)) [[likely]] { @@ -2083,27 +2106,26 @@ void Session::SendPendingData() { closed = true; return; } - } else if (stream_data.id >= 0) { + } else if (ndatalen < 0 && nwrite >= 0 && stream_data.id >= 0) { Debug(this, "Session did not accept any bytes from stream %" PRIi64 " into packet", stream_data.id); + // ndatalen < 0 means this stream's frame (data or FIN) was left out of + // the packet, due to congestion/pacing (nwrite == 0) or because other + // frames filled it. Reschedule the stream so it is retried later. + // This calls Application::ResumeStream directly (not + // Session::ResumeStream) to avoid creating a SendPendingDataScope - + // we're already inside SendPendingData. + if (stream_data.count > 0 || stream_data.fin) { + application().ResumeStream(stream_data.id); + } } // When nwrite is zero, it means we are congestion limited or it is - // just not our turn to send something. Re-schedule the stream if it - // had unsent data (payload or FIN) so the next timer-triggered - // SendPendingData retries it. Without this, a FIN-only send that - // hits nwrite=0 is lost forever — the stream already returned EOS - // from Pull and won't be re-scheduled by anyone else. - // We call Application::ResumeStream directly (not Session::ResumeStream) - // to avoid creating a SendPendingDataScope — we're already inside - // SendPendingData and re-entering would just hit nwrite=0 again. + // just not our turn to send something. if (nwrite == 0 && (stream_data.id >= 0 || !HasPendingDatagrams())) { Debug(this, "Congestion or not our turn to send"); - if (stream_data.id >= 0 && (stream_data.count > 0 || stream_data.fin)) { - application().ResumeStream(stream_data.id); - } return; } @@ -2776,6 +2798,24 @@ void Session::SetLastError(QuicError&& error) { impl_->last_error_ = std::move(error); } +bool Session::IsNoError(const QuicError& error) const { + switch (error.type()) { + case QuicError::Type::TRANSPORT: + return error.code() == NGTCP2_NO_ERROR; + case QuicError::Type::APPLICATION: + return has_application() && application().IsNoErrorCode(error.code()); + case QuicError::Type::IDLE_CLOSE: + return true; + default: + return false; + } +} + +MaybeLocal<Value> Session::ToV8ErrorValue(const QuicError& error) const { + if (IsNoError(error)) return Undefined(env()->isolate()); + return error.ToV8Value(env()); +} + bool Session::Receive(const uint8_t* data, size_t len, const SocketAddress& local_address, @@ -3208,6 +3248,14 @@ BaseObjectPtr<Stream> Session::CreateStream( return {}; } +bool Session::CanImmediatelyOpenStream(Direction direction) { + if (direction == Direction::BIDIRECTIONAL) { + return max_local_streams_bidi() > 0; + } else { + return max_local_streams_uni() > 0; + } +} + MaybeLocal<Object> Session::OpenStream(Direction direction, std::shared_ptr<DataQueue> data_source) { // If can_create_streams() returns false, we are not able to open a stream @@ -3513,13 +3561,12 @@ void Session::SetApplicationError(error_code app_error_code) { uint64_t Session::max_local_streams_uni() const { DCHECK(!is_destroyed()); - return ngtcp2_conn_get_streams_uni_left(*this); + return ngtcp2_conn_get_streams_uni_left2(*this); } uint64_t Session::max_local_streams_bidi() const { DCHECK(!is_destroyed()); - return ngtcp2_conn_get_local_transport_params(*this) - ->initial_max_streams_bidi; + return ngtcp2_conn_get_streams_bidi_left2(*this); } void Session::set_wrapped() { @@ -4018,27 +4065,9 @@ void Session::EmitClose(const QuicError& error) { CallbackScope<Session> cb_scope(this); - Local<Value> argv[] = { - Integer::New(env()->isolate(), static_cast<int>(error.type())), - BigInt::NewFromUnsigned(env()->isolate(), error.code()), - Undefined(env()->isolate()), - Undefined(env()->isolate()), - }; - if (error.reason().length() > 0 && - !ToV8Value(env()->context(), error.reason()).ToLocal(&argv[2])) { - return; - } - - // Attach a human-readable name for known wire codes (RFC 9000 sec. 20.1 - // names and OpenSSL TLS alert descriptions for CRYPTO_ERROR). Unknown - // codes leave the slot as undefined. See QuicError::name() for the - // matching path on stream-level errors. - if (const char* n = error.name()) { - argv[3] = BindingData::Get(env()).error_name_string(n); - } - - MakeCallback( - BindingData::Get(env()).session_close_callback(), arraysize(argv), argv); + Local<Value> err; + if (!ToV8ErrorValue(error).ToLocal(&err)) return; + MakeCallback(BindingData::Get(env()).session_close_callback(), 1, &err); // Importantly, the session instance itself should have been destroyed! CHECK(is_destroyed()); diff --git a/src/quic/session.h b/src/quic/session.h index 9834aa7ec130..941351c7b7b3 100644 --- a/src/quic/session.h +++ b/src/quic/session.h @@ -535,6 +535,9 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source { size_t max_packet_size() const; void set_priority_supported(bool on = true); + // Check whether flow control permits opening another stream + bool CanImmediatelyOpenStream(Direction direction); + // Open a new locally-initialized stream with the specified directionality. // If the session is not yet in a state where the stream can be opened -- // such as when the handshake is not yet sufficiently far along and ORTT @@ -546,6 +549,8 @@ class Session final : public AsyncWrap, private SessionTicket::AppData::Source { void ExtendStreamOffset(stream_id id, size_t amount); void ExtendOffset(size_t amount); void SetLastError(QuicError&& error); + bool IsNoError(const QuicError& error) const; + v8::MaybeLocal<v8::Value> ToV8ErrorValue(const QuicError& error) const; uint64_t max_data_left() const; // Transport operations that protocol applications (e.g. HTTP/3) invoke on diff --git a/src/quic/streams.cc b/src/quic/streams.cc index c62ceeb2a8e3..f29bab507a40 100644 --- a/src/quic/streams.cc +++ b/src/quic/streams.cc @@ -50,6 +50,7 @@ namespace quic { V(WRITE_ENDED, write_ended, uint8_t) \ V(RESET, reset, uint8_t) \ V(RESET_CODE, reset_code, uint64_t) \ + V(RESET_CODE_IS_ERROR, reset_code_is_error, uint8_t) \ V(HAS_OUTBOUND, has_outbound, uint8_t) \ V(HAS_READER, has_reader, uint8_t) \ /* Set when the stream has a block event handler */ \ @@ -437,8 +438,12 @@ struct Stream::Impl { ASSIGN_OR_RETURN_UNWRAP(&stream, args.This()); CHECK(args[0]->IsBigInt()); error_code code = args[0].As<BigInt>()->Uint64Value(); + const auto error = QuicError::ForApplication(code); + const bool is_error = !stream->session().IsNoError(error); stream->SendStopSending(code); + + args.GetReturnValue().Set(is_error); } // Sends a reset stream to the peer to tell it we will not be sending any @@ -1740,8 +1745,8 @@ void Stream::ReceiveStopSending(QuicError error) { void Stream::ReceiveStreamReset(uint64_t final_size, QuicError error) { // Importantly, reset stream only impacts the inbound data flow. It has no - // impact on the outbound data flow. It is essentially a signal that the peer - // has abruptly terminated the writable end of their stream with an error. + // impact on the outbound data flow. It signals that the peer abruptly + // terminated the writable end of its stream with an application code. // Any data we have received up to this point remains in the queue waiting to // be read. Debug(this, @@ -1749,6 +1754,7 @@ void Stream::ReceiveStreamReset(uint64_t final_size, QuicError error) { final_size, error); state()->reset_code = error.code(); + state()->reset_code_is_error = !session().IsNoError(error); TruncateReadable(final_size); EmitReset(error); } @@ -1862,7 +1868,7 @@ void Stream::EmitClose(const QuicError& error) { if (!env()->can_call_into_js()) return; CallbackScope<Stream> cb_scope(this); Local<Value> err; - if (!error.ToV8Value(env()).ToLocal(&err)) return; + if (!session().ToV8ErrorValue(error).ToLocal(&err)) return; MakeCallback(BindingData::Get(env()).stream_close_callback(), 1, &err); } diff --git a/src/quic/streams.h b/src/quic/streams.h index db6caaec088b..0264feccb482 100644 --- a/src/quic/streams.h +++ b/src/quic/streams.h @@ -356,7 +356,7 @@ class Stream final : public AsyncWrap, // stream. bool fin = false; // Indicates that this chunk of data was received in a 0RTT packet before - // the TLS handshake completed, suggesting that is is not as secure and + // the TLS handshake completed, suggesting that is not as secure and // could be replayed by an attacker. bool early = false; }; diff --git a/src/quic/tlscontext.cc b/src/quic/tlscontext.cc index 081af891b990..267e9fe02dde 100644 --- a/src/quic/tlscontext.cc +++ b/src/quic/tlscontext.cc @@ -189,10 +189,10 @@ OSSLContext::~OSSLContext() { void OSSLContext::reset() { if (ctx_) { - // The SSL object inside the ngtcp2 ctx may not have been set if - // SSL creation failed. Guard against null before clearing app data. - if (SSL* ssl = *this; ssl != nullptr) { - SSL_set_app_data(ssl, nullptr); + if (ssl_) { + SSL_set_app_data(ssl_.get(), nullptr); + ngtcp2_crypto_ossl_ctx_set_ssl(ctx_, nullptr); + ssl_.reset(); } // connection_ is set during Initialize(). If Initialize() was // never called (e.g. SSL creation failed), it's still nullptr. @@ -206,19 +206,20 @@ void OSSLContext::reset() { } OSSLContext::operator SSL*() const { - return ngtcp2_crypto_ossl_ctx_get_ssl(ctx_); + return ssl_.get(); } OSSLContext::operator ngtcp2_crypto_ossl_ctx*() const { return ctx_; } -void OSSLContext::Initialize(SSL* ssl, +void OSSLContext::Initialize(SSLPointer ssl, ngtcp2_crypto_conn_ref* ref, ngtcp2_conn* connection, SSL_CTX* ssl_ctx) { CHECK(ssl); - ngtcp2_crypto_ossl_ctx_set_ssl(ctx_, ssl); + ssl_ = std::move(ssl); + ngtcp2_crypto_ossl_ctx_set_ssl(ctx_, ssl_.get()); SSL_set_app_data(*this, ref); // TODO(@jasnell): Later when BoringSSL is also supported, the native // handle will be different. The ngtcp2_crypto_ossl.h impl requires @@ -276,8 +277,8 @@ bool OSSLContext::set_verify_hostname(std::string_view hostname) const { } } -bool OSSLContext::set_early_data_enabled() const { - return SSL_set_quic_tls_early_data_enabled(*this, 1) == 1; +bool OSSLContext::set_early_data_enabled(bool enabled) const { + return SSL_set_quic_tls_early_data_enabled(*this, enabled) == 1; } bool OSSLContext::set_transport_params(const ngtcp2_vec& tp) const { @@ -302,10 +303,10 @@ bool OSSLContext::set_session_ticket(const ncrypto::SSLSessionPointer& ticket) { return SSL_SESSION_get_max_early_data(ticket.get()) != 0; } -bool OSSLContext::ConfigureServer() const { +bool OSSLContext::ConfigureServer(bool enable_early_data) const { if (ngtcp2_crypto_ossl_configure_server_session(*this) != 0) return false; SSL_set_accept_state(*this); - return set_early_data_enabled(); + return set_early_data_enabled(enable_early_data); } bool OSSLContext::ConfigureClient() const { @@ -899,11 +900,12 @@ void TLSSession::Initialize( EnableTrace(session_->env(), &bio_trace_, ssl); } - ossl_context_.Initialize(ssl.release(), &ref_, session(), ctx); + ossl_context_.Initialize(std::move(ssl), &ref_, session(), ctx); switch (ctx.side()) { case Side::SERVER: { - if (!ossl_context_.ConfigureServer()) [[unlikely]] { + if (!ossl_context_.ConfigureServer(options.enable_early_data)) + [[unlikely]] { validation_error_ = "Failed to configure server session"; ossl_context_.reset(); return; @@ -951,7 +953,7 @@ void TLSSession::Initialize( ngtcp2_vec rtp = sessionTicket.transport_params(); if (ngtcp2_conn_decode_and_set_0rtt_transport_params( *session_, rtp.base, rtp.len) == 0) { - if (!ossl_context_.set_early_data_enabled()) { + if (!ossl_context_.set_early_data_enabled(true)) { validation_error_ = "Failed to enable early data"; ossl_context_.reset(); return; diff --git a/src/quic/tlscontext.h b/src/quic/tlscontext.h index ecadc1fa78d5..db4c7e97843c 100644 --- a/src/quic/tlscontext.h +++ b/src/quic/tlscontext.h @@ -41,7 +41,7 @@ class OSSLContext final { operator SSL*() const; operator ngtcp2_crypto_ossl_ctx*() const; - void Initialize(SSL* ssl, + void Initialize(ncrypto::SSLPointer ssl, ngtcp2_crypto_conn_ref* ref, ngtcp2_conn* connection, SSL_CTX* ssl_ctx); @@ -53,7 +53,7 @@ class OSSLContext final { bool set_alpn_protocols(std::string_view protocols) const; bool set_hostname(std::string_view hostname) const; bool set_verify_hostname(std::string_view hostname) const; - bool set_early_data_enabled() const; + bool set_early_data_enabled(bool enabled) const; bool set_transport_params(const ngtcp2_vec& tp) const; bool get_early_data_accepted() const; @@ -64,7 +64,7 @@ class OSSLContext final { // ticket was set successfully and the ticket supports early data. bool set_session_ticket(const ncrypto::SSLSessionPointer& ticket); - bool ConfigureServer() const; + bool ConfigureServer(bool enable_early_data) const; bool ConfigureClient() const; void reset(); @@ -73,6 +73,7 @@ class OSSLContext final { private: ngtcp2_crypto_ossl_ctx* ctx_; ngtcp2_conn* connection_ = nullptr; + ncrypto::SSLPointer ssl_; }; // Every QUIC Session has exactly one TLSSession that maintains the state diff --git a/src/stream_base.cc b/src/stream_base.cc index a73a39513fb0..fb16da9b5a9f 100644 --- a/src/stream_base.cc +++ b/src/stream_base.cc @@ -8,6 +8,7 @@ #include "node_buffer.h" #include "node_errors.h" #include "node_external_reference.h" +#include "simdutf.h" #include "string_bytes.h" #include "util-inl.h" #include "v8.h" @@ -18,6 +19,7 @@ namespace node { using v8::Array; using v8::ArrayBuffer; +using v8::ArrayBufferView; using v8::BackingStore; using v8::BackingStoreInitializationMode; using v8::ConstructorBehavior; @@ -162,8 +164,8 @@ int StreamBase::ReadStopJS(const FunctionCallbackInfo<Value>& args) { int StreamBase::UseUserBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(Buffer::HasInstance(args[0])); - uv_buf_t buf = uv_buf_init(Buffer::Data(args[0]), Buffer::Length(args[0])); - PushStreamListener(new CustomBufferJSListener(buf)); + PushStreamListener( + new CustomBufferJSListener(args.This(), args[0].As<ArrayBufferView>())); return 0; } @@ -196,6 +198,38 @@ int StreamBase::FinishWrite(const v8::FunctionCallbackInfo<v8::Value>& args, return res.err; } +namespace { + +// Same as StringBytes::Write(), but copies one-byte strings out with +// String::WriteOneByte(), which does not flatten them: strings written to a +// stream are often built by concatenation (e.g. HTTP headers) and not used +// again. +size_t WriteStringWithoutFlattening(Isolate* isolate, + char* buf, + size_t buflen, + Local<String> string, + enum encoding enc) { + const size_t length = string->Length(); + if (length == 0) return 0; + if (string->IsOneByte()) { + if ((enc == ASCII || enc == LATIN1) && buflen >= length) { + string->WriteOneByte(isolate, 0, length, reinterpret_cast<uint8_t*>(buf)); + return length; + } + if (enc == UTF8 && buflen >= 3 * length) { + // Latin-1 takes at most 2 UTF-8 bytes per char: convert from the last + // third into the first two. + char* latin1 = buf + 2 * length; + string->WriteOneByte( + isolate, 0, length, reinterpret_cast<uint8_t*>(latin1)); + return simdutf::convert_latin1_to_utf8(latin1, length, buf); + } + } + return StringBytes::Write(isolate, buf, buflen, string, enc); +} + +} // namespace + int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); Isolate* isolate = env->isolate(); @@ -297,11 +331,8 @@ int StreamBase::Writev(const FunctionCallbackInfo<Value>& args) { if (!chunks->Get(context, i * 2 + 1).ToLocal(&next_chunk)) return -1; enum encoding encoding = ParseEncoding(isolate, next_chunk); - str_size = StringBytes::Write(isolate, - str_storage, - str_size, - string, - encoding); + str_size = WriteStringWithoutFlattening( + isolate, str_storage, str_size, string, encoding); bufs[i].base = str_storage; bufs[i].len = str_size; offset += str_size; @@ -372,7 +403,7 @@ int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) { if (args[2]->IsObject()) send_handle_obj = args[2].As<Object>(); - // Compute the size of the storage that the string will be flattened into. + // Compute the size of the storage that the string will be written into. // For UTF8 strings that are very long, go ahead and take the hit for // computing their actual size, rather than tripling the storage. size_t storage_size; @@ -395,11 +426,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) { bool try_write = HasDoTryWrite() && storage_size <= sizeof(stack_storage) && (!IsIPCPipe() || send_handle_obj.IsEmpty()); if (try_write) { - data_size = StringBytes::Write(isolate, - stack_storage, - storage_size, - string, - enc); + data_size = WriteStringWithoutFlattening( + isolate, stack_storage, storage_size, string, enc); buf = uv_buf_init(stack_storage, data_size); uv_buf_t* bufs = &buf; @@ -433,11 +461,8 @@ int StreamBase::WriteString(const FunctionCallbackInfo<Value>& args) { // Write it bs = ArrayBuffer::NewBackingStore( isolate, storage_size, BackingStoreInitializationMode::kUninitialized); - data_size = StringBytes::Write(isolate, - static_cast<char*>(bs->Data()), - storage_size, - string, - enc); + data_size = WriteStringWithoutFlattening( + isolate, static_cast<char*>(bs->Data()), storage_size, string, enc); } CHECK_LE(data_size, storage_size); @@ -725,6 +750,12 @@ void StreamResource::ClearError() { uv_buf_t EmitToJSStreamListener::OnStreamAlloc(size_t suggested_size) { CHECK_NOT_NULL(stream_); Environment* env = static_cast<StreamBase*>(stream_)->stream_env(); + // Reads that ask for less than a slab (e.g. decrypted TLS records, which + // are allocated at their exact size) get their own buffer: as views over + // a shared slab, any one of them kept by JS would keep the whole slab + // alive, along with every other read that was carved out of it. + if (suggested_size < StreamReadSlab::kSlabSize) + return env->allocate_managed_buffer(suggested_size); return env->stream_read_slab().Allocate(env->isolate(), suggested_size); } @@ -765,9 +796,47 @@ void EmitToJSStreamListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf_) { stream->CallJSOnreadMethod(nread, ab, offset); } +CustomBufferJSListener::CustomBufferJSListener(Local<Object> object, + Local<ArrayBufferView> view) { + SetBuffer(object, view); +} + +void CustomBufferJSListener::SetBuffer(Local<Object> object, + Local<ArrayBufferView> view) { + // Keep the view's lifetime tied to the wrapper without a strong global root. + object->SetInternalField(StreamBase::kUserBufferField, view); + backing_store_ = view->Buffer()->GetBackingStore(); +} uv_buf_t CustomBufferJSListener::OnStreamAlloc(size_t suggested_size) { - return buffer_; + CHECK_NOT_NULL(stream_); + StreamBase* stream = static_cast<StreamBase*>(stream_); + Environment* env = stream->stream_env(); + Isolate* isolate = env->isolate(); + HandleScope handle_scope(isolate); + + Local<ArrayBufferView> view = + stream->GetAsyncWrap() + ->object() + ->GetInternalField(StreamBase::kUserBufferField) + .As<Value>() + .As<ArrayBufferView>(); + if (!backing_store_->IsImmutable()) { + // SetBuffer() materializes the backing store, so this cannot copy. + const auto contents = view->GetContents({}); + // An attached empty backing store can also have a null data pointer. + if (contents.data() != nullptr || (backing_store_->MaxByteLength() == 0 && + !view->Buffer()->WasDetached())) { + buffer_ = uv_buf_init(reinterpret_cast<char*>(contents.data()), + contents.size()); + return buffer_; + } + } + + // Allocation must return a usable buffer. Report the invalid view when the + // read completes, without writing into the user's former backing store. + using_fallback_buffer_ = true; + return env->allocate_managed_buffer(suggested_size); } @@ -779,6 +848,13 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { HandleScope handle_scope(env->isolate()); Context::Scope context_scope(env->context()); + if (using_fallback_buffer_) { + using_fallback_buffer_ = false; + env->recycle_managed_buffer(env->release_managed_buffer(buf)); + stream->CallJSOnreadMethod(UV_EINVAL, Local<ArrayBuffer>()); + return; + } + // In the case that there's an error and buf is null, return immediately. // This can happen on unices when POLLHUP is received and UV_EOF is returned // or when getting an error while performing a UV_HANDLE_ZERO_READ on Windows. @@ -795,8 +871,9 @@ void CustomBufferJSListener::OnStreamRead(ssize_t nread, const uv_buf_t& buf) { StreamBase::SKIP_NREAD_CHECKS); Local<Value> next_buf_v; if (ret.ToLocal(&next_buf_v) && !next_buf_v->IsUndefined()) { - buffer_.base = Buffer::Data(next_buf_v); - buffer_.len = Buffer::Length(next_buf_v); + CHECK(Buffer::HasInstance(next_buf_v)); + SetBuffer(stream->GetAsyncWrap()->object(), + next_buf_v.As<ArrayBufferView>()); } } diff --git a/src/stream_base.h b/src/stream_base.h index 450205a1b863..a46348c26df6 100644 --- a/src/stream_base.h +++ b/src/stream_base.h @@ -11,6 +11,7 @@ #include "v8.h" #include <climits> // INT_MIN +#include <memory> namespace node { @@ -211,10 +212,17 @@ class CustomBufferJSListener : public ReportWritesToJSStreamListener { void OnStreamRead(ssize_t nread, const uv_buf_t& buf) override; void OnStreamDestroy() override { delete this; } - explicit CustomBufferJSListener(uv_buf_t buffer) : buffer_(buffer) {} + CustomBufferJSListener(v8::Local<v8::Object> object, + v8::Local<v8::ArrayBufferView> view); private: - uv_buf_t buffer_; + void SetBuffer(v8::Local<v8::Object> object, + v8::Local<v8::ArrayBufferView> view); + + // Retain the backing store so the address in buffer_ cannot dangle. + std::shared_ptr<v8::BackingStore> backing_store_; + uv_buf_t buffer_ = uv_buf_init(nullptr, 0); + bool using_fallback_buffer_ = false; }; @@ -314,6 +322,7 @@ class StreamBase : public StreamResource { kSlot = BaseObject::kSlot, kStreamBaseField = AsyncWrap::kInternalFieldCount, kOnReadFunctionField, + kUserBufferField, kInternalFieldCount }; diff --git a/src/stream_wrap.cc b/src/stream_wrap.cc index e2ffaa0f4e19..a1416b18d466 100644 --- a/src/stream_wrap.cc +++ b/src/stream_wrap.cc @@ -33,9 +33,9 @@ #include "udp_wrap.h" #include "util-inl.h" -#include <cstring> // memcpy() +#include <cerrno> // errno #include <climits> // INT_MAX - +#include <cstring> // memcpy() namespace node { @@ -137,6 +137,7 @@ void LibuvStreamWrap::RegisterExternalReferences( registry->Register(IsConstructCallCallback); registry->Register(GetWriteQueueSize); registry->Register(SetBlocking); + registry->Register(HasPendingRead); StreamBase::RegisterExternalReferences(registry); } @@ -175,6 +176,7 @@ Local<FunctionTemplate> LibuvStreamWrap::GetConstructorTemplate( Local<FunctionTemplate>(), static_cast<PropertyAttribute>(ReadOnly | DontDelete)); SetProtoMethod(isolate, tmpl, "setBlocking", SetBlocking); + SetProtoMethod(isolate, tmpl, "hasPendingRead", HasPendingRead); StreamBase::AddMethods(env, tmpl); env->set_libuv_stream_wrap_ctor_template(tmpl); } @@ -343,6 +345,67 @@ void LibuvStreamWrap::SetBlocking(const FunctionCallbackInfo<Value>& args) { args.GetReturnValue().Set(uv_stream_set_blocking(wrap->stream(), enable)); } +// Returns true if a read on the underlying socket would complete right now, +// i.e. the OS has data, EOF, or a socket error queued that libuv has not +// delivered yet because the event loop has not polled for I/O since it +// arrived. Nothing is consumed. Returns false when there is nothing pending +// or when the handle type does not support the check. +void LibuvStreamWrap::HasPendingRead(const FunctionCallbackInfo<Value>& args) { + LibuvStreamWrap* wrap; + ASSIGN_OR_RETURN_UNWRAP(&wrap, args.This()); + args.GetReturnValue().Set(false); + + if (!wrap->IsAlive() || wrap->IsClosing()) return; + +#ifdef _WIN32 + // Only TCP sockets can be probed with recv() on Windows. + if (!wrap->is_tcp()) return; +#else + if (!wrap->is_tcp() && !wrap->is_named_pipe()) return; +#endif + + uv_os_fd_t fd; + if (uv_fileno(reinterpret_cast<uv_handle_t*>(wrap->stream()), &fd) != 0) + return; + + char c; +#ifdef _WIN32 + // libuv puts TCP sockets in non-blocking mode and reads with zero-byte + // overlapped reads, so unread data stays in the kernel buffer. + int r = recv(reinterpret_cast<SOCKET>(fd), &c, 1, MSG_PEEK); + if (r == SOCKET_ERROR) { + switch (WSAGetLastError()) { + case WSAEWOULDBLOCK: + case WSAENOTCONN: + case WSAENOTSOCK: + return; + } + } +#else + int flags = MSG_PEEK; +#ifdef MSG_DONTWAIT + flags |= MSG_DONTWAIT; +#endif + ssize_t r; + do { + r = recv(fd, &c, 1, flags); + } while (r == -1 && errno == EINTR); + if (r == -1) { + switch (errno) { + case EAGAIN: +#if EWOULDBLOCK != EAGAIN + case EWOULDBLOCK: +#endif + case ENOTCONN: + case ENOTSOCK: + return; + } + } +#endif + + args.GetReturnValue().Set(true); +} + typedef SimpleShutdownWrap<ReqWrap<uv_shutdown_t>> LibuvShutdownWrap; typedef SimpleWriteWrap<ReqWrap<uv_write_t>> LibuvWriteWrap; diff --git a/src/stream_wrap.h b/src/stream_wrap.h index b06b4be6988b..74a5ddb00c2d 100644 --- a/src/stream_wrap.h +++ b/src/stream_wrap.h @@ -114,6 +114,7 @@ class LibuvStreamWrap : public HandleWrap, public StreamBase { static void GetWriteQueueSize( const v8::FunctionCallbackInfo<v8::Value>& info); static void SetBlocking(const v8::FunctionCallbackInfo<v8::Value>& args); + static void HasPendingRead(const v8::FunctionCallbackInfo<v8::Value>& args); // Callbacks for libuv void OnUvAlloc(size_t suggested_size, uv_buf_t* buf); diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 94b579b6984d..9aec2abc41a5 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -468,13 +468,13 @@ Maybe<size_t> StringBytes::StorageSize(Isolate* isolate, Local<String> str; if (!val->ToString(isolate->GetCurrentContext()).ToLocal(&str)) return Nothing<size_t>(); - String::ValueView view(isolate, str); + const size_t length = str->Length(); size_t data_size = 0; switch (encoding) { case ASCII: case LATIN1: - data_size = view.length(); + data_size = length; break; case BUFFER: @@ -482,24 +482,24 @@ Maybe<size_t> StringBytes::StorageSize(Isolate* isolate, // A single UCS2 codepoint never takes up more than 3 utf8 bytes. // It is an exercise for the caller to decide when a string is // long enough to justify calling Size() instead of StorageSize() - data_size = 3 * view.length(); + data_size = 3 * length; break; case UCS2: - data_size = view.length() * sizeof(uint16_t); + data_size = length * sizeof(uint16_t); break; case BASE64URL: - data_size = simdutf::base64_length_from_binary(view.length(), - simdutf::base64_url); + data_size = + simdutf::base64_length_from_binary(length, simdutf::base64_url); break; case BASE64: - data_size = simdutf::base64_length_from_binary(view.length()); + data_size = simdutf::base64_length_from_binary(length); break; case HEX: - data_size = view.length() / 2; + data_size = length / 2; break; default: diff --git a/src/threadpoolwork-inl.h b/src/threadpoolwork-inl.h index 729e3de8eeaa..3bbe9b4c9edf 100644 --- a/src/threadpoolwork-inl.h +++ b/src/threadpoolwork-inl.h @@ -24,6 +24,9 @@ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS +#include <string_view> +#include "env-inl.h" +#include "node_diagnostics_channel.h" #include "node_internals.h" #include "tracing/trace_event.h" #include "util-inl.h" @@ -34,14 +37,26 @@ void ThreadPoolWork::ScheduleWork() { env_->IncreaseWaitingRequestCounter(); TRACE_EVENT_NESTABLE_ASYNC_BEGIN0( TRACING_CATEGORY_NODE2(threadpoolwork, async), type_, this); + + // Some ThreadPoolWork instances are submitted more than once. + enqueued_at_ = 0; + work_start_ = 0; + work_end_ = 0; + + if (channel_ != nullptr && channel_->active) [[unlikely]] { + enqueued_at_ = uv_hrtime(); + } + int status = uv_queue_work( env_->event_loop(), &work_req_, [](uv_work_t* req) { ThreadPoolWork* self = ContainerOf(&ThreadPoolWork::work_req_, req); + if (self->IsObserved()) self->work_start_ = uv_hrtime(); TRACE_EVENT_BEGIN0(TRACING_CATEGORY_NODE2(threadpoolwork, sync), self->type_); self->DoThreadPoolWork(); + if (self->IsObserved()) self->work_end_ = uv_hrtime(); TRACE_EVENT_END0(TRACING_CATEGORY_NODE2(threadpoolwork, sync), self->type_); }, @@ -54,11 +69,51 @@ void ThreadPoolWork::ScheduleWork() { self, "result", status); + // AfterThreadPoolWork() may unsubscribe or delete `self`. + if (self->IsObserved()) { + auto* channel = self->channel_ == nullptr + ? nullptr + : self->channel_->channel.get(); + if (channel != nullptr) self->PublishDiagnostics(*channel); + } self->AfterThreadPoolWork(status); }); CHECK_EQ(status, 0); } +void ThreadPoolWork::PublishDiagnostics(diagnostics_channel::Channel& channel) { + if (!env_->can_call_into_js() || !channel.HasSubscribers()) return; + + v8::Isolate* isolate = env_->isolate(); + v8::HandleScope handle_scope(isolate); + v8::Local<v8::Context> context = env_->context(); + + // Match performance.now() without losing precision. + auto to_milliseconds = [isolate, origin = env_->time_origin()]( + uint64_t mark) -> v8::Local<v8::Value> { + if (mark == 0) return v8::Null(isolate); + return v8::Number::New(isolate, static_cast<double>(mark - origin) / 1e6); + }; + + v8::Local<v8::DictionaryTemplate> tmpl = env_->threadpool_work_template(); + if (tmpl.IsEmpty()) { + static constexpr std::string_view names[] = { + "enqueued", "started", "ended"}; + tmpl = v8::DictionaryTemplate::New(isolate, names); + env_->set_threadpool_work_template(tmpl); + } + + v8::MaybeLocal<v8::Value> values[] = { + to_milliseconds(enqueued_at_), + to_milliseconds(work_start_), + to_milliseconds(work_end_), + }; + + v8::Local<v8::Object> message; + if (!NewDictionaryInstance(context, tmpl, values).ToLocal(&message)) return; + channel.Publish(env_, message); +} + int ThreadPoolWork::CancelWork() { return uv_cancel(reinterpret_cast<uv_req_t*>(&work_req_)); } diff --git a/src/timers.cc b/src/timers.cc index 03f0910926f3..055597ecb9eb 100644 --- a/src/timers.cc +++ b/src/timers.cc @@ -104,9 +104,7 @@ bool BindingData::PrepareForSerialization(Local<Context> context, InternalFieldInfoBase* BindingData::Serialize(int index) { DCHECK_IS_SNAPSHOT_SLOT(index); - InternalFieldInfo* info = - InternalFieldInfoBase::New<InternalFieldInfo>(type()); - return info; + return InternalFieldInfoBase::New<InternalFieldInfo>(type()); } void BindingData::Deserialize(Local<Context> context, @@ -114,11 +112,7 @@ void BindingData::Deserialize(Local<Context> context, int index, InternalFieldInfoBase* info) { DCHECK_IS_SNAPSHOT_SLOT(index); - v8::HandleScope scope(Isolate::GetCurrent()); - Realm* realm = Realm::GetCurrent(context); - // Recreate the buffer in the constructor. - BindingData* binding = realm->AddBindingData<BindingData>(holder); - CHECK_NOT_NULL(binding); + Realm::DeserializeBindingData<BindingData>(context, holder); } v8::CFunction BindingData::fast_get_libuv_now_( diff --git a/src/tracing/trace_event_legacy.h b/src/tracing/trace_event_legacy.h index 92b2e88d4823..9dc218ec6711 100644 --- a/src/tracing/trace_event_legacy.h +++ b/src/tracing/trace_event_legacy.h @@ -1012,6 +1012,14 @@ } \ } while (0) +// Expression form of the above, matching Perfetto's macro of the same name. +#define TRACE_EVENT_CATEGORY_ENABLED(category_group) \ + ([] { \ + bool enabled; \ + TRACE_EVENT_CATEGORY_GROUP_ENABLED(category_group, &enabled); \ + return enabled; \ + }()) + // Macro to explicitly warm up a given category group. This could be useful in // cases where we want to initialize a category group before any trace events // for that category group is reported. For example, to have a category group diff --git a/src/tty_wrap.cc b/src/tty_wrap.cc index 0c4c02f6aa40..1f7161e0eec8 100644 --- a/src/tty_wrap.cc +++ b/src/tty_wrap.cc @@ -25,6 +25,7 @@ #include "handle_wrap.h" #include "node_buffer.h" #include "node_external_reference.h" +#include "node_internals.h" #include "stream_base-inl.h" #include "stream_wrap.h" #include "util-inl.h" @@ -134,6 +135,7 @@ void TTYWrap::SetRawMode(const FunctionCallbackInfo<Value>& args) { int mode; if (!args[0]->Int32Value(env->context()).To(&mode)) return; int err = uv_tty_set_mode(&wrap->handle_, static_cast<uv_tty_mode_t>(mode)); + if (err == 0 && mode != UV_TTY_MODE_NORMAL) SetTerminalModeChanged(); args.GetReturnValue().Set(err); } diff --git a/src/undici_version.h b/src/undici_version.h index e0a4578df6c0..81bfc11bb62e 100644 --- a/src/undici_version.h +++ b/src/undici_version.h @@ -2,5 +2,5 @@ // Refer to tools/dep_updaters/update-undici.sh #ifndef SRC_UNDICI_VERSION_H_ #define SRC_UNDICI_VERSION_H_ -#define UNDICI_VERSION "8.12.4" +#define UNDICI_VERSION "8.13.1" #endif // SRC_UNDICI_VERSION_H_ diff --git a/src/zlib_version.h b/src/zlib_version.h index 5e85dbba976f..696df9f6dff0 100644 --- a/src/zlib_version.h +++ b/src/zlib_version.h @@ -2,5 +2,5 @@ // Refer to tools/dep_updaters/update-zlib.sh #ifndef SRC_ZLIB_VERSION_H_ #define SRC_ZLIB_VERSION_H_ -#define ZLIB_VERSION "1.3.2.1-motley-9f9f52c" +#define ZLIB_VERSION "1.4-401d185" #endif // SRC_ZLIB_VERSION_H_ diff --git a/test/addons/async-resource/test-execution-async-resource.js b/test/addons/async-resource/test-execution-async-resource.js new file mode 100755 index 000000000000..51386bd3a6bb --- /dev/null +++ b/test/addons/async-resource/test-execution-async-resource.js @@ -0,0 +1,31 @@ +'use strict'; + +const common = require('../../common'); +const assert = require('assert'); +const binding = require(`./build/${common.buildType}/binding`); +const { executionAsyncId, executionAsyncResource } = require('async_hooks'); + +// No hook is enabled and executionAsyncResource() was never called, so the +// callback scope of AsyncResource::MakeCallback() skips the async id stack. +// executionAsyncResource() must still find the resource, and executionAsyncId() +// must still be the id of the callback, also around a nested callback. +let calls = 0; +const object = { + methöd: common.mustCall(function() { + assert.strictEqual(executionAsyncId(), uid); + assert.strictEqual(executionAsyncResource(), object); + if (calls++ === 0) { + assert.strictEqual(binding.callViaFunction(resource), 'baz'); + assert.strictEqual(executionAsyncId(), uid); + assert.strictEqual(executionAsyncResource(), object); + } + return 'baz'; + }, 2), +}; +const resource = binding.createAsyncResource(object); +const uid = binding.getAsyncId(resource); +const outerId = executionAsyncId(); + +assert.strictEqual(binding.callViaFunction(resource), 'baz'); +assert.strictEqual(executionAsyncId(), outerId); +binding.destroyAsyncResource(resource); diff --git a/test/addons/dlopen-ping-pong/binding.cc b/test/addons/dlopen-ping-pong/binding.cc index be33708c9317..bba489c28105 100644 --- a/test/addons/dlopen-ping-pong/binding.cc +++ b/test/addons/dlopen-ping-pong/binding.cc @@ -13,6 +13,7 @@ const char* dlopen_pong(void) { namespace { +using v8::Exception; using v8::FunctionCallbackInfo; using v8::Isolate; using v8::Local; @@ -24,20 +25,43 @@ typedef const char* (*ping)(void); static ping ping_func; +void ThrowError(Isolate* isolate, const char* message) { + isolate->ThrowException( + Exception::Error(String::NewFromUtf8(isolate, message).ToLocalChecked())); +} + void LoadLibrary(const FunctionCallbackInfo<Value>& args) { - const String::Utf8Value filename(args.GetIsolate(), args[0]); + Isolate* isolate = args.GetIsolate(); + const String::Utf8Value filename(isolate, args[0]); + char* dlerrormsg; void* handle = dlopen(*filename, RTLD_LAZY); - if (handle == nullptr) fprintf(stderr, "%s\n", dlerror()); - assert(handle != nullptr); + if (handle == nullptr) { + dlerrormsg = dlerror(); + ThrowError(isolate, dlerrormsg != nullptr ? dlerrormsg : "dlopen failed"); + return; + } ping_func = reinterpret_cast<ping>(dlsym(handle, "dlopen_ping")); - assert(ping_func != nullptr); + if (ping_func == nullptr) { + if (dlclose(handle) != 0) { + ThrowError(isolate, "dlclose failed"); + return; + } + } } void Ping(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = args.GetIsolate(); - assert(ping_func != nullptr); - args.GetReturnValue().Set(String::NewFromUtf8( - isolate, ping_func()).ToLocalChecked()); + if (ping_func == nullptr) { + ThrowError(isolate, "ping library was not loaded"); + return; + } + const char* answer = ping_func(); + if (answer == nullptr) { + ThrowError(isolate, "dlopen_pong could not be resolved (RTLD_GLOBAL)"); + return; + } + args.GetReturnValue().Set( + String::NewFromUtf8(isolate, answer).ToLocalChecked()); } void init(Local<Object> exports) { diff --git a/test/addons/dlopen-ping-pong/binding.gyp b/test/addons/dlopen-ping-pong/binding.gyp index c3edcf0dbedc..ff6381d25788 100644 --- a/test/addons/dlopen-ping-pong/binding.gyp +++ b/test/addons/dlopen-ping-pong/binding.gyp @@ -10,10 +10,12 @@ 'xcode_settings': { 'OTHER_LDFLAGS': [ '-Wl,-undefined', '-Wl,dynamic_lookup' ] }}], - # Enable the shared object to be linked by runtime linker - ['OS in "aix os400"', { + # Deferred import of dlopen_pong (-Wl,-G) where ping.c links it directly. + # AIX uses dlsym(RTLD_DEFAULT) in ping.c instead of a link-time import. + ['OS=="os400"', { 'ldflags': [ '-Wl,-G' ] - }]], + }], + ], }, { 'target_name': 'binding', diff --git a/test/addons/dlopen-ping-pong/ping.c b/test/addons/dlopen-ping-pong/ping.c index c76f40580c41..1f5b1bff47ac 100644 --- a/test/addons/dlopen-ping-pong/ping.c +++ b/test/addons/dlopen-ping-pong/ping.c @@ -1,10 +1,26 @@ #ifndef _WIN32 +#if defined(_AIX) +#include <stddef.h> +#include <dlfcn.h> +#else const char* dlopen_pong(void); +#endif __attribute__((visibility("default"))) const char* dlopen_ping(void) { +#if defined(_AIX) + /* ping.so is built with -Wl,-G: link-time import of dlopen_pong is resolved + * when ping.so is loaded. On --shared libnode builds that resolution can fail + * even when dlopen_pong appears in binding's loader table (dump). Resolve + * at call time via the global symbol set after process.dlopen(RTLD_GLOBAL). */ + typedef const char* (*pong_fn)(void); + pong_fn pong = + (pong_fn)dlsym(RTLD_DEFAULT, "dlopen_pong"); + return pong != NULL ? pong() : NULL; +#else return dlopen_pong(); +#endif } #endif // _WIN32 diff --git a/test/cctest/inspector/test_main_thread_interface.cc b/test/cctest/inspector/test_main_thread_interface.cc new file mode 100644 index 000000000000..edb8dd57f976 --- /dev/null +++ b/test/cctest/inspector/test_main_thread_interface.cc @@ -0,0 +1,54 @@ +#include "gtest/gtest.h" +#include "inspector/main_thread_interface.h" +#include "inspector/worker_inspector.h" +#include "node_test_fixture.h" + +#include <memory> + +namespace node { +namespace inspector { +namespace { + +class MainThreadInterfaceTest : public EnvironmentTestFixture {}; + +class RetainInterfaceRequest : public Request { + public: + explicit RetainInterfaceRequest( + std::shared_ptr<MainThreadInterface>* retained_interface) + : retained_interface_(retained_interface) {} + + void Call(MainThreadInterface* thread) override { + *retained_interface_ = thread->shared_from_this(); + } + + private: + std::shared_ptr<MainThreadInterface>* retained_interface_; +}; + +TEST_F(MainThreadInterfaceTest, ClosesHandleBeforeReleasingInterface) { + const v8::HandleScope handle_scope(isolate_); + const Argv argv; + std::shared_ptr<MainThreadInterface> retained_interface; + std::shared_ptr<MainThreadHandle> handle; + { + Env env{handle_scope, argv}; + handle = (*env)->inspector_agent()->GetWorkerManager()->MainThread(); + ASSERT_FALSE(handle->Expired()); + ASSERT_TRUE(handle->Post( + std::make_unique<RetainInterfaceRequest>(&retained_interface))); + (*env)->RunAndClearInterrupts(); + ASSERT_NE(retained_interface, nullptr); + + // Keep the interface alive after its inspector owner is destroyed, so + // closing the handle cannot depend on the interface's destructor. + } + + ASSERT_TRUE(handle->Expired()); + EXPECT_FALSE(handle->Post( + std::make_unique<RetainInterfaceRequest>(&retained_interface))); + retained_interface.reset(); +} + +} // namespace +} // namespace inspector +} // namespace node diff --git a/test/cctest/test_json_utils.cc b/test/cctest/test_json_utils.cc index 3d5a78921170..868f0c8b260e 100644 --- a/test/cctest/test_json_utils.cc +++ b/test/cctest/test_json_utils.cc @@ -2,6 +2,10 @@ #include "gtest/gtest.h" +#include <cstdint> +#include <limits> +#include <sstream> + TEST(JSONUtilsTest, EscapeJsonChars) { using node::EscapeJsonChars; EXPECT_EQ("abc", EscapeJsonChars("abc")); @@ -24,3 +28,57 @@ TEST(JSONUtilsTest, EscapeJsonChars) { EXPECT_EQ("a" + expected[i], EscapeJsonChars("a" + input)); } } + +TEST(JSONUtilsTest, StringWriter) { + auto write = [](node::JSONWriter* writer) { + writer->json_start(); + writer->json_keyvalue("text", std::string_view("\"\\\n\0", 4)); + writer->json_keyvalue("utf8", "caf\xc3\xa9"); + writer->json_arraystart("values"); + writer->json_element(true); + writer->json_element(false); + writer->json_element(node::JSONWriter::Null{}); + writer->json_start(); + writer->json_objectstart("empty"); + writer->json_objectend(); + writer->json_end(); + writer->json_arrayend(); + writer->json_objectend(); + }; + + for (bool compact : {false, true}) { + std::ostringstream stream; + node::JSONWriter stream_writer(stream, compact); + write(&stream_writer); + std::string output; + node::JSONWriter string_writer(output, compact); + write(&string_writer); + EXPECT_EQ(stream.str(), output); + if (compact) { + EXPECT_EQ("{\"text\":\"\\\"\\\\\\n\\u0000\",\"utf8\":\"caf\xc3\xa9\"," + "\"values\":[true,false,null,{\"empty\":{}}]}\n", + output); + } + } +} + +TEST(JSONUtilsTest, StringWriterNumbers) { + std::string output; + node::JSONWriter writer(output, true); + writer.json_start(); + writer.json_arraystart("numbers"); + writer.json_element(std::numeric_limits<int64_t>::min()); + writer.json_element(std::numeric_limits<uint64_t>::max()); + writer.json_element(0); + writer.json_element(-0.0); + writer.json_element(1.23456789); + writer.json_element(1000000.0); + writer.json_element(0.00001); + writer.json_element(std::numeric_limits<double>::max()); + writer.json_element(std::numeric_limits<double>::denorm_min()); + writer.json_arrayend(); + writer.json_end(); + EXPECT_EQ("{\"numbers\":[-9223372036854775808,18446744073709551615,0,-0," + "1.23457,1e+06,1e-05,1.79769e+308,4.94066e-324]}", + output); +} diff --git a/test/common/README.md b/test/common/README.md index bc27da028c46..ee13afcb4c7a 100644 --- a/test/common/README.md +++ b/test/common/README.md @@ -884,6 +884,24 @@ socket.write(frame.data); The serialized `Buffer` may be retrieved using the `frame.data` property. +### Class: `DataFrame` + +The `http2.DataFrame` is a subclass of `http2.Frame` that serializes a `DATA` +frame. + +<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules --> + +```js +// id is the 32-bit stream identifier +// payload is a Buffer containing the DATA payload +// padlen is an 8-bit integer giving the number of padding bytes to include +// final is a boolean indicating whether the End-of-stream flag should be set, +// defaults to false. +const frame = new http2.DataFrame(id, payload, padlen, final); + +socket.write(frame.data); +``` + ### Class: `HeadersFrame` The `http2.HeadersFrame` is a subclass of `http2.Frame` that serializes a @@ -903,6 +921,21 @@ const frame = new http2.HeadersFrame(id, payload, padlen, final); socket.write(frame.data); ``` +### Class: `RstStreamFrame` + +The `http2.RstStreamFrame` is a subclass of `http2.Frame` that serializes an +`RST_STREAM` frame. + +<!-- eslint-disable no-undef, node-core/require-common-first, node-core/required-modules --> + +```js +// id is the 32-bit stream identifier +// code is the 32-bit error code, defaults to 0 (NO_ERROR). +const frame = new http2.RstStreamFrame(id, code); + +socket.write(frame.data); +``` + ### Class: `SettingsFrame` The `http2.SettingsFrame` is a subclass of `http2.Frame` that serializes an diff --git a/test/common/child_process.js b/test/common/child_process.js index 59505e5824dd..3e73fc937a74 100644 --- a/test/common/child_process.js +++ b/test/common/child_process.js @@ -160,6 +160,7 @@ function spawnSyncAndAssert(...args) { } module.exports = { + checkOutput, cleanupStaleProcess, logAfterTime, kExpiringChildRunTime, diff --git a/test/common/compile-cache.js b/test/common/compile-cache.js new file mode 100644 index 000000000000..4a96856b2fd0 --- /dev/null +++ b/test/common/compile-cache.js @@ -0,0 +1,24 @@ +'use strict'; + +const common = require('./'); +const childProcess = require('./child_process'); + +// The compile cache is disabled while V8 coverage is being collected. In that +// case, check that the first child says so and skip the rest of the test. +function withCompileCache(spawn) { + return (...args) => { + if (!process.env.NODE_V8_COVERAGE) { + return spawn(...args); + } + args.pop(); + childProcess.spawnSyncAndExit(...args, { + stderr: /Disabled because V8 coverage is being collected/, + }); + common.skip('the compile cache is disabled by V8 coverage'); + }; +} + +module.exports = { + spawnSyncAndAssert: withCompileCache(childProcess.spawnSyncAndAssert), + spawnSyncAndExit: withCompileCache(childProcess.spawnSyncAndExit), +}; diff --git a/test/common/debugger-probe.js b/test/common/debugger-probe.js index b8302de36957..f10dcf05b50e 100644 --- a/test/common/debugger-probe.js +++ b/test/common/debugger-probe.js @@ -1,7 +1,131 @@ 'use strict'; const assert = require('assert'); -const { spawnSyncAndExit } = require('./child_process'); +const { spawn } = require('child_process'); +const { once } = require('events'); +const { checkOutput, spawnSyncAndExit } = require('./child_process'); +const fixtures = require('./fixtures'); + +const kListeningRegex = /Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//; +const kReadyRegex = /^PROBE_READY$/m; +// Logged by the probe session when NODE_DEBUG=inspect_probe once the probes are bound. +const kStartedLine = 'CDP <- Runtime.runIfWaitingForDebugger'; + +function logProcessOutput(tag, { child, stdout, stderr }) { + console.error(`${tag} --- stderr ---`); + console.error(stderr); + console.error(`${tag} --- stdout ---`); + console.error(stdout); + console.error(`${tag} status = ${child.exitCode}, signal = ${child.signalCode}`); +} + +// Starts test/fixtures/debugger/<name> with the Node.js with args and env. +// Resolves once it prints `PROBE_READY`, the returned target will continue collecting +// the output of the process, so that it can be printed when a probe session fails. +function startTarget(name, { args = ['--inspect=127.0.0.1:0'], env } = {}) { + const child = spawn(process.execPath, [...args, fixtures.path('debugger', name)], + { env: { ...process.env, ...env } }); + // Only targets with the inspector activated would print the listening address at startup. + const expectListening = args.some((arg) => arg === '--inspect' || arg.startsWith('--inspect=')); + // Prevent a failed assertion from leaving a long-running target alive. + process.on('exit', () => child.kill()); + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + const target = { + child, stdout: '', stderr: '', + exited: once(child, 'exit').then(([code, signal]) => ({ code, signal })), + }; + return new Promise((resolve, reject) => { + let ready = false; + function check() { + if (ready || !kReadyRegex.test(target.stdout)) { return; } + // PROBE_READY message may appear before the listening line on stderr. + // Keep waiting until the listening line is found on stderr. + const match = kListeningRegex.exec(target.stderr); + if (expectListening && match === null) { return; } + ready = true; + target.host = match?.[1]; + target.port = match && Number(match[2]); + child.removeListener('exit', onExit); + resolve(target); + } + + function onExit() { + logProcessOutput(`[target ${child.pid}]:`, target); + reject(new Error(`Target ${name} exited before it was ready`)); + } + child.stdout.on('data', (chunk) => { target.stdout += chunk; check(); }); + child.stderr.on('data', (chunk) => { target.stderr += chunk; check(); }); + child.once('exit', onExit); + }); +} + +// Runs `node inspect --json <args>` and checks the passed expectations. On failure, +// print the output of the probe process and of `target` (if given). +// `onStarted` is called once the probes are bound. +async function runProbe(args, { target, onStarted, status, report: expectedReport, stderr: stderrCheck }) { + const argv = ['inspect', '--json', ...args]; + const child = spawn(process.execPath, argv, { env: { ...process.env, NODE_DEBUG: 'inspect_probe' } }); + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + const probe = { child, stdout: '', stderr: '' }; + child.stdout.on('data', (chunk) => { probe.stdout += chunk; }); + child.stderr.on('data', (chunk) => { + probe.stderr += chunk; + if (onStarted !== undefined && probe.stderr.includes(kStartedLine)) { + onStarted(target); + onStarted = undefined; + } + }); + // Unlike 'exit', 'close' is emitted after stdout and stderr are fully read. + const [code] = await once(child, 'close'); + + const failures = []; + if (code !== status) { + failures.push(`- probe process exited with status ${code}, expected ${status}`); + } + let report = null; + if (probe.stdout !== '') { + try { + report = JSON.parse(probe.stdout); + } catch { + failures.push('- stdout is not a JSON report'); + } + } + if (expectedReport === null) { + if (report !== null) { failures.push('- expected no report'); } + } else if (report === null) { + failures.push('- no report was printed'); + } else { + try { + assertProbeJson(report, expectedReport); + } catch (error) { + failures.push(`- report did not match:\n${error.message}`); + } + } + if (stderrCheck !== undefined) { + const { passed, reason } = checkOutput(probe.stderr, stderrCheck); + if (!passed) { failures.push(`- stderr ${reason}`); } + } + if (failures.length === 0) { return { report, stderr: probe.stderr }; } + + logProcessOutput(`[probe ${child.pid}]:`, probe); + if (target !== undefined) { logProcessOutput(`[target ${target.child.pid}]:`, target); } + const error = new Error(failures.join('\n')); + error.command = `${process.execPath} ${argv.join(' ')}`; + throw error; +} + +// Starts test/fixtures/debugger/<name>, runs `node inspect` against its --host and --port, +// check the expectations, and kills the process afterwards. +async function runAttachedProbe(name, probeArgs, { target: targetOptions, ...options } = {}) { + const target = await startTarget(name, targetOptions); + const result = await runProbe([...probeArgs, '--host', target.host, '--port', `${target.port}`], + { ...options, target }); + target.child.kill(); + await target.exited; + return result; +} // Work around a pre-existing inspector issue: if the debuggee exits too quickly // the inspector can crash while tearing down. For now normalize the crash @@ -60,6 +184,8 @@ function normalizeProbeReport(value) { return value; } +// If expected omits `target` or probe `locations`, assertProbeJson only checks for their presence +// but not the exact values. function assertProbeJson(output, expected) { const normalized = typeof output === 'string' ? JSON.parse(output) : output; const lastResult = normalized.results?.[normalized.results.length - 1]; @@ -70,6 +196,20 @@ function assertProbeJson(output, expected) { normalized.results[normalized.results.length - 1] = expected.results.at(-1); } + if (!Object.hasOwn(expected, 'target')) { + assert.notStrictEqual(normalized.target, undefined); + delete normalized.target; + } + if (Array.isArray(normalized.probes) && Array.isArray(expected.probes)) { + for (let i = 0; i < normalized.probes.length; i++) { + if (expected.probes[i] !== undefined && !Object.hasOwn(expected.probes[i], 'locations')) { + assert.strictEqual(Array.isArray(normalized.probes[i].locations), true, + `probes[${i}].locations must be an array`); + delete normalized.probes[i].locations; + } + } + } + assert.deepStrictEqual(normalizeProbeReport(normalized), normalizeProbeReport(expected)); } @@ -101,4 +241,7 @@ module.exports = { assertProbeJson, assertProbeCliError, assertProbeText, + runAttachedProbe, + runProbe, + startTarget, }; diff --git a/test/common/http2.js b/test/common/http2.js index 1968b5bcfd39..b198ec758c11 100644 --- a/test/common/http2.js +++ b/test/common/http2.js @@ -99,6 +99,33 @@ class HeadersFrame extends Frame { } } +class DataFrame extends Frame { + constructor(id, payload, padlen = 0, final = false) { + let len = payload.length; + let flags = 0; + if (final) flags |= FLAG_EOS; + const buffers = [payload]; + if (padlen > 0) { + buffers.unshift(Buffer.from([padlen])); + buffers.push(PADDING.slice(0, padlen)); + len += padlen + 1; + flags |= FLAG_PADDED; + } + super(len, 0, flags, id); + buffers.unshift(this[kFrameData]); + this[kFrameData] = Buffer.concat(buffers); + } +} + +class RstStreamFrame extends Frame { + constructor(id, code = 0) { + super(4, 3, 0, id); + const payload = Buffer.alloc(4); + write32BE(payload, 0, code); + this[kFrameData] = Buffer.concat([this[kFrameData], payload]); + } +} + class PingFrame extends Frame { constructor(ack = false) { const buffers = [Buffer.alloc(8)]; @@ -120,7 +147,9 @@ class AltSvcFrame extends Frame { module.exports = { Frame, AltSvcFrame, + DataFrame, HeadersFrame, + RstStreamFrame, SettingsFrame, PingFrame, kFakeRequestHeaders, diff --git a/test/doctool/test-doc-api-json.mjs b/test/doctool/test-doc-api-json.mjs index ba0469da50a1..2e15173bdc2b 100644 --- a/test/doctool/test-doc-api-json.mjs +++ b/test/doctool/test-doc-api-json.mjs @@ -28,8 +28,25 @@ function validateMisc(misc) { assert.strictEqual(typeof misc.textRaw, 'string'); } +// Counts of `deprecated` and `removed` metadata found in the current file's +// JSON output. Reset for each file and compared against the Markdown source. let numberOfDeprecatedSections = 0; let numberOfRemovedAPIs = 0; +let totalDeprecatedSections = 0; +let totalRemovedAPIs = 0; + +// Counts the YAML metadata blocks in a Markdown source file that declare +// `deprecated` or `removed`, so the JSON output can be checked against them. +const yamlBlockRe = /<!--\s*YAML\r?\n([\s\S]*?)-->/g; +function countSourceMeta(markdown) { + let deprecated = 0; + let removed = 0; + for (const { 1: body } of markdown.matchAll(yamlBlockRe)) { + if (/^\s*deprecated:/m.test(body)) deprecated++; + if (/^\s*removed:/m.test(body)) removed++; + } + return { deprecated, removed }; +} const metaExpectedKeys = new Set([ 'added', @@ -155,8 +172,22 @@ for await (const dirent of await fs.opendir(new URL('../../out/doc/api/', import 'report.md': ['introduced_in', 'meta', 'stability', 'stabilityText', 'miscs'], }[dirent.name] ?? ['modules'])]); + numberOfDeprecatedSections = 0; + numberOfRemovedAPIs = 0; assert.partialDeepStrictEqual(allExpectedKeys, findAllKeys(json)); + + const markdown = await fs.readFile( + new URL(`../../${expectedSource}`, import.meta.url), 'utf8'); + assert.deepStrictEqual( + { deprecated: numberOfDeprecatedSections, removed: numberOfRemovedAPIs }, + countSourceMeta(markdown), + `deprecated/removed metadata in ${jsonPath} does not match ${expectedSource}`, + ); + totalDeprecatedSections += numberOfDeprecatedSections; + totalRemovedAPIs += numberOfRemovedAPIs; } -assert.strictEqual(numberOfDeprecatedSections, 48); // Increase this number every time a new API is deprecated. -assert.strictEqual(numberOfRemovedAPIs, 47); // Increase this number every time a section is marked as removed. +// Guard against the source scan and the JSON output both silently finding +// nothing (e.g. if the YAML metadata format changes). +assert.ok(totalDeprecatedSections > 0); +assert.ok(totalRemovedAPIs > 0); diff --git a/test/es-module/test-esm-example-loader.mjs b/test/es-module/test-esm-example-loader.mjs deleted file mode 100644 index b85de4e64c4a..000000000000 --- a/test/es-module/test-esm-example-loader.mjs +++ /dev/null @@ -1,6 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/example-loader.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import assert from 'assert'; -import ok from '../fixtures/es-modules/test-esm-ok.mjs'; - -assert(ok); diff --git a/test/es-module/test-esm-experimental-warnings.mjs b/test/es-module/test-esm-experimental-warnings.mjs deleted file mode 100644 index 7b3ec4b942ee..000000000000 --- a/test/es-module/test-esm-experimental-warnings.mjs +++ /dev/null @@ -1,50 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: warn for obsolete hooks provided', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should not print warnings when no experimental features are enabled or used', async () => { - const { code, signal, stderr } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', - `import ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'module-named-exports.mjs'))}`, - ]); - - assert.doesNotMatch( - stderr, - /ExperimentalWarning/, - new Error('No experimental warning(s) should be emitted when no experimental feature is enabled') - ); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - describe('experimental warnings for enabled experimental feature', () => { - for ( - const [experiment, ...args] of [ - [ - /`--experimental-loader` may be removed in the future/, - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'hooks-custom.mjs'), - ], - ] - ) { - it(`should print for ${experiment.toString().replaceAll('/', '')}`, async () => { - const { code, signal, stderr } = await spawnPromisified(execPath, [ - ...args, - '--input-type=module', - '--eval', - `import ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'module-named-exports.mjs'))}`, - ]); - - assert.match(stderr, /ExperimentalWarning/); - assert.match(stderr, experiment); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - } - }); -}); diff --git a/test/es-module/test-esm-import-assertion-warning.mjs b/test/es-module/test-esm-import-assertion-warning.mjs deleted file mode 100644 index 2f9b7348a2d9..000000000000 --- a/test/es-module/test-esm-import-assertion-warning.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; - -await Promise.all([ - // Using importAssertions in the resolve hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function resolve() { - return { shortCircuit: true, url: 'data:application/json,1', importAssertions: { type: 'json' } }; - })}`, - // Using importAssertions on the context object of the resolve hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function resolve(s, c, n) { - const type = c.importAssertions.type; - return { shortCircuit: true, url: 'data:application/json,1', importAttributes: { type: type ?? 'json' } }; - })}`, - // Setting importAssertions on the context object of the load hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function load(u, c, n) { - c.importAssertions = { type: 'json' }; - return n('data:application/json,1', c); - })}`, - // Creating a new context object with importAssertions in the load hook should warn but still work. - `data:text/javascript,export ${encodeURIComponent(function load(u, c, n) { - return n('data:application/json,1', { importAssertions: { type: 'json' } }); - })}`, -].map(async (loaderURL) => { - const { stdout, stderr, code } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', ` - import assert from 'node:assert'; - import { register } from 'node:module'; - - register(${JSON.stringify(loaderURL)}); - - assert.deepStrictEqual( - { ...await import('data:') }, - { default: 1 } - );`, - ]); - - assert.match(stderr, /Use `importAttributes` instead of `importAssertions`/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); -})); diff --git a/test/es-module/test-esm-import-defers-evaluation.js b/test/es-module/test-esm-import-defers-evaluation.js new file mode 100644 index 000000000000..0679493fe961 --- /dev/null +++ b/test/es-module/test-esm-import-defers-evaluation.js @@ -0,0 +1,16 @@ +'use strict'; +// Tests that import() never evaluates the module before returning to its +// caller, even though loading and linking are synchronous. +const common = require('../common'); +const assert = require('node:assert'); + +const key = '__esmImportDefersEvaluation'; +const url = `data:text/javascript,globalThis.${key} = true; export default 1;`; + +const promise = import(url); +assert.strictEqual(globalThis[key], undefined); +promise.then(common.mustCall((namespace) => { + assert.strictEqual(globalThis[key], true); + assert.strictEqual(namespace.default, 1); + delete globalThis[key]; +})); diff --git a/test/es-module/test-esm-initialization.mjs b/test/es-module/test-esm-initialization.mjs deleted file mode 100644 index c86d3b439496..000000000000 --- a/test/es-module/test-esm-initialization.mjs +++ /dev/null @@ -1,30 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: ensure initialization happens only once', { concurrency: !process.env.TEST_PARALLEL }, () => { - it(async () => { - const { code, stderr, stdout } = await spawnPromisified(execPath, [ - '--experimental-import-meta-resolve', - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--no-warnings', - fixtures.path('es-modules', 'runmain.mjs'), - ]); - - assert.strictEqual(stderr, ''); - /** - * resolveHookRunCount = 2: - * 1. fixtures/…/runmain.mjs - * 2. node:module (imported by fixtures/…/runmain.mjs) - * 3. doesnt-matter.mjs (first import.meta.resolve call) - * 4. fixtures/…/runmain.mjs (entry point) - * 5. doesnt-matter.mjs (second import.meta.resolve call) - */ - assert.strictEqual(stdout.match(/resolve passthru/g)?.length, 5); - assert.strictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-loader-chaining.mjs b/test/es-module/test-esm-loader-chaining.mjs deleted file mode 100644 index 6c266b9da3d8..000000000000 --- a/test/es-module/test-esm-loader-chaining.mjs +++ /dev/null @@ -1,507 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -const setupArgs = [ - '--no-warnings', - '--input-type=module', - '--eval', -]; -const commonInput = 'import os from "node:os"; console.log(os)'; -const commonArgs = [ - ...setupArgs, - commonInput, -]; - -describe('ESM: loader chaining', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should load unadulterated source when there are no loaders', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - ...setupArgs, - 'import fs from "node:fs"; console.log(typeof fs?.constants?.F_OK )', - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /number/); // node:fs is an object - assert.strictEqual(code, 0); - }); - - it('should load properly different source when only load changes something', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /load passthru/); - assert.match(stdout, /resolve passthru/); - assert.match(stdout, /foo/); - assert.strictEqual(code, 0); - }); - - it('should result in proper output from multiple changes in resolve hooks', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-foo.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /resolve 42/); // It did go thru resolve-42 - assert.match(stdout, /foo/); // LIFO, so resolve-foo won - assert.strictEqual(code, 0); - }); - - it('should respect modified context within resolve chain', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-receiving-modified-context.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passing-modified-context.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /bar/); - assert.strictEqual(code, 0); - }); - - it('should accept only the correct arguments', async () => { - const { stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-log-args.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-with-too-many-args.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stdout, /^resolve arg count: 3$/m); - assert.match(stdout, /specifier: 'node:os'/); - assert.match(stdout, /next: \[AsyncFunction: nextResolve\]/); - - assert.match(stdout, /^load arg count: 3$/m); - assert.match(stdout, /url: 'node:os'/); - assert.match(stdout, /next: \[AsyncFunction: nextLoad\]/); - }); - - it('should result in proper output from multiple changes in resolve hooks', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-foo.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /resolve foo/); // It did go thru resolve-foo - assert.match(stdout, /42/); // LIFO, so resolve-42 won - assert.strictEqual(code, 0); - }); - - it('should provide the correct "next" fn when multiple calls to next within same loader', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-foo.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-multiple-next-calls.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - const countFoos = stdout.match(/resolve foo/g)?.length; - - assert.strictEqual(stderr, ''); - assert.strictEqual(countFoos, 2); - assert.strictEqual(code, 0); - }); - - it('should use the correct `name` for next<HookName>\'s function', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /next<HookName>: nextResolve/); - assert.strictEqual(code, 0); - }); - - it('should throw for incomplete resolve chain, citing errant loader & hook', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-incomplete.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.match(stdout, /resolve passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-resolve-incomplete\.mjs/); - assert.match(stderr, /'resolve'/); - assert.strictEqual(code, 1); - }); - - it('should NOT throw when nested resolve hook signaled a short circuit', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-next-modified.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout.trim(), 'foo'); - assert.strictEqual(code, 0); - }); - - it('should NOT throw when nested load hook signaled a short circuit', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-shortcircuit.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-next-modified.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /421/); - assert.strictEqual(code, 0); - }); - - it('should allow loaders to influence subsequent loader resolutions', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-strip-xxx.mjs'), - '--loader', - 'xxx/loader-resolve-strip-yyy.mjs', - ...commonArgs, - ], - { encoding: 'utf8', cwd: fixtures.path('es-module-loaders') }, - ); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - }); - - it('should throw when the resolve chain is broken', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-incomplete.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-foo-or-42.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.doesNotMatch(stdout, /resolve passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-resolve-incomplete\.mjs/); - assert.match(stderr, /'resolve'/); - assert.strictEqual(code, 1); - }); - - it('should throw for incomplete load chain, citing errant loader & hook', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-incomplete.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stdout, /load passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-load-incomplete\.mjs/); - assert.match(stderr, /'load'/); - assert.strictEqual(code, 1); - }); - - it('should throw when the load chain is broken', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-incomplete.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.doesNotMatch(stdout, /load passthru/); - assert.match(stderr, /ERR_LOADER_CHAIN_INCOMPLETE/); - assert.match(stderr, /loader-load-incomplete\.mjs/); - assert.match(stderr, /'load'/); - assert.strictEqual(code, 1); - }); - - it('should throw when invalid `specifier` argument passed to `nextResolve`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-bad-next-specifier.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(code, 1); - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-resolve-bad-next-specifier\.mjs/); - assert.match(stderr, /'resolve' hook's nextResolve\(\) specifier/); - }); - - it('should throw when resolve hook is invalid', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-null-return.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(code, 1); - assert.match(stderr, /ERR_INVALID_RETURN_VALUE/); - assert.match(stderr, /loader-resolve-null-return\.mjs/); - assert.match(stderr, /'resolve' hook's nextResolve\(\)/); - assert.match(stderr, /an object/); - assert.match(stderr, /got null/); - }); - - it('should throw when invalid `context` argument passed to `nextResolve`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-bad-next-context.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-resolve-bad-next-context\.mjs/); - assert.match(stderr, /'resolve' hook's nextResolve\(\) context/); - assert.strictEqual(code, 1); - }); - - it('should throw when load hook is invalid', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-null-return.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.strictEqual(code, 1); - assert.match(stderr, /ERR_INVALID_RETURN_VALUE/); - assert.match(stderr, /loader-load-null-return\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\)/); - assert.match(stderr, /an object/); - assert.match(stderr, /got null/); - }); - - it('should throw when invalid `url` argument passed to `nextLoad`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-bad-next-url.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-load-bad-next-url\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\) url/); - assert.strictEqual(code, 1); - }); - - it('should throw when invalid `url` argument passed to `nextLoad`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-impersonating-next-url.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - - assert.match(stderr, /ERR_INVALID_ARG_VALUE/); - assert.match(stderr, /loader-load-impersonating-next-url\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\) url/); - assert.strictEqual(code, 1); - }); - - it('should throw when invalid `context` argument passed to `nextLoad`', async () => { - const { code, stderr } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-bad-next-context.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.match(stderr, /ERR_INVALID_ARG_TYPE/); - assert.match(stderr, /loader-load-bad-next-context\.mjs/); - assert.match(stderr, /'load' hook's nextLoad\(\) context/); - assert.strictEqual(code, 1); - }); - - it('should allow loaders to influence subsequent loader `import()` calls in `resolve`', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-strip-xxx.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-dynamic-import.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.strictEqual(stderr, ''); - assert.match(stdout, /resolve dynamic import/); // It did go thru resolve-dynamic - assert.strictEqual(code, 0); - }); - - it('should allow loaders to influence subsequent loader `import()` calls in `load`', async () => { - const { code, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-strip-xxx.mjs'), - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-load-dynamic-import.mjs'), - ...commonArgs, - ], - { encoding: 'utf8' }, - ); - assert.strictEqual(stderr, ''); - assert.match(stdout, /load dynamic import/); // It did go thru load-dynamic - assert.strictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-loader-custom-condition.mjs b/test/es-module/test-esm-loader-custom-condition.mjs deleted file mode 100644 index 075e4fe2b660..000000000000 --- a/test/es-module/test-esm-loader-custom-condition.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-with-custom-condition.mjs -import '../common/index.mjs'; -import assert from 'assert'; -import util from 'util'; - -import * as ns from '../fixtures/es-modules/conditional-exports.mjs'; - -assert.deepStrictEqual({ ...ns }, { default: 'from custom condition' }); - -assert.strictEqual( - util.inspect(ns, { showHidden: false }), - "[Module: null prototype] { default: 'from custom condition' }" -); - -assert.strictEqual( - util.inspect(ns, { showHidden: true }), - '[Module: null prototype] {\n' + - " default: 'from custom condition',\n" + - " [Symbol(Symbol.toStringTag)]: 'Module'\n" + - '}' -); diff --git a/test/es-module/test-esm-loader-default-resolver.mjs b/test/es-module/test-esm-loader-default-resolver.mjs index 2a69010e0504..9f836aa56e0f 100644 --- a/test/es-module/test-esm-loader-default-resolver.mjs +++ b/test/es-module/test-esm-loader-default-resolver.mjs @@ -5,51 +5,6 @@ import { execPath } from 'node:process'; import { describe, it } from 'node:test'; describe('default resolver', () => { - // In these tests `byop` is an acronym for "bring your own protocol", and is the - // protocol our byop-dummy-loader.mjs can load - it('should accept foreign schemas without exception (e.g. byop://something/or-other)', async () => { - const { code, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/byop-dummy-loader.mjs'), - '--input-type=module', - '--eval', - "import 'byop://1/index.mjs'", - ]); - assert.strictEqual(code, 0); - assert.strictEqual(stdout.trim(), 'index.mjs!'); - assert.strictEqual(stderr, ''); - }); - - it('should resolve foreign schemas by doing regular url absolutization', async () => { - const { code, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/byop-dummy-loader.mjs'), - '--input-type=module', - '--eval', - "import 'byop://1/index2.mjs'", - ]); - assert.strictEqual(code, 0); - assert.strictEqual(stdout.trim(), '42'); - assert.strictEqual(stderr, ''); - }); - - // In this test, `byoe` is an acronym for "bring your own extension" - it('should accept foreign extensions without exception (e.g. ..//something.byoe)', async () => { - const { code, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/byop-dummy-loader.mjs'), - '--input-type=module', - '--eval', - "import 'byop://1/index.byoe'", - ]); - assert.strictEqual(code, 0); - assert.strictEqual(stdout.trim(), 'index.byoe!'); - assert.strictEqual(stderr, ''); - }); - it('should identify the parent module of an invalid URL host in import specifier', async () => { if (process.platform === 'win32') return; diff --git a/test/es-module/test-esm-loader-dependency.mjs b/test/es-module/test-esm-loader-dependency.mjs deleted file mode 100644 index 54327b478bf4..000000000000 --- a/test/es-module/test-esm-loader-dependency.mjs +++ /dev/null @@ -1,5 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-with-dep.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import '../fixtures/es-modules/test-esm-ok.mjs'; - -// We just test that this module doesn't fail loading diff --git a/test/es-module/test-esm-loader-event-loop.mjs b/test/es-module/test-esm-loader-event-loop.mjs deleted file mode 100644 index d94e55148d85..000000000000 --- a/test/es-module/test-esm-loader-event-loop.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/hooks-custom.mjs -import { mustCall } from '../common/index.mjs'; - -const done = mustCall(); - - -// Test that the process doesn't exit because of a caught exception thrown as part of dynamic import(). -for (let i = 0; i < 10; i++) { - await import('nonexistent/file.mjs').catch(() => {}); -} - -done(); diff --git a/test/es-module/test-esm-loader-http-imports.mjs b/test/es-module/test-esm-loader-http-imports.mjs deleted file mode 100644 index 96bfffe5b13f..000000000000 --- a/test/es-module/test-esm-loader-http-imports.mjs +++ /dev/null @@ -1,91 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import fixtures from '../common/fixtures.js'; -import assert from 'node:assert'; -import http from 'node:http'; -import path from 'node:path'; -import { execPath } from 'node:process'; -import { promisify } from 'node:util'; -import { describe, it, after } from 'node:test'; - - -const files = { - 'main.mjs': 'export * from "./lib.mjs";', - 'lib.mjs': 'export { sum } from "./sum.mjs";', - 'sum.mjs': 'export function sum(a, b) { return a + b }', - 'console.mjs': ` - import { sum } from './sum.mjs'; - globalThis.sum = sum; - console.log("loaded over http"); - `, -}; - -const requestListener = ({ url }, rsp) => { - const filename = path.basename(url); - const content = files[filename]; - - if (content) { - return rsp - .writeHead(200, { 'Content-Type': 'application/javascript' }) - .end(content); - } - - return rsp - .writeHead(404) - .end(); -}; - -// Leave closing idle connections to the client, so that the loader never -// reuses a keep-alive socket the server has just closed. -const server = http.createServer({ keepAliveTimeout: 0 }, requestListener); - -await promisify(server.listen.bind(server))({ - host: '127.0.0.1', - port: 0, -}); - -const { - address: host, - port, -} = server.address(); - -describe('ESM: http import via loader', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should load using --import flag', async () => { - // ! MUST NOT use spawnSync to avoid blocking the event loop - const { code, signal, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--no-warnings', - '--loader', - fixtures.fileURL('es-module-loaders', 'http-loader.mjs'), - '--import', `http://${host}:${port}/console.mjs`, - '--eval', - 'console.log(sum(1, 2))', - ] - ); - assert.strictEqual(stderr, ''); - assert.match(stdout, /loaded over http\r?\n3/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - it('should load using import inside --eval code', async () => { - // ! MUST NOT use spawnSync to avoid blocking the event loop - const { code, signal, stderr, stdout } = await spawnPromisified( - execPath, - [ - '--no-warnings', - '--loader', - fixtures.fileURL('es-module-loaders', 'http-loader.mjs'), - '--input-type=module', - '--eval', - `import * as main from 'http://${host}:${port}/main.mjs'; console.log(main)`, - ] - ); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, '[Module: null prototype] { sum: [Function: sum] }\n'); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - after(() => server.close()); -}); diff --git a/test/es-module/test-esm-loader-invalid-format.mjs b/test/es-module/test-esm-loader-invalid-format.mjs deleted file mode 100644 index 5a16381e5889..000000000000 --- a/test/es-module/test-esm-loader-invalid-format.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-invalid-format.mjs -import { expectsError, mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -import('../fixtures/es-modules/test-esm-ok.mjs') -.then(assert.fail, expectsError({ - code: 'ERR_UNKNOWN_MODULE_FORMAT', - message: /Unknown module format: esm/, -})) -.then(mustCall()); diff --git a/test/es-module/test-esm-loader-invalid-url.mjs b/test/es-module/test-esm-loader-invalid-url.mjs deleted file mode 100644 index 1ba7c621f7e9..000000000000 --- a/test/es-module/test-esm-loader-invalid-url.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-invalid-url.mjs -import { expectsError, mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -import('../fixtures/es-modules/test-esm-ok.mjs') -.then(assert.fail, (error) => { - expectsError({ code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' })(error); - assert.match(error.message, /loader-invalid-url\.mjs/); -}) -.then(mustCall()); diff --git a/test/es-module/test-esm-loader-mock.mjs b/test/es-module/test-esm-loader-mock.mjs deleted file mode 100644 index cdf56d85415b..000000000000 --- a/test/es-module/test-esm-loader-mock.mjs +++ /dev/null @@ -1,42 +0,0 @@ -import '../common/index.mjs'; -import assert from 'node:assert/strict'; -import { mock } from '../fixtures/es-module-loaders/mock.mjs'; - -mock('node:events', { - EventEmitter: 'This is mocked!', -}); - -// This resolves to node:events -// It is intercepted by mock-loader and doesn't return the normal value -assert.deepStrictEqual(await import('events'), Object.defineProperty({ - __proto__: null, - EventEmitter: 'This is mocked!', -}, Symbol.toStringTag, { - enumerable: false, - value: 'Module', -})); - -const mutator = mock('node:events', { - EventEmitter: 'This is mocked v2!', -}); - -// It is intercepted by mock-loader and doesn't return the normal value. -// This is resolved separately from the import above since the specifiers -// are different. -const mockedV2 = await import('node:events'); -assert.deepStrictEqual(mockedV2, Object.defineProperty({ - __proto__: null, - EventEmitter: 'This is mocked v2!', -}, Symbol.toStringTag, { - enumerable: false, - value: 'Module', -})); - -mutator.EventEmitter = 'This is mocked v3!'; -assert.deepStrictEqual(mockedV2, Object.defineProperty({ - __proto__: null, - EventEmitter: 'This is mocked v3!', -}, Symbol.toStringTag, { - enumerable: false, - value: 'Module', -})); diff --git a/test/es-module/test-esm-loader-modulemap.js b/test/es-module/test-esm-loader-modulemap.js index ba0358368ec1..6dada059c4af 100644 --- a/test/es-module/test-esm-loader-modulemap.js +++ b/test/es-module/test-esm-loader-modulemap.js @@ -4,7 +4,7 @@ require('../common'); const assert = require('assert'); -const { createModuleLoader } = require('internal/modules/esm/loader'); +const { ModuleLoader } = require('internal/modules/esm/loader'); const { LoadCache, ResolveCache } = require('internal/modules/esm/module_map'); const { ModuleJob } = require('internal/modules/esm/module_job'); const createDynamicModule = require( @@ -16,7 +16,7 @@ const jsonModuleDataUrl = 'data:application/json,""'; const stubJsModule = createDynamicModule([], ['default'], jsModuleDataUrl); const stubJsonModule = createDynamicModule([], ['default'], jsonModuleDataUrl); -const loader = createModuleLoader(); +const loader = new ModuleLoader(); const jsModuleJob = new ModuleJob(loader, jsModuleDataUrl, {}, stubJsModule.module); const jsonModuleJob = new ModuleJob(loader, jsonModuleDataUrl, { type: 'json' }, stubJsonModule.module); diff --git a/test/es-module/test-esm-loader-not-found.mjs b/test/es-module/test-esm-loader-not-found.mjs deleted file mode 100644 index 2abaf3078d11..000000000000 --- a/test/es-module/test-esm-loader-not-found.mjs +++ /dev/null @@ -1,24 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: nonexistent loader', () => { - it('should throw', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - 'i-dont-exist', - fixtures.path('print-error-message.js'), - ]); - - assert.notStrictEqual(code, 0); - - // Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'i-dont-exist' imported from - assert.match(stderr, /ERR_MODULE_NOT_FOUND/); - assert.match(stderr, /'i-dont-exist'/); - - assert.ok(!stderr.includes('Bad command or file name')); - }); -}); diff --git a/test/es-module/test-esm-loader-programmatically.mjs b/test/es-module/test-esm-loader-programmatically.mjs deleted file mode 100644 index dd25e3f2430e..000000000000 --- a/test/es-module/test-esm-loader-programmatically.mjs +++ /dev/null @@ -1,251 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -// This test ensures that the register function can register loaders -// programmatically. - -const commonArgs = [ - '--no-warnings', - '--input-type=module', - '--loader=data:text/javascript,', -]; - -const commonEvals = { - import: (module) => `await import(${JSON.stringify(module)});`, - register: (loader, parentURL = 'file:///') => `register(${JSON.stringify(loader)}, ${JSON.stringify(parentURL)});`, - dynamicImport: (module) => `await import(${JSON.stringify(`data:text/javascript,${encodeURIComponent(module)}`)});`, - staticImport: (module) => `import ${JSON.stringify(`data:text/javascript,${encodeURIComponent(module)}`)};`, -}; - -describe('ESM: programmatically register loaders', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('works with only a dummy CLI argument', async () => { - const parentURL = fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'); - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - `register(${JSON.stringify('./loader-resolve-passthru.mjs')}, ${JSON.stringify({ parentURL })});` + - `register(${JSON.stringify('./loader-load-passthru.mjs')}, ${JSON.stringify({ parentURL })});` + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /load passthru/); - assert.match(lines[4], /Hello from dynamic import/); - - assert.strictEqual(lines[5], ''); - }); - - describe('registering via --import', { concurrency: !process.env.TEST_PARALLEL }, () => { - for (const moduleType of ['mjs', 'cjs']) { - it(`should programmatically register a loader from a ${moduleType.toUpperCase()} file`, async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--import', fixtures.fileURL('es-module-loaders', `register-loader.${moduleType}`).href, - '--eval', commonEvals.staticImport('console.log("entry point")'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const [ - passthruStdout, - entryPointStdout, - ] = stdout.split('\n'); - - assert.match(passthruStdout, /resolve passthru/); - assert.match(entryPointStdout, /entry point/); - }); - } - }); - - it('programmatically registered loaders are appended to an existing chaining', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--loader', - fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'), - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /Hello from dynamic import/); - - assert.strictEqual(lines[4], ''); - }); - - it('works registering loaders across files', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-load.mjs')) + - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-resolve.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /load passthru/); - assert.match(lines[2], /Hello from dynamic import/); - - assert.strictEqual(lines[3], ''); - }); - - it('works registering loaders across virtual files', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-load.mjs')) + - commonEvals.dynamicImport( - commonEvals.import(fixtures.fileURL('es-module-loaders', 'register-programmatically-loader-resolve.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /load passthru/); - assert.match(lines[2], /Hello from dynamic import/); - - assert.strictEqual(lines[3], ''); - }); - - it('works registering the same loaders more them once', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')) + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /load passthru/); - assert.match(lines[4], /Hello from dynamic import/); - - assert.strictEqual(lines[5], ''); - }); - - it('works registering loaders as package name', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register('resolve', fixtures.fileURL('es-module-loaders', 'package.json')) + - commonEvals.register('load', fixtures.fileURL('es-module-loaders', 'package.json')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - // Resolve occurs twice because it is first used to resolve the `load` loader - // _AND THEN_ the `register` module. - assert.match(lines[0], /resolve passthru/); - assert.match(lines[1], /resolve passthru/); - assert.match(lines[2], /load passthru/); - assert.match(lines[3], /Hello from dynamic import/); - - assert.strictEqual(lines[4], ''); - }); - - it('works without a CLI flag', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--input-type=module', - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - - const lines = stdout.split('\n'); - - assert.match(lines[0], /load passthru/); - assert.match(lines[1], /Hello from dynamic import/); - - assert.strictEqual(lines[2], ''); - }); - - it('does not work with a loader specifier that does not exist', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register('./not-found.mjs', import.meta.url) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - assert.match(stderr, /ERR_MODULE_NOT_FOUND/); - }); - - it('does not work with a loader that got syntax errors', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - ...commonArgs, - '--eval', - "import { register } from 'node:module';" + - commonEvals.register(fixtures.fileURL('es-module-loaders', 'syntax-error.mjs')) + - commonEvals.dynamicImport('console.log("Hello from dynamic import");'), - ]); - - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - assert.match(stderr, /SyntaxError/); - }); -}); diff --git a/test/es-module/test-esm-loader-resolve-type.mjs b/test/es-module/test-esm-loader-resolve-type.mjs deleted file mode 100644 index 7dcc65a10c09..000000000000 --- a/test/es-module/test-esm-loader-resolve-type.mjs +++ /dev/null @@ -1,48 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as tmpdir from '../common/tmpdir.js'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { mkdir, rm, cp } from 'node:fs/promises'; -import { execPath } from 'node:process'; - -tmpdir.refresh(); - -const base = tmpdir.fileURL(`test-esm-loader-resolve-type-${(Math.random() * Date.now()).toFixed(0)}`); -const moduleName = 'module-counter-by-type'; -const moduleURL = new URL(`${base}/node_modules/${moduleName}`); -try { - await mkdir(moduleURL, { recursive: true }); - await cp( - fixtures.path('es-modules', 'module-counter-by-type'), - moduleURL, - { recursive: true } - ); - - const output = await spawnPromisified( - execPath, - [ - '--no-warnings', - '--input-type=module', - '--eval', - `import { getModuleTypeStats } from ${JSON.stringify(fixtures.fileURL('es-module-loaders', 'hook-resolve-type.mjs'))}; - const before = getModuleTypeStats(); - await import(${JSON.stringify(moduleName)}); - const after = getModuleTypeStats(); - console.log(JSON.stringify({ before, after }));`, - ], - { cwd: base }, - ); - - assert.deepStrictEqual(output, { - code: 0, - signal: null, - stderr: '', - stdout: JSON.stringify({ - before: { importedESM: 0, importedCJS: 0 }, - // Dynamic import in the eval script should increment ESM counter but not CJS counter - after: { importedESM: 1, importedCJS: 0 }, - }) + '\n', - }); -} finally { - await rm(base, { recursive: true, force: true }); -} diff --git a/test/es-module/test-esm-loader-spawn-promisified.mjs b/test/es-module/test-esm-loader-spawn-promisified.mjs deleted file mode 100644 index 2f27f7850f64..000000000000 --- a/test/es-module/test-esm-loader-spawn-promisified.mjs +++ /dev/null @@ -1,304 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -describe('Loader hooks throwing errors', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('throws on nonexistent modules', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "nonexistent/file.mjs"', - ]); - - assert.match(stderr, /ERR_MODULE_NOT_FOUND/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on unknown extensions', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import ${JSON.stringify(fixtures.fileURL('/es-modules/file.unknown'))}`, - ]); - - assert.match(stderr, /ERR_UNKNOWN_FILE_EXTENSION/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on invalid return values', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/badReturnVal.mjs"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on boolean false', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/format.false"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - it('throws on boolean true', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/format.true"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on invalid returned object', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/badReturnFormatVal.mjs"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on unsupported format', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/unsupportedReturnFormatVal.mjs"', - ]); - - assert.match(stderr, /ERR_UNKNOWN_MODULE_FORMAT/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('throws on invalid format property type', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'import "esmHook/badReturnSourceVal.mjs"', - ]); - - assert.match(stderr, /ERR_INVALID_RETURN_PROPERTY_VALUE/); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); - - it('rejects dynamic imports for all of the error cases checked above', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await Promise.allSettled([ - import('nonexistent/file.mjs'), - import(${JSON.stringify(fixtures.fileURL('/es-modules/file.unknown'))}), - import('esmHook/badReturnVal.mjs'), - import('esmHook/format.false'), - import('esmHook/format.true'), - import('esmHook/badReturnFormatVal.mjs'), - import('esmHook/unsupportedReturnFormatVal.mjs'), - import('esmHook/badReturnSourceVal.mjs'), - ]).then((results) => { - assert.strictEqual(results.every((result) => result.status === 'rejected'), true); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); -}); - -describe('Loader hooks parsing modules', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('can parse .js files as ESM', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import(${JSON.stringify(fixtures.fileURL('/es-module-loaders/js-as-esm.js'))}) - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.namedExport, 'named-export'); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('can define .ext files as ESM', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import(${JSON.stringify(fixtures.fileURL('/es-modules/file.ext'))}) - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - const { default: defaultExport } = parsedModule; - assert.strictEqual(typeof defaultExport, 'function'); - assert.strictEqual(defaultExport.name, 'iAmReal'); - assert.strictEqual(defaultExport(), true); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('can predetermine the format in the custom loader resolve hook', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import('esmHook/preknownFormat.pre') - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.default, 'hello world'); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('can provide source for a nonexistent file', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import('esmHook/virtual.mjs') - .then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(typeof parsedModule.default, 'undefined'); - assert.strictEqual(parsedModule.message, 'WOOHOO!'); - })`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('ensures that loaders have a separate context from userland', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - `import assert from 'node:assert'; - await import(${JSON.stringify(fixtures.fileURL('/es-modules/stateful.mjs'))}) - .then(({ default: count }) => { - assert.strictEqual(count(), 1); - });`, - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('ensures that user loaders are not bound to the internal loader', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/loader-this-value-inside-hook-functions.mjs'), - '--input-type=module', - '--eval', - ';', // Actual test is inside the loader module. - ]); - - assert.strictEqual(stderr, ''); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('throw maximum call stack error on the loader', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('/es-module-loaders/hooks-custom.mjs'), - '--input-type=module', - '--eval', - 'await import("esmHook/maximumCallStack.mjs")', - ]); - - assert(stderr.includes('Maximum call stack size exceeded')); - assert.strictEqual(stdout, ''); - assert.strictEqual(code, 1); - assert.strictEqual(signal, null); - }); -}); diff --git a/test/es-module/test-esm-loader-stringify-text.mjs b/test/es-module/test-esm-loader-stringify-text.mjs deleted file mode 100644 index 8502375b31aa..000000000000 --- a/test/es-module/test-esm-loader-stringify-text.mjs +++ /dev/null @@ -1,66 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/string-sources.mjs -import { mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -assert.rejects( - import('test:Array'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -import('test:ArrayBuffer').then( - mustCall(), -); -import('test:BigInt64Array').then( - mustCall(), -); -import('test:BigUint64Array').then( - mustCall(), -); -import('test:Float32Array').then( - mustCall(), -); -import('test:Float64Array').then( - mustCall(), -); -import('test:Int8Array').then( - mustCall(), -); -import('test:Int16Array').then( - mustCall(), -); -import('test:Int32Array').then( - mustCall(), -); -assert.rejects( - import('test:null'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -assert.rejects( - import('test:Object'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -import('test:SharedArrayBuffer').then( - mustCall(), -); -import('test:string').then( - mustCall(), -); -assert.rejects( - import('test:String'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); -import('test:Uint8ClampedArray').then( - mustCall(), -); -import('test:Uint16Array').then( - mustCall(), -); -import('test:Uint32Array').then( - mustCall(), -); -import('test:Uint8Array').then( - mustCall(), -); -assert.rejects( - import('test:undefined'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -).then(mustCall()); diff --git a/test/es-module/test-esm-loader-thenable.mjs b/test/es-module/test-esm-loader-thenable.mjs deleted file mode 100644 index d26ba7d476a5..000000000000 --- a/test/es-module/test-esm-loader-thenable.mjs +++ /dev/null @@ -1,43 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: thenable loader hooks', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should behave as a normal promise resolution', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'thenable-load-hook.mjs').href, - fixtures.path('es-modules', 'test-esm-ok.mjs'), - ]); - - assert.strictEqual(code, 0); - assert.ok(!stderr.includes('must not call')); - }); - - it('should crash the node process rejection with an error', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'thenable-load-hook-rejected.mjs').href, - fixtures.path('es-modules', 'test-esm-ok.mjs'), - ]); - - assert.notStrictEqual(code, 0); - assert.match(stderr, /\sError: must crash the process\r?\n/); - assert.ok(!stderr.includes('must not call')); - }); - - it('should just reject without an error (but NOT crash the node process)', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'thenable-load-hook-rejected-no-arguments.mjs').href, - fixtures.path('es-modules', 'test-esm-ok.mjs'), - ]); - - assert.notStrictEqual(code, 0); - assert.match(stderr, /\sundefined\r?\n/); - assert.ok(!stderr.includes('must not call')); - }); -}); diff --git a/test/es-module/test-esm-loader-with-source.mjs b/test/es-module/test-esm-loader-with-source.mjs deleted file mode 100644 index 41dca12dfc6b..000000000000 --- a/test/es-module/test-esm-loader-with-source.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/preset-cjs-source.mjs -import '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'assert'; - -const { default: existingFileSource } = await import(fixtures.fileURL('es-modules', 'cjs-file.cjs')); -const { default: noSuchFileSource } = await import(new URL('./no-such-file.cjs', import.meta.url)); - -assert.strictEqual(existingFileSource, 'no .cjs file was read to get this source'); -assert.strictEqual(noSuchFileSource, 'no .cjs file was read to get this source'); diff --git a/test/es-module/test-esm-loader-with-syntax-error.mjs b/test/es-module/test-esm-loader-with-syntax-error.mjs deleted file mode 100644 index fe41b293a3fc..000000000000 --- a/test/es-module/test-esm-loader-with-syntax-error.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - - -describe('ESM: loader with syntax error', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should crash the node process', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders', 'syntax-error.mjs').href, - fixtures.path('print-error-message.js'), - ]); - - assert.match(stderr, /SyntaxError/); - assert.ok(!stderr.includes('Bad command or file name')); - assert.notStrictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-loader.mjs b/test/es-module/test-esm-loader.mjs deleted file mode 100644 index de3481432481..000000000000 --- a/test/es-module/test-esm-loader.mjs +++ /dev/null @@ -1,88 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/hooks-custom.mjs -import '../common/index.mjs'; -import assert from 'assert'; - - -await assert.rejects( - import('nonexistent/file.mjs'), - { code: 'ERR_MODULE_NOT_FOUND' }, -); - -await assert.rejects( - import('../fixtures/es-modules/file.unknown'), - { code: 'ERR_UNKNOWN_FILE_EXTENSION' }, -); - -await assert.rejects( - import('esmHook/badReturnVal.mjs'), - { code: 'ERR_INVALID_RETURN_VALUE' }, -); - -// Nullish values are allowed; booleans are not -await assert.rejects( - import('esmHook/format.false'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); -await assert.rejects( - import('esmHook/format.true'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); - -await assert.rejects( - import('esmHook/badReturnFormatVal.mjs'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); - -await assert.rejects( - import('esmHook/unsupportedReturnFormatVal.mjs'), - { code: 'ERR_UNKNOWN_MODULE_FORMAT' }, -); - -await assert.rejects( - import('esmHook/badReturnSourceVal.mjs'), - { code: 'ERR_INVALID_RETURN_PROPERTY_VALUE' }, -); - -await assert.rejects(import('esmHook/commonJsNullSource.mjs'), { - code: 'ERR_INVALID_RETURN_PROPERTY_VALUE', - message: /"source".*'load'.*got type bigint/, -}); - -await import('../fixtures/es-module-loaders/js-as-esm.js') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.namedExport, 'named-export'); -}); - -// The custom loader tells node .ext files are MJS -await import('../fixtures/es-modules/file.ext') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - const { default: defaultExport } = parsedModule; - assert.strictEqual(typeof defaultExport, 'function'); - assert.strictEqual(defaultExport.name, 'iAmReal'); - assert.strictEqual(defaultExport(), true); -}); - -// The custom loader's resolve hook predetermines the format -await import('esmHook/preknownFormat.pre') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(parsedModule.default, 'hello world'); -}); - -// The custom loader provides source even though file does not actually exist -await import('esmHook/virtual.mjs') -.then((parsedModule) => { - assert.strictEqual(typeof parsedModule, 'object'); - assert.strictEqual(typeof parsedModule.default, 'undefined'); - assert.strictEqual(parsedModule.message, 'WOOHOO!'); -}); - -// Ensure custom loaders have separate context from userland -// hooks-custom.mjs also increments count (which starts at 0) -// if both share context, count here would be 2 -await import('../fixtures/es-modules/stateful.mjs') -.then(({ default: count }) => { - assert.strictEqual(count(), 1); -}); diff --git a/test/es-module/test-esm-named-exports.mjs b/test/es-module/test-esm-named-exports.mjs deleted file mode 100644 index bbe9c96b92d9..000000000000 --- a/test/es-module/test-esm-named-exports.mjs +++ /dev/null @@ -1,9 +0,0 @@ -// Flags: --import ./test/fixtures/es-module-loaders/builtin-named-exports.mjs -import '../common/index.mjs'; -import { readFile, __fromLoader } from 'fs'; -import assert from 'assert'; -import ok from '../fixtures/es-modules/test-esm-ok.mjs'; - -assert(ok); -assert(readFile); -assert(__fromLoader); diff --git a/test/es-module/test-esm-preserve-symlinks-not-found-plain.mjs b/test/es-module/test-esm-preserve-symlinks-not-found-plain.mjs deleted file mode 100644 index 7a538e44c072..000000000000 --- a/test/es-module/test-esm-preserve-symlinks-not-found-plain.mjs +++ /dev/null @@ -1,3 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/not-found-assert-loader.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import './not-found.js'; diff --git a/test/es-module/test-esm-preserve-symlinks-not-found.mjs b/test/es-module/test-esm-preserve-symlinks-not-found.mjs deleted file mode 100644 index 722dc467d192..000000000000 --- a/test/es-module/test-esm-preserve-symlinks-not-found.mjs +++ /dev/null @@ -1,3 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/not-found-assert-loader.mjs -/* eslint-disable node-core/require-common-first, node-core/required-modules */ -import './not-found.mjs'; diff --git a/test/es-module/test-esm-register-deprecation.mjs b/test/es-module/test-esm-register-deprecation.mjs deleted file mode 100644 index 171e5971a091..000000000000 --- a/test/es-module/test-esm-register-deprecation.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; - -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -const urlToRegister = fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs'); -const urlToRegisterEscaped = JSON.stringify(urlToRegister.href); - - -describe('module.register() deprecation (DEP0205)', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('emits DEP0205 when module.register() is called', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', - `import { register } from 'node:module'; register(${urlToRegisterEscaped});`, - ]); - - assert.match(stderr, /\[DEP0205\]/); - assert.strictEqual(code, 0); - }); - - it('only emits the warning once per process', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--input-type=module', - '--eval', - `import { register } from 'node:module'; - register(${urlToRegisterEscaped}); - register(${urlToRegisterEscaped});`, - ]); - - assert.strictEqual(stderr.split('[DEP0205]').length - 1, 1); - assert.strictEqual(code, 0); - }); - - it('does not emit when --no-deprecation is set', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--no-deprecation', - '--input-type=module', - '--eval', - `import { register } from 'node:module'; register(${urlToRegisterEscaped});`, - ]); - - assert.doesNotMatch(stderr, /DEP0205/); - assert.strictEqual(code, 0); - }); - - it('throws when --throw-deprecation is set', async () => { - const { code, stderr } = await spawnPromisified(execPath, [ - '--throw-deprecation', - '--input-type=module', - '--eval', - `import { register } from 'node:module'; register(${urlToRegisterEscaped});`, - ]); - - assert.match(stderr, /DEP0205/); - assert.notStrictEqual(code, 0); - }); -}); diff --git a/test/es-module/test-esm-require-after-failed-import.js b/test/es-module/test-esm-require-after-failed-import.js new file mode 100644 index 000000000000..6815243212f9 --- /dev/null +++ b/test/es-module/test-esm-require-after-failed-import.js @@ -0,0 +1,15 @@ +'use strict'; +// Tests that require() of an ES module whose earlier import() failed during +// instantiation throws ERR_REQUIRE_ESM_RACE_CONDITION. +const common = require('../common'); +const assert = require('node:assert'); +const fixtures = require('../common/fixtures'); + +const url = fixtures.fileURL('es-modules/require-after-failed-import/mismatched.mjs'); + +assert.rejects(import(url), { name: 'SyntaxError' }).then(common.mustCall(() => { + assert.throws( + () => require(fixtures.path('es-modules/require-after-failed-import/mismatched.mjs')), + { code: 'ERR_REQUIRE_ESM_RACE_CONDITION' }, + ); +})); diff --git a/test/es-module/test-esm-shared-loader-dep.mjs b/test/es-module/test-esm-shared-loader-dep.mjs deleted file mode 100644 index e0015bd0c755..000000000000 --- a/test/es-module/test-esm-shared-loader-dep.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-shared-dep.mjs -import { createRequire } from '../common/index.mjs'; - -import assert from 'assert'; -import '../fixtures/es-modules/test-esm-ok.mjs'; - -const require = createRequire(import.meta.url); -const dep = require('../fixtures/es-module-loaders/loader-dep.js'); - -assert.strictEqual(dep.format, 'module'); diff --git a/test/es-module/test-loaders-unknown-builtin-module.mjs b/test/es-module/test-loaders-unknown-builtin-module.mjs deleted file mode 100644 index c97e52d1e63d..000000000000 --- a/test/es-module/test-loaders-unknown-builtin-module.mjs +++ /dev/null @@ -1,12 +0,0 @@ -// Flags: --experimental-loader ./test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs -import { expectsError, mustCall } from '../common/index.mjs'; -import assert from 'assert'; - -const unknownBuiltinModule = 'node:unknown-builtin-module'; - -import(unknownBuiltinModule) -.then(assert.fail, expectsError({ - code: 'ERR_UNKNOWN_BUILTIN_MODULE', - message: `No such built-in module: ${unknownBuiltinModule}`, -})) -.then(mustCall()); diff --git a/test/es-module/test-loaders-workers-spawned.mjs b/test/es-module/test-loaders-workers-spawned.mjs deleted file mode 100644 index 68c1b863f7ca..000000000000 --- a/test/es-module/test-loaders-workers-spawned.mjs +++ /dev/null @@ -1,83 +0,0 @@ -import { spawnPromisified } from '../common/index.mjs'; -import * as fixtures from '../common/fixtures.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import { describe, it } from 'node:test'; - -describe('Worker threads do not spawn infinitely', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should not trigger an infinite loop when using a loader exports no recognized hooks', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('empty.js'), - '--eval', - 'setTimeout(() => console.log("hello"),99)', - ]); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /^hello\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('should support a CommonJS entry point and a loader that imports a CommonJS module', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-with-dep.mjs'), - fixtures.path('print-delayed.js'), - ]); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /^delayed\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('should support --require and --import along with using a loader written in CJS and CJS entry point', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--eval', - 'setTimeout(() => console.log("D"),99)', - '--import', - fixtures.fileURL('printC.js'), - '--experimental-loader', - fixtures.fileURL('printB.js'), - '--require', - fixtures.path('printA.js'), - ]); - - assert.strictEqual(stderr, ''); - // We are validating that: - // 1. the `--require` flag is run first from the main thread (and A is printed). - // 2. the `--require` flag is then run on the loader thread (and A is printed). - // 3. the `--loader` module is executed (and B is printed). - // 4. the `--import` module is evaluated once, on the main thread (and C is printed). - // 5. the user code is finally executed (and D is printed). - // The worker code should always run before the --import, but the console.log might arrive late. - assert.match(stdout, /^A\r?\n(A\r?\nB\r?\nC|A\r?\nC\r?\nB|C\r?\nA\r?\nB)\r?\nD\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - - it('should support --require and --import along with using a loader written in ESM and ESM entry point', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--require', - fixtures.path('printA.js'), - '--experimental-loader', - 'data:text/javascript,console.log("B")', - '--import', - fixtures.fileURL('printC.js'), - '--input-type=module', - '--eval', - 'setTimeout(() => console.log("D"),99)', - ]); - - assert.strictEqual(stderr, ''); - // The worker code should always run before the --import, but the console.log might arrive late. - assert.match(stdout, /^A\r?\n(A\r?\nB\r?\nC|A\r?\nC\r?\nB|C\r?\nA\r?\nB)\r?\nD\r?\n$/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); -}); diff --git a/test/es-module/test-require-esm-from-imported-cjs.js b/test/es-module/test-require-esm-from-imported-cjs.js index bbce967a4b7e..b643923313db 100644 --- a/test/es-module/test-require-esm-from-imported-cjs.js +++ b/test/es-module/test-require-esm-from-imported-cjs.js @@ -20,17 +20,3 @@ spawnSyncAndAssert( stdout: / default: { hello: 'world' }/, } ); - -spawnSyncAndAssert( - process.execPath, - [ - '--experimental-require-module', - '--import', - fixtures.fileURL('es-modules', 'require-esm-in-cjs-cache', 'instrument.js'), - fixtures.path('es-modules', 'require-esm-in-cjs-cache', 'app.cjs'), - ], - { - trim: true, - stdout: / default: { hello: 'world' }/, - } -); diff --git a/test/eslint.config_partial.mjs b/test/eslint.config_partial.mjs index 5800eef9407a..0710c4cddf04 100644 --- a/test/eslint.config_partial.mjs +++ b/test/eslint.config_partial.mjs @@ -121,6 +121,10 @@ export default [ selector: 'VariableDeclarator[init.type="Identifier"][init.name=/^(assert|fixtures)$/]', message: 'Do not destructure or rename `assert` nor `fixtures`', }, + { + selector: 'CallExpression[callee.object.name="os"][callee.property.name="tmpdir"], CallExpression[callee.name="tmpdir"]', + message: 'Do not use `os.tmpdir`, prefer the `common/tmpdir` module.', + }, ...((fixturesSpecifier) => [ { selector: `ImportDeclaration[source.value=${fixturesSpecifier.toString().replace('(\\.js)?', '\\.mjs')}]:not(${[ @@ -217,7 +221,6 @@ export default [ }, { files: [ - 'test/es-module/test-esm-example-loader.js', 'test/es-module/test-esm-type-flag.js', 'test/es-module/test-esm-type-flag-alias.js', 'test/es-module/test-require-module-detect-entry-point.js', diff --git a/test/ffi/test-ffi-vfs.js b/test/ffi/test-ffi-vfs.js index 832deda68ac7..aea31b619605 100644 --- a/test/ffi/test-ffi-vfs.js +++ b/test/ffi/test-ffi-vfs.js @@ -5,7 +5,6 @@ common.skipIfFFIMissing(); const assert = require('node:assert'); const { spawnSync } = require('node:child_process'); const fs = require('node:fs'); -const os = require('node:os'); const path = require('node:path'); const { test } = require('node:test'); const tmpdir = require('../common/tmpdir'); @@ -99,7 +98,7 @@ test('closed library images give their fd numbers back', { skip: !common.isLinux process.execPath, '--disable-warning=ExperimentalWarning', '-e', child, ], { encoding: 'utf8', - env: { ...process.env, TMPDIR: path.join(os.tmpdir(), 'no-such-directory') }, + env: { ...process.env, TMPDIR: tmpdir.resolve('no-such-directory') }, }); assert.strictEqual(status, 0, stderr); }); diff --git a/test/fixtures/bench-runner/gc.cjs b/test/fixtures/bench-runner/gc.cjs new file mode 100644 index 000000000000..f94688707e53 --- /dev/null +++ b/test/fixtures/bench-runner/gc.cjs @@ -0,0 +1,10 @@ +'use strict'; + +const { bench } = require('node:bench'); + +const options = { samples: 3, warmup: 2 }; +if (process.env.BENCH_GC_OPTION) options.gc = process.env.BENCH_GC_OPTION; + +bench('gc', options, (b) => { + b.record({ detail: typeof globalThis.gc, duration_ns: 1n }); +}); diff --git a/test/fixtures/debugger/probe-attach-blocked.js b/test/fixtures/debugger/probe-attach-blocked.js new file mode 100644 index 000000000000..ff44cc408360 --- /dev/null +++ b/test/fixtures/debugger/probe-attach-blocked.js @@ -0,0 +1,5 @@ +'use strict'; +// Blocked the main thread with a synchronous read until its stdin is closed, so it +// cannot answer inspector requests. +require('fs').writeSync(1, 'PROBE_READY\n'); +require('fs').readSync(0, Buffer.alloc(1)); diff --git a/test/fixtures/debugger/probe-attach-busy.js b/test/fixtures/debugger/probe-attach-busy.js new file mode 100644 index 000000000000..a74ba1a88120 --- /dev/null +++ b/test/fixtures/debugger/probe-attach-busy.js @@ -0,0 +1,10 @@ +'use strict'; +// Runs tick() continuously, so a breakpoint in tick() pauses the target as soon as it is bound. +let count = 0; +function tick() { + count++; + setImmediate(tick); +} + +tick(); +console.log('PROBE_READY'); diff --git a/test/fixtures/debugger/probe-attach-finishes.js b/test/fixtures/debugger/probe-attach-finishes.js new file mode 100644 index 000000000000..49d998146d68 --- /dev/null +++ b/test/fixtures/debugger/probe-attach-finishes.js @@ -0,0 +1,11 @@ +'use strict'; +// Runs tick() once when its stdin is closed, or throw if PROBE_ATTACH_THROW is set. +let count = 0; +function tick() { + count++; + if (process.env.PROBE_ATTACH_THROW) throw new Error('boom'); +} + +process.stdin.on('end', tick); +process.stdin.resume(); +console.log('PROBE_READY'); diff --git a/test/fixtures/debugger/probe-attach-loop.js b/test/fixtures/debugger/probe-attach-loop.js new file mode 100644 index 000000000000..6859bcd19e1a --- /dev/null +++ b/test/fixtures/debugger/probe-attach-loop.js @@ -0,0 +1,10 @@ +'use strict'; +// Increments a counter on a timer so probes have a changing value +// to read, and prints `PROBE_READY` once the timer is scheduled. +let count = 0; +function tick() { + count++; +} + +setInterval(tick, 50); +console.log('PROBE_READY'); diff --git a/test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs b/test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs deleted file mode 100644 index f1b770d04f4f..000000000000 --- a/test/fixtures/es-module-loaders/builtin-named-exports-loader.mjs +++ /dev/null @@ -1,59 +0,0 @@ -import module from 'node:module'; -import { readFileSync } from 'node:fs'; - -/** @type {string} */ -let GET_BUILTIN; -export function initialize(data) { - GET_BUILTIN = data.GET_BUILTIN; -} - -export async function resolve(specifier, context, next) { - const def = await next(specifier, context); - - if (def.url.startsWith('node:')) { - return { - shortCircuit: true, - url: `custom-${def.url}`, - importAttributes: context.importAttributes, - }; - } - return def; -} - -export function load(url, context, next) { - if (url.startsWith('custom-node:')) { - const urlObj = new URL(url); - return { - shortCircuit: true, - source: generateBuiltinModule(urlObj.pathname), - format: 'commonjs', - }; - } else if (context.format === undefined || context.format === null || context.format === 'commonjs') { - return { - shortCircuit: true, - source: readFileSync(new URL(url)), - format: 'commonjs', - }; - } - return next(url); -} - -function generateBuiltinModule(builtinName) { - const builtinInstance = module._load(builtinName); - const builtinExports = [ - ...Object.keys(builtinInstance), - ]; - return `\ -const $builtinInstance = ${GET_BUILTIN}(${JSON.stringify(builtinName)}); - -module.exports = $builtinInstance; -module.exports.__fromLoader = true; - -// We need this for CJS-module-lexer can parse the exported names. -${ - builtinExports - .map(name => `exports.${name} = $builtinInstance.${name};`) - .join('\n') -} -`; -} diff --git a/test/fixtures/es-module-loaders/builtin-named-exports.mjs b/test/fixtures/es-module-loaders/builtin-named-exports.mjs deleted file mode 100644 index 123b12c26bf0..000000000000 --- a/test/fixtures/es-module-loaders/builtin-named-exports.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import * as fixtures from '../../common/fixtures.mjs'; -import { createRequire, register } from 'node:module'; - -const require = createRequire(import.meta.url); - -const GET_BUILTIN = `$__get_builtin_hole_${Date.now()}`; -Object.defineProperty(globalThis, GET_BUILTIN, { - value: builtinName => require(builtinName), - enumerable: false, - configurable: false, -}); - -register(fixtures.fileURL('es-module-loaders/builtin-named-exports-loader.mjs'), { - data: { - GET_BUILTIN, - }, -}); diff --git a/test/fixtures/es-module-loaders/byop-dummy-loader.mjs b/test/fixtures/es-module-loaders/byop-dummy-loader.mjs deleted file mode 100644 index 17a3430b44e3..000000000000 --- a/test/fixtures/es-module-loaders/byop-dummy-loader.mjs +++ /dev/null @@ -1,30 +0,0 @@ -export function load(url, context, nextLoad) { - switch (url) { - case 'byop://1/index.mjs': - return { - source: 'console.log("index.mjs!")', - format: 'module', - shortCircuit: true, - }; - case 'byop://1/index2.mjs': - return { - source: 'import c from "./sub.mjs"; console.log(c);', - format: 'module', - shortCircuit: true, - }; - case 'byop://1/sub.mjs': - return { - source: 'export default 42', - format: 'module', - shortCircuit: true, - }; - case 'byop://1/index.byoe': - return { - source: 'console.log("index.byoe!")', - format: 'module', - shortCircuit: true, - }; - default: - return nextLoad(url, context); - } -} diff --git a/test/fixtures/es-module-loaders/example-loader.mjs b/test/fixtures/es-module-loaders/example-loader.mjs deleted file mode 100644 index 77d44d55f915..000000000000 --- a/test/fixtures/es-module-loaders/example-loader.mjs +++ /dev/null @@ -1,46 +0,0 @@ -import { URL } from 'url'; -import path from 'path'; -import process from 'process'; -import { builtinModules } from 'module'; - -const JS_EXTENSIONS = new Set(['.js', '.mjs']); - -const baseURL = new URL('file://'); -baseURL.pathname = process.cwd() + '/'; - -export function resolve(specifier, { parentURL = baseURL }, next) { - if (builtinModules.includes(specifier)) { - return { - shortCircuit: true, - url: 'node:' + specifier - }; - } - if (/^\.{1,2}[/]/.test(specifier) !== true && !specifier.startsWith('file:')) { - // For node_modules support: - // return next(specifier); - throw new Error( - `imports must be URLs or begin with './', or '../'; '${specifier}' does not`); - } - const resolved = new URL(specifier, parentURL); - return { - shortCircuit: true, - url: resolved.href - }; -} - -export function getFormat(url, context, defaultGetFormat) { - if (url.startsWith('node:') && builtinModules.includes(url.slice(5))) { - return { - format: 'builtin' - }; - } - const { pathname } = new URL(url); - const ext = path.extname(pathname); - if (!JS_EXTENSIONS.has(ext)) { - throw new Error( - `Cannot load file with non-JavaScript file extension ${ext}.`); - } - return { - format: 'module' - }; -} diff --git a/test/fixtures/es-module-loaders/hook-resolve-type-loader.mjs b/test/fixtures/es-module-loaders/hook-resolve-type-loader.mjs deleted file mode 100644 index c410401876e4..000000000000 --- a/test/fixtures/es-module-loaders/hook-resolve-type-loader.mjs +++ /dev/null @@ -1,25 +0,0 @@ -/** @type {Uint8Array} */ -let data; -/** @type {number} */ -let ESM_MODULE_INDEX; -/** @type {number} */ -let CJS_MODULE_INDEX; - -export function initialize({ sab, ESM_MODULE_INDEX:e, CJS_MODULE_INDEX:c }) { - data = new Uint8Array(sab); - ESM_MODULE_INDEX = e; - CJS_MODULE_INDEX = c; -} - -export async function resolve(specifier, context, next) { - const nextResult = await next(specifier, context); - const { format } = nextResult; - - if (format === 'module' || specifier.endsWith('.mjs')) { - Atomics.add(data, ESM_MODULE_INDEX, 1); - } else if (format == null || format === 'commonjs') { - Atomics.add(data, CJS_MODULE_INDEX, 1); - } - - return nextResult; -} diff --git a/test/fixtures/es-module-loaders/hook-resolve-type.mjs b/test/fixtures/es-module-loaders/hook-resolve-type.mjs deleted file mode 100644 index 7324a08e84b6..000000000000 --- a/test/fixtures/es-module-loaders/hook-resolve-type.mjs +++ /dev/null @@ -1,18 +0,0 @@ -import * as fixtures from '../../common/fixtures.mjs'; -import { register } from 'node:module'; - -const sab = new SharedArrayBuffer(2); -const data = new Uint8Array(sab); - -const ESM_MODULE_INDEX = 0 -const CJS_MODULE_INDEX = 1 - -export function getModuleTypeStats() { - const importedESM = Atomics.load(data, ESM_MODULE_INDEX); - const importedCJS = Atomics.load(data, CJS_MODULE_INDEX); - return { importedESM, importedCJS }; -} - -register(fixtures.fileURL('es-module-loaders/hook-resolve-type-loader.mjs'), { - data: { sab, ESM_MODULE_INDEX, CJS_MODULE_INDEX }, -}); diff --git a/test/fixtures/es-module-loaders/hooks-custom.mjs b/test/fixtures/es-module-loaders/hooks-custom.mjs deleted file mode 100644 index 5109d20f4d37..000000000000 --- a/test/fixtures/es-module-loaders/hooks-custom.mjs +++ /dev/null @@ -1,116 +0,0 @@ -import { pathToFileURL } from 'node:url'; -import count from '../es-modules/stateful.mjs'; - - -// Arbitrary instance of manipulating a module's internal state -// used to assert node-land and user-land have different contexts -count(); - -export function resolve(specifier, { importAttributes }, next) { - let format = ''; - - if (specifier === 'esmHook/format.false') { - format = false; - } - if (specifier === 'esmHook/format.true') { - format = true; - } - if (specifier === 'esmHook/preknownFormat.pre') { - format = 'module'; - } - - if (specifier.startsWith('esmHook')) { - return { - format, - shortCircuit: true, - url: pathToFileURL(specifier).href, - importAttributes, - }; - } - - return next(specifier); -} - -/** - * @param {string} url A fully resolved file url. - * @param {object} context Additional info. - * @param {function} next for now, next is defaultLoad a wrapper for - * defaultGetFormat + defaultGetSource - * @returns {{ format: string, source: (string|SharedArrayBuffer|Uint8Array) }} - */ -export function load(url, context, next) { - // Load all .js files as ESM, regardless of package scope - if (url.endsWith('.js')) { - return next(url, { - ...context, - format: 'module', - }); - } - - if (url.endsWith('.ext')) { - return next(url, { - ...context, - format: 'module', - }); - } - - if (url.endsWith('esmHook/badReturnVal.mjs')) { - return 'export function returnShouldBeObject() {}'; - } - - if (url.endsWith('esmHook/badReturnFormatVal.mjs')) { - return { - format: Array(0), - shortCircuit: true, - source: '', - }; - } - if (url.endsWith('esmHook/unsupportedReturnFormatVal.mjs')) { - return { - format: 'foo', // Not one of the allowable inputs: no translator named 'foo' - shortCircuit: true, - source: '', - }; - } - - if (url.endsWith('esmHook/badReturnSourceVal.mjs')) { - return { - format: 'module', - shortCircuit: true, - source: Array(0), - }; - } - - if (url.endsWith('esmHook/preknownFormat.pre')) { - return { - format: context.format, - shortCircuit: true, - source: `const msg = 'hello world'; export default msg;` - }; - } - - if (url.endsWith('esmHook/virtual.mjs')) { - return { - format: 'module', - shortCircuit: true, - source: `export const message = 'Woohoo!'.toUpperCase();`, - }; - } - - if (url.endsWith('esmHook/commonJsNullSource.mjs')) { - return { - format: 'commonjs', - shortCircuit: true, - source: 1n, - }; - } - - if (url.endsWith('esmHook/maximumCallStack.mjs')) { - function recurse() { - recurse(); - } - recurse(); - } - - return next(url); -} diff --git a/test/fixtures/es-module-loaders/hooks-initialize-port.mjs b/test/fixtures/es-module-loaders/hooks-initialize-port.mjs deleted file mode 100644 index cefe8854297c..000000000000 --- a/test/fixtures/es-module-loaders/hooks-initialize-port.mjs +++ /dev/null @@ -1,16 +0,0 @@ -let thePort = null; - -export async function initialize(port) { - port.postMessage('initialize'); - thePort = port; -} - -export async function resolve(specifier, context, next) { - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - thePort.postMessage(`resolve ${specifier}`); - - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/hooks-initialize.mjs b/test/fixtures/es-module-loaders/hooks-initialize.mjs deleted file mode 100644 index 7622d982a9d7..000000000000 --- a/test/fixtures/es-module-loaders/hooks-initialize.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeFileSync } from 'node:fs'; - -let counter = 0; - -export async function initialize() { - writeFileSync(1, `hooks initialize ${++counter}\n`); -} diff --git a/test/fixtures/es-module-loaders/hooks-input.mjs b/test/fixtures/es-module-loaders/hooks-input.mjs deleted file mode 100644 index e4eb159b3987..000000000000 --- a/test/fixtures/es-module-loaders/hooks-input.mjs +++ /dev/null @@ -1,94 +0,0 @@ -// This is expected to be used by test-esm-loader-hooks.mjs via: -// node --loader ./test/fixtures/es-module-loaders/hooks-input.mjs ./test/fixtures/es-modules/json-modules.mjs - -import assert from 'assert'; -import { writeSync } from 'fs'; -import { readFile } from 'fs/promises'; -import { fileURLToPath } from 'url'; - - -let resolveCalls = 0; -let loadCalls = 0; - -export async function resolve(specifier, context, next) { - resolveCalls++; - let url; - - if (resolveCalls === 1) { - url = new URL(specifier).href; - assert.match(specifier, /json-modules\.mjs$/); - - if (!(/\[eval\d*\]$/).test(context.parentURL)) { - assert.strictEqual(context.parentURL, undefined); - } - - assert.deepStrictEqual(context.importAttributes, {}); - } else if (resolveCalls === 2) { - url = new URL(specifier, context.parentURL).href; - assert.match(specifier, /experimental\.json$/); - assert.match(context.parentURL, /json-modules\.mjs$/); - assert.deepStrictEqual(context.importAttributes, { - type: 'json', - }); - } else { - throw new Error(`Unexpected resolve call: ${specifier}`); - } - - // Ensure `context` has all and only the properties it's supposed to - assert.deepStrictEqual(Reflect.ownKeys(context), [ - 'conditions', - 'importAttributes', - 'parentURL', - 'importAssertions', - ]); - assert.ok(Array.isArray(context.conditions)); - assert.strictEqual(typeof next, 'function'); - - const returnValue = { - url, - format: 'test', - shortCircuit: true, - } - - writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout - - return returnValue; -} - -export async function load(url, context, next) { - loadCalls++; - const source = await readFile(fileURLToPath(url)); - let format; - - if (loadCalls === 1) { - assert.match(url, /json-modules\.mjs$/); - assert.deepStrictEqual(context.importAttributes, {}); - format = 'module'; - } else if (loadCalls === 2) { - assert.match(url, /experimental\.json$/); - assert.deepStrictEqual(context.importAttributes, { - type: 'json', - }); - format = 'json'; - } - - assert.ok(new URL(url)); - // Ensure `context` has all and only the properties it's supposed to - assert.deepStrictEqual(Reflect.ownKeys(context), [ - 'format', - 'importAttributes', - 'importAssertions', - ]); - assert.strictEqual(context.format, 'test'); - assert.strictEqual(typeof next, 'function'); - - const returnValue = { - source, - format, - shortCircuit: true, - }; - - writeSync(1, JSON.stringify(returnValue) + '\n'); // For the test to validate when it parses stdout - - return returnValue; -} diff --git a/test/fixtures/es-module-loaders/http-loader.mjs b/test/fixtures/es-module-loaders/http-loader.mjs deleted file mode 100644 index 4fe8fcb47974..000000000000 --- a/test/fixtures/es-module-loaders/http-loader.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { get } from 'http'; - -export function load(url, context, nextLoad) { - if (url.startsWith('http://')) { - return new Promise((resolve, reject) => { - get(url, (rsp) => { - let data = ''; - rsp.on('data', (chunk) => data += chunk); - rsp.on('end', () => { - resolve({ - format: 'module', - shortCircuit: true, - source: data, - }); - }); - }) - .on('error', reject); - }); - } - - return nextLoad(url); -} diff --git a/test/fixtures/es-module-loaders/js-as-esm.js b/test/fixtures/es-module-loaders/js-as-esm.js deleted file mode 100644 index b4d2741b2fc5..000000000000 --- a/test/fixtures/es-module-loaders/js-as-esm.js +++ /dev/null @@ -1 +0,0 @@ -export const namedExport = 'named-export'; diff --git a/test/fixtures/es-module-loaders/loader-delayed-async-load.mjs b/test/fixtures/es-module-loaders/loader-delayed-async-load.mjs deleted file mode 100644 index 33bae9bdafd9..000000000000 --- a/test/fixtures/es-module-loaders/loader-delayed-async-load.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function load(a, b, c) { - return new Promise(d => setTimeout(() => d(c(a, b)), 99)); -} diff --git a/test/fixtures/es-module-loaders/loader-dep.js b/test/fixtures/es-module-loaders/loader-dep.js deleted file mode 100644 index c8154ac5dbe6..000000000000 --- a/test/fixtures/es-module-loaders/loader-dep.js +++ /dev/null @@ -1 +0,0 @@ -exports.format = 'module'; diff --git a/test/fixtures/es-module-loaders/loader-edge-cases.mjs b/test/fixtures/es-module-loaders/loader-edge-cases.mjs deleted file mode 100644 index 19af0e2bc078..000000000000 --- a/test/fixtures/es-module-loaders/loader-edge-cases.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { strictEqual } from "node:assert"; -import { isMainThread, workerData, parentPort } from "node:worker_threads"; - -strictEqual(isMainThread, false); - -// We want to make sure that internals are not leaked on the public module: -strictEqual(workerData, null); -strictEqual(parentPort, null); - -// We don't want `import.meta.resolve` being available from loaders -// as the sync implementation is not compatible with calling async -// functions on the same thread. -strictEqual(typeof import.meta.resolve, 'undefined'); diff --git a/test/fixtures/es-module-loaders/loader-exit-on-load.mjs b/test/fixtures/es-module-loaders/loader-exit-on-load.mjs deleted file mode 100644 index 4ee413fa46ce..000000000000 --- a/test/fixtures/es-module-loaders/loader-exit-on-load.mjs +++ /dev/null @@ -1,4 +0,0 @@ -export function load(a, b, next) { - if (a === 'data:exit') process.exit(42); - return next(a, b); -} diff --git a/test/fixtures/es-module-loaders/loader-exit-on-resolve.mjs b/test/fixtures/es-module-loaders/loader-exit-on-resolve.mjs deleted file mode 100644 index cffa4bcc486a..000000000000 --- a/test/fixtures/es-module-loaders/loader-exit-on-resolve.mjs +++ /dev/null @@ -1,4 +0,0 @@ -export function resolve(a, b, next) { - if (a === 'exit:') process.exit(42); - return next(a, b); -} diff --git a/test/fixtures/es-module-loaders/loader-exit-top-level.mjs b/test/fixtures/es-module-loaders/loader-exit-top-level.mjs deleted file mode 100644 index 6427ca06037f..000000000000 --- a/test/fixtures/es-module-loaders/loader-exit-top-level.mjs +++ /dev/null @@ -1 +0,0 @@ -process.exit(42); diff --git a/test/fixtures/es-module-loaders/loader-globalpreload-and-initialize.mjs b/test/fixtures/es-module-loaders/loader-globalpreload-and-initialize.mjs deleted file mode 100644 index 7055b90f4e75..000000000000 --- a/test/fixtures/es-module-loaders/loader-globalpreload-and-initialize.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export function globalPreload() {} -export function initialize() {} diff --git a/test/fixtures/es-module-loaders/loader-globalpreload-only.mjs b/test/fixtures/es-module-loaders/loader-globalpreload-only.mjs deleted file mode 100644 index 6b7f59d63198..000000000000 --- a/test/fixtures/es-module-loaders/loader-globalpreload-only.mjs +++ /dev/null @@ -1 +0,0 @@ -export function globalPreload() {} diff --git a/test/fixtures/es-module-loaders/loader-globalpreload-with-return.mjs b/test/fixtures/es-module-loaders/loader-globalpreload-with-return.mjs deleted file mode 100644 index f54cf72ce5b9..000000000000 --- a/test/fixtures/es-module-loaders/loader-globalpreload-with-return.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function globalPreload() { - return ''; -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-exit.mjs b/test/fixtures/es-module-loaders/loader-initialize-exit.mjs deleted file mode 100644 index 53cb4fa26f01..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-exit.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - process.exit(42); -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-never-settling.mjs b/test/fixtures/es-module-loaders/loader-initialize-never-settling.mjs deleted file mode 100644 index 80033b663a5a..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-never-settling.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - return new Promise(() => {}); -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-rejecting.mjs b/test/fixtures/es-module-loaders/loader-initialize-rejecting.mjs deleted file mode 100644 index 899accc15114..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-rejecting.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - return Promise.reject(); -} diff --git a/test/fixtures/es-module-loaders/loader-initialize-throw-null.mjs b/test/fixtures/es-module-loaders/loader-initialize-throw-null.mjs deleted file mode 100644 index 3d834b5c23cf..000000000000 --- a/test/fixtures/es-module-loaders/loader-initialize-throw-null.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export function initialize() { - throw null; -} diff --git a/test/fixtures/es-module-loaders/loader-invalid-format.mjs b/test/fixtures/es-module-loaders/loader-invalid-format.mjs deleted file mode 100644 index dc61a792b2be..000000000000 --- a/test/fixtures/es-module-loaders/loader-invalid-format.mjs +++ /dev/null @@ -1,20 +0,0 @@ -export async function resolve(specifier, { parentURL, importAttributes }, next) { - if (parentURL && specifier === '../fixtures/es-modules/test-esm-ok.mjs') { - return { - shortCircuit: true, - url: 'file:///asdf', - }; - } - return next(specifier); -} - -export async function load(url, context, next) { - if (url === 'file:///asdf') { - return { - format: 'esm', - shortCircuit: true, - source: '', - } - } - return next(url); -} diff --git a/test/fixtures/es-module-loaders/loader-invalid-url.mjs b/test/fixtures/es-module-loaders/loader-invalid-url.mjs deleted file mode 100644 index aac2b16b6f58..000000000000 --- a/test/fixtures/es-module-loaders/loader-invalid-url.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export async function resolve(specifier, { parentURL, importAttributes }, next) { - if (parentURL && specifier === '../fixtures/es-modules/test-esm-ok.mjs') { - return { - shortCircuit: true, - url: specifier, - importAttributes, - }; - } - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-load-bad-next-context.mjs b/test/fixtures/es-module-loaders/loader-load-bad-next-context.mjs deleted file mode 100644 index fe38da04f9ff..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-bad-next-context.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, next) { - return next(url, []); -} diff --git a/test/fixtures/es-module-loaders/loader-load-bad-next-url.mjs b/test/fixtures/es-module-loaders/loader-load-bad-next-url.mjs deleted file mode 100644 index c6a4c7504d43..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-bad-next-url.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, next) { - return next([]); -} diff --git a/test/fixtures/es-module-loaders/loader-load-commonjs-with-source.mjs b/test/fixtures/es-module-loaders/loader-load-commonjs-with-source.mjs deleted file mode 100644 index 3f431e630cdd..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-commonjs-with-source.mjs +++ /dev/null @@ -1,13 +0,0 @@ -import { readFile } from 'node:fs/promises'; -import { fileURLToPath } from 'node:url'; - -export async function load(url, context, nextLoad) { - const result = await nextLoad(url, context); - if (url.endsWith('/common/index.js')) { - result.source = '"use strict";module.exports=require("node:module").createRequire(' + - JSON.stringify(url) + ')(' + JSON.stringify(fileURLToPath(url)) + ');\n'; - } else if (url.startsWith('file:') && (context.format == null || context.format === 'commonjs')) { - result.source = await readFile(new URL(url)); - } - return result; -} diff --git a/test/fixtures/es-module-loaders/loader-load-dynamic-import.mjs b/test/fixtures/es-module-loaders/loader-load-dynamic-import.mjs deleted file mode 100644 index 96af5507d172..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-dynamic-import.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function load(url, context, next) { - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - // Here for asserting dynamic import - await import('xxx/loader-load-passthru.mjs'); - - writeSync(1, 'load dynamic import' + '\n'); // Signal that this specific hook ran - return next(url, context); -} diff --git a/test/fixtures/es-module-loaders/loader-load-foo-or-42.mjs b/test/fixtures/es-module-loaders/loader-load-foo-or-42.mjs deleted file mode 100644 index 285b81a910ef..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-foo-or-42.mjs +++ /dev/null @@ -1,19 +0,0 @@ -export async function load(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - const val = url.includes('42') - ? '42' - : '"foo"'; - - return { - format: 'module', - shortCircuit: true, - source: `export default ${val}`, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-load-impersonating-next-url.mjs b/test/fixtures/es-module-loaders/loader-load-impersonating-next-url.mjs deleted file mode 100644 index 1028e093e468..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-impersonating-next-url.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, next) { - return next('not/a/url'); -} diff --git a/test/fixtures/es-module-loaders/loader-load-incomplete.mjs b/test/fixtures/es-module-loaders/loader-load-incomplete.mjs deleted file mode 100644 index bf6d5ea254dc..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-incomplete.mjs +++ /dev/null @@ -1,14 +0,0 @@ -export async function load(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - return { - format: 'module', - source: 'export default 42', - }; -} diff --git a/test/fixtures/es-module-loaders/loader-load-next-modified.mjs b/test/fixtures/es-module-loaders/loader-load-next-modified.mjs deleted file mode 100644 index 401b52971311..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-next-modified.mjs +++ /dev/null @@ -1,11 +0,0 @@ -export async function load(url, context, next) { - const { - format, - source, - } = await next(url); - - return { - format, - source: source + 1, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-load-null-return.mjs b/test/fixtures/es-module-loaders/loader-load-null-return.mjs deleted file mode 100644 index 252eec4ebc28..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-null-return.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(specifier, context, next) { - return null; -} diff --git a/test/fixtures/es-module-loaders/loader-load-passing-modified-context.mjs b/test/fixtures/es-module-loaders/loader-load-passing-modified-context.mjs deleted file mode 100644 index 7676be766af5..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-passing-modified-context.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export async function load(url, context, next) { - return next(url, { - ...context, - foo: 'bar', - }); -} diff --git a/test/fixtures/es-module-loaders/loader-load-passthru.mjs b/test/fixtures/es-module-loaders/loader-load-passthru.mjs deleted file mode 100644 index 72ff6b56122d..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-passthru.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - -export async function load(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - writeSync(1, 'load passthru' + '\n'); // Signal that this specific hook ran - return next(url); -} diff --git a/test/fixtures/es-module-loaders/loader-load-receiving-modified-context.mjs b/test/fixtures/es-module-loaders/loader-load-receiving-modified-context.mjs deleted file mode 100644 index 6e5a1ee71936..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-receiving-modified-context.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function load(url, context, next) { - writeSync(1, context.foo + '\n'); // Expose actual value the hook was called with - return next(url, context); -} diff --git a/test/fixtures/es-module-loaders/loader-load-source-maps.mjs b/test/fixtures/es-module-loaders/loader-load-source-maps.mjs deleted file mode 100644 index bf5ef6b91028..000000000000 --- a/test/fixtures/es-module-loaders/loader-load-source-maps.mjs +++ /dev/null @@ -1,9 +0,0 @@ -import { readFile } from 'node:fs/promises'; - -export async function load(url, context, nextLoad) { - const resolved = await nextLoad(url, context); - if (context.format === 'commonjs') { - resolved.source = await readFile(new URL(url)); - } - return resolved; -} diff --git a/test/fixtures/es-module-loaders/loader-log-args.mjs b/test/fixtures/es-module-loaders/loader-log-args.mjs deleted file mode 100644 index b56fddbce585..000000000000 --- a/test/fixtures/es-module-loaders/loader-log-args.mjs +++ /dev/null @@ -1,31 +0,0 @@ -import { writeSync } from 'node:fs'; -import { inspect } from 'node:util' - -export async function resolve(...args) { - writeSync(1, `resolve arg count: ${args.length}\n`); - writeSync(1, inspect({ - specifier: args[0], - context: args[1], - next: args[2], - }) + '\n'); - - return { - shortCircuit: true, - url: args[0], - }; -} - -export async function load(...args) { - writeSync(1, `load arg count: ${args.length}\n`); - writeSync(1, inspect({ - url: args[0], - context: args[1], - next: args[2], - }) + '\n'); - - return { - format: 'module', - source: '', - shortCircuit: true, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-mixed-opt-in.mjs b/test/fixtures/es-module-loaders/loader-mixed-opt-in.mjs deleted file mode 100644 index 69b17a88249b..000000000000 --- a/test/fixtures/es-module-loaders/loader-mixed-opt-in.mjs +++ /dev/null @@ -1,28 +0,0 @@ -import { createRequire } from 'module'; - -const require = createRequire(import.meta.url); -const fixtures = require('../../common/fixtures.js'); - -const fixturesPath = fixtures.path('empty.js'); - -export function resolve(s, c, n) { - if (s.endsWith('entry-point')) { - return { - shortCircuit: true, - url: 'file:///c:/virtual-entry-point', - format: 'commonjs', - }; - } - return n(s, c); -} - -export async function load(u, c, n) { - if (u === 'file:///c:/virtual-entry-point') { - return { - shortCircuit: true, - source: `"use strict";require(${JSON.stringify(fixturesPath)});console.log("Hello");`, - format: 'commonjs', - }; - } - return n(u, c); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-42.mjs b/test/fixtures/es-module-loaders/loader-resolve-42.mjs deleted file mode 100644 index b571a27a9787..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-42.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - writeSync(1, 'resolve 42' + '\n'); // Signal that this specific hook ran - writeSync(1, `next<HookName>: ${next.name}\n`); // Expose actual value the hook was called with - - return next('file:///42.mjs'); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-bad-next-context.mjs b/test/fixtures/es-module-loaders/loader-resolve-bad-next-context.mjs deleted file mode 100644 index 881f5875dd02..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-bad-next-context.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function resolve(specifier, context, next) { - return next(specifier, []); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-bad-next-specifier.mjs b/test/fixtures/es-module-loaders/loader-resolve-bad-next-specifier.mjs deleted file mode 100644 index 66c941754f90..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-bad-next-specifier.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function resolve(specifier, context, next) { - return next([]); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-dynamic-import.mjs b/test/fixtures/es-module-loaders/loader-resolve-dynamic-import.mjs deleted file mode 100644 index edc2303ed9aa..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-dynamic-import.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - // Here for asserting dynamic import - await import('xxx/loader-resolve-passthru.mjs'); - - writeSync(1, 'resolve dynamic import' + '\n'); // Signal that this specific hook ran - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-foo.mjs b/test/fixtures/es-module-loaders/loader-resolve-foo.mjs deleted file mode 100644 index b5e5a419b99d..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-foo.mjs +++ /dev/null @@ -1,15 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - writeSync(1, 'resolve foo' + '\n'); // Signal that this specific hook ran - return next('file:///foo.mjs'); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-incomplete.mjs b/test/fixtures/es-module-loaders/loader-resolve-incomplete.mjs deleted file mode 100644 index cb37a4352718..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-incomplete.mjs +++ /dev/null @@ -1,13 +0,0 @@ -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - return { - url: 'file:///incomplete-resolve-chain.js', - }; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-multiple-next-calls.mjs b/test/fixtures/es-module-loaders/loader-resolve-multiple-next-calls.mjs deleted file mode 100644 index 91dbec251ede..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-multiple-next-calls.mjs +++ /dev/null @@ -1,9 +0,0 @@ -export async function resolve(specifier, context, next) { - const { url: first } = await next(specifier); - const { url: second } = await next(specifier); - - return { - format: 'module', - url: first, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-next-modified.mjs b/test/fixtures/es-module-loaders/loader-resolve-next-modified.mjs deleted file mode 100644 index a6b8e85455d3..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-next-modified.mjs +++ /dev/null @@ -1,19 +0,0 @@ -export async function resolve(url, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (url === 'node:fs' || url.includes('loader')) { - return next(url); - } - - const { - format, - url: nextUrl, - } = await next(url, context); - - return { - format, - url: `${nextUrl}?foo`, - }; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-null-return.mjs b/test/fixtures/es-module-loaders/loader-resolve-null-return.mjs deleted file mode 100644 index 16c9826a8ba5..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-null-return.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export async function resolve(specifier, context, next) { - return null; -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-passing-modified-context.mjs b/test/fixtures/es-module-loaders/loader-resolve-passing-modified-context.mjs deleted file mode 100644 index 6a92a6cd8f6a..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-passing-modified-context.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export async function resolve(specifier, context, next) { - return next(specifier, { - ...context, - foo: 'bar', - }); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-passthru.mjs b/test/fixtures/es-module-loaders/loader-resolve-passthru.mjs deleted file mode 100644 index f388f0db273d..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-passthru.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { writeSync } from 'node:fs'; - -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - writeSync(1, 'resolve passthru' + '\n'); // Signal that this specific hook ran - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-receiving-modified-context.mjs b/test/fixtures/es-module-loaders/loader-resolve-receiving-modified-context.mjs deleted file mode 100644 index f6a8fdad53ec..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-receiving-modified-context.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeSync } from 'node:fs'; - - -export async function resolve(specifier, context, next) { - writeSync(1, context.foo + '\n'); // Expose actual value the hook was called with - return next(specifier, context); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-shortcircuit.mjs b/test/fixtures/es-module-loaders/loader-resolve-shortcircuit.mjs deleted file mode 100644 index 00c18e75e2c7..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-shortcircuit.mjs +++ /dev/null @@ -1,14 +0,0 @@ -export async function resolve(specifier, context, next) { - // This check is needed to make sure that we don't prevent the - // resolution from follow-up loaders. It wouldn't be a problem - // in real life because loaders aren't supposed to break the - // resolution, but the ones used in our tests do, for convenience. - if (specifier === 'node:fs' || specifier.includes('loader')) { - return next(specifier); - } - - return { - shortCircuit: true, - url: specifier, - } -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-strip-xxx.mjs b/test/fixtures/es-module-loaders/loader-resolve-strip-xxx.mjs deleted file mode 100644 index 996dfd041c0d..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-strip-xxx.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import { writeSync } from 'node:fs'; -import { inspect } from 'node:util'; - -export async function resolve(specifier, context, nextResolve) { - if (specifier.startsWith('node:')) { - return nextResolve(specifier); - } - writeSync(1, `loader-a ${inspect({specifier})}\n`); - return nextResolve(specifier.replace(/^xxx\//, `./`)); -} diff --git a/test/fixtures/es-module-loaders/loader-resolve-strip-yyy.mjs b/test/fixtures/es-module-loaders/loader-resolve-strip-yyy.mjs deleted file mode 100644 index 7746469bf817..000000000000 --- a/test/fixtures/es-module-loaders/loader-resolve-strip-yyy.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { writeSync } from 'node:fs'; -import { inspect } from 'node:util'; - -export async function resolve(specifier, context, nextResolve) { - writeSync(1, `loader-b ${inspect({specifier})}\n`); - return nextResolve(specifier.replace(/^yyy\//, `./`)); -} diff --git a/test/fixtures/es-module-loaders/loader-shared-dep.mjs b/test/fixtures/es-module-loaders/loader-shared-dep.mjs deleted file mode 100644 index d41c1ae40339..000000000000 --- a/test/fixtures/es-module-loaders/loader-shared-dep.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import assert from 'assert'; - -import { createRequire } from '../../common/index.mjs'; - -const require = createRequire(import.meta.url); -const dep = require('./loader-dep.js'); - -export function resolve(specifier, context, next) { - assert.strictEqual(dep.format, 'module'); - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-this-value-inside-hook-functions.mjs b/test/fixtures/es-module-loaders/loader-this-value-inside-hook-functions.mjs deleted file mode 100644 index 2be18c4969ef..000000000000 --- a/test/fixtures/es-module-loaders/loader-this-value-inside-hook-functions.mjs +++ /dev/null @@ -1,21 +0,0 @@ -export function initialize() { - if (this != null) { - throw new Error('hook function must not be bound to loader instance'); - } -} - -export function resolve(url, _, next) { - if (this != null) { - throw new Error('hook function must not be bound to loader instance'); - } - - return next(url); -} - -export function load(url, _, next) { - if (this != null) { - throw new Error('hook function must not be bound to loader instance'); - } - - return next(url); -} diff --git a/test/fixtures/es-module-loaders/loader-throw-bigint.mjs b/test/fixtures/es-module-loaders/loader-throw-bigint.mjs deleted file mode 100644 index 700b0387fa7f..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-bigint.mjs +++ /dev/null @@ -1 +0,0 @@ -throw 1n; diff --git a/test/fixtures/es-module-loaders/loader-throw-boolean.mjs b/test/fixtures/es-module-loaders/loader-throw-boolean.mjs deleted file mode 100644 index 874fbd92e5fa..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-boolean.mjs +++ /dev/null @@ -1 +0,0 @@ -throw true; diff --git a/test/fixtures/es-module-loaders/loader-throw-empty-object.mjs b/test/fixtures/es-module-loaders/loader-throw-empty-object.mjs deleted file mode 100644 index 778886fcb90a..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-empty-object.mjs +++ /dev/null @@ -1 +0,0 @@ -throw {}; diff --git a/test/fixtures/es-module-loaders/loader-throw-error.mjs b/test/fixtures/es-module-loaders/loader-throw-error.mjs deleted file mode 100644 index 816051b6c783..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-error.mjs +++ /dev/null @@ -1 +0,0 @@ -throw new Error('error message'); diff --git a/test/fixtures/es-module-loaders/loader-throw-function.mjs b/test/fixtures/es-module-loaders/loader-throw-function.mjs deleted file mode 100644 index 35503d670976..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-function.mjs +++ /dev/null @@ -1 +0,0 @@ -throw function fnName() {}; diff --git a/test/fixtures/es-module-loaders/loader-throw-null.mjs b/test/fixtures/es-module-loaders/loader-throw-null.mjs deleted file mode 100644 index 37d3d14b8bfe..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-null.mjs +++ /dev/null @@ -1 +0,0 @@ -throw null; diff --git a/test/fixtures/es-module-loaders/loader-throw-number.mjs b/test/fixtures/es-module-loaders/loader-throw-number.mjs deleted file mode 100644 index 6dbc3994c7ac..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-number.mjs +++ /dev/null @@ -1 +0,0 @@ -throw 1; diff --git a/test/fixtures/es-module-loaders/loader-throw-object.mjs b/test/fixtures/es-module-loaders/loader-throw-object.mjs deleted file mode 100644 index fa7c9b7d43af..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-object.mjs +++ /dev/null @@ -1 +0,0 @@ -throw { fn() {}, symbol: Symbol('symbol'), u: undefined }; diff --git a/test/fixtures/es-module-loaders/loader-throw-string.mjs b/test/fixtures/es-module-loaders/loader-throw-string.mjs deleted file mode 100644 index 613a4321f50d..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-string.mjs +++ /dev/null @@ -1 +0,0 @@ -throw 'literal string'; diff --git a/test/fixtures/es-module-loaders/loader-throw-symbol.mjs b/test/fixtures/es-module-loaders/loader-throw-symbol.mjs deleted file mode 100644 index 05876e0b4ada..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-symbol.mjs +++ /dev/null @@ -1 +0,0 @@ -throw Symbol('symbol descriptor'); diff --git a/test/fixtures/es-module-loaders/loader-throw-undefined.mjs b/test/fixtures/es-module-loaders/loader-throw-undefined.mjs deleted file mode 100644 index 38ecbdff9801..000000000000 --- a/test/fixtures/es-module-loaders/loader-throw-undefined.mjs +++ /dev/null @@ -1 +0,0 @@ -throw undefined; diff --git a/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs b/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs deleted file mode 100644 index 65e1adf909d0..000000000000 --- a/test/fixtures/es-module-loaders/loader-unknown-builtin-module.mjs +++ /dev/null @@ -1,7 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier === 'unknown-builtin-module') return { - url: 'node:unknown-builtin-module' - }; - - return next(specifier); -} diff --git a/test/fixtures/es-module-loaders/loader-with-custom-condition.mjs b/test/fixtures/es-module-loaders/loader-with-custom-condition.mjs deleted file mode 100644 index 90c55fa576bb..000000000000 --- a/test/fixtures/es-module-loaders/loader-with-custom-condition.mjs +++ /dev/null @@ -1,17 +0,0 @@ -import { ok, deepStrictEqual } from 'assert'; - -export async function resolve(specifier, context, defaultResolve) { - ok(Array.isArray(context.conditions), 'loader receives conditions array'); - - deepStrictEqual([...context.conditions].sort(), [ - 'import', - 'module-sync', - 'node', - 'node-addons', - ]); - - return defaultResolve(specifier, { - ...context, - conditions: ['custom-condition', ...context.conditions], - }); -} diff --git a/test/fixtures/es-module-loaders/loader-with-dep.mjs b/test/fixtures/es-module-loaders/loader-with-dep.mjs deleted file mode 100644 index 625341eaed7e..000000000000 --- a/test/fixtures/es-module-loaders/loader-with-dep.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import {createRequire} from '../../common/index.mjs'; - -const require = createRequire(import.meta.url); -const dep = require('./loader-dep.js'); - -export async function resolve(specifier, { parentURL, importAttributes }, defaultResolve) { - return { - url: (await defaultResolve(specifier, { parentURL, importAttributes }, defaultResolve)).url, - format: dep.format - }; -} diff --git a/test/fixtures/es-module-loaders/loader-with-too-many-args.mjs b/test/fixtures/es-module-loaders/loader-with-too-many-args.mjs deleted file mode 100644 index 95f40ec15d20..000000000000 --- a/test/fixtures/es-module-loaders/loader-with-too-many-args.mjs +++ /dev/null @@ -1,7 +0,0 @@ -export async function resolve(specifier, context, next) { - return next(specifier, context, 'resolve-extra-arg'); -} - -export async function load(url, context, next) { - return next(url, context, 'load-extra-arg'); -} diff --git a/test/fixtures/es-module-loaders/loader-worker-spawn.mjs b/test/fixtures/es-module-loaders/loader-worker-spawn.mjs deleted file mode 100644 index 2860d116e647..000000000000 --- a/test/fixtures/es-module-loaders/loader-worker-spawn.mjs +++ /dev/null @@ -1,7 +0,0 @@ -import { Worker } from 'worker_threads'; -import { createRequire } from 'module'; - -const require = createRequire(import.meta.url); -const fixtures = require('../../common/fixtures.js'); - -new Worker(fixtures.path('empty.js')).unref(); diff --git a/test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs b/test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs deleted file mode 100644 index 5d61d81bc31e..000000000000 --- a/test/fixtures/es-module-loaders/missing-dynamic-instantiate-hook.mjs +++ /dev/null @@ -1,17 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier === 'test') { - return { - url: 'file://' - }; - } - return next(specifier); -} - -export function getFormat(url, context, defaultGetFormat) { - if (url === 'file://') { - return { - format: 'dynamic' - } - } - return defaultGetFormat(url, context, defaultGetFormat); -} diff --git a/test/fixtures/es-module-loaders/mock-loader.mjs b/test/fixtures/es-module-loaders/mock-loader.mjs deleted file mode 100644 index 3bb349b53853..000000000000 --- a/test/fixtures/es-module-loaders/mock-loader.mjs +++ /dev/null @@ -1,133 +0,0 @@ -import { receiveMessageOnPort } from 'node:worker_threads'; -const mockedModuleExports = new Map(); -let currentMockVersion = 0; - -// These hooks enable code running on the application thread to -// swap module resolution results for mocking purposes. It uses this instead -// of import.meta so that CommonJS can still use the functionality. -// -// It does so by allowing non-mocked modules to live in normal URL cache -// locations but creates 'mock-facade:' URL cache location for every time a -// module location is mocked. Since a single URL can be mocked multiple -// times but it cannot be removed from the cache, `mock-facade:` URLs have a -// form of mock-facade:$VERSION:$REPLACING_URL with the parameters being URL -// percent encoded every time a module is resolved. So if a module for -// 'file:///app.js' is mocked it might look like -// 'mock-facade:12:file%3A%2F%2F%2Fapp.js'. This encoding is done to prevent -// problems like mocking URLs with special URL characters like '#' or '?' from -// accidentally being picked up as part of the 'mock-facade:' URL containing -// the mocked URL. -// -// NOTE: due to ESM spec, once a specifier has been resolved in a source text -// it cannot be changed. So things like the following DO NOT WORK: -// -// ```mjs -// import mock from 'test-esm-loader-mock'; // See test-esm-loader-mock.mjs -// mock('file:///app.js', {x:1}); -// const namespace1 = await import('file:///app.js'); -// namespace1.x; // 1 -// mock('file:///app.js', {x:2}); -// const namespace2 = await import('file:///app.js'); -// namespace2.x; // STILL 1, because this source text already set the specifier -// // for 'file:///app.js', a different specifier that resolves -// // to that could still get a new namespace though -// assert(namespace1 === namespace2); -// ``` - -/** - * @param param0 message from the application context - */ -function onPreloadPortMessage({ - mockVersion, resolved, exports -}) { - currentMockVersion = mockVersion; - mockedModuleExports.set(resolved, exports); -} - -/** @type {URL['href']} */ -let mainImportURL; -/** @type {MessagePort} */ -let preloadPort; -export async function initialize(data) { - ({ mainImportURL, port: preloadPort } = data); - - data.port.on('message', onPreloadPortMessage); -} - -/** - * Because Node.js internals use a separate MessagePort for cross-thread - * communication, there could be some messages pending that we should handle - * before continuing. - */ -function doDrainPort() { - let msg; - while (msg = receiveMessageOnPort(preloadPort)) { - onPreloadPortMessage(msg.message); - } -} - -// Rewrites node: loading to mock-facade: so that it can be intercepted -export async function resolve(specifier, context, defaultResolve) { - doDrainPort(); - const def = await defaultResolve(specifier, context); - if (context.parentURL?.startsWith('mock-facade:')) { - // Do nothing, let it get the "real" module - } else if (mockedModuleExports.has(def.url)) { - return { - shortCircuit: true, - url: `mock-facade:${currentMockVersion}:${encodeURIComponent(def.url)}` - }; - }; - return { - shortCircuit: true, - url: def.url, - }; -} - -export async function load(url, context, defaultLoad) { - doDrainPort(); - /** - * Mocked fake module, not going to be handled in default way so it - * generates the source text, then short circuits - */ - if (url.startsWith('mock-facade:')) { - const encodedTargetURL = url.slice(url.lastIndexOf(':') + 1); - return { - shortCircuit: true, - source: generateModule(encodedTargetURL), - format: 'module', - }; - } - return defaultLoad(url, context); -} - -/** - * Generate the source code for a mocked module. - * @param {string} encodedTargetURL the module being mocked - * @returns {string} - */ -function generateModule(encodedTargetURL) { - const exports = mockedModuleExports.get( - decodeURIComponent(encodedTargetURL) - ); - let body = [ - `import { mockedModules } from ${JSON.stringify(mainImportURL)};`, - 'export {};', - 'let mapping = {__proto__: null};', - `const mock = mockedModules.get(${JSON.stringify(encodedTargetURL)});`, - ]; - for (const [i, name] of Object.entries(exports)) { - let key = JSON.stringify(name); - body.push(`var _${i} = mock.namespace[${key}];`); - body.push(`Object.defineProperty(mapping, ${key}, { enumerable: true, set(v) {_${i} = v;}, get() {return _${i};} });`); - body.push(`export {_${i} as ${name}};`); - } - body.push(`mock.listeners.push(${ - () => { - for (var k in mapping) { - mapping[k] = mock.namespace[k]; - } - } - });`); - return body.join('\n'); -} diff --git a/test/fixtures/es-module-loaders/mock.mjs b/test/fixtures/es-module-loaders/mock.mjs deleted file mode 100644 index cb167f1d5204..000000000000 --- a/test/fixtures/es-module-loaders/mock.mjs +++ /dev/null @@ -1,70 +0,0 @@ -import { register } from 'node:module'; -import { MessageChannel } from 'node:worker_threads'; - - -const { port1, port2 } = new MessageChannel(); - -register('./mock-loader.mjs', import.meta.url, { - data: { - port: port2, - mainImportURL: import.meta.url, - }, - transferList: [port2], -}); - -/** - * This is the Map that saves *all* the mocked URL -> replacement Module - * mappings - * @type {Map<string, {namespace, listeners}>} - */ -export const mockedModules = new Map(); -let mockVersion = 0; - -/** - * @param {string} resolved an absolute URL HREF string - * @param {object} replacementProperties an object to pick properties from - * to act as a module namespace - * @returns {object} a mutator object that can update the module namespace - * since we can't do something like old Object.observe - */ -export function mock(resolved, replacementProperties) { - const exportNames = Object.keys(replacementProperties); - const namespace = { __proto__: null }; - /** - * @type {Array<(name: string)=>void>} functions to call whenever an - * export name is updated - */ - const listeners = []; - for (const name of exportNames) { - let currentValueForPropertyName = replacementProperties[name]; - Object.defineProperty(namespace, name, { - __proto__: null, - enumerable: true, - get() { - return currentValueForPropertyName; - }, - set(v) { - currentValueForPropertyName = v; - for (const fn of listeners) { - try { - fn(name); - } catch { - /* noop */ - } - } - }, - }); - } - mockedModules.set(encodeURIComponent(resolved), { - namespace, - listeners, - }); - mockVersion++; - // Inform the loader that the `resolved` URL should now use the specific - // `mockVersion` and has export names of `exportNames` - // - // This allows the loader to generate a fake module for that version - // and names the next time it resolves a specifier to equal `resolved` - port1.postMessage({ mockVersion, resolved, exports: exportNames }); - return namespace; -} diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs deleted file mode 100644 index 2bc389cc3e1d..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import assert from 'node:assert'; -console.log('should be output'); - -assert.throws(() => { - import.meta.resolve('never-settle-resolve'); -}, { - code: 'ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED' -}); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/loader.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/loader.mjs deleted file mode 100644 index c180583b4c74..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/loader.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier === 'never-settle-resolve') return new Promise(() => {}); - if (specifier === 'never-settle-load') return { __proto__: null, shortCircuit: true, url: 'never-settle:///' }; - return next(specifier, context); -} - -export function load(url, context, next) { - if (url === 'never-settle:///') return new Promise(() => {}); - return next(url, context); -} diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.cjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.cjs deleted file mode 100644 index cc81affe7d0d..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.cjs +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const neverSettlingDynamicImport = import('never-settle-load'); - -console.log('should be output'); - -neverSettlingDynamicImport.then(() => process.exit(1)); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.mjs deleted file mode 100644 index 3dbf801c7605..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-load.mjs +++ /dev/null @@ -1,5 +0,0 @@ -const neverSettlingDynamicImport = import('never-settle-load'); - -console.log('should be output'); - -await neverSettlingDynamicImport; diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.cjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.cjs deleted file mode 100644 index bf6387560b47..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.cjs +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const neverSettlingDynamicImport = import('never-settle-resolve'); - -console.log('should be output'); - -neverSettlingDynamicImport.then(() => process.exit(1)); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.mjs deleted file mode 100644 index 806a131928c3..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/never-resolve.mjs +++ /dev/null @@ -1,5 +0,0 @@ -const neverSettlingDynamicImport = import('never-settle-resolve'); - -console.log('should be output'); - -await neverSettlingDynamicImport; diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.cjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/race.cjs deleted file mode 100644 index 41884ab9d2e7..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.cjs +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -Promise.race([ - import('never-settle-resolve'), - import('never-settle-load'), - import('node:process'), -]).then(result => console.log(result.default === process)); diff --git a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.mjs b/test/fixtures/es-module-loaders/never-settling-resolve-step/race.mjs deleted file mode 100644 index 8213bbe59d44..000000000000 --- a/test/fixtures/es-module-loaders/never-settling-resolve-step/race.mjs +++ /dev/null @@ -1,7 +0,0 @@ -const result = await Promise.race([ - import('never-settle-resolve'), - import('never-settle-load'), - import('node:process'), -]); - -console.log(result.default === process); diff --git a/test/fixtures/es-module-loaders/node_modules/load/index.mjs b/test/fixtures/es-module-loaders/node_modules/load/index.mjs deleted file mode 100644 index db98e8d9f878..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/load/index.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from '../../loader-load-passthru.mjs' \ No newline at end of file diff --git a/test/fixtures/es-module-loaders/node_modules/load/package.json b/test/fixtures/es-module-loaders/node_modules/load/package.json deleted file mode 100644 index b6629e247888..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/load/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "exports": "./index.mjs" -} diff --git a/test/fixtures/es-module-loaders/node_modules/resolve/index.mjs b/test/fixtures/es-module-loaders/node_modules/resolve/index.mjs deleted file mode 100644 index b3769d961359..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/resolve/index.mjs +++ /dev/null @@ -1 +0,0 @@ -export * from '../../loader-resolve-passthru.mjs' \ No newline at end of file diff --git a/test/fixtures/es-module-loaders/node_modules/resolve/package.json b/test/fixtures/es-module-loaders/node_modules/resolve/package.json deleted file mode 100644 index b6629e247888..000000000000 --- a/test/fixtures/es-module-loaders/node_modules/resolve/package.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "exports": "./index.mjs" -} diff --git a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs b/test/fixtures/es-module-loaders/not-found-assert-loader.mjs deleted file mode 100644 index bf66efbd0810..000000000000 --- a/test/fixtures/es-module-loaders/not-found-assert-loader.mjs +++ /dev/null @@ -1,16 +0,0 @@ -import assert from 'node:assert'; - -// A loader that asserts that the defaultResolve will throw "not found" -// (skipping the top-level main of course, and the built-in ones needed for run-worker). -let mainLoad = true; -export async function resolve(specifier, { importAttributes }, next) { - if (mainLoad || specifier === 'path' || specifier === 'worker_threads') { - mainLoad = false; - return next(specifier); - } - await assert.rejects(next(specifier), { code: 'ERR_MODULE_NOT_FOUND' }); - return { - url: 'node:fs', - importAttributes, - }; -} diff --git a/test/fixtures/es-module-loaders/preset-cjs-source.mjs b/test/fixtures/es-module-loaders/preset-cjs-source.mjs deleted file mode 100644 index 2cfa851a23f8..000000000000 --- a/test/fixtures/es-module-loaders/preset-cjs-source.mjs +++ /dev/null @@ -1,21 +0,0 @@ -export function resolve(specifier, context, next) { - if (specifier.endsWith('/no-such-file.cjs')) { - // Shortcut to avoid ERR_MODULE_NOT_FOUND for non-existing file, but keep the url for the load hook. - return { - shortCircuit: true, - url: specifier, - }; - } - return next(specifier); -} - -export function load(href, context, next) { - if (href.endsWith('.cjs')) { - return { - format: 'commonjs', - shortCircuit: true, - source: 'module.exports = "no .cjs file was read to get this source";', - }; - } - return next(href); -} diff --git a/test/fixtures/es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs b/test/fixtures/es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs deleted file mode 100644 index 580d092ab565..000000000000 --- a/test/fixtures/es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; -import { pathToFileURL } from 'node:url'; -register('./hooks-initialize.mjs', pathToFileURL('./')); diff --git a/test/fixtures/es-module-loaders/register-loader-with-url-parenturl.mjs b/test/fixtures/es-module-loaders/register-loader-with-url-parenturl.mjs deleted file mode 100644 index 1d82d2abc557..000000000000 --- a/test/fixtures/es-module-loaders/register-loader-with-url-parenturl.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import {register} from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -register( - fixtures.fileURL('es-module-loaders/loader-load-foo-or-42.mjs'), - new URL('data:'), -); - -import('node:os').then((result) => { - console.log(JSON.stringify(result)); -}); diff --git a/test/fixtures/es-module-loaders/register-loader.cjs b/test/fixtures/es-module-loaders/register-loader.cjs deleted file mode 100644 index 9e18dfa77e28..000000000000 --- a/test/fixtures/es-module-loaders/register-loader.cjs +++ /dev/null @@ -1,4 +0,0 @@ -const { register } = require('node:module'); -const fixtures = require('../../common/fixtures.js'); - -register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')); diff --git a/test/fixtures/es-module-loaders/register-loader.mjs b/test/fixtures/es-module-loaders/register-loader.mjs deleted file mode 100644 index f3cb2de8da3d..000000000000 --- a/test/fixtures/es-module-loaders/register-loader.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { register } from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -register(fixtures.fileURL('es-module-loaders', 'loader-resolve-passthru.mjs')); diff --git a/test/fixtures/es-module-loaders/register-programmatically-loader-load.mjs b/test/fixtures/es-module-loaders/register-programmatically-loader-load.mjs deleted file mode 100644 index fe22dc7203e9..000000000000 --- a/test/fixtures/es-module-loaders/register-programmatically-loader-load.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import * as fixtures from '../../common/fixtures.mjs'; -import { register } from 'node:module'; - -register(fixtures.fileURL('es-module-loaders', 'loader-load-passthru.mjs')); diff --git a/test/fixtures/es-module-loaders/register-programmatically-loader-resolve.mjs b/test/fixtures/es-module-loaders/register-programmatically-loader-resolve.mjs deleted file mode 100644 index 3ae8841da834..000000000000 --- a/test/fixtures/es-module-loaders/register-programmatically-loader-resolve.mjs +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; - -register('./loader-resolve-passthru.mjs', import.meta.url); diff --git a/test/fixtures/es-module-loaders/string-sources.mjs b/test/fixtures/es-module-loaders/string-sources.mjs deleted file mode 100644 index 39ad32c465fa..000000000000 --- a/test/fixtures/es-module-loaders/string-sources.mjs +++ /dev/null @@ -1,43 +0,0 @@ -const SOURCES = { - __proto__: null, - 'test:Array': ['1', '2'], // both `1,2` and `12` are valid ESM - 'test:ArrayBuffer': new ArrayBuffer(0), - 'test:BigInt64Array': new BigInt64Array(0), - 'test:BigUint64Array': new BigUint64Array(0), - 'test:Float32Array': new Float32Array(0), - 'test:Float64Array': new Float64Array(0), - 'test:Int8Array': new Int8Array(0), - 'test:Int16Array': new Int16Array(0), - 'test:Int32Array': new Int32Array(0), - 'test:null': null, - 'test:Object': {}, - 'test:SharedArrayBuffer': new SharedArrayBuffer(0), - 'test:string': '', - 'test:String': new String(''), - 'test:Uint8Array': new Uint8Array(0), - 'test:Uint8ClampedArray': new Uint8ClampedArray(0), - 'test:Uint16Array': new Uint16Array(0), - 'test:Uint32Array': new Uint32Array(0), - 'test:undefined': undefined, -} -export function resolve(specifier, context, next) { - if (specifier.startsWith('test:')) { - return { - importAttributes: context.importAttributes, - shortCircuit: true, - url: specifier, - }; - } - return next(specifier); -} - -export function load(href, context, next) { - if (href.startsWith('test:')) { - return { - format: 'module', - shortCircuit: true, - source: SOURCES[href], - }; - } - return next(href); -} diff --git a/test/fixtures/es-module-loaders/thenable-load-hook-rejected-no-arguments.mjs b/test/fixtures/es-module-loaders/thenable-load-hook-rejected-no-arguments.mjs deleted file mode 100644 index 5e008edecf7c..000000000000 --- a/test/fixtures/es-module-loaders/thenable-load-hook-rejected-no-arguments.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function load () { - let thenAlreadyAccessed = false; - return { - get then() { - if (thenAlreadyAccessed) throw new Error('must not call'); - thenAlreadyAccessed = true; - return (_, reject) => reject(); - } - }; -} diff --git a/test/fixtures/es-module-loaders/thenable-load-hook-rejected.mjs b/test/fixtures/es-module-loaders/thenable-load-hook-rejected.mjs deleted file mode 100644 index 926f6d0bebd6..000000000000 --- a/test/fixtures/es-module-loaders/thenable-load-hook-rejected.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function load () { - let thenAlreadyAccessed = false; - return { - get then() { - if (thenAlreadyAccessed) throw new Error('must not call'); - thenAlreadyAccessed = true; - return (_, reject) => reject(new Error('must crash the process')); - } - }; -} diff --git a/test/fixtures/es-module-loaders/thenable-load-hook.mjs b/test/fixtures/es-module-loaders/thenable-load-hook.mjs deleted file mode 100644 index 661f6e21ac69..000000000000 --- a/test/fixtures/es-module-loaders/thenable-load-hook.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export function load(url, context, next) { - let thenAlreadyAccessed = false; - return { - get then() { - if (thenAlreadyAccessed) throw new Error('must not call'); - thenAlreadyAccessed = true; - return (resolve) => resolve(next(url, context)); - } - }; -} diff --git a/test/fixtures/es-modules/require-after-failed-import/dep.mjs b/test/fixtures/es-modules/require-after-failed-import/dep.mjs new file mode 100644 index 000000000000..efeee5db16c0 --- /dev/null +++ b/test/fixtures/es-modules/require-after-failed-import/dep.mjs @@ -0,0 +1 @@ +export const value = 1; diff --git a/test/fixtures/es-modules/require-after-failed-import/mismatched.mjs b/test/fixtures/es-modules/require-after-failed-import/mismatched.mjs new file mode 100644 index 000000000000..9e3f57a169a0 --- /dev/null +++ b/test/fixtures/es-modules/require-after-failed-import/mismatched.mjs @@ -0,0 +1,2 @@ +import { missing } from './dep.mjs'; +export { missing }; diff --git a/test/fixtures/es-modules/require-esm-in-cjs-cache/hooks.js b/test/fixtures/es-modules/require-esm-in-cjs-cache/hooks.js deleted file mode 100644 index f33a40fba773..000000000000 --- a/test/fixtures/es-modules/require-esm-in-cjs-cache/hooks.js +++ /dev/null @@ -1,12 +0,0 @@ -import { readFileSync } from 'node:fs'; -import { fileURLToPath } from 'node:url'; - -export async function load(url, context, nextLoad) { - const result = await nextLoad(url, context); - - if (result.format === 'commonjs' && !result.source) { - result.source = readFileSync(fileURLToPath(url), 'utf8'); - } - - return result; -} diff --git a/test/fixtures/es-modules/require-esm-in-cjs-cache/instrument.js b/test/fixtures/es-modules/require-esm-in-cjs-cache/instrument.js deleted file mode 100644 index 1c99b7e9c759..000000000000 --- a/test/fixtures/es-modules/require-esm-in-cjs-cache/instrument.js +++ /dev/null @@ -1,3 +0,0 @@ -import * as mod from 'node:module'; - -mod.register(new URL('hooks.js', import.meta.url).toString()); diff --git a/test/fixtures/es-modules/require-esm-throws-with-loaders.js b/test/fixtures/es-modules/require-esm-throws-with-loaders.js deleted file mode 100644 index 79c5cf96c141..000000000000 --- a/test/fixtures/es-modules/require-esm-throws-with-loaders.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; -const { readFile, __fromLoader } = require('fs'); -const assert = require('assert'); - -assert.throws(() => require('./test-esm-ok.mjs'), { code: 'ERR_REQUIRE_ESM' }); - -assert(readFile); -assert(__fromLoader); diff --git a/test/fixtures/es-modules/worker-condition/hooks-worker.mjs b/test/fixtures/es-modules/worker-condition/hooks-worker.mjs deleted file mode 100644 index ee9cd45bd6c5..000000000000 --- a/test/fixtures/es-modules/worker-condition/hooks-worker.mjs +++ /dev/null @@ -1,6 +0,0 @@ -import { register } from 'node:module'; - -register('./hooks.mjs', import.meta.url); - -const { default: value } = await import('pkg'); -postMessage(value); diff --git a/test/fixtures/es-modules/worker-condition/hooks.mjs b/test/fixtures/es-modules/worker-condition/hooks.mjs deleted file mode 100644 index 8505bafc98db..000000000000 --- a/test/fixtures/es-modules/worker-condition/hooks.mjs +++ /dev/null @@ -1,6 +0,0 @@ -export async function resolve(specifier, context, nextResolve) { - if (specifier === 'pkg' && !context.conditions.includes('worker')) { - throw new Error(`missing worker condition: ${context.conditions}`); - } - return nextResolve(specifier, context); -} diff --git a/test/fixtures/loader-is-internal-thread.js b/test/fixtures/loader-is-internal-thread.js deleted file mode 100644 index d97328bc2075..000000000000 --- a/test/fixtures/loader-is-internal-thread.js +++ /dev/null @@ -1,3 +0,0 @@ -const { isInternalThread } = require('node:worker_threads'); - -console.log(`isInternalThread: ${isInternalThread}`); \ No newline at end of file diff --git a/test/fixtures/module-hooks/get-stats.js b/test/fixtures/module-hooks/get-stats.js deleted file mode 100644 index fa5869a455ce..000000000000 --- a/test/fixtures/module-hooks/get-stats.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -const path = require('path'); - -// Adapted from https://github.com/watson/module-details-from-path/blob/master/index.js -// used by require-in-the-middle to check the logic is still compatible with our new hooks. -exports.getStats = function getStats(filepath) { - const segments = filepath.split(path.sep); - const index = segments.lastIndexOf('node_modules'); - if (index === -1) return {}; - if (!segments[index + 1]) return {}; - const scoped = segments[index + 1][0] === '@'; - const name = scoped ? segments[index + 1] + '/' + segments[index + 2] : segments[index + 1]; - const offset = scoped ? 3 : 2; - return { - name: name, - basedir: segments.slice(0, index + offset).join(path.sep), - path: segments.slice(index + offset).join(path.sep) - } -}; diff --git a/test/fixtures/module-hooks/logger-async-hooks.mjs b/test/fixtures/module-hooks/logger-async-hooks.mjs deleted file mode 100644 index f26d0ce2ae3e..000000000000 --- a/test/fixtures/module-hooks/logger-async-hooks.mjs +++ /dev/null @@ -1,19 +0,0 @@ -import fs from 'node:fs'; - -export async function resolve(specifier, context, nextResolve) { - fs.writeSync(1, `resolve ${specifier} from ${context.parentURL}\n`); - const result = await nextResolve(specifier, context); - result.shortCircuit = true; - return result; -} - -export async function load(url, context, nextLoad) { - fs.writeSync(1, `load ${url}\n`); - const result = await nextLoad(url, context); - result.shortCircuit = true; - // Handle the async loader hook quirk where source can be nullish for CommonJS. - // If this returns that nullish value verbatim, the `require` in imported - // CJS won't get the hook invoked. - result.source ??= fs.readFileSync(new URL(url), 'utf8'); - return result; -} diff --git a/test/fixtures/module-hooks/register-loader-in-sequence.mjs b/test/fixtures/module-hooks/register-loader-in-sequence.mjs deleted file mode 100644 index c129fcfc1809..000000000000 --- a/test/fixtures/module-hooks/register-loader-in-sequence.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import {register} from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -console.log('result 1', register( - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs') -)); -console.log('result 2', register( - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs') -)); - -await import('node:os'); diff --git a/test/fixtures/module-hooks/register-loader-initialize-never-settling.mjs b/test/fixtures/module-hooks/register-loader-initialize-never-settling.mjs deleted file mode 100644 index 13091effa970..000000000000 --- a/test/fixtures/module-hooks/register-loader-initialize-never-settling.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import {register} from 'node:module'; -import fixtures from '../../common/fixtures.js'; - -try { - register(fixtures.fileURL('es-module-loaders/loader-initialize-never-settling.mjs')); -} catch (e) { - console.log('caught', e.code); -} diff --git a/test/fixtures/module-hooks/register-loader-with-cjs.cjs b/test/fixtures/module-hooks/register-loader-with-cjs.cjs deleted file mode 100644 index 2cd6c666bd14..000000000000 --- a/test/fixtures/module-hooks/register-loader-with-cjs.cjs +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; -const {register} = require('node:module'); -const fixtures = require('../../common/fixtures.js'); - -register( - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'), -); -register( - fixtures.fileURL('es-module-loaders/loader-load-foo-or-42.mjs'), -); - -import('node:os').then((result) => { - console.log(JSON.stringify(result)); -}); diff --git a/test/fixtures/module-hooks/register-loader-with-ports.mjs b/test/fixtures/module-hooks/register-loader-with-ports.mjs deleted file mode 100644 index 45e125f96a20..000000000000 --- a/test/fixtures/module-hooks/register-loader-with-ports.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import {MessageChannel} from 'node:worker_threads'; -import {register} from 'node:module'; -import {once} from 'node:events'; -import fixtures from '../../common/fixtures.js'; - -const {port1, port2} = new MessageChannel(); -port1.on('message', (msg) => { - console.log('message', msg); -}); -const result = register( - fixtures.fileURL('es-module-loaders/hooks-initialize-port.mjs'), - {data: port2, transferList: [port2]}, -); -console.log('register', result); - -const timeout = setTimeout(() => {}, 2**31 - 1); // to keep the process alive. -await Promise.all([ - once(port1, 'message').then(() => once(port1, 'message')), - import('node:os'), -]); -clearTimeout(timeout); -port1.close(); diff --git a/test/fixtures/module-hooks/require-esm-in-hooks-thread/dep.mjs b/test/fixtures/module-hooks/require-esm-in-hooks-thread/dep.mjs deleted file mode 100644 index 3d34ee667697..000000000000 --- a/test/fixtures/module-hooks/require-esm-in-hooks-thread/dep.mjs +++ /dev/null @@ -1 +0,0 @@ -export const value = 'dep:'; diff --git a/test/fixtures/module-hooks/require-esm-in-hooks-thread/esm-with-import.mjs b/test/fixtures/module-hooks/require-esm-in-hooks-thread/esm-with-import.mjs deleted file mode 100644 index 1aad2b7a98c1..000000000000 --- a/test/fixtures/module-hooks/require-esm-in-hooks-thread/esm-with-import.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { sep } from 'node:path'; -import { value } from './dep.mjs'; - -export const result = `${value}${typeof sep}`; diff --git a/test/fixtures/module-hooks/require-esm-in-hooks-thread/hooks.mjs b/test/fixtures/module-hooks/require-esm-in-hooks-thread/hooks.mjs deleted file mode 100644 index b80b4ef959b7..000000000000 --- a/test/fixtures/module-hooks/require-esm-in-hooks-thread/hooks.mjs +++ /dev/null @@ -1,9 +0,0 @@ -// Loaded on the module.register() hooks thread. It defines no hooks: require()-ing -// an ES module with imports while the hooks module is being loaded is enough. -import { createRequire } from 'node:module'; - -const require = createRequire(import.meta.url); -const { result } = require('./esm-with-import.mjs'); -if (result !== 'dep:string') { - throw new Error(`Unexpected result: ${result}`); -} diff --git a/test/fixtures/module-hooks/require-resolve-paths-caller.js b/test/fixtures/module-hooks/require-resolve-paths-caller.js deleted file mode 100644 index f18b1f377735..000000000000 --- a/test/fixtures/module-hooks/require-resolve-paths-caller.js +++ /dev/null @@ -1,13 +0,0 @@ -// Fixture CJS file that calls require.resolve with the paths option. -'use strict'; -const path = require('path'); -const fixturesDir = path.resolve(__dirname, '..', '..'); -const nodeModules = path.join(fixturesDir, 'node_modules'); - -// Use the paths option to resolve 'bar' from the fixtures node_modules. -const resolved = require.resolve('bar', { paths: [fixturesDir] }); -const expected = path.join(nodeModules, 'bar.js'); -if (resolved !== expected) { - throw new Error(`Expected ${expected}, got ${resolved}`); -} -module.exports = { resolved }; diff --git a/test/fixtures/module-hooks/sync-and-async/app.js b/test/fixtures/module-hooks/sync-and-async/app.js deleted file mode 100644 index c14477b70f71..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/app.js +++ /dev/null @@ -1,2 +0,0 @@ -console.log('Hello world'); - diff --git a/test/fixtures/module-hooks/sync-and-async/async-customize-loader.js b/test/fixtures/module-hooks/sync-and-async/async-customize-loader.js deleted file mode 100644 index ac961f0b97a3..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-customize-loader.js +++ /dev/null @@ -1,10 +0,0 @@ -export async function load(url, context, nextLoad) { - if (url.endsWith('app.js')) { - return { - shortCircuit: true, - format: 'module', - source: 'console.log("customized by async hook");', - }; - } - return nextLoad(url, context); -} diff --git a/test/fixtures/module-hooks/sync-and-async/async-customize.js b/test/fixtures/module-hooks/sync-and-async/async-customize.js deleted file mode 100644 index 78bf7fc5564b..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-customize.js +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; - -register(new URL('async-customize-loader.js', import.meta.url)); diff --git a/test/fixtures/module-hooks/sync-and-async/async-forward-loader.js b/test/fixtures/module-hooks/sync-and-async/async-forward-loader.js deleted file mode 100644 index 4a1ced7e8dbf..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-forward-loader.js +++ /dev/null @@ -1,3 +0,0 @@ -export async function load(url, context, nextLoad) { - return nextLoad(url, context); -} diff --git a/test/fixtures/module-hooks/sync-and-async/async-forward.js b/test/fixtures/module-hooks/sync-and-async/async-forward.js deleted file mode 100644 index fd10aa6df898..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/async-forward.js +++ /dev/null @@ -1,3 +0,0 @@ -import { register } from 'node:module'; - -register(new URL('async-forward-loader.js', import.meta.url)); diff --git a/test/fixtures/module-hooks/sync-and-async/sync-customize.js b/test/fixtures/module-hooks/sync-and-async/sync-customize.js deleted file mode 100644 index 90d63db1c7cc..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/sync-customize.js +++ /dev/null @@ -1,14 +0,0 @@ -import { registerHooks } from 'node:module'; - -registerHooks({ - load(url, context, nextLoad) { - if (url.endsWith('app.js')) { - return { - shortCircuit: true, - format: 'module', - source: 'console.log("customized by sync hook")', - }; - } - return nextLoad(url, context); - }, -}); diff --git a/test/fixtures/module-hooks/sync-and-async/sync-forward.js b/test/fixtures/module-hooks/sync-and-async/sync-forward.js deleted file mode 100644 index 2688a240dc88..000000000000 --- a/test/fixtures/module-hooks/sync-and-async/sync-forward.js +++ /dev/null @@ -1,7 +0,0 @@ -import { registerHooks } from 'node:module'; - -registerHooks({ - load(url, context, nextLoad) { - return nextLoad(url, context); - }, -}); diff --git a/test/fixtures/permission/fs-read.js b/test/fixtures/permission/fs-read.js index 2feb64d021b5..1446dd7bc579 100644 --- a/test/fixtures/permission/fs-read.js +++ b/test/fixtures/permission/fs-read.js @@ -721,6 +721,34 @@ const regularFile = __filename; }); } +// fs.readlink +{ + fs.readlink(blockedFile, common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemRead', + resource: path.toNamespacedPath(blockedFile), + })); + fs.readlink(bufferBlockedFile, common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemRead', + resource: path.toNamespacedPath(blockedFile), + })); + assert.throws(() => { + fs.readlinkSync(blockedFile); + }, common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemRead', + resource: path.toNamespacedPath(blockedFile), + })); + assert.rejects(async () => { + await fsPromises.readlink(blockedFile); + }, common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemRead', + resource: path.toNamespacedPath(blockedFile), + })).then(common.mustCall()); +} + // fs.realpath (JS implementation, walks the path with lstat) { assert.throws(() => { diff --git a/test/fixtures/permission/fs-write.js b/test/fixtures/permission/fs-write.js index 7a9963e17d9e..4d226329e707 100644 --- a/test/fixtures/permission/fs-write.js +++ b/test/fixtures/permission/fs-write.js @@ -115,62 +115,59 @@ const relativeProtectedFolder = process.env.RELATIVEBLOCKEDFOLDER; // fs.utimes { - assert.throws(() => { - fs.utimes(blockedFile, new Date(), new Date(), () => {}); - }, { + fs.utimes(blockedFile, new Date(), new Date(), common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(blockedFile), - }); - assert.throws(() => { - fs.utimes(bufferBlockedFile, new Date(), new Date(), () => {}); - }, { + })); + fs.utimes(bufferBlockedFile, new Date(), new Date(), common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(blockedFile), - }); - assert.throws(() => { - fs.utimes(blockedFileURL, new Date(), new Date(), () => {}); - }, { + })); + fs.utimes(blockedFileURL, new Date(), new Date(), common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(blockedFile), - }); - assert.throws(() => { - fs.utimes(relativeProtectedFile, new Date(), new Date(), () => {}); - }, { + })); + fs.utimes(relativeProtectedFile, new Date(), new Date(), common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(relativeProtectedFile), - }); - + })); + fs.utimes(path.join(blockedFolder, 'anyfile'), new Date(), new Date(), common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + resource: path.toNamespacedPath(path.join(blockedFolder, 'anyfile')), + })); assert.throws(() => { - fs.utimes(path.join(blockedFolder, 'anyfile'), new Date(), new Date(), () => {}); + fs.utimesSync(blockedFile, new Date(), new Date()); }, { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', - resource: path.toNamespacedPath(path.join(blockedFolder, 'anyfile')), + resource: path.toNamespacedPath(blockedFile), }); } // fs.lutimes { - assert.throws(() => { - fs.lutimes(blockedFile, new Date(), new Date(), () => {}); - },{ + fs.lutimes(blockedFile, new Date(), new Date(), common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(blockedFile), - }); - assert.throws(() => { - fs.lutimes(bufferBlockedFile, new Date(), new Date(), () => {}); - },{ + })); + fs.lutimes(bufferBlockedFile, new Date(), new Date(), common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(blockedFile), - }); + })); + fs.lutimes(blockedFileURL, new Date(), new Date(), common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + resource: path.toNamespacedPath(blockedFile), + })); assert.throws(() => { - fs.lutimes(blockedFileURL, new Date(), new Date(), () => {}); + fs.lutimesSync(blockedFile, new Date(), new Date()); }, { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', @@ -180,24 +177,46 @@ const relativeProtectedFolder = process.env.RELATIVEBLOCKEDFOLDER; // fs.mkdir { + fs.mkdir(path.join(blockedFolder, 'any-folder'), common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + resource: path.toNamespacedPath(path.join(blockedFolder, 'any-folder')), + })); + fs.mkdir(path.join(relativeProtectedFolder, 'any-folder'), common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + resource: path.toNamespacedPath(path.join(relativeProtectedFolder, 'any-folder')), + })); assert.throws(() => { - fs.mkdir(path.join(blockedFolder, 'any-folder'), (err) => { - assert.ifError(err); - }); - },{ + fs.mkdirSync(path.join(blockedFolder, 'any-folder')); + }, { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', resource: path.toNamespacedPath(path.join(blockedFolder, 'any-folder')), }); +} + +// fs.rmdir +{ + fs.rmdir(blockedFolder, common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + resource: path.toNamespacedPath(blockedFolder), + })); assert.throws(() => { - fs.mkdir(path.join(relativeProtectedFolder, 'any-folder'), (err) => { - assert.ifError(err); - }); - },{ + fs.rmdirSync(blockedFolder); + }, { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', - resource: path.toNamespacedPath(path.join(relativeProtectedFolder, 'any-folder')), + resource: path.toNamespacedPath(blockedFolder), }); + assert.rejects(async () => { + await fsPromises.rmdir(blockedFolder); + }, { + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + resource: path.toNamespacedPath(blockedFolder), + }).then(common.mustCall()); } // fs.mkdtemp @@ -401,20 +420,20 @@ const relativeProtectedFolder = process.env.RELATIVEBLOCKEDFOLDER; // fs.chmod { - assert.throws(() => { - fs.chmod(blockedFile, 0o755, common.mustNotCall()); - }, { + fs.chmod(blockedFile, 0o755, common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', - }); - assert.throws(() => { - fs.chmod(bufferBlockedFile, 0o755, common.mustNotCall()); - }, { + })); + fs.chmod(bufferBlockedFile, 0o755, common.expectsError({ code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', - }); + })); + fs.chmod(blockedFileURL, 0o755, common.expectsError({ + code: 'ERR_ACCESS_DENIED', + permission: 'FileSystemWrite', + })); assert.throws(() => { - fs.chmod(blockedFileURL, 0o755, common.mustNotCall()); + fs.chmodSync(blockedFile, 0o755); }, { code: 'ERR_ACCESS_DENIED', permission: 'FileSystemWrite', diff --git a/test/fixtures/print-delayed.js b/test/fixtures/print-delayed.js deleted file mode 100644 index 42eb45615b2a..000000000000 --- a/test/fixtures/print-delayed.js +++ /dev/null @@ -1,3 +0,0 @@ -setTimeout(() => { - console.log('delayed'); -}, 100); diff --git a/test/fixtures/process-timeout/blocked-worker-at-exit.js b/test/fixtures/process-timeout/blocked-worker-at-exit.js index 5ff21b423f62..febad9d0c58f 100644 --- a/test/fixtures/process-timeout/blocked-worker-at-exit.js +++ b/test/fixtures/process-timeout/blocked-worker-at-exit.js @@ -1,8 +1,8 @@ 'use strict'; // Lets the event loop stop while a Worker is blocked in a synchronous native -// call, so that exiting the process waits for the Worker. The first argument is -// a path at which a file is created once the event loop has stopped. +// call, so that exiting the process waits for the Worker. The child process +// creates a file named after the first argument once it has started. const fs = require('fs'); const path = require('path'); const { Worker } = require('worker_threads'); @@ -26,5 +26,3 @@ const interval = setInterval(() => { worker.unref(); } }, 10); - -process.on('exit', () => fs.writeFileSync(marker, '')); diff --git a/test/fixtures/process-timeout/blocked-worker-at-process-exit.js b/test/fixtures/process-timeout/blocked-worker-at-process-exit.js index b7e853e62f6b..05afe71fa2e6 100644 --- a/test/fixtures/process-timeout/blocked-worker-at-process-exit.js +++ b/test/fixtures/process-timeout/blocked-worker-at-process-exit.js @@ -1,7 +1,7 @@ 'use strict'; // Exits the process while a Worker is blocked in a synchronous native call, so -// that exiting the process waits for the Worker. The first argument is a path -// at which a file is created once the process is exiting. The second argument +// that exiting the process waits for the Worker. The child process creates a +// file named after the first argument once it has started. The second argument // is how the process exits: 'exit' calls process.exit(), 'throw' throws an // uncaught exception, and 'reject' leaves a promise rejection unhandled. const fs = require('fs'); @@ -27,5 +27,3 @@ const interval = setInterval(() => { if (mode === 'reject') return Promise.reject(new Error('boom')); process.exit(0); }, 10); - -process.on('exit', () => fs.writeFileSync(marker, '')); diff --git a/test/fixtures/sea/vfs-sourcemap/original.js b/test/fixtures/sea/vfs-sourcemap/original.js new file mode 100644 index 000000000000..74175b852670 --- /dev/null +++ b/test/fixtures/sea/vfs-sourcemap/original.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); +const { findSourceMap } = require('module'); + +const sm = findSourceMap(__filename); +assert.ok(sm, 'source map should be loaded from the SEA VFS'); +console.log('source map loaded from the SEA VFS:', sm.payload.sources[0]); + +function boom() { + throw new Error('boom from the original source'); +} + +boom(); diff --git a/test/fixtures/sea/vfs-sourcemap/sea-config.json b/test/fixtures/sea/vfs-sourcemap/sea-config.json new file mode 100644 index 000000000000..bf4c11610fb4 --- /dev/null +++ b/test/fixtures/sea/vfs-sourcemap/sea-config.json @@ -0,0 +1,10 @@ +{ + "main": "sea.js", + "output": "sea-prep.blob", + "useVfs": true, + "execArgv": ["--enable-source-maps"], + "assets": { + "sea.js.map": "sea.js.map", + "original.js": "original.js" + } +} diff --git a/test/fixtures/sea/vfs-sourcemap/sea.js b/test/fixtures/sea/vfs-sourcemap/sea.js new file mode 100644 index 000000000000..35651fc16252 --- /dev/null +++ b/test/fixtures/sea/vfs-sourcemap/sea.js @@ -0,0 +1,15 @@ +'use strict'; + +const assert = require('assert'); +const { findSourceMap } = require('module'); + +const sm = findSourceMap(__filename); +assert.ok(sm, 'source map should be loaded from the SEA VFS'); +console.log('source map loaded from the SEA VFS:', sm.payload.sources[0]); + +function boom() { + throw new Error('boom from the original source'); +} + +boom(); +//# sourceMappingURL=sea.js.map diff --git a/test/fixtures/sea/vfs-sourcemap/sea.js.map b/test/fixtures/sea/vfs-sourcemap/sea.js.map new file mode 100644 index 000000000000..5c6e3d6aaa85 --- /dev/null +++ b/test/fixtures/sea/vfs-sourcemap/sea.js.map @@ -0,0 +1,12 @@ +{ + "version": 3, + "file": "sea.js", + "sources": [ + "original.js" + ], + "names": [ + "boom" + ], + "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACI;FACJ;AACA;AACA;AACA", + "sourceRoot": "" +} \ No newline at end of file diff --git a/test/fixtures/sea/vfs-zip-sourcemap/original.js b/test/fixtures/sea/vfs-zip-sourcemap/original.js new file mode 100644 index 000000000000..74175b852670 --- /dev/null +++ b/test/fixtures/sea/vfs-zip-sourcemap/original.js @@ -0,0 +1,14 @@ +'use strict'; + +const assert = require('assert'); +const { findSourceMap } = require('module'); + +const sm = findSourceMap(__filename); +assert.ok(sm, 'source map should be loaded from the SEA VFS'); +console.log('source map loaded from the SEA VFS:', sm.payload.sources[0]); + +function boom() { + throw new Error('boom from the original source'); +} + +boom(); diff --git a/test/fixtures/sea/vfs-zip-sourcemap/sea-config.json b/test/fixtures/sea/vfs-zip-sourcemap/sea-config.json new file mode 100644 index 000000000000..d42121169ef3 --- /dev/null +++ b/test/fixtures/sea/vfs-zip-sourcemap/sea-config.json @@ -0,0 +1,7 @@ +{ + "main": "sea.js", + "output": "sea-prep.blob", + "useVfs": true, + "vfsArchive": "assets.zip", + "execArgv": ["--enable-source-maps"] +} diff --git a/test/fixtures/sea/vfs-zip-sourcemap/sea.js b/test/fixtures/sea/vfs-zip-sourcemap/sea.js new file mode 100644 index 000000000000..35651fc16252 --- /dev/null +++ b/test/fixtures/sea/vfs-zip-sourcemap/sea.js @@ -0,0 +1,15 @@ +'use strict'; + +const assert = require('assert'); +const { findSourceMap } = require('module'); + +const sm = findSourceMap(__filename); +assert.ok(sm, 'source map should be loaded from the SEA VFS'); +console.log('source map loaded from the SEA VFS:', sm.payload.sources[0]); + +function boom() { + throw new Error('boom from the original source'); +} + +boom(); +//# sourceMappingURL=sea.js.map diff --git a/test/fixtures/sea/vfs-zip-sourcemap/sea.js.map b/test/fixtures/sea/vfs-zip-sourcemap/sea.js.map new file mode 100644 index 000000000000..5c6e3d6aaa85 --- /dev/null +++ b/test/fixtures/sea/vfs-zip-sourcemap/sea.js.map @@ -0,0 +1,12 @@ +{ + "version": 3, + "file": "sea.js", + "sources": [ + "original.js" + ], + "names": [ + "boom" + ], + "mappings": "AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;EACI;FACJ;AACA;AACA;AACA", + "sourceRoot": "" +} \ No newline at end of file diff --git a/test/fixtures/test-runner/junit-colored-diff.js b/test/fixtures/test-runner/junit-colored-diff.js new file mode 100644 index 000000000000..6119f6f41cdd --- /dev/null +++ b/test/fixtures/test-runner/junit-colored-diff.js @@ -0,0 +1,5 @@ +'use strict'; +const assert = require('node:assert'); +const { test } = require('node:test'); + +test('diff', () => assert.deepStrictEqual({ a: 1 }, { a: 2 })); diff --git a/test/fixtures/test-runner/output/describe_it.snapshot b/test/fixtures/test-runner/output/describe_it.snapshot index 772a90d98918..2e5fe0d1ee28 100644 --- a/test/fixtures/test-runner/output/describe_it.snapshot +++ b/test/fixtures/test-runner/output/describe_it.snapshot @@ -230,7 +230,6 @@ ok 27 - immediate resolve pass <node-internal-frames> new Promise (<anonymous>) <node-internal-frames> - Array.map (<anonymous>) ... # Subtest: mixing describe/it and test should work ok 2 - mixing describe/it and test should work @@ -516,7 +515,6 @@ not ok 56 - custom inspect symbol that throws fail <node-internal-frames> new Promise (<anonymous>) <node-internal-frames> - Array.map (<anonymous>) ... # Subtest: sync throw fails at second not ok 2 - sync throw fails at second @@ -530,8 +528,6 @@ not ok 56 - custom inspect symbol that throws fail stack: |- TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/describe_it.js:311:11) <node-internal-frames> - async Promise.all (index 0) - <node-internal-frames> ... 1..2 not ok 57 - subtest sync throw fails @@ -605,8 +601,6 @@ not ok 59 - describe async throw fails failureType: 'testTimeoutFailure' error: 'test timed out after 5ms' code: 'ERR_TEST_FAILURE' - stack: |- - async Promise.all (index 0) ... # Subtest: timed out callback test not ok 2 - timed out callback test diff --git a/test/fixtures/test-runner/output/hooks.snapshot b/test/fixtures/test-runner/output/hooks.snapshot index 4a576028d9b9..d0cc80b1f29c 100644 --- a/test/fixtures/test-runner/output/hooks.snapshot +++ b/test/fixtures/test-runner/output/hooks.snapshot @@ -157,7 +157,6 @@ not ok 6 - after throws - no subtests stack: |- TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/hooks.js:94:28) <node-internal-frames> - async Promise.all (index 0) ... 1..2 not ok 7 - beforeEach throws @@ -182,8 +181,6 @@ not ok 7 - beforeEach throws stack: |- TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/hooks.js:100:27) <node-internal-frames> - async Promise.all (index 0) - <node-internal-frames> ... # Subtest: 2 not ok 2 - 2 @@ -223,7 +220,6 @@ not ok 8 - afterEach throws <node-internal-frames> new Promise (<anonymous>) <node-internal-frames> - Array.map (<anonymous>) ... # Subtest: 2 ok 2 - 2 @@ -256,7 +252,6 @@ not ok 9 - afterEach when test fails <node-internal-frames> new Promise (<anonymous>) <node-internal-frames> - Array.map (<anonymous>) ... # Subtest: 2 not ok 2 - 2 diff --git a/test/fixtures/test-runner/output/hooks_spec_reporter.snapshot b/test/fixtures/test-runner/output/hooks_spec_reporter.snapshot index e2ad150bb5f7..f229f1c17600 100644 --- a/test/fixtures/test-runner/output/hooks_spec_reporter.snapshot +++ b/test/fixtures/test-runner/output/hooks_spec_reporter.snapshot @@ -143,15 +143,12 @@ test at test/fixtures/test-runner/output/hooks.js:96:3 Error: beforeEach at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/hooks.js:94:28) at <node-internal-frames> - at async Promise.all (index 0) test at test/fixtures/test-runner/output/hooks.js:101:3 ✖ 1 (*ms) Error: afterEach at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/hooks.js:100:27) at <node-internal-frames> - at async Promise.all (index 0) - at <node-internal-frames> test at test/fixtures/test-runner/output/hooks.js:102:3 ✖ 2 (*ms) @@ -166,7 +163,6 @@ test at test/fixtures/test-runner/output/hooks.js:107:3 at <node-internal-frames> at new Promise (<anonymous>) at <node-internal-frames> - at Array.map (<anonymous>) test at test/fixtures/test-runner/output/hooks.js:113:3 ✖ 1 (*ms) @@ -175,7 +171,6 @@ test at test/fixtures/test-runner/output/hooks.js:113:3 at <node-internal-frames> at new Promise (<anonymous>) at <node-internal-frames> - at Array.map (<anonymous>) test at test/fixtures/test-runner/output/hooks.js:114:3 ✖ 2 (*ms) diff --git a/test/fixtures/test-runner/output/junit_empty_diagnostic.snapshot b/test/fixtures/test-runner/output/junit_empty_diagnostic.snapshot index 666c5c3523a7..7944fdf3071a 100644 --- a/test/fixtures/test-runner/output/junit_empty_diagnostic.snapshot +++ b/test/fixtures/test-runner/output/junit_empty_diagnostic.snapshot @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="utf-8"?> <testsuites> - <testcase name="failing" time="*" classname="test" file="*" failure="error"> + <testcase name="failing" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="error"> [Error [ERR_TEST_FAILURE]: error] { code: 'ERR_TEST_FAILURE', diff --git a/test/fixtures/test-runner/output/junit_reporter.snapshot b/test/fixtures/test-runner/output/junit_reporter.snapshot index 3ff11ba24154..fd4f219a721b 100644 --- a/test/fixtures/test-runner/output/junit_reporter.snapshot +++ b/test/fixtures/test-runner/output/junit_reporter.snapshot @@ -16,7 +16,7 @@ <testcase name="sync pass todo with message" time="*" classname="test" file="*"> <skipped type="todo" message="this is a passing todo"/> </testcase> - <testcase name="sync fail todo" time="*" classname="test" file="*" failure="thrown from sync fail todo"> + <testcase name="sync fail todo" time="*" classname="test" file="*"> <skipped type="todo" message="true"/> <failure type="testCodeFailure" message="thrown from sync fail todo"> [Error [ERR_TEST_FAILURE]: thrown from sync fail todo] { @@ -28,7 +28,7 @@ } </failure> </testcase> - <testcase name="sync fail todo with message" time="*" classname="test" file="*" failure="thrown from sync fail todo with message"> + <testcase name="sync fail todo with message" time="*" classname="test" file="*"> <skipped type="todo" message="this is a failing todo"/> <failure type="testCodeFailure" message="thrown from sync fail todo with message"> [Error [ERR_TEST_FAILURE]: thrown from sync fail todo with message] { @@ -48,7 +48,7 @@ </testcase> <testcase name="sync pass" time="*" classname="test" file="*"/> <!-- this test should pass --> - <testcase name="sync throw fail" time="*" classname="test" file="*" failure="thrown from sync throw fail"> + <testcase name="sync throw fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="thrown from sync throw fail"> [Error [ERR_TEST_FAILURE]: thrown from sync throw fail] { code: 'ERR_TEST_FAILURE', @@ -63,7 +63,7 @@ <skipped type="skipped" message="true"/> </testcase> <testcase name="async pass" time="*" classname="test" file="*"/> - <testcase name="async throw fail" time="*" classname="test" file="*" failure="thrown from async throw fail"> + <testcase name="async throw fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="thrown from async throw fail"> [Error [ERR_TEST_FAILURE]: thrown from async throw fail] { code: 'ERR_TEST_FAILURE', @@ -74,7 +74,7 @@ } </failure> </testcase> - <testcase name="async skip fail" time="*" classname="test" file="*" failure="thrown from async throw fail"> + <testcase name="async skip fail" time="*" classname="test" file="*"> <skipped type="skipped" message="true"/> <failure type="testCodeFailure" message="thrown from async throw fail"> [Error [ERR_TEST_FAILURE]: thrown from async throw fail] { @@ -86,7 +86,7 @@ } </failure> </testcase> - <testcase name="async assertion fail" time="*" classname="test" file="*" failure="Expected values to be strictly equal: true !== false "> + <testcase name="async assertion fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="Expected values to be strictly equal: true !== false"> [Error [ERR_TEST_FAILURE]: Expected values to be strictly equal: @@ -112,7 +112,7 @@ true !== false </failure> </testcase> <testcase name="resolve pass" time="*" classname="test" file="*"/> - <testcase name="reject fail" time="*" classname="test" file="*" failure="rejected from reject fail"> + <testcase name="reject fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="rejected from reject fail"> [Error [ERR_TEST_FAILURE]: rejected from reject fail] { code: 'ERR_TEST_FAILURE', @@ -129,7 +129,7 @@ true !== false <testcase name="immediate reject - passes but warns" time="*" classname="test" file="*"/> <testcase name="immediate resolve pass" time="*" classname="test" file="*"/> <testsuite name="subtest sync throw fail" time="*" disabled="0" errors="0" tests="1" failures="1" skipped="0" timestamp="*" hostname="HOSTNAME"> - <testcase name="+sync throw fail" time="*" classname="subtest sync throw fail" file="*" failure="thrown from subtest sync throw fail"> + <testcase name="+sync throw fail" time="*" classname="subtest sync throw fail" file="*"> <failure type="testCodeFailure" message="thrown from subtest sync throw fail"> Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:125:11) { @@ -145,7 +145,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail </testcase> <!-- this subtest should make its parent test fail --> </testsuite> - <testcase name="sync throw non-error fail" time="*" classname="test" file="*" failure="Symbol(thrown symbol from sync throw non-error fail)"> + <testcase name="sync throw non-error fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="Symbol(thrown symbol from sync throw non-error fail)"> [Error [ERR_TEST_FAILURE]: Symbol(thrown symbol from sync throw non-error fail)] { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: Symbol(thrown symbol from sync throw non-error fail) } </failure> @@ -169,7 +169,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail <testcase name="sync skip option with message" time="*" classname="test" file="*"> <skipped type="skipped" message="this is skipped"/> </testcase> - <testcase name="sync skip option is false fail" time="*" classname="test" file="*" failure="this should be executed"> + <testcase name="sync skip option is false fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="this should be executed"> [Error [ERR_TEST_FAILURE]: this should be executed] { code: 'ERR_TEST_FAILURE', @@ -195,7 +195,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail <skipped type="skipped" message="true"/> </testcase> <testcase name="callback pass" time="*" classname="test" file="*"/> - <testcase name="callback fail" time="*" classname="test" file="*" failure="callback failure"> + <testcase name="callback fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="callback failure"> [Error [ERR_TEST_FAILURE]: callback failure] { code: 'ERR_TEST_FAILURE', @@ -209,12 +209,12 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail <testcase name="sync t is this in test" time="*" classname="test" file="*"/> <testcase name="async t is this in test" time="*" classname="test" file="*"/> <testcase name="callback t is this in test" time="*" classname="test" file="*"/> - <testcase name="callback also returns a Promise" time="*" classname="test" file="*" failure="passed a callback but also returned a Promise"> + <testcase name="callback also returns a Promise" time="*" classname="test" file="*"> <failure type="callbackAndPromisePresent" message="passed a callback but also returned a Promise"> [Error [ERR_TEST_FAILURE]: passed a callback but also returned a Promise] { code: 'ERR_TEST_FAILURE', failureType: 'callbackAndPromisePresent', cause: 'passed a callback but also returned a Promise' } </failure> </testcase> - <testcase name="callback throw" time="*" classname="test" file="*" failure="thrown from callback throw"> + <testcase name="callback throw" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="thrown from callback throw"> [Error [ERR_TEST_FAILURE]: thrown from callback throw] { code: 'ERR_TEST_FAILURE', @@ -225,7 +225,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fail } </failure> </testcase> - <testcase name="callback called twice" time="*" classname="test" file="*" failure="callback invoked multiple times"> + <testcase name="callback called twice" time="*" classname="test" file="*"> <failure type="multipleCallbackInvocations" message="callback invoked multiple times"> Error [ERR_TEST_FAILURE]: callback invoked multiple times at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:272:3) { @@ -236,7 +236,7 @@ Error [ERR_TEST_FAILURE]: callback invoked multiple times </failure> </testcase> <testcase name="callback called twice in different ticks" time="*" classname="test" file="*"/> - <testcase name="callback called twice in future tick" time="*" classname="test" file="*" failure="callback invoked multiple times"> + <testcase name="callback called twice in future tick" time="*" classname="test" file="*"> <failure type="uncaughtException" message="callback invoked multiple times"> Error [ERR_TEST_FAILURE]: callback invoked multiple times at <node-internal-frames> { @@ -251,7 +251,7 @@ Error [ERR_TEST_FAILURE]: callback invoked multiple times } </failure> </testcase> - <testcase name="callback async throw" time="*" classname="test" file="*" failure="thrown from callback async throw"> + <testcase name="callback async throw" time="*" classname="test" file="*"> <failure type="uncaughtException" message="thrown from callback async throw"> Error [ERR_TEST_FAILURE]: thrown from callback async throw at <node-internal-frames> { @@ -269,12 +269,12 @@ Error [ERR_TEST_FAILURE]: thrown from callback async throw <testcase name="running subtest 3" time="*" classname="only is set on subtests but not in only mode" file="*"/> <testcase name="running subtest 4" time="*" classname="only is set on subtests but not in only mode" file="*"/> </testsuite> - <testcase name="custom inspect symbol fail" time="*" classname="test" file="*" failure="customized"> + <testcase name="custom inspect symbol fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="customized"> [Error [ERR_TEST_FAILURE]: customized] { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: customized } </failure> </testcase> - <testcase name="custom inspect symbol that throws fail" time="*" classname="test" file="*" failure="{ foo: 1, Symbol(nodejs.util.inspect.custom): [Function: [nodejs.util.inspect.custom]] }"> + <testcase name="custom inspect symbol that throws fail" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="{ foo: 1, Symbol(nodejs.util.inspect.custom): [Function: [nodejs.util.inspect.custom]] }"> [Error [ERR_TEST_FAILURE]: { foo: 1, @@ -287,7 +287,7 @@ Error [ERR_TEST_FAILURE]: thrown from callback async throw </failure> </testcase> <testsuite name="subtest sync throw fails" time="*" disabled="0" errors="0" tests="2" failures="2" skipped="0" timestamp="*" hostname="HOSTNAME"> - <testcase name="sync throw fails at first" time="*" classname="subtest sync throw fails" file="*" failure="thrown from subtest sync throw fails at first"> + <testcase name="sync throw fails at first" time="*" classname="subtest sync throw fails" file="*"> <failure type="testCodeFailure" message="thrown from subtest sync throw fails at first"> Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at first at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:334:11) { @@ -301,7 +301,7 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at first } </failure> </testcase> - <testcase name="sync throw fails at second" time="*" classname="subtest sync throw fails" file="*" failure="thrown from subtest sync throw fails at second"> + <testcase name="sync throw fails at second" time="*" classname="subtest sync throw fails" file="*"> <failure type="testCodeFailure" message="thrown from subtest sync throw fails at second"> Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at second at TestContext.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:337:11) { @@ -316,12 +316,12 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at second </failure> </testcase> </testsuite> - <testcase name="timed out async test" time="*" classname="test" file="*" failure="test timed out after 5ms"> + <testcase name="timed out async test" time="*" classname="test" file="*"> <failure type="testTimeoutFailure" message="test timed out after 5ms"> [Error [ERR_TEST_FAILURE]: test timed out after 5ms] { code: 'ERR_TEST_FAILURE', failureType: 'testTimeoutFailure', cause: 'test timed out after 5ms' } </failure> </testcase> - <testcase name="timed out callback test" time="*" classname="test" file="*" failure="test timed out after 5ms"> + <testcase name="timed out callback test" time="*" classname="test" file="*"> <failure type="testTimeoutFailure" message="test timed out after 5ms"> [Error [ERR_TEST_FAILURE]: test timed out after 5ms] { code: 'ERR_TEST_FAILURE', failureType: 'testTimeoutFailure', cause: 'test timed out after 5ms' } </failure> @@ -329,12 +329,12 @@ Error [ERR_TEST_FAILURE]: thrown from subtest sync throw fails at second <testcase name="large timeout async test is ok" time="*" classname="test" file="*"/> <testcase name="large timeout callback test is ok" time="*" classname="test" file="*"/> <testcase name="successful thenable" time="*" classname="test" file="*"/> - <testcase name="rejected thenable" time="*" classname="test" file="*" failure="custom error"> + <testcase name="rejected thenable" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="custom error"> [Error [ERR_TEST_FAILURE]: custom error] { code: 'ERR_TEST_FAILURE', failureType: 'testCodeFailure', cause: 'custom error' } </failure> </testcase> - <testcase name="unfinished test with uncaughtException" time="*" classname="test" file="*" failure="foo"> + <testcase name="unfinished test with uncaughtException" time="*" classname="test" file="*"> <failure type="uncaughtException" message="foo"> Error [ERR_TEST_FAILURE]: foo at <node-internal-frames> { @@ -346,7 +346,7 @@ Error [ERR_TEST_FAILURE]: foo } </failure> </testcase> - <testcase name="unfinished test with unhandledRejection" time="*" classname="test" file="*" failure="bar"> + <testcase name="unfinished test with unhandledRejection" time="*" classname="test" file="*"> <failure type="unhandledRejection" message="bar"> Error [ERR_TEST_FAILURE]: bar at <node-internal-frames> { @@ -358,7 +358,7 @@ Error [ERR_TEST_FAILURE]: bar } </failure> </testcase> - <testcase name="assertion errors display actual and expected properly" time="*" classname="test" file="*" failure="Expected values to be loosely deep-equal: { bar: 1, baz: { date: 1970-01-01T00:00:00.000Z, null: null, number: 1, string: 'Hello', undefined: undefined }, boo: [ 1 ], foo: 1 } should loosely deep-equal { baz: { date: 1970-01-01T00:00:00.000Z, null: null, number: 1, string: 'Hello', undefined: undefined }, boo: [ 1 ], circular: <ref *1> { bar: 2, c: [Circular *1] } }"> + <testcase name="assertion errors display actual and expected properly" time="*" classname="test" file="*"> <failure type="testCodeFailure" message="Expected values to be loosely deep-equal: { bar: 1, baz: { date: 1970-01-01T00:00:00.000Z, null: null, number: 1, string: 'Hello', undefined: undefined }, boo: [ 1 ], foo: 1 } should loosely deep-equal { baz: { date: 1970-01-01T00:00:00.000Z, null: null, number: 1, string: 'Hello', undefined: undefined }, boo: [ 1 ], circular: <ref *1> { bar: 2, c: [Circular *1] } }"> [Error [ERR_TEST_FAILURE]: Expected values to be loosely deep-equal: @@ -443,7 +443,7 @@ should loosely deep-equal } </failure> </testcase> - <testcase name="invalid subtest fail" time="*" classname="test" file="*" failure="test could not be started because its parent finished"> + <testcase name="invalid subtest fail" time="*" classname="test" file="*"> <failure type="parentAlreadyFinished" message="test could not be started because its parent finished"> Error [ERR_TEST_FAILURE]: test could not be started because its parent finished at Immediate.<anonymous> (<project-root>/test/fixtures/test-runner/output/output.js:197:7) { diff --git a/test/fixtures/test-runner/output/test-timeout-flag.snapshot b/test/fixtures/test-runner/output/test-timeout-flag.snapshot index 2b5ba9d76a20..eb31f34dcd1f 100644 --- a/test/fixtures/test-runner/output/test-timeout-flag.snapshot +++ b/test/fixtures/test-runner/output/test-timeout-flag.snapshot @@ -9,8 +9,6 @@ TAP version 13 failureType: 'testTimeoutFailure' error: 'test timed out after 100ms' code: 'ERR_TEST_FAILURE' - stack: |- - async Promise.all (index 0) ... # Subtest: should timeout after 5ms not ok 2 - should timeout after 5ms diff --git a/test/fixtures/test-runner/output/timeout_in_before_each_should_not_affect_further_tests.snapshot b/test/fixtures/test-runner/output/timeout_in_before_each_should_not_affect_further_tests.snapshot index 00d349065823..1348ec5aa6bc 100644 --- a/test/fixtures/test-runner/output/timeout_in_before_each_should_not_affect_further_tests.snapshot +++ b/test/fixtures/test-runner/output/timeout_in_before_each_should_not_affect_further_tests.snapshot @@ -14,8 +14,6 @@ gonna timeout failureType: 'hookFailed' error: 'failed running beforeEach hook' code: 'ERR_TEST_FAILURE' - stack: |- - async Promise.all (index 0) ... # Subtest: first describe second test ok 2 - first describe second test @@ -45,8 +43,6 @@ not gonna timeout failureType: 'hookFailed' error: 'failed running afterEach hook' code: 'ERR_TEST_FAILURE' - stack: |- - async Promise.all (index 0) ... # Subtest: second describe second test ok 2 - second describe second test diff --git a/test/fixtures/test-runner/rerun-shared-helper-across-files/a.mjs b/test/fixtures/test-runner/rerun-shared-helper-across-files/a.mjs new file mode 100644 index 000000000000..2f45f6bb2626 --- /dev/null +++ b/test/fixtures/test-runner/rerun-shared-helper-across-files/a.mjs @@ -0,0 +1,4 @@ +import { describeEngine } from './helper.mjs'; + +describeEngine('a-1'); +describeEngine('a-2'); diff --git a/test/fixtures/test-runner/rerun-shared-helper-across-files/b.mjs b/test/fixtures/test-runner/rerun-shared-helper-across-files/b.mjs new file mode 100644 index 000000000000..13d3dc936581 --- /dev/null +++ b/test/fixtures/test-runner/rerun-shared-helper-across-files/b.mjs @@ -0,0 +1,6 @@ +import { describeEngine } from './helper.mjs'; + +describeEngine('b-1'); +describeEngine('b-2'); +describeEngine('b-3'); +describeEngine('b-4', { fails: true }); diff --git a/test/fixtures/test-runner/rerun-shared-helper-across-files/helper.mjs b/test/fixtures/test-runner/rerun-shared-helper-across-files/helper.mjs new file mode 100644 index 000000000000..3c4b0d8abd4c --- /dev/null +++ b/test/fixtures/test-runner/rerun-shared-helper-across-files/helper.mjs @@ -0,0 +1,13 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert'; + +// Every test file calling this registers its suites and tests at the same +// source location, which is outside of the test file itself. +export function describeEngine(name, { fails = false } = {}) { + describe(name, () => { + it('works', ({ attempt }) => { + assert.ok(!fails, `${name} always fails`); + assert.strictEqual(attempt, 0, `${name} already passed and must not run again`); + }); + }); +} diff --git a/test/fixtures/test-runner/worker-id/test-1.mjs b/test/fixtures/test-runner/worker-id/test-1.mjs index 7e6f40f2b18c..1458e2f45eaf 100644 --- a/test/fixtures/test-runner/worker-id/test-1.mjs +++ b/test/fixtures/test-runner/worker-id/test-1.mjs @@ -1,4 +1,4 @@ -import { test } from 'node:test'; +import { describe, test } from 'node:test'; test('worker ID is available as environment variable', (t) => { const workerId = process.env.NODE_TEST_WORKER_ID; @@ -24,3 +24,9 @@ test('worker ID is available via context', (t) => { throw new Error(`context.workerId (${workerId}) should match NODE_TEST_WORKER_ID (${envWorkerId})`); } }); + +describe('worker ID is available via suite context', (s) => { + if (s.workerId !== Number(process.env.NODE_TEST_WORKER_ID)) { + throw new Error(`suite context.workerId (${s.workerId}) should match NODE_TEST_WORKER_ID (${process.env.NODE_TEST_WORKER_ID})`); + } +}); diff --git a/test/fixtures/test426/.github/dependabot.yml b/test/fixtures/test426/.github/dependabot.yml new file mode 100644 index 000000000000..425b6b6b57fe --- /dev/null +++ b/test/fixtures/test426/.github/dependabot.yml @@ -0,0 +1,27 @@ +version: 2 +updates: + # Tooling for building and type-checking the npm package. + - package-ecosystem: npm + directory: / + schedule: + interval: weekly + groups: + npm-minor-and-patch: + patterns: + - '*' + update-types: + - minor + - patch + + # Actions used by the workflows. + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions-minor-and-patch: + patterns: + - '*' + update-types: + - minor + - patch diff --git a/test/fixtures/wpt/WebCryptoAPI/import_export/jwk_key_ops_duplicates.https.any.js b/test/fixtures/wpt/WebCryptoAPI/import_export/jwk_key_ops_duplicates.https.any.js new file mode 100644 index 000000000000..047079191bba --- /dev/null +++ b/test/fixtures/wpt/WebCryptoAPI/import_export/jwk_key_ops_duplicates.https.any.js @@ -0,0 +1,18 @@ +// META: title=WebCryptoAPI: importKey rejects a JWK with duplicate key_ops +// META: global=window,worker + +'use strict'; + +// RFC 7517 section 4.3: "Duplicate key operation values MUST NOT be present". +// WebCrypto rejects a key_ops member that is invalid per JWK with DataError. +promise_test(async t => { + const jwk = { + kty: 'oct', + k: 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8', + alg: 'HS256', + key_ops: ['sign', 'verify', 'verify'], + }; + await promise_rejects_dom(t, 'DataError', + crypto.subtle.importKey('jwk', jwk, {name: 'HMAC', hash: 'SHA-256'}, + true, ['sign'])); +}, 'importKey rejects a JWK whose key_ops has a duplicate'); diff --git a/test/fixtures/wpt/url/failure.html b/test/fixtures/wpt/url/failure.html index d95b1d52d672..71efb0f27d91 100644 --- a/test/fixtures/wpt/url/failure.html +++ b/test/fixtures/wpt/url/failure.html @@ -29,8 +29,15 @@ }, "URL's constructor's base argument: " + name) self.test(() => { - const url = new URL("about:blank") + const original = "http://user:pass@example.com:8080/path?query#fragment" + const url = new URL(original) assert_throws_js(TypeError, () => url.href = test.input) + const expected = new URL(original) + for (const property of ["href", "origin", "protocol", "username", "password", "host", "hostname", "port", "pathname", "search", "hash"]) { + assert_equals(url[property], expected[property], property) + } + url.hash = "changed" + assert_equals(url.href, "http://user:pass@example.com:8080/path?query#changed") }, "URL's href: " + name) // The following use cases resolve the URL input relative to the current diff --git a/test/fixtures/wpt/url/resources/IdnaTestV2.json b/test/fixtures/wpt/url/resources/IdnaTestV2.json index ed4d433ebeeb..be363124a6ad 100644 --- a/test/fixtures/wpt/url/resources/IdnaTestV2.json +++ b/test/fixtures/wpt/url/resources/IdnaTestV2.json @@ -7048,22 +7048,33 @@ "output": "j" }, { - "comment": "C1; V7", + "comment": "C1", "input": "\u10ad\ud8be\udccd\ua868\u05ae\u3002\u10be\u200c\u200c", "output": null }, { - "comment": "C1; V7", + "comment": "C1", "input": "\u2d0d\ud8be\udccd\ua868\u05ae\u3002\u2d1e\u200c\u200c", "output": null }, { - "comment": "V7", "input": "xn--5cb172r175fug38a.xn--mlj", "output": "xn--5cb172r175fug38a.xn--mlj" }, { - "comment": "C1; V7", + "input": "\u2d0d\ud8be\udccd\ua868\u05ae.\u2d1e", + "output": "xn--5cb172r175fug38a.xn--mlj" + }, + { + "input": "\u10ad\ud8be\udccd\ua868\u05ae.\u10be", + "output": "xn--5cb172r175fug38a.xn--mlj" + }, + { + "input": "\u10ad\ud8be\udccd\ua868\u05ae.\u2d1e", + "output": "xn--5cb172r175fug38a.xn--mlj" + }, + { + "comment": "C1", "input": "xn--5cb172r175fug38a.xn--0uga051h", "output": "xn--5cb172r175fug38a.xn--0uga051h" }, @@ -8238,67 +8249,67 @@ "output": "xn--ep37b.xn----hec165lho83b" }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b\uff0e\u1baa\u03c2\u10a6\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b.\u1baa\u03c2\u10a6\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b.\u1baa\u03c2\u2d06\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b.\u1baa\u03a3\u10a6\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b.\u1baa\u03c3\u2d06\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b.\u1baa\u03a3\u2d06\u200d", "output": null }, { - "comment": "V6; V7", + "comment": "V6", "input": "xn--nu4s.xn--4xa153j7im", "output": "xn--nu4s.xn--4xa153j7im" }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "xn--nu4s.xn--4xa153jk8cs1q", "output": "xn--nu4s.xn--4xa153jk8cs1q" }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "xn--nu4s.xn--3xa353jk8cs1q", "output": "xn--nu4s.xn--3xa353jk8cs1q" }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b\uff0e\u1baa\u03c2\u2d06\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b\uff0e\u1baa\u03a3\u10a6\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b\uff0e\u1baa\u03c3\u2d06\u200d", "output": null }, { - "comment": "C2; V6; V7", + "comment": "C2; V6", "input": "\ud8bc\udc2b\uff0e\u1baa\u03a3\u2d06\u200d", "output": null }, @@ -11936,20 +11947,25 @@ "output": null }, { - "comment": "V7", "input": "\ud8ba\udcac\u3002\u0729\u3002\ucbd95", - "output": null + "output": "xn--t92s.xn--znb.xn--5-y88f" }, { - "comment": "V7", "input": "\ud8ba\udcac\u3002\u0729\u3002\u110d\u1173\u11ac5", - "output": null + "output": "xn--t92s.xn--znb.xn--5-y88f" }, { - "comment": "V7", "input": "xn--t92s.xn--znb.xn--5-y88f", "output": "xn--t92s.xn--znb.xn--5-y88f" }, + { + "input": "\ud8ba\udcac.\u0729.\ucbd95", + "output": "xn--t92s.xn--znb.xn--5-y88f" + }, + { + "input": "\ud8ba\udcac.\u0729.\u110d\u1173\u11ac5", + "output": "xn--t92s.xn--znb.xn--5-y88f" + }, { "comment": "C2; V6", "input": "\u17ca.\u200d\ud835\udfee\ud804\udc3f", diff --git a/test/fixtures/wpt/url/resources/setters_tests.json b/test/fixtures/wpt/url/resources/setters_tests.json index 221e77a951bb..94d2dcd78d4a 100644 --- a/test/fixtures/wpt/url/resources/setters_tests.json +++ b/test/fixtures/wpt/url/resources/setters_tests.json @@ -677,6 +677,16 @@ "port": "8080" } }, + { + "href": "http://example.net:8080", + "new_value": "example.com:0", + "expected": { + "href": "http://example.com:0/", + "host": "example.com:0", + "hostname": "example.com", + "port": "0" + } + }, { "comment": "Port number is unchanged if not specified", "href": "http://example.net:8080", @@ -697,6 +707,16 @@ "host": "example.net" } }, + { + "href": "http://example.net:8080/path", + "new_value": ":example.com:15", + "expected": { + "href": "http://example.net:8080/path", + "host": "example.net:8080", + "hostname": "example.net", + "port": "8080" + } + }, { "comment": "The empty host is OK for non-special schemes", "href": "view-source+http://example.net/foo", @@ -1066,6 +1086,16 @@ "port": "" } }, + { + "href": "file:///x", + "new_value": "example.net", + "expected": { + "href": "file://example.net/x", + "host": "example.net", + "hostname": "example.net", + "port": "" + } + }, { "href": "sc://test@test/", "new_value": "", @@ -1519,6 +1549,16 @@ "port": "" } }, + { + "href": "file:///x", + "new_value": "example.net", + "expected": { + "href": "file://example.net/x", + "host": "example.net", + "hostname": "example.net", + "port": "" + } + }, { "href": "sc://test@test/", "new_value": "", @@ -1693,6 +1733,16 @@ "port": "" } }, + { + "href": "http://example.net:8080", + "new_value": "0", + "expected": { + "href": "http://example.net:0/", + "host": "example.net:0", + "hostname": "example.net", + "port": "0" + } + }, { "comment": "Default port number is removed", "href": "http://example.net:8080", @@ -2034,6 +2084,14 @@ "pathname": "/home" } }, + { + "href": "https://example.net/home#nav", + "new_value": "", + "expected": { + "href": "https://example.net/#nav", + "pathname": "/" + } + }, { "comment": "\\ is a segment delimiter for 'special' URLs", "href": "http://example.net/home?lang=fr#nav", diff --git a/test/fixtures/wpt/url/resources/urltestdata-javascript-only.json b/test/fixtures/wpt/url/resources/urltestdata-javascript-only.json index a3793c1f472f..01b37526b99e 100644 --- a/test/fixtures/wpt/url/resources/urltestdata-javascript-only.json +++ b/test/fixtures/wpt/url/resources/urltestdata-javascript-only.json @@ -14,5 +14,20 @@ "pathname": "/%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", "search": "?%EF%BF%BD%F0%90%9F%BE%EF%BF%BD%EF%B7%90%EF%B7%8F%EF%B7%AF%EF%B7%B0%EF%BF%BE%EF%BF%BF", "hash": "" + }, + { + "input": "b/c", + "base": "http://example.com/\uD801/b", + "href": "http://example.com/%EF%BF%BD/b/c", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%EF%BF%BD/b/c", + "search": "", + "hash": "" } ] diff --git a/test/fixtures/wpt/url/resources/urltestdata.json b/test/fixtures/wpt/url/resources/urltestdata.json index 22900fb0ecce..950569a80247 100644 --- a/test/fixtures/wpt/url/resources/urltestdata.json +++ b/test/fixtures/wpt/url/resources/urltestdata.json @@ -3823,6 +3823,43 @@ "search": "", "hash": "" }, + "Leading and trailing U+007F DELETE are not trimmed", + { + "input": "\u007Fhttp://example.com/", + "base": null, + "failure": true, + "relativeTo": "non-opaque-path-base" + }, + { + "input": "\u007Fjavascript:alert(1)", + "base": "http://example.org/foo/bar", + "href": "http://example.org/foo/%7Fjavascript:alert(1)", + "origin": "http://example.org", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.org", + "hostname": "example.org", + "port": "", + "pathname": "/foo/%7Fjavascript:alert(1)", + "search": "", + "hash": "" + }, + { + "input": "http://example.com/\u007F", + "base": null, + "href": "http://example.com/%7F", + "origin": "http://example.com", + "protocol": "http:", + "username": "", + "password": "", + "host": "example.com", + "hostname": "example.com", + "port": "", + "pathname": "/%7F", + "search": "", + "hash": "" + }, { "input": "non-special:opaque ", "base": null, @@ -10684,5 +10721,81 @@ "pathname": "blank", "search": "", "hash": "#%00%01%1F%20!%22#$%&'()*+,-./09:;%3C=%3E?@AZ[\\]^_%60az{|}~%7F%C2%80%C2%81%C3%89%C3%A9" + }, + "# Relative resolution against empty-path and path-only non-special base URLs with query/fragment", + { + "input": "p", + "base": "git://host?q#r", + "href": "git://host/p", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "/p", + "search": "", + "hash": "" + }, + { + "input": "?q2", + "base": "git://host?q#r", + "href": "git://host?q2", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "", + "search": "?q2", + "hash": "" + }, + { + "input": "#h", + "base": "git://host?q#r", + "href": "git://host?q#h", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "host", + "hostname": "host", + "port": "", + "pathname": "", + "search": "?q", + "hash": "#h" + }, + { + "input": "?q2", + "base": "git:/.//a?q#r", + "href": "git:/.//a?q2", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//a", + "search": "?q2", + "hash": "" + }, + { + "input": "#h", + "base": "git:/.//a?q#r", + "href": "git:/.//a?q#h", + "origin": "null", + "protocol": "git:", + "username": "", + "password": "", + "host": "", + "hostname": "", + "port": "", + "pathname": "//a", + "search": "?q", + "hash": "#h" } ] diff --git a/test/fixtures/wpt/url/url-setters-lone-surrogates.any.js b/test/fixtures/wpt/url/url-setters-lone-surrogates.any.js new file mode 100644 index 000000000000..1a81723d9466 --- /dev/null +++ b/test/fixtures/wpt/url/url-setters-lone-surrogates.any.js @@ -0,0 +1,44 @@ +// Not in setters_tests.json since lone surrogates are not portable JSON. + +[{ + property: 'pathname', + newValue: '\uDC01\uD802a', + expected: { + href: 'http://example.net/%EF%BF%BD%EF%BF%BDa', + pathname: '/%EF%BF%BD%EF%BF%BDa' + } +}, + { + property: 'search', + newValue: '\uDC01\uD802a', + expected: { + href: 'http://example.net/?%EF%BF%BD%EF%BF%BDa', + search: '?%EF%BF%BD%EF%BF%BDa' + } + }, + { + property: 'hash', + newValue: '\uDC01\uD802a', + expected: { + href: 'http://example.net/#%EF%BF%BD%EF%BF%BDa', + hash: '#%EF%BF%BD%EF%BF%BDa' + } + }, + { + property: 'host', + newValue: 'exa\uDC01\uD802mple.com', + expected: {href: 'http://example.net/', host: 'example.net'} + }, + { + property: 'hostname', + newValue: 'exa\uDC01\uD802mple.com', + expected: {href: 'http://example.net/', hostname: 'example.net'} + }].forEach(({property, newValue, expected}) => { + test(() => { + const url = new URL('http://example.net/'); + url[property] = newValue; + for (const [key, value] of Object.entries(expected)) { + assert_equals(url[key], value, key); + } + }, `Setting ${property} to a value with lone surrogates`); +}); diff --git a/test/fixtures/wpt/url/url-setters-stripping.any.js b/test/fixtures/wpt/url/url-setters-stripping.any.js index ac90cc17e0bf..ff91aea87252 100644 --- a/test/fixtures/wpt/url/url-setters-stripping.any.js +++ b/test/fixtures/wpt/url/url-setters-stripping.any.js @@ -121,5 +121,26 @@ for(const scheme of ["https", "wpt++"]) { }, `Setting ${property} with ${type} ${cpReference} (${scheme}:)`); } } + + // searchParams has to reflect the resulting query, also when it was obtained before setting + // search + for (const [type, input] of [ + ["leading", String.fromCodePoint(i) + "test"], + ["middle", "te" + String.fromCodePoint(i) + "st"], + ["trailing", "test" + String.fromCodePoint(i)] + ]) { + for (const searchParamsFirst of [false, true]) { + test(() => { + const expected = stripped ? "test" : input; + const url = urlRecord(scheme); + if (searchParamsFirst) { + url.searchParams; + } + url.search = input; + assert_array_equals([...url.searchParams.keys()], [expected], "keys"); + assert_array_equals([...url.searchParams.values()], [""], "values"); + }, `Setting search with ${type} ${cpReference} updates ${searchParamsFirst ? "previously obtained " : ""}searchParams (${scheme}:)`); + } + } } } diff --git a/test/fixtures/wpt/url/urlsearchparams-constructor.any.js b/test/fixtures/wpt/url/urlsearchparams-constructor.any.js index d482911350ba..ecd341a431e4 100644 --- a/test/fixtures/wpt/url/urlsearchparams-constructor.any.js +++ b/test/fixtures/wpt/url/urlsearchparams-constructor.any.js @@ -19,6 +19,15 @@ test(function () { assert_equals(params.toString(), "a=b") }, 'URLSearchParams constructor, remove leading "?"') +test(function() { + var params = new URLSearchParams('??a=b') + assert_equals(params.toString(), '%3Fa=b') + params = new URLSearchParams('?') + assert_equals(params.toString(), '') + params = new URLSearchParams('??') + assert_equals(params.toString(), '%3F=') +}, 'URLSearchParams constructor, remove only one leading "?"') + test(() => { var params = new URLSearchParams(DOMException); assert_equals(params.toString(), "INDEX_SIZE_ERR=1&DOMSTRING_SIZE_ERR=2&HIERARCHY_REQUEST_ERR=3&WRONG_DOCUMENT_ERR=4&INVALID_CHARACTER_ERR=5&NO_DATA_ALLOWED_ERR=6&NO_MODIFICATION_ALLOWED_ERR=7&NOT_FOUND_ERR=8&NOT_SUPPORTED_ERR=9&INUSE_ATTRIBUTE_ERR=10&INVALID_STATE_ERR=11&SYNTAX_ERR=12&INVALID_MODIFICATION_ERR=13&NAMESPACE_ERR=14&INVALID_ACCESS_ERR=15&VALIDATION_ERR=16&TYPE_MISMATCH_ERR=17&SECURITY_ERR=18&NETWORK_ERR=19&ABORT_ERR=20&URL_MISMATCH_ERR=21"A_EXCEEDED_ERR=22&TIMEOUT_ERR=23&INVALID_NODE_TYPE_ERR=24&DATA_CLONE_ERR=25") @@ -130,6 +139,20 @@ test(function() { assert_equals(newParams.get('query'), testValue); }, 'Parse encoded +'); +test(function() { + var params = new URLSearchParams('a=b%2Bc'); + assert_equals(params.get('a'), 'b+c'); + params = new URLSearchParams('a%2Bb=c'); + assert_equals(params.get('a+b'), 'c'); +}, 'Parse %2B'); + +test(function() { + var params = new URLSearchParams('='); + assert_true(params.has('')); + assert_equals(params.get(''), ''); + assert_equals(params.toString(), '='); +}, 'Parse ='); + test(function() { var params = new URLSearchParams('a=b c'); assert_equals(params.get('a'), 'b c'); @@ -196,6 +219,18 @@ test(function() { assert_throws_js(TypeError, function() { new URLSearchParams([[1,2,3]]); }); }, "Constructor with sequence of sequences of strings"); +test(function() { + var params = new URLSearchParams([[1, 2], ['a', 'b']]); + assert_equals(params.toString(), '1=2&a=b'); +}, 'Constructor with sequence of sequences of non-strings'); + +test(function() { + var params = new URLSearchParams({1: 2, 'a': 'b'}); + assert_equals(params.toString(), '1=2&a=b'); + params = new URLSearchParams({false: true, 0: 'foo'}); + assert_equals(params.toString(), '0=foo&false=true'); +}, 'Constructor with record of non-strings, in property order'); + [ { "input": {"+": "%C2"}, "output": [["+", "%C2"]], "name": "object with +" }, { "input": {c: "x", a: "?"}, "output": [["c", "x"], ["a", "?"]], "name": "object with two keys" }, diff --git a/test/fixtures/wpt/url/urlsearchparams-foreach.any.js b/test/fixtures/wpt/url/urlsearchparams-foreach.any.js index ff19643ac220..2de9f15f8696 100644 --- a/test/fixtures/wpt/url/urlsearchparams-foreach.any.js +++ b/test/fixtures/wpt/url/urlsearchparams-foreach.any.js @@ -74,3 +74,21 @@ test(function() { assert_array_equals(seen, ["param0", "param2"], "param1 should not have been seen by the loop"); assert_equals(String(searchParams), "param1=1", "param1 should remain"); }, "delete every param seen during iteration"); + +test(function() { + const params = new URLSearchParams('a=1&b=2&c=3'); + assert_array_equals([...params.keys()], ['a', 'b', 'c']); + assert_array_equals([...params.values()], ['1', '2', '3']); + const entries = [...params.entries()]; + assert_equals(entries.length, 3); + assert_array_equals(entries[0], ['a', '1']); + assert_array_equals(entries[1], ['b', '2']); + assert_array_equals(entries[2], ['c', '3']); +}, 'keys(), values() and entries()'); + +test(function() { + const params = new URLSearchParams('a=1'); + params.forEach(function(value, key, object) { + assert_equals(object, params); + }); +}, 'ForEach passes the URLSearchParams object'); diff --git a/test/fixtures/wpt/url/urlsearchparams-stringifier.any.js b/test/fixtures/wpt/url/urlsearchparams-stringifier.any.js index 6187db64b174..96e54abce1ca 100644 --- a/test/fixtures/wpt/url/urlsearchparams-stringifier.any.js +++ b/test/fixtures/wpt/url/urlsearchparams-stringifier.any.js @@ -143,3 +143,25 @@ test(() => { assert_equals(params.toString(), "a%0Ab=c%0Dd&e%0A%0Df=g%0D%0Ah"); }, 'URLSearchParams must not do newline normalization'); + +test(() => { + for (let i = 0; i <= 0xFF; i++) { + const c = String.fromCodePoint(i); + let expected; + if (c === ' ') { + expected = '+'; + } else if (/[*\-._0-9A-Za-z]/.test(c)) { + expected = c; + } else { + expected = + Array + .from(new TextEncoder().encode(c), + b => '%' + b.toString(16).toUpperCase().padStart(2, '0')) + .join(''); + } + const params = new URLSearchParams(); + params.append(c, c); + assert_equals(params.toString(), `${expected}=${expected}`, + `U+${i.toString(16).toUpperCase().padStart(4, '0')}`); + } +}, 'Serialize U+0000 to U+00FF'); diff --git a/test/fixtures/wpt/versions.json b/test/fixtures/wpt/versions.json index 7f04f8878113..f16fe17b2a8b 100644 --- a/test/fixtures/wpt/versions.json +++ b/test/fixtures/wpt/versions.json @@ -76,7 +76,7 @@ "path": "streams" }, "url": { - "commit": "c48d58747e1f211527fb695fd60548a997fae617", + "commit": "2fa965b55c94cbb2f15324aa8a149500fd5f05f9", "path": "url" }, "urlpattern": { @@ -100,7 +100,7 @@ "path": "web-locks" }, "WebCryptoAPI": { - "commit": "e87deca3369c630ca2ade57734c5a42adbbc7e48", + "commit": "4ba9d1b8e4b714685cc82e6ed0e432e917d85573", "path": "WebCryptoAPI" }, "webidl": { diff --git a/test/internet/test-tls-autoselectfamily-servername.js b/test/internet/test-tls-autoselectfamily-servername.js deleted file mode 100644 index 26f51ae6024d..000000000000 --- a/test/internet/test-tls-autoselectfamily-servername.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -const common = require('../common'); -const { addresses: { INET_HOST } } = require('../common/internet'); - -if (!common.hasCrypto) { - common.skip('missing crypto'); -} - -const { connect } = require('tls'); - -// Test that TLS connecting works without autoSelectFamily -{ - const socket = connect({ - host: INET_HOST, - port: 443, - servername: INET_HOST, - autoSelectFamily: false, - }); - - socket.on('secureConnect', common.mustCall(() => socket.end())); -} - -// Test that TLS connecting works with autoSelectFamily -{ - const socket = connect({ - host: INET_HOST, - port: 443, - servername: INET_HOST, - autoSelectFamily: true, - }); - - socket.on('secureConnect', common.mustCall(() => socket.end())); -} diff --git a/test/module-hooks/test-async-loader-hooks-called-with-expected-args.mjs b/test/module-hooks/test-async-loader-hooks-called-with-expected-args.mjs deleted file mode 100644 index 195bf02bb6fd..000000000000 --- a/test/module-hooks/test-async-loader-hooks-called-with-expected-args.mjs +++ /dev/null @@ -1,28 +0,0 @@ -// Test that loader hooks are called with all expected arguments -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/hooks-input.mjs'), - fixtures.path('es-modules/json-modules.mjs'), - ], - { - stdout(output) { - const lines = output.split('\n'); - assert.match(lines[0], /{"url":"file:\/\/\/.*\/json-modules\.mjs","format":"test","shortCircuit":true}/); - assert.match(lines[1], /{"source":{"type":"Buffer","data":\[.*\]},"format":"module","shortCircuit":true}/); - assert.match(lines[2], /{"url":"file:\/\/\/.*\/experimental\.json","format":"test","shortCircuit":true}/); - assert.match(lines[3], /{"source":{"type":"Buffer","data":\[.*\]},"format":"json","shortCircuit":true}/); - assert.strictEqual(lines.length, 4); - }, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-called-with-register.mjs b/test/module-hooks/test-async-loader-hooks-called-with-register.mjs deleted file mode 100644 index d1f9181240d7..000000000000 --- a/test/module-hooks/test-async-loader-hooks-called-with-register.mjs +++ /dev/null @@ -1,31 +0,0 @@ -// Test that loader hooks are called with all expected arguments using register function -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader=data:text/javascript,', - '--input-type=module', - '--eval', - "import { register } from 'node:module';" + - `register(${JSON.stringify(fixtures.fileURL('es-module-loaders/hooks-input.mjs'))});` + - `await import(${JSON.stringify(fixtures.fileURL('es-modules/json-modules.mjs'))});`, - ], - { - stdout(output) { - const lines = output.split('\n'); - assert.match(lines[0], /{"url":"file:\/\/\/.*\/json-modules\.mjs","format":"test","shortCircuit":true}/); - assert.match(lines[1], /{"source":{"type":"Buffer","data":\[.*\]},"format":"module","shortCircuit":true}/); - assert.match(lines[2], /{"url":"file:\/\/\/.*\/experimental\.json","format":"test","shortCircuit":true}/); - assert.match(lines[3], /{"source":{"type":"Buffer","data":\[.*\]},"format":"json","shortCircuit":true}/); - assert.strictEqual(lines.length, 4); - }, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-globalpreload-no-warning-with-initialize.mjs b/test/module-hooks/test-async-loader-hooks-globalpreload-no-warning-with-initialize.mjs deleted file mode 100644 index 54501748bcea..000000000000 --- a/test/module-hooks/test-async-loader-hooks-globalpreload-no-warning-with-initialize.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test that `globalPreload` should not emit warning when `initialize` is supplied - -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-globalpreload-and-initialize.mjs'), - fixtures.path('empty.js'), - ], - { - stderr(output) { - assert.doesNotMatch(output, /`globalPreload` has been removed; use `initialize` instead/); - }, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-globalpreload-warning.mjs b/test/module-hooks/test-async-loader-hooks-globalpreload-warning.mjs deleted file mode 100644 index 36a2c0089a91..000000000000 --- a/test/module-hooks/test-async-loader-hooks-globalpreload-warning.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that `globalPreload` should emit warning -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-globalpreload-only.mjs'), - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-globalpreload-with-return.mjs'), - fixtures.path('empty.js'), - ], - { - stderr(output) { - const matches = output.match(/`globalPreload` has been removed; use `initialize` instead/g); - assert.strictEqual(matches.length, 1); - }, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-in-sequence.mjs b/test/module-hooks/test-async-loader-hooks-initialize-in-sequence.mjs deleted file mode 100644 index bc973f587845..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-in-sequence.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test that `initialize` should execute in sequence -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-in-sequence.mjs'), - ], - { - stdout: 'hooks initialize 1\n' + - 'result 1 undefined\n' + - 'hooks initialize 2\n' + - 'result 2 undefined', - trim: true, - stderr: '', - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-invoke.mjs b/test/module-hooks/test-async-loader-hooks-initialize-invoke.mjs deleted file mode 100644 index 72dc87c12e35..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-invoke.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that `initialize` should be invoked correctly -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/hooks-initialize.mjs'), - '--input-type=module', - '--eval', - 'import os from "node:os";', - ], - { - stdout: 'hooks initialize 1', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-never-settling.mjs b/test/module-hooks/test-async-loader-hooks-initialize-never-settling.mjs deleted file mode 100644 index d1c12238ef0c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-never-settling.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// Test that `initialize` returning never-settling promise should be handled -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-initialize-never-settling.mjs'), - ], - { - stdout: 'caught ERR_ASYNC_LOADER_REQUEST_NEVER_SETTLED', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-process-exit.mjs b/test/module-hooks/test-async-loader-hooks-initialize-process-exit.mjs deleted file mode 100644 index d9476af27e8f..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-process-exit.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that it should be fine to call `process.exit` from a `initialize` hook -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-initialize-exit.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-rejecting.mjs b/test/module-hooks/test-async-loader-hooks-initialize-rejecting.mjs deleted file mode 100644 index e5d2a62fbc86..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-rejecting.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that `initialize` returning rejecting promise should be handled -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-initialize-rejecting.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /undefined$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-initialize-throw-null.mjs b/test/module-hooks/test-async-loader-hooks-initialize-throw-null.mjs deleted file mode 100644 index 69844e31ae91..000000000000 --- a/test/module-hooks/test-async-loader-hooks-initialize-throw-null.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that `initialize` throwing null should be handled -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-initialize-throw-null.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /null$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-mixed-opt-in.mjs b/test/module-hooks/test-async-loader-hooks-mixed-opt-in.mjs deleted file mode 100644 index 398df25d7bbe..000000000000 --- a/test/module-hooks/test-async-loader-hooks-mixed-opt-in.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader should handle mixed of opt-in modules and non-opt-in ones -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-mixed-opt-in.mjs'), - 'entry-point', - ], - { - stdout: 'Hello', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-import-meta-resolve.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-import-meta-resolve.mjs deleted file mode 100644 index 35a4f7a566e5..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-import-meta-resolve.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test import.meta.resolve of a never-settling resolve should throw in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/import.meta.never-resolve.mjs'), - ], - { - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-load-cjs.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-load-cjs.mjs deleted file mode 100644 index 05401b9080b3..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-load-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test never-settling load in CJS files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.cjs'), - ], - { - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-no-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-no-warning.mjs deleted file mode 100644 index dbadecc32876..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-no-warning.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test top-level await of a never-settling load without warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-with-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-with-warning.mjs deleted file mode 100644 index d4b30ae23f86..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-load-esm-with-warning.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test top-level await of a never-settling load with warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-load.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: /Warning: Detected unsettled top-level await at.+never-load\.mjs:5/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-race-cjs.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-race-cjs.mjs deleted file mode 100644 index 1de677f88838..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-race-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test race of never-settling hooks in CJS files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/race.cjs'), - ], - { - stdout: /^true$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-race-esm.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-race-esm.mjs deleted file mode 100644 index e662dc43210d..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-race-esm.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test top-level await of a race of never-settling hooks in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/race.mjs'), - ], - { - stdout: /^true$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-cjs.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-resolve-cjs.mjs deleted file mode 100644 index 1469a7b313cc..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test never-settling resolve in CJS files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.cjs'), - ], - { - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-no-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-no-warning.mjs deleted file mode 100644 index 43a7a98127c8..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-no-warning.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test top-level await of a never-settling resolve without warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-with-warning.mjs b/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-with-warning.mjs deleted file mode 100644 index 1a4c40c8bb96..000000000000 --- a/test/module-hooks/test-async-loader-hooks-never-settling-resolve-esm-with-warning.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test top-level await of a never-settling resolve with warning in ESM files -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/never-settling-resolve-step/loader.mjs'), - fixtures.path('es-module-loaders/never-settling-resolve-step/never-resolve.mjs'), - ], - { - status: 13, - signal: null, - stdout: /^should be output$/, - stderr: /Warning: Detected unsettled top-level await at.+never-resolve\.mjs:5/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-no-leak-internals.mjs b/test/module-hooks/test-async-loader-hooks-no-leak-internals.mjs deleted file mode 100644 index 781aed8601f5..000000000000 --- a/test/module-hooks/test-async-loader-hooks-no-leak-internals.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader hooks should not leak internals or expose import.meta.resolve -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-edge-cases.mjs'), - fixtures.path('empty.js'), - ], - { - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-process-exit-async.mjs b/test/module-hooks/test-async-loader-hooks-process-exit-async.mjs deleted file mode 100644 index af3b939bcf8c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-process-exit-async.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that it should be fine to call `process.exit` from a custom async hook -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-exit-on-load.mjs'), - '--input-type=module', - '--eval', - 'import "data:exit"', - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-process-exit-sync.mjs b/test/module-hooks/test-async-loader-hooks-process-exit-sync.mjs deleted file mode 100644 index 64c079b90b75..000000000000 --- a/test/module-hooks/test-async-loader-hooks-process-exit-sync.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that it should be fine to call `process.exit` from a custom sync hook -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-exit-on-resolve.mjs'), - '--input-type=module', - '--eval', - 'import "data:text/javascript,import.meta.resolve(%22exit:%22)"', - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-process-exit-top-level.mjs b/test/module-hooks/test-async-loader-hooks-process-exit-top-level.mjs deleted file mode 100644 index a25c0013c507..000000000000 --- a/test/module-hooks/test-async-loader-hooks-process-exit-top-level.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that it should be fine to call process.exit from the loader thread top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-exit-top-level.mjs'), - fixtures.path('empty.js'), - ], - { - status: 42, - signal: null, - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-cjs.mjs b/test/module-hooks/test-async-loader-hooks-register-with-cjs.mjs deleted file mode 100644 index 8d83ee6be878..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-cjs.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that `register` should work with cjs -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-with-cjs.cjs'), - ], - { - stdout(output) { - assert.deepStrictEqual(output.split('\n').sort(), ['hooks initialize 1', '{"default":"foo"}', ''].sort()); - }, - stderr: '', - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-import.mjs b/test/module-hooks/test-async-loader-hooks-register-with-import.mjs deleted file mode 100644 index 454eccb5c624..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-import.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that `register` should work with `import` -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--import', - fixtures.fileURL('es-module-loaders/register-loader.mjs'), - '--input-type=module', - '--eval', - 'import "node:os"', - ], - { - stdout: 'resolve passthru', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-ports.mjs b/test/module-hooks/test-async-loader-hooks-register-with-ports.mjs deleted file mode 100644 index 022760596fd9..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-ports.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// Test that loader should allow communicating with loader via `register` ports -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - fixtures.path('module-hooks/register-loader-with-ports.mjs'), - ], - { - stdout: 'register undefined\nmessage initialize\nmessage resolve node:os', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-require.mjs b/test/module-hooks/test-async-loader-hooks-register-with-require.mjs deleted file mode 100644 index 87ea43f8a66c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-require.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that `register` should work with `require` -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--require', - fixtures.path('es-module-loaders/register-loader.cjs'), - '--input-type=module', - '--eval', - 'import "node:os";', - ], - { - stdout: 'resolve passthru\nresolve passthru', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-register-with-url-parenturl.mjs b/test/module-hooks/test-async-loader-hooks-register-with-url-parenturl.mjs deleted file mode 100644 index a033ab3c4d2f..000000000000 --- a/test/module-hooks/test-async-loader-hooks-register-with-url-parenturl.mjs +++ /dev/null @@ -1,26 +0,0 @@ -// Test that `register` should accept URL objects as `parentURL` -import '../common/index.mjs'; -import assert from 'node:assert'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--import', - fixtures.fileURL('es-module-loaders/register-hooks-with-current-cwd-parent-url.mjs'), - fixtures.path('es-module-loaders/register-loader-with-url-parenturl.mjs'), - ], - { - cwd: fixtures.path('es-module-loaders/'), - }, - { - stdout(output) { - assert.deepStrictEqual(output.split('\n').sort(), ['hooks initialize 1', '{"default":"foo"}'].sort()); - }, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-remove-beforeexit-listener.mjs b/test/module-hooks/test-async-loader-hooks-remove-beforeexit-listener.mjs deleted file mode 100644 index 9a28bb59dd31..000000000000 --- a/test/module-hooks/test-async-loader-hooks-remove-beforeexit-listener.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that it should be fine to call `process.removeAllListeners("beforeExit")`("beforeExit") from the main thread -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-delayed-async-load.mjs'), - '--input-type=module', - '--eval', - 'setInterval(() => process.removeAllListeners("beforeExit"),1).unref();await import("data:text/javascript,")', - ], - { - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-require-esm-in-hooks-thread.mjs b/test/module-hooks/test-async-loader-hooks-require-esm-in-hooks-thread.mjs deleted file mode 100644 index 8a647568ffee..000000000000 --- a/test/module-hooks/test-async-loader-hooks-require-esm-in-hooks-thread.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that require(esm) of a module with imports works while loading a module.register() hooks module. -// Refs: https://github.com/nodejs/node/issues/66767 -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--input-type=module', - '--eval', - `import { register } from 'node:module'; - register(${JSON.stringify(fixtures.fileURL('module-hooks/require-esm-in-hooks-thread/hooks.mjs'))}); - console.log('ok');`, - ], - { - stdout: 'ok', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-require-resolve-default.mjs b/test/module-hooks/test-async-loader-hooks-require-resolve-default.mjs deleted file mode 100644 index 71e539fe118b..000000000000 --- a/test/module-hooks/test-async-loader-hooks-require-resolve-default.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader should use CJS loader to respond to `require.resolve` calls by default -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-resolve-passthru.mjs'), - fixtures.path('require-resolve.js'), - ], - { - stdout: 'resolve passthru', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-require-resolve-opt-in.mjs b/test/module-hooks/test-async-loader-hooks-require-resolve-opt-in.mjs deleted file mode 100644 index 0cbf2fd2d942..000000000000 --- a/test/module-hooks/test-async-loader-hooks-require-resolve-opt-in.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader should use ESM loader to respond to `require.resolve` calls when opting in -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-load-commonjs-with-source.mjs'), - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-resolve-passthru.mjs'), - fixtures.path('require-resolve.js'), - ], - { - stdout: 'resolve passthru\n'.repeat(10).trim(), - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-source-maps-cjs.mjs b/test/module-hooks/test-async-loader-hooks-source-maps-cjs.mjs deleted file mode 100644 index 83bd53405d1b..000000000000 --- a/test/module-hooks/test-async-loader-hooks-source-maps-cjs.mjs +++ /dev/null @@ -1,23 +0,0 @@ -// Test that loader should support source maps in commonjs translator -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--enable-source-maps', - '--import', - fixtures.fileURL('es-module-loaders/loader-load-source-maps.mjs'), - fixtures.path('source-map/throw-on-require.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /throw-on-require\.ts:9:9/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-bigint.mjs b/test/module-hooks/test-async-loader-hooks-throw-bigint.mjs deleted file mode 100644 index 34136f81bf21..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-bigint.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle bigint thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-bigint.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^1$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-boolean.mjs b/test/module-hooks/test-async-loader-hooks-throw-boolean.mjs deleted file mode 100644 index 476fad3c1415..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-boolean.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle boolean thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-boolean.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^true$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-empty-object.mjs b/test/module-hooks/test-async-loader-hooks-throw-empty-object.mjs deleted file mode 100644 index ac09704c28ca..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-empty-object.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle empty plain object thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-empty-object.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^\{\}$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-error.mjs b/test/module-hooks/test-async-loader-hooks-throw-error.mjs deleted file mode 100644 index b37ce50db1e3..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-error.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle regular Error object thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-error.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^Error: error message$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-function.mjs b/test/module-hooks/test-async-loader-hooks-throw-function.mjs deleted file mode 100644 index bb371f727c84..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-function.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle function thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-function.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^\[Function: fnName\]$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-null.mjs b/test/module-hooks/test-async-loader-hooks-throw-null.mjs deleted file mode 100644 index 33528ff2b975..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-null.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle null thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-null.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^null$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-number.mjs b/test/module-hooks/test-async-loader-hooks-throw-number.mjs deleted file mode 100644 index da1f301089ca..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-number.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle number thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-number.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^1$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-object.mjs b/test/module-hooks/test-async-loader-hooks-throw-object.mjs deleted file mode 100644 index 8280bd0d105b..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-object.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle plain object thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-object.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^\{ fn: \[Function: fn\], symbol: Symbol\(symbol\), u: undefined \}$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-string.mjs b/test/module-hooks/test-async-loader-hooks-throw-string.mjs deleted file mode 100644 index 4ea6372e865c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-string.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle string thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-string.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^literal string$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-symbol.mjs b/test/module-hooks/test-async-loader-hooks-throw-symbol.mjs deleted file mode 100644 index 44339537ba9c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-symbol.mjs +++ /dev/null @@ -1,20 +0,0 @@ -// Test that loader hooks should handle symbol thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-symbol.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', // Throwing a symbol doesn't produce any output - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-throw-undefined.mjs b/test/module-hooks/test-async-loader-hooks-throw-undefined.mjs deleted file mode 100644 index aff5292a857f..000000000000 --- a/test/module-hooks/test-async-loader-hooks-throw-undefined.mjs +++ /dev/null @@ -1,22 +0,0 @@ -// Test that loader hooks should handle undefined thrown from top-level -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-throw-undefined.mjs'), - fixtures.path('empty.js'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /^undefined$/m, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-use-hooks-require-esm.mjs b/test/module-hooks/test-async-loader-hooks-use-hooks-require-esm.mjs deleted file mode 100644 index 1eee6a6014aa..000000000000 --- a/test/module-hooks/test-async-loader-hooks-use-hooks-require-esm.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// Test that loader should use hooks for require of ESM -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-deprecation', - '--no-experimental-require-module', - '--import', - fixtures.fileURL('es-module-loaders/builtin-named-exports.mjs'), - fixtures.path('es-modules/require-esm-throws-with-loaders.js'), - ], - { - stdout: '', - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-with-worker-permission-allowed.mjs b/test/module-hooks/test-async-loader-hooks-with-worker-permission-allowed.mjs deleted file mode 100644 index 9be7e8c39600..000000000000 --- a/test/module-hooks/test-async-loader-hooks-with-worker-permission-allowed.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// Test that loader hooks should allow spawning workers when allowed by CLI flags -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndAssert } from '../common/child_process.js'; - -spawnSyncAndAssert( - execPath, - [ - '--no-warnings', - '--permission', - '--allow-worker', - '--allow-fs-read', - '*', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-worker-spawn.mjs'), - fixtures.path('es-modules/esm-top-level-await.mjs'), - ], - { - stdout: /^1\n2$/, - stderr: '', - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-with-worker-permission-restricted.mjs b/test/module-hooks/test-async-loader-hooks-with-worker-permission-restricted.mjs deleted file mode 100644 index fe76f2f5842c..000000000000 --- a/test/module-hooks/test-async-loader-hooks-with-worker-permission-restricted.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// Test that loader hooks should not allow spawning workers if restricted by CLI flags -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--permission', - '--allow-fs-read', - '*', - '--experimental-loader', - fixtures.fileURL('es-module-loaders/loader-worker-spawn.mjs'), - fixtures.path('es-modules/esm-top-level-await.mjs'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /code: 'ERR_ACCESS_DENIED'/, - trim: true, - }, -); diff --git a/test/module-hooks/test-async-loader-hooks-without-worker-permission.mjs b/test/module-hooks/test-async-loader-hooks-without-worker-permission.mjs deleted file mode 100644 index 21589234144d..000000000000 --- a/test/module-hooks/test-async-loader-hooks-without-worker-permission.mjs +++ /dev/null @@ -1,25 +0,0 @@ -// Test that loader hooks should not work without worker permission -import '../common/index.mjs'; -import { execPath } from 'node:process'; -import fixtures from '../common/fixtures.js'; -import { spawnSyncAndExit } from '../common/child_process.js'; - -spawnSyncAndExit( - execPath, - [ - '--no-warnings', - '--permission', - '--allow-fs-read', - '*', - '--experimental-loader', - fixtures.fileURL('empty.js'), - fixtures.path('es-modules/esm-top-level-await.mjs'), - ], - { - status: 1, - signal: null, - stdout: '', - stderr: /Error: Access to this API has been restricted/, - trim: true, - }, -); diff --git a/test/module-hooks/test-module-hooks-load-async-and-sync.js b/test/module-hooks/test-module-hooks-load-async-and-sync.js deleted file mode 100644 index 75f4987942f9..000000000000 --- a/test/module-hooks/test-module-hooks-load-async-and-sync.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; -// This tests that sync and async hooks can be mixed. - -require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); -const fixtures = require('../common/fixtures'); - -const app = fixtures.path('module-hooks', 'sync-and-async', 'app.js'); - -const testCases = [ - // When mixing sync and async hooks, the sync ones always run first. - { preload: ['sync-customize', 'async-customize'], stdout: 'customized by sync hook' }, - { preload: ['async-customize', 'sync-customize'], stdout: 'customized by sync hook' }, - // It should still work when neither hook does any customization. - { preload: ['sync-forward', 'async-forward'], stdout: 'Hello world' }, - { preload: ['async-forward', 'sync-forward'], stdout: 'Hello world' }, - // It should work when only one hook is customizing. - { preload: ['sync-customize', 'async-forward'], stdout: 'customized by sync hook' }, - { preload: ['async-customize', 'sync-forward'], stdout: 'customized by async hook' }, -]; - - -for (const { preload, stdout } of testCases) { - const importArgs = []; - for (const p of preload) { - importArgs.push('--import', fixtures.fileURL(`module-hooks/sync-and-async/${p}.js`)); - } - spawnSyncAndAssert(process.execPath, [...importArgs, app], { - stdout, - trim: true, - }); -} diff --git a/test/module-hooks/test-module-hooks-load-builtin-import.mjs b/test/module-hooks/test-module-hooks-load-builtin-import.mjs index f78c69692fe0..159189f53c5d 100644 --- a/test/module-hooks/test-module-hooks-load-builtin-import.mjs +++ b/test/module-hooks/test-module-hooks-load-builtin-import.mjs @@ -5,8 +5,7 @@ import process from 'node:process'; // This tests that imported builtins get null as source from default // step, and the source returned are ignored. -// TODO(joyeecheung): this is to align with the module.register() behavior -// but perhaps the load hooks should not be invoked for builtins at all. +// TODO(joyeecheung): perhaps the load hooks should not be invoked for builtins at all. // Pick a builtin that's unlikely to be loaded already - like zlib. assert(!process.moduleLoadList.includes('NativeModule zlib')); diff --git a/test/module-hooks/test-module-hooks-load-builtin-require.js b/test/module-hooks/test-module-hooks-load-builtin-require.js index d86eb4b9df76..ac4de0f14da3 100644 --- a/test/module-hooks/test-module-hooks-load-builtin-require.js +++ b/test/module-hooks/test-module-hooks-load-builtin-require.js @@ -7,8 +7,7 @@ const { registerHooks } = require('module'); // This tests that required builtins get null as source from default // step, and the source returned are ignored. -// TODO(joyeecheung): this is to align with the module.register() behavior -// but perhaps the load hooks should not be invoked for builtins at all. +// TODO(joyeecheung): perhaps the load hooks should not be invoked for builtins at all. // Pick a builtin that's unlikely to be loaded already - like zlib. assert(!process.moduleLoadList.includes('NativeModule zlib')); diff --git a/test/module-hooks/test-module-hooks-resolve-require-resolve-loaded-with-source.js b/test/module-hooks/test-module-hooks-resolve-require-resolve-loaded-with-source.js deleted file mode 100644 index de66beda5b2e..000000000000 --- a/test/module-hooks/test-module-hooks-resolve-require-resolve-loaded-with-source.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -// This tests that require.resolve() in a CJS file loaded via the re-invented -// require (triggered when module.register() installs an async loader that -// provides source for a CJS file) still goes through resolve hooks registered -// via module.registerHooks(). - -const common = require('../common'); -const assert = require('assert'); -const { register, registerHooks } = require('module'); -const fixtures = require('../common/fixtures'); -const { pathToFileURL } = require('url'); - -const redirectedPath = fixtures.path('module-hooks', 'redirected-assert.js'); - -// Register an async loader that provides source for CJS files, which triggers -// the re-invented require path. -register(fixtures.fileURL('module-hooks', 'logger-async-hooks.mjs')); - -const hook = registerHooks({ - resolve: common.mustCall((specifier, context, nextResolve) => { - if (specifier === 'test-require-resolve-hook-target') { - return { - url: pathToFileURL(redirectedPath).href, - shortCircuit: true, - }; - } - return nextResolve(specifier, context); - }, 2), -}); - -import('../fixtures/module-hooks/require-resolve-caller.js').then(common.mustCall((ns) => { - assert.strictEqual(ns.default.resolved, redirectedPath); - hook.deregister(); -})); diff --git a/test/node-api/test_async/test-loop.js b/test/node-api/test_async/test-loop.js index 1b05cbad4a50..221063e8a366 100644 --- a/test/node-api/test_async/test-loop.js +++ b/test/node-api/test_async/test-loop.js @@ -1,14 +1,23 @@ 'use strict'; const common = require('../../common'); const assert = require('assert'); +const dc = require('diagnostics_channel'); const test_async = require(`./build/${common.buildType}/test_async`); const iterations = 500; let x = 0; +const events = []; +const onThreadPoolWork = (event) => events.push(event); const workDone = common.mustCall((status) => { assert.strictEqual(status, 0); + if (x === 0) assert.strictEqual(events.length, 0); if (++x < iterations) { setImmediate(() => test_async.DoRepeatedWork(workDone)); + } else { + dc.unsubscribe('uv.threadpool.work.node_api', onThreadPoolWork); + assert.strictEqual(events.length, iterations - 1); } }, iterations); +// Subscribe after submission to verify subscription latching. test_async.DoRepeatedWork(workDone); +dc.subscribe('uv.threadpool.work.node_api', onThreadPoolWork); diff --git a/test/node-api/test_async/test.js b/test/node-api/test_async/test.js index 34ecae08e67f..03e02fcd5096 100644 --- a/test/node-api/test_async/test.js +++ b/test/node-api/test_async/test.js @@ -2,6 +2,7 @@ const common = require('../../common'); const assert = require('assert'); const child_process = require('child_process'); +const dc = require('diagnostics_channel'); const test_async = require(`./build/${common.buildType}/test_async`); const testException = 'test_async_cb_exception'; @@ -27,4 +28,12 @@ test_async.Test(5, {}, common.mustCall(function(err, val) { })); // Async work item cancellation with callback. -test_async.TestCancel(common.mustCall()); +const events = []; +const onThreadPoolWork = (event) => events.push(event); +dc.subscribe('uv.threadpool.work.node_api', onThreadPoolWork); +test_async.TestCancel(common.mustCall(() => { + dc.unsubscribe('uv.threadpool.work.node_api', onThreadPoolWork); + const event = events.find(({ started, ended }) => + started === null && ended === null); + assert.ok(event); +})); diff --git a/test/parallel/test-async-hooks-execution-async-resource-lazy.js b/test/parallel/test-async-hooks-execution-async-resource-lazy.js new file mode 100644 index 000000000000..c5270c4921ad --- /dev/null +++ b/test/parallel/test-async-hooks-execution-async-resource-lazy.js @@ -0,0 +1,27 @@ +// Flags: --expose-internals +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); +const { AsyncResource, executionAsyncResource } = require('async_hooks'); +const { internalBinding } = require('internal/test/binding'); +const { FSReqCallback } = internalBinding('fs'); +const { async_hook_fields, constants: { kLazyScopes } } = internalBinding('async_wrap'); + +// No hook and no executionAsyncResource() yet, so the scope of this callback skips the id stack. +// Asked for here, its resource comes off the chain of lazy scopes, and for an AsyncWrap the +// resource is held as a Global. +fs.stat(__filename, common.mustSucceed(() => { + assert.ok(async_hook_fields[kLazyScopes] > 0); + const resource = executionAsyncResource(); + assert.ok(resource instanceof FSReqCallback); + assert.strictEqual(executionAsyncResource(), resource); + + // A context pushed on the stack while the lazy scope is still open: the stack answers, not the + // chain. + const inner = new AsyncResource('TEST'); + inner.runInAsyncScope(common.mustCall(() => { + assert.strictEqual(executionAsyncResource(), inner); + })); + assert.strictEqual(executionAsyncResource(), resource); +})); diff --git a/test/parallel/test-bench-cli-reporters.js b/test/parallel/test-bench-cli-reporters.js index 31cee67aaa12..9bc775c7c472 100644 --- a/test/parallel/test-bench-cli-reporters.js +++ b/test/parallel/test-bench-cli-reporters.js @@ -125,16 +125,19 @@ for (const { file, status } of [ fixtures.path('bench-runner/a.cjs'), ]); assert.strictEqual(result.status, 0); - parseRecords(result); - assert.match(fs.readFileSync(destination, 'utf8'), - /^benchmark \| samples \| mean rate/); + const records = parseRecords(result); + assert.strictEqual(records[0].type, 'bench:environment'); + const output = fs.readFileSync(destination, 'utf8'); + assert.match(output, /^node: v\d+/); + assert.match(output, /^benchmark \| samples \| mean rate/m); } { const result = spawnBench([fixtures.path('bench-runner/a.cjs')]); assert.strictEqual(result.status, 0); assert.strictEqual(result.stderr, ''); - assert.match(result.stdout, /^benchmark \| samples \| mean rate/); + assert.match(result.stdout, /^node: v\d+/); + assert.match(result.stdout, /^benchmark \| samples \| mean rate/m); assert.match(result.stdout, /1 completed, 0 failed, 0 skipped/); } diff --git a/test/parallel/test-bench-do-not-optimize.js b/test/parallel/test-bench-do-not-optimize.js new file mode 100644 index 000000000000..015fa123aa0c --- /dev/null +++ b/test/parallel/test-bench-do-not-optimize.js @@ -0,0 +1,60 @@ +// Flags: --expose-gc --experimental-bench --no-warnings +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { Readable } = require('stream'); +const { createRunner, doNotOptimize } = require('node:bench'); +const { spec } = require('node:bench/reporters'); + +// The value is returned unchanged. +for (const value of [ + 0, -0, 1.5, NaN, Infinity, 1n, 'string', true, null, undefined, + Symbol('symbol'), {}, [], () => {}, +]) { + assert.ok(Object.is(doNotOptimize(value), value)); +} + +function result(name, median) { + return { + type: 'bench:complete', + data: { + name, + params: {}, + samples: [{}], + summary: { + mean: median, + median, + coefficientOfVariation: 0, + confidenceInterval: { lower: median, upper: median }, + skewness: 0, + }, + }, + }; +} + +(async () => { + // Values are released after the sample that produced them. + const runner = createRunner({ yieldBetweenSamples: false }); + let ref; + runner.bench('retained', { samples: 1, warmup: 0 }, common.mustCall((b) => { + const value = {}; + ref = new WeakRef(value); + b.start(); + doNotOptimize(value); + b.end(); + })); + await runner.run().toArray(); + await new Promise(setImmediate); + globalThis.gc(); + assert.strictEqual(ref.deref(), undefined); + + // The spec reporter flags median rates of at least one operation per + // nanosecond as implausible. + const output = (await Readable.from([ + result('plausible', 999_999_999), + result('implausible', 1e9), + ]).compose(spec).toArray()).join(''); + assert.match(output, /^plausible \|.* \| $/m); + assert.match(output, /^implausible \|.* \| implausible$/m); +})().then(common.mustCall()); diff --git a/test/parallel/test-bench-end-operations.js b/test/parallel/test-bench-end-operations.js new file mode 100644 index 000000000000..83a51512e1b7 --- /dev/null +++ b/test/parallel/test-bench-end-operations.js @@ -0,0 +1,91 @@ +// Flags: --experimental-bench --no-warnings +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { createRunner } = require('node:bench'); + +function waitForTick() { + const started = process.hrtime.bigint(); + while (process.hrtime.bigint() === started); +} + +const runner = createRunner({ yieldBetweenSamples: false }); + +runner.bench('default operations', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + b.start(); + waitForTick(); + const sample = b.end(); + assert.strictEqual(sample.operations, 1); + })); + +runner.bench('undefined operations with options', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + b.start(); + waitForTick(); + const sample = b.end(undefined, { detail: 'value' }); + assert.strictEqual(sample.operations, 1); + assert.strictEqual(sample.detail, 'value'); + })); + +const invalid = [0, -1, 0.5, NaN, Infinity, null, '1']; +for (const operations of invalid) { + runner.bench(`invalid ${String(operations)}`, { samples: 1, warmup: 0 }, + (b) => { + b.start(); + waitForTick(); + b.end(operations); + }); +} + +runner.bench('record default operations', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + const sample = b.record({ duration_ns: 10n }); + assert.strictEqual(sample.operations, 1); + assert.strictEqual(sample.rate, 100_000_000); + })); + +runner.bench('record undefined operations', { samples: 1, warmup: 0 }, + common.mustCall((b) => { + const sample = b.record({ duration_ns: 10n, operations: undefined }); + assert.strictEqual(sample.operations, 1); + })); + +for (const operations of invalid) { + runner.bench(`record invalid ${String(operations)}`, + { samples: 1, warmup: 0 }, + (b) => b.record({ duration_ns: 10n, operations })); +} + +(async () => { + const records = await runner.run().toArray(); + const byName = new Map(records + .filter(({ type }) => type === 'bench:complete') + .map(({ data }) => [data.name, data])); + + assert.deepStrictEqual( + byName.get('default operations').samples.map(({ operations }) => operations), + [1]); + assert.deepStrictEqual( + byName.get('undefined operations with options').samples + .map(({ operations }) => operations), + [1]); + + for (const name of ['record default operations', + 'record undefined operations']) { + assert.deepStrictEqual( + byName.get(name).samples.map(({ operations }) => operations), [1]); + } + + for (const operations of invalid) { + const code = typeof operations === 'number' ? + 'ERR_OUT_OF_RANGE' : 'ERR_INVALID_ARG_TYPE'; + for (const prefix of ['invalid', 'record invalid']) { + const { error, samples } = + byName.get(`${prefix} ${String(operations)}`); + assert.strictEqual(error.code, code); + assert.strictEqual(samples.length, 0); + } + } +})().then(common.mustCall()); diff --git a/test/parallel/test-bench-gc.js b/test/parallel/test-bench-gc.js new file mode 100644 index 000000000000..5c01cca86596 --- /dev/null +++ b/test/parallel/test-bench-gc.js @@ -0,0 +1,126 @@ +// Flags: --expose-gc --experimental-bench --no-warnings +'use strict'; + +const common = require('../common'); +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const fixtures = require('../common/fixtures'); +const { bench, createRunner } = require('node:bench'); + +const spawnTimeout = common.platformTimeout(30_000); +const fixture = fixtures.path('bench-runner/gc.cjs'); + +function spawnNode(args, env = undefined) { + const result = spawnSync(process.execPath, args, { + __proto__: null, + encoding: 'utf8', + env: { ...process.env, ...env }, + timeout: spawnTimeout, + }); + assert.ifError(result.error); + assert.strictEqual(result.signal, null); + return result; +} + +function parseRecords(output) { + return output.trim().split('\n').map((line) => JSON.parse(line)); +} + +function countForcedCollections(output) { + return output.split('\n').filter((line) => /^\[\d+:.*testing/.test(line)) + .length; +} + +// Invalid modes are rejected when declared or configured. +for (const gc of ['always', true, null]) { + assert.throws(() => bench('invalid', { gc }, () => {}), + { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => createRunner({ gc }), + { code: 'ERR_INVALID_ARG_VALUE' }); + assert.throws(() => createRunner().run({ gc }), + { code: 'ERR_INVALID_ARG_VALUE' }); +} + +(async () => { + // The effective mode is reported in the plan. run() overrides + // createRunner(), which overrides the benchmark option. + for (const { runner, run: runGc, expected } of [ + { expected: ['none', 'once', 'sample'] }, + { runner: 'sample', expected: ['sample', 'sample', 'sample'] }, + { runner: 'sample', run: 'none', expected: ['none', 'none', 'none'] }, + ]) { + const instance = createRunner({ gc: runner, yieldBetweenSamples: false }); + for (const gc of [undefined, 'once', 'sample']) { + instance.bench(`gc ${gc}`, { gc, samples: 2, warmup: 1 }, (b) => { + b.record({ duration_ns: 1n }); + }); + } + const records = await instance.run({ gc: runGc }).toArray(); + const plans = records.filter(({ type }) => type === 'bench:plan'); + assert.deepStrictEqual(plans.map(({ data }) => data.gc), expected); + const completions = records.filter(({ type }) => type === 'bench:complete'); + assert.deepStrictEqual( + completions.map(({ data }) => [data.error, data.samples.length]), + [[undefined, 2], [undefined, 2], [undefined, 2]]); + } + + // A forced collection runs once before the first measured sample for + // 'once', and before every measured sample for 'sample'. + for (const { args = [], env, expected } of [ + { expected: 0 }, + { env: { BENCH_GC_OPTION: 'once' }, expected: 1 }, + { env: { BENCH_GC_OPTION: 'sample' }, expected: 3 }, + { args: ['--bench-gc=once'], expected: 1 }, + { args: ['--bench-gc=none'], env: { BENCH_GC_OPTION: 'sample' }, + expected: 0 }, + ]) { + const result = spawnNode([ + '--expose-gc', '--trace-gc', '--no-warnings', '--experimental-bench', + '--bench', '--bench-isolation=none', '--bench-reporter=json', + '--bench-reporter-destination=stderr', ...args, fixture, + ], env); + assert.strictEqual(result.status, 0, result.stderr); + assert.strictEqual(countForcedCollections(result.stdout), expected); + } + + // Without --expose-gc, benchmarks that request collection fail. + { + const result = spawnNode([ + '--no-warnings', '--experimental-bench', '--bench', + '--bench-isolation=none', '--bench-reporter=json', + '--bench-reporter-destination=stdout', fixture, + ], { BENCH_GC_OPTION: 'once' }); + assert.strictEqual(result.status, 1); + const complete = parseRecords(result.stdout) + .find(({ type }) => type === 'bench:complete'); + assert.strictEqual(complete.data.error.code, 'ERR_INVALID_STATE'); + assert.match(complete.data.error.message, + /'once' gc mode requires the --expose-gc flag/); + } + + // With process isolation, --bench-gc exposes gc to the child process. + { + const result = spawnNode([ + '--no-warnings', '--experimental-bench', '--bench', '--bench-gc=sample', + '--bench-reporter=json', '--bench-reporter-destination=stdout', fixture, + ]); + assert.strictEqual(result.status, 0, result.stderr); + const records = parseRecords(result.stdout); + const plan = records.find(({ type }) => type === 'bench:plan'); + assert.strictEqual(plan.data.gc, 'sample'); + const complete = records.find(({ type }) => type === 'bench:complete'); + assert.strictEqual(complete.data.error, undefined); + assert.deepStrictEqual( + complete.data.samples.map(({ detail }) => detail), + ['function', 'function', 'function']); + } + + // Invalid --bench-gc values are rejected at startup. + { + const result = spawnNode([ + '--experimental-bench', '--bench', '--bench-gc=always', fixture, + ]); + assert.strictEqual(result.status, 9); + assert.match(result.stderr, /invalid value for --bench-gc/); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-bench-reporters.js b/test/parallel/test-bench-reporters.js index b5078a40de6b..09cde1d46b11 100644 --- a/test/parallel/test-bench-reporters.js +++ b/test/parallel/test-bench-reporters.js @@ -4,6 +4,7 @@ const common = require('../common'); const { completeSample } = require('../common/bench'); const assert = require('assert'); +const os = require('os'); const { Readable } = require('stream'); const { bench, run } = require('node:bench'); const { json, spec } = require('node:bench/reporters'); @@ -26,7 +27,25 @@ bench('json failed', { samples: 1 }, () => { const lines = chunks.join('').trim().split('\n'); const records = lines.map((line) => JSON.parse(line)); - assert.strictEqual(records.length, 8); + assert.strictEqual(records.length, 9); + const { type: environmentType, data: environment } = records[0]; + assert.strictEqual(environmentType, 'bench:environment'); + assert.strictEqual(environment.node, process.version); + assert.strictEqual(environment.v8, process.versions.v8); + assert.strictEqual(environment.platform, process.platform); + assert.strictEqual(environment.arch, process.arch); + assert.strictEqual(environment.os.type, os.type()); + assert.strictEqual(environment.os.release, os.release()); + assert.strictEqual(environment.os.machine, os.machine()); + assert.strictEqual( + environment.cpus.reduce((total, { count }) => total + count, 0), + os.cpus().length); + assert.strictEqual(environment.availableParallelism, + os.availableParallelism()); + assert.strictEqual(environment.memory.total, os.totalmem()); + assert.strictEqual(typeof environment.memory.free, 'number'); + assert.strictEqual(environment.loadavg.length, 3); + assert.deepStrictEqual(environment.execArgv, process.execArgv); const plans = records.filter(({ type }) => type === 'bench:plan'); assert.deepStrictEqual(plans.map(({ data }) => data.selected), [true, true]); const sample = records.find(({ type }) => type === 'bench:sample'); @@ -105,7 +124,18 @@ bench('json failed', { samples: 1 }, () => { }, ]; const specChunks = await Readable.from(synthetic).compose(spec).toArray(); - assert.strictEqual(specChunks.join(''), + const specOutput = specChunks.join(''); + const specHeaderEnd = specOutput.indexOf('\n\n') + 2; + const specHeader = specOutput.slice(0, specHeaderEnd); + assert.match(specHeader, + new RegExp(`^node: ${RegExp.escape(process.version)} ` + + `\\(V8 ${RegExp.escape(process.versions.v8)}\\), ` + + `${process.platform} ${process.arch} `)); + assert.match(specHeader, /^cpu: .*\(available parallelism: \d+\)$/m); + assert.match(specHeader, /^memory: [\d.]+ \w+ total, [\d.]+ \w+ free/m); + assert.match(specHeader, /^load average: [\d.]+, [\d.]+, [\d.]+$/m); + assert.match(specHeader, /^exec argv: --experimental-bench --no-warnings$/m); + assert.strictEqual(specOutput.slice(specHeaderEnd), 'benchmark | samples | mean rate | 95% CI | ' + 'median rate | warning\n' + 'fast [size="small"] | 2 | 1.50k ops/s | ' + @@ -123,7 +153,8 @@ bench('json failed', { samples: 1 }, () => { type: 'bench:diagnostic', data: { aggregate, circular }, }]).compose(json).toArray(); - const jsonEdge = JSON.parse(jsonEdgeChunks.join('')); + assert.strictEqual(jsonEdgeChunks.length, 2); + const jsonEdge = JSON.parse(jsonEdgeChunks[1]); assert.deepStrictEqual(jsonEdge.data.aggregate.errors, ['1']); assert.strictEqual(jsonEdge.data.circular.self, '[Circular]'); @@ -134,7 +165,10 @@ bench('json failed', { samples: 1 }, () => { for await (const chunk of json(undefinedRecord())) { undefinedChunks.push(chunk); } - assert.strictEqual(undefinedChunks.join(''), 'null\n'); + assert.strictEqual(undefinedChunks.length, 2); + assert.strictEqual(JSON.parse(undefinedChunks[0]).type, + 'bench:environment'); + assert.strictEqual(undefinedChunks[1], 'null\n'); function result(name, rate) { return { diff --git a/test/parallel/test-blob-file-backed.js b/test/parallel/test-blob-file-backed.js index c5a5ce14807d..769aa5642980 100644 --- a/test/parallel/test-blob-file-backed.js +++ b/test/parallel/test-blob-file-backed.js @@ -2,7 +2,6 @@ const common = require('../common'); const assert = require('assert'); -const { TextDecoder } = require('util'); const { writeFileSync, openAsBlob, diff --git a/test/parallel/test-buffer-isascii.js b/test/parallel/test-buffer-isascii.js index 48cc96a17d61..7fe32038757c 100644 --- a/test/parallel/test-buffer-isascii.js +++ b/test/parallel/test-buffer-isascii.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); const { isAscii, Buffer } = require('buffer'); -const { TextEncoder } = require('util'); const encoder = new TextEncoder(); diff --git a/test/parallel/test-buffer-isutf8.js b/test/parallel/test-buffer-isutf8.js index 151fc0baf4ae..f6efe95c8b27 100644 --- a/test/parallel/test-buffer-isutf8.js +++ b/test/parallel/test-buffer-isutf8.js @@ -3,7 +3,6 @@ require('../common'); const assert = require('assert'); const { isUtf8, Buffer } = require('buffer'); -const { TextEncoder } = require('util'); const encoder = new TextEncoder(); diff --git a/test/parallel/test-cli-eval.js b/test/parallel/test-cli-eval.js index 5b090279621f..660d308a8fb2 100644 --- a/test/parallel/test-cli-eval.js +++ b/test/parallel/test-cli-eval.js @@ -329,6 +329,14 @@ if (common.hasCrypto) { common.mustSucceed((stdout) => { assert.match(stdout, /[0-9a-f]{32}/i); })); + child.execFile(process.execPath, ['-e', 'console.log(typeof crypto.randomBytes) // comment'], + common.mustSucceed((stdout) => { + assert.strictEqual(stdout, 'function\n'); + })); + child.execFile(process.execPath, ['-p', 'typeof crypto.randomBytes // comment'], + common.mustSucceed((stdout) => { + assert.strictEqual(stdout, 'function\n'); + })); } // Assert that overriding crypto works. child.exec( diff --git a/test/parallel/test-compile-cache-api-env.js b/test/parallel/test-compile-cache-api-env.js index 197f1495a886..7504d7a1fd60 100644 --- a/test/parallel/test-compile-cache-api-env.js +++ b/test/parallel/test-compile-cache-api-env.js @@ -4,7 +4,7 @@ // with a NODE_COMPILE_CACHE environment variable override. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-api-flush.js b/test/parallel/test-compile-cache-api-flush.js index 7e66b1fee103..fb4c26ba1bb0 100644 --- a/test/parallel/test-compile-cache-api-flush.js +++ b/test/parallel/test-compile-cache-api-flush.js @@ -3,7 +3,7 @@ // This tests module.flushCompileCache() works as expected. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-api-options-portable-env.js b/test/parallel/test-compile-cache-api-options-portable-env.js index 5586e3e84046..d9f196d33045 100644 --- a/test/parallel/test-compile-cache-api-options-portable-env.js +++ b/test/parallel/test-compile-cache-api-options-portable-env.js @@ -4,7 +4,7 @@ // variable NODE_COMPILE_CACHE overrides. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-api-portable.js b/test/parallel/test-compile-cache-api-portable.js index 620b3bdce875..3ba390503c40 100644 --- a/test/parallel/test-compile-cache-api-portable.js +++ b/test/parallel/test-compile-cache-api-portable.js @@ -4,7 +4,7 @@ // and supports portable paths across directory relocations. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fs = require('fs'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-api-readonly.js b/test/parallel/test-compile-cache-api-readonly.js index 8ac0248a4d53..df91ee45e4b9 100644 --- a/test/parallel/test-compile-cache-api-readonly.js +++ b/test/parallel/test-compile-cache-api-readonly.js @@ -4,7 +4,7 @@ // entries are read, nothing is written, and a missing directory is not created. const common = require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); diff --git a/test/parallel/test-compile-cache-api-success.js b/test/parallel/test-compile-cache-api-success.js index 2d4d94fd6e9d..e8a5226f7b50 100644 --- a/test/parallel/test-compile-cache-api-success.js +++ b/test/parallel/test-compile-cache-api-success.js @@ -3,7 +3,7 @@ // This tests module.enableCompileCache() and module.getCompileCacheDir() work. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-api-tmpdir.js b/test/parallel/test-compile-cache-api-tmpdir.js index e676893b01f5..1d4cdbb242c7 100644 --- a/test/parallel/test-compile-cache-api-tmpdir.js +++ b/test/parallel/test-compile-cache-api-tmpdir.js @@ -4,7 +4,7 @@ // the TMPDIR environment variable override. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-bad-syntax.js b/test/parallel/test-compile-cache-bad-syntax.js index 63f6374b2c38..b868ad385e9d 100644 --- a/test/parallel/test-compile-cache-bad-syntax.js +++ b/test/parallel/test-compile-cache-bad-syntax.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works. require('../common'); -const { spawnSyncAndExit } = require('../common/child_process'); +const { spawnSyncAndExit } = require('../common/compile-cache'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); diff --git a/test/parallel/test-compile-cache-coverage.js b/test/parallel/test-compile-cache-coverage.js new file mode 100644 index 000000000000..f2f5e9e2f77f --- /dev/null +++ b/test/parallel/test-compile-cache-coverage.js @@ -0,0 +1,45 @@ +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const { spawnSyncAndAssert } = require('../common/child_process'); +const assert = require('assert'); +const fixtures = require('../common/fixtures'); +const fs = require('fs'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); +const cacheDir = tmpdir.resolve('compile_cache'); +const env = { + ...process.env, + NODE_DEBUG_NATIVE: 'COMPILE_CACHE', + NODE_V8_COVERAGE: tmpdir.resolve('coverage'), +}; + +spawnSyncAndAssert( + process.execPath, + [fixtures.path('empty.js')], + { env: { ...env, NODE_COMPILE_CACHE: cacheDir }, cwd: tmpdir.path }, + { stderr: /Disabled because V8 coverage is being collected/ }); +assert(!fs.existsSync(cacheDir)); + +spawnSyncAndAssert( + process.execPath, + ['-r', fixtures.path('compile-cache-wrapper.js'), fixtures.path('empty.js')], + { + env: { + ...env, + NODE_COMPILE_CACHE: undefined, + NODE_TEST_COMPILE_CACHE_DIR: cacheDir, + }, + cwd: tmpdir.path, + }, + { + stdout(output) { + assert.match(output, /Compile cache already disabled/); + assert.match(output, /dir after enableCompileCache: undefined/); + }, + stderr: /Disabled because V8 coverage is being collected/, + }); +assert(!fs.existsSync(cacheDir)); diff --git a/test/parallel/test-compile-cache-dynamic-import.js b/test/parallel/test-compile-cache-dynamic-import.js index 01731dc68225..757e992eaa88 100644 --- a/test/parallel/test-compile-cache-dynamic-import.js +++ b/test/parallel/test-compile-cache-dynamic-import.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works in existing directory. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-esm.js b/test/parallel/test-compile-cache-esm.js index 963de8bcaba2..9bddc23424c2 100644 --- a/test/parallel/test-compile-cache-esm.js +++ b/test/parallel/test-compile-cache-esm.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works in existing directory. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-existing-directory.js b/test/parallel/test-compile-cache-existing-directory.js index 0fc60f9544d5..d9c7e690fd50 100644 --- a/test/parallel/test-compile-cache-existing-directory.js +++ b/test/parallel/test-compile-cache-existing-directory.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works in existing directory. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fs = require('fs'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-portable-esm.js b/test/parallel/test-compile-cache-portable-esm.js index 18766b6810ea..bfcb6f9e2da5 100644 --- a/test/parallel/test-compile-cache-portable-esm.js +++ b/test/parallel/test-compile-cache-portable-esm.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works after moving directory and unusual characters in path are handled correctly. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fs = require('fs'); diff --git a/test/parallel/test-compile-cache-portable.js b/test/parallel/test-compile-cache-portable.js index b5978b5b0c62..04b7360833ca 100644 --- a/test/parallel/test-compile-cache-portable.js +++ b/test/parallel/test-compile-cache-portable.js @@ -4,7 +4,7 @@ // environment variable. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fs = require('fs'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-success.js b/test/parallel/test-compile-cache-success.js index c02a62432869..4d5d7a67214a 100644 --- a/test/parallel/test-compile-cache-success.js +++ b/test/parallel/test-compile-cache-success.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-typescript-commonjs.js b/test/parallel/test-compile-cache-typescript-commonjs.js index 60e86c3c0f9d..5ee65a806e67 100644 --- a/test/parallel/test-compile-cache-typescript-commonjs.js +++ b/test/parallel/test-compile-cache-typescript-commonjs.js @@ -6,7 +6,7 @@ const common = require('../common'); if (!process.config.variables.node_use_amaro) { common.skip('Requires Amaro'); } -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-typescript-esm.js b/test/parallel/test-compile-cache-typescript-esm.js index 98473dbb2a5b..e85f442e5ac1 100644 --- a/test/parallel/test-compile-cache-typescript-esm.js +++ b/test/parallel/test-compile-cache-typescript-esm.js @@ -6,7 +6,7 @@ const common = require('../common'); if (!process.config.variables.node_use_amaro) { common.skip('Requires Amaro'); } -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-typescript-strip-sourcemaps.js b/test/parallel/test-compile-cache-typescript-strip-sourcemaps.js index a6c95e432b78..f229587c1f26 100644 --- a/test/parallel/test-compile-cache-typescript-strip-sourcemaps.js +++ b/test/parallel/test-compile-cache-typescript-strip-sourcemaps.js @@ -7,7 +7,7 @@ const common = require('../common'); if (!process.config.variables.node_use_amaro) { common.skip('Requires Amaro'); } -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-compile-cache-updated-file.js b/test/parallel/test-compile-cache-updated-file.js index 68f20a6990cc..c3fecae97f0f 100644 --- a/test/parallel/test-compile-cache-updated-file.js +++ b/test/parallel/test-compile-cache-updated-file.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works in existing directory. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const fs = require('fs'); const tmpdir = require('../common/tmpdir'); diff --git a/test/parallel/test-compile-cache-wasm.js b/test/parallel/test-compile-cache-wasm.js index 278198378dd2..31019b33892f 100644 --- a/test/parallel/test-compile-cache-wasm.js +++ b/test/parallel/test-compile-cache-wasm.js @@ -3,7 +3,7 @@ // This tests NODE_COMPILE_CACHE works for WebAssembly modules imported as ESM. require('../common'); -const { spawnSyncAndAssert } = require('../common/child_process'); +const { spawnSyncAndAssert } = require('../common/compile-cache'); const assert = require('assert'); const tmpdir = require('../common/tmpdir'); const fixtures = require('../common/fixtures'); diff --git a/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js b/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js index 3f0dbc73ba5d..9aae5cacbfc1 100644 --- a/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js +++ b/test/parallel/test-crypto-pqc-key-objects-slh-dsa.js @@ -107,13 +107,21 @@ for (const asymmetricKeyType of [ assert.throws(() => createPrivateKey(keys.private), { code: isBoringSSL ? 'ERR_OSSL_EVP_UNSUPPORTED_ALGORITHM' : 'ERR_OSSL_UNSUPPORTED', }); - } else { - const publicKey = createPublicKey(keys.public); + } + + const supported = hasOpenSSL(3, 5) || + (isBoringSSL && (asymmetricKeyType === 'slh-dsa-sha2-128s' || + asymmetricKeyType === 'slh-dsa-shake-256f')); + if (supported) { + const publicKey = createPublicKey(isBoringSSL ? + { format: 'jwk', key: keys.jwk } : keys.public); + const privateKey = createPrivateKey(isBoringSSL ? + { format: 'jwk', key: keys.jwk } : keys.private); assertPublicKey(publicKey); - const pubFromPriv = createPublicKey(keys.private); + const pubFromPriv = createPublicKey(isBoringSSL ? privateKey : keys.private); assertPublicKey(pubFromPriv); - assertPrivateKey(createPrivateKey(keys.private)); + assertPrivateKey(privateKey); assert.strictEqual(pubFromPriv.equals(publicKey), true); // JWK import error tests diff --git a/test/parallel/test-crypto-pqc-keygen-slh-dsa.js b/test/parallel/test-crypto-pqc-keygen-slh-dsa.js index a8e480818cd1..2d3fc3c578bf 100644 --- a/test/parallel/test-crypto-pqc-keygen-slh-dsa.js +++ b/test/parallel/test-crypto-pqc-keygen-slh-dsa.js @@ -4,31 +4,27 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); -const { hasOpenSSL } = require('../common/crypto'); +const { hasOpenSSL, isBoringSSL } = require('../common/crypto'); const assert = require('assert'); const { generateKeyPair, } = require('crypto'); -if (!hasOpenSSL(3, 5)) { - for (const asymmetricKeyType of [ - 'slh-dsa-sha2-128f', 'slh-dsa-sha2-128s', 'slh-dsa-sha2-192f', 'slh-dsa-sha2-192s', - 'slh-dsa-sha2-256f', 'slh-dsa-sha2-256s', 'slh-dsa-shake-128f', 'slh-dsa-shake-128s', - 'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s', - ]) { +for (const asymmetricKeyType of [ + 'slh-dsa-sha2-128f', 'slh-dsa-sha2-128s', 'slh-dsa-sha2-192f', 'slh-dsa-sha2-192s', + 'slh-dsa-sha2-256f', 'slh-dsa-sha2-256s', 'slh-dsa-shake-128f', 'slh-dsa-shake-128s', + 'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s', +]) { + const supported = hasOpenSSL(3, 5) || + (isBoringSSL && (asymmetricKeyType === 'slh-dsa-sha2-128s' || + asymmetricKeyType === 'slh-dsa-shake-256f')); + if (!supported) { assert.throws(() => generateKeyPair(asymmetricKeyType, common.mustNotCall()), { code: 'ERR_INVALID_ARG_VALUE', message: /The argument 'type' must be a supported key type/ }); - } -} else { - for (const asymmetricKeyType of [ - 'slh-dsa-sha2-128f', 'slh-dsa-sha2-128s', 'slh-dsa-sha2-192f', 'slh-dsa-sha2-192s', - 'slh-dsa-sha2-256f', 'slh-dsa-sha2-256s', 'slh-dsa-shake-128f', 'slh-dsa-shake-128s', - 'slh-dsa-shake-192f', 'slh-dsa-shake-192s', 'slh-dsa-shake-256f', 'slh-dsa-shake-256s', - ]) { - + } else { function assertJwk(jwk) { assert.strictEqual(jwk.kty, 'AKP'); // SLH-DSA algorithm names keep the last character (f/s) lowercase. diff --git a/test/parallel/test-datetime-change-notify.js b/test/parallel/test-datetime-change-notify.js index 018435119070..95f0ff9db2eb 100644 --- a/test/parallel/test-datetime-change-notify.js +++ b/test/parallel/test-datetime-change-notify.js @@ -25,8 +25,8 @@ const cases = [ expected: /Pacific (?:Standard|Daylight) Time/, }, { - timeZone: 'Europe/Dublin', - expected: /Irish Standard Time|Greenwich Mean Time/, + timeZone: 'Europe/Amsterdam', + expected: /Central European (?:Standard|Summer) Time/, }, ]; diff --git a/test/parallel/test-debugger-probe-attach-invalid.js b/test/parallel/test-debugger-probe-attach-invalid.js new file mode 100644 index 000000000000..36fa5b231bb9 --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-invalid.js @@ -0,0 +1,17 @@ +// Tests that probe mode rejects invalid --pid, --host and --port usage. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const { assertProbeCliError } = require('../common/debugger-probe'); + +const probe = ['--probe', 'app.js:1', '--expr', 'x']; + +assertProbeCliError([...probe, '--pid', '123', 'app.js'], /--pid and --host cannot be used together with an entry point script/); +assertProbeCliError([...probe, '--host', '127.0.0.1', 'app.js'], /--pid and --host cannot be used together with an entry point script/); + +assertProbeCliError([...probe, '--port', '0'], /Cannot attach to port 0/); +assertProbeCliError(probe, + /Probe mode requires an entry point script, or --pid, --port or --host to attach to a running process/); +assertProbeCliError([...probe, '--pid', 'abc'], /Invalid pid: abc/); diff --git a/test/parallel/test-debugger-probe-attach-pause-early.js b/test/parallel/test-debugger-probe-attach-pause-early.js new file mode 100644 index 000000000000..ee9181175545 --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-pause-early.js @@ -0,0 +1,28 @@ +// Tests that a target pausing at a breakpoint while the session is still binding the next one +// still works. The pause should be handled once all the probes are bound. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const fixtures = require('../common/fixtures'); +const { runAttachedProbe } = require('../common/debugger-probe'); + +// Line 5 runs continuously, so the breakpoint pauses the target before line 10 is bound. +runAttachedProbe('probe-attach-busy.js', [ + '--probe', 'probe-attach-busy.js:5', '--expr', 'typeof count', '--max-hit', '1', + '--probe', 'probe-attach-busy.js:10', '--expr', '1', +], { + status: 0, + report: { + v: 2, + probes: [ + { expr: 'typeof count', target: { suffix: 'probe-attach-busy.js', line: 5 }, maxHit: 1 }, + { expr: '1', target: { suffix: 'probe-attach-busy.js', line: 10 } }, + ], + results: [{ + probe: 0, event: 'hit', hit: 1, result: { type: 'string', value: 'number' }, + location: { url: fixtures.fileURL('debugger', 'probe-attach-busy.js').href, line: 5, column: 3 }, + }, { event: 'completed' }], + }, +}).then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-attach-refused.js b/test/parallel/test-debugger-probe-attach-refused.js new file mode 100644 index 000000000000..d5da1330409d --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-refused.js @@ -0,0 +1,39 @@ +// Tests attach failures result in an error instead of a report. Without --pid the target +// should already be listening, so a failed connection should be an immediate error. +// An inspector that belongs to another process should be rejected. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const net = require('net'); +const { once } = require('events'); +const { runProbe, startTarget } = require('../common/debugger-probe'); + +async function main() { + // Create a port that will refuse connections. + const server = net.createServer((socket) => socket.resetAndDestroy()); + await once(server.listen(0, '127.0.0.1'), 'listening'); + const { port } = server.address(); + + await runProbe(['--probe', 'app.js:1', '--expr', '1', '--port', `${port}`], { + status: 1, + report: null, + stderr: new RegExp(`Could not attach to 127\\.0\\.0\\.1:${port}: `), + }); + server.close(); + + const other = await startTarget('probe-attach-loop.js'); + const target = await startTarget('probe-attach-loop.js', { args: ['--inspect-port=0'] }); + await runProbe(['--probe', 'app.js:1', '--expr', '1', '--pid', `${target.child.pid}`, '--port', `${other.port}`], { + target, + status: 1, + report: null, + stderr: new RegExp(`The inspector at 127\\.0\\.0\\.1:${other.port} belongs to process ${other.child.pid}, ` + + `not to --pid ${target.child.pid}\\.`), + }); + other.child.kill(); + target.child.kill(); +} + +main().then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-attach-startup-timeout.js b/test/parallel/test-debugger-probe-attach-startup-timeout.js new file mode 100644 index 000000000000..0f490c9da968 --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-startup-timeout.js @@ -0,0 +1,28 @@ +// Tests that --timeout limits the startup of an attach session when the main thread of +// the target is blocked and does not answer Runtime.enable. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const { runAttachedProbe } = require('../common/debugger-probe'); + +runAttachedProbe('probe-attach-blocked.js', [ + '--timeout', '1000', '--probe', 'probe-attach-blocked.js:5', '--expr', '1', +], { + status: 1, + report: { + v: 2, + probes: [{ expr: '1', target: { suffix: 'probe-attach-blocked.js', line: 5 }, locations: [] }], + results: [{ + event: 'error', + error: { + code: 'probe_failure', + message: 'Timed out after 1000ms waiting for the target to respond before probes: probe-attach-blocked.js:5. ' + + 'Its main thread may be blocked in synchronous work. Try increasing `--timeout`.', + details: { lastCdpMethod: 'Runtime.enable' }, + }, + pending: [0], + }], + }, +}).then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-attach-target-completes.js b/test/parallel/test-debugger-probe-attach-target-completes.js new file mode 100644 index 000000000000..2649ea44f455 --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-target-completes.js @@ -0,0 +1,38 @@ +// Tests that an attach session exits normally when the target finishes on its own, instead of +// waiting for --timeout. Probes that never are hit should be reported as missed. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const assert = require('assert'); +const fixtures = require('../common/fixtures'); +const { runProbe, startTarget } = require('../common/debugger-probe'); + +async function main() { + const target = await startTarget('probe-attach-finishes.js'); + // Closing its stdin makes the target run line 5 once and exit. Line 11 only runs at startup. + await runProbe([ + '--probe', 'probe-attach-finishes.js:5', '--expr', 'count', + '--probe', 'probe-attach-finishes.js:11', '--expr', '1', + '--host', target.host, '--port', `${target.port}`, + ], { + target, + onStarted: () => target.child.stdin.end(), + status: 0, + report: { + v: 2, + probes: [ + { expr: 'count', target: { suffix: 'probe-attach-finishes.js', line: 5 } }, + { expr: '1', target: { suffix: 'probe-attach-finishes.js', line: 11 } }, + ], + results: [{ + probe: 0, event: 'hit', hit: 1, result: { type: 'number', value: 0, description: '0' }, + location: { url: fixtures.fileURL('debugger', 'probe-attach-finishes.js').href, line: 5, column: 3 }, + }, { event: 'miss', pending: [1] }], + }, + }); + assert.deepStrictEqual(await target.exited, { code: 0, signal: null }); +} + +main().then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-attach-target-crashes.js b/test/parallel/test-debugger-probe-attach-target-crashes.js new file mode 100644 index 000000000000..df84532653f3 --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-target-crashes.js @@ -0,0 +1,61 @@ +// Tests that if the target is terminated by an uncaught exception, the attach session reports +// probe_target_exit with the exception, instead of as completed. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const assert = require('assert'); +const fixtures = require('../common/fixtures'); +const { runProbe, startTarget } = require('../common/debugger-probe'); + +const url = fixtures.fileURL('debugger', 'probe-attach-finishes.js').href; +const path = fixtures.path('debugger', 'probe-attach-finishes.js'); + +async function main() { + const target = await startTarget('probe-attach-finishes.js', { env: { PROBE_ATTACH_THROW: '1' } }); + // Closing its stdin makes the target run line 5 once and throw. Line 11 only runs at startup. + await runProbe([ + '--probe', 'probe-attach-finishes.js:5', '--expr', 'count', + '--probe', 'probe-attach-finishes.js:11', '--expr', '1', + '--host', target.host, '--port', `${target.port}`, + ], { + target, + onStarted: () => target.child.stdin.end(), + status: 0, + report: { + v: 2, + probes: [ + { expr: 'count', target: { suffix: 'probe-attach-finishes.js', line: 5 } }, + { expr: '1', target: { suffix: 'probe-attach-finishes.js', line: 11 } }, + ], + results: [{ + probe: 0, event: 'hit', hit: 1, result: { type: 'number', value: 0, description: '0' }, + location: { url, line: 5, column: 3 }, + }, { + event: 'error', + pending: [1], + error: { + code: 'probe_target_exit', + message: 'Target exited with an uncaught exception before probes: probe-attach-finishes.js:11', + details: { + exception: { + exceptionId: 1, + text: 'Uncaught', + lineNumber: 5, + columnNumber: 37, + scriptId: '<scriptId>', + url: path, + stackTrace: { callFrames: '<callFrames>' }, + exception: { type: 'object', subtype: 'error', description: 'Error: boom\n<stack>' }, + executionContextId: 1, + }, + }, + }, + }], + }, + }); + assert.deepStrictEqual(await target.exited, { code: 1, signal: null }); +} + +main().then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-attach-timeout.js b/test/parallel/test-debugger-probe-attach-timeout.js new file mode 100644 index 000000000000..22a0daec63ae --- /dev/null +++ b/test/parallel/test-debugger-probe-attach-timeout.js @@ -0,0 +1,37 @@ +// Tests that an attach session without --max-hit ends at --timeout with exit code 0. +// It should list the probes that are never hit. The `locations` distinguish a probe +// that does not get hit from a probe that does not match any script. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const fixtures = require('../common/fixtures'); +const { runAttachedProbe } = require('../common/debugger-probe'); + +const timeout = common.platformTimeout(2000); + +// Line 10 only runs at startup. +runAttachedProbe('probe-attach-loop.js', [ + '--timeout', `${timeout}`, + '--probe', 'probe-attach-loop.js:10', '--expr', '1', + '--probe', 'no-such-file.js:14', '--expr', '1', +], { + status: 0, + report: { + v: 2, + probes: [{ + expr: '1', target: { suffix: 'probe-attach-loop.js', line: 10 }, + locations: [{ url: fixtures.fileURL('debugger', 'probe-attach-loop.js').href, line: 10, column: 1 }], + }, { expr: '1', target: { suffix: 'no-such-file.js', line: 14 }, locations: [] }], + results: [{ + event: 'timeout', + pending: [0, 1], + error: { + code: 'probe_timeout', + message: `Session timed out after ${timeout}ms waiting for probes: probe-attach-loop.js:10, ` + + 'no-such-file.js:14, detaching from the target', + }, + }], + }, +}).then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-attach.js b/test/parallel/test-debugger-probe-attach.js new file mode 100644 index 000000000000..8643b2d5e88b --- /dev/null +++ b/test/parallel/test-debugger-probe-attach.js @@ -0,0 +1,56 @@ +// Tests a --host/--port attach session that hits a probe in a script loaded before it attached, +// and ends at --max-hit. The target should continue running, so a second session can still attach +// to it. Killing the target during that session is reported as a probe failure, because without +// --pid an exit cannot be distinguished from a network failure. +'use strict'; +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const fixtures = require('../common/fixtures'); +const { runProbe, startTarget } = require('../common/debugger-probe'); + +const url = fixtures.fileURL('debugger', 'probe-attach-loop.js').href; +const location = { url, line: 6, column: 3 }; +const hit = (n) => ({ probe: 0, event: 'hit', hit: n, location, result: { type: 'string', value: 'number' } }); + +async function main() { + const target = await startTarget('probe-attach-loop.js'); + const attachArgs = ['--host', target.host, '--port', `${target.port}`]; + await runProbe(['--probe', 'probe-attach-loop.js:6', '--expr', 'typeof count', '--max-hit', '2', ...attachArgs], { + target, + status: 0, + report: { + v: 2, + target: { host: target.host, port: target.port }, + probes: [{ + expr: 'typeof count', target: { suffix: 'probe-attach-loop.js', line: 6 }, maxHit: 2, locations: [location], + }], + results: [hit(1), hit(2), { event: 'completed' }], + }, + }); + + // Line 10 only runs at startup, so this session should wait until the target is killed. + await runProbe(['--probe', 'probe-attach-loop.js:10', '--expr', '1', ...attachArgs], { + target, + onStarted: () => target.child.kill('SIGKILL'), + status: 1, + report: { + v: 2, + probes: [{ + expr: '1', target: { suffix: 'probe-attach-loop.js', line: 10 }, locations: [{ url, line: 10, column: 1 }], + }], + results: [{ + event: 'error', + pending: [0], + error: { + code: 'probe_failure', + message: 'Inspector connection lost before probes: probe-attach-loop.js:10. The target was likely ' + + "terminated externally. If the failure persists, check the target's process environment.", + }, + }], + }, + }); + await target.exited; +} + +main().then(common.mustCall()); diff --git a/test/parallel/test-debugger-probe-bound-never-hit.js b/test/parallel/test-debugger-probe-bound-never-hit.js index cc3ef278d27f..f0da697e9b20 100644 --- a/test/parallel/test-debugger-probe-bound-never-hit.js +++ b/test/parallel/test-debugger-probe-bound-never-hit.js @@ -1,4 +1,5 @@ // Tests that probing an unreachable line produces a `miss` with no hit events. +// The probe should be bound successfully, so the report should show its resolved location. 'use strict'; const common = require('../common'); @@ -9,6 +10,7 @@ const { spawnSyncAndAssert } = require('../common/child_process'); const { assertProbeJson } = require('../common/debugger-probe'); const cwd = fixtures.path('debugger'); +const fixtureUrl = fixtures.fileURL('debugger', 'probe-bound-never-hit.js').href; spawnSyncAndAssert(process.execPath, [ 'inspect', @@ -23,6 +25,7 @@ spawnSyncAndAssert(process.execPath, [ probes: [{ expr: '1', target: { suffix: 'probe-bound-never-hit.js', line: 4 }, + locations: [{ url: fixtureUrl, line: 4, column: 3 }], }], results: [{ event: 'miss', diff --git a/test/parallel/test-debugger-probe-json.js b/test/parallel/test-debugger-probe-json.js index f0808d1f6259..901f91941079 100644 --- a/test/parallel/test-debugger-probe-json.js +++ b/test/parallel/test-debugger-probe-json.js @@ -27,10 +27,13 @@ spawnSyncAndAssert(process.execPath, [ stdout(output) { assertProbeJson(output, { v: 2, + target: { argv: ['probe.js'] }, + // The script is parsed after the breakpoints are bound, so the locations + // come from the resolution reported from parsing the script. probes: [ - { expr: 'index', target: { suffix: 'probe.js', line: 8 } }, - { expr: 'total', target: { suffix: 'probe.js', line: 8 } }, - { expr: 'finalValue', target: { suffix: 'probe.js', line: 12 } }, + { expr: 'index', target: { suffix: 'probe.js', line: 8 }, locations: [locationAt8] }, + { expr: 'total', target: { suffix: 'probe.js', line: 8 }, locations: [locationAt8] }, + { expr: 'finalValue', target: { suffix: 'probe.js', line: 12 }, locations: [locationAt12] }, ], results: [ { diff --git a/test/parallel/test-debugger-probe-late-resolution.js b/test/parallel/test-debugger-probe-late-resolution.js index a66dd15a15f3..ca443834dbd5 100644 --- a/test/parallel/test-debugger-probe-late-resolution.js +++ b/test/parallel/test-debugger-probe-late-resolution.js @@ -26,8 +26,16 @@ spawnSyncAndAssert(process.execPath, [ assertProbeJson(output, { v: 2, probes: [ - { expr: 'value', target: { suffix: 'probe-late-target.mjs', line: 3 } }, - { expr: 'value', target: { suffix: 'probe-late-target.cjs', line: 5 } }, + { + expr: 'value', + target: { suffix: 'probe-late-target.mjs', line: 3 }, + locations: [{ url: esmUrl, line: 3, column: 3 }], + }, + { + expr: 'value', + target: { suffix: 'probe-late-target.cjs', line: 5 }, + locations: [{ url: cjsUrl, line: 5, column: 3 }], + }, ], results: [ { diff --git a/test/parallel/test-debugger-probe-miss.js b/test/parallel/test-debugger-probe-miss.js index 99ccbd72a4d8..8660b17638c4 100644 --- a/test/parallel/test-debugger-probe-miss.js +++ b/test/parallel/test-debugger-probe-miss.js @@ -1,4 +1,5 @@ -// This tests that probe sessions report unresolved breakpoints as misses. +// Tests that when breakpoints that are not resolved for a probe session should be +// reported as misses with an empty array as its locations. 'use strict'; const common = require('../common'); @@ -22,6 +23,7 @@ spawnSyncAndAssert(process.execPath, [ probes: [{ expr: '42', target: { suffix: 'probe-miss.js', line: 99 }, + locations: [], }], results: [{ event: 'miss', diff --git a/test/parallel/test-debugger-probe-startup-disconnect.js b/test/parallel/test-debugger-probe-startup-disconnect.js index 68c8432dc552..dfcfccaa7bd4 100644 --- a/test/parallel/test-debugger-probe-startup-disconnect.js +++ b/test/parallel/test-debugger-probe-startup-disconnect.js @@ -22,7 +22,7 @@ client.callMethod = common.mustCall((method) => { setImmediate(() => client.emit('close')); return new Promise(() => {}); }); -client.reset = common.mustCall(); +client.reset = common.mustCallAtLeast(); const session = new ProbeInspectorSession({ childArgv: ['-e', ''], @@ -30,6 +30,7 @@ const session = new ProbeInspectorSession({ port: 0, probes: [probe], skipPortPreflight: true, + timeout: 30000, }); session.client = client; diff --git a/test/parallel/test-dgram-negative-zero.js b/test/parallel/test-dgram-negative-zero.js new file mode 100644 index 000000000000..a59fc93a5a26 --- /dev/null +++ b/test/parallel/test-dgram-negative-zero.js @@ -0,0 +1,12 @@ +'use strict'; + +const common = require('../common'); +const dgram = require('dgram'); + +const socket = dgram.createSocket('udp4'); + +socket.bind(0, common.mustCall(() => { + socket.setRecvBufferSize(-0); + socket.setSendBufferSize(-0); + socket.close(); +})); diff --git a/test/parallel/test-diagnostics-channel-http2-client-request-headers.js b/test/parallel/test-diagnostics-channel-http2-client-request-headers.js new file mode 100644 index 000000000000..8287d3daa7ba --- /dev/null +++ b/test/parallel/test-diagnostics-channel-http2-client-request-headers.js @@ -0,0 +1,234 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const { once } = require('events'); +const dc = require('diagnostics_channel'); +const http2 = require('http2'); + +const kPublishCount = 8; + +let currentSession; +let injection; + +dc.subscribe('http2.client.request.headers', common.mustCall(({ headers, session }) => { + assert.strictEqual(session, currentSession); + assert.strictEqual(session.constructor.name, 'ClientHttp2Session'); + assert.ok(!!headers && typeof headers === 'object'); + if (injection !== undefined) + injection(headers); +}, kPublishCount)); + +function doRequest(client, headers) { + return new Promise((resolve, reject) => { + const stream = client.request(headers); + stream.setEncoding('utf8'); + let body = ''; + stream.on('data', (chunk) => { body += chunk; }); + stream.on('end', () => resolve(JSON.parse(body))); + stream.on('error', reject); + }); +} + +async function main() { + const server = http2.createServer(); + server.on('stream', (stream, headers) => { + // Echo the received request headers back in the response body. + stream.respond({ 'content-type': 'application/json' }); + stream.end(JSON.stringify(headers)); + }); + server.listen(0); + await once(server, 'listening'); + const port = server.address().port; + + // Scenario 1: request() called while the session is still connecting, + // with an object headers argument. + { + const client = http2.connect(`http://localhost:${port}`); + currentSession = client; + injection = (headers) => { + headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'; + }; + // Also make sure the snapshot published to 'http2.client.stream.created' + // reflects the injected header, since serialization happens after the + // 'http2.client.request.headers' publish. + const onCreated = common.mustCall(({ headers }) => { + assert.strictEqual( + headers.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + }, 1); + dc.subscribe('http2.client.stream.created', onCreated); + const origHeaders = { ':path': '/connecting' }; + const received = await doRequest(client, origHeaders); + dc.unsubscribe('http2.client.stream.created', onCreated); + assert.strictEqual( + received.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + assert.strictEqual(received[':path'], '/connecting'); + // The subscriber mutates a copy, so the caller's object is unchanged. + assert.deepStrictEqual(origHeaders, { ':path': '/connecting' }); + client.close(); + await once(client, 'close'); + } + + // Scenario 2: request() called on an already-connected session. + { + const client = http2.connect(`http://localhost:${port}`); + await once(client, 'connect'); + currentSession = client; + injection = (headers) => { + headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-b7ad6b7169203331-01'; + }; + const received = await doRequest(client, { ':path': '/connected' }); + assert.strictEqual( + received.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-b7ad6b7169203331-01'); + assert.strictEqual(received[':path'], '/connected'); + client.close(); + await once(client, 'close'); + } + + // Scenario 3: no headers argument at all. The subscriber must still be + // able to inject headers into the fresh object that is published. + { + const client = http2.connect(`http://localhost:${port}`); + currentSession = client; + let sawFreshObject; + injection = (headers) => { + sawFreshObject = headers[':path'] === undefined; + headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'; + }; + const received = await doRequest(client); + assert.ok(sawFreshObject); + assert.strictEqual( + received.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + assert.strictEqual(received[':path'], '/'); + client.close(); + await once(client, 'close'); + } + + // Scenario 4: a subscriber that does not mutate the headers must have no + // effect on the request. + { + const client = http2.connect(`http://localhost:${port}`); + await once(client, 'connect'); + currentSession = client; + injection = undefined; + const received = await doRequest(client, { + ':path': '/no-mutation', + 'x-test': 'value', + }); + assert.strictEqual(received.traceparent, undefined); + assert.deepStrictEqual(received, { + ':method': 'GET', + ':scheme': 'http', + ':authority': `localhost:${port}`, + ':path': '/no-mutation', + 'x-test': 'value', + }); + client.close(); + await once(client, 'close'); + } + + // Scenario 5: an array of raw headers can be mutated in place. + { + const client = http2.connect(`http://localhost:${port}`); + currentSession = client; + const origHeaders = [':path', '/array']; + let sawArray; + injection = (headers) => { + sawArray = Array.isArray(headers); + headers.push('traceparent', '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + }; + const received = await doRequest(client, origHeaders); + assert.ok(sawArray); + assert.strictEqual( + received.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + assert.strictEqual(received[':path'], '/array'); + // The subscriber mutates a copy, so the caller's array is unchanged. + assert.deepStrictEqual(origHeaders, [':path', '/array']); + client.close(); + await once(client, 'close'); + } + + // Scenario 6: injected headers go through the same validation as headers + // passed directly to request(). Injecting an unknown pseudo-header throws + // the same error that passing it directly would. + { + const client = http2.connect(`http://localhost:${port}`); + currentSession = client; + injection = (headers) => { + headers[':foo'] = 'invalid'; + }; + assert.throws(() => client.request({ ':path': '/invalid' }), + { code: 'ERR_HTTP2_INVALID_PSEUDOHEADER' }); + injection = undefined; + client.destroy(); + } + + // Scenario 7: sensitiveHeaders is preserved on the published copy, in + // object form, and mutating it does not touch the caller's list. + { + const client = http2.connect(`http://localhost:${port}`); + currentSession = client; + const origHeaders = { + ':path': '/sensitive', + 'authorization': 'secret', + [http2.sensitiveHeaders]: ['authorization'], + }; + let sawSensitive; + injection = (headers) => { + sawSensitive = headers[http2.sensitiveHeaders]?.slice(); + headers[http2.sensitiveHeaders].push('traceparent'); + headers.traceparent = '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'; + }; + const received = await doRequest(client, origHeaders); + assert.strictEqual( + received.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + assert.deepStrictEqual(sawSensitive, ['authorization']); + assert.deepStrictEqual(origHeaders, { + ':path': '/sensitive', + 'authorization': 'secret', + [http2.sensitiveHeaders]: ['authorization'], + }); + client.close(); + await once(client, 'close'); + } + + // Scenario 8: same as scenario 7, in raw array form. + { + const client = http2.connect(`http://localhost:${port}`); + currentSession = client; + const origHeaders = [':path', '/sensitive-array', 'authorization', 'secret']; + origHeaders[http2.sensitiveHeaders] = ['authorization']; + let sawArray; + let sawSensitive; + injection = (headers) => { + sawArray = Array.isArray(headers); + sawSensitive = headers[http2.sensitiveHeaders]?.slice(); + headers[http2.sensitiveHeaders].push('traceparent'); + headers.push('traceparent', '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + }; + const received = await doRequest(client, origHeaders); + assert.strictEqual( + received.traceparent, + '00-0af7651916cd43dd8f8ba5c1d1f77f0f-00f067aa0ba902b7-01'); + assert.ok(sawArray); + assert.deepStrictEqual(sawSensitive, ['authorization']); + assert.strictEqual(origHeaders.length, 4); + assert.deepStrictEqual(origHeaders[http2.sensitiveHeaders], ['authorization']); + client.close(); + await once(client, 'close'); + } + + server.close(); + await once(server, 'close'); +} + +main().then(common.mustCall()); diff --git a/test/parallel/test-diagnostics-channel-threadpool-work.js b/test/parallel/test-diagnostics-channel-threadpool-work.js new file mode 100644 index 000000000000..5111a4fb2b5f --- /dev/null +++ b/test/parallel/test-diagnostics-channel-threadpool-work.js @@ -0,0 +1,100 @@ +'use strict'; + +const common = require('../common'); + +const assert = require('node:assert'); +const crypto = common.hasCrypto ? require('node:crypto') : null; +const dc = require('node:diagnostics_channel'); +const fs = require('node:fs'); +const { + cp, + glob, + readFile, + readdir, + writeFile, +} = require('node:fs/promises'); +const { createHistogram } = require('node:perf_hooks'); +const { it } = require('node:test'); +const zlib = require('node:zlib'); + +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); +const sourceDir = tmpdir.resolve('source'); +const sourceFile = `${sourceDir}/file.js`; +fs.mkdirSync(`${sourceDir}/nested`, { recursive: true }); +fs.writeFileSync(sourceFile, 'data'); + +async function assertPublishes(t, type, trigger) { + const channel = `uv.threadpool.work.${type}`; + let published = false; + const handler = () => { published = true; }; + dc.subscribe(channel, handler); + t.after(() => dc.unsubscribe(channel, handler)); + + await trigger(); + + assert.ok(published); +} + +it('publishes for crypto work', { skip: !common.hasCrypto }, (t) => { + return assertPublishes(t, 'crypto', () => new Promise((resolve, reject) => { + crypto.pbkdf2('password', '0123456789abcdef', 1000, 16, 'sha256', + (err) => { + if (err) reject(err); + else resolve(); + }); + })); +}); + +it('publishes for fs.cp work', (t) => { + return assertPublishes(t, 'fs.cp', () => + cp(sourceDir, tmpdir.resolve('copy'), { recursive: true })); +}); + +it('publishes for fs.readfile work', (t) => { + return assertPublishes(t, 'fs.readfile', () => readFile(sourceFile)); +}); + +it('publishes for fs.writefile work', (t) => { + return assertPublishes(t, 'fs.writefile', () => + writeFile(tmpdir.resolve('written'), 'data')); +}); + +it('publishes for glob work', (t) => { + return assertPublishes(t, 'glob', () => + Array.fromAsync(glob('**', { cwd: sourceDir }))); +}); + +it('publishes for histogram.qrde work', (t) => { + return assertPublishes(t, 'histogram.qrde', () => { + const histogram = createHistogram(); + histogram.record(1); + return histogram.qrde({ bins: 1 }); + }); +}); + +it('publishes for readdir_recursive work', (t) => { + return assertPublishes(t, 'readdir_recursive', () => + readdir(sourceDir, { recursive: true })); +}); + +it('publishes for node_sqlite3.BackupJob work', { + skip: !common.hasSQLite, +}, (t) => { + return assertPublishes(t, 'node_sqlite3.BackupJob', async () => { + const { backup, DatabaseSync } = require('node:sqlite'); + const database = new DatabaseSync(':memory:'); + t.after(() => database.close()); + await backup(database, tmpdir.resolve('backup.db')); + }); +}); + +it('publishes for zlib work', (t) => { + return assertPublishes(t, 'zlib', () => new Promise((resolve, reject) => { + zlib.gzip('data', (err) => { + if (err) reject(err); + else resolve(); + }); + })); +}); diff --git a/test/parallel/test-diagnostics-channel-worker-threads-registry.js b/test/parallel/test-diagnostics-channel-worker-threads-registry.js new file mode 100644 index 000000000000..cd28c0926c25 --- /dev/null +++ b/test/parallel/test-diagnostics-channel-worker-threads-registry.js @@ -0,0 +1,87 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const { once } = require('events'); +const dc = require('diagnostics_channel'); +const { Worker, isMainThread, parentPort, workerData } = require('worker_threads'); + +// Only the main thread publishes registry updates; allow the test's own workers. +if (!isMainThread && workerData !== 'parent' && workerData !== 'child') { + common.skip('This test must be started on the main thread'); +} + +const channelName = 'worker_threads.main.registry'; + +if (isMainThread) { + // Expect one snapshot for each registration and removal in the worker tree. + const snapshots = []; + const childRegistered = Promise.withResolvers(); + const childRemoved = Promise.withResolvers(); + + dc.subscribe(channelName, common.mustCall((message) => { + assert.strictEqual(Object.getPrototypeOf(message), null); + assert.deepStrictEqual(Object.keys(message), ['threadIds']); + snapshots.push(message.threadIds); + + if (snapshots.length === 2) { + childRegistered.resolve(); + } + if (snapshots.length === 3) { + childRemoved.resolve(); + } + }, 4)); + + async function test() { + const worker = new Worker(__filename, { workerData: 'parent' }); + const threadId = worker.threadId; + + // The child ID and its registry update arrive on independent channels. + const [[childId]] = await Promise.all([ + once(worker, 'message'), + once(worker, 'online'), + childRegistered.promise, + ]); + + assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId]]); + + // Remove the nested worker first, keeping its parent alive for the update. + worker.postMessage('stop'); + await childRemoved.promise; + + assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId], [threadId]]); + + // Let the parent exit naturally, then check that earlier snapshots are intact. + const exited = once(worker, 'exit'); + worker.postMessage('finish'); + const [code] = await exited; + + assert.strictEqual(code, 0); + assert.deepStrictEqual(snapshots, [[threadId], [threadId, childId], [threadId], []]); + } + + test().then(common.mustCall()); +} else { + // Neither the parent worker nor its child should publish this channel locally. + dc.subscribe(channelName, common.mustNotCall()); + + if (workerData === 'child') { + // Keep the child alive until its parent explicitly terminates it. + parentPort.on('message', common.mustNotCall()); + } else { + async function run() { + const worker = new Worker(__filename, { workerData: 'child' }); + await once(worker, 'online'); + parentPort.postMessage(worker.threadId); + + // The main thread requests termination after observing both registrations. + await once(parentPort, 'message'); + assert.strictEqual(await worker.terminate(), 1); + + // Wait until the main thread observes the child's removal before exiting. + await once(parentPort, 'message'); + parentPort.close(); + } + + run().then(common.mustCall()); + } +} diff --git a/test/parallel/test-dlopen-binary.js b/test/parallel/test-dlopen-binary.js index 8a575a52c975..24c4b07cbfbe 100644 --- a/test/parallel/test-dlopen-binary.js +++ b/test/parallel/test-dlopen-binary.js @@ -1,6 +1,7 @@ // Flags: --expose-internals 'use strict'; const common = require('../common'); +const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const fs = require('fs'); const os = require('os'); @@ -22,7 +23,7 @@ const bytes = fs.readFileSync(addonPath); const flags = (os.constants.dlopen?.RTLD_LAZY) || 0; // A path that does not exist on disk, as a VFS-resident addon would be. -const fakePath = path.join(os.tmpdir(), 'nonexistent-vfs-dir', 'binding.node'); +const fakePath = tmpdir.resolve('nonexistent-vfs-dir', 'binding.node'); assert.ok(!fs.existsSync(fakePath)); const m = { exports: {} }; diff --git a/test/parallel/test-dtls-passphrase.mjs b/test/parallel/test-dtls-passphrase.mjs index d9926401b452..d1687a162dc3 100644 --- a/test/parallel/test-dtls-passphrase.mjs +++ b/test/parallel/test-dtls-passphrase.mjs @@ -8,13 +8,15 @@ // only, ignored when the key is not encrypted. import { hasCrypto, mustNotCall, skip } from '../common/index.mjs'; +import tmpdir from '../common/tmpdir.js'; import * as fixtures from '../common/fixtures.mjs'; import assert from 'node:assert'; import { execFileSync } from 'node:child_process'; import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; import { join } from 'node:path'; +tmpdir.refresh(); + if (!hasCrypto) { skip('missing crypto'); } @@ -29,7 +31,7 @@ const PASSPHRASE = 'correct horse battery staple'; // Generate an encrypted key and a matching self-signed certificate rather // than checking a fixture in, so the passphrase is visible in the test. -const dir = mkdtempSync(join(tmpdir(), 'dtls-passphrase-')); +const dir = mkdtempSync(tmpdir.resolve('dtls-passphrase-')); let encryptedKey; let encryptedCert; try { diff --git a/test/parallel/test-errors-systemerror.js b/test/parallel/test-errors-systemerror.js index 629a3d1c0869..651e7f8d8962 100644 --- a/test/parallel/test-errors-systemerror.js +++ b/test/parallel/test-errors-systemerror.js @@ -7,6 +7,7 @@ const { E, SystemError, codes, kIsNodeError } = require('internal/errors'); const { inspect } = require('internal/util/inspect'); assert.throws( + // eslint-disable-next-line no-restricted-syntax () => { new SystemError(); }, { name: 'TypeError', diff --git a/test/parallel/test-esm-loader-hooks-inspect-brk.js b/test/parallel/test-esm-loader-hooks-inspect-brk.js deleted file mode 100644 index 251ebb230dcd..000000000000 --- a/test/parallel/test-esm-loader-hooks-inspect-brk.js +++ /dev/null @@ -1,31 +0,0 @@ -// This tests esm loader's internal worker will not be blocked by --inspect-brk. -// Regression: https://github.com/nodejs/node/issues/53681 - -'use strict'; -const common = require('../common'); - -common.skipIfInspectorDisabled(); - -const assert = require('assert'); -const fixtures = require('../common/fixtures'); -const { NodeInstance } = require('../common/inspector-helper.js'); - -async function runTest() { - const main = fixtures.path('es-module-loaders', 'register-loader.mjs'); - const child = new NodeInstance(['--inspect-brk=0'], '', main); - - const session = await child.connectInspectorSession(); - await session.send({ method: 'NodeRuntime.enable' }); - await session.waitForNotification('NodeRuntime.waitingForDebugger'); - await session.send([ - { 'method': 'Runtime.enable' }, - { 'method': 'Debugger.enable' }, - { 'method': 'Runtime.runIfWaitingForDebugger' }, - ]); - await session.send({ method: 'NodeRuntime.disable' }); - await session.waitForNotification('Debugger.paused'); - await session.runToCompletion(); - assert.strictEqual((await child.expectShutdown()).exitCode, 0); -} - -runTest(); diff --git a/test/parallel/test-esm-loader-hooks-inspect-wait.js b/test/parallel/test-esm-loader-hooks-inspect-wait.js deleted file mode 100644 index 427b05641cce..000000000000 --- a/test/parallel/test-esm-loader-hooks-inspect-wait.js +++ /dev/null @@ -1,35 +0,0 @@ -// This tests esm loader's internal worker will not be blocked by --inspect-wait. -// Regression: https://github.com/nodejs/node/issues/53681 - -'use strict'; -const common = require('../common'); - -common.skipIfInspectorDisabled(); - -const assert = require('assert'); -const fixtures = require('../common/fixtures'); -const { NodeInstance } = require('../common/inspector-helper.js'); - -async function runTest() { - const main = fixtures.path('es-module-loaders', 'register-loader.mjs'); - process.env.NODE_DEBUG = 'esm,async_loader_worker'; - const child = new NodeInstance(['--inspect-wait=0'], '', main); - - const session = await child.connectInspectorSession(); - await session.send({ method: 'NodeRuntime.enable' }); - await session.waitForNotification('NodeRuntime.waitingForDebugger'); - await session.send([ - { 'method': 'Runtime.enable' }, - { 'method': 'Debugger.enable' }, - { 'method': 'Runtime.runIfWaitingForDebugger' }, - ]); - await session.send({ method: 'NodeRuntime.disable' }); - await session.waitForDisconnect(); - const result = await child.expectShutdown(); - assert.deepStrictEqual(result, { - exitCode: 0, - signal: null, - }); -} - -runTest(); diff --git a/test/parallel/test-fastutf8stream-destroy.js b/test/parallel/test-fastutf8stream-destroy.js index 04f7cad8088f..3351842e729a 100644 --- a/test/parallel/test-fastutf8stream-destroy.js +++ b/test/parallel/test-fastutf8stream-destroy.js @@ -4,9 +4,11 @@ const common = require('../common'); const tmpdir = require('../common/tmpdir'); const assert = require('node:assert'); const { + close, openSync, readFile, readFileSync, + write, } = require('node:fs'); const { Utf8Stream } = require('node:fs'); const { isMainThread } = require('node:worker_threads'); @@ -64,3 +66,128 @@ function getTempFile() { stream.destroy(); stream.on('close', common.mustCall()); } + +{ + // The fd is closed only after a write that is in flight at destroy() time + // completes. Data buffered behind it is dropped, so 'finish' is not emitted. + const dest = getTempFile(); + const fd = openSync(dest, 'w'); + let releaseWrite; + const stream = new Utf8Stream({ + fd, + fs: { + write: common.mustCall((...args) => { + releaseWrite = () => { + releaseWrite = null; + write(...args); + }; + }), + fsync: (fd, callback) => process.nextTick(callback), + close: common.mustCall((fd, callback) => { + assert.strictEqual(releaseWrite, null); + close(fd, callback); + }), + }, + }); + + stream.on('error', common.mustNotCall()); + stream.on('finish', common.mustNotCall()); + stream.on('close', common.mustCall(() => { + assert.strictEqual(readFileSync(dest, 'utf8'), 'hello world\n'); + })); + + assert.ok(stream.write('hello world\n')); + stream.write('dropped\n'); + stream.end(); + stream.destroy(); + setImmediate(() => releaseWrite()); +} + +{ + // A write started from an 'error' listener right before destroy() also + // completes before the fd is closed. + const dest = getTempFile(); + const fd = openSync(dest, 'w'); + let releaseWrite; + const stream = new Utf8Stream({ + fd, + fs: { + write: common.mustCall((...args) => { + if (releaseWrite === undefined) { + releaseWrite = null; + const err = new Error('EIO'); + err.code = 'EIO'; + process.nextTick(args.at(-1), err); + return; + } + releaseWrite = () => { + releaseWrite = null; + write(...args); + }; + }, 2), + fsync: (fd, callback) => process.nextTick(callback), + close: common.mustCall((fd, callback) => { + assert.strictEqual(releaseWrite, null); + close(fd, callback); + }), + }, + }); + + stream.on('error', common.mustCall(() => { + stream.write('second\n'); + stream.destroy(); + setImmediate(() => releaseWrite()); + })); + stream.on('close', common.mustCall()); + + assert.ok(stream.write('first\n')); +} + +{ + // A pending write that fails after destroy() with no 'error' listener + // throws, and the fd is still closed. + const dest = getTempFile(); + const fd = openSync(dest, 'w'); + let failWrite; + const stream = new Utf8Stream({ + fd, + fs: { + write: common.mustCall((fd, data, encoding, callback) => { + failWrite = () => { + const err = new Error('EIO'); + err.code = 'EIO'; + callback(err); + }; + }), + }, + }); + + stream.on('close', common.mustCall()); + + assert.ok(stream.write('hello world\n')); + stream.destroy(); + setImmediate(common.mustCall(() => { + process.once('uncaughtException', common.mustCall((err) => { + if (err.code !== 'EIO') throw err; + })); + failWrite(); + })); +} + +{ + // destroy() closes the fd even if fs.write() threw synchronously. + const fd = openSync(getTempFile(), 'w'); + const stream = new Utf8Stream({ + fd, + fs: { + write: common.mustCall(() => { + throw new Error('write failed'); + }), + }, + }); + + stream.on('close', common.mustCall()); + + assert.throws(() => stream.write('hello world\n'), { message: 'write failed' }); + stream.destroy(); +} diff --git a/test/parallel/test-fileurltopathbuffer.js b/test/parallel/test-fileurltopathbuffer.js index 11a78b76c0ef..db6bdc532a0e 100644 --- a/test/parallel/test-fileurltopathbuffer.js +++ b/test/parallel/test-fileurltopathbuffer.js @@ -55,7 +55,15 @@ assert.throws(() => writeFileSync(testPath, 'test'), { name: 'URIError', }); -writeFileSync(testPathBuffer, 'test'); + +try { + writeFileSync(testPathBuffer, 'test'); +} catch (e) { + // ZFS with utf8only=on (default) rejects non-UTF-8 file names + if (e.code === 'EILSEQ') + common.skip('test requires filesystem that accepts non-UTF-8 names'); + throw e; +} assert.ok(existsSync(testPathBuffer)); // Using fileURLToPath fails because the URL contains non-Unicode diff --git a/test/parallel/test-fs-cp-dereference-symlink-to-file.mjs b/test/parallel/test-fs-cp-dereference-symlink-to-file.mjs new file mode 100644 index 000000000000..8c921630366c --- /dev/null +++ b/test/parallel/test-fs-cp-dereference-symlink-to-file.mjs @@ -0,0 +1,42 @@ +// This tests that cp() and cpSync() copy the target file of a symlink passed +// as src when dereference is true and recursive is not set. + +import { mustCall, mustNotMutateObjectDeep } from '../common/index.mjs'; +import { nextdir } from '../common/fs.js'; +import assert from 'node:assert'; +import { + cp, + cpSync, + lstatSync, + mkdirSync, + readFileSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import tmpdir from '../common/tmpdir.js'; + +tmpdir.refresh(); + +const src = nextdir(); +mkdirSync(src); +writeFileSync(join(src, 'foo.txt'), 'foo'); +symlinkSync(join(src, 'foo.txt'), join(src, 'link.txt')); + +const opts = mustNotMutateObjectDeep({ dereference: true }); + +{ + const dest = join(nextdir(), 'foo.txt'); + cpSync(join(src, 'link.txt'), dest, opts); + assert(lstatSync(dest).isFile()); + assert.strictEqual(readFileSync(dest, 'utf8'), 'foo'); +} + +{ + const dest = join(nextdir(), 'foo.txt'); + cp(join(src, 'link.txt'), dest, opts, mustCall((err) => { + assert.ifError(err); + assert(lstatSync(dest).isFile()); + assert.strictEqual(readFileSync(dest, 'utf8'), 'foo'); + })); +} diff --git a/test/parallel/test-fs-mkdir-recursive-erofs.js b/test/parallel/test-fs-mkdir-recursive-erofs.js new file mode 100644 index 000000000000..0f874888ffe8 --- /dev/null +++ b/test/parallel/test-fs-mkdir-recursive-erofs.js @@ -0,0 +1,70 @@ +'use strict'; + +// Test that mkdir with the recursive option reports EROFS when the target is +// on a read-only file system instead of turning it into ENOENT. +// Ref: https://github.com/nodejs/node/issues/47098 + +const common = require('../common'); + +if (common.isWindows) + common.skip('no read-only file system to test against on Windows'); + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); + +const probe = `node-test-erofs-${process.pid}`; + +// Find a mounted read-only file system. Linux lists mount options in +// /proc/self/mounts (for example /sys in a container, or squashfs images); +// on macOS the system volume is read-only. Confirm the candidate with a plain +// mkdir, which must fail with EROFS rather than with a permission error. +function findReadOnlyRoot() { + const candidates = []; + if (common.isLinux) { + let mounts; + try { + mounts = fs.readFileSync('/proc/self/mounts', 'utf8'); + } catch { + return null; + } + for (const line of mounts.split('\n')) { + const fields = line.split(' '); + if (fields.length >= 4 && /(^|,)ro(,|$)/.test(fields[3])) { + candidates.push(fields[1].replaceAll('\\040', ' ')); + } + } + } else if (common.isMacOS) { + candidates.push('/'); + } + + for (const dir of candidates) { + try { + fs.mkdirSync(path.join(dir, probe)); + } catch (err) { + if (err.code === 'EROFS') return dir; + continue; + } + // Not read-only after all. + fs.rmdirSync(path.join(dir, probe)); + } + return null; +} + +const root = findReadOnlyRoot(); +if (root === null) + common.skip('no read-only file system available'); + +const target = path.join(root, probe, 'child'); +const expected = { code: 'EROFS', syscall: 'mkdir' }; + +assert.throws(() => fs.mkdirSync(target, { recursive: true }), expected); + +fs.mkdir(target, { recursive: true }, common.mustCall((err) => { + assert.strictEqual(err.code, 'EROFS'); + assert.strictEqual(err.syscall, 'mkdir'); + assert(err.path); +})); + +assert.rejects(fs.promises.mkdir(target, { recursive: true }), expected) + .then(common.mustCall()); diff --git a/test/parallel/test-fs-negative-zero.js b/test/parallel/test-fs-negative-zero.js index 09f965eb171f..c8cda8aba6bf 100644 --- a/test/parallel/test-fs-negative-zero.js +++ b/test/parallel/test-fs-negative-zero.js @@ -1,15 +1,14 @@ 'use strict'; -require('../common'); - +const common = require('../common'); +const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const { spawnSync } = require('child_process'); const fs = require('fs'); -const path = require('path'); -const os = require('os'); -const missing = path.join( - os.tmpdir(), +tmpdir.refresh(); + +const missing = tmpdir.resolve( `node-fs-negative-zero-${process.pid}`, 'entry', ); @@ -46,3 +45,28 @@ assert.strictEqual(child.stdout.toString(), 'hello'); fs.watchFile(missing, { interval: -0 }, () => {}); fs.unwatchFile(missing); + +// A length of -0 writes nothing, like 0. +{ + const buffer = Buffer.from('abc'); + + const fd = fs.openSync(tmpdir.resolve('negative-zero-fd.txt'), 'w'); + assert.strictEqual(fs.writeSync(fd, buffer, 0, -0), 0); + assert.strictEqual(fs.writeSync(fd, buffer, { length: -0 }), 0); + fs.write(fd, buffer, 0, -0, common.mustSucceed((written) => { + assert.strictEqual(written, 0); + fs.write(fd, buffer, { length: -0 }, common.mustSucceed((written) => { + assert.strictEqual(written, 0); + fs.closeSync(fd); + })); + })); + + (async () => { + const handle = + await fs.promises.open(tmpdir.resolve('negative-zero-handle.txt'), 'w'); + assert.strictEqual((await handle.write(buffer, 0, -0)).bytesWritten, 0); + assert.strictEqual( + (await handle.write(buffer, { length: -0 })).bytesWritten, 0); + await handle.close(); + })().then(common.mustCall()); +} diff --git a/test/parallel/test-fs-opendir-invalid-buffersize.js b/test/parallel/test-fs-opendir-invalid-buffersize.js new file mode 100644 index 000000000000..c48bfa25a29a --- /dev/null +++ b/test/parallel/test-fs-opendir-invalid-buffersize.js @@ -0,0 +1,80 @@ +'use strict'; + +// This tests that fs.opendir() and fs.promises.opendir() report an invalid +// bufferSize to the caller instead of throwing from an internal callback. + +const common = require('../common'); +const assert = require('assert'); +const fs = require('fs'); + +const tmpdir = require('../common/tmpdir'); +tmpdir.refresh(); + +for (const bufferSize of [-1, 0, 0.5, 1.5, Infinity, NaN]) { + const expected = { code: 'ERR_OUT_OF_RANGE', name: 'RangeError' }; + assert.throws( + () => fs.opendir(tmpdir.path, { bufferSize }, common.mustNotCall()), + expected, + ); + assert.rejects(fs.promises.opendir(tmpdir.path, { bufferSize }), expected) + .then(common.mustCall()); +} + +for (const bufferSize of ['', '1', null, undefined]) { + const expected = { code: 'ERR_INVALID_ARG_TYPE', name: 'TypeError' }; + assert.throws( + () => fs.opendir(tmpdir.path, { bufferSize }, common.mustNotCall()), + expected, + ); + assert.rejects(fs.promises.opendir(tmpdir.path, { bufferSize }), expected) + .then(common.mustCall()); +} + +// A valid bufferSize still opens the directory. +fs.opendir(tmpdir.path, { bufferSize: 1 }, common.mustSucceed((dir) => { + dir.closeSync(); +})); + +// bufferSize is read only once, so a getter can't pass the validation and then +// return an invalid value when the directory has been opened. +{ + let reads = 0; + const options = { + get bufferSize() { + return reads++ === 0 ? 1 : 0; + }, + }; + fs.opendir(tmpdir.path, options, common.mustSucceed((dir) => { + assert.strictEqual(reads, 1); + dir.closeSync(); + })); +} + +// The other options are copied and validated before the directory is opened, +// so a getter can't pass the checks and then hand an invalid value to the Dir +// constructor. The call either fails or succeeds, never from the internal +// callback. +for (let validReads = 0; validReads < 5; validReads++) { + let reads = 0; + const options = { + get encoding() { + return reads++ < validReads ? 'utf8' : 'bogus'; + }, + }; + fs.promises.opendir(tmpdir.path, options).then( + (dir) => dir.closeSync(), + (err) => { + if (err.code !== 'ERR_INVALID_ARG_VALUE') throw err; + }, + ).then(common.mustCall()); +} + +// A non-enumerable bufferSize is ignored, the same as in fs.opendirSync(). +{ + const options = {}; + Object.defineProperty(options, 'bufferSize', { value: 0 }); + fs.opendirSync(tmpdir.path, options).closeSync(); + fs.opendir(tmpdir.path, options, common.mustSucceed((dir) => { + dir.closeSync(); + })); +} diff --git a/test/parallel/test-fs-promises.js b/test/parallel/test-fs-promises.js index 07f01187e89b..6ddc4cd3cb36 100644 --- a/test/parallel/test-fs-promises.js +++ b/test/parallel/test-fs-promises.js @@ -9,6 +9,7 @@ const fs = require('fs'); const fsPromises = fs.promises; const { access, + appendFile, chmod, chown, copyFile, @@ -62,6 +63,30 @@ assert.strictEqual( } ).then(common.mustCall()); + assert.rejects( + readFile('this file does not exist'), + { + code: 'ENOENT', + stack: /at async assert\.rejects/ + } + ).then(common.mustCall()); + + assert.rejects( + writeFile(path.join('this dir does not exist', 'file'), 'data'), + { + code: 'ENOENT', + stack: /at async assert\.rejects/ + } + ).then(common.mustCall()); + + assert.rejects( + appendFile(path.join('this dir does not exist', 'file'), 'data'), + { + code: 'ENOENT', + stack: /at async assert\.rejects/ + } + ).then(common.mustCall()); + assert.rejects( access(__filename, 8), { diff --git a/test/parallel/test-fs-read-stream-hwm-zero.js b/test/parallel/test-fs-read-stream-hwm-zero.js new file mode 100644 index 000000000000..720a5fb1988d --- /dev/null +++ b/test/parallel/test-fs-read-stream-hwm-zero.js @@ -0,0 +1,51 @@ +'use strict'; + +const common = require('../common'); + +const assert = require('node:assert'); +const fs = require('node:fs'); +const { setDefaultHighWaterMark } = require('node:stream'); + +const expected = fs.readFileSync(__filename); + +function readAll(stream, check) { + const chunks = []; + stream.on('data', (chunk) => chunks.push(chunk)); + stream.on('end', () => check(Buffer.concat(chunks))); +} + +{ + const stream = fs.createReadStream(__filename, { highWaterMark: 0 }); + assert.strictEqual(stream.readableHighWaterMark, 0); + readAll(stream, common.mustCall((data) => { + assert.deepStrictEqual(data, expected); + })); +} + +{ + const stream = fs.createReadStream(__filename, { + highWaterMark: 0, + start: 10, + end: 20, + }); + readAll(stream, common.mustCall((data) => { + assert.deepStrictEqual(data, expected.subarray(10, 21)); + })); +} + +fs.promises.open(__filename).then(common.mustCall((fh) => { + const stream = fh.createReadStream({ highWaterMark: 0 }); + readAll(stream, common.mustCall((data) => { + assert.deepStrictEqual(data, expected); + })); +})); + +setDefaultHighWaterMark(false, 0); + +{ + const stream = fs.createReadStream(__filename); + assert.strictEqual(stream.readableHighWaterMark, 0); + readAll(stream, common.mustCall((data) => { + assert.deepStrictEqual(data, expected); + })); +} diff --git a/test/parallel/test-fs-read-stream-set-default-hwm.js b/test/parallel/test-fs-read-stream-set-default-hwm.js new file mode 100644 index 000000000000..3ec78dacc43a --- /dev/null +++ b/test/parallel/test-fs-read-stream-set-default-hwm.js @@ -0,0 +1,34 @@ +'use strict'; + +const common = require('../common'); + +const assert = require('node:assert'); +const fs = require('node:fs'); +const { setDefaultHighWaterMark } = require('node:stream'); + +{ + const stream = fs.createReadStream(__filename); + assert.strictEqual(stream.readableHighWaterMark, 64 * 1024); + stream.destroy(); +} + +setDefaultHighWaterMark(false, 1024 * 1024); + +{ + const stream = fs.createReadStream(__filename); + assert.strictEqual(stream.readableHighWaterMark, 1024 * 1024); + stream.destroy(); +} + +{ + const stream = fs.createReadStream(__filename, { highWaterMark: 1024 }); + assert.strictEqual(stream.readableHighWaterMark, 1024); + stream.destroy(); +} + +fs.promises.open(__filename).then(async (fh) => { + const stream = fh.createReadStream({ autoClose: false }); + assert.strictEqual(stream.readableHighWaterMark, 1024 * 1024); + stream.destroy(); + await fh.close(); +}).then(common.mustCall()); diff --git a/test/parallel/test-fs-readdir-ucs2.js b/test/parallel/test-fs-readdir-ucs2.js index 264858ec6ae8..b541ecd32f5b 100644 --- a/test/parallel/test-fs-readdir-ucs2.js +++ b/test/parallel/test-fs-readdir-ucs2.js @@ -18,7 +18,8 @@ const fullpath = Buffer.concat([root, filebuff]); try { fs.closeSync(fs.openSync(fullpath, 'w+')); } catch (e) { - if (e.code === 'EINVAL') + // EILSEQ: ZFS with utf8only=on (default) rejects non-UTF-8 file names + if (e.code === 'EINVAL' || e.code === 'EILSEQ') common.skip('test requires filesystem that supports UCS2'); throw e; } diff --git a/test/parallel/test-fs-watch-ref-unref.js b/test/parallel/test-fs-watch-ref-unref.js index e51ecaf5b2fc..a037fd345319 100644 --- a/test/parallel/test-fs-watch-ref-unref.js +++ b/test/parallel/test-fs-watch-ref-unref.js @@ -7,7 +7,7 @@ if (common.isIBMi) const fs = require('fs'); -const watcher = fs.watch(__filename, common.mustNotCall()); +const watcher = fs.watch(__filename); watcher.unref(); diff --git a/test/parallel/test-fs-write-stream-writev-retry-position.js b/test/parallel/test-fs-write-stream-writev-retry-position.js new file mode 100644 index 000000000000..17dfb474ceff --- /dev/null +++ b/test/parallel/test-fs-write-stream-writev-retry-position.js @@ -0,0 +1,74 @@ +'use strict'; +const common = require('../common'); +const tmpdir = require('../common/tmpdir'); +const assert = require('assert'); +const fs = require('fs'); + +tmpdir.refresh(); + +const data = 'AAAABBBBCCCC'; + +// Report back fewer bytes than were handed over, asynchronously: the retry has +// to observe the position as it is after _writev() advanced this.pos by the +// whole batch. +function shortWrite(bytes) { + return (fd, chunks, position, cb) => { + const head = Buffer.concat(chunks).subarray(0, bytes); + fs.write(fd, head, 0, bytes, position, + (er, bytesWritten) => cb(er, bytesWritten, chunks)); + }; +} + +function eagain(fd, chunks, position, cb) { + process.nextTick(cb, Object.assign(new Error(), { code: 'EAGAIN' }), 0, chunks); +} + +// The positions handed to writev() are the contract under test: watching the +// resulting file alone would still pass if some later rewrite happened to land +// the bytes correctly by another route. +function run(name, { prefix = '', start, firstCall }, expectedPositions) { + const file = tmpdir.resolve(`partial-writev-${name}.txt`); + fs.writeFileSync(file, prefix); + + const positions = []; + const stream = fs.createWriteStream(file, { + flags: 'r+', + start, + fs: { + ...fs, + writev: common.mustCall((fd, chunks, position, cb) => { + positions.push(position); + if (positions.length === 1) { + firstCall(fd, chunks, position, cb); + } else { + fs.writev(fd, chunks, position, cb); + } + }, 2), + }, + }); + + stream.cork(); + stream.write('AAAA'); + stream.write('BBBB'); + stream.write('CCCC'); + stream.uncork(); + stream.end(); + + stream.on('error', common.mustNotCall()); + stream.on('close', common.mustCall(() => { + if (expectedPositions !== undefined) { + assert.deepStrictEqual(positions, expectedPositions, `${name} positions`); + } + assert.strictEqual(fs.readFileSync(file, 'utf8'), prefix + data, name); + })); +} + +// Partial write: resume right after the bytes that reached the disk. +run('start-5', { prefix: '#####', start: 5, firstCall: shortWrite(3) }, [5, 8]); +run('start-0', { start: 0, firstCall: shortWrite(3) }, [0, 3]); + +// EAGAIN: nothing was written, so the retry goes back to the same position. +run('eagain', { prefix: '#####', start: 5, firstCall: eagain }, [5, 5]); + +// Without a start the stream follows the fd offset; only the bytes matter. +run('no-start', { firstCall: shortWrite(3) }); diff --git a/test/parallel/test-gc-net-timeout.js b/test/parallel/test-gc-net-timeout.js index 0fc93bfc62c2..5346b3a6a179 100644 --- a/test/parallel/test-gc-net-timeout.js +++ b/test/parallel/test-gc-net-timeout.js @@ -41,6 +41,9 @@ function getAll() { const req = net.connect(server.address().port); req.resume(); + req.on('error', (err) => { + if (err?.code !== 'ECONNRESET') throw err; + }); req.setTimeout(10, function() { req.destroy(); done++; diff --git a/test/parallel/test-heap-pointer-compression-warning.js b/test/parallel/test-heap-pointer-compression-warning.js new file mode 100644 index 000000000000..6b899d2650b7 --- /dev/null +++ b/test/parallel/test-heap-pointer-compression-warning.js @@ -0,0 +1,134 @@ +// Flags: --no-warnings --expose-internals --expose-gc +'use strict'; + +// Tests the HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT warning, which is emitted +// once per thread when the heap that survives a full GC would not fit in the +// 4 GiB pointer compression cage. It says the heap "is likely to exceed" the +// limit from 6.5 GiB and "will exceed" it from 8 GiB. The thresholds are +// lowered through an internal binding so the test does not need to allocate a +// large heap. + +const common = require('../common'); + +common.skipIf32Bits(); +if (process.config.variables.v8_enable_pointer_compression) { + common.skip('the warning is only emitted without pointer compression'); +} + +const assert = require('assert'); +const { internalBinding } = require('internal/test/binding'); +const { spawnSyncAndAssert } = require('../common/child_process'); +const { Worker, isMainThread, threadId } = require('worker_threads'); + +const kCode = 'HEAP_EXCEEDS_POINTER_COMPRESSION_LIMIT'; +const kLikely = /is likely to exceed that limit, and the application may run out of memory/; +const kCertain = /will exceed that limit, and the application will run out of memory/; +const childFlags = ['--expose-internals', '--expose-gc']; + +// Larger than any heap this test can have. +const kNever = Number.MAX_SAFE_INTEGER; + +function triggerWarning(tier) { + const { setPointerCompressionHeapWarningThresholds } = internalBinding('v8'); + if (tier === 'likely') { + setPointerCompressionHeapWarningThresholds(1, kNever); + } else { + setPointerCompressionHeapWarningThresholds(1, 1); + } + globalThis.gc(); + // The warning is emitted from an unref'ed immediate, so keep the event loop + // alive for one more iteration. + setImmediate(() => {}); +} + +switch (process.argv[2]) { + case 'child': + triggerWarning(process.argv[3]); + return; + case 'worker': { + const { parentPort } = require('worker_threads'); + process.on('warning', (warning) => { + if (warning.code !== kCode) return; + parentPort.postMessage({ name: warning.name, message: warning.message }); + }); + triggerWarning('certain'); + return; + } +} + +// Collect only this warning; requiring internal/test/binding emits its own. +const warnings = []; +process.on('warning', (warning) => { + if (warning.code === kCode) warnings.push(warning); +}); + +// With the default thresholds, an ordinary heap does not trigger the warning. +globalThis.gc(); +setImmediate(common.mustCall(() => { + assert.strictEqual(warnings.length, 0); + + // A heap between the two thresholds gets the "likely" wording. + triggerWarning('likely'); + + setImmediate(common.mustCall(() => { + // The warning is emitted only once per thread, and its wording is decided + // when it is first triggered: a heap that later passes the "certain" + // threshold does not emit a second warning. + internalBinding('v8').setPointerCompressionHeapWarningThresholds(1, 1); + globalThis.gc(); + setImmediate(() => {}); + })); +})); + +process.on('exit', () => { + assert.strictEqual(warnings.length, 1); + const [warning] = warnings; + assert.strictEqual(warning.name, 'Warning'); + // The test-worker suite runs this file inside a worker thread. + const thread = isMainThread ? 'the main thread' : `worker thread ${threadId}`; + assert.match(warning.message, + new RegExp(`The V8 heap of ${thread} is using \\d+ MiB`)); + assert.match(warning.message, /limited to 4096 MiB/); + assert.match(warning.message, kLikely); + assert.doesNotMatch(warning.message, kCertain); +}); + +// A heap at or above the "certain" threshold gets the "will exceed" wording, +// and the default stderr output includes the code. +spawnSyncAndAssert(process.execPath, [ + ...childFlags, + __filename, + 'child', + 'certain', +], { + stderr(output) { + assert.match( + output, + new RegExp(`\\[${kCode}\\] Warning: The V8 heap of the main thread`)); + assert.match(output, kCertain); + assert.doesNotMatch(output, kLikely); + }, +}); + +// The code can be used to disable the warning. +spawnSyncAndAssert(process.execPath, [ + ...childFlags, + `--disable-warning=${kCode}`, + __filename, + 'child', + 'certain', +], { + stderr(output) { + assert.doesNotMatch(output, new RegExp(kCode)); + }, +}); + +// Each worker thread has its own heap and its own warning. +const worker = new Worker(__filename, { argv: ['worker'] }); +worker.on('message', common.mustCall((warning) => { + assert.strictEqual(warning.name, 'Warning'); + assert.match( + warning.message, + new RegExp(`The V8 heap of worker thread ${worker.threadId} is using`)); + assert.match(warning.message, kCertain); +})); diff --git a/test/parallel/test-http-agent-free-socket-pending-read.js b/test/parallel/test-http-agent-free-socket-pending-read.js new file mode 100644 index 000000000000..a8ff4d681d65 --- /dev/null +++ b/test/parallel/test-http-agent-free-socket-pending-read.js @@ -0,0 +1,121 @@ +'use strict'; + +// The free socket data guard in http.Agent only runs when the event loop +// polls for I/O. If data reaches an idle socket's OS buffer and a request +// takes that socket before the loop has polled, the guard never sees the data +// and it would be parsed as the response to that request. The Agent must +// check for pending data before handing a kept-alive socket to a request. + +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); + +const poison = + 'HTTP/1.1 200 OK\r\n' + + 'X-Poisoned: true\r\n' + + 'Connection: keep-alive\r\n' + + 'Content-Length: 0\r\n' + + '\r\n'; + +// Keep the event loop from polling until the bytes are in the client's +// socket buffer, so libuv cannot deliver them to the data guard first. +function waitForPendingRead(socket) { + const deadline = Date.now() + common.platformTimeout(5000); + while (!socket._handle.hasPendingRead()) { + assert.ok(Date.now() < deadline, 'timed out waiting for pending data'); + } +} + +function checkResponse(req, expectedBody, cb) { + req.on('response', common.mustCall((res) => { + let body = ''; + res.setEncoding('utf8'); + res.on('data', (chunk) => { body += chunk; }); + res.on('end', common.mustCall(() => { + assert.strictEqual(res.headers['x-poisoned'], undefined); + assert.strictEqual(body, expectedBody); + cb?.(res); + })); + })); +} + +// A socket taken from the free pool. +{ + let serverSocket; + const server = http.createServer(common.mustCall((req, res) => { + serverSocket ||= req.socket; + res.end(req.url); + }, 2)); + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true }); + const options = { host: '127.0.0.1', port: server.address().port, agent }; + const name = agent.getName(options); + + const request1 = http.request({ ...options, path: '/request1' }); + request1.end(); + checkResponse(request1, '/request1'); + + request1.on('close', common.mustCall(() => { + process.nextTick(common.mustCall(() => { + assert.strictEqual(agent.freeSockets[name]?.length, 1); + const freeSocket = agent.freeSockets[name][0]; + + serverSocket.write(poison); + waitForPendingRead(freeSocket); + + // Same tick: the loop has not polled since the data arrived. + const request2 = http.request({ ...options, path: '/request2' }); + request2.end(); + + assert.strictEqual(freeSocket.destroyed, true); + assert.strictEqual(request2.reusedSocket, false); + + checkResponse(request2, '/request2', common.mustCall(() => { + agent.destroy(); + server.close(); + })); + })); + })); + })); +} + +// A released socket handed directly to a queued request. +{ + let serverSocket; + const server = http.createServer(common.mustCall((req, res) => { + serverSocket ||= req.socket; + res.end(req.url); + }, 2)); + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + const options = { host: '127.0.0.1', port: server.address().port, agent }; + const name = agent.getName(options); + + const request1 = http.request({ ...options, path: '/request1' }); + request1.end(); + const request2 = http.request({ ...options, path: '/request2' }); + request2.end(); + assert.strictEqual(agent.requests[name]?.length, 1); + + let socket1; + request1.on('socket', common.mustCall((socket) => { + socket1 = socket; + })); + + // The socket is released to the queued request on the next tick after + // 'end', so the loop does not poll in between. + checkResponse(request1, '/request1', common.mustCall(() => { + serverSocket.write(poison); + waitForPendingRead(socket1); + })); + + checkResponse(request2, '/request2', common.mustCall(() => { + assert.strictEqual(socket1.destroyed, true); + assert.strictEqual(request2.reusedSocket, false); + agent.destroy(); + server.close(); + })); + })); +} diff --git a/test/parallel/test-http-agent-keepalive-expired-free-socket.js b/test/parallel/test-http-agent-keepalive-expired-free-socket.js new file mode 100644 index 000000000000..553054a1ad45 --- /dev/null +++ b/test/parallel/test-http-agent-keepalive-expired-free-socket.js @@ -0,0 +1,319 @@ +// Flags: --expose-internals --no-warnings --allow-natives-syntax +'use strict'; + +const common = require('../common'); + +// A free socket expires by its idle timeout timer. When the event loop is +// blocked longer than that timeout, the timer cannot run, and the next +// request must not reuse the socket, because the server may already have +// closed it. +// Refs: https://github.com/nodejs/node/issues/54293 + +const assert = require('node:assert'); +const http = require('node:http'); +const { internalBinding } = require('internal/test/binding'); + +function count(lists) { + return Object.values(lists).reduce((n, list) => n + list.length, 0); +} + +// Makes `sockets` concurrent requests, then calls `callback` once all their +// sockets are in the agent's free pool. +function fillPool(agent, port, sockets, callback) { + let free = 0; + agent.on('free', function onFree() { + if (++free === sockets) { + agent.removeListener('free', onFree); + setImmediate(callback); + } + }); + for (let i = 0; i < sockets; i++) { + http.get({ port, agent }, common.mustCall((res) => res.resume())); + } +} + +function testReuse(agentOptions, blockMs, expectReuse, next) { + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 2)); + // No Keep-Alive hint from the server, so the agent's `timeout` alone sets + // the socket's idle timeout. + server.keepAliveTimeout = 0; + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true, ...agentOptions }); + const { port } = server.address(); + + fillPool(agent, port, 1, common.mustCall(() => { + const [socket] = Object.values(agent.freeSockets)[0]; + assert.strictEqual(socket.timeout, agentOptions.timeout ?? 0); + common.sleepSync(blockMs); + const req = http.get({ port, agent }, common.mustCall((res) => { + res.resume(); + res.on('end', common.mustCall(() => { + agent.destroy(); + server.close(next); + })); + })); + assert.strictEqual(req.reusedSocket, expectReuse); + assert.strictEqual(socket.destroyed, !expectReuse); + })); + })); +} + +// The expired sockets release their slots at once, so a burst of requests +// after the block opens no more than maxSockets connections. +function testMaxSockets(next) { + const timeout = common.platformTimeout(500); + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 6)); + server.keepAliveTimeout = 0; + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true, timeout: 60_000, maxSockets: 2 }); + const { port } = server.address(); + + fillPool(agent, port, 2, common.mustCall(() => { + const pooled = [...Object.values(agent.freeSockets)[0]]; + assert.strictEqual(pooled.length, 2); + for (const socket of pooled) { + socket.setTimeout(timeout); + } + common.sleepSync(timeout * 2); + let done = 0; + for (let i = 0; i < 4; i++) { + http.get({ port, agent }, common.mustCall((res) => { + res.resume(); + res.on('end', () => { + if (++done === 4) { + agent.destroy(); + server.close(next); + } + }); + })); + } + assert(pooled.every((socket) => socket.destroyed)); + assert.strictEqual(agent.totalSocketCount, 2); + assert.strictEqual(count(agent.sockets), 2); + assert.strictEqual(count(agent.requests), 2); + })); + })); +} + +// When the socket that the scheduling picks first has expired and the other +// one has not, the expired one is removed and the request reuses the other. +function testMixedPool(scheduling, next) { + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 3)); + // No Keep-Alive hint from the server, so both sockets enter the pool with + // the agent's `timeout` as their idle timeout. + server.keepAliveTimeout = 0; + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ + keepAlive: true, + timeout: 60_000, + scheduling, + }); + const { port } = server.address(); + + fillPool(agent, port, 2, common.mustCall(() => { + const [first, last] = Object.values(agent.freeSockets)[0]; + // The socket that the scheduling picks first gets an idle timeout that + // passes during the block. + const [expired, kept] = scheduling === 'fifo' ? + [first, last] : + [last, first]; + expired.setTimeout(100); + common.sleepSync(300); + const req = http.get({ port, agent }, common.mustCall((res) => { + assert.strictEqual(req.socket, kept); + res.resume(); + res.on('end', common.mustCall(() => { + agent.destroy(); + server.close(next); + })); + })); + assert.strictEqual(req.reusedSocket, true); + assert.strictEqual(expired.destroyed, true); + assert.strictEqual(kept.destroyed, false); + assert.strictEqual(agent.totalSocketCount, 1); + assert.strictEqual(count(agent.freeSockets), 0); + assert.strictEqual(count(agent.sockets), 1); + })); + })); +} + +// A pooled socket whose timeout is set again is expired by its restarted timer, +// not by the time it entered the pool. +function testRestartedTimeout(next) { + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 2)); + // No Keep-Alive hint from the server, so the agent's `timeout` alone sets + // the socket's idle timeout. + server.keepAliveTimeout = 0; + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true, timeout: 60_000 }); + const { port } = server.address(); + + fillPool(agent, port, 1, common.mustCall(() => { + const [socket] = Object.values(agent.freeSockets)[0]; + common.sleepSync(300); + // Shorter than the block: only a timer restarted now has not passed it. + socket.setTimeout(200); + const req = http.get({ port, agent }, common.mustCall((res) => { + assert.strictEqual(res.socket, socket); + res.resume(); + res.on('end', common.mustCall(() => { + agent.destroy(); + server.close(next); + })); + })); + assert.strictEqual(req.reusedSocket, true); + })); + })); +} + +// A request timeout that fired while the response waited unread is cleared when +// the socket is kept alive. Its timer then still holds the fired timeout, but +// the socket has no idle timeout, so it is reused. +function testFiredTimeoutCleared(next) { + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 2)); + // No Keep-Alive hint from the server, and the agent has no `timeout`, so the + // pooled socket has no idle timeout. + server.keepAliveTimeout = 0; + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true }); + const { port } = server.address(); + + function reuse(socket) { + assert.strictEqual(socket.timeout, 0); + const req = http.get({ port, agent }, common.mustCall((res) => { + assert.strictEqual(res.socket, socket); + res.resume(); + res.on('end', common.mustCall(() => { + agent.destroy(); + server.close(next); + })); + })); + assert.strictEqual(req.reusedSocket, true); + } + + const first = http.get({ port, agent }, common.mustCall((res) => { + const { socket } = res; + // The response is read only after the request timeout has fired. + first.setTimeout(50, common.mustCall(() => { + setImmediate(common.mustCall(() => { + agent.once('free', common.mustCall(() => { + setImmediate(common.mustCall(() => reuse(socket))); + })); + res.resume(); + })); + })); + })); + })); +} + +// A destroyed socket can stay in the free pool until its 'close' event. A +// request made before that event must not get it. +function testDestroyedSocket(next) { + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 3)); + // No Keep-Alive hint from the server, so the pooled sockets have no idle + // timeout and cannot expire. + server.keepAliveTimeout = 0; + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true }); + const { port } = server.address(); + + fillPool(agent, port, 2, common.mustCall(() => { + const [first, last] = Object.values(agent.freeSockets)[0]; + last.destroy(); + const req = http.get({ port, agent }, common.mustCall((res) => { + assert.strictEqual(req.socket, first); + res.resume(); + res.on('end', common.mustCall(() => { + agent.destroy(); + server.close(next); + })); + })); + assert.strictEqual(req.reusedSocket, true); + assert.strictEqual(agent.totalSocketCount, 1); + assert.strictEqual(count(agent.freeSockets), 0); + assert.strictEqual(count(agent.sockets), 1); + })); + })); +} + +// addRequest() reads the timers' clock through a fast API call when it takes a +// socket from the pool; the optimized function must be able to make it. +function testOptimizedAddRequest(next) { + const server = http.createServer(common.mustCall((req, res) => { + res.end('ok'); + }, 3)); + + server.listen(0, common.mustCall(() => { + const agent = new http.Agent({ keepAlive: true, timeout: 60_000 }); + const { port } = server.address(); + + function get(callback) { + http.get({ port, agent }, common.mustCall((res) => { + res.resume(); + res.on('end', common.mustCall(() => setImmediate(callback))); + })); + } + + eval('%PrepareFunctionForOptimization(http.Agent.prototype.addRequest)'); + get(common.mustCall(() => get(common.mustCall(() => { + eval('%OptimizeFunctionOnNextCall(http.Agent.prototype.addRequest)'); + const fastCalls = getFastCallCount(); + get(common.mustCall(() => { + agent.destroy(); + server.close(next); + })); + if (common.isDebug) { + assert.strictEqual(getFastCallCount() - fastCalls, 1); + } + })))); + })); +} + +// The fast API call counter exists in debug builds only. +function getFastCallCount() { + if (!common.isDebug) return 0; + const { getV8FastApiCallCount } = internalBinding('debug'); + return getV8FastApiCallCount('timers.getLibuvNow'); +} + +// The cases run one after another, so that one case's block does not delay +// the timers of another. +const cases = [ + // The idle timeout passed during the block. + (next) => testReuse({ timeout: 100 }, 300, false, next), + (next) => testReuse({ timeout: 100, scheduling: 'fifo' }, 300, false, next), + // The idle timeout did not pass during the block. + (next) => testReuse({ timeout: 60_000 }, 300, true, next), + // A socket without an idle timeout is not expired by the clock. + (next) => testReuse({}, 300, true, next), + testMaxSockets, + // The idle timeout of one of two pooled sockets passed during the block. + (next) => testMixedPool('lifo', next), + (next) => testMixedPool('fifo', next), + testRestartedTimeout, + testFiredTimeoutCleared, + testDestroyedSocket, + testOptimizedAddRequest, +]; + +(function run(i) { + if (i < cases.length) cases[i](common.mustCall(() => run(i + 1))); +})(0); diff --git a/test/parallel/test-http-client-request-options-injection.js b/test/parallel/test-http-client-request-options-injection.js new file mode 100644 index 000000000000..47067f1895bd --- /dev/null +++ b/test/parallel/test-http-client-request-options-injection.js @@ -0,0 +1,54 @@ +'use strict'; + +const common = require('../common'); +const assert = require('node:assert'); +const http = require('node:http'); +const path = require('node:path'); +const tmpdir = require('../common/tmpdir'); + +// Regression test: an ordinary object that happens to satisfy `isURL()` (truthy +// `href`/`protocol`, with `auth`/`path` absent) must not be able to smuggle +// HTTP request options such as `socketPath`, `method`, `headers`, or `agent` +// through `urlToHttpOptions()`. Doing so would let an attacker redirect an +// otherwise hostname-validated request to a Unix domain socket (e.g. the +// Docker daemon) and defeat hostname-based SSRF defenses. + +const server = http.createServer(common.mustCall((req, res) => { + assert.strictEqual(req.method, 'GET'); // `method` must not be smuggled in. + assert.strictEqual(req.headers['x-injected'], undefined); // `headers` too. + assert.strictEqual(req.url, '/ping'); + res.writeHead(200); + res.end('pong'); +})); + +server.listen(0, common.localhostIPv4, common.mustCall(() => { + const { port } = server.address(); + // A duck-typed object that `isURL()` would accept, but which is not a genuine + // WHATWG URL instance. + const duckTypedUrl = { + href: 'http://127.0.0.1/verify', + protocol: 'http:', + hostname: '127.0.0.1', + pathname: '/ping', + port: String(port), + username: '', + password: '', + search: '', + hash: '', + socketPath: path.join(tmpdir.path, 'should-not-be-used.sock'), + method: 'POST', + headers: { 'x-injected': 'yes' }, + agent: false, + }; + const req = http.request(duckTypedUrl, common.mustCall((res) => { + let body = ''; + res.on('data', (chunk) => { body += chunk; }); + res.on('end', common.mustCall(() => { + assert.strictEqual(body, 'pong'); + server.close(); + })); + })); + req.on('error', common.mustNotCall( + 'request connected to the injected socketPath instead of the hostname')); + req.end(); +})); diff --git a/test/parallel/test-http-header-value-relaxed.js b/test/parallel/test-http-header-value-relaxed.js index 68311f3ce96a..3e0916c4f0ca 100644 --- a/test/parallel/test-http-header-value-relaxed.js +++ b/test/parallel/test-http-header-value-relaxed.js @@ -234,9 +234,49 @@ if (kRelaxedInboundSupported) { // Should not throw - control chars allowed in insecure mode req.setHeader('X-Test', 'value\x01here'); req.setHeader('X-Bel', 'ding\x07'); + // Outgoing values are validated as in relaxed mode: NUL, CR, and LF are + // still rejected, as they would allow header injection. + for (const value of ['value\x00here', 'value\rhere', 'value\nhere']) { + assert.throws(() => req.setHeader('X-Test', value), + { code: 'ERR_INVALID_CHAR' }); + assert.throws(() => req.appendHeader('X-Test', value), + { code: 'ERR_INVALID_CHAR' }); + } req.destroy(); } +// ============================================================================ +// Test 11b: httpValidation: 'insecure' server response still rejects +// NUL, CR, and LF in outgoing header values +// ============================================================================ +{ + const server = http.createServer({ + httpValidation: 'insecure', + }, common.mustCall((req, res) => { + for (const value of ['value\x00here', 'value\rhere', 'value\nhere']) { + assert.throws(() => res.setHeader('X-Test', value), + { code: 'ERR_INVALID_CHAR' }); + assert.throws(() => res.writeHead(200, { 'X-Test': value }), + { code: 'ERR_INVALID_CHAR' }); + } + res.setHeader('X-Custom', 'value\x01here'); + res.end('ok'); + })); + + server.listen(0, common.mustCall(() => { + http.get({ + port: server.address().port, + httpValidation: 'insecure', + }, common.mustCall((res) => { + assert.strictEqual(res.headers['x-custom'], 'value\x01here'); + res.resume(); + res.on('end', common.mustCall(() => { + server.close(); + })); + })); + })); +} + // ============================================================================ // Test 12: Mutual exclusion - client throws when both options are set // ============================================================================ diff --git a/test/parallel/test-http-outgoing-append-header-array.js b/test/parallel/test-http-outgoing-append-header-array.js new file mode 100644 index 000000000000..3fd3897e687c --- /dev/null +++ b/test/parallel/test-http-outgoing-append-header-array.js @@ -0,0 +1,79 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); +const { ServerResponse } = require('http'); + +// setHeader() stores a copy of an array value, so appendHeader() never +// mutates an array the caller passed in. Frozen arrays must not make +// appendHeader() throw. + +function createResponse() { + return new ServerResponse({ + method: 'GET', + httpVersionMajor: 1, + httpVersionMinor: 1, + }); +} + +// setHeader() with an array, then appendHeader(). +{ + const res = createResponse(); + const cookies = ['a=1']; + res.setHeader('Set-Cookie', cookies); + res.appendHeader('set-cookie', 'b=2'); + res.appendHeader('set-cookie', ['c=3', 'd=4']); + assert.deepStrictEqual(cookies, ['a=1']); + assert.deepStrictEqual(res.getHeader('set-cookie'), + ['a=1', 'b=2', 'c=3', 'd=4']); +} + +// The response owns the stored array: changing the caller's array later has +// no effect, and getHeader() returns the stored array itself. +{ + const res = createResponse(); + const cookies = ['a=1']; + res.setHeader('Set-Cookie', cookies); + cookies.push('b=2'); + assert.deepStrictEqual(res.getHeader('set-cookie'), ['a=1']); + res.getHeader('set-cookie').push('c=3'); + assert.deepStrictEqual(res.getHeader('set-cookie'), ['a=1', 'c=3']); +} + +// setHeader() with a frozen array, then appendHeader(). +{ + const res = createResponse(); + const cookies = Object.freeze(['a=1']); + res.setHeader('Set-Cookie', cookies); + res.appendHeader('set-cookie', 'b=2'); + assert.deepStrictEqual(res.getHeader('set-cookie'), ['a=1', 'b=2']); +} + +// appendHeader() with an array on an unset field, then appendHeader(). +{ + const res = createResponse(); + const cookies = Object.freeze(['a=1']); + res.appendHeader('Set-Cookie', cookies); + res.appendHeader('set-cookie', 'b=2'); + assert.deepStrictEqual(res.getHeader('set-cookie'), ['a=1', 'b=2']); +} + +// setHeaders() with an array value, then appendHeader(). +{ + const res = createResponse(); + const values = Object.freeze(['a', 'b']); + res.setHeaders(new Map([['x-foo', values]])); + res.appendHeader('x-foo', 'c'); + assert.deepStrictEqual(values, ['a', 'b']); + assert.deepStrictEqual(res.getHeader('x-foo'), ['a', 'b', 'c']); +} + +// writeHead() with a raw header array after setHeader(): duplicate names +// go through appendHeader(). +{ + const res = createResponse(); + res.setHeader('X-Other', '1'); + const cookies = Object.freeze(['a=1']); + res.writeHead(200, ['Set-Cookie', cookies, 'Set-Cookie', 'b=2']); + assert.deepStrictEqual(res.getHeader('set-cookie'), ['a=1', 'b=2']); +} diff --git a/test/parallel/test-http-outgoing-encoded-chunk-length.js b/test/parallel/test-http-outgoing-encoded-chunk-length.js new file mode 100644 index 000000000000..b28b0f54ddf1 --- /dev/null +++ b/test/parallel/test-http-outgoing-encoded-chunk-length.js @@ -0,0 +1,96 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const http = require('http'); +const net = require('net'); + +// The length announced for a chunk (or in Content-Length) must match the +// number of bytes actually written, also for encodings where the decoded size +// is smaller than the one estimated by `Buffer.byteLength()`. + +const cases = [ + // [string, encoding, expected decoded bytes] + ['QUJD REVG', 'base64', 'ABCDEF'], + ['QUJD\r\n\r\nREVG', 'BASE64', 'ABCDEF'], + ['QUJD REVG', 'base64url', 'ABCDEF'], + ['41424 3', 'hex', 'AB'], + ['4142zz4344', 'hex', 'AB'], + ['414', 'hex', 'A'], +]; + +// Reads the raw request, returning the body bytes de-framed according to +// the framing used. Fails if the framing is not exactly consumed. +function parseChunked(raw) { + let rest = raw; + let body = ''; + for (;;) { + const eol = rest.indexOf('\r\n'); + assert.notStrictEqual(eol, -1); + const size = parseInt(rest.slice(0, eol), 16); + rest = rest.slice(eol + 2); + if (size === 0) { + assert.strictEqual(rest, '\r\n'); + return body; + } + body += rest.slice(0, size); + assert.strictEqual(rest.slice(size, size + 2), '\r\n'); + rest = rest.slice(size + 2); + } +} + +function run(send, isComplete, verify) { + const server = net.createServer(common.mustCall((socket) => { + let data = ''; + socket.setEncoding('latin1'); + socket.on('data', (chunk) => { + data += chunk; + const idx = data.indexOf('\r\n\r\n'); + if (idx === -1) return; + const head = data.slice(0, idx); + const raw = data.slice(idx + 4); + if (isComplete(head, raw)) { + verify(head, raw); + socket.end('HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n'); + } + }); + })); + + server.listen(0, common.mustCall(() => { + const req = http.request({ port: server.address().port, method: 'POST', agent: false }, + common.mustCall((res) => { + res.resume(); + res.on('end', common.mustCall(() => server.close())); + })); + send(req); + })); +} + +for (const [str, encoding, expected] of cases) { + // Chunked, write() then end() + run((req) => { + req.write(str, encoding); + req.end(); + }, (head, raw) => raw.endsWith('0\r\n\r\n'), common.mustCall((head, raw) => { + assert.match(head, /Transfer-Encoding: chunked/i); + assert.strictEqual(parseChunked(raw), expected); + })); + + // Chunked, write() twice so a following chunk would be mis-framed + run((req) => { + req.write(str, encoding); + req.write('tail'); + req.end(); + }, (head, raw) => raw.endsWith('0\r\n\r\n'), common.mustCall((head, raw) => { + assert.strictEqual(parseChunked(raw), `${expected}tail`); + })); + + // Single final chunk: Content-Length is computed + run((req) => { + req.end(str, encoding); + }, (head, raw) => raw.length >= expected.length, common.mustCall((head, raw) => { + const match = /Content-Length: (\d+)/i.exec(head); + assert.ok(match); + assert.strictEqual(Number(match[1]), expected.length); + assert.strictEqual(raw, expected); + })); +} diff --git a/test/parallel/test-http2-buffered-response-after-close.js b/test/parallel/test-http2-buffered-response-after-close.js new file mode 100644 index 000000000000..59a10ebb7375 --- /dev/null +++ b/test/parallel/test-http2-buffered-response-after-close.js @@ -0,0 +1,79 @@ +'use strict'; + +// A client stream that closed normally can still hold its whole response in +// the readable buffer. Consuming it from then on must succeed rather than +// report ERR_STREAM_PREMATURE_CLOSE. +// Refs: https://github.com/nodejs/node/issues/65677 + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const http2 = require('http2'); +const { once } = require('events'); +const { Writable } = require('stream'); +const { finished, pipeline } = require('stream/promises'); +const { text } = require('stream/consumers'); +const { setImmediate: setImmediateAsync } = require('timers/promises'); + +const body = 'complete response'; + +const consumers = { + async asyncIterator(request) { + let received = ''; + for await (const chunk of request) + received += chunk; + return received; + }, + async finishedThenData(request) { + let received = ''; + const done = finished(request, { writable: false }); + request.on('data', (chunk) => { received += chunk; }); + await done; + return received; + }, + async pipeline(request) { + let received = ''; + await pipeline(request, new Writable({ + write(chunk, encoding, callback) { + received += chunk; + callback(); + }, + })); + return received; + }, + text, +}; + +const server = http2.createServer(); +server.on('stream', (stream) => { + stream.resume(); + stream.on('end', () => { + stream.respond({ ':status': 200 }, { waitForTrailers: true }); + stream.on('wantTrailers', () => stream.sendTrailers({ 'grpc-status': '0' })); + stream.end(body); + }); +}); + +server.listen(0, common.mustCall(async () => { + const session = http2.connect(`http://localhost:${server.address().port}`); + + for (const [name, consume] of Object.entries(consumers)) { + const request = session.request({ ':method': 'POST' }); + request.end('request'); + await once(request, 'response'); + + // Attempt to read the response _after_ the server has cleanly closed the stream: + while (!request.closed) + await setImmediateAsync(); + + assert.strictEqual(request.rstCode, http2.constants.NGHTTP2_NO_ERROR); + assert.strictEqual(request.destroyed, false); + assert.strictEqual(request.readableLength, Buffer.byteLength(body)); + assert.strictEqual(await consume(request), body, name); + } + + session.close(); + server.close(); +})); diff --git a/test/parallel/test-http2-client-reset-after-response.js b/test/parallel/test-http2-client-reset-after-response.js new file mode 100644 index 000000000000..0ad67dae03e2 --- /dev/null +++ b/test/parallel/test-http2-client-reset-after-response.js @@ -0,0 +1,61 @@ +'use strict'; + +// RFC 9113 section 8.1 allows a server to send RST_STREAM(NO_ERROR) after a +// complete response while the request is still open, and clients must not +// discard the response because of it. This is how servers send clients a +// response that cancels a request (e.g. politely rejecting an upload). +// The response should still stay fully readable and end cleanly, while the +// rest of the request is quietly discarded. +// Refs: https://github.com/nodejs/node/issues/66693 + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const http2 = require('http2'); +const { once } = require('events'); + +const body = 'upload rejected'; + +const server = http2.createServer(); +server.on('stream', common.mustCall((stream) => { + stream.respond({ ':status': 413 }); + stream.once('data', common.mustCall(() => { + stream.end(body); + stream.close(http2.constants.NGHTTP2_NO_ERROR); + })); +})); + +server.listen(0, common.mustCall(async () => { + const session = http2.connect(`http://localhost:${server.address().port}`); + const request = session.request({ ':method': 'POST' }); + request.on('error', common.mustNotCall()); + const [headers] = await once(request, 'response'); + assert.strictEqual(headers[':status'], 413); + + // Keep uploading without reading the response. The reset arrives partway + // through, and neither the write in flight then nor later ones may stall. + const chunk = Buffer.alloc(16 * 1024); + for (let i = 0; i < 20; i++) { + await new Promise((resolve) => { + request.write(chunk, common.mustSucceed(resolve)); + }); + } + assert.strictEqual(request.closed, true); + assert.strictEqual(request.rstCode, http2.constants.NGHTTP2_NO_ERROR); + assert.strictEqual(request.destroyed, false); + + request.end(); + await once(request, 'finish'); + + let received = ''; + request.setEncoding('utf8'); + request.on('data', (chunk) => { received += chunk; }); + request.on('end', common.mustCall()); + await once(request, 'close'); + assert.strictEqual(received, body); + + session.close(); + server.close(); +})); diff --git a/test/parallel/test-http2-client-reset-after-trailers.js b/test/parallel/test-http2-client-reset-after-trailers.js new file mode 100644 index 000000000000..b93c67fcd017 --- /dev/null +++ b/test/parallel/test-http2-client-reset-after-trailers.js @@ -0,0 +1,107 @@ +'use strict'; + +// A server may send the final DATA, trailers with END_STREAM and +// RST_STREAM(NO_ERROR) together while the request is still open (RFC 9113 +// section 8.1), as gRPC servers do. A client that has paused partway through +// the response must still be able to read the rest, and likewise for +// RST_STREAM(CANCEL), which should only affect the request. +// This closely reproduces https://github.com/nodejs/node/issues/66693 +// which requires some raw frame writes to match the reset behaviour. + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const http2 = require('http2'); +const net = require('net'); +const { once } = require('events'); +const { setImmediate: setImmediateAsync } = require('timers/promises'); +const h2test = require('../common/http2'); + +const first = Buffer.from('first chunk'); +const last = Buffer.from('last chunk'); +// HPACK: indexed :status 200. +const responseHeaders = Buffer.from([0x88]); +// HPACK: literal without indexing, grpc-status: 0. +const responseTrailers = Buffer.concat([ + Buffer.from([0x00, 11]), Buffer.from('grpc-status'), + Buffer.from([1]), Buffer.from('0'), +]); +const streamId = 1; +const startRequest = 'start of request'; +const continueRequest = 'more of request'; + +async function startServer(code) { + const server = net.createServer(common.mustCall((socket) => { + // Client request -> response frames flow for the server: + const replies = [ + [startRequest, [ + new h2test.HeadersFrame(streamId, responseHeaders), + new h2test.DataFrame(streamId, first), + ]], + [continueRequest, [ + new h2test.DataFrame(streamId, last), + new h2test.HeadersFrame(streamId, responseTrailers, 0, true), + new h2test.RstStreamFrame(streamId, code), + ]], + ]; + + let received = Buffer.alloc(0); + socket.on('error', () => {}); + socket.on('data', (chunk) => { + received = Buffer.concat([received, chunk]); + while (replies.length > 0 && received.includes(replies[0][0])) { + const [, frames] = replies.shift(); + socket.write(Buffer.concat(frames.map((frame) => frame.data))); + } + }); + + // Write settings to start the session: + socket.write(new h2test.SettingsFrame().data); + socket.write(new h2test.SettingsFrame(true).data); + })); + server.listen(0); + await once(server, 'listening'); + return server; +} + +(async () => { + for (const code of [ + http2.constants.NGHTTP2_NO_ERROR, + http2.constants.NGHTTP2_CANCEL, + ]) { + const server = await startServer(code); + const session = http2.connect(`http://localhost:${server.address().port}`); + const request = session.request({ ':method': 'POST' }); + request.on('error', common.mustNotCall()); + request.on('response', common.mustCall()); + + // Read the first response chunk, then stop reading. + request.write(startRequest); + const [chunk] = await once(request, 'data'); + assert.deepStrictEqual(chunk, first); + request.pause(); + + // Trigger the last response chunk + trailers + RST_STREAM. + request.write(continueRequest); + const [trailers] = await once(request, 'trailers'); + assert.strictEqual(trailers['grpc-status'], '0'); + + while (!request.closed) + await setImmediateAsync(); + assert.strictEqual(request.rstCode, code); + assert.strictEqual(request.destroyed, false); + + // Check that we can still read the response after the RST: + const chunks = []; + request.on('data', (chunk) => chunks.push(chunk)); + request.on('end', common.mustCall()); + request.resume(); + await once(request, 'close'); + assert.deepStrictEqual(Buffer.concat(chunks), last); + + session.destroy(); + server.close(); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-http2-close-destroy-queued-body.js b/test/parallel/test-http2-close-destroy-queued-body.js new file mode 100644 index 000000000000..68cc846ffbcf --- /dev/null +++ b/test/parallel/test-http2-close-destroy-queued-body.js @@ -0,0 +1,46 @@ +'use strict'; + +// Destroying a stream that was closed with NO_ERROR while its request body +// was still queued behind flow control must still send RST_STREAM. +// Refs: https://github.com/nodejs/node/issues/67363 + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const { NGHTTP2_NO_ERROR } = http2.constants; + +// A small stream window makes sure that most of the body stays queued. +const server = http2.createServer({ settings: { initialWindowSize: 16384 } }); + +let req; + +server.on('stream', common.mustCall((stream) => { + // The stream is not being read yet, so the request body is stuck behind + // flow control when the client closes and destroys the request. + req.close(); + req.destroy(); + + stream.on('error', common.expectsError({ + code: 'ERR_HTTP2_STREAM_ABORTED', + })); + stream.on('close', common.mustCall(() => { + assert.strictEqual(stream.rstCode, NGHTTP2_NO_ERROR); + server.close(); + })); + // Open the window again. Without the RST_STREAM this is what makes the + // client loop. + stream.resume(); +})); + +server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + req = client.request({ ':method': 'POST' }); + req.on('error', common.mustNotCall()); + req.on('close', common.mustCall(() => { + assert.strictEqual(req.rstCode, NGHTTP2_NO_ERROR); + client.close(); + })); + req.end(Buffer.alloc(1024 * 1024)); +})); diff --git a/test/parallel/test-http2-compat-get-headers.js b/test/parallel/test-http2-compat-get-headers.js index f98ceca1db14..b93ba5f8290b 100644 --- a/test/parallel/test-http2-compat-get-headers.js +++ b/test/parallel/test-http2-compat-get-headers.js @@ -33,7 +33,7 @@ const server = http2.createServer(common.mustCall((request, response) => { const headers = response.getHeaders(); assert.deepStrictEqual(headers, expected); assert.deepStrictEqual(Object.keys(headers), Object.keys(expected)); - assert.strictEqual(headers['set-cookie'], cookies); + assert.strictEqual(headers['set-cookie'], response.getHeader('set-cookie')); assert.notStrictEqual(response.getHeaders(), headers); headers['x-first'] = 'changed'; @@ -42,8 +42,9 @@ const server = http2.createServer(common.mustCall((request, response) => { assert.deepStrictEqual(response.getHeaders(), expected); headers['set-cookie'].push('third=value'); - assert.strictEqual(response.getHeader('set-cookie'), cookies); + assert.strictEqual(response.getHeader('set-cookie'), headers['set-cookie']); assert.strictEqual(response.getHeader('set-cookie').length, 3); + expected['set-cookie'] = [...cookies, 'third=value']; response.removeHeader('X-First'); response.setHeader('X-First', 'replacement'); diff --git a/test/parallel/test-http2-compat-serverrequest-end-after-abort.js b/test/parallel/test-http2-compat-serverrequest-end-after-abort.js new file mode 100644 index 000000000000..3652e0a51787 --- /dev/null +++ b/test/parallel/test-http2-compat-serverrequest-end-after-abort.js @@ -0,0 +1,152 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// A request whose stream is reset by the peer before END_STREAM has an +// incomplete body. Like http1, the compat request must not emit 'end' for it. + +const assert = require('assert'); +const http2 = require('http2'); +const { finished } = require('stream'); + +const codes = [ + http2.constants.NGHTTP2_NO_ERROR, + http2.constants.NGHTTP2_CANCEL, +]; + +const server = http2.createServer(common.mustCall((req, res) => { + // Tell the client the partial body arrived, so it can reset the stream. + req.once('data', common.mustCall(() => res.writeHead(200).flushHeaders())); + req.on('end', common.mustNotCall()); + req.on('aborted', common.mustCall()); + req.on('error', common.expectsError({ code: 'ERR_HTTP2_STREAM_ABORTED' })); + req.on('close', common.mustCall(() => { + assert.strictEqual(req.aborted, true); + assert.strictEqual(req.readableEnded, false); + })); + finished(req, common.mustCall((err) => { + assert.ok(err); + })); +}, codes.length)); + +server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + let pending = codes.length; + + for (const code of codes) { + const req = client.request({ + ':method': 'POST', + 'content-length': '1000', + }); + req.on('error', () => {}); + req.on('close', common.mustCall(() => { + if (--pending === 0) { + client.close(); + server.close(); + } + })); + // Send part of the body, then reset the stream without END_STREAM once + // the server has seen it. + req.write('{"action":"partial"}'); + req.on('response', common.mustCall(() => req.close(code))); + } +})); + +// A complete body followed by a reset still ends the request normally. +{ + const server = http2.createServer(common.mustCall((req, res) => { + let body = ''; + req.setEncoding('utf8'); + req.on('data', (chunk) => body += chunk); + req.on('end', common.mustCall(() => { + assert.strictEqual(body, 'complete'); + res.writeHead(200).flushHeaders(); + })); + req.on('error', common.mustNotCall()); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request({ ':method': 'POST' }); + req.on('error', () => {}); + req.on('response', common.mustCall(() => { + req.close(http2.constants.NGHTTP2_CANCEL); + })); + req.on('close', common.mustCall(() => { + client.close(); + server.close(); + })); + req.end('complete'); + })); +} + +// A stream closed locally by the server before the peer sends END_STREAM also +// has an incomplete body and must not emit 'end'. +{ + const server = http2.createServer(common.mustCall((req, res) => { + req.once('data', common.mustCall(() => { + // Tear the stream down locally while the body is still in flight. + req.stream.destroy(); + })); + req.on('end', common.mustNotCall()); + req.on('aborted', common.mustCall()); + req.on('error', common.mustNotCall()); + req.on('close', common.mustCall(() => { + assert.strictEqual(req.aborted, true); + assert.strictEqual(req.readableEnded, false); + })); + finished(req, common.mustCall((err) => { + assert.ok(err); + })); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request({ + ':method': 'POST', + 'content-length': '1000', + }); + req.on('error', () => {}); + req.on('close', common.mustCall(() => { + client.close(); + server.close(); + })); + req.write('{"action":"partial"}'); + })); +} + +// An unexpected session teardown mid-body also produces an incomplete request +// that must not emit 'end'. +{ + const server = http2.createServer(common.mustCall((req, res) => { + req.once('data', common.mustCall(() => { + req.stream.session.destroy(); + })); + req.on('end', common.mustNotCall()); + req.on('aborted', common.mustCall()); + req.on('error', common.mustNotCall()); + req.on('close', common.mustCall(() => { + assert.strictEqual(req.aborted, true); + assert.strictEqual(req.readableEnded, false); + })); + finished(req, common.mustCall((err) => { + assert.ok(err); + })); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request({ + ':method': 'POST', + 'content-length': '1000', + }); + req.on('error', () => {}); + req.on('close', common.mustCall(() => { + client.close(); + server.close(); + })); + req.write('{"action":"partial"}'); + })); +} diff --git a/test/parallel/test-http2-compat-serverresponse-headers.js b/test/parallel/test-http2-compat-serverresponse-headers.js index 95423fd09d8e..43d5f46d470f 100644 --- a/test/parallel/test-http2-compat-serverresponse-headers.js +++ b/test/parallel/test-http2-compat-serverresponse-headers.js @@ -47,6 +47,14 @@ server.listen(0, common.mustCall(function() { ]); assert.strictEqual(response.hasHeader(real), true); + // appendHeader() must not mutate an array passed to setHeader(). + const values = Object.freeze(['a', 'b']); + response.setHeader('x-array', values); + response.appendHeader('x-array', 'c'); + assert.deepStrictEqual(values, ['a', 'b']); + assert.deepStrictEqual(response.getHeader('x-array'), ['a', 'b', 'c']); + response.removeHeader('x-array'); + response.removeHeader(denormalised); assert.strictEqual(response.hasHeader(denormalised), false); assert.strictEqual(response.hasHeader(real), false); diff --git a/test/parallel/test-http2-compat-write-information-callback.js b/test/parallel/test-http2-compat-write-information-callback.js new file mode 100644 index 000000000000..ecca7897ed2c --- /dev/null +++ b/test/parallel/test-http2-compat-write-information-callback.js @@ -0,0 +1,144 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) common.skip('missing crypto'); + +const assert = require('node:assert'); +const http2 = require('node:http2'); + +// The callback passed to writeContinue(), writeEarlyHints() and +// writeInformation() is called asynchronously, in order, once the +// informational headers have been written to the socket. +{ + const server = http2.createServer(); + + server.on('request', common.mustCall((req, res) => { + const { socket } = res.stream.session; + const bytesWritten = socket.bytesWritten; + const order = []; + let sync = true; + + assert.strictEqual(res.writeContinue(common.mustCall((err) => { + assert.strictEqual(err, null); + assert.strictEqual(sync, false); + assert.ok(socket.bytesWritten > bytesWritten); + order.push(100); + })), true); + assert.strictEqual(res.writeEarlyHints({ + link: '</styles.css>; rel=preload; as=style', + }, common.mustCall((err) => { + assert.strictEqual(err, null); + order.push(103); + })), true); + const onInformation = common.mustCall((err) => { + assert.strictEqual(err, null); + order.push(110); + assert.deepStrictEqual(order, [100, 103, 110]); + res.end('done'); + }); + assert.strictEqual( + res.writeInformation(110, { 'X-Progress': '50%' }, onInformation), true); + sync = false; + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request(); + + const seen = []; + req.on('headers', (headers) => seen.push(headers[':status'])); + req.on('response', common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.deepStrictEqual(seen, [100, 103, 110]); + })); + + req.resume(); + req.on('end', common.mustCall(() => { + client.close(); + server.close(); + })); + })); +} + +// The headers can be omitted, with or without a callback. +{ + const server = http2.createServer(); + + server.on('request', common.mustCall((req, res) => { + const order = []; + + assert.strictEqual(res.writeInformation(102), true); + assert.strictEqual(res.writeInformation(102, { 'X-Call': 'headers' }), true); + assert.strictEqual(res.writeInformation( + 102, { 'X-Call': 'headers-callback' }, common.mustCall((err) => { + assert.strictEqual(err, null); + order.push('headers-callback'); + })), true); + assert.strictEqual(res.writeInformation( + 102, undefined, common.mustCall((err) => { + assert.strictEqual(err, null); + order.push('undefined-callback'); + assert.deepStrictEqual( + order, ['headers-callback', 'undefined-callback']); + res.end('done'); + })), true); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request(); + + const seen = []; + req.on('headers', (headers) => { + seen.push([headers[':status'], headers['x-call']]); + }); + req.on('response', common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.deepStrictEqual(seen, [ + [102, undefined], + [102, 'headers'], + [102, 'headers-callback'], + [102, undefined], + ]); + })); + + req.resume(); + req.on('end', common.mustCall(() => { + client.close(); + server.close(); + })); + })); +} + +// The callback is not called when nothing is sent, and a non-function +// callback is rejected. +{ + const server = http2.createServer(); + + server.on('request', common.mustCall((req, res) => { + for (const cb of [null, 1, 'cb', {}]) { + assert.throws(() => res.writeContinue(cb), + { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => res.writeInformation(110, undefined, cb), + { code: 'ERR_INVALID_ARG_TYPE' }); + assert.throws(() => res.writeEarlyHints({ link: '</a>' }, cb), + { code: 'ERR_INVALID_ARG_TYPE' }); + } + + res.writeHead(200); + assert.strictEqual(res.writeContinue(common.mustNotCall()), false); + assert.strictEqual( + res.writeInformation(110, undefined, common.mustNotCall()), false); + res.end(); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request(); + req.resume(); + req.on('end', common.mustCall(() => { + client.close(); + server.close(); + })); + })); +} diff --git a/test/parallel/test-http2-info-headers-callback-reentrant.js b/test/parallel/test-http2-info-headers-callback-reentrant.js new file mode 100644 index 000000000000..767dcd72e8b0 --- /dev/null +++ b/test/parallel/test-http2-info-headers-callback-reentrant.js @@ -0,0 +1,75 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const http2 = require('http2'); +const { duplexPair } = require('stream'); +const { setImmediate } = require('timers/promises'); + +// Informational headers that are sent from the completion callback of another +// write belong to the next write to the underlying stream. Their callback must +// not be called before that write has finished. + +(async () => { + const [clientSide, serverSide] = duplexPair(); + let hold = false; + let pendingWrite; + const originalWrite = serverSide._write; + serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) { + if (hold) { + // Deliver the data, but do not complete the write. + assert.strictEqual(pendingWrite, undefined); + originalWrite.call(this, buf, enc, common.mustCall(() => { + pendingWrite = cb; + })); + return; + } + originalWrite.call(this, buf, enc, cb); + }); + + const server = http2.createServer(); + let called = false; + let first; + server.on('stream', common.mustCall((stream) => { + if (first === undefined) { + first = stream; + return; + } + first.respond(); + first.write('data', common.mustCall(() => { + // This runs while the write that carried the DATA frame is being + // completed. Closing the first stream starts the next write, which + // carries the informational headers of the second stream. + hold = true; + stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => { + assert.strictEqual(err, null); + called = true; + })); + first.close(); + })); + }, 2)); + server.emit('connection', serverSide); + + const client = http2.connect('http://localhost', { + createConnection: () => clientSide, + }); + const req1 = client.request(); + req1.on('error', () => {}); + req1.resume(); + const req2 = client.request(); + req2.resume(); + await new Promise((resolve) => req2.on('headers', common.mustCall(resolve))); + + assert.strictEqual(typeof pendingWrite, 'function'); + assert.strictEqual(called, false); + hold = false; + pendingWrite(); + await setImmediate(); + assert.strictEqual(called, true); + + client.destroy(); + server.close(); +})().then(common.mustCall()); diff --git a/test/parallel/test-http2-info-headers-callback.js b/test/parallel/test-http2-info-headers-callback.js new file mode 100644 index 000000000000..e59e339069ee --- /dev/null +++ b/test/parallel/test-http2-info-headers-callback.js @@ -0,0 +1,171 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) common.skip('missing crypto'); + +const assert = require('node:assert'); +const http2 = require('node:http2'); +const { duplexPair } = require('node:stream'); + +// The callback passed to additionalHeaders() is called once the HEADERS frame +// has been written to the socket. +{ + const server = http2.createServer(); + + server.on('stream', common.mustCall((stream) => { + const { socket } = stream.session; + const bytesWritten = socket.bytesWritten; + let sync = true; + + for (const callback of [null, 1, 'callback', {}]) { + assert.throws(() => stream.additionalHeaders({ ':status': 103 }, callback), + { code: 'ERR_INVALID_ARG_TYPE' }); + } + + // Informational headers without a callback do not shift the callbacks of + // the ones that follow. + stream.additionalHeaders({ ':status': 102 }); + stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => { + assert.strictEqual(err, null); + assert.strictEqual(sync, false); + assert.ok(socket.bytesWritten > bytesWritten); + stream.respond(); + stream.end('done'); + })); + sync = false; + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request(); + + const seen = []; + req.on('headers', (headers) => seen.push(headers[':status'])); + req.on('response', common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.deepStrictEqual(seen, [102, 103]); + })); + + req.resume(); + req.on('end', common.mustCall(() => { + client.close(); + server.close(); + })); + })); +} + +// The callback is called with an error if the session is destroyed before the +// HEADERS frame is written. +{ + const server = http2.createServer(); + + server.on('stream', common.mustCall((stream) => { + stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => { + assert.strictEqual(err.code, 'ECANCELED'); + server.close(); + })); + stream.session.destroy(); + })); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + client.on('error', () => {}); + const req = client.request(); + req.on('headers', common.mustNotCall()); + req.on('error', () => {}); + req.on('close', common.mustCall(() => client.destroy())); + req.resume(); + })); +} + +// The callback is called with an error if the write to the underlying stream +// that carries the HEADERS frame fails. +{ + const kHeadersFrameType = 1; + const hasHeadersFrame = (buf) => { + for (let offset = 0; offset + 9 <= buf.length;) { + if (buf[offset + 3] === kHeadersFrameType) + return true; + offset += 9 + buf.readUIntBE(offset, 3); + } + return false; + }; + + const [clientSide, serverSide] = duplexPair(); + const originalWrite = serverSide._write; + serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) { + if (hasHeadersFrame(buf)) + return cb(new Error('write failed')); + originalWrite.call(this, buf, enc, cb); + }); + + const server = http2.createServer(); + server.on('sessionError', common.mustCall()); + server.on('stream', common.mustCall((stream) => { + stream.on('error', common.mustCall()); + stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => { + assert.strictEqual(err.code, 'EPIPE'); + assert.strictEqual(err.syscall, 'write'); + client.destroy(); + })); + })); + server.emit('connection', serverSide); + + const client = http2.connect('http://localhost', { + createConnection: () => clientSide, + }); + client.on('error', () => {}); + const req = client.request(); + req.on('headers', common.mustNotCall()); + req.on('error', () => {}); + req.resume(); +} + +// The callback is called with an error if the stream is destroyed before the +// HEADERS frame has been serialized. This happens when another write to the +// underlying stream is still in progress, so that the frame is still queued. +{ + const [clientSide, serverSide] = duplexPair(); + let hold = false; + let pendingWrite; + let onHold; + const originalWrite = serverSide._write; + serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) { + if (!hold) + return originalWrite.call(this, buf, enc, cb); + // Deliver the data, but do not complete the write yet. + originalWrite.call(this, buf, enc, common.mustCall(() => { + pendingWrite = cb; + onHold(); + })); + }); + + const server = http2.createServer(); + server.on('stream', common.mustCall((stream) => { + onHold = common.mustCall(() => { + stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => { + assert.strictEqual(err.code, 'ECANCELED'); + hold = false; + pendingWrite(); + })); + stream.destroy(); + }); + hold = true; + stream.additionalHeaders({ ':status': 102 }); + })); + server.emit('connection', serverSide); + + const client = http2.connect('http://localhost', { + createConnection: () => clientSide, + }); + client.on('error', () => {}); + const req = client.request(); + const seen = []; + req.on('headers', (headers) => seen.push(headers[':status'])); + req.on('error', () => {}); + req.on('close', common.mustCall(() => { + assert.deepStrictEqual(seen, [102]); + client.destroy(); + })); + req.resume(); +} diff --git a/test/parallel/test-http2-info-headers-errors.js b/test/parallel/test-http2-info-headers-errors.js index aa1e28222c4c..72f235534571 100644 --- a/test/parallel/test-http2-info-headers-errors.js +++ b/test/parallel/test-http2-info-headers-errors.js @@ -4,6 +4,7 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); +const assert = require('assert'); const http2 = require('http2'); const { internalBinding } = require('internal/test/binding'); const { @@ -57,7 +58,11 @@ server.on('stream', common.mustCall((stream, headers) => { stream.on('error', errorMustNotCall); } - stream.additionalHeaders({ ':status': 100 }); + // The callback is called with the same error. + stream.additionalHeaders({ ':status': 100 }, common.mustCall((err) => { + assert.strictEqual(err.code, currentError.error.code); + assert.strictEqual(err.message, currentError.error.message); + })); }, tests.length)); server.listen(0, common.mustCall(() => runTest(tests.shift()))); diff --git a/test/parallel/test-http2-info-headers-reset-pending-write.js b/test/parallel/test-http2-info-headers-reset-pending-write.js new file mode 100644 index 000000000000..9b9e417086b5 --- /dev/null +++ b/test/parallel/test-http2-info-headers-reset-pending-write.js @@ -0,0 +1,82 @@ +// Flags: --expose-gc +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const http2 = require('http2'); +const { duplexPair } = require('stream'); +const { setImmediate } = require('timers/promises'); + +// The stream can be reset and garbage collected while the write that carries +// its informational headers is still pending. The callback must not be called +// before that write has finished, and completing it must not crash. + +const { NGHTTP2_CANCEL } = http2.constants; +const kHeadersFrameType = 1; + +function hasHeadersFrame(buf) { + for (let offset = 0; offset + 9 <= buf.length;) { + if (buf[offset + 3] === kHeadersFrameType) + return true; + offset += 9 + buf.readUIntBE(offset, 3); + } + return false; +} + +(async () => { + const [clientSide, serverSide] = duplexPair(); + let pendingWrite; + const originalWrite = serverSide._write; + serverSide._write = common.mustCallAtLeast(function(buf, enc, cb) { + // Deliver the data, but do not complete the write that carries the + // informational headers. + const hold = hasHeadersFrame(buf); + originalWrite.call(this, buf, enc, common.mustCall(() => { + if (hold) { + assert.strictEqual(pendingWrite, undefined); + pendingWrite = cb; + } else { + cb(); + } + })); + }); + + const server = http2.createServer(); + let called = false; + let streamClosed; + const closed = new Promise((resolve) => { streamClosed = resolve; }); + server.on('stream', common.mustCall((stream) => { + stream.on('close', common.mustCall(streamClosed)); + stream.additionalHeaders({ ':status': 103 }, common.mustCall((err) => { + assert.strictEqual(err, null); + called = true; + })); + })); + server.emit('connection', serverSide); + + const client = http2.connect('http://localhost', { + createConnection: () => clientSide, + }); + const req = client.request(); + req.on('headers', common.mustCall(() => req.close(NGHTTP2_CANCEL))); + req.resume(); + + await closed; + // Let the deferred native stream cleanup run, then collect the wrapper + // while the write is still awaiting completion. + for (let i = 0; i < 10; i++) { + await setImmediate(); + global.gc(); + } + assert.strictEqual(typeof pendingWrite, 'function'); + assert.strictEqual(called, false); + pendingWrite(); + await setImmediate(); + assert.strictEqual(called, true); + + client.destroy(); + server.close(); +})().then(common.mustCall()); diff --git a/test/parallel/test-http2-max-session-memory-client-request.js b/test/parallel/test-http2-max-session-memory-client-request.js new file mode 100644 index 000000000000..96abde18ebd5 --- /dev/null +++ b/test/parallel/test-http2-max-session-memory-client-request.js @@ -0,0 +1,167 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const http2 = require('http2'); +const net = require('net'); +const { once } = require('events'); + +// maxSessionMemory is documented to reject new streams while the limit is +// exceeded. Make sure that also holds for requests initiated by a client +// session, so that a peer that does not read cannot make the client queue +// frames without bound. As for response headers, request bodies that are +// queued waiting for flow control are not counted, so a large upload does not +// prevent unrelated requests on the same session. + +async function queuedUploadDoesNotBlockRequests() { + // The server never opens its flow-control window, so the upload stays queued + // in the client session. + const server = http2.createServer({ settings: { initialWindowSize: 0 } }); + server.on('stream', common.mustCall((stream) => { + stream.on('error', () => {}); + }, 2)); + server.listen(0); + await once(server, 'listening'); + + const client = http2.connect(`http://localhost:${server.address().port}`, { + maxSessionMemory: 1, + }); + client.on('error', common.mustNotCall()); + await once(client, 'remoteSettings'); + + const uploadArrived = once(server, 'stream'); + const upload = client.request({ ':method': 'POST', ':path': '/upload' }); + upload.on('error', () => {}); + upload.end(Buffer.alloc(4 * 1024 * 1024)); + await uploadArrived; + + const other = client.request({ ':path': '/other' }); + other.on('error', () => {}); + await once(server, 'stream'); + + other.destroy(); + upload.destroy(); + client.destroy(); + server.close(); +} + +// A minimal HTTP/2 peer on a plain TCP socket, so that it can genuinely stop +// reading. It acknowledges SETTINGS and answers every request with +// `:status: 200` and END_STREAM, which closes the stream. +function respondingPeer(socket) { + socket.write(Buffer.from([0, 0, 0, 4, 0, 0, 0, 0, 0])); // SETTINGS + let buffered = Buffer.alloc(0); + let prefaceSeen = false; + socket.on('data', (chunk) => { + buffered = Buffer.concat([buffered, chunk]); + if (!prefaceSeen) { + if (buffered.length < 24) return; + buffered = buffered.subarray(24); + prefaceSeen = true; + } + while (buffered.length >= 9) { + const length = buffered.readUIntBE(0, 3); + if (buffered.length < 9 + length) return; + const type = buffered[3]; + const flags = buffered[4]; + const streamId = buffered.readUInt32BE(5) & 0x7fffffff; + buffered = buffered.subarray(9 + length); + if (type === 4 && !(flags & 1)) { + socket.write(Buffer.from([0, 0, 0, 4, 1, 0, 0, 0, 0])); // SETTINGS ACK + } else if (type === 1) { + // HEADERS, END_STREAM | END_HEADERS, ':status: 200' (static index 8). + const frame = Buffer.from([0, 0, 1, 1, 5, 0, 0, 0, 0, 0x88]); + frame.writeUInt32BE(streamId, 5); + socket.write(frame); + } + } + }); +} + +async function stalledPeerRejectsRequestsAndSessionRecovers(stall) { + // Requests are submitted in batches that yield to the event loop, so their + // frames are written to the socket. While the peer answers them, streams + // close and nothing is rejected; once it stops reading, no responses arrive, + // so streams stay open and accumulate until maxSessionMemory rejects new + // requests. + let peerSocket; + const server = net.createServer((socket) => { + peerSocket = socket; + respondingPeer(socket); + }); + server.listen(0); + await once(server, 'listening'); + + const client = http2.connect(`http://localhost:${server.address().port}`, { + maxSessionMemory: 1, + }); + client.on('error', () => {}); + await once(client, 'remoteSettings'); + if (stall) peerSocket.pause(); + + let rejection; + const closed = []; + for (let batch = 0; batch < 200 && rejection === undefined; batch++) { + const batchClosed = []; + for (let i = 0; i < 100; i++) { + const req = client.request({ ':path': '/' }); + req.on('error', (err) => { + if (err.code === 'ERR_HTTP2_SESSION_MEMORY_EXCEEDED') rejection ??= err; + }); + batchClosed.push(new Promise((resolve) => req.once('close', resolve))); + req.end(); + } + closed.push(...batchClosed); + // With a responsive peer, wait for the batch to finish so that the number + // of open streams does not depend on how quickly the peer answers. + await (stall ? new Promise(setImmediate) : Promise.all(batchClosed)); + } + + if (!stall) { + assert.strictEqual(rejection, undefined); + client.destroy(); + peerSocket.destroy(); + server.close(); + return; + } + + assert.ok(rejection, 'expected a request to be rejected'); + assert.strictEqual( + rejection.message, + 'The request was not sent because the session exceeded maxSessionMemory'); + assert.strictEqual(client.destroyed, false); + assert.strictEqual(client.closed, false); + + // Once the peer reads again it answers the open streams, which close and + // free session memory, so a request that was rejected can be retried on the + // same session. + peerSocket.resume(); + await Promise.all(closed); + let retry; + for (;;) { + retry = client.request({ ':path': '/retry' }); + retry.resume(); + retry.end(); + // An accepted request gets its stream ID synchronously. + if (!retry.pending) break; + const [err] = await once(retry, 'error'); + assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_MEMORY_EXCEEDED'); + await new Promise(setImmediate); + } + await once(retry, 'close'); + assert.strictEqual(retry.rstCode, 0); + assert.strictEqual(client.destroyed, false); + + client.destroy(); + peerSocket.destroy(); + server.close(); +} + +(async () => { + await queuedUploadDoesNotBlockRequests(); + await stalledPeerRejectsRequestsAndSessionRecovers(false); + await stalledPeerRejectsRequestsAndSessionRecovers(true); +})().then(common.mustCall()); diff --git a/test/parallel/test-http2-max-session-memory-response-limits.js b/test/parallel/test-http2-max-session-memory-response-limits.js index ca4458725d00..e0f71d88ba4b 100644 --- a/test/parallel/test-http2-max-session-memory-response-limits.js +++ b/test/parallel/test-http2-max-session-memory-response-limits.js @@ -16,6 +16,10 @@ async function test(kind, bodySize = 4 * 1024 * 1024) { server.on('session', (session) => sessions.add(session)); server.on('stream', (stream) => { stream.on('error', () => {}); + // Leave the response open. Ending it before the request body arrives + // makes the server send RST_STREAM(NO_ERROR), which can reach the client + // together with the rejected headers and close the stream before the + // client's own reset does. switch (kind) { case 'repeated-informational': for (let i = 0; i < 80; i++) { @@ -25,15 +29,12 @@ async function test(kind, bodySize = 4 * 1024 * 1024) { break; case 'pairs': stream.respond({ ':status': 413, 'a': '1', 'b': '2', 'c': '3', 'd': '4' }); - stream.end(); return; case 'size': stream.respond({ ':status': 413, 'x-large': 'x'.repeat(2048) }); - stream.end(); return; } stream.respond({ ':status': 413 }); - stream.end(); }); server.listen(0); await once(server, 'listening'); diff --git a/test/parallel/test-http2-server-close-destroy-queued-body.js b/test/parallel/test-http2-server-close-destroy-queued-body.js new file mode 100644 index 000000000000..635b8fe5241f --- /dev/null +++ b/test/parallel/test-http2-server-close-destroy-queued-body.js @@ -0,0 +1,51 @@ +'use strict'; + +// Destroying a stream that was closed with NO_ERROR while its response body +// was still queued behind flow control must still send RST_STREAM. +// Refs: https://github.com/nodejs/node/issues/67363 + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const { NGHTTP2_NO_ERROR } = http2.constants; + +const server = http2.createServer(); + +let serverStream; + +server.on('stream', common.mustCall((stream) => { + serverStream = stream; + stream.on('error', common.mustNotCall()); + stream.on('close', common.mustCall(() => { + assert.strictEqual(stream.rstCode, NGHTTP2_NO_ERROR); + })); + stream.respond(); + stream.end(Buffer.alloc(1024 * 1024)); +})); + +server.listen(0, common.mustCall(() => { + // A small stream window makes sure that most of the body stays queued. + const client = http2.connect(`http://localhost:${server.address().port}`, + { settings: { initialWindowSize: 16384 } }); + const req = client.request(); + req.on('response', common.mustCall(() => { + // The response is not being read yet, so the response body is stuck + // behind flow control when the server closes and destroys the stream. + serverStream.close(); + serverStream.destroy(); + // Open the window again. Without the RST_STREAM this is what makes the + // server loop. + req.resume(); + })); + req.on('error', common.expectsError({ + code: 'ERR_HTTP2_STREAM_ABORTED', + })); + req.on('close', common.mustCall(() => { + assert.strictEqual(req.rstCode, NGHTTP2_NO_ERROR); + client.close(); + server.close(); + })); + req.end(); +})); diff --git a/test/parallel/test-http2-server-set-headers.js b/test/parallel/test-http2-server-set-headers.js new file mode 100644 index 000000000000..943e87c97d98 --- /dev/null +++ b/test/parallel/test-http2-server-set-headers.js @@ -0,0 +1,204 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const body = + '<html><head></head><body><h1>this is some data</h2></body></html>'; + +// Starts a server with the given request handler, sends one request and +// calls onResponse with the response headers. +function testResponse(onRequest, onResponse) { + const server = http2.createServer(onRequest); + server.on('error', common.mustNotCall()); + + server.listen(0, common.mustCall(() => { + const client = http2.connect(`http://localhost:${server.address().port}`); + const req = client.request({ ':path': '/' }); + req.setEncoding('utf8'); + req.on('response', onResponse); + + let data = ''; + req.on('data', (d) => data += d); + req.on('end', common.mustCall(() => { + assert.strictEqual(data, body); + server.close(); + client.close(); + })); + req.end(); + })); +} + +// Map, including a header name that is not lower case and a connection +// header, which is dropped with a warning. +{ + const compatMsg = 'The provided connection header is not valid, ' + + 'the value will be dropped from the header and ' + + 'will never be in use.'; + common.expectWarning('UnsupportedWarning', compatMsg); + + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Map([ + ['foobar', 'baz'], + ['X-POWERED-BY', 'node-test'], + ['connection', 'connection-test'], + ])); + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.strictEqual(headers.foobar, 'baz'); + assert.strictEqual(headers['x-powered-by'], 'node-test'); + assert.strictEqual(headers.connection, undefined); + })); +} + +// Headers instance. +{ + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Headers({ foo: '1', bar: '2' })); + res.writeHead(200); + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.strictEqual(headers.foo, '1'); + assert.strictEqual(headers.bar, '2'); + })); +} + +// An existing header is replaced. +{ + testResponse(common.mustCall((req, res) => { + res.setHeader('foo', '1'); + res.setHeader('bar', '2'); + res.setHeaders(new Headers({ foo: '3' })); + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers.foo, '3'); + assert.strictEqual(headers.bar, '2'); + })); +} + +// Headers passed to writeHead() as an object take precedence. +{ + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Headers({ foo: '1', bar: '2' })); + res.writeHead(200, { foo: '3' }); + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.strictEqual(headers.foo, '3'); + assert.strictEqual(headers.bar, '2'); + })); +} + +// Headers passed to writeHead() as an array take precedence. +{ + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Headers({ foo: '1', bar: '2' })); + res.writeHead(200, ['foo', '3']); + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers[':status'], 200); + assert.strictEqual(headers.foo, '3'); + assert.strictEqual(headers.bar, '2'); + })); +} + +// Multiple set-cookie values appended to a Headers instance. +{ + testResponse(common.mustCall((req, res) => { + const headers = new Headers(); + headers.append('Set-Cookie', 'a=b'); + headers.append('Set-Cookie', 'c=d'); + res.setHeaders(headers); + res.end(body); + }), common.mustCall((headers) => { + assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']); + })); +} + +// Multiple set-cookie values as an array in a Map, with a name that is not +// lower case. +{ + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Map([['Set-Cookie', ['a=b', 'c=d']]])); + res.end(body); + }), common.mustCall((headers) => { + assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']); + })); +} + +// Lower case set-cookie in a Map, as an array and as a single value. +{ + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Map([['set-cookie', ['a=b', 'c=d']]])); + res.end(body); + }), common.mustCall((headers) => { + assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']); + })); + + testResponse(common.mustCall((req, res) => { + res.setHeaders(new Map([['set-cookie', 'a=b']])); + res.end(body); + }), common.mustCall((headers) => { + assert.deepStrictEqual(headers['set-cookie'], ['a=b']); + })); +} + +// set-cookie values replace the ones set before. +{ + testResponse(common.mustCall((req, res) => { + res.setHeader('set-cookie', ['x=y']); + const headers = new Headers(); + headers.append('Set-Cookie', 'a=b'); + headers.append('Set-Cookie', 'c=d'); + res.setHeaders(headers); + res.end(body); + }), common.mustCall((headers) => { + assert.deepStrictEqual(headers['set-cookie'], ['a=b', 'c=d']); + })); +} + +// Throws when the headers have already been sent. +{ + testResponse(common.mustCall((req, res) => { + res.writeHead(200); + assert.throws(() => { + res.setHeaders(new Headers({ foo: '1' })); + }, { + code: 'ERR_HTTP2_HEADERS_SENT', + name: 'Error', + }); + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers.foo, undefined); + })); +} + +// Throws when headers is neither a Headers instance nor a Map. +{ + testResponse(common.mustCall((req, res) => { + for (const headers of [ + ['foo', '1'], + { foo: '1' }, + null, + undefined, + 'test', + 1, + { keys() {} }, + { get() {} }, + ]) { + assert.throws(() => { + res.setHeaders(headers); + }, { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + }); + } + res.end(body); + }), common.mustCall((headers) => { + assert.strictEqual(headers.foo, undefined); + })); +} diff --git a/test/parallel/test-http2-session-destroy-pending-write.js b/test/parallel/test-http2-session-destroy-pending-write.js new file mode 100644 index 000000000000..7ff3941a0724 --- /dev/null +++ b/test/parallel/test-http2-session-destroy-pending-write.js @@ -0,0 +1,91 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// Destroying a session while a socket write is pending must flush the final +// GOAWAY before ending the socket, including when called from a stream handler. +const assert = require('assert'); +const http2 = require('http2'); +const { Duplex } = require('stream'); +const { + HeadersFrame, + SettingsFrame, + kClientMagic, + kFakeRequestHeaders, +} = require('../common/http2'); + +for (const [code, deferDestroy] of [ + [0, false], + [http2.constants.NGHTTP2_REFUSED_STREAM, false], + [0, true], + [http2.constants.NGHTTP2_REFUSED_STREAM, true], +]) { + const output = []; + let pendingWrite; + const socket = new Duplex({ + read() {}, + write(chunk, encoding, callback) { + output.push(Buffer.from(chunk)); + if (pendingWrite === undefined) { + // Hold the initial SETTINGS write until the stream handler destroys + // the session. No timers or large response bodies are needed. + pendingWrite = callback; + setImmediate(() => { + socket.push(new HeadersFrame(1, kFakeRequestHeaders, 0, true).data); + }); + } else { + callback(); + } + }, + }); + + const session = http2.performServerHandshake(socket); + session.on('stream', common.mustCall((stream) => { + assert.strictEqual(typeof pendingWrite, 'function'); + stream.on('close', common.mustCall()); + if (code !== 0) { + stream.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_ERROR'); + })); + } + const destroy = common.mustCall(() => { + session.destroy(code); + assert.strictEqual(session.destroyed, true); + setImmediate(common.mustCall(() => { + const callback = pendingWrite; + pendingWrite = null; + callback(); + })); + }); + if (deferDestroy) + setImmediate(destroy); + else + destroy(); + })); + session.on('close', common.mustCall()); + if (code !== 0) { + session.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_HTTP2_SESSION_ERROR'); + })); + } + + socket.on('finish', common.mustCall(() => { + const data = Buffer.concat(output); + let goaways = 0; + for (let offset = 0; offset < data.length;) { + const length = data.readUIntBE(offset, 3); + assert(data.length >= offset + 9 + length); + if (data[offset + 3] === 7) { + goaways++; + assert.strictEqual(data.readUInt32BE(offset + 9), 1); + assert.strictEqual(data.readUInt32BE(offset + 13), code); + } + offset += 9 + length; + } + assert.strictEqual(goaways, 1); + })); + + socket.push(Buffer.concat([kClientMagic, new SettingsFrame().data])); +} diff --git a/test/parallel/test-http2-tls-fatal-alert.js b/test/parallel/test-http2-tls-fatal-alert.js new file mode 100644 index 000000000000..d60b05a9746b --- /dev/null +++ b/test/parallel/test-http2-tls-fatal-alert.js @@ -0,0 +1,63 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); +const assert = require('assert'); +const http2 = require('http2'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +for (const customConnection of [false, true]) { + const server = http2.createSecureServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), + requestCert: true, + rejectUnauthorized: true, + minVersion: 'TLSv1.3', + maxVersion: 'TLSv1.3', + }); + server.on('tlsClientError', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_SSL_PEER_DID_NOT_RETURN_A_CERTIFICATE'); + })); + server.listen(0, '127.0.0.1', common.mustCall(() => { + const options = { + host: '127.0.0.1', + port: server.address().port, + servername: 'localhost', + rejectUnauthorized: false, + ALPNProtocols: ['h2'], + minVersion: 'TLSv1.3', + maxVersion: 'TLSv1.3', + }; + const socket = customConnection ? tls.connect(options) : undefined; + const session = http2.connect(`https://127.0.0.1:${server.address().port}`, { + ...options, + ...(customConnection ? { createConnection: () => socket } : {}), + }); + const transport = socket || session.socket; + // Destroying the socket must not emit the TLS error a second time. + transport.on('error', common.mustCall()); + let errorEmitted = false; + session.on('connect', common.mustCall(() => { + assert.strictEqual(transport.getProtocol(), 'TLSv1.3'); + })); + session.on('error', common.mustCall((err) => { + // OpenSSL and BoringSSL use different names for the same TLS alert. + assert.ok([ + 'ERR_SSL_TLSV13_ALERT_CERTIFICATE_REQUIRED', + 'ERR_SSL_TLSV1_ALERT_CERTIFICATE_REQUIRED', + ].includes(err.code), `Unexpected TLS error code: ${err.code}`); + errorEmitted = true; + })); + transport.on('close', common.mustCall(function() { + // The session's socket proxy may already be detached. + assert(this.destroyed); + })); + session.on('close', common.mustCall(() => { + assert(errorEmitted); + assert(session.destroyed); + if (socket) assert(socket.destroyed); + server.close(common.mustCall()); + })); + })); +} diff --git a/test/parallel/test-https-agent-additional-options.js b/test/parallel/test-https-agent-additional-options.js index eca5f147a419..84cb6a40f4ba 100644 --- a/test/parallel/test-https-agent-additional-options.js +++ b/test/parallel/test-https-agent-additional-options.js @@ -56,30 +56,29 @@ const updatedValues = new Map([ ['sessionIdContext', 'sessionIdContext'], ]); -let value; +// Every variation must be pooled under its own name, and repeating a +// variation must reuse the name it had. +const requested = new Set(); +let expectedNames = 1; function variations(iter, port, cb) { return common.mustCall((res) => { res.resume(); https.globalAgent.once('free', common.mustCall(() => { - // Verify that the most recent connection is in the freeSockets pool. + // Verify that the connections are in the freeSockets pool, one name for + // each distinct set of options. const keys = Object.keys(https.globalAgent.freeSockets); - if (value) { - assert.ok( - keys.some((val) => val.startsWith(value.toString() + ':') || - val.endsWith(':' + value.toString()) || - val.includes(':' + value.toString() + ':')), - `missing value: ${value.toString()} in ${keys}` - ); - } + assert.strictEqual(keys.length, expectedNames, `unexpected ${keys}`); const next = iter.next(); if (next.done) { https.globalAgent.destroy(); server.close(); } else { - // Save `value` for check the next time. const [key, val] = next.value; - value = val; + if (!requested.has(key)) { + requested.add(key); + expectedNames++; + } https.get({ ...getBaseOptions(port), [key]: val }, variations(iter, port, cb)); } @@ -90,5 +89,7 @@ function variations(iter, port, cb) { server.listen(0, common.mustCall(() => { const port = server.address().port; https.globalAgent.keepAlive = true; - https.get(getBaseOptions(port), variations(updatedValues.entries(), port)); + const all = [...updatedValues.entries()]; + const entries = [...all, all[0]]; + https.get(getBaseOptions(port), variations(entries.values(), port)); })); diff --git a/test/parallel/test-https-agent-getname.js b/test/parallel/test-https-agent-getname.js index 4b6555724b09..2a15f5e6d610 100644 --- a/test/parallel/test-https-agent-getname.js +++ b/test/parallel/test-https-agent-getname.js @@ -14,13 +14,13 @@ const agent = new https.Agent(); // empty argument assert.strictEqual( agent.getName(), - 'localhost:::::::::::::::::::::::::::' + 'localhost::::::::::::::::::::::::::::' ); // empty options assert.strictEqual( agent.getName({}), - 'localhost:::::::::::::::::::::::::::' + 'localhost::::::::::::::::::::::::::::' ); // Pass all options arguments @@ -47,10 +47,10 @@ const options = { assert.strictEqual( agent.getName(options), - '0.0.0.0:443:192.168.1.1:s2:ca:s4:cert:ciphers:s3:key::' + - 's3:pfx::false:localhost:::secureProtocol:' + - 'a3:7:v1:Yw==:7:v1:cg==:7:v1:bA==:false:ecdhCurve:dhparam:0:' + - 'sessionIdContext:"sigalgs"::::::::' + '0.0.0.0:443:192.168.1.1:s2:ca:s4:cert:s7:ciphers:s3:key::' + + 's3:pfx::b5:false:s9:localhost:::s14:secureProtocol:' + + 'a3:7:v1:Yw==:7:v1:cg==:7:v1:bA==:b5:false:s9:ecdhCurve:s7:dhparam:' + + 'n1:0:s16:sessionIdContext:s7:sigalgs:::::::::' ); { @@ -105,6 +105,11 @@ assert.strictEqual( agent.getName({ ...baseOptions, allowPartialTrustChain: false }) ); + assert.notStrictEqual( + agent.getName(baseOptions), + agent.getName({ ...baseOptions, allowRenegotiation: false }) + ); + const secureContext1 = tls.createSecureContext({ ca: agent1 }); const secureContext2 = tls.createSecureContext({ ca: agent6 }); assert.strictEqual( @@ -151,4 +156,43 @@ assert.strictEqual( agent.getName({ ...baseOptions, session: Buffer.from('one') }), agent.getName({ ...baseOptions, session: Buffer.from('two') }) ); + + // Values containing the field delimiter must not shift across fields. + const collisions = [ + [{ servername: 'a:b' }, { servername: 'a', minVersion: 'b:' }], + [{ minVersion: 'a:b' }, { minVersion: 'a', maxVersion: 'b:' }], + [{ maxVersion: 'a:b' }, { maxVersion: 'a', secureProtocol: 'b:' }], + [{ rejectUnauthorized: 'false:a' }, + { rejectUnauthorized: 'false', servername: 'a:' }], + [{ honorCipherOrder: 'a:b' }, { honorCipherOrder: 'a', ecdhCurve: 'b:' }], + [{ ecdhCurve: 'a:b' }, { ecdhCurve: 'a', dhparam: 'b:' }], + [{ dhparam: 'a:b' }, { dhparam: 'a', secureOptions: 'b:' }], + [{ secureOptions: '1:a' }, { secureOptions: 1, sessionIdContext: 'a:' }], + [{ sessionIdContext: 'a:b' }, { sessionIdContext: 'a', sigalgs: 'b:' }], + [{ sigalgs: ['a:b'] }, { sigalgs: ['a', 'b'] }], + [{ servername: 'a', rejectUnauthorized: false, ecdhCurve: 'P-256:P-384' }, + { rejectUnauthorized: 'false:a', honorCipherOrder: 'P-256', + ecdhCurve: 'P-384' }], + ]; + for (const [first, second] of collisions) { + assert.notStrictEqual( + agent.getName({ ...baseOptions, ...first }), + agent.getName({ ...baseOptions, ...second }), + `${JSON.stringify(first)} collides with ${JSON.stringify(second)}` + ); + } + + // The type of a value is part of its key. + assert.notStrictEqual( + agent.getName({ ...baseOptions, rejectUnauthorized: false }), + agent.getName({ ...baseOptions, rejectUnauthorized: 'false' }) + ); + + assert.notStrictEqual( + agent.getName({ ...baseOptions, dhparam: new DataView(new ArrayBuffer(2)) }), + agent.getName({ + ...baseOptions, + dhparam: new DataView(new Uint8Array([1, 2]).buffer), + }) + ); } diff --git a/test/parallel/test-intl.js b/test/parallel/test-intl.js index 7d1742f2c7d1..b9eed5c50898 100644 --- a/test/parallel/test-intl.js +++ b/test/parallel/test-intl.js @@ -89,7 +89,8 @@ if (!common.hasIntl) { // Check with toLocaleString { const localeString = dtf.format(date0); - assert.strictEqual(localeString, 'Jan 70'); + // CLDR 49 prepends a U+2019 RIGHT SINGLE QUOTATION MARK to `yy` formats for English locales + assert.match(localeString, /Jan \u2019?70/); } // Options to request GMT const optsGMT = { timeZone: GMT }; diff --git a/test/parallel/test-is-internal-thread.mjs b/test/parallel/test-is-internal-thread.mjs index 27f20f2d2176..6592e236116d 100644 --- a/test/parallel/test-is-internal-thread.mjs +++ b/test/parallel/test-is-internal-thread.mjs @@ -1,33 +1,16 @@ -import { mustCall, spawnPromisified } from '../common/index.mjs'; +import { mustCall } from '../common/index.mjs'; import * as fixtures from '../common/fixtures.mjs'; import assert from 'node:assert'; -import { execPath } from 'node:process'; import { describe, it } from 'node:test'; import { isInternalThread, Worker } from 'node:worker_threads'; describe('worker_threads.isInternalThread', { concurrency: !process.env.TEST_PARALLEL }, () => { - it('should be true inside the loader thread', async () => { - const { code, signal, stdout, stderr } = await spawnPromisified(execPath, [ - '--no-warnings', - '--experimental-loader', - fixtures.fileURL('loader-is-internal-thread.js'), - '--eval', - 'setTimeout(() => {},99)', - ]); - - assert.strictEqual(stderr, ''); - assert.match(stdout, /isInternalThread: true/); - assert.strictEqual(code, 0); - assert.strictEqual(signal, null); - }); - it('should be false inside the main thread', async () => { assert.strictEqual(isInternalThread, false); }); it('should be false inside a regular worker thread', async () => { const worker = new Worker(fixtures.path('worker-is-internal-thread.js')); - worker.on('message', mustCall((message) => { assert.strictEqual(message, 'isInternalThread: false'); })); diff --git a/test/parallel/test-net-onread-buffer-detached.js b/test/parallel/test-net-onread-buffer-detached.js new file mode 100644 index 000000000000..41bebe5e1f91 --- /dev/null +++ b/test/parallel/test-net-onread-buffer-detached.js @@ -0,0 +1,77 @@ +'use strict'; + +const common = require('../common'); +const net = require('net'); +const assert = require('assert'); + +// Regression test. +// +// When an `onread` callback transfers a view of the reusable buffer into a byte +// `ReadableStream`, the transfer detaches the buffer's backing store. The socket +// must not keep writing subsequent peer data into the detached backing store, +// otherwise it corrupts the chunk the application has retained. + +let controller; +const stream = new ReadableStream({ + type: 'bytes', + start(c) { + controller = c; + }, +}); +const reader = stream.getReader(); + +const server = net.createServer(common.mustCall((socket) => { + socket.setNoDelay(true); + socket.write('first'); + // Send more data shortly after the client transfers the first chunk. + const timer = setTimeout(() => { + socket.write('Z'.repeat(1024)); + }, 50); + socket.on('close', () => clearTimeout(timer)); + socket.on('error', common.mustNotCall()); +})); + +server.listen(0, common.mustCall(() => { + const port = server.address().port; + + let transferred = false; + + const client = net.createConnection({ + host: '127.0.0.1', + port, + onread: { + buffer: Buffer.alloc(4096), + callback(nread, buf) { + // Enqueueing a view transfers (and thereby detaches) the underlying + // ArrayBuffer. An affected binary then keeps writing later peer data + // over this chunk's memory. + if (transferred) return; + transferred = true; + const view = new Uint8Array(buf.buffer, buf.byteOffset, nread); + controller.enqueue(view); + }, + }, + }); + + client.on('error', common.mustNotCall()); + + (async () => { + const { value: chunk, done } = await reader.read(); + assert.strictEqual(done, false); + + // The first peer write ("first", 5 bytes) is delivered intact. + assert.strictEqual(chunk[0], 0x66); // 'f' + assert.strictEqual(Buffer.from(chunk).toString(), 'first'); + + // Give the second peer write time to reach the client. Reading has stopped, + // so the retained chunk must not be overwritten. + await new Promise((resolve) => setTimeout(resolve, 200)); + + assert.strictEqual(chunk[0], 0x66, + `retained chunk was corrupted: 0x${chunk[0].toString(16)}`); + assert.strictEqual(Buffer.from(chunk).toString(), 'first'); + + client.end(); + server.close(); + })().then(common.mustCall()); +})); diff --git a/test/parallel/test-net-onread-buffer-lifetime.js b/test/parallel/test-net-onread-buffer-lifetime.js new file mode 100644 index 000000000000..a527ef46e3b0 --- /dev/null +++ b/test/parallel/test-net-onread-buffer-lifetime.js @@ -0,0 +1,179 @@ +// Flags: --js-immutable-arraybuffer +'use strict'; + +// Reads must not modify an immutable ArrayBuffer created by transferring a +// registered onread buffer. + +const common = require('../common'); +const assert = require('node:assert'); +const { once } = require('node:events'); +const net = require('node:net'); +const { test } = require('node:test'); + +for (const mode of ['before first read', 'between reads', 'replacement buffer']) { + test(`onread buffer transferred ${mode}`, async (t) => { + const backing = new ArrayBuffer(8); + new Uint8Array(backing).fill(42); + const buffer = mode === 'replacement buffer' ? + Buffer.from(backing, 2, 4) : new Uint8Array(backing, 2, 4); + const firstBuffer = new Uint8Array(1); + const connections = new Set(); + let peer; + let socket; + let immutable; + let expected; + let factoryCalls = 0; + let readError; + const closed = Promise.withResolvers(); + + const server = net.createServer(common.mustCall((connection) => { + peer = connection; + connection.on('error', (error) => { + if (error.code !== 'ECONNRESET') throw error; + }); + if (mode === 'before first read') { + connection.end('test'); + } else { + connection.write('a'); + } + })); + server.on('connection', (connection) => { + connections.add(connection); + connection.on('close', () => connections.delete(connection)); + }); + t.after(async () => { + socket?.destroy(); + for (const connection of connections) connection.destroy(); + if (server.listening) { + await new Promise((resolve) => server.close(resolve)); + } + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + + function transfer() { + expected = [...new Uint8Array(backing)]; + immutable = backing.transferToImmutable(); + assert.strictEqual(buffer.byteLength, 0); + assert.strictEqual(immutable.immutable, true); + } + + socket = net.connect({ + host: '127.0.0.1', + port: server.address().port, + onread: { + buffer: mode === 'replacement buffer' ? common.mustCall(() => { + return ++factoryCalls === 1 ? firstBuffer : buffer; + }, 2) : buffer, + callback: common.mustCall((nread, view) => { + try { + if (immutable !== undefined) { + assert.deepStrictEqual([...new Uint8Array(immutable)], expected); + assert.fail('onread called after the buffer was transferred'); + } + assert.strictEqual(nread, 1); + assert.strictEqual(view, mode === 'replacement buffer' ? firstBuffer : buffer); + assert.strictEqual(view[0], 97); + // Transfer after onStreamRead checks for detachment and registers + // any replacement buffer returned by the factory. + setImmediate(common.mustCall(() => { + transfer(); + peer.end('test'); + })); + } catch (error) { + closed.reject(error); + return false; + } + }, mode === 'before first read' ? 0 : 1), + }, + }); + socket.on('data', common.mustNotCall()); + socket.on('end', common.mustNotCall()); + socket.on('error', common.mustCall((error) => { + readError = error; + })); + socket.on('close', common.mustCall(closed.resolve)); + if (mode === 'before first read') transfer(); + assert.strictEqual(await closed.promise, true); + assert.strictEqual(readError.code, 'EINVAL'); + assert.strictEqual(readError.syscall, 'read'); + assert.deepStrictEqual([...new Uint8Array(immutable)], expected); + }); +} + +test('onread factory replaces buffers transferred after each read', async (t) => { + const message = Buffer.from('test'); + const chunks = []; + const closed = Promise.withResolvers(); + let peer; + let socket; + + const server = net.createServer(common.mustCall((connection) => { + peer = connection; + connection.on('error', (error) => { + if (error.code !== 'ECONNRESET') throw error; + }); + connection.end(message); + })); + t.after(async () => { + socket?.destroy(); + peer?.destroy(); + if (server.listening) { + await new Promise((resolve) => server.close(resolve)); + } + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + + socket = net.connect({ + host: '127.0.0.1', + port: server.address().port, + onread: { + buffer: common.mustCall(() => new Uint8Array(1), message.length + 1), + callback: common.mustCall((nread, view) => { + try { + assert.strictEqual(nread, 1); + const immutable = view.buffer.transferToImmutable(); + assert.strictEqual(view.byteLength, 0); + assert.strictEqual(immutable.immutable, true); + chunks.push(immutable); + } catch (error) { + closed.reject(error); + return false; + } + }, message.length), + }, + }); + socket.on('data', common.mustNotCall()); + socket.on('end', common.mustCall()); + socket.on('error', closed.reject); + socket.on('close', common.mustCall(closed.resolve)); + assert.strictEqual(await closed.promise, false); + assert.deepStrictEqual(chunks.flatMap((chunk) => [...new Uint8Array(chunk)]), [...message]); +}); + +test('empty onread buffer reports ENOBUFS', async (t) => { + let socket; + const server = net.createServer(common.mustCall((connection) => { + connection.on('error', (error) => { + if (error.code !== 'ECONNRESET') throw error; + }); + connection.end('test'); + })); + t.after(async () => { + socket?.destroy(); + await new Promise((resolve) => server.close(resolve)); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + + socket = net.connect({ + host: '127.0.0.1', + port: server.address().port, + onread: { buffer: new Uint8Array(0), callback: common.mustNotCall() }, + }); + await assert.rejects(once(socket, 'close'), { + code: 'ENOBUFS', + syscall: 'read', + }); +}); diff --git a/test/parallel/test-net-write-concatenated-string.js b/test/parallel/test-net-write-concatenated-string.js new file mode 100644 index 000000000000..8bfc7a4dd485 --- /dev/null +++ b/test/parallel/test-net-write-concatenated-string.js @@ -0,0 +1,60 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +// Writes concatenated strings around the size limits of the stack buffer used +// by StreamBase::WriteString() and checks the bytes on the wire. + +function concat(length, base) { + let str = ''; + for (let i = 0; i < length; i++) + str += String.fromCharCode(base + i % 16); + return str; +} + +const cases = []; +for (const length of [0, 13, 5461, 5462, 16384, 16385]) { + // ASCII, non-ASCII Latin-1, two-byte. + for (const base of [0x61, 0xe0, 0x2000]) { + for (const encoding of ['utf8', 'latin1', 'ascii']) { + cases.push({ length, base, encoding }); + } + } +} + +const expected = []; + +const server = net.createServer(common.mustCall((socket) => { + const chunks = []; + socket.on('data', (chunk) => chunks.push(chunk)); + socket.on('end', common.mustCall(() => { + const actual = Buffer.concat(chunks); + let offset = 0; + for (const [i, buf] of expected.entries()) { + const { length, base, encoding } = cases[i]; + assert.deepStrictEqual( + actual.subarray(offset, offset + buf.length), + buf, + `length ${length}, base 0x${base.toString(16)}, ${encoding}`); + offset += buf.length; + } + assert.strictEqual(offset, actual.length); + server.close(); + })); +})); + +server.listen(0, common.mustCall(() => { + const socket = net.connect(server.address().port); + let i = 0; + function next() { + if (i === cases.length) return socket.end(); + const { length, base, encoding } = cases[i++]; + const str = concat(length, base); + // Each write waits for the previous one so that it goes through + // WriteString() and not Writev(). + socket.write(str, encoding, common.mustSucceed(next)); + expected.push(Buffer.from(str, encoding)); + } + socket.on('connect', common.mustCall(next)); +})); diff --git a/test/parallel/test-net-writev-concatenated-string.js b/test/parallel/test-net-writev-concatenated-string.js new file mode 100644 index 000000000000..975630fe1ac2 --- /dev/null +++ b/test/parallel/test-net-writev-concatenated-string.js @@ -0,0 +1,62 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const net = require('net'); + +// Writes concatenated strings with a Buffer after each of them in a single +// StreamBase::Writev() call, like an HTTP response header followed by a Buffer +// body, and checks the bytes on the wire. + +function concat(length, base) { + let str = ''; + for (let i = 0; i < length; i++) + str += String.fromCharCode(base + i % 16); + return str; +} + +const separator = Buffer.from('|'); +const writes = []; +// Writev() reserves 3 bytes per character for UTF-8 strings of up to 65535 +// characters and the exact size for longer ones. +for (const length of [0, 13, 5461, 16385, 65535, 65536]) { + // ASCII, non-ASCII Latin-1, two-byte. + for (const base of [0x61, 0xe0, 0x2000]) { + for (const encoding of ['utf8', 'latin1', 'ascii']) { + writes.push({ + label: `length ${length}, base 0x${base.toString(16)}, ${encoding}`, + str: concat(length, base), + encoding, + }); + } + } +} + +const server = net.createServer(common.mustCall((socket) => { + const chunks = []; + socket.on('data', (chunk) => chunks.push(chunk)); + socket.on('end', common.mustCall(() => { + const actual = Buffer.concat(chunks); + let offset = 0; + for (const { label, str, encoding } of writes) { + const expected = Buffer.concat([Buffer.from(str, encoding), separator]); + assert.deepStrictEqual( + actual.subarray(offset, offset + expected.length), expected, label); + offset += expected.length; + } + assert.strictEqual(offset, actual.length); + server.close(); + })); +})); + +server.listen(0, common.mustCall(() => { + const socket = net.connect(server.address().port, common.mustCall(() => { + // Corked writes are flushed together with Writev(). + socket.cork(); + for (const { str, encoding } of writes) { + socket.write(str, encoding); + socket.write(separator); + } + socket.uncork(); + socket.end(); + })); +})); diff --git a/test/parallel/test-node-run.js b/test/parallel/test-node-run.js index 57faa80b9f82..b276c54ca23e 100644 --- a/test/parallel/test-node-run.js +++ b/test/parallel/test-node-run.js @@ -12,6 +12,8 @@ const fixtures = require('../common/fixtures'); const tmpdir = require('../common/tmpdir'); const envSuffix = common.isWindows ? '-windows' : ''; +tmpdir.refresh(); + describe('node --run [command]', { concurrency: !process.env.TEST_PARALLEL }, () => { it('returns error on non-existent file', async () => { const child = await common.spawnPromisified( @@ -336,4 +338,45 @@ describe('node --run [command]', { concurrency: !process.env.TEST_PARALLEL }, () assert.strictEqual(child.stdout, ''); assert.strictEqual(child.code, 1); }); + + it('skips node_modules directories that cannot be inspected', { + skip: common.isWindows || process.getuid() === 0, + }, async () => { + const projectDir = tmpdir.resolve('unreadable-node-modules'); + const nodeModules = path.join(projectDir, 'node_modules'); + fs.mkdirSync(nodeModules, { recursive: true }); + fs.writeFileSync(path.join(projectDir, 'package.json'), JSON.stringify({ + scripts: { test: 'echo ok' }, + })); + fs.chmodSync(nodeModules, 0o000); + try { + const child = await common.spawnPromisified( + process.execPath, + [ '--run', 'test'], + { cwd: projectDir }, + ); + assert.strictEqual(child.stdout.trim(), 'ok'); + assert.strictEqual(child.stderr, ''); + assert.strictEqual(child.code, 0); + } finally { + fs.chmodSync(nodeModules, 0o755); + } + }); + + it('returns error when the current working directory is removed', { + // Windows, SunOS, AIX and IBM i refuse to remove a directory that is in + // use as a cwd. + skip: common.isWindows || common.isSunOS || common.isAIX || common.isIBMi, + }, async () => { + const removedDir = tmpdir.resolve('removed-cwd'); + fs.mkdirSync(removedDir); + const child = await common.spawnPromisified( + '/bin/sh', + [ '-c', 'rmdir "$PWD" && exec "$0" --run test', process.execPath], + { cwd: removedDir }, + ); + assert.match(child.stderr, /Can't determine the current working directory/); + assert.strictEqual(child.stdout, ''); + assert.strictEqual(child.code, 1); + }); }); diff --git a/test/parallel/test-os-negative-zero.js b/test/parallel/test-os-negative-zero.js new file mode 100644 index 000000000000..7d355bb4c864 --- /dev/null +++ b/test/parallel/test-os-negative-zero.js @@ -0,0 +1,23 @@ +'use strict'; + +require('../common'); + +const assert = require('assert'); +const os = require('os'); + +// -0 passes the int32 validation, so it must be accepted like 0 instead of +// aborting the process in the binding. +assert.strictEqual(os.getPriority(-0), os.getPriority(0)); + +os.setPriority(-0, os.getPriority()); + +// Setting the priority to 0 may need more privileges than the process has, +// which is reported as a system error rather than an abort. +for (const args of [[0, -0], [-0, -0], [-0]]) { + try { + os.setPriority(...args); + } catch (err) { + assert.strictEqual(err.code, 'ERR_SYSTEM_ERROR'); + assert.strictEqual(err.info.code, 'EACCES'); + } +} diff --git a/test/parallel/test-os.js b/test/parallel/test-os.js index f15499d692e1..695917230e9a 100644 --- a/test/parallel/test-os.js +++ b/test/parallel/test-os.js @@ -42,6 +42,8 @@ const is = { process.env.TMPDIR = '/tmpdir'; process.env.TMP = '/tmp'; process.env.TEMP = '/temp'; + +/* eslint-disable no-restricted-syntax */ if (common.isWindows) { assert.strictEqual(os.tmpdir(), '/temp'); process.env.TEMP = ''; @@ -72,6 +74,7 @@ if (common.isWindows) { process.env.TMPDIR = '/'; assert.strictEqual(os.tmpdir(), '/'); } +/* eslint-enable no-restricted-syntax */ const endianness = os.endianness(); is.string(endianness); @@ -250,7 +253,7 @@ assert.strictEqual(`${os.homedir}`, os.homedir()); assert.strictEqual(`${os.release}`, os.release()); assert.strictEqual(`${os.type}`, os.type()); assert.strictEqual(`${os.endianness}`, os.endianness()); -assert.strictEqual(`${os.tmpdir}`, os.tmpdir()); +assert.strictEqual(`${os.tmpdir}`, os.tmpdir()); // eslint-disable-line no-restricted-syntax assert.strictEqual(`${os.arch}`, os.arch()); assert.strictEqual(`${os.platform}`, os.platform()); assert.strictEqual(`${os.version}`, os.version()); diff --git a/test/parallel/test-path-glob.js b/test/parallel/test-path-glob.js index 11633f52245e..6b53e26bdd6f 100644 --- a/test/parallel/test-path-glob.js +++ b/test/parallel/test-path-glob.js @@ -16,6 +16,9 @@ const globs = { ['foo\\bar\\baz\\boo', 'foo\\[bc-r]ar\\baz\\*', true], // Matches 'bar' or 'car' in 'foo\\bar' ['foo\\bar\\baz', 'foo/**', true], // Matches anything in 'foo' ['foo\\bar\\baz', '*', false], // No match + ['a\\b\\c\\d\\e', '**/a/b/c/**/d/**', true], // Globstar sections of different lengths + ['x\\a\\b\\c\\d\\e', '**/a/b/c/**/d/**/e', true], // Globstar sections of different lengths + ['a\\b\\c\\d', '**/a/b/c/**/d/**', false], // Trailing globstar needs a segment ], posix: [ ['foo/bar/baz', 'foo/[bcr]ar/baz', true], // Matches 'bar' or 'car' in 'foo/bar' @@ -28,6 +31,9 @@ const globs = { ['foo/bar/baz/boo', 'foo/[bc-r]ar/baz/*', true], // Matches 'bar' or 'car' in 'foo/bar' ['foo/bar/baz', 'foo/**', true], // Matches anything in 'foo' ['foo/bar/baz', '*', false], // No match + ['a/b/c/d/e', '**/a/b/c/**/d/**', true], // Globstar sections of different lengths + ['x/a/b/c/d/e', '**/a/b/c/**/d/**/e', true], // Globstar sections of different lengths + ['a/b/c/d', '**/a/b/c/**/d/**', false], // Trailing globstar needs a segment ], }; diff --git a/test/parallel/test-path-resolve.js b/test/parallel/test-path-resolve.js index 088ed4b3ff18..dd70dea530fe 100644 --- a/test/parallel/test-path-resolve.js +++ b/test/parallel/test-path-resolve.js @@ -71,6 +71,15 @@ resolveTests.forEach(([resolve, tests]) => { }); assert.strictEqual(failures.length, 0, failures.join('\n')); +for (const resolve of [path.posix.resolve, path.win32.resolve]) { + assert.throws(() => resolve('a', 1), { + code: 'ERR_INVALID_ARG_TYPE', + name: 'TypeError', + message: 'The "paths[1]" argument must be of type string. ' + + 'Received type number (1)', + }); +} + if (common.isWindows) { // Test resolving the current Windows drive letter from a spawned process. // See https://github.com/nodejs/node/issues/7215 diff --git a/test/parallel/test-permission-allow-inspector.js b/test/parallel/test-permission-allow-inspector.js deleted file mode 100644 index 05022ff24044..000000000000 --- a/test/parallel/test-permission-allow-inspector.js +++ /dev/null @@ -1,54 +0,0 @@ -// Flags: --permission --allow-fs-read=* --allow-inspector -'use strict'; - -const common = require('../common'); - -common.skipIfInspectorDisabled(); - -const { Session } = require('node:inspector/promises'); -const assert = require('node:assert'); - -const session = new Session(); -session.connect(); - -// Guarantee WorkerImpl doesn't gets bypassed -(async () => { - await session.post('Debugger.enable'); - await session.post('Runtime.enable'); - - globalThis.Worker = require('node:worker_threads').Worker; - - const { result: { objectId } } = await session.post('Runtime.evaluate', { expression: 'Worker' }); - const { internalProperties } = await session.post('Runtime.getProperties', { objectId: objectId }); - const { - value: { - value: { scriptId } - } - } = internalProperties.filter((prop) => prop.name === '[[FunctionLocation]]')[0]; - const { scriptSource } = await session.post('Debugger.getScriptSource', { scriptId }); - - const lineNumber = scriptSource.substring(0, scriptSource.indexOf('new WorkerImpl')).split('\n').length; - - // Attempt to bypass it based on https://hackerone.com/reports/1962701 - await session.post('Debugger.setBreakpointByUrl', { - lineNumber: lineNumber, - url: 'node:internal/worker', - columnNumber: 0, - condition: '((isInternal = true),false)' - }); - - assert.throws(() => { - new Worker(` - const child_process = require("node:child_process"); - console.log(child_process.execSync("ls -l").toString()); - - console.log(require("fs").readFileSync("/etc/passwd").toString()) - `, { - eval: true, - }); - }, { - message: 'Access to this API has been restricted. Use --allow-worker to manage permissions.', - code: 'ERR_ACCESS_DENIED', - permission: 'WorkerThreads' - }); -})().then(common.mustCall()); diff --git a/test/parallel/test-permission-audit-fs-fd-apis-does-not-deny.js b/test/parallel/test-permission-audit-fs-fd-apis-does-not-deny.js new file mode 100644 index 000000000000..5ea4cb2ae0da --- /dev/null +++ b/test/parallel/test-permission-audit-fs-fd-apis-does-not-deny.js @@ -0,0 +1,86 @@ +'use strict'; + +const common = require('../common'); +const { isMainThread } = require('worker_threads'); + +if (!isMainThread) { + common.skip('This test only works on a main thread'); +} + +const assert = require('assert'); +const fs = require('fs'); +const { spawnSync } = require('child_process'); +const { test } = require('node:test'); +const fixtures = require('../common/fixtures'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +const target = tmpdir.resolve('audit-fd-apis.txt'); +fs.copyFileSync(fixtures.path('permission', 'deny', 'regular-file.md'), target); + +function run(flag, op) { + const childScript = ` + const fs = require('node:fs'); + (async () => { + const fd = fs.openSync(process.env.TARGET, 'r+'); + const fh = await fs.promises.open(process.env.TARGET, 'r+'); + const cb = (fn, ...args) => new Promise((resolve, reject) => { + fn(fd, ...args, (err) => err ? reject(err) : resolve()); + }); + try { + await (${op}); + console.log('RESULT NO_THROW'); + } catch (e) { + console.log('RESULT THREW ' + e.code); + } finally { + await fh.close(); + fs.closeSync(fd); + } + })(); + `; + const { status, stdout, stderr } = spawnSync( + process.execPath, + [ + flag, + '--allow-fs-read=*', + '--allow-fs-write=*', + '--allow-env=TARGET', + '-e', + childScript, + ], + { encoding: 'utf8', env: { ...process.env, TARGET: target } }, + ); + assert.strictEqual(status, 0, stderr); + const resultLine = stdout.split('\n').find((l) => l.startsWith('RESULT ')); + assert.ok(resultLine, stdout); + return resultLine.replace('RESULT ', ''); +} + +const ops = [ + ['fs.fsyncSync()', 'fs.fsyncSync(fd)'], + ['fs.fsync()', 'cb(fs.fsync)'], + ['filehandle.sync()', 'fh.sync()'], + ['fs.fdatasyncSync()', 'fs.fdatasyncSync(fd)'], + ['fs.fdatasync()', 'cb(fs.fdatasync)'], + ['filehandle.datasync()', 'fh.datasync()'], + ['fs.fchmodSync()', 'fs.fchmodSync(fd, 0o644)'], + ['fs.fchmod()', 'cb(fs.fchmod, 0o644)'], + ['filehandle.chmod()', 'fh.chmod(0o644)'], + ['fs.fchownSync()', 'fs.fchownSync(fd, -1, -1)'], + ['fs.fchown()', 'cb(fs.fchown, -1, -1)'], + ['filehandle.chown()', 'fh.chown(-1, -1)'], + ['fs.futimesSync()', 'fs.futimesSync(fd, 1, 1)'], + ['fs.futimes()', 'cb(fs.futimes, 1, 1)'], + ['filehandle.utimes()', 'fh.utimes(1, 1)'], +]; + +for (const [api, op] of ops) { + test(`audit mode does not disable ${api}`, () => { + assert.strictEqual(run('--permission-audit', op), 'NO_THROW'); + }); + + test(`enforce mode still disables ${api}`, () => { + assert.strictEqual(run('--permission', op), 'THREW ERR_ACCESS_DENIED'); + }); +} diff --git a/test/parallel/test-permission-child-process-inherit-flags.js b/test/parallel/test-permission-child-process-inherit-flags.js index 36e89bfb1c72..808be87c3ec0 100644 --- a/test/parallel/test-permission-child-process-inherit-flags.js +++ b/test/parallel/test-permission-child-process-inherit-flags.js @@ -100,6 +100,51 @@ const childProcess = require('child_process'); assert.strictEqual(worker, 'false'); } +{ + const tmpdir = require('../common/tmpdir'); + const dir = tmpdir.resolve('inherit flags dir'); + const file = `${dir}/file.txt`; + + const grandchildSource = ` + console.log(process.permission.has('fs.read')); + console.log(process.permission.has('fs.read', ${JSON.stringify(file)})); + console.log(process.permission.has('fs.read', ${JSON.stringify(__filename)})); + `; + const childSource = ` + const { status, stdout, stderr } = require('child_process').spawnSync( + process.execPath, ['-e', ${JSON.stringify(grandchildSource)}]); + console.log(JSON.stringify({ + status, + stderr: stderr.toString(), + permissions: stdout.toString().trim().split('\\n'), + })); + `; + + function run(args) { + const { status, stdout, stderr } = childProcess.spawnSync( + process.execPath, + ['--permission', '--allow-child-process', ...args, '-e', childSource], + ); + assert.strictEqual(status, 0, stderr.toString()); + const grandchild = JSON.parse(stdout.toString()); + assert.strictEqual(grandchild.status, 0, grandchild.stderr); + return grandchild.permissions; + } + + assert.deepStrictEqual(run(['--allow-fs-read', '*']), + ['true', 'true', 'true']); + + assert.deepStrictEqual(run(['--allow-fs-read', `${dir}/*`]), + ['false', 'true', 'false']); + + assert.deepStrictEqual(run([`--allow-fs-read=${dir}/*`]), + ['false', 'true', 'false']); + + assert.deepStrictEqual( + run(['--allow-fs-read', `${dir}/*`, `--allow-fs-read=${__filename}`]), + ['false', 'true', 'true']); +} + { assert.strictEqual(process.env.NODE_OPTIONS, undefined); } diff --git a/test/parallel/test-permission-drop-env-empty-reference.js b/test/parallel/test-permission-drop-env-empty-reference.js new file mode 100644 index 000000000000..924218a9112e --- /dev/null +++ b/test/parallel/test-permission-drop-env-empty-reference.js @@ -0,0 +1,34 @@ +'use strict'; + +const common = require('../common'); +const { isMainThread } = require('worker_threads'); + +if (!isMainThread) { + common.skip('This test only works on a main thread'); +} + +const assert = require('assert'); +const { spawnSync } = require('child_process'); + +// An empty reference must not drop every environment variable. +const { status, stdout, stderr } = spawnSync(process.execPath, [ + '--permission', + '--allow-env=A,B', + '-e', + ` + const assert = require('assert'); + assert.throws(() => process.permission.drop('env', ''), { + code: 'ERR_INVALID_ARG_VALUE', + }); + assert.throws(() => process.permission.drop('env', new Uint8Array(0)), { + code: 'ERR_INVALID_ARG_VALUE', + }); + assert.strictEqual(process.env.A, '1'); + assert.strictEqual(process.env.B, '2'); + `, +], { + env: { ...process.env, A: '1', B: '2' }, + encoding: 'utf8', +}); + +assert.strictEqual(status, 0, `stdout: ${stdout}\nstderr: ${stderr}`); diff --git a/test/parallel/test-permission-drop-errors.js b/test/parallel/test-permission-drop-errors.js index ae3a9b2fcc9e..35765690bc58 100644 --- a/test/parallel/test-permission-drop-errors.js +++ b/test/parallel/test-permission-drop-errors.js @@ -39,6 +39,25 @@ const assert = require('assert'); })); } +{ + // An empty reference must not drop the whole scope. + for (const scope of ['fs.read', 'fs.write', 'child', 'env']) { + for (const reference of ['', new Uint8Array(0), Buffer.alloc(0)]) { + assert.throws(() => { + process.permission.drop(scope, reference); + }, common.expectsError({ + code: 'ERR_INVALID_ARG_VALUE', + })); + } + } + + assert.strictEqual(process.permission.has('fs.read'), true); + assert.strictEqual(process.permission.has('child'), false); + + process.permission.drop('child', null); + process.permission.drop('child', undefined); +} + { process.permission.drop('invalid-scope'); process.permission.drop('invalid-scope', '/tmp'); diff --git a/test/parallel/test-permission-drop-fs-granted-path.js b/test/parallel/test-permission-drop-fs-granted-path.js index fdb9b194979e..82d04b49040f 100644 --- a/test/parallel/test-permission-drop-fs-granted-path.js +++ b/test/parallel/test-permission-drop-fs-granted-path.js @@ -167,6 +167,71 @@ for (const files of [ assert.strictEqual(child.status, 0); } +// Grant a path that does not exist yet, then create it as a directory +// dropping it still revokes the grant +{ + const later = path.join(tmpdir.path, 'later-dir'); + const child = spawnSync(process.execPath, [ + '--permission', + `--allow-fs-read=${later}`, + `--allow-fs-write=${later}`, + '-e', + ` + const assert = require('assert'); + const fs = require('fs'); + const later = ${JSON.stringify(later)}; + + fs.mkdirSync(later); + for (const scope of ['fs.read', 'fs.write']) { + assert.ok(process.permission.has(scope, later)); + + process.permission.drop(scope, later); + + assert.ok(!process.permission.has(scope, later)); + assert.ok(!process.permission.has(scope, later + '/file.txt')); + } + `, + ]); + if (child.status !== 0) { + console.error('Case 6 stderr:', child.stderr?.toString()); + } + assert.strictEqual(child.status, 0); +} + +// Grant a directory, then remove it - dropping it still revokes the grant +{ + const gone = path.join(tmpdir.path, 'gone-dir'); + fs.mkdirSync(gone); + const child = spawnSync(process.execPath, [ + '--permission', + `--allow-fs-read=${gone}`, + `--allow-fs-read=${dir}`, + `--allow-fs-write=${gone}`, + `--allow-fs-write=${dir}`, + '-e', + ` + const assert = require('assert'); + const fs = require('fs'); + const gone = ${JSON.stringify(gone)}; + const dir = ${JSON.stringify(dir)}; + + fs.rmdirSync(gone); + for (const scope of ['fs.read', 'fs.write']) { + assert.ok(process.permission.has(scope, gone)); + + process.permission.drop(scope, gone); + + assert.ok(!process.permission.has(scope, gone)); + assert.ok(process.permission.has(scope, dir + '/item1.txt')); + } + `, + ]); + if (child.status !== 0) { + console.error('Case 7 stderr:', child.stderr?.toString()); + } + assert.strictEqual(child.status, 0); +} + // Drop entire scope without reference - revokes everything { const child = spawnSync(process.execPath, [ diff --git a/test/parallel/test-permission-fs-promises-stack-trace.js b/test/parallel/test-permission-fs-promises-stack-trace.js new file mode 100644 index 000000000000..7a9999c979aa --- /dev/null +++ b/test/parallel/test-permission-fs-promises-stack-trace.js @@ -0,0 +1,44 @@ +'use strict'; + +require('../common'); +const assert = require('assert'); +const { spawnSync } = require('child_process'); +const tmpdir = require('../common/tmpdir'); + +tmpdir.refresh(); + +// The permission model denies access before the first await, so the stack +// still has the frames of a caller that does not await the promise. +const { status, stderr } = spawnSync( + process.execPath, + [ + '--permission', + '-e', + ` + const assert = require('assert'); + const { readFile, writeFile, appendFile, stat } = require('fs/promises'); + const target = ${JSON.stringify(tmpdir.resolve('file'))}; + + function readCaller() { return readFile(target); } + function writeCaller() { return writeFile(target, 'data'); } + function appendCaller() { return appendFile(target, 'data'); } + async function awaitAppendCaller() { await appendFile(target, 'data'); } + async function awaitStatCaller() { await stat(target); } + + const cases = [ + [readCaller, /at readCaller /], + [writeCaller, /at writeCaller /], + [appendCaller, /at appendCaller /], + [awaitAppendCaller, /at awaitAppendCaller /], + [awaitStatCaller, /at async awaitStatCaller /], + ]; + let checked = 0; + for (const [caller, stack] of cases) { + assert.rejects(caller(), { code: 'ERR_ACCESS_DENIED', stack }) + .then(() => checked++); + } + process.on('exit', () => assert.strictEqual(checked, cases.length)); + `, + ], +); +assert.strictEqual(status, 0, stderr.toString()); diff --git a/test/parallel/test-process-env-allowed-flags-are-documented.js b/test/parallel/test-process-env-allowed-flags-are-documented.js index 910fec097b69..ba33ae989863 100644 --- a/test/parallel/test-process-env-allowed-flags-are-documented.js +++ b/test/parallel/test-process-env-allowed-flags-are-documented.js @@ -137,7 +137,6 @@ assert(undocumented.delete('--experimental-worker')); assert(undocumented.delete('--napi-modules')); assert(undocumented.delete('--node-snapshot')); assert(undocumented.delete('--no-node-snapshot')); -assert(undocumented.delete('--loader')); assert(undocumented.delete('--verify-base-objects')); assert(undocumented.delete('--no-verify-base-objects')); assert(undocumented.delete('--trace-promises')); diff --git a/test/parallel/test-process-exit-background-gc.js b/test/parallel/test-process-exit-background-gc.js new file mode 100644 index 000000000000..1e2f3668502e --- /dev/null +++ b/test/parallel/test-process-exit-background-gc.js @@ -0,0 +1,34 @@ +// Flags: --stress-concurrent-allocation +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) { common.skip('missing crypto'); } + +// Regression test for https://github.com/nodejs/node/issues/64274. +// process.exit() joined the V8 platform workers while one was parked +// waiting for a GC that the main thread no longer performs. + +const { pbkdf2, pbkdf2Sync } = require('crypto'); +const password = 'top secret'; +const salt = '0123456789abcdef'; + +// A small live set keeps the old generation limit low. +const keep = []; +for (let i = 0; i < 1e5; i++) keep.push({ i }); + +// Pick an iteration count that keeps the threadpool busy for about a second. +const probeIterations = 2e5; +const start = process.hrtime.bigint(); +pbkdf2Sync(password, salt, probeIterations, 64, 'sha512'); +const nsPerIteration = Number(process.hrtime.bigint() - start) / + probeIterations; +const iterations = Math.ceil(1e9 / nsPerIteration); + +setTimeout(() => { + // uv_library_shutdown() waits for this job, so the main thread stays out of + // JS and cannot serve the GC that the stress allocation task asks for. + pbkdf2(password, salt, iterations, 64, 'sha512', () => {}); + // Use up the old generation budget, so that the next background allocation + // fails and parks that task in CollectionBarrier. + for (let i = 0; i < 40; i++) new Array(1e5).fill(i); + process.exit(0); +}, 300); diff --git a/test/parallel/test-process-timeout-blocked.js b/test/parallel/test-process-timeout-blocked.js index db3553e11d59..84c3ecb937e7 100644 --- a/test/parallel/test-process-timeout-blocked.js +++ b/test/parallel/test-process-timeout-blocked.js @@ -13,8 +13,10 @@ const tmpdir = require('../common/tmpdir'); tmpdir.refresh(); // The deadline is measured from the start of the process, so on a slow machine -// it can expire before the fixture has reached the state under test, which the -// fixture signals by creating a file. If it did not get that far and did not +// it can expire before the fixture has reached the state under test. Unless the +// main thread is blocked or exiting by then, it handles the timeout and prints +// what it was doing. A fixture that expects it to do so signals that it got far +// enough by creating a file. If the fixture did not get that far and did not // print the expected message, run it again with a longer timeout. function runUntilReady(fixture, expected, args = []) { for (let timeout = common.platformTimeout(1000); ; timeout *= 2) { @@ -30,7 +32,9 @@ function runUntilReady(fixture, expected, args = []) { ], { encoding: 'utf8' }); const elapsed = Number(process.hrtime.bigint() - start) / 1e6; - if (!expected.test(child.stderr) && !fs.existsSync(marker) && + if (!expected.test(child.stderr) && + /^Main thread was/m.test(child.stderr) && + !fs.existsSync(marker) && timeout < common.platformTimeout(16000)) { continue; } diff --git a/test/parallel/test-quic-connect-first-flight-failure.mjs b/test/parallel/test-quic-connect-first-flight-failure.mjs new file mode 100644 index 000000000000..aab291bb72bb --- /dev/null +++ b/test/parallel/test-quic-connect-first-flight-failure.mjs @@ -0,0 +1,21 @@ +// Flags: --experimental-quic --no-warnings + +// Test: connect() rejects when the session closes during the first flight. + +import { hasQuic, skip } from '../common/index.mjs'; +import assert from 'node:assert'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { connect } = await import('../common/quic.mjs'); + +// An empty list leaves the ClientHello without a cipher suite or a group, and +// a handshakeTimeout of 0 has already expired once the first flight is out. +const cases = [{ ciphers: '' }, { groups: '' }, { handshakeTimeout: 0 }]; +for (const options of cases) { + await assert.rejects(connect('127.0.0.1:1', options), { + code: 'ERR_QUIC_CONNECTION_FAILED', + }); +} diff --git a/test/parallel/test-quic-h3-error-codes.mjs b/test/parallel/test-quic-h3-error-codes.mjs index 3a91a2e8f056..46b7db008662 100644 --- a/test/parallel/test-quic-h3-error-codes.mjs +++ b/test/parallel/test-quic-h3-error-codes.mjs @@ -120,3 +120,85 @@ const decoder = new TextDecoder(); await clientSession.close(); await serverEndpoint.close(); } + +// RESET_STREAM with H3_NO_ERROR is a clean application-level reset. It does +// not reject stream.closed, and truncatedReads: 'ignore' accepts the missing +// FIN without turning the nonzero code back into an error. +{ + const H3_NO_ERROR = 0x100n; + const reset = Promise.withResolvers(); + + const serverEndpoint = await listen(mustCall(), { + sni: { '*': { keys: [key], certs: [cert] } }, + onheaders: mustCall(function() { + this.resetStream(H3_NO_ERROR); + }), + }); + + const clientSession = await connect(serverEndpoint.address, { + servername: 'localhost', + verifyPeer: 'manual', + truncatedReads: 'ignore', + }); + await clientSession.opened; + + const stream = await clientSession.createBidirectionalStream({ + headers: { + ':method': 'GET', + ':path': '/', + ':scheme': 'https', + ':authority': 'localhost', + }, + }); + stream.onreset = mustCall((error) => { + assert.strictEqual(error.code, 'ERR_QUIC_APPLICATION_ERROR'); + assert.strictEqual(error.errorCode, H3_NO_ERROR); + reset.resolve(); + }); + stream.writer.endSync(); + + const body = await bytes(stream); + assert.strictEqual(body.byteLength, 0); + await reset.promise; + await stream.closed; + + await clientSession.close(); + await serverEndpoint.close(); +} + +// A locally sent STOP_SENDING with H3_NO_ERROR is a clean application-level +// truncation. With truncatedReads: 'ignore', the nonzero code does not fail +// the read. +{ + const H3_NO_ERROR = 0x100n; + + const serverEndpoint = await listen(mustCall(), { + sni: { '*': { keys: [key], certs: [cert] } }, + onheaders: mustCall(), + }); + + const clientSession = await connect(serverEndpoint.address, { + servername: 'localhost', + verifyPeer: 'manual', + truncatedReads: 'ignore', + }); + await clientSession.opened; + + const stream = await clientSession.createBidirectionalStream({ + headers: { + ':method': 'GET', + ':path': '/', + ':scheme': 'https', + ':authority': 'localhost', + }, + }); + stream.writer.endSync(); + + stream.stopSending(H3_NO_ERROR); + const body = await bytes(stream); + assert.strictEqual(body.byteLength, 0); + await stream.closed; + + await clientSession.close(); + await serverEndpoint.close(); +} diff --git a/test/parallel/test-quic-h3-reset-after-headers.mjs b/test/parallel/test-quic-h3-reset-after-headers.mjs new file mode 100644 index 000000000000..1f1d7bced60f --- /dev/null +++ b/test/parallel/test-quic-h3-reset-after-headers.mjs @@ -0,0 +1,86 @@ +// Flags: --experimental-quic --no-warnings + +// Test: an HTTP/3 server that abandons a stream right after submitting +// response headers delivers RESET_STREAM to the client, and the session +// keeps working. The headers are still queued in nghttp3 when the stream +// is destroyed. If nghttp3 later tries to write them, reading the body of +// the removed stream fails and the whole session closes silently. + +import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import assert from 'node:assert'; +import * as fixtures from '../common/fixtures.mjs'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('node:quic'); +const { createPrivateKey } = await import('node:crypto'); + +const key = createPrivateKey(fixtures.readKey('agent1-key.pem')); +const cert = fixtures.readKey('agent1-cert.pem'); + +// RFC 9114 H3_REQUEST_CANCELLED. +const H3_REQUEST_CANCELLED = 0x10cn; + +const cases = [ + ['resetStream() then destroy()', (stream) => { + stream.resetStream(H3_REQUEST_CANCELLED); + stream.destroy(); + }], + ['destroy() with a code', (stream) => { + stream.onerror = () => {}; + stream.destroy(new Error('abandoned'), { code: H3_REQUEST_CANCELLED }); + }], +]; + +function request(session, path) { + return session.createBidirectionalStream({ + headers: { + ':method': 'GET', + ':path': path, + ':scheme': 'https', + ':authority': 'localhost', + }, + }); +} + +for (const [label, abandon] of cases) { + const serverEndpoint = await listen(mustCall((serverSession) => { + serverSession.onerror = () => {}; + }), { + sni: { '*': { keys: [key], certs: [cert] } }, + onheaders: mustCall(function(headers) { + // Submit response headers, then abandon the first request in the + // same tick, before nghttp3 has written the headers. + this.sendHeaders({ ':status': '200' }, { + terminal: headers[':path'] !== '/abandon', + }); + if (headers[':path'] === '/abandon') abandon(this); + }, 2), + }); + + const clientSession = await connect(serverEndpoint.address, { + servername: 'localhost', + verifyPeer: 'manual', + }); + await clientSession.opened; + + // The first request is abandoned with H3_REQUEST_CANCELLED. + const abandoned = await request(clientSession, '/abandon'); + abandoned.onerror = () => {}; + const reset = Promise.withResolvers(); + abandoned.onreset = mustCall((error) => reset.resolve(error)); + const error = await reset.promise; + assert.strictEqual(error?.errorCode, H3_REQUEST_CANCELLED, label); + + // The session still works: a second request gets a response. + const ok = await request(clientSession, '/ok'); + const status = Promise.withResolvers(); + ok.onheaders = mustCall((headers) => status.resolve(headers[':status'])); + assert.strictEqual(await status.promise, 200, label); + await ok.closed; + + await clientSession.close(); + await serverEndpoint.close(); +} diff --git a/test/parallel/test-quic-internal-endpoint-stats-state.mjs b/test/parallel/test-quic-internal-endpoint-stats-state.mjs index 2f4ce6ccc141..bc44619cdfa8 100644 --- a/test/parallel/test-quic-internal-endpoint-stats-state.mjs +++ b/test/parallel/test-quic-internal-endpoint-stats-state.mjs @@ -153,6 +153,7 @@ assert.strictEqual(streamState.finReceived, false); assert.strictEqual(streamState.readEnded, false); assert.strictEqual(streamState.writeEnded, false); assert.strictEqual(streamState.reset, false); +assert.strictEqual(streamState.resetCodeIsError, false); assert.strictEqual(streamState.hasReader, false); assert.strictEqual(streamState.wantsBlock, false); assert.strictEqual(streamState.wantsReset, false); diff --git a/test/parallel/test-quic-max-payload-size.mjs b/test/parallel/test-quic-max-payload-size.mjs index 9923f1204070..fde5e4e12b89 100644 --- a/test/parallel/test-quic-max-payload-size.mjs +++ b/test/parallel/test-quic-max-payload-size.mjs @@ -5,7 +5,7 @@ // We verify by checking that more packets are needed to transfer // the same amount of data compared to the default. -import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import { hasQuic, skip, mustCall, mustNotCall } from '../common/index.mjs'; import assert from 'node:assert'; import { dump } from 'node:stream/iter'; @@ -55,3 +55,18 @@ const smallPkts = await transferAndGetPacketCount(1200); // The key assertion: the option is accepted and data transfers correctly. assert.ok(defaultPkts > 0n); assert.ok(smallPkts > 0n); + +// Both ends of the supported range work, as a number and as a bigint. +for (const maxPayloadSize of [1200n, 65527, 65527n]) { + assert.ok(await transferAndGetPacketCount(maxPayloadSize) > 0n); +} + +// Anything outside of the range is rejected before a session is created. +for (const maxPayloadSize of [0, 0n, 1199, 1199n, 65528, 65528n]) { + const expected = { + code: 'ERR_INVALID_ARG_VALUE', + message: 'The maxPayloadSize option must be between 1200 and 65527', + }; + await assert.rejects(listen(mustNotCall(), { maxPayloadSize }), expected); + await assert.rejects(connect('127.0.0.1:1', { maxPayloadSize }), expected); +} diff --git a/test/parallel/test-quic-session-application-no-error.mjs b/test/parallel/test-quic-session-application-no-error.mjs new file mode 100644 index 000000000000..bfd2584f8b74 --- /dev/null +++ b/test/parallel/test-quic-session-application-no-error.mjs @@ -0,0 +1,122 @@ +// Flags: --experimental-quic --no-warnings + +// Application-level no-error codes are interpreted in the context of the +// negotiated application protocol. + +import { hasQuic, skip, mustCall, mustNotCall } from '../common/index.mjs'; +import assert from 'node:assert'; +import * as fixtures from '../common/fixtures.mjs'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('node:quic'); +const { createPrivateKey } = await import('node:crypto'); +const key = createPrivateKey(fixtures.readKey('agent1-key.pem')); +const cert = fixtures.readKey('agent1-cert.pem'); + +// H3_NO_ERROR (0x100) and unknown HTTP/3 error codes are clean closes. +// 0x21 is one of the reserved codes defined by RFC 9114 Section 8.1. +for (const code of [0x100n, 0x21n]) { + const serverSessionReady = Promise.withResolvers(); + const endpoint = await listen(mustCall((session) => { + serverSessionReady.resolve(session); + }), { + alpn: ['h3'], + sni: { '*': { keys: [key], certs: [cert] } }, + }); + + const clientSession = await connect(endpoint.address, { + alpn: 'h3', + servername: 'localhost', + verifyPeer: 'manual', + reuseEndpoint: false, + }); + const serverSession = await serverSessionReady.promise; + serverSession.onerror = mustNotCall(); + await Promise.all([ + clientSession.opened, + serverSession.opened, + ]); + + await clientSession.close({ + code, + type: 'application', + reason: 'normal HTTP/3 close', + }); + await serverSession.closed; + await endpoint.close(); +} + +// H3_DATAGRAM_ERROR (0x33) is a known HTTP/3 application error. +{ + const serverSessionReady = Promise.withResolvers(); + const endpoint = await listen(mustCall((session) => { + serverSessionReady.resolve(session); + }), { + alpn: ['h3'], + sni: { '*': { keys: [key], certs: [cert] } }, + }); + + const clientSession = await connect(endpoint.address, { + alpn: 'h3', + servername: 'localhost', + verifyPeer: 'manual', + reuseEndpoint: false, + }); + const serverSession = await serverSessionReady.promise; + await Promise.all([ + clientSession.opened, + serverSession.opened, + ]); + + const closed = assert.rejects(serverSession.closed, { + code: 'ERR_QUIC_APPLICATION_ERROR', + errorCode: 0x33n, + reason: 'HTTP datagram failure', + }); + await clientSession.close({ + code: 0x33n, + type: 'application', + reason: 'HTTP datagram failure', + }); + await closed; + await endpoint.close(); +} + +// The same application code is not implicitly clean for another ALPN. +{ + const serverSessionReady = Promise.withResolvers(); + const endpoint = await listen(mustCall((session) => { + serverSessionReady.resolve(session); + }), { + alpn: ['quic-test'], + sni: { '*': { keys: [key], certs: [cert] } }, + }); + + const clientSession = await connect(endpoint.address, { + alpn: 'quic-test', + servername: 'localhost', + verifyPeer: 'manual', + reuseEndpoint: false, + }); + const serverSession = await serverSessionReady.promise; + await Promise.all([ + clientSession.opened, + serverSession.opened, + ]); + + const closed = assert.rejects(serverSession.closed, { + code: 'ERR_QUIC_APPLICATION_ERROR', + errorCode: 0x100n, + reason: 'application failure', + }); + await clientSession.close({ + code: 0x100n, + type: 'application', + reason: 'application failure', + }); + await closed; + await endpoint.close(); +} diff --git a/test/parallel/test-quic-stream-fin-packet-full.mjs b/test/parallel/test-quic-stream-fin-packet-full.mjs new file mode 100644 index 000000000000..2c0749fd3dc5 --- /dev/null +++ b/test/parallel/test-quic-stream-fin-packet-full.mjs @@ -0,0 +1,57 @@ +// Flags: --experimental-quic --experimental-stream-iter --no-warnings + +// Test: a FIN that does not fit in the current packet is still sent. +// +// For a fixed body the final data and the FIN go out as separate STREAM +// frames, packed into the same packet where possible. When the data leaves +// only a few bytes free, the FIN-only frame does not fit and the packet is +// sent without it. The stream must then be retried, or the peer never sees +// the end of the stream. +// +// Which body size leaves too little room depends on per-packet overhead, so +// this sweeps sizes around one packet's payload, one stream at a time. + +import { hasQuic, skip, mustCall } from '../common/index.mjs'; +import assert from 'node:assert'; + +if (!hasQuic) { + skip('QUIC is not enabled'); +} + +const { listen, connect } = await import('../common/quic.mjs'); +const { bytes } = await import('stream/iter'); + +const kMinSize = 1000; +const kMaxSize = 1300; +const kCount = kMaxSize - kMinSize + 1; + +const received = []; +let next = Promise.withResolvers(); + +const serverEndpoint = await listen(mustCall((serverSession) => { + serverSession.onstream = mustCall(async (stream) => { + const data = await bytes(stream); + received.push(data.byteLength); + next.resolve(); + }, kCount); +})); + +const clientSession = await connect(serverEndpoint.address); +await clientSession.opened; +const closed = clientSession.closed.then(() => 'closed', () => 'closed'); + +for (let size = kMinSize; size <= kMaxSize; size++) { + const stream = await clientSession.createUnidirectionalStream(); + stream.setBody(new Uint8Array(size)); + const result = await Promise.race([next.promise.then(() => 'ok'), closed]); + assert.strictEqual(result, 'ok', + `session closed before the FIN of a ${size}-byte ` + + 'stream arrived'); + next = Promise.withResolvers(); + assert.strictEqual(received.at(-1), size); +} + +assert.strictEqual(received.length, kCount); + +await clientSession.close(); +await serverEndpoint.close(); diff --git a/test/parallel/test-quic-stream-limits-pending.mjs b/test/parallel/test-quic-stream-limits-pending.mjs index 1a4502156724..f4498a3acd07 100644 --- a/test/parallel/test-quic-stream-limits-pending.mjs +++ b/test/parallel/test-quic-stream-limits-pending.mjs @@ -16,9 +16,11 @@ if (!hasQuic) { const { listen, connect } = await import('../common/quic.mjs'); const { bytes } = await import('stream/iter'); +const { setTimeout: sleep } = await import('timers/promises'); const encoder = new TextEncoder(); const allDone = Promise.withResolvers(); +const twoDone = Promise.withResolvers(); let serverStreamCount = 0; // Server allows only 1 bidi stream at a time. @@ -27,11 +29,17 @@ const serverEndpoint = await listen(mustCall((serverSession) => { await bytes(stream); stream.writer.endSync(); await stream.closed; - if (++serverStreamCount === 2) { - serverSession.close(); + ++serverStreamCount; + if (serverStreamCount === 2) { + twoDone.resolve(); + } + if (serverStreamCount === 3) { allDone.resolve(); } - }, 2); + if (serverStreamCount === 4) { + serverSession.close(); + } + }, 3); }), { transportParams: { initialMaxStreamsBidi: 1 }, }); @@ -51,17 +59,34 @@ s1.opened.then(() => { opened++; }); -// Second stream is created but queued as pending because the -// server only allows 1 concurrent bidi stream. -const s2 = await clientSession.createBidirectionalStream({ - body: encoder.encode('stream 2'), +let s2; +await assert.rejects( + async () => { + // Second stream should not open, but throw. + s2 = await clientSession.createBidirectionalStream({ + body: encoder.encode('stream 2a'), + waitUntilAvailable: false, + }); + // eslint-disable-next-line node-core/must-call-assert + s2.opened.then(() => { + opened++; + }); + }, + { + name: 'Error', + message: 'No new stream available within flow control', + }, +); +// Ok try again a second second stream, that patiently waits +s2 = await clientSession.createBidirectionalStream({ + body: encoder.encode('stream 2b') }); - // eslint-disable-next-line node-core/must-call-assert s2.opened.then(() => { opened++; }); + // Third stream is created but queued as pending because the // server only allows 1 concurrent bidi stream. const s3 = await clientSession.createBidirectionalStream({ @@ -69,9 +94,10 @@ const s3 = await clientSession.createBidirectionalStream({ }); -// s2 should be pending until s1 closes and the server grants +// s2 and s3 should be pending until s1 closes and the server grants // more stream credits. assert.strictEqual(s2.pending, true); +assert.strictEqual(s3.pending, true); assert.strictEqual(opened, 1); await dump(s1); @@ -82,15 +108,20 @@ s3.destroy(err); await Promise.all([assert.rejects(s3.opened, err), assert.rejects(s3.closed, err)]); - -// After s1 closes, the server sends MAX_STREAMS which opens s2. +// After s1 closes, the server sends MAX_STREAMS which opens s3. // Wait for the server to receive both streams. -await allDone.promise; -assert.strictEqual(opened, 2); - +await twoDone.promise; // s2 should no longer be pending. await dump(s2); await s2.closed; +await sleep(10); // We wait a bit, as we do not have a callback exposed to js +// fourth stream should open immediately and not throw +const s4 = await clientSession.createBidirectionalStream({ + body: encoder.encode('stream 4'), + waitUntilAvailable: false +}); +await Promise.all([s4.closed, allDone.promise]); + await clientSession.close(); await serverEndpoint.close(); diff --git a/test/parallel/test-quic-stream-limits-uni.mjs b/test/parallel/test-quic-stream-limits-uni.mjs index f3686ca45e3c..1c7fbd974386 100644 --- a/test/parallel/test-quic-stream-limits-uni.mjs +++ b/test/parallel/test-quic-stream-limits-uni.mjs @@ -39,6 +39,7 @@ let opened = 0; // First uni stream opens immediately. const s1 = await clientSession.createUnidirectionalStream({ body: encoder.encode('uni 1'), + waitUntilAvailable: false, }); // eslint-disable-next-line node-core/must-call-assert diff --git a/test/parallel/test-quic-stream-truncated-reads.mjs b/test/parallel/test-quic-stream-truncated-reads.mjs index e5c381a8d679..0fed12dbb6fc 100644 --- a/test/parallel/test-quic-stream-truncated-reads.mjs +++ b/test/parallel/test-quic-stream-truncated-reads.mjs @@ -3,8 +3,8 @@ // Test: a stream read that ends without a FIN is a truncation. What the read // reports is decided in this order: // -// 1. the peer reset the stream with a non-zero code: ERR_QUIC_STREAM_RESET -// carrying that code, under either policy; +// 1. the peer reset the stream with an application error code: +// ERR_QUIC_STREAM_RESET carrying that code, under either policy; // 2. the stream was already being torn down and its closed promise rejected: // that same error, under either policy; // 3. otherwise the truncation carries no error of its own and the @@ -53,8 +53,8 @@ const stall = (stream) => { stream.setBody(stallingBody(1000)); }; assert.strictEqual(threw, undefined); } -// A peer reset with a nonzero code is rule 1: an error under either policy, -// carrying the peer's code. It also rejects the closed promise on both sides. +// A peer reset whose code represents an application error is rule 1 under +// either policy, carrying the peer's code. It also rejects closed on both sides. { const serverClosed = Promise.withResolvers(); const { received, threw, closedError } = await readStream(async (stream) => { diff --git a/test/parallel/test-quic-zero-rtt-disabled-server.mjs b/test/parallel/test-quic-zero-rtt-disabled-server.mjs index c2164d7c8b35..b1190e8379e2 100644 --- a/test/parallel/test-quic-zero-rtt-disabled-server.mjs +++ b/test/parallel/test-quic-zero-rtt-disabled-server.mjs @@ -22,71 +22,114 @@ const cert = fixtures.readKey('agent1-cert.pem'); const sni = { '*': { keys: [key], certs: [cert] } }; const alpn = ['quic-test']; -// Use the same tokenSecret for both servers so the token is valid. -const tokenSecret = randomBytes(16); - -let savedTicket; -let savedToken; -const gotTicket = Promise.withResolvers(); -const gotToken = Promise.withResolvers(); - -// First server: enableEarlyData: true (default) to generate a valid ticket. -const serverEndpoint1 = await listen((serverSession) => { - serverSession.onstream = async (stream) => { - for await (const _ of stream) { /* drain */ } // eslint-disable-line no-unused-vars - stream.writer.endSync(); - await stream.closed; +{ + // Use the same tokenSecret for both servers so the token is valid. + const tokenSecret = randomBytes(16); + + let savedTicket; + let savedToken; + const gotTicket = Promise.withResolvers(); + const gotToken = Promise.withResolvers(); + + // First server: enableEarlyData: true (default) to generate a valid ticket. + const serverEndpoint1 = await listen((serverSession) => { + serverSession.onstream = async (stream) => { + for await (const _ of stream) { /* drain */ } // eslint-disable-line no-unused-vars + stream.writer.endSync(); + await stream.closed; + serverSession.close(); + }; + }, { + sni, + alpn, + endpoint: { tokenSecret }, + }); + + const cs1 = await connect(serverEndpoint1.address, { + alpn: 'quic-test', + verifyPeer: 'manual', + onsessionticket(ticket) { + savedTicket = ticket; + gotTicket.resolve(); + }, + onnewtoken(token) { + savedToken = token; + gotToken.resolve(); + }, + }); + await Promise.all([cs1.opened, gotTicket.promise, gotToken.promise]); + await cs1.close(); + await serverEndpoint1.close(); + + // Second server: enableEarlyData: false — rejects 0-RTT. + const serverEndpoint2 = await listen(async (serverSession) => { + await serverSession.opened; serverSession.close(); - }; -}, { - sni, - alpn, - endpoint: { tokenSecret }, -}); - -const cs1 = await connect(serverEndpoint1.address, { - alpn: 'quic-test', - verifyPeer: 'manual', - onsessionticket(ticket) { - savedTicket = ticket; - gotTicket.resolve(); - }, - onnewtoken(token) { - savedToken = token; - gotToken.resolve(); - }, -}); -await Promise.all([cs1.opened, gotTicket.promise, gotToken.promise]); -await cs1.close(); -await serverEndpoint1.close(); - -// Second server: enableEarlyData: false — rejects 0-RTT. -const serverEndpoint2 = await listen(async (serverSession) => { - await serverSession.opened; - serverSession.close(); - await serverSession.closed; -}, { - sni, - alpn, - enableEarlyData: false, - endpoint: { tokenSecret }, - onerror: mustNotCall(), -}); - -const cs2 = await connect(serverEndpoint2.address, { - alpn: 'quic-test', - verifyPeer: 'manual', - sessionTicket: savedTicket, - token: savedToken, -}); - -// The deferred handshake needs a send to trigger. Use sendDatagram -// since it's simpler than a stream for this test. -await cs2.sendDatagram(new Uint8Array([1])); - -const info2 = await cs2.opened; -assert.strictEqual(info2.earlyDataAttempted, true); -assert.strictEqual(info2.earlyDataAccepted, false); - -await cs2.closed; -await serverEndpoint2.close(); + await serverSession.closed; + }, { + sni, + alpn, + enableEarlyData: false, + endpoint: { tokenSecret }, + onerror: mustNotCall(), + }); + + const cs2 = await connect(serverEndpoint2.address, { + alpn: 'quic-test', + verifyPeer: 'manual', + sessionTicket: savedTicket, + token: savedToken, + }); + + // The deferred handshake needs a send to trigger. Use sendDatagram + // since it's simpler than a stream for this test. + await cs2.sendDatagram(new Uint8Array([1])); + + const info2 = await cs2.opened; + assert.strictEqual(info2.earlyDataAttempted, true); + assert.strictEqual(info2.earlyDataAccepted, false); + + await cs2.closed; + await serverEndpoint2.close(); +} + +// A server with early data disabled must issue tickets that do not permit +// 0-RTT. Reusing the ticket on the same endpoint must fall back to 1-RTT. +{ + const ticketReady = Promise.withResolvers(); + const endpoint = await listen(() => {}, { + sni, + alpn, + enableEarlyData: false, + onerror: mustNotCall(), + }); + + const client = await connect(endpoint.address, { + alpn: 'quic-test', + verifyPeer: 'manual', + onsessionticket(ticket) { + ticketReady.resolve(ticket); + }, + }); + + await client.opened; + const ticket = await ticketReady.promise; + await client.close(); + + const client2 = await connect(endpoint.address, { + alpn: 'quic-test', + verifyPeer: 'manual', + sessionTicket: ticket, + }); + + await client2.createUnidirectionalStream({ + body: 'hello from 0-RTT', + }); + + const info = await client2.opened; + assert.strictEqual(info.earlyDataAttempted, false); + assert.strictEqual(info.earlyDataAccepted, false); + + await client2.close(); + await endpoint.close(); +} diff --git a/test/parallel/test-repl-paste-highlight.js b/test/parallel/test-repl-paste-highlight.js new file mode 100644 index 000000000000..152bddf684e8 --- /dev/null +++ b/test/parallel/test-repl-paste-highlight.js @@ -0,0 +1,84 @@ +// Flags: --expose-internals +'use strict'; + +// Pasted text reaches the REPL as a single input chunk containing many +// characters. With syntax highlighting enabled, check that such a chunk leaves +// the correct line buffer, highlighted rendering and evaluated result. + +const common = require('../common'); +const assert = require('assert'); +const { highlight } = require('internal/repl/highlight'); +const { startNewREPLServer } = require('../common/repl'); + +common.skipIfInspectorDisabled(); + +// Everything written since the most recent full redraw of the input. +function lastRedraw(rendered) { + const clearScreenDown = '\x1b[0J'; + return rendered.slice(rendered.lastIndexOf(clearScreenDown) + clearScreenDown.length); +} + +// The expected rendering is built with the REPL's own highlighter on purpose. +// This test is not about which colors highlight() picks (that is covered by +// test-repl-highlight.js); whatever it produces is taken as correct. The point +// is that a pasted chunk ends up rendered exactly as highlight() renders the +// same text when it is typed, so changes to the highlighting style do not +// require changes here. +function expectedRendering(line) { + const [first, ...rest] = line.split('\n'); + return `> ${highlight(first)}` + rest.map((l) => `\n| ${highlight(l)}`).join(''); +} + +// Pastes `chunk` as one 'data' event, checks the resulting line and its +// rendering, then submits the line and returns the REPL context. +async function paste(chunk, expectedLine) { + const { replServer, output, run } = startNewREPLServer({ + prompt: '> ', + useColors: true, + }); + output.accumulator = ''; + + await run(chunk); + assert.strictEqual(replServer.line, expectedLine); + const rendered = lastRedraw(output.accumulator); + assert.ok( + rendered.startsWith(expectedRendering(expectedLine)), + `unexpected rendering: ${JSON.stringify(rendered)}`, + ); + + await run('\r'); + replServer.close(); + return replServer.context; +} + +function createObject(i) { + return { + id: i, + name: `item-${i}`, + tags: ['alpha', 'beta', 'gamma'], + nested: { enabled: true, ratio: 0.5, label: 'a string value' }, + }; +} + +(async () => { + // Large multi-line object. + { + const objects = []; + for (let i = 0; i < 16; i++) objects.push(createObject(i)); + const lines = `x = ${JSON.stringify(objects, null, 2)}`.split('\n'); + const context = await paste(lines.join('\r'), lines.join('\n')); + assert.strictEqual(JSON.stringify(context.x), JSON.stringify(objects)); + } + + // Long single line. + { + const items = []; + for (let i = 0; i < 100; i++) { + items.push(`{ id: ${i}, name: 'item-${i}', tags: ['a', 'b'] }`); + } + const line = `y = [${items.join(', ')}]`; + const context = await paste(line, line); + assert.strictEqual(context.y.length, 100); + assert.strictEqual(context.y[99].name, 'item-99'); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-runner-entry-file.mjs b/test/parallel/test-runner-entry-file.mjs index 94750e6a745e..9b630453825d 100644 --- a/test/parallel/test-runner-entry-file.mjs +++ b/test/parallel/test-runner-entry-file.mjs @@ -48,6 +48,19 @@ describe('entryFile attribution in reporter events', { concurrency: false }, () assert.strictEqual(backupB.data.entryFile, bPath); }); + it('resolves entryFile against the cwd option', async () => { + const events = await collectEvents({ + isolation: 'process', + cwd: fixtures.path('test-runner', 'entry-file'), + files: ['a.test.mjs', 'b.test.mjs'], + }); + const pass = events.filter(({ type }) => type === 'test:pass'); + const backupA = pass.find(({ data }) => data.name === 'backup A'); + const backupB = pass.find(({ data }) => data.name === 'backup B'); + assert.strictEqual(backupA.data.entryFile, aPath); + assert.strictEqual(backupB.data.entryFile, bPath); + }); + it('does not stamp entryFile with isolation none', async () => { const events = await collectEvents({ isolation: 'none' }); for (const { data } of events) { diff --git a/test/parallel/test-runner-force-exit-stdout-drain.js b/test/parallel/test-runner-force-exit-stdout-drain.js new file mode 100644 index 000000000000..4fe012321099 --- /dev/null +++ b/test/parallel/test-runner-force-exit-stdout-drain.js @@ -0,0 +1,51 @@ +'use strict'; +// With --test-force-exit, buffered reporter output on stdout (both in test +// child processes and in the main runner) must be flushed before exiting. +// Refs: https://github.com/nodejs/node/issues/67149 +require('../common'); +const tmpdir = require('../common/tmpdir'); +const assert = require('node:assert'); +const { spawn } = require('node:child_process'); +const { writeFileSync } = require('node:fs'); +const { once } = require('node:events'); +const { setTimeout } = require('node:timers/promises'); +const { test } = require('node:test'); + +const kFiles = 8; +const kTestsPerFile = 300; + +tmpdir.refresh(); +const files = []; +for (let i = 0; i < kFiles; i++) { + const file = tmpdir.resolve(`t${i}.test.js`); + writeFileSync(file, `'use strict'; +const { test } = require('node:test'); +for (let i = 0; i < ${kTestsPerFile}; i++) { + test('test ' + i + ' ' + 'x'.repeat(1000), () => {}); +} +`); + files.push(file); +} + +test('no results are lost when stdout is read slowly', async () => { + const child = spawn(process.execPath, [ + '--test', + '--test-force-exit', + `--test-concurrency=${kFiles}`, + '--test-reporter=junit', + ...files, + ], { cwd: tmpdir.path }); + + // Let the pipes back up before reading anything. + child.stdout.pause(); + await setTimeout(1000); + let stdout = ''; + child.stdout.setEncoding('utf8'); + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stdout.resume(); + + const [code] = await once(child, 'close'); + assert.strictEqual(code, 0); + assert.strictEqual(stdout.match(/<testcase /g)?.length, kFiles * kTestsPerFile); + assert.match(stdout, /<\/testsuites>\n$/); +}); diff --git a/test/parallel/test-runner-junit-invalid-xml.js b/test/parallel/test-runner-junit-invalid-xml.js new file mode 100644 index 000000000000..83f7d80f8734 --- /dev/null +++ b/test/parallel/test-runner-junit-invalid-xml.js @@ -0,0 +1,96 @@ +'use strict'; +// Regression tests for the junit reporter emitting malformed XML. +require('../common'); +const fixtures = require('../common/fixtures'); +const assert = require('node:assert'); +const { spawnSync } = require('node:child_process'); +const { test } = require('node:test'); +const { junit } = require('node:test/reporters'); + +// Characters that XML 1.0 forbids anywhere, even as character references. +const kInvalidXMLChars = /[^\t\n\r\x20-퟿-�\u{10000}-\u{10FFFF}]/u; + +function assertWellFormedChars(xml) { + assert.doesNotMatch(xml, kInvalidXMLChars); + for (const { 1: dec, 2: hex } of xml.matchAll(/&#(?:(\d+)|x([0-9a-fA-F]+));/g)) { + const code = dec !== undefined ? Number(dec) : Number.parseInt(hex, 16); + assert.doesNotMatch(String.fromCodePoint(code), kInvalidXMLChars, + `illegal character reference &#${dec ?? `x${hex}`};`); + } +} + +async function render(events) { + let out = ''; + for await (const chunk of junit((async function*() { yield* events; })())) { + out += chunk; + } + return out; +} + +const details = { duration_ms: 1 }; + +test('control characters are not written to the report', async () => { + const name = 'name\x00with\x1b[31mcontrols\x1b[39m\x07￾\uD800'; + const error = new Error('\x1b[32mexpected\x1b[39m\x0b\x0c\x00'); + const xml = await render([ + { type: 'test:start', data: { name, nesting: 0 } }, + { type: 'test:fail', data: { name, nesting: 0, details: { ...details, error } } }, + { type: 'test:diagnostic', data: { nesting: 0, message: 'diag\x00\x1b[1m' } }, + ]); + assertWellFormedChars(xml); + // ANSI escape sequences are stripped, other illegal characters are replaced. + assert.match(xml, /name="name�withcontrols���&#27;"/); + assert.match(xml, /message="expected���"/); + assert.match(xml, /<!-- diag� -->/); +}); + +test('colored assertion diffs produce a valid report', () => { + const child = spawnSync(process.execPath, [ + '--test-reporter=junit', + fixtures.path('test-runner', 'junit-colored-diff.js'), + ], { env: { ...process.env, FORCE_COLOR: '1' } }); + const xml = child.stdout.toString(); + assert.strictEqual(child.status, 1, child.stderr.toString()); + assert.match(xml, /<failure /); + assertWellFormedChars(xml); +}); + +test('a test that never reports a result does not swallow later tests', async () => { + const xml = await render([ + { type: 'test:start', data: { name: 'suite', nesting: 0 } }, + { type: 'test:start', data: { name: 'first', nesting: 1 } }, + { type: 'test:pass', data: { name: 'first', nesting: 1, details } }, + { type: 'test:start', data: { name: 'next file', nesting: 0 } }, + { type: 'test:pass', data: { name: 'next file', nesting: 0, details } }, + ]); + assert.doesNotMatch(xml, /undefined/); + assert.strictEqual(xml, [ + '<?xml version="1.0" encoding="utf-8"?>', + '<testsuites>', + `\t<testsuite name="suite" disabled="0" errors="0" tests="1" failures="0" skipped="0" hostname="${require('os').hostname()}">`, + '\t\t<testcase name="first" time="0.001000" classname="test"/>', + '\t</testsuite>', + '\t<testcase name="next file" time="0.001000" classname="test"/>', + '</testsuites>', + '', + ].join('\n')); +}); + +test('an unfinished leaf test is reported as a failure', async () => { + const xml = await render([ + { type: 'test:start', data: { name: 'lost', nesting: 0 } }, + { type: 'test:start', data: { name: 'ok', nesting: 0 } }, + { type: 'test:pass', data: { name: 'ok', nesting: 0, details } }, + ]); + assert.match(xml, /<testcase name="lost" classname="test" failure="test did not report a result">\n\t\t<failure type="incomplete" message="test did not report a result"\/>\n\t<\/testcase>/); + assert.match(xml, /<testcase name="ok" time="0\.001000" classname="test"\/>/); +}); + +test('results without a test:start are not wrapped in an undefined element', async () => { + const xml = await render([ + { type: 'test:pass', data: { name: 'a', nesting: 0, details } }, + { type: 'test:pass', data: { name: 'b', nesting: 0, details } }, + ]); + assert.doesNotMatch(xml, /undefined|name="root"/); + assert.match(xml, /^\t<testcase name="a" [^\n]*\/>\n\t<testcase name="b" [^\n]*\/>$/m); +}); diff --git a/test/parallel/test-runner-tags-inheritance.mjs b/test/parallel/test-runner-tags-inheritance.mjs index 0285ad97b678..703e4021606d 100644 --- a/test/parallel/test-runner-tags-inheritance.mjs +++ b/test/parallel/test-runner-tags-inheritance.mjs @@ -46,6 +46,23 @@ test('multi-level nesting flattens by union', () => { }); }); +test('suite context exposes inherited tags', () => { + describe('outer', { tags: ['a'] }, () => { + describe('mid', { tags: ['b'] }, (s) => { + assert.deepStrictEqual(s.tags, ['a', 'b']); + }); + }); +}); + +test('child tags do not leak into the suite context', () => { + describe('suite', { tags: ['a'] }, (s) => { + it('child', { tags: ['b'] }, (t) => { + assert.deepStrictEqual(t.tags, ['a', 'b']); + assert.deepStrictEqual(s.tags, ['a']); + }); + }); +}); + test('child without own tags inherits parent set unchanged', () => { describe('outer', { tags: ['db', 'fast'] }, () => { it('child', (t) => { diff --git a/test/parallel/test-runner-test-rerun-failures.js b/test/parallel/test-runner-test-rerun-failures.js index 585406ec919c..cdaef0f1d6d3 100644 --- a/test/parallel/test-runner-test-rerun-failures.js +++ b/test/parallel/test-runner-test-rerun-failures.js @@ -232,6 +232,32 @@ test('failing test is not swallowed when siblings share its source location', as assertAttempt(state, 1); }); +{ + // Both fixtures register all of their suites and tests from the same + // location in a shared helper. In each mode, the suite that fails must keep + // failing on the next attempt, and the ones that passed must be replayed. + const a = fixtures.path('test-runner', 'rerun-shared-helper-across-files', 'a.mjs'); + const b = fixtures.path('test-runner', 'rerun-shared-helper-across-files', 'b.mjs'); + const modes = [ + { name: 'process isolation', args: ['--test', a, b], pass: 5 }, + { name: 'no isolation', args: ['--test', '--test-isolation=none', a, b], pass: 5 }, + { name: 'a file run without --test', args: [b], pass: 3 }, + ]; + + for (const { name, args, pass } of modes) { + test(`failing test in a helper shared by test files is not swallowed with ${name}`, async () => { + for (let attempt = 0; attempt < 2; attempt++) { + const { code, signal, stdout } = await common.spawnPromisified( + process.execPath, ['--test-rerun-failures', stateFile, ...args]); + assert.strictEqual(signal, null); + assert.match(stdout, new RegExp(`^ℹ pass ${pass}$`, 'm'), `attempt ${attempt}`); + assert.match(stdout, /^ℹ fail 1$/m, `attempt ${attempt}`); + assert.strictEqual(code, 1, `attempt ${attempt}`); + } + }); + } +} + test('rerun preserves the original duration on the replayed pass', async () => { const durationFixture = fixtures.path('test-runner', 'rerun-duration.js'); const args = ['--test-rerun-failures', stateFile, durationFixture]; diff --git a/test/parallel/test-runner-v8-deserializer.mjs b/test/parallel/test-runner-v8-deserializer.mjs index f376ca6edb86..b0ca5eb7d3f2 100644 --- a/test/parallel/test-runner-v8-deserializer.mjs +++ b/test/parallel/test-runner-v8-deserializer.mjs @@ -91,7 +91,7 @@ describe('v8 deserializer', common.mustCall(() => { reported = []; fileTest = new runner.FileTest({ name: 'filetest', - harness: { config: {} }, + harness: { config: { cwd: process.cwd() } }, }); fileTest.reporter.on('data', (data) => reported.push(data)); assert(fileTest.isClearToSend()); diff --git a/test/parallel/test-source-map-entry-indices.js b/test/parallel/test-source-map-entry-indices.js new file mode 100644 index 000000000000..e1e8406ae576 --- /dev/null +++ b/test/parallel/test-source-map-entry-indices.js @@ -0,0 +1,70 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { SourceMap } = require('node:module'); + +// Segments listed out of column order are looked up by generated position. +{ + const sm = new SourceMap({ + version: 3, + sources: ['a.js'], + names: [], + mappings: 'KAAA,LAAC', + }); + + assert.strictEqual(sm.findEntry(0, 0).originalColumn, 1); + assert.strictEqual(sm.findEntry(0, 6).originalColumn, 0); +} + +// In an index map, a source or name index outside its own section's lists +// does not resolve to an entry of another section. +{ + const sm = new SourceMap({ + version: 3, + sections: [ + { + offset: { line: 0, column: 0 }, + map: { + version: 3, + sources: ['a.js'], + names: ['first'], + mappings: 'AAAAA,ECAAC', + }, + }, + { + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['b.js'], + names: ['second'], + mappings: 'AAAAA', + }, + }, + ], + }); + + assert.deepStrictEqual(sm.findEntry(0, 0), { + generatedLine: 0, + generatedColumn: 0, + originalSource: 'a.js', + originalLine: 0, + originalColumn: 0, + name: 'first', + }); + assert.deepStrictEqual(sm.findEntry(0, 2), { + generatedLine: 0, + generatedColumn: 2, + originalSource: undefined, + originalLine: 0, + originalColumn: 0, + name: undefined, + }); + assert.deepStrictEqual(sm.findEntry(1, 0), { + generatedLine: 1, + generatedColumn: 0, + originalSource: 'b.js', + originalLine: 0, + originalColumn: 0, + name: 'second', + }); +} diff --git a/test/parallel/test-source-map-invalid-section-offset.js b/test/parallel/test-source-map-invalid-section-offset.js new file mode 100644 index 000000000000..3a0783a2ea78 --- /dev/null +++ b/test/parallel/test-source-map-invalid-section-offset.js @@ -0,0 +1,42 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { SourceMap } = require('node:module'); + +// Section offsets are stored in an Int32Array, so they must be validated +// instead of being implicitly coerced. +function sectionedMap(offset) { + return { + version: 3, + sections: [{ + offset, + map: { + version: 3, + sources: ['a.js'], + names: [], + mappings: 'AAAA', + }, + }], + }; +} + +{ + const sm = new SourceMap(sectionedMap({ line: 1, column: 2 })); + assert.deepStrictEqual(sm.findEntry(1, 2), { + generatedLine: 1, + generatedColumn: 2, + originalSource: 'a.js', + originalLine: 0, + originalColumn: 0, + name: undefined, + }); +} + +for (const value of ['1', 1.5, 2 ** 31, null, {}]) { + assert.throws(() => new SourceMap(sectionedMap({ line: value, column: 0 })), { + code: /^ERR_(INVALID_ARG_TYPE|OUT_OF_RANGE)$/, + }); + assert.throws(() => new SourceMap(sectionedMap({ line: 0, column: value })), { + code: /^ERR_(INVALID_ARG_TYPE|OUT_OF_RANGE)$/, + }); +} diff --git a/test/parallel/test-source-map-scopes-decoding.js b/test/parallel/test-source-map-scopes-decoding.js new file mode 100644 index 000000000000..72c4e14919f9 --- /dev/null +++ b/test/parallel/test-source-map-scopes-decoding.js @@ -0,0 +1,70 @@ +// Flags: --expose-internals +'use strict'; + +// Decoding of the scopes proposal beyond the test426 decoding tests in +// test/test426/test-source-map-decoding.mjs. + +require('../common'); +const fixtures = require('../common/fixtures'); +const assert = require('assert'); +const { SourceMap, kScopes } = require('internal/source_map/source_map'); + +// DecodeIndexSourceMap appends the sources of each section, with their +// [[RootScopes]], and has no [[Ranges]]. +{ + const section = JSON.parse( + fixtures.readSync(['test426', 'decoding', 'scopes', 'range-call-site.map'], 'utf8')); + const { originalScopes, generatedRanges } = new SourceMap({ + version: 3, + sections: [ + { offset: { line: 0, column: 0 }, map: section }, + { offset: { line: 20, column: 4 }, map: section }, + ], + })[kScopes]; + assert.strictEqual(originalScopes.length, 2); + assert.strictEqual(originalScopes[0][0].name, null); + assert.strictEqual(originalScopes[1][0].children[0].name, 'inlineMe'); + assert.strictEqual(originalScopes[1][0].sourceIndex, 1); + assert.deepStrictEqual(generatedRanges, []); +} + +// A range can reference the innermost of deeply nested scopes. +{ + const depth = 50_000; + const { originalScopes, generatedRanges } = new SourceMap({ + version: 3, + sources: ['original.js'], + names: [], + mappings: '', + scopes: ['BAAA,'.repeat(depth) + 'CAA,'.repeat(depth - 1) + 'CAA'], + // Definition: source 0, scope index 49999 (`+0hD`), the innermost scope. + ranges: ['ECAA+0hD,FA'], + })[kScopes]; + let innermost = originalScopes[0][0]; + for (let i = 1; i < depth; ++i) innermost = innermost.children[0]; + assert.strictEqual(innermost.children.length, 0); + assert.strictEqual(generatedRanges[0].definition, innermost); +} + +// Malformed scopes and ranges decode to nothing instead of throwing. +for (const [scopes, ranges, scopeCount, rangeCount] of [ + ['BCAAA,CKA', 'ECAAA,FKA', 1, 1], // Well-formed. + ['BCAAA', 'ECAAA', 0, 0], // Start without an end. + ['CKA', 'FKA', 0, 0], // End without a start. + ['BCAA!,CKA', 'ECAA!,FKA', 0, 0], // Invalid base64 digit. + ['BCAAg,CKA', 'ECAAg,FKA', 0, 0], // Truncated VLQ. + ['BCAAA,ZZ,CKA', 'ECAAA,ZZ,FKA', 1, 1], // Unknown items are ignored. + ['BA//////DA,CAA', 'EA//////D,FA', 1, 1], // A Vlq of 2^32 - 1. + ['BAggggggEA,CAA', 'EAggggggE,FA', 0, 0], // A Vlq of 2^32. +]) { + const { originalScopes, generatedRanges } = new SourceMap({ + version: 3, + sources: ['original.js'], + names: ['global'], + mappings: '', + scopes: [scopes], + ranges: [ranges], + })[kScopes]; + assert.strictEqual(originalScopes[0].length, scopeCount, scopes); + assert.strictEqual(generatedRanges.length, rangeCount, ranges); +} diff --git a/test/parallel/test-source-map-section-names.js b/test/parallel/test-source-map-section-names.js new file mode 100644 index 000000000000..22c342951ef8 --- /dev/null +++ b/test/parallel/test-source-map-section-names.js @@ -0,0 +1,35 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { SourceMap } = require('node:module'); + +// Names are looked up across sections, including sections that have no names. +const sm = new SourceMap({ + version: 3, + sections: [ + { + offset: { line: 0, column: 0 }, + map: { version: 3, sources: ['a.js'], names: ['a0', 'a1'], + mappings: 'AAAAA,CAAAC' }, + }, + { + offset: { line: 1, column: 0 }, + map: { version: 3, sources: ['b.js'], mappings: 'AAAA' }, + }, + { + offset: { line: 2, column: 0 }, + map: { version: 3, sources: ['c.js'], names: [], mappings: 'AAAA' }, + }, + { + offset: { line: 3, column: 0 }, + map: { version: 3, sources: ['d.js'], names: ['d0'], + mappings: 'AAAAA' }, + }, + ], +}); + +assert.strictEqual(sm.findEntry(0, 0).name, 'a0'); +assert.strictEqual(sm.findEntry(0, 1).name, 'a1'); +assert.strictEqual(sm.findEntry(1, 0).name, undefined); +assert.strictEqual(sm.findEntry(2, 0).name, undefined); +assert.strictEqual(sm.findEntry(3, 0).name, 'd0'); diff --git a/test/parallel/test-source-map-trailing-unmapped-segment.js b/test/parallel/test-source-map-trailing-unmapped-segment.js new file mode 100644 index 000000000000..d5c7243ad999 --- /dev/null +++ b/test/parallel/test-source-map-trailing-unmapped-segment.js @@ -0,0 +1,67 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const { SourceMap } = require('node:module'); + +// A segment with only a generated column marks the code after it as unmapped. +// When it is the last segment of the mappings, it must not inherit the +// original position of the segment before it. +const unmapped = { + originalSource: undefined, + originalLine: undefined, + originalColumn: undefined, + name: undefined, +}; + +// Trailing unmapped segment on the same line as the last mapped segment. +{ + const sm = new SourceMap({ + version: 3, + sources: ['a.js'], + names: [], + mappings: 'AAAA,K', + }); + + assert.deepStrictEqual(sm.findEntry(0, 5), { + generatedLine: 0, + generatedColumn: 5, + ...unmapped, + }); + assert.deepStrictEqual(sm.findOrigin(1, 6), {}); +} + +// Trailing unmapped segment on a later line. +{ + const sm = new SourceMap({ + version: 3, + sources: ['a.js'], + names: [], + mappings: 'AAAA;A', + }); + + assert.deepStrictEqual(sm.findEntry(1, 3), { + generatedLine: 1, + generatedColumn: 0, + ...unmapped, + }); + assert.deepStrictEqual(sm.findOrigin(2, 4), {}); +} + +// A segment without a name field must not pick up a name from the names array. +{ + const sm = new SourceMap({ + version: 3, + sources: ['a.js'], + names: ['should-not-be-used'], + mappings: 'AAAA', + }); + + assert.deepStrictEqual(sm.findEntry(0, 0), { + generatedLine: 0, + generatedColumn: 0, + originalSource: 'a.js', + originalLine: 0, + originalColumn: 0, + name: undefined, + }); +} diff --git a/test/parallel/test-sqlite-custom-functions.js b/test/parallel/test-sqlite-custom-functions.js index 0a4b80b80ae2..c6c5fa0388ce 100644 --- a/test/parallel/test-sqlite-custom-functions.js +++ b/test/parallel/test-sqlite-custom-functions.js @@ -322,6 +322,30 @@ suite('Database.prototype.function()', () => { }); }); + test('empty buffers are returned as empty blobs, not NULL', () => { + using db = new Database(':memory:'); + db.function('retEmptyArrayBuffer', () => new ArrayBuffer(0)); + db.function('retEmptySharedArrayBuffer', () => new SharedArrayBuffer(0)); + db.function('retEmptyUint8Array', () => { + return new Uint8Array(new ArrayBuffer(0)); + }); + using stmt = db.prepare(`SELECT + typeof(retEmptyArrayBuffer()) AS arrayBufferType, + typeof(retEmptySharedArrayBuffer()) AS sharedArrayBufferType, + typeof(retEmptyUint8Array()) AS uint8ArrayType, + retEmptyArrayBuffer() AS arrayBuffer, + retEmptySharedArrayBuffer() AS sharedArrayBuffer + `); + assert.deepStrictEqual(stmt.get(), { + __proto__: null, + arrayBufferType: 'blob', + sharedArrayBufferType: 'blob', + uint8ArrayType: 'blob', + arrayBuffer: new Uint8Array(), + sharedArrayBuffer: new Uint8Array(), + }); + }); + test('throws if returned BigInt is too large for SQLite', () => { const db = new Database(':memory:'); db.function('retBigInt', () => { diff --git a/test/parallel/test-sqlite-diagnostic-channel.js b/test/parallel/test-sqlite-diagnostic-channel.js index eb9461f337d5..20df20edfe16 100644 --- a/test/parallel/test-sqlite-diagnostic-channel.js +++ b/test/parallel/test-sqlite-diagnostic-channel.js @@ -234,4 +234,38 @@ suite('sqlite.db.query diagnostics channel', () => { { __proto__: null, x: 1 }, ]); }); + + it('does not replace an exception that is already pending', (t) => { + using db = new Database(':memory:'); + let calls = 0; + const handler = () => { + calls++; + }; + dc.subscribe('sqlite.db.query', handler); + t.after(() => dc.unsubscribe('sqlite.db.query', handler)); + + db.function('boom', () => { + throw new Error('boom'); + }); + assert.throws(() => db.prepare('SELECT boom()').get(), { + message: 'boom', + }); + + db.exec('CREATE TABLE t (a INTEGER)'); + db.exec('INSERT INTO t VALUES (9223372036854775807)'); + assert.throws(() => db.prepare('SELECT a FROM t').get(), { + code: 'ERR_OUT_OF_RANGE', + }); + assert.throws(() => db.prepare('SELECT a FROM t').all(), { + code: 'ERR_OUT_OF_RANGE', + }); + + // A query that does not throw is still published. + const before = calls; + assert.deepStrictEqual(db.prepare('SELECT 1 AS x').get(), { + __proto__: null, + x: 1, + }); + assert.ok(calls > before); + }); }); diff --git a/test/parallel/test-sqlite-error-setter-reentry.js b/test/parallel/test-sqlite-error-setter-reentry.js new file mode 100644 index 000000000000..d3d8b6ba6dd0 --- /dev/null +++ b/test/parallel/test-sqlite-error-setter-reentry.js @@ -0,0 +1,61 @@ +'use strict'; + +const { skipIfSQLiteMissing, mustCall } = require('../common'); +skipIfSQLiteMissing(); +const assert = require('node:assert'); +const { test } = require('node:test'); +const { Database } = require('node:sqlite'); + +// Setting `code` on a thrown error runs Error.prototype setters. Closing the +// database there must not crash run() or get(). +function closeFromCodeSetter(db, fn) { + Object.defineProperty(Error.prototype, 'code', { + __proto__: null, + configurable: true, + get: undefined, + set: mustCall(() => { + delete Error.prototype.code; + db.close(); + }), + }); + try { + return fn(); + } finally { + delete Error.prototype.code; + } +} + +const cases = [ + { + name: 'statement.run() failing in sqlite3_step()', + sql: 'INSERT INTO t VALUES (1)', + call: (db, sql) => db.prepare(sql).run(), + error: { message: 'UNIQUE constraint failed: t.x' }, + }, + { + name: 'statement.get() failing to convert a row', + sql: 'SELECT 9007199254740993', + call: (db, sql) => db.prepare(sql).get(), + error: { name: 'RangeError', message: /too large/ }, + }, + { + name: 'tag store run() failing in sqlite3_step()', + call: (db) => db.createTagStore().run`INSERT INTO t VALUES (1)`, + error: { message: 'UNIQUE constraint failed: t.x' }, + }, + { + name: 'tag store get() failing to convert a row', + call: (db) => db.createTagStore().get`SELECT 9007199254740993`, + error: { name: 'RangeError', message: /too large/ }, + }, +]; + +for (const { name, sql, call, error } of cases) { + test(`database.close() from an error setter during ${name}`, () => { + const db = new Database(':memory:'); + db.exec('CREATE TABLE t (x UNIQUE); INSERT INTO t VALUES (1);'); + + assert.throws(() => closeFromCodeSetter(db, () => call(db, sql)), error); + assert.strictEqual(db.isOpen, false); + }); +} diff --git a/test/parallel/test-sqlite-typed-array-and-data-view.js b/test/parallel/test-sqlite-typed-array-and-data-view.js index e13b8b33daab..b0766aaa01c1 100644 --- a/test/parallel/test-sqlite-typed-array-and-data-view.js +++ b/test/parallel/test-sqlite-typed-array-and-data-view.js @@ -120,3 +120,38 @@ suite('Statement with ArrayBuffer and SharedArrayBuffer', () => { }); } }); + +suite('Statement with empty buffers', () => { + const emptyBuffers = [ + ['ArrayBuffer', () => new ArrayBuffer(0)], + ['SharedArrayBuffer', () => new SharedArrayBuffer(0)], + ['Uint8Array', () => new Uint8Array()], + ['Uint8Array on empty ArrayBuffer', () => new Uint8Array(new ArrayBuffer(0))], + ['DataView on empty ArrayBuffer', () => new DataView(new ArrayBuffer(0))], + ]; + + for (const [displayName, createBuffer] of emptyBuffers) { + test(`${displayName} binds as an empty blob, not NULL`, (t) => { + using db = new Database(':memory:'); + db.exec('CREATE TABLE test (data BLOB NOT NULL)'); + const buffer = createBuffer(); + // Anonymous binding + { + using stmt = db.prepare('SELECT typeof(?) AS type'); + t.assert.strictEqual(stmt.get(buffer).type, 'blob'); + } + // Named binding (object) + { + using stmt = db.prepare('SELECT typeof($data) AS type'); + t.assert.strictEqual(stmt.get({ '$data': buffer }).type, 'blob'); + } + // Insert into a NOT NULL column and read it back + { + using insert = db.prepare('INSERT INTO test VALUES (?)'); + insert.run(buffer); + using select = db.prepare('SELECT data FROM test'); + t.assert.deepStrictEqual(select.get().data, new Uint8Array()); + } + }); + } +}); diff --git a/test/parallel/test-sqlite-virtual-table.js b/test/parallel/test-sqlite-virtual-table.js index cc520f723444..8e55a0ea4446 100644 --- a/test/parallel/test-sqlite-virtual-table.js +++ b/test/parallel/test-sqlite-virtual-table.js @@ -3,8 +3,10 @@ const { skipIfSQLiteMissing, mustCallAtLeast } = require('../common'); skipIfSQLiteMissing(); const assert = require('node:assert'); +const { join } = require('node:path'); const { Database } = require('node:sqlite'); const { suite, test } = require('node:test'); +const tmpdir = require('../common/tmpdir'); suite('Database.prototype.createModule()', () => { suite('input validation', () => { @@ -986,4 +988,106 @@ suite('Database.prototype.createModule()', () => { assert.strictEqual(callCount, 2); }); }); + + suite('statements prepared while a cursor is closing', () => { + test('finalizes statements prepared from a generator finally', () => { + tmpdir.refresh(); + const filename = join(tmpdir.path, 'vtab-close.db'); + const db = new Database(filename); + db.exec('CREATE TABLE log (m TEXT)'); + let late; + db.createModule('gen', { + columns: [{ name: 'v', type: 'INTEGER' }], + *rows() { + try { + yield [1]; + yield [2]; + } finally { + db.prepare("INSERT INTO log VALUES ('closed')").run(); + late = db.prepare('SELECT COUNT(*) AS c FROM log'); + } + }, + }); + + const it = db.prepare('SELECT v FROM gen').iterate(); + assert.strictEqual(it.next().value.v, 1); + db.close(); + + assert.strictEqual(db.isOpen, false); + assert.throws(() => late.get(), { + code: 'ERR_INVALID_STATE', + message: 'statement has been finalized', + }); + assert.throws(() => late.run(), { + code: 'ERR_INVALID_STATE', + message: 'statement has been finalized', + }); + + const check = new Database(filename); + assert.strictEqual( + check.prepare('SELECT COUNT(*) AS c FROM log').get().c, + 1, + ); + check.close(); + }); + + test('finalizes statements already open when prepare() reenters', () => { + const db = new Database(':memory:'); + const earlier = db.prepare('SELECT 1 AS n'); + const prepared = []; + db.createModule('gen', { + columns: [{ name: 'v', type: 'INTEGER' }], + *rows() { + try { + yield [1]; + } finally { + for (let i = 0; i < 32; i++) { + prepared.push(db.prepare(`SELECT ${i} AS n`)); + } + } + }, + }); + + db.prepare('SELECT v FROM gen').iterate().next(); + db.close(); + + assert.throws(() => earlier.get(), { code: 'ERR_INVALID_STATE' }); + for (const stmt of prepared) { + assert.throws(() => stmt.get(), { code: 'ERR_INVALID_STATE' }); + } + }); + + test('finalizes a statement prepared while deserialize() drops it', () => { + const source = new Database(':memory:'); + source.exec('CREATE TABLE t (a INTEGER)'); + source.exec('INSERT INTO t VALUES (123)'); + const serialized = source.serialize(); + source.close(); + + const db = new Database(':memory:'); + db.exec('CREATE TABLE t (a INTEGER)'); + db.exec('INSERT INTO t VALUES (7)'); + let late; + db.createModule('gen', { + columns: [{ name: 'v', type: 'INTEGER' }], + *rows() { + try { + yield [1]; + } finally { + late = db.prepare('SELECT a FROM t'); + } + }, + }); + db.prepare('SELECT v FROM gen').iterate().next(); + db.deserialize(serialized); + + assert.strictEqual(db.isOpen, true); + assert.throws(() => late.get(), { + code: 'ERR_INVALID_STATE', + message: 'statement has been finalized', + }); + assert.strictEqual(db.prepare('SELECT a FROM t').get().a, 123); + db.close(); + }); + }); }); diff --git a/test/parallel/test-stream-filter.js b/test/parallel/test-stream-filter.js index 0b70c391c88f..53171dce78ef 100644 --- a/test/parallel/test-stream-filter.js +++ b/test/parallel/test-stream-filter.js @@ -174,3 +174,13 @@ const { setTimeout } = require('timers/promises'); // Check that map isn't getting called. stream.filter(() => true); } + +{ + // Already aborted AbortSignal on an empty stream + const stream = Readable.from([]).filter(common.mustNotCall(), { + signal: AbortSignal.abort(), + }); + assert.rejects(stream.toArray(), { + name: 'AbortError', + }).then(common.mustCall()); +} diff --git a/test/parallel/test-stream-finished-protocol-close.js b/test/parallel/test-stream-finished-protocol-close.js new file mode 100644 index 000000000000..468f11c835fd --- /dev/null +++ b/test/parallel/test-stream-finished-protocol-close.js @@ -0,0 +1,93 @@ +'use strict'; + +// Some streams (e.g. Http2Stream) report `closed` or emit 'aborted' at the +// protocol level while their complete body is still buffered. That body is +// still consumable, so eos() must wait for 'end' rather than reporting a +// premature close. + +const common = require('../common'); +const assert = require('assert'); +const { Duplex, Readable, finished } = require('stream'); + +function createStream(Type = Readable) { + const stream = new Type({ read() {}, write() {}, autoDestroy: false }); + stream.aborted = false; + let protocolClosed = false; + Object.defineProperty(stream, 'closed', { + get: () => protocolClosed, + set: (value) => { protocolClosed = value; }, + }); + return stream; +} + +{ + // 'aborted' after the readable ended, with eos() already attached. + const stream = createStream(); + stream.push('body'); + finished(stream, common.mustSucceed(() => { + assert.strictEqual(stream.readableEnded, true); + })); + stream.push(null); + stream.aborted = true; + stream.emit('aborted'); + setImmediate(common.mustCall(() => stream.resume())); +} + +{ + // Already closed when eos() is attached, consumed on a later tick. + const stream = createStream(); + stream.push('body'); + stream.push(null); + stream.closed = true; + let received = ''; + finished(stream, common.mustSucceed(() => { + assert.strictEqual(received, 'body'); + })); + setImmediate(common.mustCall(() => { + stream.on('data', (chunk) => { received += chunk; }); + })); +} + +{ + // 'aborted' before the readable ended is still a premature close. + const stream = createStream(); + stream.push('body'); + finished(stream, common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE'); + })); + stream.aborted = true; + stream.emit('aborted'); +} + +{ + // Closed before the readable ended is still a premature close. + const stream = createStream(); + stream.push('body'); + stream.closed = true; + finished(stream, common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE'); + })); +} + +{ + // Destroyed before the buffered body is consumed is a premature close. + const stream = createStream(); + stream.push('body'); + stream.push(null); + stream.closed = true; + finished(stream, common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE'); + })); + setImmediate(common.mustCall(() => stream.destroy())); +} + +{ + // A Duplex with an unfinished writable side is still a premature close. + const stream = createStream(Duplex); + stream.push('body'); + stream.push(null); + stream.closed = true; + finished(stream, common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE'); + })); +} diff --git a/test/parallel/test-stream-flatMap.js b/test/parallel/test-stream-flatMap.js index a75672e73c8d..c5ef6a571628 100644 --- a/test/parallel/test-stream-flatMap.js +++ b/test/parallel/test-stream-flatMap.js @@ -138,3 +138,13 @@ function oneTo5() { // Check that map isn't getting called. stream.flatMap(() => true); } + +{ + // Already aborted AbortSignal on an empty stream + const stream = Readable.from([]).flatMap(common.mustNotCall(), { + signal: AbortSignal.abort(), + }); + assert.rejects(stream.toArray(), { + name: 'AbortError', + }).then(common.mustCall()); +} diff --git a/test/parallel/test-stream-forEach.js b/test/parallel/test-stream-forEach.js index cccd263adf4c..a5f754312f80 100644 --- a/test/parallel/test-stream-forEach.js +++ b/test/parallel/test-stream-forEach.js @@ -137,3 +137,12 @@ const { once } = require('events'); // Check that map isn't getting called. stream.forEach(() => true); } + +{ + // Already aborted AbortSignal on an empty stream + assert.rejects(Readable.from([]).forEach(common.mustNotCall(), { + signal: AbortSignal.abort(), + }), { + name: 'AbortError', + }).then(common.mustCall()); +} diff --git a/test/parallel/test-stream-iter-abort-pending-read.js b/test/parallel/test-stream-iter-abort-pending-read.js new file mode 100644 index 000000000000..87a051a17df1 --- /dev/null +++ b/test/parallel/test-stream-iter-abort-pending-read.js @@ -0,0 +1,165 @@ +// Flags: --experimental-stream-iter +'use strict'; + +// An abort while a from() source's next() is pending: the pull, pipe or +// consumer rejects at once with the abort reason, and the source is closed +// at once, before its pending next() settles. When that next() settles +// later, nothing more happens: no write, no batch delivered, and no +// unhandled rejection (which would fail the test). + +const common = require('../common'); +const assert = require('assert'); +const { bytes, pipeTo, pull, from } = require('stream/iter'); + +const tick = () => new Promise(setImmediate); + +// An async source whose first next() gives one batch and whose later +// next() calls stay pending until release(). +function pendingSource() { + const log = []; + let reads = 0; + let release = null; + const source = { + [Symbol.asyncIterator]() { return this; }, + next() { + reads++; + log.push('next'); + if (reads === 1) { + return Promise.resolve({ done: false, value: [new Uint8Array([1])] }); + } + return new Promise((resolve) => { + release = () => resolve({ done: false, value: [new Uint8Array([2])] }); + }); + }, + return() { + log.push('return'); + return Promise.resolve({ done: true, value: undefined }); + }, + }; + return { source, log, release: () => release() }; +} + +async function checkPendingRead(start, { stateful = false } = {}) { + const { source, log, release } = pendingSource(); + const ac = new AbortController(); + const reason = new Error('stop'); + const { done, readFirst, extra } = start(from(source), ac.signal, log); + await readFirst; + await tick(); + assert.deepStrictEqual(log, ['next', 'next']); + ac.abort(reason); + await assert.rejects(done, reason); + await tick(); + // Closed while its next() is pending. + assert.deepStrictEqual(log.slice(0, 3), ['next', 'next', 'return']); + if (stateful) assert.ok(log.includes('finally')); + release(); + await tick(); + await tick(); + assert.deepStrictEqual(extra(), []); + assert.strictEqual(log.filter((x) => x === 'return').length, 1); + assert.strictEqual(log.filter((x) => x === 'next').length, 2); +} + +// pull() with a signal, with and without a stateless transform. +async function testPull(transforms) { + await checkPendingRead((normalized, signal) => { + const it = pull(normalized, ...transforms, { signal })[Symbol.asyncIterator](); + const late = []; + const readFirst = it.next(); + const done = readFirst.then(() => it.next()).then((r) => late.push(r)); + return { done, readFirst, extra: () => late }; + }); +} + +// pull() without a signal, stopped with return() while a pull is pending. +async function testPullReturn() { + const { source, log, release } = pendingSource(); + const it = pull(from(source), (c) => c)[Symbol.asyncIterator](); + await it.next(); + const pending = it.next(); + await tick(); + const returned = it.return(); + await assert.rejects(pending, { name: 'AbortError' }); + await returned; + assert.deepStrictEqual(log, ['next', 'next', 'return']); + release(); + await tick(); + await tick(); + assert.deepStrictEqual(log, ['next', 'next', 'return']); +} + +// The same, stopped with throw(). +async function testPullThrow() { + const { source, log, release } = pendingSource(); + const it = pull(from(source), (c) => c)[Symbol.asyncIterator](); + await it.next(); + const pending = it.next(); + await tick(); + const error = new Error('thrown'); + const thrown = it.throw(error); + await assert.rejects(pending, error); + await assert.rejects(thrown, error); + assert.deepStrictEqual(log, ['next', 'next', 'return']); + release(); + await tick(); + await tick(); + assert.deepStrictEqual(log, ['next', 'next', 'return']); +} + +// A stateful transform's generator waits for the source in user code: it +// still sees the read fail at once, and its finally block runs before the +// source's next() settles. +async function testPullStateful() { + await checkPendingRead((normalized, signal, log) => { + const transform = { + async *transform(source) { + try { + for await (const batch of source) yield batch; + } finally { + log.push('finally'); + } + }, + }; + const it = pull(normalized, transform, { signal })[Symbol.asyncIterator](); + const late = []; + const readFirst = it.next(); + const done = readFirst.then(() => it.next()).then((r) => late.push(r)); + return { done, readFirst, extra: () => late }; + }, { stateful: true }); +} + +async function testPipeTo(transforms) { + await checkPendingRead((normalized, signal) => { + const written = []; + let first; + const readFirst = new Promise((resolve) => { first = resolve; }); + const writer = { + write(chunk) { written.push(chunk[0]); first(); }, + end() {}, + fail() {}, + }; + const done = pipeTo(normalized, ...transforms, writer, { signal }); + return { done, readFirst, extra: () => written.slice(1) }; + }); +} + +async function testBytes() { + await checkPendingRead((normalized, signal) => { + // bytes() gives nothing back before the end: the first read is done + // once the source has been read twice. + const done = bytes(normalized, { signal }); + return { done, readFirst: tick(), extra: () => [] }; + }); +} + +(async () => { + await testPull([]); + await testPull([(c) => c]); + await testPullReturn(); + await testPullThrow(); + await testPullStateful(); + await testPipeTo([]); + await testPipeTo([(c) => c]); + await testBytes(); +})().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-broadcast-basic.js b/test/parallel/test-stream-iter-broadcast-basic.js index c59689c2d12b..7b2187f94e32 100644 --- a/test/parallel/test-stream-iter-broadcast-basic.js +++ b/test/parallel/test-stream-iter-broadcast-basic.js @@ -392,8 +392,27 @@ async function testOverlappingNextKeepsEarlierRead() { assert.strictEqual(bc.consumerCount, 0); } +async function testOverlappingNextResolvedInOrder() { + const { writer, broadcast: bc } = broadcast(); + const it = bc.push()[Symbol.asyncIterator](); + const reads = [it.next(), it.next(), it.next(), it.next(), it.next()]; + + for (const value of ['a', 'b', 'c']) await writer.write(value); + const error = new Error('failed'); + writer.fail(error); + + for (const [i, value] of ['a', 'b', 'c'].entries()) { + const result = await reads[i]; + assert.strictEqual(result.done, false); + assert.strictEqual(Buffer.concat(result.value).toString(), value); + } + await assert.rejects(reads[3], error); + await assert.rejects(reads[4], error); +} + Promise.all([ testBasicBroadcast(), + testOverlappingNextResolvedInOrder(), testMultipleWrites(), testConsumerCount(), testWriteSync(), diff --git a/test/parallel/test-stream-iter-broadcast-from.js b/test/parallel/test-stream-iter-broadcast-from.js index 8bc2abde2e17..1d1049083d87 100644 --- a/test/parallel/test-stream-iter-broadcast-from.js +++ b/test/parallel/test-stream-iter-broadcast-from.js @@ -159,6 +159,67 @@ async function testBroadcastFromCancelWhileBlocked() { assert.strictEqual(sourceReturned, true); } +// A sync source is written as the broadcast has room, including values +// normalized asynchronously, and its error reaches the consumers after the +// data before it. Cancelling the broadcast while the pump waits for room +// closes the source. +async function testBroadcastFromSyncSource() { + const reason = new Error('sync source boom'); + function* source() { + yield [Uint8Array.of(1)]; + yield Promise.resolve(Uint8Array.of(2)); + yield 'c'; + yield [Uint8Array.of(4)]; + throw reason; + } + const { broadcast: bc } = Broadcast.from(source()); + const read = async (consumer) => { + const values = []; + try { + for await (const batch of consumer) values.push(...batch.map((c) => c[0])); + } catch (error) { + values.push(error); + } + return values; + }; + const results = await Promise.all([read(bc.push()), read(bc.push())]); + for (const values of results) { + assert.deepStrictEqual(values, [1, 2, 99, 4, reason]); + } + + let closed = false; + function* endless() { + try { + for (;;) yield [new Uint8Array(1024)]; + } finally { + closed = true; + } + } + const { broadcast: blocked } = Broadcast.from(endless(), { budget: 4096 }); + const consumer = blocked.push()[Symbol.asyncIterator](); + await consumer.next(); + await setImmediate(); + assert.strictEqual(closed, false); + blocked.cancel(); + await setImmediate(); + assert.strictEqual(closed, true); + assert.strictEqual((await consumer.next()).done, true); +} + +// With a 'drop-newest' policy, a sync source is still read one batch at a +// time while consumers read. +async function testBroadcastFromSyncSourceDropNewest() { + function* source() { + for (let i = 0; i < 8; i++) yield [Uint8Array.of(i)]; + } + const { broadcast: bc } = Broadcast.from(source(), { + budget: 2, backpressure: 'drop-newest', + }); + const values = []; + for await (const batch of bc.push()) values.push(...batch.map((c) => c[0])); + assert.deepStrictEqual(values, [0, 1, 2, 3, 4, 5, 6, 7]); +} + // ============================================================================= // Source error propagation via Broadcast.from() // ============================================================================= @@ -229,6 +290,8 @@ Promise.all([ testAbortSignal(), testAlreadyAbortedSignal(), testBroadcastFromCancelWhileBlocked(), + testBroadcastFromSyncSource(), + testBroadcastFromSyncSourceDropNewest(), testBroadcastFromSourceError(), testBroadcastProtocolReturnsBroadcast(), testBroadcastProtocolReturnsNull(), diff --git a/test/parallel/test-stream-iter-broadcast-waiter-cleanup.js b/test/parallel/test-stream-iter-broadcast-waiter-cleanup.js index 4e0f6dd4d47a..3bb1c6443245 100644 --- a/test/parallel/test-stream-iter-broadcast-waiter-cleanup.js +++ b/test/parallel/test-stream-iter-broadcast-waiter-cleanup.js @@ -31,4 +31,55 @@ async function testDetachedWaitersAreReleased() { shared.cancel(); } -testDetachedWaitersAreReleased().then(common.mustCall()); +// Consumers waiting for writes are notified once per write, across many +// writes: some wait with one next() at a time, one queues several next() +// calls, and one detaches while it is waiting. Every remaining consumer +// gets every chunk, in order. +async function testWaitersAcrossWrites() { + // A 4-byte budget, so that the writer also waits for the consumers. + const { writer, broadcast: shared } = broadcast({ budget: 4 }); + const n = 200; + const readAll = async (iterator) => { + const seen = []; + for (;;) { + const { done, value } = await iterator.next(); + if (done) return seen; + for (const chunk of value) seen.push(chunk[0]); + } + }; + const readQueued = async (iterator) => { + const seen = []; + for (;;) { + const results = await Promise.all( + [iterator.next(), iterator.next(), iterator.next()]); + for (const { done, value } of results) { + if (done) return seen; + for (const chunk of value) seen.push(chunk[0]); + } + } + }; + const a = readAll(shared.push()[Symbol.asyncIterator]()); + const b = readAll(shared.push()[Symbol.asyncIterator]()); + const c = readQueued(shared.push()[Symbol.asyncIterator]()); + for (let i = 0; i < n; i++) { + if (i === n / 2) { + // Joins at the current position, waits, and detaches while waiting. + const detaching = shared.push()[Symbol.asyncIterator](); + const pending = detaching.next(); + await detaching.return(); + await pending; + } + await writer.write(new Uint8Array([i % 256])); + if (i % 7 === 0) await new Promise(setImmediate); + } + await writer.end(); + const expected = Array.from({ length: n }, (_, i) => i % 256); + assert.deepStrictEqual(await a, expected); + assert.deepStrictEqual(await b, expected); + assert.deepStrictEqual(await c, expected); + assert.strictEqual(shared.consumerCount, 0); +} + +testDetachedWaitersAreReleased() + .then(testWaitersAcrossWrites) + .then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-consumers-bytes.js b/test/parallel/test-stream-iter-consumers-bytes.js index 531917eb9734..5bf06a19ea89 100644 --- a/test/parallel/test-stream-iter-consumers-bytes.js +++ b/test/parallel/test-stream-iter-consumers-bytes.js @@ -3,6 +3,7 @@ const common = require('../common'); const assert = require('assert'); +const { getEventListeners } = require('events'); const { from, fromSync, @@ -272,7 +273,27 @@ async function testTextStringSource() { assert.strictEqual(result, 'direct-string'); } +// With a signal, exceeding the limit closes the source, rejects with the +// limit error, and leaves no listener on the signal. +async function testBytesSignalAndLimit() { + const ac = new AbortController(); + let closed = false; + async function* source() { + try { + for (;;) yield [new Uint8Array(8)]; + } finally { + closed = true; + } + } + await assert.rejects( + bytes(source(), { signal: ac.signal, limit: 20 }), + { code: 'ERR_OUT_OF_RANGE' }); + assert.strictEqual(closed, true); + assert.strictEqual(getEventListeners(ac.signal, 'abort').length, 0); +} + Promise.all([ + testBytesSignalAndLimit(), testBytesSyncBasic(), testBytesSyncLimit(), testBytesAsync(), diff --git a/test/parallel/test-stream-iter-consumers-merge.js b/test/parallel/test-stream-iter-consumers-merge.js index 5cbe773ac082..9e69d5f7fcb9 100644 --- a/test/parallel/test-stream-iter-consumers-merge.js +++ b/test/parallel/test-stream-iter-consumers-merge.js @@ -461,7 +461,79 @@ async function testMergeMultiSourceBreakWithCleanupError() { ); } +// merge() of a single source behaves as an async generator reading it: +// an abort rejects the pending read, closes the source and ends the +// iteration; an abort before the first read does not open the source; +// return() is queued behind pending reads. +async function testMergeSingleSourceProtocol() { + const log = []; + function source(name, values, { hang = false } = {}) { + let i = 0; + return { + [Symbol.asyncIterator]() { + log.push(`${name} iterator`); + return { + next() { + log.push(`${name} next ${i}`); + if (hang && i === values.length) return new Promise(() => {}); + return Promise.resolve(i < values.length ? + { done: false, value: values[i++] } : { done: true }); + }, + return() { + log.push(`${name} return`); + return Promise.resolve({ done: true }); + }, + }; + }, + }; + } + + async function settle(label, promise) { + try { + const result = await promise; + log.push(`${label}: ${result.done ? 'done' : result.value[0][0]}`); + } catch (error) { + log.push(`${label}: ${error.name}`); + } + } + const chunk = (n) => [Uint8Array.of(n)]; + + const aborted = AbortSignal.abort(); + let it = merge(source('a', [chunk(1)]), { signal: aborted })[ + Symbol.asyncIterator](); + await settle('a 1', it.next()); + await settle('a 2', it.next()); + + const ac = new AbortController(); + it = merge(source('b', [chunk(1)], { hang: true }), { signal: ac.signal })[ + Symbol.asyncIterator](); + await settle('b 1', it.next()); + const pending = it.next(); + await setImmediate(); + ac.abort(); + await settle('b 2', pending); + await settle('b 3', it.next()); + + it = merge(source('c', [chunk(1), 'x', chunk(3)]))[Symbol.asyncIterator](); + const results = [it.next(), it.next(), it.return(), it.next()]; + for (let i = 0; i < results.length; i++) await settle(`c ${i}`, results[i]); + + it = merge(source('d', [chunk(1)]))[Symbol.asyncIterator](); + await settle('d return', it.return()); + await assert.rejects(it.throw(new Error('thrown')), { message: 'thrown' }); + + assert.deepStrictEqual(log, [ + 'a 1: AbortError', 'a 2: done', + 'b iterator', 'b next 0', 'b 1: 1', 'b next 1', 'b return', + 'b 2: AbortError', 'b 3: done', + 'c iterator', 'c next 0', 'c next 1', 'c 0: 1', 'c 1: 120', 'c return', + 'c 2: done', 'c 3: done', + 'd return: done', + ]); +} + Promise.all([ + testMergeSingleSourceProtocol(), testMergeTwoSources(), testMergeSingleSource(), testMergeEmpty(), diff --git a/test/parallel/test-stream-iter-from-async.js b/test/parallel/test-stream-iter-from-async.js index 1b58fd6603ca..a6bd4a486921 100644 --- a/test/parallel/test-stream-iter-from-async.js +++ b/test/parallel/test-stream-iter-from-async.js @@ -123,7 +123,7 @@ async function testFromDoesNotHoldBackNestedAsyncIterable() { } const iterator = from(source())[Symbol.asyncIterator](); - assert.deepStrictEqual(await iterator.next(), + assert.deepStrictEqual({ ...await iterator.next() }, { done: false, value: [new Uint8Array([1])] }); resolve(); const rest = []; @@ -529,7 +529,441 @@ async function testFromFunctionWithProtocols() { assert.throws(() => from(() => {}), { code: 'ERR_INVALID_ARG_TYPE' }); } +// from() reads async sources like an async generator looping over them with +// for await. The tests below check the parts of that behavior that are +// observable from the source: when it is read and closed. + +// Creates an async iterable source of `values`, recording calls in `log`. +function createLoggedSource(log, values, { failAt = -1, returnError } = {}) { + let i = 0; + return { + [Symbol.asyncIterator]() { + log.push('iterator'); + return { + async next() { + log.push(`next ${i}`); + if (i === failAt) { + i++; + throw new Error('source failed'); + } + if (i >= values.length) return { done: true, value: undefined }; + return { done: false, value: values[i++] }; + }, + async return() { + log.push('return'); + if (returnError !== undefined) throw returnError; + return { done: true, value: undefined }; + }, + }; + }, + }; +} + +async function settle(log, label, promise) { + try { + const result = await promise; + log.push(`${label}: ${result.done ? 'done' : result.value.length}`); + } catch (error) { + const reason = error.name === 'AbortError' ? error.name : + error.code ?? error.message; + log.push(`${label}: ${reason}`); + } +} + +async function testFromQueuesConcurrentNext() { + const log = []; + const iterator = from(createLoggedSource(log, [ + Uint8Array.of(1), Uint8Array.of(2), + ]))[Symbol.asyncIterator](); + const results = [iterator.next(), iterator.next(), iterator.next()]; + for (let i = 0; i < results.length; i++) { + await settle(log, `result ${i}`, results[i]); + } + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result 0: 1', 'next 2', 'result 1: 1', + 'result 2: done', + ]); +} + +async function testFromSplitsOversizedBatches() { + const log = []; + const batch = Array.from({ length: 300 }, () => new Uint8Array(1)); + const iterator = from(createLoggedSource(log, [batch, [], [batch[0]]]))[ + Symbol.asyncIterator](); + for (let i = 0; i < 5; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result 0: 128', 'result 1: 128', 'result 2: 44', + 'next 1', 'next 2', 'result 3: 1', 'next 3', 'result 4: done', + ]); +} + +async function testFromSourceErrorDoesNotCloseSource() { + const log = []; + const iterator = from(createLoggedSource(log, [Uint8Array.of(1)], { + failAt: 1, + }))[Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result 0: 1', 'next 1', 'result 1: source failed', + 'result 2: done', + ]); +} + +async function testFromNormalizationErrorClosesSource() { + // A value that cannot be normalized. + let log = []; + let iterator = from(createLoggedSource(log, [Uint8Array.of(1), 42]))[ + Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result 0: 1', 'next 1', 'return', + 'result 1: ERR_INVALID_ARG_TYPE', 'result 2: done', + ]); + + // A nested async iterable that fails. + async function* nested() { + yield Uint8Array.of(2); + throw new Error('nested failed'); + } + log = []; + iterator = from(createLoggedSource(log, [nested()]))[Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result 0: 1', 'return', 'result 1: nested failed', + 'result 2: done', + ]); +} + +async function testFromReturnAndThrowBeforeStart() { + const log = []; + let iterator = from(createLoggedSource(log, [Uint8Array.of(1)]))[ + Symbol.asyncIterator](); + assert.deepStrictEqual({ ...await iterator.return('v') }, + { done: true, value: 'v' }); + await settle(log, 'after return', iterator.next()); + iterator = from(createLoggedSource(log, [Uint8Array.of(1)]))[ + Symbol.asyncIterator](); + await settle(log, 'throw', iterator.throw(new Error('thrown'))); + await settle(log, 'after throw', iterator.next()); + // The source is never read. + assert.deepStrictEqual(log, [ + 'after return: done', 'throw: thrown', 'after throw: done', + ]); +} + +async function testFromReturnAndThrowCloseSource() { + const returnError = new Error('return failed'); + for (const method of ['return', 'throw']) { + const log = []; + let nestedClosed = false; + async function* nested() { + try { + yield Uint8Array.of(1); + yield Uint8Array.of(2); + } finally { + nestedClosed = true; + } + } + const iterator = from(createLoggedSource(log, [nested()], { + returnError, + }))[Symbol.asyncIterator](); + await settle(log, 'result', iterator.next()); + await settle(log, method, iterator[method](new Error('thrown'))); + await settle(log, 'after', iterator.next()); + assert.strictEqual(nestedClosed, true); + // return() propagates errors from closing the source; throw() keeps its + // own error. + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result: 1', 'return', + method === 'return' ? 'return: return failed' : 'throw: thrown', + 'after: done', + ]); + } +} + +// Creates a sync iterable source of `values`, recording calls in `log`. +function createLoggedSyncSource(log, values, { failAt = -1, returnError } = {}) { + let i = 0; + return { + [Symbol.iterator]() { + log.push('iterator'); + return { + next() { + log.push(`next ${i}`); + if (i === failAt) { + i++; + throw new Error('source failed'); + } + if (i >= values.length) return { done: true, value: undefined }; + return { done: false, value: values[i++] }; + }, + return() { + log.push('return'); + if (returnError !== undefined) throw returnError; + return { done: true, value: undefined }; + }, + }; + }, + }; +} + +async function testFromSyncSourceBatching() { + // Single chunks are collected into batches of up to 128 chunks; any other + // value is yielded after the chunks collected before it. + const log = []; + const chunks = Array.from({ length: 130 }, () => new Uint8Array(1)); + const iterator = from(createLoggedSyncSource(log, [ + ...chunks, [Uint8Array.of(1), Uint8Array.of(2)], Uint8Array.of(3), 'ab', + ]))[Symbol.asyncIterator](); + for (let i = 0; i < 6; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', ...Array.from({ length: 128 }, (_, i) => `next ${i}`), + 'result 0: 128', 'next 128', 'next 129', 'next 130', 'result 1: 2', + 'result 2: 2', 'next 131', 'next 132', 'result 3: 1', 'result 4: 1', + 'next 133', 'result 5: done', + ]); +} + +async function testFromSyncSourceLargeAndEmptyBatches() { + // Batches of more than 128 chunks are split, after the chunks collected + // before them; empty batches only flush collected chunks. Returning while + // a batch is split closes the source, returning after its last batch + // does not. + const large = Array.from({ length: 300 }, () => new Uint8Array(1)); + let log = []; + let iterator = from(createLoggedSyncSource(log, [ + Uint8Array.of(1), [], [], large, Uint8Array.of(2), + ]))[Symbol.asyncIterator](); + for (let i = 0; i < 6; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result 0: 1', 'next 2', 'next 3', + 'result 1: 128', 'result 2: 128', 'result 3: 44', 'next 4', 'next 5', + 'result 4: 1', 'result 5: done', + ]); + + log = []; + iterator = from(createLoggedSyncSource(log, [large]))[ + Symbol.asyncIterator](); + await settle(log, 'result', iterator.next()); + await settle(log, 'return', iterator.return()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result: 128', 'return', 'return: done', + ]); + + // A result whose value getter throws ends the iteration without closing + // the source. + log = []; + const source = { + [Symbol.iterator]() { + return { + next() { + log.push('next'); + return { done: false, get value() { throw new Error('getter'); } }; + }, + return() { + log.push('return'); + return { done: true }; + }, + }; + }, + }; + iterator = from(source)[Symbol.asyncIterator](); + await settle(log, 'result 0', iterator.next()); + await settle(log, 'result 1', iterator.next()); + assert.deepStrictEqual(log, ['next', 'result 0: getter', 'result 1: done']); + + // The next() method of the source's iterator is read once, as for...of + // reads it. + let reads = 0; + let count = 0; + const accessorSource = { + [Symbol.iterator]() { + return { + get next() { + reads++; + return () => (count < 3 ? + { done: false, value: [Uint8Array.of(count++)] } : + { done: true, value: undefined }); + }, + }; + }, + }; + const chunks = []; + for await (const batch of from(accessorSource)) chunks.push(...batch); + assert.deepStrictEqual(chunks, [ + Uint8Array.of(0), Uint8Array.of(1), Uint8Array.of(2), + ]); + assert.strictEqual(reads, 1); +} + +async function testFromSyncSourceErrors() { + // An error from the source does not close it. + let log = []; + let iterator = from(createLoggedSyncSource(log, [[Uint8Array.of(1)]], { + failAt: 1, + }))[Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) await settle(log, `result ${i}`, iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result 0: 1', 'next 1', 'result 1: source failed', + 'result 2: done', + ]); + + // An error processing a value closes it, also after flushing the chunks + // collected before the value, and when normalizing a promise fails. + for (const value of [42, Promise.reject(new Error('rejected'))]) { + log = []; + iterator = from(createLoggedSyncSource(log, [Uint8Array.of(1), value]))[ + Symbol.asyncIterator](); + for (let i = 0; i < 3; i++) { + await settle(log, `result ${i}`, iterator.next()); + } + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result 0: 1', 'return', + `result 1: ${value === 42 ? 'ERR_INVALID_ARG_TYPE' : 'rejected'}`, + 'result 2: done', + ]); + } +} + +async function testFromSyncSourceReturnAndThrow() { + const returnError = new Error('return failed'); + for (const method of ['return', 'throw']) { + // While reading the source, it is closed: return() propagates errors + // from closing it, throw() keeps its own error. + let log = []; + let iterator = from(createLoggedSyncSource(log, [ + [Uint8Array.of(1)], [Uint8Array.of(2)], + ], { returnError }))[Symbol.asyncIterator](); + await settle(log, 'result', iterator.next()); + await settle(log, method, iterator[method](new Error('thrown'))); + await settle(log, 'after', iterator.next()); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'result: 1', 'return', + method === 'return' ? 'return: return failed' : 'throw: thrown', + 'after: done', + ]); + + // Once the source has ended, it is not closed. + log = []; + iterator = from(createLoggedSyncSource(log, [Uint8Array.of(1)]))[ + Symbol.asyncIterator](); + await settle(log, 'result', iterator.next()); + await settle(log, method, iterator[method](new Error('thrown'))); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result: 1', + method === 'return' ? 'return: done' : 'throw: thrown', + ]); + } +} + +async function testFromSyncSourceCallOrder() { + // A next() made synchronously after another that finished synchronously + // runs at once, before a return() made after it. + let log = []; + let iterator = from(createLoggedSyncSource(log, [ + [Uint8Array.of(1)], 'a', [Uint8Array.of(2)], + ]))[Symbol.asyncIterator](); + let results = [iterator.next(), iterator.next(), iterator.return()]; + for (let i = 0; i < results.length; i++) { + await settle(log, `result ${i}`, results[i]); + } + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result 0: 1', 'result 1: 1', 'return', + 'result 2: done', + ]); + + // A call made while a value is normalized asynchronously is queued + // behind it, and so a return() made then cancels it. + log = []; + iterator = from(createLoggedSyncSource(log, [ + [Uint8Array.of(1)], Promise.resolve(Uint8Array.of(2)), [Uint8Array.of(3)], + ]))[Symbol.asyncIterator](); + results = [iterator.next(), iterator.next(), iterator.next(), + iterator.return()]; + for (let i = 0; i < results.length; i++) { + await settle(log, `result ${i}`, results[i]); + } + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'next 1', 'result 0: 1', 'return', + 'result 1: AbortError', 'result 2: done', 'result 3: done', + ]); + + // A next() made synchronously after another reads the source at once. + log = []; + iterator = from(createLoggedSyncSource(log, [ + [Uint8Array.of(1)], [Uint8Array.of(2)], + ]))[Symbol.asyncIterator](); + const first = iterator.next(); + log.push('first called'); + const second = iterator.next(); + log.push('second called'); + await settle(log, 'first', first); + await settle(log, 'second', second); + assert.deepStrictEqual(log, [ + 'iterator', 'next 0', 'first called', 'next 1', 'second called', + 'first: 1', 'second: 1', + ]); +} + +// from() returns its own results unchanged: they already yield normalized +// batches, and normalizing them again would add a layer to every read. +async function testFromReturnsItsOwnResults() { + async function* asyncSource() { + yield 'a'; + yield [new Uint8Array([98])]; + } + + function* syncSource() { + yield 'c'; + yield new Uint8Array([100]); + } + const inputs = [ + [asyncSource(), 'ab'], + [syncSource(), 'cd'], + ['ef', 'ef'], + [[new Uint8Array([103]), new Uint8Array([104])], 'gh'], + [[], ''], + [{ [Symbol.for('Stream.toAsyncStreamable')]() { return 'ij'; } }, 'ij'], + ]; + for (const [input, expected] of inputs) { + const normalized = from(input); + assert.strictEqual(from(normalized), normalized); + assert.strictEqual(await text(from(from(normalized))), expected); + } +} + +// from() of a value needing no normalization reads like an async generator +// yielding its batches: each iteration starts over, return() and throw() +// end it, and arrays are yielded in bounded batches. +async function testFromValueIteration() { + const chunk = new Uint8Array([1]); + const source = from(chunk); + for (let i = 0; i < 2; i++) { + const batches = await Array.fromAsync(source); + assert.deepStrictEqual(batches, [[chunk]]); + } + + let iterator = source[Symbol.asyncIterator](); + assert.deepStrictEqual({ ...await iterator.return(5) }, + { done: true, value: 5 }); + assert.strictEqual((await iterator.next()).done, true); + + iterator = source[Symbol.asyncIterator](); + assert.deepStrictEqual((await iterator.next()).value, [chunk]); + const error = new Error('thrown'); + await assert.rejects(iterator.throw(error), error); + assert.strictEqual((await iterator.next()).done, true); + + const chunks = Array.from({ length: 300 }, () => chunk); + const lengths = (await Array.fromAsync(from(chunks))) + .map((batch) => batch.length); + assert.deepStrictEqual(lengths, [128, 128, 44]); + assert.deepStrictEqual(await Array.fromAsync(from([])), []); +} + Promise.all([ + testFromValueIteration(), + testFromReturnsItsOwnResults(), testFromString(), testFromAsyncGenerator(), testFromAsyncIteratorResultShapes(), @@ -563,4 +997,15 @@ Promise.all([ testConsumerAbortClosesPendingNestedIterator(), testFromCancellationHandlesCleanupRejection(), testFromDataView(), + testFromQueuesConcurrentNext(), + testFromSplitsOversizedBatches(), + testFromSourceErrorDoesNotCloseSource(), + testFromNormalizationErrorClosesSource(), + testFromReturnAndThrowBeforeStart(), + testFromReturnAndThrowCloseSource(), + testFromSyncSourceBatching(), + testFromSyncSourceLargeAndEmptyBatches(), + testFromSyncSourceErrors(), + testFromSyncSourceReturnAndThrow(), + testFromSyncSourceCallOrder(), ]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-from-sync.js b/test/parallel/test-stream-iter-from-sync.js index 133597914c45..f6b2b0a5f84a 100644 --- a/test/parallel/test-stream-iter-from-sync.js +++ b/test/parallel/test-stream-iter-from-sync.js @@ -255,7 +255,90 @@ function testFromSyncFunctionWithToStreamable() { assert.throws(() => fromSync(() => {}), { code: 'ERR_INVALID_ARG_TYPE' }); } +// The iterators of fromSync() behave as generators do: values are batched +// and normalized, iterables can be iterated again, and return(), throw() +// and errors normalizing a value close the source as for...of does. +function testFromSyncIteratorProtocol() { + function loggedSource(log, values) { + return { + [Symbol.iterator]() { + let i = 0; + log.push('iterator'); + return { + next() { + log.push(`next ${i}`); + return i < values.length ? + { done: false, value: values[i++] } : + { done: true, value: undefined }; + }, + return() { + log.push('return'); + return { done: true, value: undefined }; + }, + }; + }, + }; + } + const lengths = (iterable) => Array.from(iterable, (batch) => batch.length); + + const chunks = Array.from({ length: 130 }, () => new Uint8Array(1)); + let log = []; + const source = fromSync(loggedSource(log, [ + ...chunks, ['ab', ['cd']], Uint8Array.of(1), [], + ])); + assert.deepStrictEqual(lengths(source), [128, 2, 2, 1]); + assert.strictEqual(log.at(-1), 'next 133'); + assert.deepStrictEqual(lengths(source), [128, 2, 2, 1]); + + // Values that need no normalization. + for (const value of ['x', Uint8Array.of(1), [Uint8Array.of(1)], []]) { + const iterable = fromSync(value); + assert.deepStrictEqual(lengths(iterable), lengths(iterable)); + const iterator = iterable[Symbol.iterator](); + assert.strictEqual(iterator[Symbol.iterator](), iterator); + assert.deepStrictEqual({ ...iterator.return('r') }, + { done: true, value: 'r' }); + assert.strictEqual(iterator.next().done, true); + assert.throws(() => iterable[Symbol.iterator]().throw(new Error('t')), + { message: 't' }); + } + assert.deepStrictEqual(lengths(fromSync(new Array(300).fill(chunks[0]))), + [128, 128, 44]); + + // return() while reading the source, or a value, closes the source; + // before reading it, or after it ended, does not. + for (const values of [[[Uint8Array.of(1)], [Uint8Array.of(2)]], + [new Array(200).fill('a')]]) { + log = []; + const iterator = fromSync(loggedSource(log, values))[Symbol.iterator](); + iterator.next(); + assert.deepStrictEqual({ ...iterator.return() }, + { done: true, value: undefined }); + assert.deepStrictEqual(log, ['iterator', 'next 0', 'return']); + assert.strictEqual(iterator.next().done, true); + } + log = []; + const unstarted = fromSync(loggedSource(log, ['a']))[Symbol.iterator](); + unstarted.return(); + assert.deepStrictEqual(log, []); + + // throw() and an error normalizing a value close the source, and the + // error is thrown. + log = []; + const thrown = fromSync(loggedSource(log, ['a', 'b']))[Symbol.iterator](); + thrown.next(); + assert.throws(() => thrown.throw(new Error('thrown')), { message: 'thrown' }); + assert.deepStrictEqual(log, ['iterator', 'next 0', 'return']); + log = []; + const invalid = fromSync(loggedSource(log, ['a', 42]))[Symbol.iterator](); + invalid.next(); + assert.throws(() => invalid.next(), { code: 'ERR_INVALID_ARG_TYPE' }); + assert.deepStrictEqual(log, ['iterator', 'next 0', 'next 1', 'return']); + assert.strictEqual(invalid.next().done, true); +} + Promise.all([ + testFromSyncIteratorProtocol(), testFromSyncString(), testFromSyncUint8Array(), testFromSyncArrayBuffer(), diff --git a/test/parallel/test-stream-iter-iterator-result.js b/test/parallel/test-stream-iter-iterator-result.js index 4f29bf05534a..96cbdc6ec18d 100644 --- a/test/parallel/test-stream-iter-iterator-result.js +++ b/test/parallel/test-stream-iter-iterator-result.js @@ -3,8 +3,6 @@ // Iterator results created by the stream/iter iterators themselves do not // inherit from Object.prototype, so prototype pollution cannot affect them. -// (Iterators implemented as async generators, such as the one returned by -// pull(), return ordinary iterator results created by the engine.) const common = require('../common'); const assert = require('assert'); @@ -12,6 +10,7 @@ const { inspect } = require('util'); const { broadcast, from, + pull, push, share, shareSync, @@ -33,6 +32,14 @@ async function testAsyncIterators() { return readable; }, 'share()': () => share(from('a')).pull(), + 'pull()': () => pull(from('a')), + 'pull() with a signal': () => pull(from('a'), { + signal: new AbortController().signal, + }), + 'pull() with a transform': () => pull(from('a'), (chunks) => chunks), + 'from() of an async iterable': () => from((async function*() { + yield 'a'; + })()), 'broadcast()': () => { const { writer, broadcast: bc } = broadcast(); const consumer = bc.push(); diff --git a/test/parallel/test-stream-iter-pipeto-signal.js b/test/parallel/test-stream-iter-pipeto-signal.js index be04c8c635df..57fa9fed530e 100644 --- a/test/parallel/test-stream-iter-pipeto-signal.js +++ b/test/parallel/test-stream-iter-pipeto-signal.js @@ -7,7 +7,8 @@ const common = require('../common'); const assert = require('assert'); const { setTimeout } = require('timers/promises'); -const { pipeTo, from } = require('stream/iter'); +const { getEventListeners } = require('events'); +const { bytes, pipeTo, pull, from } = require('stream/iter'); async function testPipeToPreAbortedSignalFailsWriter() { const reason = new Error('already aborted'); @@ -160,6 +161,139 @@ async function testPipeToLiveSignalWithTransformsCompletes() { assert.ok(written.length > 0); } +async function testSignalAbortedWhileReadingSource() { + // The signal can abort while the source is producing a value; the read + // must still reject with the abort reason, and the source be closed, even + // if the value never comes. + const identity = (chunks) => chunks; + for (const consume of [ + (source, signal) => pipeTo(source, { write() {} }, { signal }), + (source, signal) => pipeTo(source, identity, { write() {} }, { signal }), + (source, signal) => bytes(source, { signal }), + (source, signal) => bytes(pull(source, { signal })), + (source, signal) => bytes(pull(source, identity, { signal })), + ]) { + const ac = new AbortController(); + const reason = new Error('aborted while reading'); + let closed = false; + const source = { + [Symbol.asyncIterator]() { + return { + next() { + ac.abort(reason); + return new Promise(() => {}); + }, + async return() { + closed = true; + return { done: true }; + }, + }; + }, + }; + await assert.rejects(consume(source, ac.signal), reason); + assert.strictEqual(closed, true); + } +} + +// write(), writev() and end() are all passed the same options object. +async function testWriteOptionsShared() { + const ac = new AbortController(); + const seen = []; + const writer = { + async write(chunk, options) { seen.push(options); }, + async writev(chunks, options) { seen.push(options); }, + async end(options) { seen.push(options); }, + }; + async function* source() { + yield [new Uint8Array([1])]; + yield [new Uint8Array([2]), new Uint8Array([3])]; + yield [new Uint8Array([4])]; + } + await pipeTo(source(), writer, { signal: ac.signal }); + assert.strictEqual(seen.length, 4); + assert.strictEqual(new Set(seen).size, 1); + assert.strictEqual(seen[0].signal, ac.signal); +} + +// The signal aborting while a chunk is written synchronously stops the pipe: +// no other chunk is written, the source is closed, and the pipe rejects with +// the abort reason. +async function testAbortDuringWriteSync() { + for (const sync of [true, false]) { + const ac = new AbortController(); + const reason = new Error('abort in writeSync'); + const written = []; + let closed = false; + function* syncSource() { + try { + for (let i = 0; i < 5; i++) yield [new Uint8Array([i])]; + } finally { + closed = true; + } + } + + async function* asyncSource() { + try { + for (let i = 0; i < 5; i++) yield [new Uint8Array([i])]; + } finally { + closed = true; + } + } + const writer = { + write: common.mustNotCall(), + writeSync(chunk) { + written.push(chunk[0]); + if (chunk[0] === 1) ac.abort(reason); + return true; + }, + fail: common.mustCall((error) => assert.strictEqual(error, reason)), + }; + await assert.rejects( + pipeTo(sync ? syncSource() : asyncSource(), writer, + { signal: ac.signal }), + reason); + assert.deepStrictEqual(written, [0, 1]); + await setTimeout(1); + assert.strictEqual(closed, true); + } +} + +// The signal aborting while a write is pending rejects the pipe at once, +// even if the write never completes. +async function testAbortWhileWritePending() { + const ac = new AbortController(); + const reason = new Error('abort while writing'); + const writer = { + write() { + ac.abort(reason); + return new Promise(() => {}); + }, + }; + await assert.rejects(pipeTo(from('a'), writer, { signal: ac.signal }), + reason); +} + +async function testSignalListenersRemoved() { + // No abort listener is left on the signal once reading completes, fails + // or is aborted. + const ac = new AbortController(); + await pipeTo(from('abc'), { write() {} }, { signal: ac.signal }); + await bytes(from('abc'), { signal: ac.signal }); + await assert.rejects(bytes((async function*() { + yield 'a'; + throw new Error('source failed'); + })(), { signal: ac.signal }), /source failed/); + assert.strictEqual(getEventListeners(ac.signal, 'abort').length, 0); + + const aborting = new AbortController(); + await assert.rejects(bytes((async function*() { + yield 'a'; + aborting.abort(); + yield 'b'; + })(), { signal: aborting.signal }), { name: 'AbortError' }); + assert.strictEqual(getEventListeners(aborting.signal, 'abort').length, 0); +} + Promise.all([ testPipeToPreAbortedSignalFailsWriter(), testPipeToPreAbortedSignalPreventFail(), @@ -168,4 +302,9 @@ Promise.all([ testPipeToLiveSignalWithTransforms(), testPipeToLiveSignalCompletes(), testPipeToLiveSignalWithTransformsCompletes(), + testSignalAbortedWhileReadingSource(), + testSignalListenersRemoved(), + testWriteOptionsShared(), + testAbortDuringWriteSync(), + testAbortWhileWritePending(), ]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-pipeto.js b/test/parallel/test-stream-iter-pipeto.js index ed1614552f93..c5dc0a3f1339 100644 --- a/test/parallel/test-stream-iter-pipeto.js +++ b/test/parallel/test-stream-iter-pipeto.js @@ -345,6 +345,109 @@ async function testPipeToSyncIterableAsyncValue() { assert.strictEqual(result, 'ab'); } +// pipeTo() reads sync iterables synchronously when it can. An error writing +// a batch must still close the source, ignoring an error closing it, and an +// error reading the source must not close it. +async function testPipeToSyncIterableWriteError() { + for (const returnThrows of [false, true]) { + const error = new Error('write'); + let closed = false; + const source = { + [Symbol.iterator]() { + let i = 0; + return { + next() { + return { done: false, value: [new Uint8Array([i++])] }; + }, + return() { + closed = true; + if (returnThrows) throw new Error('return'); + return { done: true }; + }, + }; + }, + }; + await assert.rejects(pipeTo(source, { + write: common.mustNotCall(), + writeSync: common.mustCall(() => { throw error; }), + fail: common.mustCall((reason) => assert.strictEqual(reason, error)), + }), error); + assert.strictEqual(closed, true); + } + + const error = new Error('source'); + const source = { + [Symbol.iterator]() { + return { + next() { throw error; }, + return: common.mustNotCall(), + }; + }, + }; + await assert.rejects(pipeTo(source, { + write: common.mustNotCall(), + writeSync: common.mustNotCall(), + fail: common.mustCall((reason) => assert.strictEqual(reason, error)), + }), error); +} + +// pipeTo() reads async iterables without waiting for a cancellation, since +// nothing cancels them while a read is pending. An error writing a batch +// must still close the source, ignoring an error closing it, an error +// reading the source must not close it, and the source's results are still +// checked. +async function testPipeToAsyncIterableErrors() { + for (const returnRejects of [false, true]) { + const error = new Error('write'); + let closed = false; + const source = { + [Symbol.asyncIterator]() { + let i = 0; + return { + async next() { + return { done: false, value: [new Uint8Array([i++])] }; + }, + async return() { + closed = true; + if (returnRejects) throw new Error('return'); + return { done: true }; + }, + }; + }, + }; + await assert.rejects(pipeTo(source, { + write: common.mustNotCall(), + writeSync: common.mustCall(() => { throw error; }), + fail: common.mustCall((reason) => assert.strictEqual(reason, error)), + }), error); + assert.strictEqual(closed, true); + } + + const error = new Error('source'); + await assert.rejects(pipeTo({ + [Symbol.asyncIterator]() { + return { + next() { return Promise.reject(error); }, + return: common.mustNotCall(), + }; + }, + }, { + write: common.mustNotCall(), + writeSync: common.mustNotCall(), + fail: common.mustCall((reason) => assert.strictEqual(reason, error)), + }), error); + + await assert.rejects(pipeTo({ + [Symbol.asyncIterator]() { + return { next: async () => 42 }; + }, + }, { + write: common.mustNotCall(), + writeSync: common.mustNotCall(), + fail: common.mustCall(), + }), { code: 'ERR_INVALID_RETURN_VALUE' }); +} + Promise.all([ testPipeToSync(), testPipeTo(), @@ -365,5 +468,7 @@ Promise.all([ testPipeToSyncIterableUsesFromBatching(), testPipeToSyncIterableWriteFallback(), testPipeToSyncIterableAsyncValue(), + testPipeToSyncIterableWriteError(), + testPipeToAsyncIterableErrors(), testPipeToSourceNormalizationIndependentOfWriter(), ]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-pull-async.js b/test/parallel/test-stream-iter-pull-async.js index 5bffd49d5112..53480cb653df 100644 --- a/test/parallel/test-stream-iter-pull-async.js +++ b/test/parallel/test-stream-iter-pull-async.js @@ -4,9 +4,11 @@ const common = require('../common'); const assert = require('assert'); const { + array, broadcast, dump, from, + pipeTo, pull, push, share, @@ -17,6 +19,7 @@ const { const { setImmediate } = require('timers/promises'); const { inspect } = require('util'); +const { getEventListeners } = require('events'); async function testPullIdentity() { const data = await text(pull(from('hello-async'))); @@ -313,7 +316,7 @@ async function testPullReturnWhileSourceNextPending() { ]); assert.notStrictEqual(result, timeout); - assert.deepStrictEqual(result, { value: undefined, done: true }); + assert.deepStrictEqual({ ...result }, { value: undefined, done: true }); await next; } @@ -364,6 +367,125 @@ async function testPullSignalAbortWithTransformWhileSourceNextPending() { await assert.rejects(next, { name: 'AbortError' }); } +// An abort rejects a pending pull at once, wherever the pipeline is waiting: +// here, on a transform that never settles. +async function testPullSignalAbortWhileTransformPending() { + const ac = new AbortController(); + let transformSignal; + const iter = pull(from('a'), (chunks, options) => { + transformSignal = options.signal; + return new Promise(() => {}); + }, { signal: ac.signal })[Symbol.asyncIterator](); + const next = iter.next(); + await setImmediate(); + const reason = new Error('stop'); + ac.abort(reason); + await assert.rejects(next, reason); + assert.strictEqual(transformSignal.reason, reason); + await assert.rejects(iter.next(), reason); +} + +// When the signal aborts while no pull is pending, the source is closed once, +// and the next pull rejects. +async function testPullSignalAbortWhileIdleClosesSource() { + const log = []; + const ac = new AbortController(); + const iter = pull(createLoggedSource(log, [1, 2, 3]), (chunks) => chunks, + { signal: ac.signal })[Symbol.asyncIterator](); + assert.strictEqual((await iter.next()).done, false); + const reason = new Error('stop'); + ac.abort(reason); + await setImmediate(); + assert.deepStrictEqual(log, ['next 0', 'return']); + await assert.rejects(iter.next(), reason); + assert.strictEqual((await iter.return()).done, true); + assert.deepStrictEqual(log, ['next 0', 'return']); +} + +// The pipeline's listener on the signal is removed once the pipeline is +// done, however it ends. +async function testPullSignalListenerRemoved() { + const identity = (chunks) => chunks; + const ac = new AbortController(); + const { signal } = ac; + await text(pull(from(['a', 'b']), identity, { signal })); + assert.strictEqual(getEventListeners(signal, 'abort').length, 0); + + let iter = pull(from(['a', 'b']), identity, { signal })[Symbol.asyncIterator](); + await iter.next(); + assert.strictEqual(getEventListeners(signal, 'abort').length, 1); + await iter.return(); + assert.strictEqual(getEventListeners(signal, 'abort').length, 0); + + iter = pull(from(['a', 'b']), () => { throw new Error('failed'); }, + { signal })[Symbol.asyncIterator](); + await assert.rejects(iter.next(), /failed/); + assert.strictEqual(getEventListeners(signal, 'abort').length, 0); + + iter = pull(from(['a', 'b']), identity, { signal })[Symbol.asyncIterator](); + await iter.next(); + ac.abort(); + assert.strictEqual(getEventListeners(signal, 'abort').length, 0); + await assert.rejects(iter.next(), { name: 'AbortError' }); +} + +// Stateful transforms: called on the first pull, with a source that ends +// with one null flush signal; their output is normalized; stopping early +// closes the output and the source. +async function testStatefulTransformProtocol() { + const log = []; + const stateful = { + async *transform(source) { + log.push('called'); + try { + for await (const batch of source) { + log.push(batch === null ? 'flush' : `batch ${batch[0][0]}`); + if (batch === null) { + yield 'end'; + } else { + yield batch; + yield batch[0]; + yield null; + yield []; + } + } + } finally { + log.push('output closed'); + } + }, + }; + const iterable = pull(createLoggedSource(log, [1, 2]), stateful); + assert.deepStrictEqual(log, []); + const chunks = await array(iterable); + assert.deepStrictEqual(chunks.map((chunk) => chunk[0]), [1, 1, 2, 2, 101]); + assert.deepStrictEqual(log, [ + 'called', 'next 0', 'batch 1', 'next 1', 'batch 2', 'next 2', 'flush', + 'output closed', + ]); + + log.length = 0; + const iterator = pull(createLoggedSource(log, [1, 2, 3]), + stateful)[Symbol.asyncIterator](); + assert.strictEqual((await iterator.next()).value[0][0], 1); + assert.strictEqual((await iterator.return()).done, true); + assert.deepStrictEqual(log, [ + 'called', 'next 0', 'batch 1', 'return', 'output closed', + ]); + assert.strictEqual((await iterator.next()).done, true); + + // Outputs that are sync iterables are read as for await reads them. + const syncOutput = { transform: () => [[Uint8Array.of(7)], 'x'] }; + assert.deepStrictEqual((await array(pull(from('a'), syncOutput))).map( + (chunk) => chunk[0]), [7, 120]); + + // Errors from the transform reject the pull. + const failing = { + // eslint-disable-next-line require-yield + async *transform() { throw new Error('stateful failed'); }, + }; + await assert.rejects(array(pull(from('a'), failing)), /stateful failed/); +} + // Pull consumer break (return()) cleans up transform signal async function testPullConsumerBreakCleanup() { let signalAborted = false; @@ -552,7 +674,7 @@ async function testPipeToStringSource() { assert.strictEqual(data, 'hello-pipe'); } -// INVARIANT: Each transform invocation receives its own options object. +// Each transform receives its own options object. // A transform that mutates options must not affect subsequent transforms. async function testTransformOptionsNotShared() { const seen = []; @@ -574,43 +696,213 @@ async function testTransformOptionsNotShared() { assert.strictEqual(seen[1].mutated, undefined); } -// Stateless transforms get a new options object for every call, and stateful -// transforms one for the pipeline. The options object has only `signal`, does +// Each transform of a pipeline gets its own options object, passed to every +// call of a stateless transform. The options object has only `signal`, does // not inherit from Object.prototype, and its prototype is frozen, so that a -// transform cannot pass state to others through it. +// transform cannot pass state to others through it. The signal is the same +// for every transform and every call. async function testTransformOptionsShape() { const seen = []; + const statelessSeen = []; + let statefulOptions; const stateless = (chunks, options) => { seen.push(options); + statelessSeen.push(options); return chunks; }; const stateful = { async* transform(source, options) { seen.push(options); + statefulOptions = options; for await (const chunks of source) yield chunks; }, }; const ac = new AbortController(); await text(pull(from(['a', 'b']), stateless, stateful, { signal: ac.signal })); - // Stateless: one call per batch plus the flush call. + // Stateless: one call per batch plus the flush call; stateful: one call. + assert.strictEqual(statelessSeen.length, 3); + assert.strictEqual(new Set(statelessSeen).size, 1); assert.strictEqual(seen.length, 4); - assert.strictEqual(new Set(seen).size, seen.length); + assert.notStrictEqual(statefulOptions, statelessSeen[0]); for (const options of seen) { assert.strictEqual(options instanceof Object, false); assert.deepStrictEqual(Object.keys(options), ['signal']); assert.ok(options.signal instanceof AbortSignal); + assert.strictEqual(options.signal, seen[0].signal); assert.strictEqual(Object.isFrozen(Object.getPrototypeOf(options)), true); assert.match(inspect(options), /^TransformOptions \{ signal: /); } - assert.strictEqual(Object.getPrototypeOf(seen[0]), - Object.getPrototypeOf(seen[3])); + assert.strictEqual(Object.getPrototypeOf(statefulOptions), + Object.getPrototypeOf(statelessSeen[0])); assert.throws(() => { Object.getPrototypeOf(seen[0]).leak = true; }, TypeError); } +// `options.signal` can be assigned, as a data property could, whether or +// not it has been read. +async function testTransformOptionsSignalAssignable() { + const seen = []; + let calls = 0; + const transform = (chunks, options) => { + seen.push(options.signal); + options.signal = ++calls; + return chunks; + }; + const unread = (chunks, options) => { + options.signal = 'unread'; + seen.push(options.signal); + return chunks; + }; + await text(pull(from(['a', 'b']), transform, unread)); + assert.ok(seen[0] instanceof AbortSignal); + assert.deepStrictEqual(seen.slice(1), ['unread', 1, 'unread', 2, 'unread']); +} + +// The transforms' signal is the pipeline's: first read after the pipeline +// has been aborted, it is already aborted with the same reason, and read +// before, it is aborted when the pipeline is. +async function testTransformSignalReadAfterAbort() { + const reason = new Error('stop'); + let options; + const transform = (chunks, opts) => { + options = opts; + throw reason; + }; + await assert.rejects(text(pull(from('a'), transform)), reason); + assert.strictEqual(options.signal.aborted, true); + assert.strictEqual(options.signal.reason, reason); + assert.strictEqual(options.signal, options.signal); + + const ac = new AbortController(); + let signal; + const iterator = pull(from(['a', 'b']), (chunks, opts) => { + signal ??= opts.signal; + return chunks; + }, { signal: ac.signal })[Symbol.asyncIterator](); + await iterator.next(); + assert.strictEqual(signal.aborted, false); + ac.abort(reason); + assert.strictEqual(signal.aborted, true); + assert.strictEqual(signal.reason, reason); +} + // Run the uncaughtException test sequentially (it installs a global handler // that would interfere with concurrent tests). +// Transform pipelines read and close the source like an async generator +// looping over it with for await. The tests below check the parts of that +// behavior that are observable from the source and the transforms' signal. + +// Creates an async iterable source of batches of one-byte chunks with values +// `values`, recording calls in `log`. +function createLoggedSource(log, values, { failAt = -1 } = {}) { + let i = 0; + return { + [Symbol.asyncIterator]() { + return { + async next() { + log.push(`next ${i}`); + if (i === failAt) { + i++; + throw new Error('source failed'); + } + if (i >= values.length) return { done: true, value: undefined }; + return { done: false, value: [Uint8Array.of(values[i++])] }; + }, + async return() { + log.push('return'); + return { done: true, value: undefined }; + }, + }; + }, + }; +} + +// A transform recording its calls, and the abort of its signal, in `log`. +function createLoggedTransform(log, transform = (chunks) => chunks) { + let listening = false; + return (chunks, options) => { + log.push(chunks === null ? 'flush' : `transform ${chunks[0][0]}`); + if (!listening) { + listening = true; + options.signal.addEventListener('abort', () => { + log.push(`abort: ${options.signal.reason.message}`); + }); + } + return transform(chunks, options); + }; +} + +async function testTransformErrorClosesSource() { + const fail = (chunks) => { + if (chunks?.[0][0] === 2) throw new Error('transform failed'); + return chunks; + }; + for (const transform of [fail, async (chunks) => fail(chunks)]) { + const log = []; + await assert.rejects(async () => { + // eslint-disable-next-line no-unused-vars + for await (const _ of pull(createLoggedSource(log, [1, 2, 3]), + createLoggedTransform(log, transform))); + }, /transform failed/); + assert.deepStrictEqual(log, [ + 'next 0', 'transform 1', 'next 1', 'transform 2', 'return', + 'abort: transform failed', + ]); + } +} + +async function testTransformSourceErrorDoesNotCloseSource() { + const log = []; + await assert.rejects(async () => { + // eslint-disable-next-line no-unused-vars + for await (const _ of pull(createLoggedSource(log, [1], { failAt: 1 }), + createLoggedTransform(log))); + }, /source failed/); + assert.deepStrictEqual(log, [ + 'next 0', 'transform 1', 'next 1', 'abort: source failed', + ]); +} + +async function testPipeToTransformsStoppedEarly() { + // When the writer fails, the transforms' signal is aborted, and the + // transforms are closed, closing the source, as when the consumer of pull() + // stops early. + const log = []; + let writes = 0; + await assert.rejects(pipeTo( + createLoggedSource(log, [1, 2, 3]), createLoggedTransform(log), { + write() { + if (++writes === 2) throw new Error('write failed'); + }, + }), /write failed/); + assert.deepStrictEqual(log, [ + 'next 0', 'transform 1', 'next 1', 'transform 2', 'abort: Aborted', + 'return', + ]); +} + +async function testTransformReturnClosesOutputAndSource() { + // A transform output that is iterated asynchronously is closed, and then + // the source, when the pipeline is stopped while reading it. + const log = []; + const iterator = pull(createLoggedSource(log, [1, 2]), + createLoggedTransform(log, async function*() { + try { + yield Uint8Array.of(1); + yield Uint8Array.of(2); + } finally { + log.push('output closed'); + } + }))[Symbol.asyncIterator](); + assert.strictEqual((await iterator.next()).done, false); + assert.strictEqual((await iterator.return()).done, true); + assert.strictEqual((await iterator.next()).done, true); + assert.deepStrictEqual(log, [ + 'next 0', 'transform 1', 'output closed', 'abort: Aborted', 'return', + ]); +} + (async () => { await Promise.all([ testPullIdentity(), @@ -646,6 +938,16 @@ async function testTransformOptionsShape() { testPipeToStringSource(), testTransformOptionsNotShared(), testTransformOptionsShape(), + testTransformSignalReadAfterAbort(), + testPullSignalAbortWhileTransformPending(), + testPullSignalAbortWhileIdleClosesSource(), + testPullSignalListenerRemoved(), + testStatefulTransformProtocol(), + testTransformOptionsSignalAssignable(), + testTransformErrorClosesSource(), + testTransformSourceErrorDoesNotCloseSource(), + testPipeToTransformsStoppedEarly(), + testTransformReturnClosesOutputAndSource(), ]); // Run after all concurrent tests complete to avoid global handler races await testTransformSignalListenerErrorOnSourceError(); diff --git a/test/parallel/test-stream-iter-push-basic.js b/test/parallel/test-stream-iter-push-basic.js index 9b1c044cac47..ad7eab5f53a4 100644 --- a/test/parallel/test-stream-iter-push-basic.js +++ b/test/parallel/test-stream-iter-push-basic.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); -const { push, text } = require('stream/iter'); +const { from, push, text } = require('stream/iter'); async function testBasicWriteRead() { const { writer, readable } = push(); @@ -174,6 +174,21 @@ async function testInvalidBackpressure() { } } +async function testReturnValue() { + // return(value) resolves with `value`, read directly or through from(). + for (const getIterator of [ + (readable) => readable[Symbol.asyncIterator](), + (readable) => from(readable)[Symbol.asyncIterator](), + ]) { + const { writer, readable } = push(); + const iterator = getIterator(readable); + const result = await iterator.return('value'); + assert.strictEqual(result.done, true); + assert.strictEqual(result.value, 'value'); + assert.strictEqual(writer.canWrite, null); + } +} + Promise.all([ testBasicWriteRead(), testMultipleWrites(), @@ -187,4 +202,5 @@ Promise.all([ testConsumerBreakWriteSyncReturnsFalse(), testPushWithTransforms(), testInvalidBackpressure(), + testReturnValue(), ]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-push-writer.js b/test/parallel/test-stream-iter-push-writer.js index a37c5eac2aa3..0278ce569b9d 100644 --- a/test/parallel/test-stream-iter-push-writer.js +++ b/test/parallel/test-stream-iter-push-writer.js @@ -3,7 +3,7 @@ const common = require('../common'); const assert = require('assert'); -const { dump, ondrain, push, text } = require('stream/iter'); +const { dump, push, ondrain, text, array } = require('stream/iter'); const { setImmediate } = require('timers/promises'); async function testOndrain() { @@ -663,7 +663,36 @@ async function testFailRejectsPendingReadWithFalsyReason() { ); } +// Strings are encoded as UTF-8 (lone surrogates as U+FFFD), small ones into +// a shared, untransferable pool, which must not mix up their bytes, also +// when the pool fills up; large ones each into an ArrayBuffer of their own. +async function testWriteStrings() { + const strings = []; + for (let i = 0; i < 3000; i++) { + strings.push(`row ${i} héllo 😀 \ud800 ${'x'.repeat(i % 97)}`); + } + strings.push('y'.repeat(10000), 'z'); + const { writer, readable } = push(); + const read = array(readable); + for (const string of strings) { + if (!writer.writeSync(string)) await writer.write(string); + } + await writer.end(); + const chunks = await read; + const decoder = new TextDecoder(); + assert.deepStrictEqual(chunks.map((chunk) => decoder.decode(chunk)), + strings.map((s) => s.replace('\ud800', '\ufffd'))); + for (const chunk of chunks) { + assert.strictEqual(Object.getPrototypeOf(chunk), Uint8Array.prototype); + } + const pooled = chunks[0]; + assert.ok(pooled.buffer.byteLength > pooled.byteLength); + assert.throws(() => pooled.buffer.transfer(), TypeError); + assert.strictEqual(chunks[3000].buffer.byteLength, 10000); +} + Promise.all([ + testWriteStrings(), testOndrain(), testDropPoliciesReportPhysicalCapacity(), testOndrainNonDrainable(), diff --git a/test/parallel/test-stream-iter-resizable-buffers.js b/test/parallel/test-stream-iter-resizable-buffers.js index 91f7429ec12f..675e69496535 100644 --- a/test/parallel/test-stream-iter-resizable-buffers.js +++ b/test/parallel/test-stream-iter-resizable-buffers.js @@ -42,6 +42,37 @@ async function testBufferedViewMutationRejected() { } } +// Several buffered writes, single chunks and batches, read as one batch: +// they are delivered in order, and a view resized after it was written +// among them rejects the read. +async function testBufferedEntriesReadTogether() { + { + const { writer, readable } = push(); + writer.writeSync(Uint8Array.of(1)); + writer.writevSync([Uint8Array.of(2), Uint8Array.of(3)]); + writer.writeSync(Uint8Array.of(4)); + writer.endSync(); + const batches = await array(readable); + assert.deepStrictEqual(batches.map((c) => c[0]), [1, 2, 3, 4]); + } + for (const single of [true, false]) { + const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const { writer, readable } = push(); + writer.writeSync(Uint8Array.of(1)); + writer.writevSync([Uint8Array.of(2), Uint8Array.of(3)]); + if (single) { + writer.writeSync(new Uint8Array(buffer)); + } else { + writer.writevSync([Uint8Array.of(4), new Uint8Array(buffer)]); + } + buffer.resize(2); + await assert.rejects( + readable[Symbol.asyncIterator]().next(), + kResizeError, + ); + } +} + async function testDropOldestUsesAcceptedByteLength() { const buffer = new ArrayBuffer(16384, { maxByteLength: 16384 }); const { writer, broadcast: bc } = broadcast({ @@ -103,6 +134,29 @@ async function testBroadcastRejectsResizedBufferedView() { await assert.rejects(writer.end(), kResizeError); } +// The same, for a view buffered in a batch of several chunks. +async function testBufferedBatchViewResizeRejected() { + { + const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const { writer, broadcast: bc } = broadcast(); + const iterator = bc.push()[Symbol.asyncIterator](); + assert.strictEqual( + writer.writevSync([Uint8Array.of(1), new Uint8Array(buffer)]), true); + buffer.resize(2); + await assert.rejects(iterator.next(), kResizeError); + await assert.rejects(writer.end(), kResizeError); + } + { + const buffer = new ArrayBuffer(1, { maxByteLength: 2 }); + const shared = share([[Uint8Array.of(1), new Uint8Array(buffer)]]); + const first = shared.pull()[Symbol.asyncIterator](); + const second = shared.pull()[Symbol.asyncIterator](); + assert.strictEqual((await first.next()).value.length, 2); + buffer.resize(2); + await assert.rejects(second.next(), kResizeError); + } +} + async function testShareRejectsResizedBufferedView() { const asyncBuffer = new ArrayBuffer(1, { maxByteLength: 2 }); const shared = share([[new Uint8Array(asyncBuffer)]]); @@ -167,6 +221,96 @@ async function testPipeRejectsWriterResize() { ); } +// Single-chunk batches are checked around writeSync() without a snapshot +// object. Detaching or resizing the view in writeSync() must still be +// rejected, for views on ArrayBuffers and on growable SharedArrayBuffers. +async function testPipeRejectsSyncWriteDetachOrResize() { + const cases = [ + ['detach', () => new ArrayBuffer(2), (buffer) => buffer.transfer()], + ['resize', () => new ArrayBuffer(1, { maxByteLength: 2 }), + (buffer) => buffer.resize(2)], + ['grow shared', () => new SharedArrayBuffer(1, { maxByteLength: 2 }), + (buffer) => buffer.grow(2)], + ]; + for (const [, createBuffer, change] of cases) { + const asyncBuffer = createBuffer(); + await assert.rejects(pipeTo([new Uint8Array(asyncBuffer)], { + writeSync() { + change(asyncBuffer); + return true; + }, + write: common.mustNotCall(), + fail: common.mustCall(), + }), kResizeError); + + const syncBuffer = createBuffer(); + assert.throws(() => pipeToSync([new Uint8Array(syncBuffer)], { + writeSync() { + change(syncBuffer); + return true; + }, + fail: common.mustCall(), + }, { preventClose: true }), kResizeError); + } + + // An unchanged view is written; when writeSync() declines it, pipeTo() + // falls back to write() for it. + const chunk = Uint8Array.of(1, 2); + const written = []; + assert.strictEqual(await pipeTo([chunk], { + writeSync: () => false, + write(value) { written.push(value); }, + }, { preventClose: true }), 2); + assert.deepStrictEqual(written, [chunk]); +} + +// Batches of several chunks written one at a time are checked against the +// byteLengths recorded when the batch was accepted, before and after each +// writeSync(). Detaching a later chunk, or the chunk being written, must be +// rejected. +async function testPipeRejectsDetachInMultiChunkBatch() { + for (const detachIndex of [1, 0]) { + const asyncBuffers = [new ArrayBuffer(2), new ArrayBuffer(2)]; + const asyncWritten = []; + await assert.rejects(pipeTo([asyncBuffers.map((b) => new Uint8Array(b))], { + writeSync(chunk) { + asyncWritten.push(chunk.byteLength); + if (asyncWritten.length === 1) asyncBuffers[detachIndex].transfer(); + return true; + }, + write: common.mustNotCall(), + fail: common.mustCall(), + }), kResizeError); + assert.deepStrictEqual(asyncWritten, [2]); + + const syncBuffers = [new ArrayBuffer(2), new ArrayBuffer(2)]; + const syncWritten = []; + assert.throws(() => pipeToSync([syncBuffers.map((b) => new Uint8Array(b))], { + writeSync(chunk) { + syncWritten.push(chunk.byteLength); + if (syncWritten.length === 1) syncBuffers[detachIndex].transfer(); + return true; + }, + fail: common.mustCall(), + }, { preventClose: true }), kResizeError); + assert.deepStrictEqual(syncWritten, [2]); + } + + // When writeSync() declines a chunk, pipeTo() writes the rest of the batch + // with write(). + const chunks = [Uint8Array.of(1), Uint8Array.of(2, 3), Uint8Array.of(4)]; + const written = []; + assert.strictEqual(await pipeTo([chunks], { + writeSync(chunk) { + if (chunk === chunks[1]) return false; + written.push(chunk); + return true; + }, + write(chunk) { written.push(chunk); }, + }, { preventClose: true }), 4); + assert.deepStrictEqual(written, chunks); +} + async function testConsumersRejectDetachedViews() { // Views of fixed-length buffers are tracked without a full snapshot; they // must still be rejected when detached after being accepted. @@ -196,13 +340,65 @@ async function testConsumersRejectDetachedViews() { assert.strictEqual(result, chunk); } +// A writer with only write() is checked the same way, before and after each +// write(), and after the promise it returns, if any. +async function testPipeRejectsDetachWithWriteOnly() { + for (const detachIndex of [1, 0]) { + const buffers = [new ArrayBuffer(2), new ArrayBuffer(2)]; + const written = []; + await assert.rejects(pipeTo([buffers.map((b) => new Uint8Array(b))], { + write(chunk) { + written.push(chunk.byteLength); + if (written.length === 1) buffers[detachIndex].transfer(); + }, + fail: common.mustCall(), + }), kResizeError); + assert.deepStrictEqual(written, [2]); + } + + const buffer = new ArrayBuffer(2); + await assert.rejects(pipeTo([new Uint8Array(buffer)], { + async write() { + await null; + buffer.transfer(); + }, + fail: common.mustCall(), + }), kResizeError); +} + +// Only what was accounted for a view is checked: its byteLength. A +// fixed-length view of a resizable buffer that stays in bounds is unchanged. +async function testFixedLengthViewOfResizedBuffer() { + const buffer = new ArrayBuffer(4, { maxByteLength: 8 }); + const view = new Uint8Array(buffer, 0, 2); + const { writer, readable } = push(); + assert.strictEqual(writer.writeSync(view), true); + buffer.resize(8); + writer.endSync(); + const [chunk] = await array(readable); + assert.strictEqual(chunk, view); + + // Shrinking the buffer so that the view is out of bounds makes its + // byteLength 0: rejected. + const { writer: writer2, readable: readable2 } = push(); + assert.strictEqual(writer2.writeSync(view), true); + buffer.resize(1); + await assert.rejects(readable2[Symbol.asyncIterator]().next(), kResizeError); +} + Promise.all([ + testPipeRejectsDetachWithWriteOnly(), + testFixedLengthViewOfResizedBuffer(), testBufferedViewMutationRejected(), + testBufferedEntriesReadTogether(), testDropOldestUsesAcceptedByteLength(), testPendingWritesRejectResizedViews(), testBroadcastRejectsResizedBufferedView(), testShareRejectsResizedBufferedView(), + testBufferedBatchViewResizeRejected(), testConsumersRejectResizedViews(), testConsumersRejectDetachedViews(), testPipeRejectsWriterResize(), + testPipeRejectsSyncWriteDetachOrResize(), + testPipeRejectsDetachInMultiChunkBatch(), ]).then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-share-async.js b/test/parallel/test-stream-iter-share-async.js index 8ea06427543e..11df7c9bfa56 100644 --- a/test/parallel/test-stream-iter-share-async.js +++ b/test/parallel/test-stream-iter-share-async.js @@ -507,6 +507,57 @@ async function testShareConsumerConcurrentNextCalls() { assert.strictEqual(dec.decode(r2.value[0]), 'second'); } +// A sync source is read as the consumers pull, including values that are +// normalized asynchronously, and its errors reach every consumer after the +// data before them. +async function testShareSyncSource() { + const reason = new Error('sync source boom'); + function* source() { + yield [Uint8Array.of(1)]; + yield Promise.resolve(Uint8Array.of(2)); + yield 'c'; + yield [Uint8Array.of(4)]; + throw reason; + } + const shared = share(source()); + const consumers = [shared.pull(), shared.pull()]; + const read = async (consumer) => { + const values = []; + try { + for await (const batch of consumer) values.push(...batch.map((c) => c[0])); + } catch (error) { + values.push(error); + } + return values; + }; + const results = await Promise.all(consumers.map(read)); + for (const values of results) { + assert.deepStrictEqual(values, [1, 2, 99, 4, reason]); + } + + // Concurrent next() calls get the batches in order. + function* numbers() { + for (let i = 0; i < 4; i++) yield [Uint8Array.of(i)]; + } + const it = share(numbers()).pull()[Symbol.asyncIterator](); + const all = await Promise.all([it.next(), it.next(), it.next(), it.next(), + it.next()]); + assert.deepStrictEqual(all.map((r) => (r.done ? 'done' : r.value[0][0])), + [0, 1, 2, 3, 'done']); + + // 'strict' backpressure rejects a consumer that would exceed the budget + // when another one lags. + function* big() { + for (let i = 0; i < 4; i++) yield [new Uint8Array(8)]; + } + const strict = share(big(), { budget: 16 }); + const fast = strict.pull()[Symbol.asyncIterator](); + strict.pull(); + await fast.next(); + await fast.next(); + await assert.rejects(fast.next(), { code: 'ERR_OUT_OF_RANGE' }); +} + // share() accepts string source directly (normalized via from()) async function testShareStringSource() { const shared = share('hello-share'); @@ -516,6 +567,7 @@ async function testShareStringSource() { Promise.all([ testBasicShare(), + testShareSyncSource(), testShareMultipleConsumers(), testShareConsumerCount(), testShareCancel(), diff --git a/test/parallel/test-stream-iter-share-read-retention.js b/test/parallel/test-stream-iter-share-read-retention.js new file mode 100644 index 000000000000..d95fee336429 --- /dev/null +++ b/test/parallel/test-stream-iter-share-read-retention.js @@ -0,0 +1,47 @@ +// Flags: --experimental-stream-iter --expose-gc --no-warnings +'use strict'; + +// Reading the source of a share() must not leave objects behind for every +// read: what a share keeps alive must not grow with the number of batches +// read from its source. + +const common = require('../common'); +const assert = require('assert'); +const { queryObjects } = require('v8'); +const { share } = require('stream/iter'); + +async function test() { + const reads = 4000; + const chunk = new Uint8Array(1); + let i = 0; + const source = { + [Symbol.asyncIterator]() { return this; }, + async next() { + return i++ < reads ? + { done: false, value: [chunk] } : + { done: true, value: undefined }; + }, + }; + const shared = share(source, { backpressure: 'unbounded' }); + const a = shared.pull()[Symbol.asyncIterator](); + const b = shared.pull()[Symbol.asyncIterator](); + + const promises = []; + for (let n = 0; n < reads; n++) { + assert.strictEqual((await a.next()).done, false); + assert.strictEqual((await b.next()).done, false); + if (n === 1000 || n === 3000) { + globalThis.gc(); + promises.push(queryObjects(Promise, { format: 'count' })); + } + } + assert.strictEqual((await a.next()).done, true); + assert.strictEqual((await b.next()).done, true); + + // 2000 reads happened between the two counts. Retaining even one promise + // per read would add 2000. + const growth = promises[1] - promises[0]; + assert.ok(growth < 200, `${growth} promises retained across 2000 reads`); +} + +test().then(common.mustCall()); diff --git a/test/parallel/test-stream-iter-transform-buffering.js b/test/parallel/test-stream-iter-transform-buffering.js index b1b813f60b9b..95b9a71f65c2 100644 --- a/test/parallel/test-stream-iter-transform-buffering.js +++ b/test/parallel/test-stream-iter-transform-buffering.js @@ -4,8 +4,13 @@ const common = require('../common'); const assert = require('assert'); const { brotliDecompressSync, gunzipSync, gzipSync } = require('zlib'); -const { compressBrotli, compressGzip, decompressGzip } = require('zlib/iter'); -const { bytes, from, pull } = require('stream/iter'); +const { + compressBrotli, + compressGzip, + decompressGzip, + decompressGzipSync, +} = require('zlib/iter'); +const { bytes, from, fromSync, pull, pullSync } = require('stream/iter'); async function testDecompressionOutputIsBounded() { let input = Buffer.alloc(32 * 1024 * 1024, 0x61); @@ -38,6 +43,34 @@ async function testSmallChunkSizeDecompression() { assert.deepStrictEqual(Buffer.from(output), input); } +// With a chunk size that does not divide the batch size, output collected +// beyond a batch is taken a batch at a time, from the front. +async function testPartialBatchDrains() { + const input = Buffer.alloc(1024 * 1024); + for (let i = 0; i < input.length; i++) input[i] = (i * 7 + (i >> 12)) & 0xff; + const compressed = gzipSync(input); + const batchSizes = (batches) => batches.map((batch) => { + return batch.reduce((total, chunk) => total + chunk.length, 0); + }); + + const asyncBatches = []; + for await (const batch of pull(from(compressed), + decompressGzip({ chunkSize: 1000 }))) { + asyncBatches.push(batch); + } + const syncBatches = [ + ...pullSync(fromSync(compressed), decompressGzipSync({ chunkSize: 1000 })), + ]; + for (const batches of [asyncBatches, syncBatches]) { + assert.deepStrictEqual(Buffer.concat(batches.flat()), input); + assert.ok(batches.length > 1); + // A batch is closed once it holds 64 KiB. + for (const size of batchSizes(batches)) { + assert.ok(size <= 64 * 1024 + 1000, `batch of ${size} bytes`); + } + } +} + // Deterministic incompressible data. Brotli's buffering decisions depend on // content, so random data would make the tests below flaky. function incompressible(size) { @@ -108,6 +141,7 @@ async function testSourceReturnFailuresAreIgnored() { await testDecompressionOutputIsBounded(); await Promise.all([ testSmallChunkSizeDecompression(), + testPartialBatchDrains(), testLargeFinishOutput(), testExplicitFlushSignal(), testSourceReturnFailuresAreIgnored(), diff --git a/test/parallel/test-stream-map.js b/test/parallel/test-stream-map.js index 212658313885..be2628c41825 100644 --- a/test/parallel/test-stream-map.js +++ b/test/parallel/test-stream-map.js @@ -358,3 +358,13 @@ function createDependentPromises(n) { const stream = Readable.from([1, 2, 3, 4, 5]).map((x) => x); assert.strictEqual(stream.readable, true); } + +{ + // Already aborted AbortSignal on an empty stream + const stream = Readable.from([]).map(common.mustNotCall(), { + signal: AbortSignal.abort(), + }); + assert.rejects(stream.toArray(), { + name: 'AbortError', + }).then(common.mustCall()); +} diff --git a/test/parallel/test-stream-pipe-replaced-write.js b/test/parallel/test-stream-pipe-replaced-write.js new file mode 100644 index 000000000000..ef65d453a486 --- /dev/null +++ b/test/parallel/test-stream-pipe-replaced-write.js @@ -0,0 +1,81 @@ +'use strict'; + +// pipe() calls dest.write(). The fast path of a flowing pipe must not go +// around a write() replaced on the instance, overridden in a subclass, as +// compression middleware does to the response it wraps, or patched on +// Writable.prototype, as APM tools do. + +const common = require('../common'); +const assert = require('assert'); +const { Readable, Writable } = require('stream'); + +const CHUNKS = 64; + +// Pushes from inside _read(), which is what lets the fast path take over. +function source() { + const data = Buffer.alloc(CHUNKS * 1024, 'a'); + let offset = 0; + return new Readable({ + read() { + if (offset >= data.length) { + this.push(null); + return; + } + this.push(data.subarray(offset, offset += 1024)); + }, + }); +} + +{ + const dest = new Writable({ + write(chunk, encoding, callback) { + callback(); + }, + }); + let calls = 0; + const write = dest.write; + dest.write = function(chunk, encoding, callback) { + calls++; + return write.call(this, chunk, encoding, callback); + }; + source().pipe(dest).on('finish', common.mustCall(() => { + assert.strictEqual(calls, CHUNKS); + })); +} + +{ + class Counting extends Writable { + calls = 0; + + write(chunk, encoding, callback) { + this.calls++; + return super.write(chunk, encoding, callback); + } + + _write(chunk, encoding, callback) { + callback(); + } + } + const dest = new Counting(); + source().pipe(dest).on('finish', common.mustCall(() => { + assert.strictEqual(dest.calls, CHUNKS); + })); +} + +{ + const dest = new Writable({ + write(chunk, encoding, callback) { + callback(); + }, + }); + const write = Writable.prototype.write; + let calls = 0; + Writable.prototype.write = function(chunk, encoding, callback) { + if (this === dest) calls++; + return write.call(this, chunk, encoding, callback); + }; + source().pipe(dest).on('finish', common.mustCall(() => { + Writable.prototype.write = write; + assert.strictEqual(calls, CHUNKS); + })); +} diff --git a/test/parallel/test-stream-readable-construct-hwm-zero.js b/test/parallel/test-stream-readable-construct-hwm-zero.js new file mode 100644 index 000000000000..ccabc366d700 --- /dev/null +++ b/test/parallel/test-stream-readable-construct-hwm-zero.js @@ -0,0 +1,82 @@ +'use strict'; + +const common = require('../common'); + +const assert = require('node:assert'); +const { Duplex, Readable } = require('node:stream'); + +function create(construct, objectMode = false) { + const chunks = objectMode ? [{ a: 1 }, { b: 2 }] : ['a', 'b']; + return new Readable({ + highWaterMark: 0, + objectMode, + construct, + read() { + this.push(chunks.length ? chunks.shift() : null); + }, + }); +} + +create((cb) => setImmediate(cb)).toArray().then(common.mustCall((data) => { + assert.deepStrictEqual(data.map(String), ['a', 'b']); +})); + +create((cb) => cb()).toArray().then(common.mustCall((data) => { + assert.deepStrictEqual(data.map(String), ['a', 'b']); +})); + +create((cb) => setImmediate(cb), true).toArray().then(common.mustCall((data) => { + assert.deepStrictEqual(data, [{ a: 1 }, { b: 2 }]); +})); + +(async () => { + const data = []; + for await (const chunk of create((cb) => setImmediate(cb))) { + data.push(String(chunk)); + } + assert.deepStrictEqual(data, ['a', 'b']); +})().then(common.mustCall()); + +{ + const stream = create((cb) => setImmediate(cb)); + const data = []; + stream.on('readable', () => { + let chunk; + while ((chunk = stream.read()) !== null) data.push(String(chunk)); + }); + stream.on('end', common.mustCall(() => { + assert.deepStrictEqual(data, ['a', 'b']); + })); +} + +{ + const stream = create((cb) => setImmediate(cb)); + const data = []; + stream.on('data', (chunk) => data.push(String(chunk))); + stream.on('end', common.mustCall(() => { + assert.deepStrictEqual(data, ['a', 'b']); + })); +} + +{ + const chunks = ['a', 'b']; + const duplex = new Duplex({ + readableHighWaterMark: 0, + construct(cb) { + setImmediate(cb); + }, + read() { + this.push(chunks.length ? chunks.shift() : null); + }, + write: common.mustNotCall(), + }); + duplex.toArray().then(common.mustCall((data) => { + assert.deepStrictEqual(data.map(String), ['a', 'b']); + })); +} + +new Readable({ + highWaterMark: 0, + construct: common.mustCall((cb) => setImmediate(cb)), + read: common.mustNotCall(), +}); diff --git a/test/parallel/test-stream-some-find-every.mjs b/test/parallel/test-stream-some-find-every.mjs index c18e418ddce5..a583350eb954 100644 --- a/test/parallel/test-stream-some-find-every.mjs +++ b/test/parallel/test-stream-some-find-every.mjs @@ -167,6 +167,15 @@ function oneTo5Async() { name: 'AbortError', }, `${op} should abort with pre-aborted abort controller`).then(common.mustCall()); } + { + // Support for pre-aborted AbortSignal on an empty stream + assert.rejects(Readable.from([])[op]( + common.mustNotCall(), + { signal: AbortSignal.abort() } + ), { + name: 'AbortError', + }, `${op} should abort with pre-aborted signal on empty stream`).then(common.mustCall()); + } } } { diff --git a/test/parallel/test-stream-toArray.js b/test/parallel/test-stream-toArray.js index 438e21724e40..e713b00826fe 100644 --- a/test/parallel/test-stream-toArray.js +++ b/test/parallel/test-stream-toArray.js @@ -91,3 +91,15 @@ const assert = require('assert'); }); }, /ERR_INVALID_ARG_TYPE/).then(common.mustCall()); } + +{ + // Already aborted AbortSignal on an empty stream + const reason = new Error('aborted'); + const stream = Readable.from([]); + assert.rejects(stream.toArray({ signal: AbortSignal.abort(reason) }), { + name: 'AbortError', + cause: reason, + }).then(common.mustCall(() => { + assert.strictEqual(stream.destroyed, true); + })); +} diff --git a/test/parallel/test-tls-allow-renegotiation.js b/test/parallel/test-tls-allow-renegotiation.js new file mode 100644 index 000000000000..5292d794b6f4 --- /dev/null +++ b/test/parallel/test-tls-allow-renegotiation.js @@ -0,0 +1,139 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// Tests the allowRenegotiation option of tls.createServer() and tls.connect(). + +const assert = require('assert'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); +const { hasOpenSSL, isBoringSSL } = require('../common/crypto'); + +if (isBoringSSL) { + // BoringSSL servers always refuse renegotiation. + for (const create of [ + () => tls.createServer({ allowRenegotiation: true }), + () => new tls.TLSSocket(null, { isServer: true, allowRenegotiation: true }), + ]) { + assert.throws(create, { code: 'ERR_TLS_RENEGOTIATION_UNSUPPORTED' }); + } + require('../common/boringssl').testRenegotiationUnsupported(); + return; +} + +// Renegotiation as a protocol feature was dropped after TLS1.2. +tls.DEFAULT_MAX_VERSION = 'TLSv1.2'; + +const handshakeFailure = hasOpenSSL(4, 0) ? + 'ERR_SSL_TLS_ALERT_HANDSHAKE_FAILURE' : hasOpenSSL(3, 2) ? + 'ERR_SSL_SSL/TLS_ALERT_HANDSHAKE_FAILURE' : + 'ERR_SSL_SSLV3_ALERT_HANDSHAKE_FAILURE'; + +const idleTimeout = common.platformTimeout(60_000); + +const serverOptions = { + key: fixtures.readKey('rsa_private.pem'), + cert: fixtures.readKey('rsa_cert.crt'), +}; + +for (const allowRenegotiation of [null, 0, 'false', {}]) { + const expected = { code: 'ERR_INVALID_ARG_TYPE' }; + assert.throws(() => tls.createServer({ allowRenegotiation }), expected); + assert.throws(() => tls.connect({ port: 1, allowRenegotiation }), expected); +} + +function connect(server, options, onSecure) { + const client = tls.connect({ + port: server.address().port, + rejectUnauthorized: false, + ...options, + }, () => onSecure(client)); + client.on('close', common.mustCall(() => server.close())); +} + +// A side that does not allow renegotiation cannot start one itself. +function assertCannotRenegotiate(socket) { + assert.strictEqual(socket.renegotiate({}, common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_TLS_RENEGOTIATION_DISABLED'); + })), false); +} + +// A server that does not allow renegotiation refuses the client's attempt, and +// the attempt leaves the server's side of the connection as it was. +function testServerRefuses({ disableRenegotiation }) { + const server = tls.createServer({ + ...serverOptions, + allowRenegotiation: false, + }, common.mustCall((socket) => { + socket.setTimeout(idleTimeout); + // Has no effect: the attempt is refused without an error on this side. + if (disableRenegotiation) socket.disableRenegotiation(); + assertCannotRenegotiate(socket); + socket.on('secure', common.mustNotCall('renegotiation completed')); + // The client gives up on the connection once its attempt is refused. + socket.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, handshakeFailure); + assert.strictEqual(socket.timeout, idleTimeout); + socket.destroy(); + })); + })); + + server.listen(0, common.mustCall(() => { + connect(server, {}, common.mustCall((client) => { + client.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_SSL_NO_RENEGOTIATION'); + client.destroy(); + })); + client.on('secure', common.mustNotCall('renegotiation completed')); + assert.strictEqual(client.renegotiate({}), true); + })); + })); +} + +// A client that does not allow renegotiation refuses the server's request. +function testClientRefuses() { + const server = tls.createServer(serverOptions, common.mustCall((socket) => { + socket.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, 'ERR_SSL_NO_RENEGOTIATION'); + socket.destroy(); + })); + socket.on('secure', common.mustNotCall('renegotiation completed')); + assert.strictEqual(socket.renegotiate({}), true); + })); + + server.listen(0, common.mustCall(() => { + connect(server, { allowRenegotiation: false }, common.mustCall((client) => { + client.setTimeout(idleTimeout); + assertCannotRenegotiate(client); + client.on('secure', common.mustNotCall('renegotiation completed')); + // The server gives up on the connection once its request is refused. + client.on('error', common.mustCall((err) => { + assert.strictEqual(err.code, handshakeFailure); + assert.strictEqual(client.timeout, idleTimeout); + client.destroy(); + })); + })); + })); +} + +function testAllowed() { + const server = tls.createServer({ + ...serverOptions, + allowRenegotiation: true, + }, common.mustCall((socket) => socket.resume())); + + server.listen(0, common.mustCall(() => { + connect(server, { allowRenegotiation: true }, common.mustCall((client) => { + assert.strictEqual(client.renegotiate({}, common.mustSucceed(() => { + client.end(); + })), true); + })); + })); +} + +testServerRefuses({ disableRenegotiation: false }); +testServerRefuses({ disableRenegotiation: true }); +testClientRefuses(); +testAllowed(); diff --git a/test/parallel/test-tls-autoselectfamily-servername.js b/test/parallel/test-tls-autoselectfamily-servername.js new file mode 100644 index 000000000000..f6306e06a911 --- /dev/null +++ b/test/parallel/test-tls-autoselectfamily-servername.js @@ -0,0 +1,38 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const { connect, createServer } = require('tls'); +const { createMockedLookup } = require('../common/dns'); +const fixtures = require('../common/fixtures'); + +const key = fixtures.readKey('agent1-key.pem'); +const cert = fixtures.readKey('agent1-cert.pem'); +const ca = fixtures.readKey('ca1-cert.pem'); +const servername = 'agent1'; + +for (const autoSelectFamily of [false, true]) { + const server = createServer({ key, cert }, common.mustCall((peer) => { + assert.strictEqual(peer.servername, servername); + peer.end(); + server.close(); + })); + + server.listen(0, '127.0.0.1', common.mustCall(() => { + // The server only listens on IPv4. Falling back from IPv6 replaces the + // client's TCP handle, which must preserve the TLS server name. + const lookup = autoSelectFamily ? + createMockedLookup('::1', '127.0.0.1') : createMockedLookup('127.0.0.1'); + const socket = connect({ + host: servername, + port: server.address().port, + servername, + ca, + autoSelectFamily, + lookup, + }, common.mustCall(() => socket.end())); + })); +} diff --git a/test/parallel/test-tls-client-error-close.js b/test/parallel/test-tls-client-error-close.js new file mode 100644 index 000000000000..d96ce760dec0 --- /dev/null +++ b/test/parallel/test-tls-client-error-close.js @@ -0,0 +1,42 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const net = require('net'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +const server = tls.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), +}, common.mustNotCall()); + +server.on('tlsClientError', common.mustCall((err, socket) => { + assert.match(err.code, /^ERR_SSL_/); + assert(socket.destroyed); + // Connection details must remain available while handling the error. + assert.strictEqual(socket.remoteAddress, '127.0.0.1'); + assert.strictEqual(socket.remoteFamily, 'IPv4'); + assert(socket.remotePort > 0); + socket.on('close', common.mustCall(() => { + // The SSL state has been freed before close listeners run. + assert.strictEqual(socket.getProtocol(), null); + server.close(common.mustCall()); + })); +})); + +server.listen(0, '127.0.0.1', common.mustCall(() => { + const client = net.connect(server.address().port, '127.0.0.1'); + client.on('connect', common.mustCall(() => { + // Reject the handshake without a TLS client. + client.write(Buffer.alloc(64, 42)); + })); + client.on('error', common.mustCallAtLeast((err) => { + assert.strictEqual(err.code, 'ECONNRESET'); + }, 0)); + client.on('close', common.mustCall()); + client.resume(); +})); diff --git a/test/parallel/test-tls-fatal-error-close.js b/test/parallel/test-tls-fatal-error-close.js new file mode 100644 index 000000000000..6530c4ac9846 --- /dev/null +++ b/test/parallel/test-tls-fatal-error-close.js @@ -0,0 +1,59 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const net = require('net'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +const server = tls.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), + minVersion: 'TLSv1.3', + maxVersion: 'TLSv1.3', +}, common.mustCall((socket) => { + const remotePort = socket.remotePort; + let errorEmitted = false; + socket.on('error', common.mustCall((err) => { + assert.match(err.code, /^ERR_SSL_/); + assert(socket.destroyed); + assert.strictEqual(socket.errored, err); + // Destroy the socket while preserving connection details for this handler. + assert.strictEqual(socket.remoteAddress, '127.0.0.1'); + assert.strictEqual(socket.remoteFamily, 'IPv4'); + assert.strictEqual(socket.remotePort, remotePort); + assert.strictEqual(socket.getProtocol(), 'TLSv1.3'); + errorEmitted = true; + })); + socket.on('close', common.mustCall(() => { + assert(errorEmitted); + assert(socket.destroyed); + assert.strictEqual(socket.getProtocol(), null); + client.destroy(); + server.close(common.mustCall()); + })); +})); +server.on('tlsClientError', common.mustNotCall()); + +let client; +server.listen(0, '127.0.0.1', common.mustCall(() => { + const transport = net.connect(server.address().port, '127.0.0.1'); + client = tls.connect({ + socket: transport, + rejectUnauthorized: false, + minVersion: 'TLSv1.3', + maxVersion: 'TLSv1.3', + }); + client.on('error', () => {}); + client.on('close', common.mustCall()); + server.once('secureConnection', common.mustCall(() => { + // Corrupt an application-data record without closing the TCP connection. + // The server must close on the TLS error without application cleanup. + const record = Buffer.alloc(37); + record.set([23, 3, 3, 0, 32]); + transport.write(record); + })); +})); diff --git a/test/parallel/test-tls-handshake-complete-after-destroy-newsession.js b/test/parallel/test-tls-handshake-complete-after-destroy-newsession.js new file mode 100644 index 000000000000..51232c4d6783 --- /dev/null +++ b/test/parallel/test-tls-handshake-complete-after-destroy-newsession.js @@ -0,0 +1,76 @@ +'use strict'; + +// A socket that failed during the handshake does not complete it when the +// callback of the `newSession` event is called afterwards. + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const net = require('net'); +const tls = require('tls'); +const { constants } = require('crypto'); +const fixtures = require('../common/fixtures'); + +const key = fixtures.readKey('agent1-key.pem'); +const cert = fixtures.readKey('agent1-cert.pem'); + +const server = tls.createServer({ + key, + cert, + maxVersion: 'TLSv1.2', + secureOptions: constants.SSL_OP_NO_TICKET, +}); + +// An invalid TLS record is appended to the client chunk that follows the +// ClientHello, which is expected to carry ClientKeyExchange, ChangeCipherSpec +// and Finished in a single `data` event. The server then fails with a TLS +// error after it has requested the callback of the `newSession` event. +const invalidRecord = Buffer.from([0x17, 0x03, 0x03, 0x00, 0x05, 1, 2, 3, 4, 5]); +const proxy = net.createServer(common.mustCall((downstream) => { + const upstream = net.connect(server.address().port); + let first = true; + let injected = false; + downstream.on('data', (chunk) => { + // Handshake records have the content type 0x16. + if (!first && !injected && chunk[0] === 0x16) { + injected = true; + chunk = Buffer.concat([chunk, invalidRecord]); + } + first = false; + upstream.write(chunk); + }); + upstream.pipe(downstream); + downstream.on('error', () => {}); + upstream.on('error', () => {}); + downstream.on('close', () => upstream.destroy()); + upstream.on('close', () => downstream.destroy()); +})); + +let done; +server.on('secureConnection', common.mustNotCall()); +server.on('newSession', common.mustCall((id, data, callback) => { + done = callback; +})); +server.on('tlsClientError', common.mustCall((err, socket) => { + assert.ok(socket.destroyed); + socket.on('secure', common.mustNotCall()); + done(); + setImmediate(common.mustCall(() => { + proxy.close(); + server.close(); + })); +})); + +server.listen(0, common.mustCall(() => { + proxy.listen(0, common.mustCall(() => { + const client = tls.connect({ + port: proxy.address().port, + maxVersion: 'TLSv1.2', + secureOptions: constants.SSL_OP_NO_TICKET, + rejectUnauthorized: false, + }); + client.on('error', () => {}); + })); +})); diff --git a/test/parallel/test-tls-negative-zero.js b/test/parallel/test-tls-negative-zero.js new file mode 100644 index 000000000000..b4b9237920dd --- /dev/null +++ b/test/parallel/test-tls-negative-zero.js @@ -0,0 +1,9 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const tls = require('tls'); + +tls.createSecureContext({ sessionTimeout: -0 }); diff --git a/test/parallel/test-tls-ocsp-request-sni-without-certificate.js b/test/parallel/test-tls-ocsp-request-sni-without-certificate.js new file mode 100644 index 000000000000..e1e1f50a87e6 --- /dev/null +++ b/test/parallel/test-tls-ocsp-request-sni-without-certificate.js @@ -0,0 +1,46 @@ +'use strict'; + +// The OCSPRequest event reports the certificate that the connection uses, +// also when the SNI context only carries a CA. + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +const key = fixtures.readKey('agent1-key.pem'); +const cert = fixtures.readKey('agent1-cert.pem'); +const ca = fixtures.readKey('ca1-cert.pem'); + +const server = tls.createServer({ + key, + cert, + SNICallback: common.mustCall((servername, callback) => { + callback(null, tls.createSecureContext({ ca })); + }), +}); + +server.on('OCSPRequest', common.mustCall((certificate, issuer, callback) => { + assert.deepStrictEqual( + certificate, + new crypto.X509Certificate(cert).raw); + callback(null, null); +})); + +server.listen(0, common.mustCall(() => { + const client = tls.connect({ + port: server.address().port, + servername: 'sni.example.com', + requestOCSP: true, + rejectUnauthorized: false, + }); + + client.on('OCSPResponse', common.mustCall(() => { + client.destroy(); + server.close(); + })); +})); diff --git a/test/parallel/test-tls-onread-buffer-lifetime.js b/test/parallel/test-tls-onread-buffer-lifetime.js new file mode 100644 index 000000000000..a04c4fd0df5c --- /dev/null +++ b/test/parallel/test-tls-onread-buffer-lifetime.js @@ -0,0 +1,141 @@ +// Flags: --js-immutable-arraybuffer +'use strict'; + +// TLS reads must not modify an immutable ArrayBuffer created by transferring a +// registered onread buffer. + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const fixtures = require('../common/fixtures'); +const assert = require('node:assert'); +const { once } = require('node:events'); +const { test } = require('node:test'); +const tls = require('node:tls'); + +const options = { + key: fixtures.readKey('agent2-key.pem'), + cert: fixtures.readKey('agent2-cert.pem'), +}; + +for (const mode of ['before first read', 'between reads', 'replacement buffer']) { + test(`tls onread buffer transferred ${mode}`, async (t) => { + const backing = new ArrayBuffer(8); + new Uint8Array(backing).fill(42); + const buffer = mode === 'replacement buffer' ? + Buffer.from(backing, 2, 4) : new Uint8Array(backing, 2, 4); + const firstBuffer = new Uint8Array(1); + const connections = new Set(); + let peer; + let socket; + let immutable; + let expected; + let factoryCalls = 0; + let readError; + const closed = Promise.withResolvers(); + + const server = tls.createServer(options, common.mustCall((connection) => { + peer = connection; + connections.add(connection); + connection.on('close', () => connections.delete(connection)); + connection.on('error', (error) => { + if (error.code !== 'ECONNRESET') throw error; + }); + if (mode === 'before first read') { + connection.end('test'); + } else { + connection.write('a'); + } + })); + server.on('connection', (connection) => { + connections.add(connection); + connection.on('close', () => connections.delete(connection)); + }); + t.after(async () => { + socket?.destroy(); + for (const connection of connections) connection.destroy(); + if (server.listening) { + await new Promise((resolve) => server.close(resolve)); + } + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + + function transfer() { + expected = [...new Uint8Array(backing)]; + immutable = backing.transferToImmutable(); + assert.strictEqual(buffer.byteLength, 0); + assert.strictEqual(immutable.immutable, true); + } + + socket = tls.connect({ + host: '127.0.0.1', + port: server.address().port, + rejectUnauthorized: false, + onread: { + buffer: mode === 'replacement buffer' ? common.mustCall(() => { + return ++factoryCalls === 1 ? firstBuffer : buffer; + }, 2) : buffer, + callback: common.mustCall((nread, view) => { + try { + if (immutable !== undefined) { + assert.deepStrictEqual([...new Uint8Array(immutable)], expected); + assert.fail('onread called after the buffer was transferred'); + } + assert.strictEqual(nread, 1); + assert.strictEqual(view, mode === 'replacement buffer' ? firstBuffer : buffer); + assert.strictEqual(view[0], 97); + // Transfer after onStreamRead checks for detachment and registers + // any replacement buffer returned by the factory. + setImmediate(common.mustCall(() => { + transfer(); + peer.end('test'); + })); + } catch (error) { + closed.reject(error); + return false; + } + }, mode === 'before first read' ? 0 : 1), + }, + }); + socket.on('data', common.mustNotCall()); + socket.on('end', common.mustNotCall()); + socket.on('error', common.mustCall((error) => { + readError = error; + })); + socket.on('close', common.mustCall(closed.resolve)); + if (mode === 'before first read') transfer(); + assert.strictEqual(await closed.promise, true); + assert.strictEqual(readError.code, 'EINVAL'); + assert.strictEqual(readError.syscall, 'read'); + assert.deepStrictEqual([...new Uint8Array(immutable)], expected); + }); +} + +test('empty TLS onread buffer reports ENOBUFS', async (t) => { + let socket; + const server = tls.createServer(options, common.mustCall((connection) => { + connection.on('error', (error) => { + if (error.code !== 'ECONNRESET') throw error; + }); + connection.end('test'); + })); + t.after(async () => { + socket?.destroy(); + await new Promise((resolve) => server.close(resolve)); + }); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + + socket = tls.connect({ + host: '127.0.0.1', + port: server.address().port, + rejectUnauthorized: false, + onread: { buffer: new Uint8Array(0), callback: common.mustNotCall() }, + }); + await assert.rejects(once(socket, 'close'), { + code: 'ENOBUFS', + syscall: 'read', + }); +}); diff --git a/test/parallel/test-tls-renegotiation-pending-deprecation.js b/test/parallel/test-tls-renegotiation-pending-deprecation.js new file mode 100644 index 000000000000..f8f692299cd2 --- /dev/null +++ b/test/parallel/test-tls-renegotiation-pending-deprecation.js @@ -0,0 +1,106 @@ +'use strict'; + +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const { isBoringSSL } = require('../common/crypto'); +if (isBoringSSL) + common.skip('BoringSSL does not support renegotiation'); + +// With --pending-deprecation, renegotiation emits a deprecation warning unless +// it is a client that set allowRenegotiation: true accepting a server's request. + +const assert = require('assert'); +const { fork } = require('child_process'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +tls.DEFAULT_MAX_VERSION = 'TLSv1.2'; + +const serverOptions = { + key: fixtures.readKey('rsa_private.pem'), + cert: fixtures.readKey('rsa_cert.crt'), +}; + +// The endpoint under test runs in a child process, as the warning is emitted +// once per process and the peer would otherwise emit it too. +if (process.argv[2] === 'child') { + const { role, allowRenegotiation, initiate, port } = + JSON.parse(process.argv[3]); + + if (role === 'server') { + const server = tls.createServer({ + ...serverOptions, + allowRenegotiation, + }, common.mustCall((socket) => { + socket.resume(); + socket.on('close', common.mustCall(() => server.close())); + })); + server.listen(0, common.mustCall(() => { + process.send({ port: server.address().port }); + })); + } else { + const client = tls.connect({ + port, + rejectUnauthorized: false, + allowRenegotiation, + }, common.mustCall(() => { + if (initiate) + client.renegotiate({}, common.mustSucceed(() => client.end())); + })); + client.resume(); + } + return; +} + +function start(options, warns) { + const child = fork(__filename, ['child', JSON.stringify(options)], { + execArgv: ['--pending-deprecation'], + stdio: ['ignore', 'inherit', 'pipe', 'ipc'], + }); + let stderr = ''; + child.stderr.setEncoding('utf8'); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.on('close', common.mustCall((code) => { + assert.strictEqual(code, 0, stderr); + assert.strictEqual( + stderr.includes('[DEP0213] DeprecationWarning: TLS renegotiation'), + warns, + stderr); + })); + return child; +} + +function testServer(options, warns) { + const child = start({ role: 'server', ...options }, warns); + child.on('message', common.mustCall(({ port }) => { + const client = tls.connect({ + port, + rejectUnauthorized: false, + }, common.mustCall(() => { + client.renegotiate({}, common.mustSucceed(() => client.end())); + })); + client.resume(); + })); +} + +function testClient(options, warns) { + const server = tls.createServer(serverOptions, common.mustCall((socket) => { + socket.resume(); + socket.on('close', common.mustCall(() => server.close())); + if (!options.initiate) + socket.renegotiate({}, common.mustSucceed(() => socket.end())); + })); + server.listen(0, common.mustCall(() => { + start({ role: 'client', port: server.address().port, ...options }, warns); + })); +} + +// A server completing a renegotiation, whether or not it set the option. +testServer({ allowRenegotiation: true }, true); +// Any call to renegotiate(). +testClient({ allowRenegotiation: true, initiate: true }, true); +// A client accepting the server's request, unless it set the option. +testClient({ initiate: false }, true); +testClient({ allowRenegotiation: true, initiate: false }, false); diff --git a/test/parallel/test-tls-session-arraybuffer-view.js b/test/parallel/test-tls-session-arraybuffer-view.js new file mode 100644 index 000000000000..2853c7a2239e --- /dev/null +++ b/test/parallel/test-tls-session-arraybuffer-view.js @@ -0,0 +1,127 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const { once } = require('events'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +async function connect(options, useSetter = false, captureSession = false) { + const { session, ...connectOptions } = options; + const socket = tls.connect(useSetter ? connectOptions : options); + const closed = new Promise((resolve) => { + socket.once('close', common.mustCall(resolve)); + }); + if (useSetter) + socket.setSession(session); + const sessionPromise = captureSession ? once(socket, 'session') : undefined; + socket.resume(); + + try { + await once(socket, 'secureConnect'); + const result = { + reused: socket.isSessionReused(), + authorized: socket.authorized, + session: captureSession ? (await sessionPromise)[0] : undefined, + }; + await closed; + return result; + } finally { + socket.destroy(); + } +} + +function offsetView(session, View) { + // Keep unrelated bytes on both sides to check that only the view is used. + const buffer = new ArrayBuffer(session.length + 16); + new Uint8Array(buffer).fill(0xff); + new Uint8Array(buffer, 8, session.length).set(session); + return new View(buffer, 8, session.length); +} + +async function testVersion(version) { + const server = tls.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), + minVersion: version, + maxVersion: version, + }, (socket) => socket.end('ok')); + server.listen(0); + await once(server, 'listening'); + + try { + const options = { + port: server.address().port, + host: '127.0.0.1', + servername: 'agent1', + ca: fixtures.readKey('ca1-cert.pem'), + minVersion: version, + maxVersion: version, + }; + const first = await connect(options, false, true); + assert.strictEqual(first.authorized, true); + assert.strictEqual(first.reused, false); + + const tagged = first.session; + const prefix = Buffer.from('\0nodejs:tls:session:1\0'); + assert.deepStrictEqual(tagged.subarray(0, prefix.length), prefix); + const raw = tagged.subarray( + prefix.length + 2 + tagged.readUInt16BE(prefix.length)); + + const conversions = [ + (session) => session, + (session) => session.toString('latin1'), + (session) => new Uint8Array(session), + (session) => new Uint8ClampedArray(session), + (session) => new Int8Array(session), + (session) => offsetView(session, Uint8Array), + (session) => offsetView(session, DataView), + ]; + + for (const convert of conversions) { + for (const useSetter of [false, true]) { + // Untagged sessions must cause a full handshake on verified clients. + const fresh = await connect({ + ...options, + session: convert(raw), + }, useSetter); + assert.strictEqual(fresh.authorized, true); + assert.strictEqual(fresh.reused, false); + + // A tagged session still resumes for its authenticated host. + const resumed = await connect({ + ...options, + session: convert(tagged), + }, useSetter); + assert.strictEqual(resumed.authorized, true); + assert.strictEqual(resumed.reused, true); + + for (const session of [raw, tagged]) { + await assert.rejects(connect({ + ...options, + servername: 'bank.example', + session: convert(session), + }, useSetter), { code: 'ERR_TLS_CERT_ALTNAME_INVALID' }); + } + + // Raw sessions remain usable when verification is explicitly disabled. + const unverified = await connect({ + ...options, + session: convert(raw), + rejectUnauthorized: false, + }, useSetter); + assert.strictEqual(unverified.reused, true); + } + } + } finally { + server.close(); + await once(server, 'close'); + } +} + +(async () => { + await testVersion('TLSv1.2'); + await testVersion('TLSv1.3'); +})().then(common.mustCall()); diff --git a/test/parallel/test-tls-small-read-own-buffer.js b/test/parallel/test-tls-small-read-own-buffer.js new file mode 100644 index 000000000000..cc65e92f7360 --- /dev/null +++ b/test/parallel/test-tls-small-read-own-buffer.js @@ -0,0 +1,46 @@ +'use strict'; +const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + +// Small TLS reads must not be views over a larger shared buffer: JS keeping +// one of them would keep the whole buffer, and every other read in it, alive. + +const assert = require('assert'); +const tls = require('tls'); +const fixtures = require('../common/fixtures'); + +const kBlock = 320; +const kBlocks = 3; + +const server = tls.createServer({ + key: fixtures.readKey('agent1-key.pem'), + cert: fixtures.readKey('agent1-cert.pem'), +}, common.mustCall((socket) => { + let received = 0; + socket.on('data', common.mustCallAtLeast((chunk) => { + assert.strictEqual(chunk.byteOffset, 0); + assert.strictEqual(chunk.buffer.byteLength, chunk.length); + received += chunk.length; + if (received === kBlocks * kBlock) { + socket.end(); + server.close(); + } else if (received % kBlock === 0) { + // Ask for the next block only once this one has arrived, so that each + // block is a separate small read. + socket.write('n'); + } + })); +})); + +server.listen(0, common.mustCall(() => { + const client = tls.connect({ + port: server.address().port, + rejectUnauthorized: false, + }, common.mustCall(() => { + client.write(Buffer.alloc(kBlock)); + })); + client.on('data', common.mustCall(() => { + client.write(Buffer.alloc(kBlock)); + }, kBlocks - 1)); +})); diff --git a/test/parallel/test-tls-socket-invalid-session.js b/test/parallel/test-tls-socket-invalid-session.js new file mode 100644 index 000000000000..09685ef745a2 --- /dev/null +++ b/test/parallel/test-tls-socket-invalid-session.js @@ -0,0 +1,27 @@ +'use strict'; +const common = require('../common'); + +if (!common.hasCrypto) + common.skip('missing crypto'); + +const assert = require('assert'); +const crypto = require('crypto'); +const tls = require('tls'); + +// A session that fails to deserialize must not leave an error on the OpenSSL +// error queue for the next unrelated crypto operation to pick up. + +const badKey = '-----BEGIN PRIVATE KEY-----\nAAAA\n-----END PRIVATE KEY-----'; + +function keyErrorCode() { + try { + crypto.createPrivateKey(badKey); + } catch (err) { + return err.code; + } + assert.fail('createPrivateKey() should have thrown'); +} + +const expected = keyErrorCode(); +new tls.TLSSocket(null, { session: Buffer.from('invalid session') }); +assert.strictEqual(keyErrorCode(), expected); diff --git a/test/parallel/test-url-urltooptions.js b/test/parallel/test-url-urltooptions.js index 8e7e5dc89409..5df48afe0429 100644 --- a/test/parallel/test-url-urltooptions.js +++ b/test/parallel/test-url-urltooptions.js @@ -36,6 +36,44 @@ assert.strictEqual(copiedOpts.search, undefined); assert.strictEqual(copiedOpts.hash, undefined); assert.strictEqual(copiedOpts.href, undefined); +// A genuine URL instance can still be extended with own enumerable properties +// (e.g. extra request options) and those properties are carried through. +const extendedUrl = new URL('http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test'); +extendedUrl.headers = { foo: 'Bar' }; +extendedUrl.method = 'POST'; +const extendedOpts = urlToHttpOptions(extendedUrl); +assert.deepStrictEqual(extendedOpts.headers, { foo: 'Bar' }); +assert.strictEqual(extendedOpts.method, 'POST'); + +// A duck-typed object that satisfies `isURL()` (truthy `href` and `protocol`, +// `auth`/`path` absent) must not be able to smuggle transport/connection +// options (e.g. `socketPath`) into the request options. Only genuine WHATWG +// URL instances may carry additional own enumerable properties. +const duckTypedUrl = { + href: 'http://safe-webhook.com/verify', + protocol: 'http:', + hostname: 'safe-webhook.com', + pathname: '/v1.41/version', + port: '', + username: '', + password: '', + search: '', + hash: '', + socketPath: '/var/run/docker.sock', + method: 'GET', + headers: { 'Content-Type': 'application/json' }, + agent: false, +}; +const duckTypedOpts = urlToHttpOptions(duckTypedUrl); +assert.strictEqual(duckTypedOpts.socketPath, undefined); +assert.strictEqual(duckTypedOpts.method, undefined); +assert.strictEqual(duckTypedOpts.headers, undefined); +assert.strictEqual(duckTypedOpts.agent, undefined); +// URL-derived fields are still populated from the duck-typed object. +assert.strictEqual(duckTypedOpts.hostname, 'safe-webhook.com'); +assert.strictEqual(duckTypedOpts.path, '/v1.41/version'); +assert.strictEqual(duckTypedOpts.protocol, 'http:'); + // Test when passed an invalid argument assert.throws(() => { urlToHttpOptions('http://127.0.0.1'); diff --git a/test/parallel/test-util-debounce.js b/test/parallel/test-util-debounce.js index 15d93e610418..3e47deea6c32 100644 --- a/test/parallel/test-util-debounce.js +++ b/test/parallel/test-util-debounce.js @@ -4,10 +4,15 @@ const common = require('../common'); const assert = require('node:assert'); const { createHook } = require('node:async_hooks'); +const { getEventListeners } = require('node:events'); const { setTimeout } = require('node:timers/promises'); const { debounce } = require('node:util'); const { TIMEOUT_MAX } = require('internal/timers'); +function abortListenerCount(signal) { + return getEventListeners(signal, 'abort').length; +} + for (const value of [undefined, null, true, 0, 'fn', {}, [], Symbol()]) { assert.throws(() => debounce(value, 1), { code: 'ERR_INVALID_ARG_TYPE', @@ -320,6 +325,41 @@ assert.throws(() => debounce(() => {}, 1, { signal: {} }), { assert.strictEqual(await result, 1); } + { + const { signal } = new AbortController(); + const debounced = debounce(common.mustCall((value) => value, 2), 1, { + signal, + }); + assert.strictEqual(abortListenerCount(signal), 0); + const first = debounced(1); + assert.strictEqual(abortListenerCount(signal), 1); + assert.strictEqual(await first, 1); + assert.strictEqual(abortListenerCount(signal), 0); + + const second = debounced(2); + debounced.flush(); + assert.strictEqual(abortListenerCount(signal), 0); + assert.strictEqual(await second, 2); + + const third = debounced(3); + debounced.cancel(); + assert.strictEqual(abortListenerCount(signal), 0); + await assert.rejects(third, { code: 'ABORT_ERR' }); + } + + { + const { signal } = new AbortController(); + const debounced = debounce(common.mustCall((value) => value), 10, { + leading: true, + signal, + }); + assert.strictEqual(await debounced(1), 1); + // The leading call keeps the listener until the wait is over. + assert.strictEqual(abortListenerCount(signal), 1); + await setTimeout(20); + assert.strictEqual(abortListenerCount(signal), 0); + } + { const debounced = debounce(common.mustCall((value) => value), 1); assert.strictEqual(await debounced(42), 42); diff --git a/test/parallel/test-util-throttle.js b/test/parallel/test-util-throttle.js index b22fb4630e7e..f03c5ef0da7d 100644 --- a/test/parallel/test-util-throttle.js +++ b/test/parallel/test-util-throttle.js @@ -4,10 +4,15 @@ const common = require('../common'); const assert = require('node:assert'); const { createHook } = require('node:async_hooks'); +const { getEventListeners } = require('node:events'); const { setImmediate } = require('node:timers/promises'); const { throttle } = require('node:util'); const { TIMEOUT_MAX } = require('internal/timers'); +function abortListenerCount(signal) { + return getEventListeners(signal, 'abort').length; +} + process.on('unhandledRejection', common.mustNotCall()); for (const value of [undefined, null, true, 0, 'fn', {}, [], Symbol()]) { @@ -257,6 +262,47 @@ throttle(() => {}, 1, 1, { ); } + { + const { signal } = new AbortController(); + const throttled = throttle(common.mustCall((value) => value, 2), 1, 10, { + signal, + }); + assert.strictEqual(abortListenerCount(signal), 0); + const first = throttled(1); + assert.strictEqual(abortListenerCount(signal), 0); + const second = throttled(2); + assert.strictEqual(abortListenerCount(signal), 1); + assert.deepStrictEqual(await Promise.all([first, second]), [1, 2]); + assert.strictEqual(abortListenerCount(signal), 0); + } + + { + const { signal } = new AbortController(); + const throttled = throttle(common.mustCall(), 1, TIMEOUT_MAX, { signal }); + throttled(); + const queued = throttled(); + assert.strictEqual(abortListenerCount(signal), 1); + throttled.cancel(); + assert.strictEqual(abortListenerCount(signal), 0); + await assert.rejects(queued, { code: 'ABORT_ERR' }); + } + + { + // Calls waiting on concurrency are queued too, so they keep the listener. + const { signal } = new AbortController(); + const { promise, resolve } = Promise.withResolvers(); + const throttled = throttle(common.mustCall(() => promise, 2), 2, TIMEOUT_MAX, { + concurrency: 1, + signal, + }); + const first = throttled(); + const second = throttled(); + assert.strictEqual(abortListenerCount(signal), 1); + resolve(); + await Promise.all([first, second]); + assert.strictEqual(abortListenerCount(signal), 0); + } + { const expected = new Error('failure'); const throttled = throttle(common.mustCall((value) => { diff --git a/test/parallel/test-v8-collect-gc-profile-minor-ms.js b/test/parallel/test-v8-collect-gc-profile-minor-ms.js index 1f00470da6c1..848caeb733a1 100644 --- a/test/parallel/test-v8-collect-gc-profile-minor-ms.js +++ b/test/parallel/test-v8-collect-gc-profile-minor-ms.js @@ -10,7 +10,7 @@ profiler.start(); global.gc({ type: 'minor', execution: 'sync' }); const profile = profiler.stop(); -assert.deepStrictEqual( +assert.partialDeepStrictEqual( profile.statistics.map(({ gcType }) => gcType), ['MinorMarkSweep'], ); diff --git a/test/parallel/test-vfs-fs-readv-writev.js b/test/parallel/test-vfs-fs-readv-writev.js new file mode 100644 index 000000000000..9e4bd1427bc5 --- /dev/null +++ b/test/parallel/test-vfs-fs-readv-writev.js @@ -0,0 +1,35 @@ +// Flags: --experimental-vfs +'use strict'; + +const common = require('../common'); +const assert = require('node:assert'); +const fs = require('node:fs'); +const path = require('node:path'); +const tmpdir = require('../common/tmpdir'); +const vfs = require('node:vfs'); + +tmpdir.refresh(); +const mounted = vfs.create(); +mounted.mkdirSync('/files', { recursive: true }); +const mountPoint = mounted.mount(); + +const realFd = fs.openSync(tmpdir.resolve('real.txt'), 'w+'); +const virtualFd = fs.openSync(path.join(mountPoint, 'files/virtual.txt'), 'w+'); +let remaining = 2; + +for (const fd of [realFd, virtualFd]) { + const chunks = [Buffer.from('hello'), Buffer.from('world')]; + fs.writev(fd, chunks, null, common.mustSucceed((bytesWritten, buffers) => { + assert.strictEqual(bytesWritten, 10); + assert.strictEqual(buffers, chunks); + + const received = [Buffer.alloc(5), Buffer.alloc(5)]; + fs.readv(fd, received, 0, common.mustSucceed((bytesRead, readBuffers) => { + assert.strictEqual(bytesRead, 10); + assert.strictEqual(readBuffers, received); + assert.strictEqual(Buffer.concat(received).toString(), 'helloworld'); + fs.closeSync(fd); + if (--remaining === 0) mounted.unmount(); + })); + })); +} diff --git a/test/parallel/test-vfs-real-provider-promises.js b/test/parallel/test-vfs-real-provider-promises.js index 21ff7533993c..3822a718db5a 100644 --- a/test/parallel/test-vfs-real-provider-promises.js +++ b/test/parallel/test-vfs-real-provider-promises.js @@ -35,6 +35,19 @@ const myVfs = vfs.create(new vfs.RealFSProvider(root)); assert.deepStrictEqual(entries.sort(), ['sub']); await myVfs.promises.rmdir('/d/sub'); + // Recursive mkdir returns the first directory created, as a VFS-relative + // path (never the backing-directory path), matching MemoryProvider. + const createdSub = await myVfs.promises.mkdir('/d/sub', { recursive: true }); + assert.strictEqual(createdSub, '/d/sub'); + assert.strictEqual(await myVfs.promises.mkdir('/d/sub', { recursive: true }), + undefined); + const created = await myVfs.promises.mkdir('/d/deep/nested', { recursive: true }); + assert.strictEqual(created, '/d/deep'); + assert.strictEqual(myVfs.existsSync(created), true); + await myVfs.promises.rmdir('/d/sub'); + await myVfs.promises.rmdir('/d/deep/nested'); + await myVfs.promises.rmdir('/d/deep'); + // rename await myVfs.promises.writeFile('/old.txt', 'x'); await myVfs.promises.rename('/old.txt', '/new.txt'); diff --git a/test/parallel/test-vfs-real-provider.js b/test/parallel/test-vfs-real-provider.js index 6ddba52aa73f..f8e6ae31be38 100644 --- a/test/parallel/test-vfs-real-provider.js +++ b/test/parallel/test-vfs-real-provider.js @@ -7,7 +7,7 @@ // test-vfs-real-provider-handle.js, and symlinks/path-escape live in // test-vfs-real-provider-symlinks.js. -require('../common'); +const common = require('../common'); const tmpdir = require('../common/tmpdir'); const assert = require('assert'); const fs = require('fs'); @@ -106,6 +106,49 @@ fs.mkdirSync(testDir, { recursive: true }); fs.rmdirSync(path.join(testDir, 'deep/nested/dir')); fs.rmdirSync(path.join(testDir, 'deep/nested')); fs.rmdirSync(path.join(testDir, 'deep')); + + // Recursive mkdir returns the first directory created, as a VFS-relative + // path (never the backing-directory path), matching MemoryProvider. + const created = realVfs.mkdirSync('/returned/nested/dir', { recursive: true }); + assert.strictEqual(created, '/returned'); + assert.strictEqual(realVfs.existsSync(created), true); + assert.strictEqual( + realVfs.mkdirSync('/returned/nested/dir', { recursive: true }), + undefined, + ); + assert.strictEqual(realVfs.mkdirSync('/returned/new-dir'), + undefined); + fs.rmdirSync(path.join(testDir, 'returned/nested/dir')); + fs.rmdirSync(path.join(testDir, 'returned/nested')); + fs.rmdirSync(path.join(testDir, 'returned/new-dir')); + fs.rmdirSync(path.join(testDir, 'returned')); +} + +// Mounted recursive mkdir returns a path that exists on the real filesystem. +{ + const realVfs = vfs.create(new vfs.RealFSProvider(testDir)); + const mountPoint = realVfs.mount(); + try { + const created = realVfs.mkdirSync(path.join(mountPoint, 'm/nested/dir'), + { recursive: true }); + assert.strictEqual(created, path.join(mountPoint, 'm')); + assert.strictEqual(fs.existsSync(created), true); + } finally { + realVfs.unmount(); + fs.rmSync(path.join(testDir, 'm'), { recursive: true, force: true }); + } +} + +// Recursive mkdir works when the root is given in the Windows long-path +// form, which is what the native bindings hand back: the returned path must +// still be translated relative to the root, not rejected as an escape. +if (common.isWindows) { + const longVfs = vfs.create(new vfs.RealFSProvider( + path.toNamespacedPath(testDir))); + const created = longVfs.mkdirSync('/long/deep/dir', { recursive: true }); + assert.strictEqual(created, '/long'); + assert.strictEqual(longVfs.existsSync('/long/deep/dir'), true); + fs.rmSync(path.join(testDir, 'long'), { recursive: true, force: true }); } // unlink diff --git a/test/parallel/test-webstreams-byte-enqueue-pending-read-requests.js b/test/parallel/test-webstreams-byte-enqueue-pending-read-requests.js new file mode 100644 index 000000000000..d067d23fac1b --- /dev/null +++ b/test/parallel/test-webstreams-byte-enqueue-pending-read-requests.js @@ -0,0 +1,57 @@ +'use strict'; + +// A released BYOB reader's partially filled pull-into is moved to the +// queue on the next enqueue(). If a default reader is waiting with more +// than one read request, the queue must only fill as many read requests +// as it has chunks for, and the newly enqueued chunk must go to the next +// read request. + +const common = require('../common'); +const assert = require('assert'); +const { ReadableStream } = require('stream/web'); + +async function test(numReads) { + let controller; + const rs = new ReadableStream({ + type: 'bytes', + start(c) { + controller = c; + }, + }); + + // Leave a pull-into with 1 of the required 2 bytes filled. + const byobReader = rs.getReader({ mode: 'byob' }); + const byobRead = byobReader.read(new Uint8Array(2), { min: 2 }); + await new Promise(setImmediate); + controller.enqueue(new Uint8Array([1])); + byobReader.releaseLock(); + await assert.rejects(byobRead, { name: 'TypeError' }); + + const reader = rs.getReader(); + const reads = []; + for (let i = 0; i < numReads; i++) { + reads.push(reader.read()); + } + + controller.enqueue(new Uint8Array([2])); + controller.enqueue(new Uint8Array([3])); + controller.close(); + + const results = await Promise.all(reads); + const expected = [[1], [2], [3]].slice(0, numReads); + assert.deepStrictEqual(results.map(({ value }) => [...value]), expected); + + // Chunks that were not read yet are still in the queue. + const rest = []; + for (let result = await reader.read(); !result.done; + result = await reader.read()) { + rest.push(...result.value); + } + assert.deepStrictEqual(rest, [1, 2, 3].slice(numReads)); +} + +(async () => { + for (const numReads of [1, 2, 3]) { + await test(numReads); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-webworker-conditions.js b/test/parallel/test-webworker-conditions.js index 313e3f3d643d..6cf564597eb0 100644 --- a/test/parallel/test-webworker-conditions.js +++ b/test/parallel/test-webworker-conditions.js @@ -70,8 +70,4 @@ function runWebWorker(url, options) { const [threadResult] = await once(thread, 'message'); assert.deepStrictEqual(threadResult, { thread: 'default', webWorker: 'worker' }); - // Async module customization hooks registered from a Web Worker. - assert.strictEqual( - await runWebWorker(new URL('hooks-worker.mjs', base), { type: 'module' }), - 'worker'); })().then(common.mustCall()); diff --git a/test/parallel/test-whatwg-readablestream-pipeto-async-context.js b/test/parallel/test-whatwg-readablestream-pipeto-async-context.js new file mode 100644 index 000000000000..5a096e3097a2 --- /dev/null +++ b/test/parallel/test-whatwg-readablestream-pipeto-async-context.js @@ -0,0 +1,157 @@ +'use strict'; + +// The pipeTo() pump must keep running in the async context of the +// pipeTo() call when it resumes after backpressure or after a chunk +// arrives, instead of taking the context of the code that cleared the +// backpressure or enqueued the chunk. The source pulls and the writes the +// pump issues are checked. + +const common = require('../common'); +const assert = require('assert'); +const { AsyncLocalStorage } = require('async_hooks'); +const { setImmediate: tick } = require('timers/promises'); + +const als = new AsyncLocalStorage(); + +function store() { + return als.getStore() ?? 'none'; +} + +// Settles the pending callbacks from the given context until `promise` +// settles. +async function settleUntil(promise, ctx, pending) { + let finished = false; + promise.then(common.mustCall(() => { finished = true; })); + while (!finished) { + await tick(); + while (pending.length > 0) als.run(ctx, pending.shift()); + } + await promise; +} + +const tests = []; +function test(name, expected, fn) { + tests.push({ name, expected, fn }); +} + +test('sink writes resolved from another context', [ + // The first pull and write follow the source's start step. + 'pull:creator', 'write-1:creator', + 'pull:piper', 'write-2:piper', + 'pull:piper', 'write-3:piper', + 'pull:piper', +], async (seen) => { + let n = 0; + const pending = []; + const rs = als.run('creator', () => new ReadableStream({ + pull(c) { + seen.push(`pull:${store()}`); + if (++n > 3) c.close(); else c.enqueue(n); + }, + }, { highWaterMark: 0 })); + const ws = als.run('creator', () => new WritableStream({ + write(chunk) { + seen.push(`write-${chunk}:${store()}`); + const { promise, resolve } = Promise.withResolvers(); + pending.push(resolve); + return promise; + }, + }, { highWaterMark: 1 })); + await settleUntil(als.run('piper', () => rs.pipeTo(ws)), 'releaser', pending); +}); + +test('push source under backpressure', [ + 'write-a:pusher-a', 'write-b:piper', 'write-c:piper', 'write-d:piper', +], async (seen) => { + let controller; + const pending = []; + const rs = als.run('creator', () => new ReadableStream({ + start(c) { controller = c; }, + }, { highWaterMark: 0 })); + const ws = als.run('creator', () => new WritableStream({ + write(chunk) { + seen.push(`write-${chunk}:${store()}`); + const { promise, resolve } = Promise.withResolvers(); + pending.push(resolve); + return promise; + }, + }, { highWaterMark: 1 })); + const piped = als.run('piper', () => rs.pipeTo(ws)); + await tick(); + for (const chunk of 'abcd') + als.run(`pusher-${chunk}`, () => controller.enqueue(chunk)); + als.run('closer', () => controller.close()); + await settleUntil(piped, 'releaser', pending); +}); + +test('pipeThrough() with pulls resolved from another context', [ + 'pull:piper', 'transform-1:resolver', + 'pull:piper', 'transform-2:resolver', + 'pull:piper', 'transform-3:resolver', + 'pull:piper', +], async (seen) => { + let n = 0; + const pending = []; + const readable = als.run('piper', () => new ReadableStream({ + pull(c) { + seen.push(`pull:${store()}`); + const { promise, resolve } = Promise.withResolvers(); + pending.push(() => { + if (++n > 3) c.close(); else c.enqueue(n); + resolve(); + }); + return promise; + }, + }, { highWaterMark: 0 }).pipeThrough(new TransformStream({ + transform(chunk, c) { + seen.push(`transform-${chunk}:${store()}`); + c.enqueue(chunk); + }, + }))); + const consumed = als.run('reader', async () => { + // eslint-disable-next-line no-unused-vars + for await (const _ of readable); + }); + await settleUntil(consumed, 'resolver', pending); +}); + +test('pipeThrough() chain into a slow sink', [ + 'pull:creator', 't1-1:piper', 't2-1:piper', 'write-1:piper', + 'pull:piper', 't1-2:piper', 't2-2:piper', 'write-2:piper', + 'pull:piper', 't1-3:piper', 't2-3:piper', 'write-3:piper', + 'pull:piper', +], async (seen) => { + let n = 0; + function transform(name) { + return new TransformStream({ + transform(chunk, c) { + seen.push(`${name}-${chunk}:${store()}`); + c.enqueue(chunk); + }, + }); + } + const rs = als.run('creator', () => new ReadableStream({ + pull(c) { + seen.push(`pull:${store()}`); + if (++n > 3) c.close(); else c.enqueue(n); + }, + }, { highWaterMark: 0 })); + const ws = als.run('creator', () => new WritableStream({ + async write(chunk) { + seen.push(`write-${chunk}:${store()}`); + await tick(); + }, + }, { highWaterMark: 1 })); + await als.run('piper', () => rs.pipeThrough(transform('t1')) + .pipeThrough(transform('t2')).pipeTo(ws)); +}); + +(async () => { + for (const { name, expected, fn } of tests) { + const seen = []; + await fn(seen); + // Only the context of each callback is checked, not how the callbacks + // of different streams interleave. + assert.deepStrictEqual(seen.sort(), expected.toSorted(), name); + } +})().then(common.mustCall()); diff --git a/test/parallel/test-whatwg-url-custom-href-side-effect.js b/test/parallel/test-whatwg-url-custom-href-side-effect.js index 30967d9feaef..daecb2a2226f 100644 --- a/test/parallel/test-whatwg-url-custom-href-side-effect.js +++ b/test/parallel/test-whatwg-url-custom-href-side-effect.js @@ -13,3 +13,19 @@ assert.throws(() => { }); assert.deepStrictEqual(url, ref); + +const setHref = Object.getOwnPropertyDescriptor(URL.prototype, 'href').set; +let calls = 0; + +assert.throws(() => { + setHref.call({}, { + toString() { + calls++; + return 'https://example.com/'; + }, + }); +}, { + name: 'TypeError', +}); + +assert.strictEqual(calls, 0); diff --git a/test/parallel/test-whatwg-url-searchparams-parse-no-equals.js b/test/parallel/test-whatwg-url-searchparams-parse-no-equals.js new file mode 100644 index 000000000000..a67a2e7863b8 --- /dev/null +++ b/test/parallel/test-whatwg-url-searchparams-parse-no-equals.js @@ -0,0 +1,27 @@ +'use strict'; + +// Pairs with no '=' mixed with pairs that have one. + +require('../common'); +const assert = require('node:assert'); + +const cases = [ + ['a&b&c=d', [['a', ''], ['b', ''], ['c', 'd']]], + ['a=b&c&d&e=f&g', [['a', 'b'], ['c', ''], ['d', ''], ['e', 'f'], ['g', '']]], + ['a&&b=c=d&&e', [['a', ''], ['b', 'c=d'], ['e', '']]], + ['=&a&=b', [['', ''], ['a', ''], ['', 'b']]], + ['?a&b=', [['a', ''], ['b', '']]], + ['a+b&c%20d=e+f&g', [['a b', ''], ['c d', 'e f'], ['g', '']]], + [`${'a&'.repeat(50)}x=y`, [...Array(50).fill(['a', '']), ['x', 'y']]], +]; + +for (const [input, expected] of cases) { + assert.deepStrictEqual([...new URLSearchParams(input)], expected); +} + +{ + const pairs = 1 << 18; + const params = new URLSearchParams(`${'a&'.repeat(pairs)}x=y`); + assert.strictEqual(params.size, pairs + 1); + assert.strictEqual(params.get('x'), 'y'); +} diff --git a/test/parallel/test-worker-memory.js b/test/parallel/test-worker-memory.js index 9b115053aab5..665a01f3dce4 100644 --- a/test/parallel/test-worker-memory.js +++ b/test/parallel/test-worker-memory.js @@ -8,11 +8,11 @@ const util = require('util'); const { Worker } = require('worker_threads'); let numWorkers = +process.env.JOBS || require('os').availableParallelism(); -if (numWorkers > 20) { - // Cap the number of workers at 20 (as an even divisor of 60 used as +if (numWorkers > 10) { + // Cap the number of workers at 10 (as an even divisor of 60 used as // the total number of workers started) otherwise the test fails on // machines with high core counts. - numWorkers = 20; + numWorkers = 10; } // Verify that a Worker's memory isn't kept in memory after the thread finishes. diff --git a/test/parallel/test-zlib-zip-interop.js b/test/parallel/test-zlib-zip-interop.js index 429f7b02973e..a1c54bed178a 100644 --- a/test/parallel/test-zlib-zip-interop.js +++ b/test/parallel/test-zlib-zip-interop.js @@ -81,9 +81,19 @@ test('an archive written by createZipArchive is readable by unzip, zipinfo, and const zipinfo = spawnSync('zipinfo', [archivePath], { env }); assert.strictEqual(zipinfo.status, 0); + const zipinfoOut = zipinfo.stdout.toString(); for (const name of Object.keys(files)) { - if (!zipinfoUnicode && /[^\x20-\x7e]/.test(name)) continue; - assert.ok(zipinfo.stdout.toString().includes(name), `zipinfo missing ${name}`); + if (zipinfoOut.includes(name)) continue; + // Info-ZIP's zipinfo replaces non-ASCII bytes with '?' unless built with + // wide-character support (e.g. natspec or alt-iconv-utf8-print); stock + // builds replace non-ASCII bytes with '?' regardless of UNICODE_SUPPORT, + // which can leave replacement characters (U+FFFD) once decoded. + if (/[^\x20-\x7e]/.test(name)) { + if (!zipinfoUnicode) continue; + const placeholder = name.replace(/[^\x20-\x7e]+/g, '?'); + if (zipinfoOut.replace(/[?\uFFFD]+/g, '?').includes(placeholder)) continue; + } + assert.fail(`zipinfo missing ${name}`); } const extractDir = path.join(dir, 'out'); diff --git a/test/pseudo-tty/test-os-guessFileDescriptorType.js b/test/pseudo-tty/test-os-guessFileDescriptorType.js new file mode 100644 index 000000000000..0efb4780aa99 --- /dev/null +++ b/test/pseudo-tty/test-os-guessFileDescriptorType.js @@ -0,0 +1,28 @@ +'use strict'; + +require('../common'); +const assert = require('node:assert'); +const { guessFileDescriptorType } = require('os'); + +assert.strictEqual(guessFileDescriptorType(0), 'TTY'); +assert.strictEqual(guessFileDescriptorType(1), 'TTY'); +assert.strictEqual(guessFileDescriptorType(2), 'TTY'); + +assert.strictEqual(guessFileDescriptorType(55555), 'UNKNOWN'); +assert.strictEqual(guessFileDescriptorType(2 ** 31 - 1), 'UNKNOWN'); + +[ + -1, + 1.1, + '1', + [], + {}, + () => {}, + 2 ** 31, + true, + false, + 1n, + Symbol(), + undefined, + null, +].forEach((val) => assert.throws(() => guessFileDescriptorType(val), { code: 'ERR_INVALID_FD' })); diff --git a/test/pseudo-tty/test-os-guessFileDescriptorType.out b/test/pseudo-tty/test-os-guessFileDescriptorType.out new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/test/pseudo-tty/test-stdio-exit-keeps-foreign-tty-mode.js b/test/pseudo-tty/test-stdio-exit-keeps-foreign-tty-mode.js new file mode 100644 index 000000000000..805b1233d02d --- /dev/null +++ b/test/pseudo-tty/test-stdio-exit-keeps-foreign-tty-mode.js @@ -0,0 +1,32 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const child_process = require('child_process'); +const { spawnSyncAndExitWithoutError } = require('../common/child_process'); + +// Tests that a process which never changed the terminal mode does not write +// the terminal attributes recorded at startup back on exit. Doing so would +// clobber changes made in the meantime by another process sharing the +// terminal, e.g. the pager in `node -h | less`. + +const child = child_process.spawn(process.execPath, [ + '-e', 'console.log("Y"); require("fs").readSync(3, Buffer.alloc(1));', +], { stdio: ['inherit', 'pipe', 'inherit', 'pipe'] }); + +child.stdout.on('data', common.mustCall(() => { + // The child has recorded the terminal state by now. Change it behind its + // back, like a pager does, then let the child exit. + process.stdin.setRawMode(true); + child.stdio[3].end('x'); +})); + +child.on('exit', common.mustCall((code) => { + assert.strictEqual(code, 0); + // BusyBox stty warns on stderr when the pty has no window size. + const { child: { stdout } } = spawnSyncAndExitWithoutError('stty', ['-a'], { + stdio: ['inherit', 'pipe', 'pipe'], + encoding: 'utf8', + }); + process.stdin.setRawMode(false); + assert.match(stdout, /-icanon\b/); +})); diff --git a/test/pseudo-tty/test-stdio-exit-keeps-foreign-tty-mode.out b/test/pseudo-tty/test-stdio-exit-keeps-foreign-tty-mode.out new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/test/pummel/test-buffer-indexof-large.js b/test/pummel/test-buffer-indexof-large.js index 0f0999705417..e47b4fe49bff 100644 --- a/test/pummel/test-buffer-indexof-large.js +++ b/test/pummel/test-buffer-indexof-large.js @@ -25,3 +25,22 @@ assert.strictEqual(buffer.indexOf('\n', -1), match); assert.strictEqual(buffer.lastIndexOf(0x0a, -1), match); assert.strictEqual(buffer.lastIndexOf(Buffer.from([0x0a]), -1), match); assert.strictEqual(buffer.lastIndexOf('\n', -1), match); + +// Offsets outside the int32 range must not be clamped. +// Clear the ranges searched below, as allocUnsafe() does not zero memory. +const before = 2 ** 31 + 10; +const offset = 2 ** 31 + 50; +buffer.fill(0, 0, 100); +buffer.fill(0, 2 ** 31, match); +buffer[60] = 0x0a; +buffer[before] = 0x0a; + +for (const value of [0x0a, Buffer.from([0x0a]), '\n']) { + assert.strictEqual(buffer.indexOf(value, offset), match); + assert.strictEqual(buffer.lastIndexOf(value, offset), before); + assert.strictEqual(buffer.includes(value, match + 1), false); + assert.strictEqual(buffer.indexOf(value, Infinity), -1); + // buffer.length is 2 ** 31 + 101, so -offset resolves to index 51. + assert.strictEqual(buffer.indexOf(value, -offset), 60); + assert.strictEqual(buffer.lastIndexOf(value, -offset), -1); +} diff --git a/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs b/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs index 52b018e7028d..98c6ef837e7a 100644 --- a/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs +++ b/test/pummel/test-crypto-pqc-sign-verify-slh-dsa.mjs @@ -3,14 +3,14 @@ import * as common from '../common/index.mjs'; if (!common.hasCrypto) common.skip('missing crypto'); -import { hasOpenSSL } from '../common/crypto.js'; +import { hasOpenSSL, isBoringSSL } from '../common/crypto.js'; -if (!hasOpenSSL(3, 5)) - common.skip('requires OpenSSL >= 3.5'); +if (!hasOpenSSL(3, 5) && !isBoringSSL) + common.skip('requires OpenSSL >= 3.5 or BoringSSL'); import * as assert from 'node:assert'; import { promisify } from 'node:util'; -import { randomBytes, sign, verify } from 'node:crypto'; +import { createPrivateKey, createPublicKey, randomBytes, sign, verify } from 'node:crypto'; import fixtures from '../common/fixtures.js'; const pSign = promisify(sign); @@ -34,10 +34,20 @@ for (const [asymmetricKeyType, sigLen] of [ ['slh-dsa-shake-256f', 49856], ['slh-dsa-shake-256s', 29792], ]) { + if (isBoringSSL && asymmetricKeyType !== 'slh-dsa-sha2-128s' && + asymmetricKeyType !== 'slh-dsa-shake-256f') { + common.printSkipMessage(`Skipping unsupported ${asymmetricKeyType}`); + continue; + } const keys = { public: fixtures.readKey(getKeyFileName(asymmetricKeyType, 'public'), 'ascii'), private: fixtures.readKey(getKeyFileName(asymmetricKeyType, 'private'), 'ascii'), }; + if (isBoringSSL) { + const jwk = JSON.parse(fixtures.readKey(`${asymmetricKeyType}.json`)); + keys.public = createPublicKey({ format: 'jwk', key: jwk }); + keys.private = createPrivateKey({ format: 'jwk', key: jwk }); + } const data = randomBytes(32); // Start the async signature before the sync work to overlap the two. @@ -59,8 +69,10 @@ for (const [asymmetricKeyType, sigLen] of [ assert.strictEqual(await pVerify(undefined, data, keys.public, signature), true); } - assert.throws(() => sign('sha256', data, keys.private), { code: 'ERR_OSSL_INVALID_DIGEST' }); + const code = isBoringSSL ? + 'ERR_OSSL_EVP_COMMAND_NOT_SUPPORTED' : 'ERR_OSSL_INVALID_DIGEST'; + assert.throws(() => sign('sha256', data, keys.private), { code }); assert.throws( () => verify('sha256', data, keys.public, Buffer.alloc(sigLen)), - { code: 'ERR_OSSL_INVALID_DIGEST' }); + { code }); } diff --git a/test/sea/test-single-executable-application-vfs-sourcemap.js b/test/sea/test-single-executable-application-vfs-sourcemap.js new file mode 100644 index 000000000000..e54b4c60e796 --- /dev/null +++ b/test/sea/test-single-executable-application-vfs-sourcemap.js @@ -0,0 +1,71 @@ +'use strict'; + +// This tests that source maps are correctly loaded from a Single Executable +// Application when "useVfs" is enabled. The `.map` file and the original +// sources are bundled as `"assets"` and served from inside the read-only +// virtual file system mounted by the SEA, so `findSourceMap()` and the +// source-mapped stack trace must resolve against the mount point instead of +// the real file system. +// +// The fixture (`test/fixtures/sea/vfs-sourcemap/`) enables source maps through +// `execArgv` (`--enable-source-maps`), verifies that `module.findSourceMap()` +// finds the bundled map, and then throws an error. This test asserts that: +// 1. the mapped stack trace for the throw frame references the ORIGINAL +// source (`original.js`) rather than the generated `sea.js`, and +// 2. the original source line shown above the error is read back from the +// VFS (it carries the original 4-space indentation, not the 2-space +// indentation of the generated `sea.js`). +// +// The fixture's `sea.js.map` is a source-map-v3 identity mapping that is tied +// to the current content of `sea.js` and `original.js`: most lines are mapped +// one-to-one, and the `throw` line maps its column from 2 (the generated +// 2-space indentation) to 4 (the original 4-space indentation). If either +// fixture source is edited, regenerate the map so the columns stay in sync. + +require('../common'); + +const { + buildSEA, + skipIfBuildSEAIsNotSupported, +} = require('../common/sea'); + +skipIfBuildSEAIsNotSupported(); + +const tmpdir = require('../common/tmpdir'); +const { spawnSyncAndAssert } = require('../common/child_process'); +const fixtures = require('../common/fixtures'); + +tmpdir.refresh(); +const outputFile = buildSEA(fixtures.path('sea', 'vfs-sourcemap')); + +spawnSyncAndAssert( + outputFile, + { + env: { + ...process.env, + NODE_DEBUG_NATIVE: undefined, + }, + }, + { + // The SEA main script throws an uncaught error to produce the + // source-mapped stack trace. + status: 1, + stdout: /source map loaded from the SEA VFS: .*\/original\.js/, + stderr(stderr) { + // The throw frame must be remapped to the original source bundled in + // the VFS. Its column (5) matches the original 4-space indentation. + if (!/at boom \(.*\/original\.js:\d+:\d+\)/.test(stderr)) { + throw new Error(`the boom() frame was not source-mapped:\n${stderr}`); + } + // It must not still point at the generated sea.js. + if (/at boom \(.*\/sea\.js:\d+:\d+\)/.test(stderr)) { + throw new Error(`the boom() frame was not remapped to original.js:\n${stderr}`); + } + // The original source line is read from the VFS, so it shows the + // original 4-space indentation (the generated sea.js uses 2 spaces). + if (!/^ {4}throw new Error\('boom from the original source'\);$/m.test(stderr)) { + throw new Error(`the original source line was not read from the VFS:\n${stderr}`); + } + }, + }, +); diff --git a/test/sea/test-single-executable-application-vfs-zip-sourcemap.js b/test/sea/test-single-executable-application-vfs-zip-sourcemap.js new file mode 100644 index 000000000000..f9e6eed46a00 --- /dev/null +++ b/test/sea/test-single-executable-application-vfs-zip-sourcemap.js @@ -0,0 +1,91 @@ +'use strict'; + +// This tests that source maps are correctly loaded from a Single Executable +// Application when the assets are served from a ZIP archive mounted through +// the VFS (`"vfsArchive"`). The `.map` file and the original sources live in +// the archive and are served from the mount point, so `findSourceMap()` and +// the source-mapped stack trace must resolve against the mount point instead +// of the real file system. +// +// The fixture (`test/fixtures/sea/vfs-zip-sourcemap/`) enables source maps +// through `execArgv` (`--enable-source-maps`), verifies that +// `module.findSourceMap()` finds the bundled map, and then throws an error. +// This test asserts that the throw frame is remapped to the ORIGINAL source +// (`original.js`) in the archive and that the original source line (with its +// original 4-space indentation) is read back from the VFS. +// +// The fixture's `sea.js.map` is a source-map-v3 identity mapping that is tied +// to the current content of `sea.js` and `original.js`: most lines are mapped +// one-to-one, and the `throw` line maps its column from 2 (the generated +// 2-space indentation) to 4 (the original 4-space indentation). If either +// fixture source is edited, regenerate the map so the columns stay in sync. + +const common = require('../common'); + +const { + buildSEA, + skipIfBuildSEAIsNotSupported, +} = require('../common/sea'); + +skipIfBuildSEAIsNotSupported(); + +const tmpdir = require('../common/tmpdir'); +const { spawnSyncAndAssert } = require('../common/child_process'); +const fixtures = require('../common/fixtures'); +const { createWriteStream } = require('fs'); +const { pipeline } = require('stream/promises'); +const { zipFiles } = require('zlib'); + +// Asserts that the SEA stderr contains a source-mapped stack trace for an +// error thrown in `boom()`. +function assertSourceMappedStderr(stderr) { + // The throw frame must be remapped to the original source in the VFS. + if (!/at boom \(.*\/original\.js:\d+:\d+\)/.test(stderr)) { + throw new Error(`the boom() frame was not source-mapped:\n${stderr}`); + } + // It must not still point at the generated sea.js. + if (/at boom \(.*\/sea\.js:\d+:\d+\)/.test(stderr)) { + throw new Error(`the boom() frame was not remapped to original.js:\n${stderr}`); + } + // The original source line is read from the VFS, so it shows the original + // 4-space indentation (the generated sea.js uses 2 spaces). + if (!/^ {4}throw new Error\('boom from the original source'\);$/m.test(stderr)) { + throw new Error(`the original source line was not read from the VFS:\n${stderr}`); + } +} + +async function main() { + tmpdir.refresh(); + + // Build the assets archive with the ZIP support of node:zlib. This is what + // "vfsArchive" users do themselves before running --build-sea. + const fixture = (...args) => fixtures.path('sea', 'vfs-zip-sourcemap', ...args); + await pipeline( + zipFiles([ + [fixture('sea.js.map'), 'sea.js.map'], + [fixture('original.js'), 'original.js'], + ]), + createWriteStream(tmpdir.resolve('assets.zip')), + ); +} + +main().then(common.mustCall(() => { + const outputFile = buildSEA(fixtures.path('sea', 'vfs-zip-sourcemap')); + + spawnSyncAndAssert( + outputFile, + { + env: { + ...process.env, + NODE_DEBUG_NATIVE: undefined, + }, + }, + { + // The SEA main script throws an uncaught error to produce the + // source-mapped stack trace. + status: 1, + stdout: /source map loaded from the SEA VFS: .*\/original\.js/, + stderr: assertSourceMappedStderr, + }, + ); +})); diff --git a/test/sequential/test-debugger-probe-attach-pid.js b/test/sequential/test-debugger-probe-attach-pid.js new file mode 100644 index 000000000000..ba72253dd607 --- /dev/null +++ b/test/sequential/test-debugger-probe-attach-pid.js @@ -0,0 +1,54 @@ +// Tests that when a probe session starts by attaching to a process with --pid, +// which activates inspector in the target process, should stop the probe session after +// reaching --max-hit. +'use strict'; + +const common = require('../common'); +common.skipIfInspectorDisabled(); + +const fixtures = require('../common/fixtures'); +const { runProbe, startTarget } = require('../common/debugger-probe'); + +async function main() { + const target = await startTarget('probe-attach-loop.js', { args: [`--inspect-port=${common.PORT}`] }); + const { pid } = target.child; + const attachArgs = ['--pid', `${pid}`, '--port', `${common.PORT}`]; + await runProbe(['--probe', 'probe-attach-loop.js:6', '--expr', 'typeof count', '--max-hit', '1', ...attachArgs], { + target, + status: 0, + report: { + v: 2, + target: { pid, host: '127.0.0.1', port: common.PORT }, + probes: [{ expr: 'typeof count', target: { suffix: 'probe-attach-loop.js', line: 6 }, maxHit: 1 }], + results: [{ + probe: 0, event: 'hit', hit: 1, result: { type: 'string', value: 'number' }, + location: { url: fixtures.fileURL('debugger', 'probe-attach-loop.js').href, line: 6, column: 3 }, + }, { event: 'completed' }], + }, + }); + + // The target should be left running after --max-hit is reached and it is detached. + // We should be able to attach a second session to it. Killing the target at this point + // should result in a probe_target_exit with exit code 0 + // Line 10 only runs at startup, so this session should wait until the target is killed. + await runProbe(['--probe', 'probe-attach-loop.js:10', '--expr', '1', ...attachArgs], { + target, + onStarted: () => target.child.kill('SIGKILL'), + status: 0, + report: { + v: 2, + probes: [{ expr: '1', target: { suffix: 'probe-attach-loop.js', line: 10 } }], + results: [{ + event: 'error', + pending: [0], + error: { + code: 'probe_target_exit', + message: 'Target exited before probes: probe-attach-loop.js:10', + }, + }], + }, + }); + await target.exited; +} + +main().then(common.mustCall()); diff --git a/test/sequential/test-gc-http-client-onerror.js b/test/sequential/test-gc-http-client-onerror.js index 1c311c6a9b64..b498f3c77331 100644 --- a/test/sequential/test-gc-http-client-onerror.js +++ b/test/sequential/test-gc-http-client-onerror.js @@ -1,13 +1,11 @@ 'use strict'; // Flags: --expose-gc // just like test-gc-http-client.js, -// but with an on('error') handler that does nothing. +// but with an on('error') handler that rethrows. const common = require('../common'); const { onGC } = require('../common/gc'); -const cpus = require('os').availableParallelism(); - function serverHandler(req, res) { req.resume(); res.writeHead(200, { 'Content-Type': 'text/plain' }); @@ -15,23 +13,23 @@ function serverHandler(req, res) { } const http = require('http'); -const numRequests = 36; -let createClients = true; -let done = 0; +// Keep the number of in-flight requests small and fixed. Opening too many +// connections at once can overflow the listen queue (capped at 128 on macOS), +// and the kernel then resets connections that are still being established. +const concurrency = 8; +const numRequests = 64; let count = 0; +let done = 0; let countGC = 0; const server = http.createServer(serverHandler); server.listen(0, common.mustCall(() => { - for (let i = 0; i < cpus; i++) - getAll(numRequests); + for (let i = 0; i < concurrency; i++) + getNext(); })); -function getAll(requestsRemaining) { - if (!createClients) - return; - - if (requestsRemaining <= 0) +function getNext() { + if (count >= numRequests) return; const req = http.get({ @@ -42,13 +40,14 @@ function getAll(requestsRemaining) { count++; onGC(req, { ongc }); - - setImmediate(getAll, requestsRemaining - 1); } function cb(res) { res.resume(); - done++; + res.on('end', () => { + done++; + getNext(); + }); } function onerror(err) { @@ -62,16 +61,14 @@ function ongc() { setImmediate(status); function status() { - if (done > 0) { - createClients = false; + if (done === numRequests) { global.gc(); - console.log(`done/collected/total: ${done}/${countGC}/${count}`); - if (countGC === count) { + console.log(`done/collected/total: ${done}/${countGC}/${numRequests}`); + if (countGC === numRequests) { server.close(); - } else { - setImmediate(status); + return; } - } else { - setImmediate(status); } + + setImmediate(status); } diff --git a/test/sequential/test-gc-http-client.js b/test/sequential/test-gc-http-client.js index 6b2a5fc03afb..56a6fff1b39b 100644 --- a/test/sequential/test-gc-http-client.js +++ b/test/sequential/test-gc-http-client.js @@ -5,31 +5,29 @@ const common = require('../common'); const { onGC } = require('../common/gc'); -const cpus = require('os').availableParallelism(); - function serverHandler(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); } const http = require('http'); -const numRequests = 36; -let createClients = true; -let done = 0; +// Keep the number of in-flight requests small and fixed. Opening too many +// connections at once can overflow the listen queue (capped at 128 on macOS), +// and the kernel then resets connections that are still being established. +const concurrency = 8; +const numRequests = 64; let count = 0; +let done = 0; let countGC = 0; const server = http.createServer(serverHandler); server.listen(0, common.mustCall(() => { - for (let i = 0; i < cpus; i++) - getAll(numRequests); + for (let i = 0; i < concurrency; i++) + getNext(); })); -function getAll(requestsRemaining) { - if (!createClients) - return; - - if (requestsRemaining <= 0) +function getNext() { + if (count >= numRequests) return; const req = http.get({ @@ -40,13 +38,14 @@ function getAll(requestsRemaining) { count++; onGC(req, { ongc }); - - setImmediate(getAll, requestsRemaining - 1); } function cb(res) { res.resume(); - done += 1; + res.on('end', () => { + done++; + getNext(); + }); } function ongc() { @@ -56,16 +55,14 @@ function ongc() { setImmediate(status); function status() { - if (done > 0) { - createClients = false; + if (done === numRequests) { global.gc(); - console.log(`done/collected/total: ${done}/${countGC}/${count}`); - if (countGC === count) { + console.log(`done/collected/total: ${done}/${countGC}/${numRequests}`); + if (countGC === numRequests) { server.close(); - } else { - setImmediate(status); + return; } - } else { - setImmediate(status); } + + setImmediate(status); } diff --git a/test/test426/README.md b/test/test426/README.md index 85db408434bc..59e657ed7e91 100644 --- a/test/test426/README.md +++ b/test/test426/README.md @@ -7,7 +7,7 @@ suite ensures that the Node.js source map implementation conforms to the The [`test/fixtures/test426`](../fixtures/test426/) contains a copy of the set of [Source Map Tests][] suite. The last updated hash is: -* <https://github.com/tc39/source-map-tests/commit/fae1fa49815813088c433e8486e330e8d953a444> +* <https://github.com/tc39/source-map-tests/commit/bc255a703449b2bc10989772d940df5bf37acf4f> See the json files in [the `status` folder](./status) for prerequisites, expected failures, and support status for specific tests. diff --git a/test/test426/status/decoding.json b/test/test426/status/decoding.json new file mode 100644 index 000000000000..ebbb12cdd14c --- /dev/null +++ b/test/test426/status/decoding.json @@ -0,0 +1,5 @@ +{ + "debug-id": { + "skip": "debugId is not supported" + } +} diff --git a/test/test426/test-source-map-decoding.mjs b/test/test426/test-source-map-decoding.mjs new file mode 100644 index 000000000000..493c268b8dbb --- /dev/null +++ b/test/test426/test-source-map-decoding.mjs @@ -0,0 +1,94 @@ +// Flags: --expose-internals +import '../common/index.mjs'; +import * as fixtures from '../common/fixtures.mjs'; + +import assert from 'node:assert'; +import test from 'node:test'; +import { readdirSync, readFileSync } from 'node:fs'; +import sourceMap from 'internal/source_map/source_map'; + +const { SourceMap, kScopes } = sourceMap; + +// Runs the decoding tests: each `<name>.map` in a proposal directory is +// decoded and compared with its `<name>.map.golden` Decoded Source Map Record. +// See test/fixtures/test426/decoding/README.md. + +const kStatus = JSON.parse(readFileSync(new URL('./status/decoding.json', import.meta.url), 'utf8')); + +// Compares the parts of the golden record that each proposal adds, as +// described by its `<proposal>/<proposal>.d.ts`. +const kProposalCheckers = { + scopes: checkScopes, +}; + +for (const proposal of readdirSync(fixtures.path('test426/decoding'), { withFileTypes: true })) { + if (!proposal.isDirectory()) continue; + const dir = fixtures.path('test426/decoding', proposal.name); + const files = readdirSync(dir).filter((file) => file.endsWith('.map')); + const checker = kProposalCheckers[proposal.name]; + for (const file of files) { + const name = `${proposal.name}/${file}`; + test(name, { + skip: kStatus[proposal.name]?.skip ?? kStatus[name]?.skip, + todo: checker === undefined, + }, () => { + if (checker === undefined) return; + const payload = JSON.parse(readFileSync(`${dir}/${file}`, 'utf8')); + const golden = JSON.parse(readFileSync(`${dir}/${file}.golden`, 'utf8')); + checker(new SourceMap(payload), golden); + }); + } +} + +function checkScopes(sourceMap, golden) { + const { originalScopes, generatedRanges } = sourceMap[kScopes]; + const flattenedScopes = originalScopes.map((roots) => flatten(roots)); + assert.deepStrictEqual( + originalScopes.map((roots) => ({ rootScopes: roots.map(toGoldenScope) })), + golden.sources.map(({ rootScopes }) => ({ rootScopes }))); + assert.deepStrictEqual( + generatedRanges.map((range) => toGoldenRange(range, flattenedScopes)), + golden.ranges); +} + +function toGoldenScope(scope) { + return { + start: scope.start, + end: scope.end, + name: scope.name, + kind: scope.kind, + isStackFrame: scope.isStackFrame, + variables: scope.variables, + children: scope.children.map(toGoldenScope), + }; +} + +// The golden format refers to a definition by its source index and its index +// in the pre-order list of that source's scopes. +function toGoldenRange(range, flattenedScopes) { + let definition = null; + if (range.definition !== null) { + const { sourceIndex } = range.definition; + definition = { + source: sourceIndex, + scope: flattenedScopes[sourceIndex].indexOf(range.definition), + }; + } + return { + start: range.start, + end: range.end, + definition, + stackFrameType: range.stackFrameType, + callSite: range.callSite, + bindings: range.bindings, + children: range.children.map((child) => toGoldenRange(child, flattenedScopes)), + }; +} + +function flatten(scopes, result = []) { + for (const scope of scopes) { + result.push(scope); + flatten(scope.children, result); + } + return result; +} diff --git a/tools/actions/lint-release-proposal-commit-list.mjs b/tools/actions/lint-release-proposal-commit-list.mjs index fa5ebf79cdfe..701c76aca669 100755 --- a/tools/actions/lint-release-proposal-commit-list.mjs +++ b/tools/actions/lint-release-proposal-commit-list.mjs @@ -46,19 +46,40 @@ commitList = commitList let expectedNumberOfCommitsLeft = commitList.match(/\n\* \[/g)?.length ?? 0; +function reportError(message, lineStart = -1) { + let annotation = `file=${CHANGELOG_PATH}`; + if (lineStart !== -1) { + let line = 1; + for (let i = 0; i < lineStart + commitListingStart; i = changelog.indexOf('\n', i + 1)) { + line++; + } + annotation += `,line=${line}`; + } + console.error(`::error ${annotation},title=Release proposal linter::${message}`); + process.exitCode ||= 1; +} + for await (const line of stdinLineByLine) { const { smallSha, title, prURL } = JSON.parse(line); if (smallSha === RELEASE_COMMIT_SHA.slice(0, 10)) { - assert.strictEqual( - expectedNumberOfCommitsLeft, 0, - 'Some commits are listed without being included in the proposal, or are listed more than once', - ); + if (expectedNumberOfCommitsLeft !== 0) { + reportError('Some commits are listed without being included in the proposal, or are listed more than once'); + // Avoid reporting the same discrepancy again after the loop. + expectedNumberOfCommitsLeft = 0; + } continue; } + // Used by the wrapping shell (in lint-release-proposal.yml) to check to labels + console.log(prURL); + const lineStart = commitList.indexOf(`\n* [[\`${smallSha}\`]`); - assert.notStrictEqual(lineStart, -1, `Cannot find ${smallSha} on the list`); + if (lineStart === -1) { + reportError(`Cannot find ${smallSha} on the list`); + continue; + } + expectedNumberOfCommitsLeft--; const lineEnd = commitList.indexOf('\n', lineStart + 1); try { @@ -80,15 +101,10 @@ for await (const line of stdinLineByLine) { if (e?.code !== 'ERR_ASSERTION') { throw e; } - let line = 1; - for (let i = 0; i < lineStart + commitListingStart; i = changelog.indexOf('\n', i + 1)) { - line++; - } - console.error(`::error file=${CHANGELOG_PATH},line=${line},title=Release proposal linter::${e.message}`); + reportError(e.message, lineStart); console.error(e); - process.exitCode ||= 1; } - expectedNumberOfCommitsLeft--; - console.log(prURL); } -assert.strictEqual(expectedNumberOfCommitsLeft, 0, 'Release commit is not the last commit in the proposal'); +if (expectedNumberOfCommitsLeft !== 0) { + reportError('Release commit is not the last commit in the proposal'); +} diff --git a/tools/create_expfile.sh b/tools/create_expfile.sh index 977f509e2ec5..0bedb5a4031f 100755 --- a/tools/create_expfile.sh +++ b/tools/create_expfile.sh @@ -6,7 +6,7 @@ # by native add-ons. # # The raw symbol data is obtained by using dump -tov on -# the .a files which make up the node executable. +# the .a and .o files which make up the node executable. # # dump -tov flags: # -t: Display symbol table entries @@ -29,12 +29,17 @@ # Symbols for the gtest libraries are excluded as # they are not linked into the node executable. # -echo "Searching $1 to write out expfile to $2" +SEARCH_DIR="$1" +OUTPUT="$2" +TARGET_NAME="$3" +shift 3 || true +# Remaining arguments are explicit extra inputs for the build to order on. -# This special sequence must be at the start of the exp file. -echo "#!." > "$2.tmp" +echo "Searching $SEARCH_DIR to write out expfile to $OUTPUT" + +SYMFILE="${OUTPUT}.syms" +: > "$SYMFILE" -# Pull the symbols from the .a files. # Use dump -tov to get visibility information and exclude HIDDEN symbols. # This prevents AIX linker error 0711-407 when addons try to import symbols # with visibility attributes. @@ -42,46 +47,47 @@ echo "#!." > "$2.tmp" # IMPORTANT: AIX dump -tov output has a visibility column that contains either # a visibility keyword (HIDDEN/EXPORTED/PROTECTED) or blank spaces when no # visibility attribute is set. Since AWK splits fields on whitespace, this -# results in different field counts: -# -# With visibility keyword (8 fields after AWK splits): -# [137] m 0x00003290 .text 1 weak HIDDEN ._ZNKSt3__1... -# $1 $2 $3 $4 $5 $6 $7 $8 -# | | └─ Symbol name -# | └─ Visibility (HIDDEN/EXPORTED/PROTECTED) -# └─ Linkage (weak/extern) -# -# Without visibility keyword (7 fields after AWK splits, spaces collapsed): -# [77] m 0x00000000 .text 1 weak ._ZN8simdjson... -# $1 $2 $3 $4 $5 $6 $7 -# | └─ Symbol name -# └─ Linkage (weak/extern) -# -# The awk script handles both cases by using an associative array V[] -# to map field values to their export suffixes. For fields that don't match -# any key in V[], the lookup returns an empty string, which is perfect for -# handling the variable field positions caused by the blank visibility column. -# -find "$1" -name "*.a" | grep -v gtest | while read -r f; do - dump -tov -X 32_64 "$f" 2>/dev/null | \ - awk ' - BEGIN { - V["EXPORTED"]=" export" - V["PROTECTED"]=" protected" - V["HIDDEN"]=" hidden" - V["weak"]=" weak" - } - /^\[[0-9]+\]\tm +[^ ]+ +\.(text|data|tdata|bss) +[^ ]+ +(extern|weak)( +(EXPORTED|PROTECTED|HIDDEN))?/ { - # Exclude symbols starting with dot, __sinit, __sterm, __[0-9]+__ - # Also exclude HIDDEN symbols to avoid visibility attribute issues - if (!match($NF,/^(\.|__sinit|__sterm|__[0-9]+__)/)) { - # Skip if HIDDEN visibility (can be at $(NF-1) or $(NF-2)) - if ($(NF-1) != "HIDDEN" && $(NF-2) != "HIDDEN") { - print $NF V[$(NF-1)] V[$(NF-2)] - } - } +# results in different field counts. The awk script handles both cases by using +# an associative array V[] to map field values to their export suffixes. + +# This is to bypass the lint-sh job from saying "Expressions don't expand in +# single quotes, use double quotes for that." which is invalid for this case +# shellcheck disable=SC2016 +DUMP_AWK=' +BEGIN { + V["EXPORTED"]=" export" + V["PROTECTED"]=" protected" + V["HIDDEN"]=" hidden" + V["weak"]=" weak" +} +/^\[[0-9]+\]\tm +[^ ]+ +\.(text|data|tdata|bss) +[^ ]+ +(extern|weak)( +(EXPORTED|PROTECTED|HIDDEN))?/ { + if (!match($NF,/^(\.|__sinit|__sterm|__[0-9]+__)/)) { + if ($(NF-1) != "HIDDEN" && $(NF-2) != "HIDDEN") { + print $NF V[$(NF-1)] V[$(NF-2)] } - ' -done | sort -u >> "$2.tmp" + } +} +' + +find "$SEARCH_DIR" -name "*.a" | grep -v gtest | while read -r f; do + dump -tov -X 32_64 "$f" 2>/dev/null | awk "$DUMP_AWK" >> "$SYMFILE" +done + +# Objects linked directly into the target (not archived), e.g. node_snapshot.o. +if [ -n "$TARGET_NAME" ] && [ -d "$SEARCH_DIR/$TARGET_NAME" ]; then + find "$SEARCH_DIR/$TARGET_NAME" -name "*.o" | while read -r f; do + dump -tov -X 32_64 "$f" 2>/dev/null | awk "$DUMP_AWK" >> "$SYMFILE" + done +fi + +for extra in "$@"; do + if [ -f "$extra" ]; then + dump -tov -X 32_64 "$extra" 2>/dev/null | awk "$DUMP_AWK" >> "$SYMFILE" + fi +done -mv -f "$2.tmp" "$2" +{ + echo "#!." + sort -u "$SYMFILE" +} > "$OUTPUT" +rm -f "$SYMFILE" diff --git a/tools/dep_updaters/update-amaro.sh b/tools/dep_updaters/update-amaro.sh index 0169e9304bc0..f257497b7e50 100755 --- a/tools/dep_updaters/update-amaro.sh +++ b/tools/dep_updaters/update-amaro.sh @@ -60,7 +60,7 @@ rm -rf node_modules mv ./* "$DEPS_DIR/amaro" # update version information in src/undici_version.h -cat > "$ROOT/src/amaro_version.h" <<EOF +cat > "$BASE_DIR/src/amaro_version.h" <<EOF // This is an auto generated file, please do not edit. // Refer to tools/dep_updaters/update-amaro.sh #ifndef SRC_AMARO_VERSION_H_ diff --git a/tools/dep_updaters/update-c-ares.sh b/tools/dep_updaters/update-c-ares.sh index ca77ee52183d..71a333bfee25 100755 --- a/tools/dep_updaters/update-c-ares.sh +++ b/tools/dep_updaters/update-c-ares.sh @@ -73,7 +73,7 @@ echo "Replacing existing c-ares" replace_dir "$DEPS_DIR/cares" "$ARES_FOLDER" echo "Updating cares.gyp" -"$NODE" "$ROOT/tools/dep_updaters/update-c-ares.mjs" +"$NODE" "$BASE_DIR/tools/dep_updaters/update-c-ares.mjs" # Update the version number on maintaining-dependencies.md # and print the new version as the last line of the script as we need diff --git a/tools/dep_updaters/utils.sh b/tools/dep_updaters/utils.sh index 76a40d4bbc49..9ece341d1e85 100644 --- a/tools/dep_updaters/utils.sh +++ b/tools/dep_updaters/utils.sh @@ -1,8 +1,5 @@ #!/bin/sh -ROOT=$(cd "$(dirname "$0")/../.." && pwd) -export ROOT - # This function compare new version with current version of a dependency and # exit the script if the versions are the same # diff --git a/tools/eslint/eslint.config_utils.mjs b/tools/eslint/eslint.config_utils.mjs index 7b09047937bf..e6008c457935 100644 --- a/tools/eslint/eslint.config_utils.mjs +++ b/tools/eslint/eslint.config_utils.mjs @@ -16,6 +16,10 @@ export const noRestrictedSyntaxCommonAll = [ selector: 'ThrowStatement > CallExpression[callee.name=/Error$/]', message: 'Use `new` keyword when throwing an `Error`.', }, + { + selector: 'ExpressionStatement > NewExpression[callee.name=/Error$/]', + message: 'Throw, return, or assign the `Error`; constructing it alone does nothing.', + }, { selector: "CallExpression[callee.property.name='substr']", message: 'Use String.prototype.slice() or String.prototype.substring() instead of String.prototype.substr()', diff --git a/tools/nix/pkgs-26.05.nix b/tools/nix/pkgs-26.05.nix index 9a410b7fce91..4d6d6c38d856 100644 --- a/tools/nix/pkgs-26.05.nix +++ b/tools/nix/pkgs-26.05.nix @@ -1,10 +1,10 @@ arg: let repo = "https://github.com/NixOS/nixpkgs"; - rev = "57f1c8965649ce5bcac5118a0d2e41f1fbdc56e5"; + rev = "c78b9f9c117e3ad7a6c1a161a48dc388693049b0"; nixpkgs = import (builtins.fetchTarball { url = "${repo}/archive/${rev}.tar.gz"; - sha256 = "08gxbi52psc9wvflpfsli9fjvcv1jvzd70w6c8pxl4swjvfcsq3d"; + sha256 = "06gawwcw5k3d5wfs56mmy2xdxifjyhvcd5xzfbjp1amz30q0h4ni"; }) arg; in # Unstable channel no longer supports Intel architecture for macOS. We can use the 26.05 channel diff --git a/tools/nix/pkgs.nix b/tools/nix/pkgs.nix index 6ed279484a52..9f757fb86587 100644 --- a/tools/nix/pkgs.nix +++ b/tools/nix/pkgs.nix @@ -1,10 +1,10 @@ arg: let repo = "https://github.com/NixOS/nixpkgs"; - rev = "085af13c1607f4f73ab1e7a51071faf6577a7e87"; + rev = "93a9ed0a866099a230ed5146a5bb7d16fd5c9b14"; nixpkgs = import (builtins.fetchTarball { url = "${repo}/archive/${rev}.tar.gz"; - sha256 = "0wwdfxvwc19qymmjshf8qzw39dqyav1kgxna2ady9l7akqzanm1i"; + sha256 = "1x2cili34ky3fcj7b0z7ivmr7mkv0szr8kfqkcwrhlfnbg4y147h"; }) arg; in # Unstable channel no longer supports Intel architecture for macOS. We can use the 26.05 channel diff --git a/tools/osx-notarize.sh b/tools/osx-notarize.sh index c9b50a2f3b69..2dcd00405473 100755 --- a/tools/osx-notarize.sh +++ b/tools/osx-notarize.sh @@ -91,7 +91,7 @@ notarize_binary() { # There is nothing to staple to a bare binary, so the only way to confirm # the ticket is live is to have codesign look it up. spctl cannot be used # here: it rejects command line tools with "does not seem to be an app". - if ! retry codesign --verify --verbose=2 -R=notarized "$1"; then + if ! retry codesign --verify --verbose=2 --check-notarization -R=notarized "$1"; then echo "error: $1 will not be accepted by Gatekeeper!" 1>&2 exit 1 fi diff --git a/tools/v8_gypfiles/toolchain.gypi b/tools/v8_gypfiles/toolchain.gypi index 058580f2ab42..645f19ca5c9f 100644 --- a/tools/v8_gypfiles/toolchain.gypi +++ b/tools/v8_gypfiles/toolchain.gypi @@ -122,6 +122,13 @@ # On by default in Clang and V8 requires it at least for arm64. '-flax-vector-conversions', ], + 'cflags_cc': [ + # TODO(joyeecheung): this may be removed after we switch to C++23 + '-Wno-invalid-constexpr', + # V8 uses the clang-only nodebug attribute in + # src/execution/simulator.h, which GCC ignores with a warning. + '-Wno-attributes', + ], }], ['clang==1 or OS!="win"', { 'cflags_cc': [ diff --git a/tools/v8_gypfiles/v8.gyp b/tools/v8_gypfiles/v8.gyp index a3166cae5627..b2cd68247795 100644 --- a/tools/v8_gypfiles/v8.gyp +++ b/tools/v8_gypfiles/v8.gyp @@ -75,6 +75,8 @@ }, '(OS!="aix" and OS!="os400") and (OS!="win" or clang==1)', { 'cflags': [ '-fvisibility=hidden', + ], + 'cflags_cc': [ '-fvisibility-inlines-hidden' ], }], # MSVC hides the non-public symbols by default so no need to configure it. diff --git a/typings/internalBinding/worker.d.ts b/typings/internalBinding/worker.d.ts index e168ff8abb17..7801b2c569dd 100644 --- a/typings/internalBinding/worker.d.ts +++ b/typings/internalBinding/worker.d.ts @@ -41,7 +41,6 @@ export interface WorkerBinding { threadId: number; threadName: string; isMainThread: boolean; - isInternalThread: boolean; ownsProcessState: boolean; resourceLimits?: Float64Array; kMaxYoungGenerationSizeMb: number; diff --git a/typings/primordials.d.ts b/typings/primordials.d.ts index 7a424c729502..63a75bbee042 100644 --- a/typings/primordials.d.ts +++ b/typings/primordials.d.ts @@ -168,6 +168,14 @@ declare namespace primordials { export const ArrayBufferPrototypeSlice: UncurryThis<typeof ArrayBuffer.prototype.slice> export const ArrayBufferPrototypeTransfer: UncurryThis<typeof ArrayBuffer.prototype.transfer> export const ArrayBufferPrototypeGetByteLength: UncurryGetter<typeof ArrayBuffer.prototype , "byteLength">; + export import AsyncDisposableStack = globalThis.AsyncDisposableStack, + export const AsyncDisposableStackPrototype: typeof AsyncDisposableStack.prototype + export const AsyncDisposableStackAdopt: UncurryThis<typeof AsyncDisposableStack.prototype.adopt> + export const AsyncDisposableStackDefer: UncurryThis<typeof AsyncDisposableStack.prototype.defer> + export const AsyncDisposableStackDispose: UncurryThis<typeof AsyncDisposableStack.prototype.dispose> + export const AsyncDisposableStackMove: UncurryThis<typeof AsyncDisposableStack.prototype.move> + export const AsyncDisposableStackUse: UncurryThis<typeof AsyncDisposableStack.prototype.use> + export const AsyncDisposableStackSymbolAsyncDispose: UncurryMethod<typeof AsyncDisposableStack.prototype, typeof Symbol.asyncDispose>; export import BigInt = globalThis.BigInt; export const BigIntPrototype: typeof BigInt.prototype export const BigIntAsUintN: typeof BigInt.asUintN @@ -259,6 +267,14 @@ declare namespace primordials { export const DatePrototypeToLocaleDateString: UncurryThis<typeof Date.prototype.toLocaleDateString> export const DatePrototypeToLocaleTimeString: UncurryThis<typeof Date.prototype.toLocaleTimeString> export const DatePrototypeSymbolToPrimitive: UncurryMethod<typeof Date.prototype, typeof Symbol.toPrimitive>; + export import DisposableStack = globalThis.DisposableStack, + export const DisposableStackPrototype: typeof DisposableStack.prototype + export const DisposableStackAdopt: UncurryThis<typeof DisposableStack.prototype.adopt> + export const DisposableStackDefer: UncurryThis<typeof DisposableStack.prototype.defer> + export const DisposableStackDispose: UncurryThis<typeof DisposableStack.prototype.dispose> + export const DisposableStackMove: UncurryThis<typeof DisposableStack.prototype.move> + export const DisposableStackUse: UncurryThis<typeof DisposableStack.prototype.use> + export const DisposableStackSymbolDispose: UncurryMethod<typeof DisposableStack.prototype, typeof Symbol.dispose>; export import Error = globalThis.Error; export const ErrorPrototype: typeof Error.prototype // @ts-ignore @@ -444,6 +460,8 @@ declare namespace primordials { export const StringPrototypeToWellFormed: UncurryThis<typeof String.prototype.toWellFormed> export const StringPrototypeValueOf: UncurryThis<typeof String.prototype.valueOf> export const StringPrototypeReplaceAll: UncurryThis<typeof String.prototype.replaceAll> + export import SuppressedError = globalThis.SuppressedError; + export const SuppressedErrorPrototype: typeof SuppressedError.prototype export import Symbol = globalThis.Symbol; export const SymbolPrototype: typeof Symbol.prototype export const SymbolFor: typeof Symbol.for