diff --git a/.github/scripts/rows/report-failure.ps1 b/.github/scripts/rows/report-failure.ps1 deleted file mode 100644 index 5064af6..0000000 --- a/.github/scripts/rows/report-failure.ps1 +++ /dev/null @@ -1,53 +0,0 @@ -param( - # The issue title, one per build or per job, so a failure that repeats lands on one issue. - [Parameter(Mandatory = $true)][string]$Title, - # A file of `step: reason` lines the steps wrote when they failed. It may be missing. - [string]$Reasons = '', - # The failing capture of the row proof. It may be missing. - [string]$Capture = '', - # Where the job's files are kept, for the person who looks into it. - [string]$Files = '' -) - -$ErrorActionPreference = 'Stop' -# Opens or updates the issue of a failed row job, so a failure is never silent. A person is told -# which step failed and why, and sees the capture of the failing window. - -$run = "$env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID" -$lines = @() -if ($Reasons -and (Test-Path $Reasons)) { $lines = @(Get-Content $Reasons | Where-Object { $_.Trim() }) } -if ($lines.Count -eq 0) { $lines = @('A step failed without recording its reason. The job log has it.') } -$body = @("Run: $run", '', 'Reason:', '') + ($lines | ForEach-Object { "- $_" }) -if ($Files) { $body += @('', "Files of this job, kept for 30 days: $Files") } - -# An issue cannot hold an upload made through the API, so the capture is a file of a prerelease that -# only holds failure captures. The table release stays as Rivet downloads it. -if ($Capture -and (Test-Path $Capture)) { - $tag = 'row-failures' - gh release view $tag 2>$null | Out-Null - if ($LASTEXITCODE -ne 0) { - gh release create $tag --title 'Row failure captures' --notes 'Captures of failed row proofs, linked from their issues.' --prerelease --latest=false | Out-Null - } - $slug = ($Title -replace '[^A-Za-z0-9.]+', '-').Trim('-').ToLower() - $name = "$slug-$env:GITHUB_RUN_ID.png" - $copy = Join-Path (Split-Path $Capture) $name - Copy-Item $Capture $copy -Force - gh release upload $tag $copy --clobber | Out-Null - if ($LASTEXITCODE -eq 0) { - $body += @('', 'Capture of the failing window:', '', "![failing capture]($env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/releases/download/$tag/$name)") - } else { - $body += @('', 'The capture could not be uploaded. It is in the job files.') - } -} -$text = $body -join "`n" - -gh label create browser-rows --color B60205 --description 'A failure of the browser rows job' --force | Out-Null -# The search matches words, so the exact title is checked here. -$open = @(gh issue list --state open --label browser-rows --limit 100 --json number,title | ConvertFrom-Json | - Where-Object title -eq $Title) -if ($open.Count -gt 0) { - gh issue comment $open[0].number --body $text -} else { - gh issue create --title $Title --label browser-rows --body $text -} -if ($LASTEXITCODE -ne 0) { throw "Could not open or update the issue '$Title'" } diff --git a/.github/workflows/browser-rows.yml b/.github/workflows/browser-rows.yml index 5b0cbf5..f4fc7c2 100644 --- a/.github/workflows/browser-rows.yml +++ b/.github/workflows/browser-rows.yml @@ -1,127 +1,43 @@ -# Keeps Rivet's supported-build table ahead of Chrome, Edge and Brave. +# Tests the row finder on browser builds as their makers release them. # -# A browser updates itself whenever its maker says, and Rivet does not hold it back. So this job -# watches what the makers publish, builds a whole row for each new build from the verified row of -# the build before it, proves the row on the real browser, and publishes a signed table that reaches -# people without reinstalling Rivet. A row the generator cannot vouch for, such as the first of a new milestone, -# becomes a pull request for a person and is not published. +# Rivet finds the values of a row in the installed browser's own binary, by the descriptions in +# rivet/platform/windows/rows/descriptions.json. This job only measures that finder. Once a day it +# reads what Chrome, Edge and Brave publish, takes the newest stable builds that have no verified +# row, runs `chrome-builds find` on each and uploads how many values it found and did not find, per +# feature. It makes no row, signs nothing, publishes nothing and opens no pull request. # -# Needs on the default branch: this file. Needs in the repository's secrets: -# RIVET_TABLE_SIGNING_KEY the private key from `chrome-builds table-key` -# and in its variables: -# RIVET_TABLE_PUBLIC_KEY the matching public key, which release builds are built with -# The signed table is published as this repository's `builds-table` release, which Rivet downloads -# without signing in. A fork or copy without the signing secret runs only the gate job, which does -# nothing. +# A run started by hand with `score` runs the finder on builds that have a verified row and are +# still downloadable, and compares every value it found with that row. It fails when a found value +# is wrong. A value not found is reported, not a failure. # -# A failure is never silent: a failed build opens or updates the issue named after it, with the step -# that failed, its reason and the capture of the failing window. Each step records its reason in -# `failure.txt` before it stops. -# -# No browser's debug symbols are downloaded or read. A maker can ship a build long before its -# symbols appear, or never publish them. A row is made from the verified prior row, the fingerprints -# of its functions, the prior build's module and the new build's module: each function must match -# one place, or two independent methods must agree on it, and every offset, slot and size is read -# again from the new module. A feature whose values are not found is off in the row, and a part the -# window cannot do without stops the row for a person. -# -# A run started by hand with `score` makes, the same way, the rows of builds that already have a -# verified row, and compares them value by value. It is a measurement: it publishes, proposes and -# reports nothing, and fails only when a value it found differs from the verified one. +# No browser's debug symbols are downloaded or read. name: Browser rows on: schedule: - # Every two hours: a rollout starts within hours of a version appearing in the feeds. - - cron: "17 */2 * * *" + - cron: "17 5 * * *" workflow_dispatch: inputs: - withdraw: - description: "Rows to take out of the published table, as browser@version separated by semicolons. Leave empty for a normal run." - required: false - default: "" - trial: - description: "Make rows with the code of the branch this run is started on, and keep them only in the run's files: nothing is proposed, published or reported." - type: boolean - required: false - default: false - only: - description: "With trial: the builds to make, as browser@version separated by semicolons, instead of those the feeds list." - required: false - default: "" score: - description: "Score the generator on builds that have a verified row, as browser@prior>new separated by semicolons, or 'default' for scripts/tests/row-score.ps1's list. Nothing is published." + description: "Score the finder on builds with a verified row, as browser@version separated by semicolons, or 'default' for scripts/tests/row-score.ps1's list. Leave empty to test the newest releases." required: false default: "" permissions: - contents: write - pull-requests: write - issues: write - # A pull request this workflow opens with its own token starts no other workflow, except one it - # dispatches; it dispatches the test workflow on its branch, so the pull request has its checks. - actions: write + contents: read concurrency: group: browser-rows cancel-in-progress: false env: - RELEASE_TAG: builds-table # Each build is a download of hundreds of megabytes, and a run does no more than this many builds. MOST_PER_RUN: "3" jobs: - gate: - name: Check that this repository signs rows - runs-on: ubuntu-latest - outputs: - enabled: ${{ steps.key.outputs.enabled }} - steps: - # A job condition cannot read secrets, so a step says whether the signing key is there. - - id: key - env: - SIGNING_KEY: ${{ secrets.RIVET_TABLE_SIGNING_KEY }} - run: | - if [[ -n "$SIGNING_KEY" ]]; then echo "enabled=true" >> "$GITHUB_OUTPUT"; else echo "enabled=false" >> "$GITHUB_OUTPUT"; fi - - withdraw: - name: Take rows out of the published table - needs: gate - if: needs.gate.outputs.enabled == 'true' && github.event.inputs.withdraw != '' - runs-on: windows-latest - defaults: - run: - shell: pwsh - steps: - - uses: actions/checkout@v4 - with: - ref: develop - - - name: Build the table tool - working-directory: rivet - run: cargo build --release -p rivet-platform-windows --bin chrome-builds - - - name: Sign the published table again without the rows - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_REPO: ${{ github.repository }} - RIVET_TABLE_SIGNING_KEY: ${{ secrets.RIVET_TABLE_SIGNING_KEY }} - RIVET_TABLE_PUBLIC_KEY: ${{ vars.RIVET_TABLE_PUBLIC_KEY }} - WITHDRAW: ${{ github.event.inputs.withdraw }} - run: | - gh release download $env:RELEASE_TAG --pattern table.bin --output published.bin - if ($LASTEXITCODE -ne 0) { throw "There is no published table to take rows out of." } - $builds = @($env:WITHDRAW -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) - rivet/target/release/chrome-builds.exe table-withdraw published.bin table.bin @builds - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - gh release upload $env:RELEASE_TAG table.bin --clobber - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - watch: - name: Find builds with no row - needs: gate - if: needs.gate.outputs.enabled == 'true' && github.event.inputs.withdraw == '' && github.event.inputs.score == '' + name: Find new builds + if: github.event.inputs.score == '' runs-on: windows-latest defaults: run: @@ -130,9 +46,6 @@ jobs: builds: ${{ steps.pending.outputs.builds }} steps: - uses: actions/checkout@v4 - with: - # A trial makes rows with the code it is started on; every other run uses develop. - ref: ${{ inputs.trial && github.ref || 'develop' }} - name: Build the row tools working-directory: rivet @@ -150,9 +63,6 @@ jobs: id: pending env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - RIVET_TABLE_PUBLIC_KEY: ${{ vars.RIVET_TABLE_PUBLIC_KEY }} - TRIAL: ${{ inputs.trial }} - ONLY: ${{ inputs.only }} run: | $feeds = Join-Path $env:RUNNER_TEMP "feeds" New-Item -ItemType Directory -Force $feeds | Out-Null @@ -162,62 +72,23 @@ jobs: curl.exe -fsSL -o "$feeds/edge.json" "https://edgeupdates.microsoft.com/api/products?view=enterprise" gh api "repos/brave/brave-browser/releases?per_page=40" > "$feeds/brave.json" $tools = "rivet/target/release" - $tables = @("--table", "rivet/runtime/windows/rows/table.json") - # What has been published counts, even before its pull request is merged. - gh release download $env:RELEASE_TAG --pattern table.bin --dir $feeds 2>$null - if ($LASTEXITCODE -eq 0) { - & "$tools/chrome-builds.exe" table-read "$feeds/table.bin" "$feeds/published.json" - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $tables += @("--table", "$feeds/published.json") - } - & "$tools/rivet-rows.exe" known @tables | Set-Content "$feeds/known.json" + & "$tools/rivet-rows.exe" known --table rivet/runtime/windows/rows/table.json | Set-Content "$feeds/known.json" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } & "$tools/chrome-builds.exe" pending "$feeds/chrome-stable.json" "$feeds/chrome-beta.json" "$feeds/edge.json" "$feeds/brave.json" "$feeds/known.json" | Set-Content "$feeds/pending.json" if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } Get-Content "$feeds/pending.json" - $only = @($env:ONLY -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) - if ($only.Count) { - if ($env:TRIAL -ne 'true') { throw "Builds are named only for a trial run." } - # A named build need not be in the feeds any more: Edge's update service still serves it. - $listed = @(Get-Content -Raw "$feeds/pending.json" | ConvertFrom-Json) - $builds = @(foreach ($name in $only) { - $browser, $version = $name -split '@', 2 - $known = $listed | Where-Object { $_.browser -eq $browser -and $_.version -eq $version } | Select-Object -First 1 - if ($known) { $known } else { [pscustomobject]@{ browser = $browser; version = $version; channel = 'stable'; download = '' } } - }) - $json = $builds | ConvertTo-Json -Compress -AsArray - "builds=$json" >> $env:GITHUB_OUTPUT - exit 0 - } - $builds = foreach ($build in @(Get-Content -Raw "$feeds/pending.json" | ConvertFrom-Json)) { - # A proposal waits for its person, and a run must not spend its turn on it again. - $branch = "feat/row-$($build.browser -replace ' ','-')-$($build.version)".ToLower() - git ls-remote --exit-code --heads origin $branch | Out-Null - if ($LASTEXITCODE -eq 0) { "$($build.browser) $($build.version) waits for review."; continue } - # A build nobody can fetch yet must not take the turn of one that can be made now. - try { - ./.github/scripts/rows/fetch-browser.ps1 -Browser $build.browser -Version $build.version -Channel $build.channel -Download "$($build.download)" -ResolveOnly | Out-Null - $build - } catch { - "::warning::$($build.browser) $($build.version) has no row and cannot be fetched yet: $_" - } - } - $global:LASTEXITCODE = 0 - $builds = @(@($builds) | Where-Object { $_ -and $_ -isnot [string] } | Select-Object -First ([int]$env:MOST_PER_RUN)) + # The newest stable build of each browser that people have now. + $listed = @(Get-Content -Raw "$feeds/pending.json" | ConvertFrom-Json) + $builds = @($listed | Where-Object { $_.channel -eq 'stable' -and $_.serving } | + Group-Object browser | ForEach-Object { + $_.Group | Sort-Object { [version]$_.version } -Descending | Select-Object -First 1 + } | Select-Object -First ([int]$env:MOST_PER_RUN)) # Through the pipeline: -InputObject would wrap the whole list as one element of another list. $json = if ($builds.Count) { $builds | ConvertTo-Json -Compress -AsArray } else { "[]" } "builds=$json" >> $env:GITHUB_OUTPUT - exit 0 - - name: Tell a person that the watch failed - if: failure() && !inputs.trial - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - ./.github/scripts/rows/report-failure.ps1 -Title "Browser rows: the watch failed" - - row: - name: Row for ${{ matrix.build.browser }} ${{ matrix.build.version }} + find: + name: Find rows in ${{ matrix.build.browser }} ${{ matrix.build.version }} needs: watch if: needs.watch.outputs.builds != '[]' runs-on: windows-latest @@ -231,8 +102,6 @@ jobs: shell: pwsh steps: - uses: actions/checkout@v4 - with: - ref: ${{ inputs.trial && github.ref || 'develop' }} - uses: actions/download-artifact@v4 with: @@ -242,250 +111,27 @@ jobs: - name: Get the build id: build run: | - trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Get the build: $_"; break } ./.github/scripts/rows/fetch-browser.ps1 ` -Browser "${{ matrix.build.browser }}" -Version "${{ matrix.build.version }}" ` -Channel "${{ matrix.build.channel }}" -Download "${{ matrix.build.download }}" ` -Out (Join-Path $env:RUNNER_TEMP "browser") -Output $env:GITHUB_OUTPUT - - name: Get the build of the row before it - id: prior - run: | - trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Get the prior build: $_"; break } - $browser = "${{ matrix.build.browser }}" - $version = "${{ matrix.build.version }}" - $temp = $env:RUNNER_TEMP - $prior = Join-Path $temp "prior.json" - ./tools/rivet-rows.exe prior $browser $version --table rivet/runtime/windows/rows/table.json | Set-Content $prior - if ($LASTEXITCODE -ne 0) { throw "rivet-rows found no prior row for $browser $version" } - $priorVersion = (Get-Content -Raw $prior | ConvertFrom-Json).frame.version - # The prior build's own module gives what its row was made from: its function starts, - # its class names and the instructions the methods compare with the new build. - $found = Join-Path $temp "prior-build.txt" - $fetch = @{ Browser = $browser; Version = $priorVersion; Out = (Join-Path $temp "prior-browser"); Output = $found } - try { - ./.github/scripts/rows/fetch-browser.ps1 @fetch -Channel "${{ matrix.build.channel }}" - } catch { - if ("${{ matrix.build.channel }}" -eq 'stable') { throw "The prior build $browser $priorVersion could not be fetched: $_" } - ./.github/scripts/rows/fetch-browser.ps1 @fetch -Channel stable - } - $priorModule = (Get-Content $found | Where-Object { $_ -like 'module=*' } | Select-Object -First 1) -replace '^module=', '' - "module=$priorModule" >> $env:GITHUB_OUTPUT - - - name: Make the row - id: made - env: - PRIOR_MODULE: ${{ steps.prior.outputs.module }} - run: | - trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Make the row: $_"; break } - $temp = $env:RUNNER_TEMP - # Every function is looked for by its fingerprint and the methods that read the prior - # build next to the new one. Offsets, slots and sizes are read from the new module. - ./tools/chrome-builds.exe find "$temp/prior.json" $env:PRIOR_MODULE "${{ steps.build.outputs.module }}" "${{ matrix.build.version }}" "$temp/row.json" "$temp/report.json" - $code = $LASTEXITCODE - if ($code -ne 0 -and $code -ne 3) { throw "chrome-builds find exited with $code; report.json says why" } - # Fingerprints, read from this build's own module at the places the row holds, let the - # next build's row start from this one. A row that needs review may still hold a prior - # address, which would fingerprint the wrong code, so it gets none. - if ($code -eq 0) { - ./tools/chrome-builds.exe fingerprint "$temp/row.json" "${{ steps.build.outputs.module }}" "$temp/row.json" - if ($LASTEXITCODE -ne 0) { "The row has no fingerprints." } - } else { - "A row that needs review gets no fingerprints." - } - "for_review=$($code -eq 3)".ToLower() >> $env:GITHUB_OUTPUT - Get-Content "$temp/report.json" - exit 0 - - - name: Prove the row on the real browser - if: steps.made.outputs.for_review == 'false' - run: | - trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Prove the row: $_"; break } - $temp = $env:RUNNER_TEMP - # A throwaway key: this proves the same path a user's table takes, and nothing it signs leaves this job. - $pair = ./tools/chrome-builds.exe table-key - $env:RIVET_TABLE_SIGNING_KEY = ($pair[0] -split ' ')[1] - $env:RIVET_TABLE_PUBLIC_KEY = ($pair[1] -split ' ')[1] - # The drive step builds Rivet again and must trust the same throwaway key, so it reads it here. - Set-Content (Join-Path $temp "test-key.txt") $env:RIVET_TABLE_PUBLIC_KEY - $env:LOCALAPPDATA = Join-Path $temp "local" - New-Item -ItemType Directory -Force $env:LOCALAPPDATA | Out-Null - Set-Content "$temp/part.json" '{"schema":1,"sequence":0,"rows":[]}' - ./tools/chrome-builds.exe table-add "$temp/part.json" "$temp/row.json" - ./tools/chrome-builds.exe table-sign "$temp/part.json" "$temp/test.bin" - Push-Location rivet - cargo build -p rivet -p rivet-runtime-windows - if ($LASTEXITCODE -ne 0) { throw "cargo build exited with $LASTEXITCODE" } - target/debug/rivet.exe builds apply "$temp/test.bin" - if ($LASTEXITCODE -ne 0) { throw "rivet builds apply refused the test table" } - Pop-Location - ./scripts/tests/windows-row-proof.ps1 ` - -Rivet rivet/target/debug/rivet.exe -Runtime rivet/target/debug/rivet_runtime_windows.dll ` - -Browser "${{ steps.build.outputs.executable }}" -Work (Join-Path $temp "session") - - - name: Drive every feature on the real browser - if: steps.made.outputs.for_review == 'false' + - name: Run the finder on the build run: | - # A browser is listed as supported only when every feature check passed on it. A check - # that could not run counts as failed, so its row is not published, except the features - # rivet/platform/windows/test-desktop-limits.json lists, which stay reported as not driven. - trap { Add-Content (Join-Path $env:RUNNER_TEMP failure.txt) "Drive every feature: $_"; break } - $temp = $env:RUNNER_TEMP - $name = "${{ matrix.build.browser }}".ToLower() - $features = Join-Path $temp "session/features" - # The table the proof step applied lives here, and this Rivet trusts its key. - $env:LOCALAPPDATA = Join-Path $temp "local" - # This Rivet must trust the throwaway key the proof step signed the candidate row with, so the - # features run against the row being proposed; the key is built in, so it is set before the build. - $env:RIVET_TABLE_PUBLIC_KEY = (Get-Content (Join-Path $temp "test-key.txt")).Trim() - # An installed build has rivet.ico beside the runtime, which the taskbar relaunch row needs. - Copy-Item rivet/installer/windows/setup-ui/assets/logo.ico rivet/target/debug/rivet.ico -Force - # The harness builds Rivet itself, with the test flags that keep sync and sign-in off. - ./scripts/tests/windows-features.ps1 -Browsers $name ` - -Executable "${{ steps.build.outputs.executable }}" -OutDir $features - # A check of a feature the row turns off for this build is not required; the row ships with - # that feature off, and the gate prints a note for it. - ./tools/chrome-builds.exe gate (Join-Path $features "results.json") $name "$temp/row.json" - if ($LASTEXITCODE -ne 0) { throw "a feature check failed or could not run; results.json lists which" } - Set-Content (Join-Path $temp "session/features-passed") "${{ matrix.build.version }}" + ./tools/chrome-builds.exe find "${{ steps.build.outputs.module }}" "${{ matrix.build.version }}" (Join-Path $env:RUNNER_TEMP "report.json") + if ($LASTEXITCODE -ne 0) { throw "chrome-builds find exited with $LASTEXITCODE" } - uses: actions/upload-artifact@v4 - id: files if: always() with: - name: row-${{ matrix.build.browser }}-${{ matrix.build.version }} - path: | - ${{ runner.temp }}/row.json - ${{ runner.temp }}/report.json - ${{ runner.temp }}/part.json - ${{ runner.temp }}/session/row.png - ${{ runner.temp }}/session/row-failed.png - ${{ runner.temp }}/session/features-passed - ${{ runner.temp }}/session/features/results.json - ${{ runner.temp }}/session/features/traces/**/*.log - ${{ runner.temp }}/session/features/*/*.png - ${{ runner.temp }}/session/features/profiles/*/Crashpad/reports/*.dmp + name: finder-${{ matrix.build.browser }}-${{ matrix.build.version }} + path: ${{ runner.temp }}/report.json retention-days: 30 - - name: Tell a person that this build failed - if: failure() && !inputs.trial - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - ./.github/scripts/rows/report-failure.ps1 ` - -Title "Row failed: ${{ matrix.build.browser }} ${{ matrix.build.version }}" ` - -Reasons (Join-Path $env:RUNNER_TEMP failure.txt) ` - -Capture (Join-Path $env:RUNNER_TEMP session/row-failed.png) ` - -Files "${{ steps.files.outputs.artifact-url }}" - - - name: Ask a person about a row the generator cannot vouch for - if: steps.made.outputs.for_review == 'true' && !inputs.trial - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - $temp = $env:RUNNER_TEMP - $branch = "feat/row-$("${{ matrix.build.browser }}" -replace ' ','-')-${{ matrix.build.version }}".ToLower() - git ls-remote --exit-code --heads origin $branch | Out-Null - if ($LASTEXITCODE -eq 0) { "A pull request for this row is open."; exit 0 } - git config user.name "rivet-browser-rows" - git config user.email "rivet-browser-rows@users.noreply.github.com" - git switch -c $branch - ./tools/chrome-builds.exe table-add rivet/runtime/windows/rows/table.json "$temp/row.json" - git add rivet/runtime/windows/rows/table.json - git commit -m "Feat: Propose a row for ${{ matrix.build.browser }} ${{ matrix.build.version }}" - git push -u origin $branch - $report = Get-Content -Raw "$temp/report.json" | ConvertFrom-Json - $body = "The generator could not vouch for this row, so it was not published. It was made from the $($report.prior_version) row: $($report.fingerprinted.Count) of $($report.addresses) addresses matched exactly one place by fingerprint, and $($report.settled.Count) were settled by two methods.`n`n" - $body += (($report.review | ForEach-Object { "- $_" }) -join "`n") - if ($report.switched_off.Count -gt 0) { - $body += "`n`nThese features are off in this row, because a value they need could not be read from this build:`n`n" - $body += (($report.switched_off | ForEach-Object { "- $_" }) -join "`n") - } - gh pr create --draft --base develop --head $branch --title "Feat: Propose a row for ${{ matrix.build.browser }} ${{ matrix.build.version }}" --body $body - gh workflow run test.yml --ref $branch - - publish: - name: Publish the signed table - needs: row - # A row that failed its proof holds up nothing else: the others have passed theirs. - if: ${{ !cancelled() && needs.row.result != 'skipped' && !inputs.trial }} - runs-on: windows-latest - defaults: - run: - shell: pwsh - steps: - - uses: actions/checkout@v4 - with: - ref: develop - - - uses: actions/download-artifact@v4 - with: - path: artifacts - - - name: Sign and publish what passed - id: publish - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - GH_REPO: ${{ github.repository }} - RIVET_TABLE_SIGNING_KEY: ${{ secrets.RIVET_TABLE_SIGNING_KEY }} - RIVET_TABLE_PUBLIC_KEY: ${{ vars.RIVET_TABLE_PUBLIC_KEY }} - run: | - if (-not $env:RIVET_TABLE_SIGNING_KEY -or -not $env:RIVET_TABLE_PUBLIC_KEY) { - throw "Set the RIVET_TABLE_SIGNING_KEY secret and the RIVET_TABLE_PUBLIC_KEY variable." - } - $tool = (Get-ChildItem artifacts/row-tools/chrome-builds.exe).FullName - # A part exists only for a row whose report had nothing for review, only a row whose - # proof passed has its image, and only a browser that passed every feature has its mark. - $parts = @(Get-ChildItem artifacts/row-* -Directory | Where-Object { - (Test-Path "$_/part.json") -and (Test-Path "$_/session/row.png") -and - (Test-Path "$_/session/features-passed") - } | ForEach-Object { "$_/part.json" }) - if ($parts.Count -eq 0) { "No row passed."; "published=false" >> $env:GITHUB_OUTPUT; exit 0 } - & $tool table-merge rivet/runtime/windows/rows/table.json @parts - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - $signing = @("rivet/runtime/windows/rows/table.json", "table.bin") - gh release view $env:RELEASE_TAG 2>$null - if ($LASTEXITCODE -ne 0) { - gh release create $env:RELEASE_TAG --title "Supported-build table" --notes "The signed table Rivet downloads." --latest=false - } else { - gh release download $env:RELEASE_TAG --pattern table.bin --output published.bin - if ($LASTEXITCODE -eq 0) { $signing += "published.bin" } - } - & $tool table-sign @signing - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - gh release upload $env:RELEASE_TAG table.bin --clobber - if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - "published=true" >> $env:GITHUB_OUTPUT - - - name: Tell a person that publishing failed - if: failure() - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - ./.github/scripts/rows/report-failure.ps1 -Title "Browser rows: publishing the table failed" - - - name: Record the rows in the repository - if: steps.publish.outputs.published == 'true' - env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - $branch = "feat/rows-$env:GITHUB_RUN_ID" - git config user.name "rivet-browser-rows" - git config user.email "rivet-browser-rows@users.noreply.github.com" - git switch -c $branch - git add rivet/runtime/windows/rows/table.json - git commit -m "Feat: Record rows published by the table job" - git push -u origin $branch - gh pr create --base develop --head $branch --title "Feat: Record rows published by the table job" --body "These rows are already published in the signed table and passed the row proof in run $env:GITHUB_RUN_ID. Merging adds them to the table compiled into the next Rivet." - gh workflow run test.yml --ref $branch - score: - name: Score the generator against verified rows - # A measurement: it needs no signing key, and it publishes, proposes and reports nothing. + name: Score the finder against verified rows if: github.event.inputs.score != '' runs-on: windows-latest - permissions: - contents: read defaults: run: shell: pwsh @@ -496,14 +142,14 @@ jobs: working-directory: rivet run: cargo build --release -p rivet-platform-windows -p rivet-runtime-windows --bins - - name: Make each row without symbols and compare it with its verified row + - name: Find each build's values and compare them with its verified row env: SCORE: ${{ github.event.inputs.score }} run: | - $pairs = if ($env:SCORE -eq 'default') { @() } else { @($env:SCORE -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } + $builds = if ($env:SCORE -eq 'default') { @() } else { @($env:SCORE -split ';' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) } ./scripts/tests/row-score.ps1 ` - -Rows rivet/target/release/rivet-rows.exe -Generator rivet/target/release/chrome-builds.exe ` - -Table rivet/runtime/windows/rows/table.json -Pairs $pairs -Fetch ` + -Rows rivet/target/release/rivet-rows.exe -Finder rivet/target/release/chrome-builds.exe ` + -Table rivet/runtime/windows/rows/table.json -Builds $builds -Fetch ` -Work (Join-Path $env:RUNNER_TEMP "score") - uses: actions/upload-artifact@v4 diff --git a/rivet/platform/windows/rows/descriptions.json b/rivet/platform/windows/rows/descriptions.json new file mode 100644 index 0000000..30ec8ce --- /dev/null +++ b/rivet/platform/windows/rows/descriptions.json @@ -0,0 +1,223 @@ +{ + "schema": 1, + "values": [ + { + "path": "navigation.open_url", + "kind": "trace", + "texts": ["WebContentsImpl::OpenURL"], + "steps": [{"sole_caller": 3}], + "source": ["content/browser/web_contents/web_contents_impl.cc"], + "tag": "156.0.8078.80", + "note": "WebContentsImpl::OpenURL opens with TRACE_EVENT1(\"content\", \"WebContentsImpl::OpenURL\", ...)." + }, + { + "path": "omnibox.classify", + "kind": "trace", + "texts": ["AutocompleteClassifier::Classify"], + "steps": [{"sole_caller": 3}], + "source": ["components/omnibox/browser/autocomplete_classifier.cc"], + "tag": "156.0.8078.80", + "note": "AutocompleteClassifier::Classify opens with TRACE_EVENT1 of its own name." + }, + { + "path": "omnibox.start", + "kind": "trace", + "texts": ["AutocompleteController::Start"], + "steps": [{"sole_caller": 3}], + "source": ["components/omnibox/browser/autocomplete_controller.cc"], + "tag": "156.0.8078.80", + "note": "AutocompleteController::Start opens with TRACE_EVENT1 of its own name." + }, + { + "path": "omnibox.classifier_for_profile", + "kind": "trace", + "texts": ["AutocompleteClassifier"], + "steps": [{"sole_caller": 3}, {"most_callers_lead": 10}], + "source": ["chrome/browser/autocomplete/autocomplete_classifier_factory.cc"], + "tag": "156.0.8078.80", + "note": "The factory's constructor names its service \"AutocompleteClassifier\". GetInstance creates the factory, and GetForProfile, which every user of the classifier calls, is by far its most called caller." + }, + { + "path": "layout.on_paint", + "kind": "trace", + "texts": ["BrowserFrameViewWin::OnPaint"], + "steps": [{"sole_caller": 3}], + "source": ["chrome/browser/ui/views/frame/browser_frame_view_win.cc"], + "tag": "156.0.8078.80", + "note": "BrowserFrameViewWin::OnPaint opens with TRACE_EVENT0(\"views.frame\", ...)." + }, + { + "path": "layout.layout", + "kind": "trace", + "texts": ["BrowserFrameViewWin::Layout"], + "steps": [{"sole_caller": 3}], + "source": ["chrome/browser/ui/views/frame/browser_frame_view_win.cc"], + "tag": "156.0.8078.80", + "note": "BrowserFrameViewWin::Layout opens with TRACE_EVENT0(\"views.frame\", ...)." + }, + { + "path": "tabs.activate_tab", + "kind": "trace", + "texts": ["TabStripModel::ActivateTab"], + "steps": [{"sole_caller": 3}, {"only_caller_at_most_bytes": 128}], + "source": ["chrome/browser/ui/tabs/tab_strip_model.cc"], + "tag": "156.0.8078.80", + "note": "ActivateTab holds TRACE_EVENT0(\"ui\", \"TabStripModel::ActivateTab\"). ActivateTabAt is a check and one call to it, so it is its only small caller." + }, + { + "path": "side_panel.generate_colors_css", + "kind": "trace", + "texts": ["generate_rgb_vars"], + "steps": [{"sole_caller": 3}], + "source": ["chrome/browser/ui/webui/theme_source.cc"], + "tag": "156.0.8078.80", + "note": "GenerateColorsCss reads the \"generate_rgb_vars\" query parameter." + }, + { + "path": "side_panel.entry_id_to_string", + "kind": "trace", + "texts": ["kReadingList"], + "steps": [{"sole_caller": 3}], + "source": ["chrome/browser/ui/side_panel/side_panel_entry_id.cc", "chrome/browser/ui/side_panel/side_panel_entry_id.h"], + "tag": "156.0.8078.80", + "note": "SidePanelEntryIdToString returns #entry_id for each id of SIDE_PANEL_ENTRY_IDS, and kReadingList is one of them." + }, + { + "path": "_web_contents_table", + "kind": "table_of", + "function": "navigation.open_url", + "slot": 1, + "source": ["content/public/browser/web_contents.h", "content/public/browser/page_navigator.h"], + "tag": "156.0.8078.80", + "note": "WebContents derives first from PageNavigator, whose virtual destructor is slot 0 and OpenURL slot 1, so the table that holds OpenURL in slot 1 is the WebContents table of WebContentsImpl." + }, + { + "path": "app_window.browser_context", + "kind": "table_slot", + "table": "_web_contents_table", + "slot": 7, + "source": ["content/public/browser/web_contents.h"], + "tag": "156.0.8078.80", + "note": "GetBrowserContext is slot 7: the new virtuals of WebContents follow PageNavigator's two in declaration order, Android, iOS and Mac blocks left out." + }, + { + "path": "omnibox.browser_context", + "kind": "table_slot", + "table": "_web_contents_table", + "slot": 7, + "source": ["content/public/browser/web_contents.h"], + "tag": "156.0.8078.80", + "note": "The same GetBrowserContext as app_window.browser_context." + }, + { + "path": "tabs.visible_url", + "kind": "table_slot", + "table": "_web_contents_table", + "slot": 13, + "source": ["content/public/browser/web_contents.h"], + "tag": "156.0.8078.80", + "note": "GetVisibleURL is slot 13 in the declaration order of web_contents.h." + }, + { + "path": "layout.frame_vtable", + "kind": "class", + "names": ["BrowserFrameViewWin"], + "source": ["chrome/browser/ui/views/frame/browser_frame_view_win.h"], + "tag": "156.0.8078.80", + "note": "METADATA_HEADER(BrowserFrameViewWin, ...) names the class." + }, + { + "path": "frame.frame_view_vtable", + "kind": "class", + "names": ["BrowserFrameViewWin"], + "source": ["chrome/browser/ui/views/frame/browser_frame_view_win.h"], + "tag": "156.0.8078.80", + "note": "The same table as layout.frame_vtable." + }, + { + "path": "layout.caption_vtable", + "kind": "class", + "names": ["WindowsCaptionButton"], + "source": ["chrome/browser/ui/views/frame/windows_caption_button.h"], + "tag": "156.0.8078.80", + "note": "METADATA_HEADER(WindowsCaptionButton, ...) names the class." + }, + { + "path": "layout.corner_vtable", + "kind": "class", + "names": ["CustomFloatingCorner"], + "source": ["chrome/browser/ui/views/frame/custom_floating_corner.h"], + "tag": "156.0.8078.80", + "note": "METADATA_HEADER(CustomFloatingCorner, ...) names the class." + }, + { + "path": "side_panel.side_panel_vtable", + "kind": "class", + "names": ["SidePanel"], + "part": "view", + "source": ["chrome/browser/ui/views/side_panel/side_panel.h", "ui/views/view.h"], + "tag": "156.0.8078.80", + "note": "METADATA_HEADER(SidePanel, ...) names the class. The row holds the table of its views::View part." + }, + { + "path": "side_panel.browser_view_view_vtable", + "kind": "class", + "names": ["BrowserView"], + "part": "view", + "source": ["chrome/browser/ui/views/frame/browser_view.h", "ui/views/view.h"], + "tag": "156.0.8078.80", + "note": "METADATA_HEADER(BrowserView, ...) names the class. The row holds the table of its views::View part." + }, + { + "path": "split.location_bar_vtable", + "kind": "class", + "names": ["LocationBarView"], + "part": "view", + "source": ["chrome/browser/ui/views/location_bar/location_bar_view.h", "ui/views/view.h"], + "tag": "156.0.8078.80", + "note": "METADATA_HEADER(LocationBarView, ...) names the class. The row holds the table of its views::View part." + }, + { + "path": "layout.on_paint_slot", + "kind": "slot_of", + "table": "layout.frame_vtable", + "function": "layout.on_paint", + "source": ["chrome/browser/ui/views/frame/browser_frame_view_win.h"], + "tag": "156.0.8078.80", + "note": "OnPaint overrides views::View::OnPaint, so it sits in one slot of the frame view's table." + }, + { + "path": "layout.caption_paint_slot", + "kind": "slot_of", + "table": "layout.caption_vtable", + "function": "layout.caption_paint", + "source": ["chrome/browser/ui/views/frame/windows_caption_button.h"], + "tag": "156.0.8078.80", + "note": "The slot of WindowsCaptionButton::PaintButtonContents. Not found until layout.caption_paint has a description." + }, + { + "path": "tabs.browser_in_view", + "kind": "first_load", + "function": "tabs.active_web_contents", + "source": ["chrome/browser/ui/browser.h"], + "tag": "156.0.8078.80", + "note": "The member the accessor reads first. Not found until tabs.active_web_contents has a description." + }, + { + "path": "side_panel.browser_offset", + "kind": "first_load", + "function": "navigation.active_web_contents", + "source": ["chrome/browser/ui/browser.h"], + "tag": "156.0.8078.80", + "note": "The member the accessor reads first. Not found until navigation.active_web_contents has a description." + }, + { + "path": "app_window.web_view_size", + "kind": "allocation_size", + "constructor": "app_window.web_view_ctor", + "source": ["ui/views/controls/webview/webview.h"], + "tag": "156.0.8078.80", + "note": "The size every std::make_unique allocates. Not found until app_window.web_view_ctor has a description." + } + ] +} diff --git a/rivet/platform/windows/src/bin/chrome-builds.rs b/rivet/platform/windows/src/bin/chrome-builds.rs index 18cc22b..94a213b 100644 --- a/rivet/platform/windows/src/bin/chrome-builds.rs +++ b/rivet/platform/windows/src/bin/chrome-builds.rs @@ -1,13 +1,12 @@ -//! Makes and publishes rows of Rivet's supported-build table. No browser's debug symbols are read: -//! a new row comes from the verified prior row, its fingerprints, the prior module and the new one. +//! Finds the rows of Rivet's supported-build table in one browser build, and keeps the signed +//! table. No browser's debug symbols and no other build are read: every value is found in the build +//! at hand by the checked-in descriptions, written from public Chromium source. //! -//! `chrome-builds find ` -//! makes a candidate row for a new build and exits 3 when the row needs a person's review. -//! `chrome-builds score ` -//! makes the row of a build that already has a verified row the same way, compares the two value -//! by value and writes the score of each feature. It exits 5 when a value it found is wrong. -//! `chrome-builds fingerprint ` adds the fingerprints of a row's -//! functions, read from its own module, so the next build's row can start from them. +//! `chrome-builds find ` applies every description to one build and +//! writes the values found and not found, by feature. +//! `chrome-builds score ` does the same for a build that +//! has a verified row and compares the two value by value: per feature, hits, wrong values and +//! values not found. It exits 5 when a value it found is wrong. //! `chrome-builds pending ` //! prints the builds that have no row yet, most urgent first. //! `chrome-builds table-key` prints a new signing key pair. @@ -22,38 +21,15 @@ use std::path::Path; use std::process::ExitCode; -use rivet_platform_windows::chrome_build::{self, PeFile}; -use rivet_platform_windows::row_port::{self, PortReport}; -use rivet_platform_windows::{row_watch, signed_table}; +use rivet_platform_windows::chrome_build::PeFile; +use rivet_platform_windows::{row_find, row_watch, signed_table}; fn main() -> ExitCode { let arguments: Vec = std::env::args().skip(1).collect(); let result = match arguments.iter().map(String::as_str).collect::>().as_slice() { - ["find", prior, prior_module, module, version, row, report] => { - return match find( - Path::new(prior), - Path::new(prior_module), - Path::new(module), - version, - Path::new(row), - Path::new(report), - ) { - Ok(true) => ExitCode::SUCCESS, - Ok(false) => ExitCode::from(3), - Err(error) => { - eprintln!("chrome-builds: {error}"); - ExitCode::FAILURE - } - } - } - ["score", prior, prior_module, module, verified, out] => { - return match score( - Path::new(prior), - Path::new(prior_module), - Path::new(module), - Path::new(verified), - Path::new(out), - ) { + ["find", module, version, report] => find(Path::new(module), version, Path::new(report)), + ["score", module, verified, out] => { + return match score(Path::new(module), Path::new(verified), Path::new(out)) { Ok(true) => ExitCode::SUCCESS, Ok(false) => ExitCode::from(5), Err(error) => { @@ -67,7 +43,6 @@ fn main() -> ExitCode { } ["gate", results, browser] => gate(Path::new(results), browser, None), ["gate", results, browser, row] => gate(Path::new(results), browser, Some(Path::new(row))), - ["fingerprint", row, module, out] => fingerprint(Path::new(row), Path::new(module), Path::new(out)), ["release-sign", version, signed, files @ ..] => release_sign(version, Path::new(signed), files), ["release-check", signed, file] => release_check(Path::new(signed), Path::new(file)), ["table-key"] => signed_table::generate_key().map(|(private, public)| { @@ -84,7 +59,7 @@ fn main() -> ExitCode { ["table-withdraw", published, signed, builds @ ..] if !builds.is_empty() => { table_withdraw(Path::new(published), Path::new(signed), builds) } - _ => Err("usage: chrome-builds find | score | pending | gate [row.json] | fingerprint | release-sign ... | release-check | table-key | table-add | table-read | table-merge ... | table-sign [published-file] | table-withdraw ...".into()), + _ => Err("usage: chrome-builds find | score | pending | gate [row.json] | release-sign ... | release-check | table-key | table-add | table-read | table-merge ... | table-sign [published-file] | table-withdraw ...".into()), }; match result { Ok(()) => ExitCode::SUCCESS, @@ -99,153 +74,82 @@ fn read(path: &Path) -> Result, String> { std::fs::read(path).map_err(|error| format!("could not read {}: {error}", path.display())) } -/// Makes the row of `version` from the prior row, the prior row's own module and the new module. -fn make( - prior: &serde_json::Value, - prior_module: &Path, - module: &Path, - version: &str, -) -> Result<(serde_json::Value, PortReport), String> { - let prior_bytes = read(prior_module)?; - let prior_pe = - PeFile::parse(&prior_bytes).ok_or("the prior module is not a 64-bit PE image")?; - // A module of another build would give fingerprints and class names of the wrong functions. - let start = prior["frame"]["hwnd_for_view"] - .as_u64() - .and_then(|address| u32::try_from(address).ok()); - let prologue = prior["frame"]["hwnd_for_view_prologue"] - .as_str() - .and_then(chrome_build::hex); - match (start, prologue) { - (Some(start), Some(prologue)) - if prior_pe.read(start, prologue.len()) == Some(prologue.as_slice()) => {} - _ => return Err("the prior module is not the build of the prior row".into()), - } - // The fingerprints the prior row stored were read from this module when the row was made. - // A row stored without them gets them from the module now. - let prints = match prior["fingerprints"].as_object() { - Some(stored) => stored.clone(), - None => { - let (prints, missing) = row_port::fingerprints_of(prior, &prior_pe); - if !missing.is_empty() { - println!( - "the prior build gives no fingerprint for {}", - missing.join(", ") - ); - } - prints - } - }; - // Each class table of the prior row is found again by its views class's name too. - let classes = row_port::prior_classes(prior, &prior_pe); +/// Applies every description to one module. +fn find_in(module: &Path) -> Result { + let descriptions = row_find::descriptions()?; let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("the new module is not a 64-bit PE image")?; - let (mut row, mut report) = - row_port::find_candidate(prior, &prints, Some(&prior_pe), &classes, version, &pe); - row_port::leave_out_screen_origin(&mut row, &mut report); - report.review.extend(row_port::hand_only_review(prior)); - println!( - "exception tables: {} function starts in the prior build, {} in the new one; {} class tables named", - prior_pe.function_starts().len(), - pe.function_starts().len(), - classes.len() - ); - Ok((row, report)) + let pe = PeFile::parse(&bytes).ok_or("the module is not a 64-bit PE image")?; + Ok(row_find::find(&pe, &descriptions)) } -/// Makes a candidate row for a new build. True when nothing needs a person's review. -fn find( - prior_path: &Path, - prior_module: &Path, - module: &Path, - version: &str, - row_path: &Path, - report_path: &Path, -) -> Result { - let prior = json_file(prior_path)?; - let (row, report) = make(&prior, prior_module, module, version)?; - let text = |value: &dyn erased::Json| value.pretty(); - std::fs::write(row_path, text(&row)).map_err(|error| error.to_string())?; - std::fs::write(report_path, text(&report)).map_err(|error| error.to_string())?; - println!( - "{} {} from {}: {} of {} addresses found by fingerprint, {} settled by two methods, {} values read, {} carried, {} features off, {} for review", - report.browser, - report.version, - report.prior_version, - report.fingerprinted.len(), - report.addresses, - report.settled.len(), - report.derived.len(), - report.carried.len(), - report.switched_off.len(), - report.review.len() - ); - Ok(report.review.is_empty()) +fn write_json(path: &Path, value: &serde_json::Value) -> Result<(), String> { + let text = serde_json::to_string_pretty(value).map_err(|error| error.to_string())? + " +"; + std::fs::write(path, text).map_err(|error| format!("could not write {}: {error}", path.display())) } -/// Makes the row of a build that already has a verified row, and scores it against that row. -/// True when no value it found is wrong. Nothing is written but the score. -fn score( - prior_path: &Path, - prior_module: &Path, - module: &Path, - verified_path: &Path, - out: &Path, -) -> Result { - let prior = json_file(prior_path)?; - let verified = json_file(verified_path)?; - let version = verified["frame"]["version"] - .as_str() - .ok_or("the verified row has no frame version")? - .to_owned(); - let (row, report) = make(&prior, prior_module, module, &version)?; - let score = row_port::score_row(&row, &report, &verified, &prior); - std::fs::write( +/// Finds the values of one build and reports them by feature. Not finding a value is a result, +/// not a failure. +fn find(module: &Path, version: &str, report: &Path) -> Result<(), String> { + let found = find_in(module)?; + let groups = row_find::report(&found); + let values: serde_json::Map = found + .row_values() + .map(|(path, value)| (path.clone(), format!("{value:#x}").into())) + .collect(); + write_json( + report, + &serde_json::json!({ + "module": module.display().to_string(), + "version": version, + "values": values, + "features": groups, + }), + )?; + println!("{version}:"); + for (group, each) in &groups { + println!(" {group}: {} found, {} not found", each.found.len(), each.not_found.len()); + for line in &each.not_found { + println!(" not found: {line}"); + } + } + Ok(()) +} + +/// Finds the values of a build that has a verified row and scores them against it. True when no +/// value found is wrong. +fn score(module: &Path, verified: &Path, out: &Path) -> Result { + let verified = json_file(verified)?; + let found = find_in(module)?; + let score = row_find::score(&found, &verified); + write_json( out, - serde_json::to_string_pretty(&score).map_err(|error| error.to_string())? + "\n", - ) - .map_err(|error| error.to_string())?; + &serde_json::json!({ + "browser": verified["frame"]["browser"], + "version": verified["frame"]["version"], + "features": score.groups, + }), + )?; println!( - "{} {} from {}:", - score.browser, score.version, score.prior_version + "{} {}:", + verified["frame"]["browser"].as_str().unwrap_or("?"), + verified["frame"]["version"].as_str().unwrap_or("?") ); - for (feature, each) in &score.features { - let state = if each.off { "off" } else { "on" }; + for (group, each) in &score.groups { println!( - " {feature}: {state}, {} equal, {} wrong, {} carried, {} not found, {} not held", - each.equal, - each.different.len(), - each.carried.len(), + " {group}: {} hit, {} wrong, {} not found, {} unchecked", + each.hit, + each.wrong.len(), each.not_found.len(), - each.not_held.len() + each.unchecked.len() ); - for line in &each.different { + for line in &each.wrong { println!(" wrong: {line}"); } - for line in &each.carried { - println!(" carried: {line}"); - } - } - if !score.review.is_empty() { - println!( - " the row would stop for review: {}", - score.review.join("; ") - ); } Ok(score.wrong() == 0) } -mod erased { - pub trait Json { - fn pretty(&self) -> String; - } - impl Json for T { - fn pretty(&self) -> String { - serde_json::to_string_pretty(self).unwrap_or_default() + "\n" - } - } -} - fn json_file(path: &Path) -> Result { serde_json::from_slice(&read(path)?) .map_err(|error| format!("{} is not JSON: {error}", path.display())) @@ -382,18 +286,6 @@ fn gate(results: &Path, browser: &str, row: Option<&Path>) -> Result<(), String> Ok(()) } -/// Adds the function fingerprints of a verified row, read from its own module, so a runtime can -/// find the same functions in a build that has no row yet. -fn fingerprint(row_path: &Path, module: &Path, out: &Path) -> Result<(), String> { - let mut row: serde_json::Value = serde_json::from_slice(&read(row_path)?) - .map_err(|error| format!("the row is not JSON: {error}"))?; - let bytes = read(module)?; - let pe = PeFile::parse(&bytes).ok_or("the module is not a 64-bit PE image")?; - row_port::add_fingerprints(&mut row, &pe)?; - let text = serde_json::to_string_pretty(&row).map_err(|error| error.to_string())?; - std::fs::write(out, text).map_err(|error| format!("could not write {}: {error}", out.display())) -} - /// Signs the SHA-256 of each release file, so an installer or update applies only these files. fn release_sign(version: &str, signed: &Path, files: &[&str]) -> Result<(), String> { let private = std::env::var("RIVET_TABLE_SIGNING_KEY") diff --git a/rivet/platform/windows/src/chrome_build.rs b/rivet/platform/windows/src/chrome_build.rs index 158eb82..aee5df1 100644 --- a/rivet/platform/windows/src/chrome_build.rs +++ b/rivet/platform/windows/src/chrome_build.rs @@ -225,6 +225,58 @@ impl<'a> PeFile<'a> { ranges } + /// The exception table entry that starts at `start`, as its start, end and unwind data. The + /// linker writes the table sorted by start. + fn runtime_function(&self, start: u32) -> Option<(u32, u32, u32)> { + let (directory, size) = self.exception_directory; + let table = self.offset(directory).filter(|_| directory != 0)?; + let (mut low, mut high) = (0usize, (size / 12) as usize); + while low < high { + let middle = (low + high) / 2; + let entry = table + middle * 12; + let begin = u32_at(self.bytes, entry)?; + match begin.cmp(&start) { + std::cmp::Ordering::Less => low = middle + 1, + std::cmp::Ordering::Greater => high = middle, + std::cmp::Ordering::Equal => { + return Some(( + begin, + u32_at(self.bytes, entry + 4)?, + u32_at(self.bytes, entry + 8)?, + )) + } + } + } + None + } + + /// The first part of the function that the part at `start` belongs to. A part the linker moved + /// out of its function has unwind data with `UNW_FLAG_CHAININFO`, which ends in the entry of the + /// part it continues. A part without such data is a function's first part. + pub fn primary_part(&self, start: u32) -> u32 { + let mut at = start; + for _ in 0..8 { + let Some((_, _, unwind)) = self.runtime_function(at) else { + break; + }; + // The low bit marks an entry that points at another entry rather than unwind data. + let unwind = unwind & !1; + let Some(head) = self.read(unwind, 4) else { + break; + }; + if (head[0] >> 3) & 4 == 0 { + break; + } + let codes = u32::from(head[2]); + let chained = unwind + 4 + ((codes + 1) & !1) * 2; + match self.read(chained, 4) { + Some(raw) => at = u32::from_le_bytes(raw.try_into().expect("four bytes")), + None => break, + } + } + at + } + /// Finds the slot of `function` in the vtable at `vtable`, scanning a bounded number of slots. pub fn vtable_slot(&self, vtable: u32, function: u32) -> Option { (0..512u32).find(|slot| self.pointer_rva(vtable + slot * 8) == Some(function)) diff --git a/rivet/platform/windows/src/lib.rs b/rivet/platform/windows/src/lib.rs index 2734201..dd67e9d 100644 --- a/rivet/platform/windows/src/lib.rs +++ b/rivet/platform/windows/src/lib.rs @@ -11,16 +11,17 @@ pub mod control; pub mod focus; pub mod hold; pub mod row_class; -pub mod row_command; pub mod row_features; -pub mod row_port; +pub mod row_find; pub mod row_recipe; -pub mod row_resolve; pub mod row_watch; pub mod signed_table; pub mod start; +#[cfg(test)] +pub(crate) mod test_module; #[cfg(windows)] pub mod textservices; +pub mod x64; use std::path::Path; use std::time::Duration; diff --git a/rivet/platform/windows/src/row_class.rs b/rivet/platform/windows/src/row_class.rs index 0817a3a..7eb2d6b 100644 --- a/rivet/platform/windows/src/row_class.rs +++ b/rivet/platform/windows/src/row_class.rs @@ -12,13 +12,13 @@ //! them to load one loads, every function that loads the same pointer as its result, the tables //! whose second slot holds one of them, and the table the constructors that write such a table //! write at offset zero of the same object. The load is read the way the runtime's -//! `chromium/reflect.rs` reads it, so the generator and the runtime agree on the static a table +//! `chromium/reflect.rs` reads it, so the finder and the runtime agree on the static a table //! names. Nothing is guessed: a step that finds nothing, or more than one table, gives no table. use std::collections::{BTreeMap, BTreeSet, HashSet}; use crate::chrome_build::PeFile; -use crate::row_port::x64; +use crate::x64; /// How many levels of callers above the code that uses the name are read. const CALLER_DEPTH: usize = 3; @@ -64,7 +64,7 @@ pub fn load_target(pe: &PeFile, at: u32) -> Option<(u32, bool)> { } /// Every place outside the code that holds `name` as a zero-terminated text. -fn texts(pe: &PeFile, name: &str) -> BTreeSet { +pub(crate) fn texts(pe: &PeFile, name: &str) -> BTreeSet { let mut needle = name.as_bytes().to_vec(); needle.push(0); let mut found = BTreeSet::new(); @@ -83,12 +83,12 @@ fn texts(pe: &PeFile, name: &str) -> BTreeSet { /// A `lea` or `mov` of a 64-bit register with a RIP-relative operand. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct RipUse { - at: u32, - target: u32, +pub(crate) struct RipUse { + pub(crate) at: u32, + pub(crate) target: u32, register: u8, /// A `mov`, which reads the word at the target, rather than a `lea`. - word: bool, + pub(crate) word: bool, } fn rip_use(bytes: &[u8], rva: u32) -> Option { @@ -156,7 +156,7 @@ impl CodeIndex { /// Every RIP-relative `lea` or `mov` in the code whose target is one of `targets`, in the order /// of where they are. -fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { +pub(crate) fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { let index = CodeIndex::of(pe); let mut found = Vec::new(); for target in targets { @@ -174,7 +174,7 @@ fn rip_uses(pe: &PeFile, targets: &BTreeSet) -> Vec { /// Every direct `call` or `jmp` into one of `targets`, as (site, whether it is a jump), in the /// order of where they are. -fn branches_into(pe: &PeFile, targets: &BTreeSet) -> Vec<(u32, bool)> { +pub(crate) fn branches_into(pe: &PeFile, targets: &BTreeSet) -> Vec<(u32, bool)> { let index = CodeIndex::of(pe); let mut found = Vec::new(); for target in targets { @@ -191,7 +191,7 @@ fn branches_into(pe: &PeFile, targets: &BTreeSet) -> Vec<(u32, bool)> { } /// The function part the exception table lists around an address. -fn enclosing(ranges: &BTreeMap, rva: u32) -> Option { +pub(crate) fn enclosing(ranges: &BTreeMap, rva: u32) -> Option { let (start, end) = ranges.range(..=rva).next_back()?; (rva < *end).then_some(*start) } @@ -389,13 +389,42 @@ fn object_tables(stores: &[Store], around: &Store) -> Vec<(i64, u32)> { last.into_iter().collect() } +/// Which of an object's tables a class name means. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Place { + /// The table at this place in the order of where they go: 0 is the object's start. + At(usize), + /// The table of the object's `views::View` part. `ui/views/view.h` declares `View` with seven + /// polymorphic bases before `ui::metadata::MetaDataProvider` (`LayerDelegate`, + /// `LayerObserver`, `LayerOwner`, `AcceleratorTarget`, `EventTarget`, `EventHandler`, + /// `PropertyHandler`), so the `View` part's table is the seventh before the provider's. + View, +} + +/// How many tables of a `views::View` lie between its own table and its metadata provider's. +const VIEW_BEFORE_PROVIDER: usize = 7; + /// A class name and which of its object's tables is meant: `BrowserView` is the table at the start -/// of the object, `BrowserView#6` the seventh in the order of where they go. A class with several -/// bases has a table for each, and the order of the bases is the class's own declaration. -fn name_and_order(name: &str) -> (&str, usize) { +/// of the object, `BrowserView#6` the seventh in the order of where they go, and `BrowserView#view` +/// the table of its `views::View` part. A class with several bases has a table for each, and the +/// order of the bases is the class's own declaration. +fn name_and_order(name: &str) -> (&str, Place) { match name.split_once('#') { - Some((bare, order)) => (bare, order.parse().unwrap_or(usize::MAX)), - None => (name, 0), + Some((bare, "view")) => (bare, Place::View), + Some((bare, order)) => (bare, Place::At(order.parse().unwrap_or(usize::MAX))), + None => (name, Place::At(0)), + } +} + +/// Which of an object's tables, in the order of where they go, `order` means, when the metadata +/// provider's table is the one at `provider_offset`. +fn place_index(tables: &[(i64, u32)], provider_offset: i64, order: Place) -> Option { + match order { + Place::At(index) => Some(index), + Place::View => tables + .iter() + .position(|(at, _)| *at == provider_offset) + .and_then(|provider| provider.checked_sub(VIEW_BEFORE_PROVIDER)), } } @@ -404,7 +433,7 @@ fn tables_beside( pe: &PeFile, ranges: &BTreeMap, provider: u32, - order: usize, + order: Place, ) -> BTreeSet { let writers: BTreeSet = rip_uses(pe, &BTreeSet::from([provider])) .iter() @@ -423,7 +452,8 @@ fn tables_beside( { continue; } - if let Some((_, table)) = tables.get(order) { + let index = place_index(&tables, written.offset, order); + if let Some((_, table)) = index.and_then(|index| tables.get(index)) { found.insert(*table); } } @@ -450,187 +480,6 @@ pub fn class_tables(pe: &PeFile, name: &str) -> BTreeSet { found } -/// How many levels of callees below the code that fills the metadata are read for its name. -const CALLEE_DEPTH: usize = 2; -/// How many names may be tried for one table before it counts as too unclear to name. -const NAMES_MOST: usize = 16; -/// How long a class name may be. -const NAME_MOST: usize = 120; - -/// The zero-terminated text at `rva` when it reads as a C++ class name without its namespace. -fn identifier_at(pe: &PeFile, rva: u32) -> Option { - let bytes = [NAME_MOST + 1, 64, 32, 16, 8] - .into_iter() - .find_map(|length| pe.read(rva, length))?; - let end = bytes.iter().position(|byte| *byte == 0)?; - let name = &bytes[..end]; - let first = *name.first()?; - (name.len() >= 2 - && (first.is_ascii_alphabetic() || first == b'_') - && name - .iter() - .all(|byte| byte.is_ascii_alphanumeric() || *byte == b'_')) - .then(|| String::from_utf8_lossy(name).into_owned()) -} - -/// What a function's body loads with a RIP-relative `lea` outside the code, and the functions it -/// calls or jumps to directly. -fn body_of(pe: &PeFile, ranges: &BTreeMap, start: u32) -> (Vec, Vec) { - let end = ranges.get(&start).copied().unwrap_or(start); - let length = end.saturating_sub(start).min(BODY_MOST) as usize; - let Some(bytes) = pe.read(start, length) else { - return (vec![], vec![]); - }; - let (mut loads, mut callees) = (Vec::new(), Vec::new()); - let mut at = 0; - while at < bytes.len() { - let Some(instruction) = x64::decode_body(&bytes[at..]) else { - break; - }; - if instruction.length == 0 || at + instruction.length > bytes.len() { - break; - } - let raw = &bytes[at..at + instruction.length]; - let rva = start + at as u32; - if let Some(found) = (raw.len() == 7).then(|| rip_use(raw, rva)).flatten() { - if !found.word && !pe.is_code(found.target) { - loads.push(found.target); - } - } - if raw.len() == 5 && matches!(raw[0], 0xE8 | 0xE9) { - let rel = i32::from_le_bytes(raw[1..5].try_into().expect("five bytes")); - if let Ok(target) = u32::try_from(i64::from(rva) + 5 + i64::from(rel)) { - if ranges.contains_key(&target) { - callees.push(target); - } - } - } - at += instruction.length; - } - (loads, callees) -} - -/// The metadata statics a class table's objects reach, and the table's place among the object's -/// tables: each constructor that writes the table into an object also writes other tables into it, -/// and the second slot of the `ui::metadata::MetaDataProvider` table among them returns the class's -/// static, as `getters` reads. Constructors that put the table at different places give no place. -fn statics_of_table( - pe: &PeFile, - ranges: &BTreeMap, - table: u32, -) -> (BTreeSet<(u32, bool)>, Option) { - let writers: BTreeSet = rip_uses(pe, &BTreeSet::from([table])) - .iter() - .filter(|each| !each.word) - .filter_map(|each| enclosing(ranges, each.at)) - .collect(); - let mut found = BTreeSet::new(); - let mut orders = BTreeSet::new(); - for writer in writers { - let stores = stores_in(pe, writer, ranges[&writer]); - for written in stores.iter().filter(|store| store.table == table) { - let tables = object_tables(&stores, written); - let Some(order) = tables.iter().position(|(_, each)| *each == table) else { - continue; - }; - orders.insert(order); - for (_, other) in tables.iter().filter(|(_, other)| *other != table) { - let Some(getter) = pe.pointer_rva(other + 8).filter(|at| pe.is_code(*at)) else { - continue; - }; - if let Some(each) = load_target(pe, getter).filter(|(at, _)| !pe.is_code(*at)) { - found.insert(each); - } - } - } - } - let order = (orders.len() == 1) - .then(|| orders.into_iter().next()) - .flatten(); - (found, order) -} - -/// The names the code that fills a metadata static loads, nearest first: the texts that the -/// functions whose result is the static, and their callees, load. Only those that read as a class -/// name are kept. -fn names_of_static( - pe: &PeFile, - ranges: &BTreeMap, - found: (u32, bool), -) -> Vec> { - let mut layer: BTreeSet = rip_uses(pe, &BTreeSet::from([found.0])) - .iter() - .filter_map(|each| enclosing(ranges, each.at)) - .filter(|function| load_target(pe, *function) == Some(found)) - .collect(); - let mut seen = layer.clone(); - let mut by_depth = Vec::new(); - for _ in 0..=CALLEE_DEPTH { - if layer.is_empty() || seen.len() > CALLERS_MOST { - break; - } - let mut names = Vec::new(); - let mut next = BTreeSet::new(); - for function in &layer { - let (loads, callees) = body_of(pe, ranges, *function); - names.extend(loads.into_iter().filter_map(|at| identifier_at(pe, at))); - next.extend(callees.into_iter().filter(|callee| !seen.contains(callee))); - } - by_depth.push(names); - seen.extend(&next); - layer = next; - } - by_depth -} - -/// The views class a class table belongs to, by the class name its `ui::metadata` holds, read back -/// from the build: the metadata static the table's objects reach, and the names the code that fills -/// it loads. A name counts only where `class_tables` gives exactly this table for it, so a name -/// that is not the class's own gives none. The nearest code that yields exactly one such name -/// names the table; none, or two, gives no name. -pub fn class_name_of_table(pe: &PeFile, table: u32) -> Option { - let ranges = pe.function_ranges(); - let mut by_depth: Vec> = Vec::new(); - let (statics, order) = statics_of_table(pe, &ranges, table); - let order = order?; - let placed = |name: &str| match order { - 0 => name.to_owned(), - order => format!("{name}#{order}"), - }; - for each in statics { - for (depth, names) in names_of_static(pe, &ranges, each).into_iter().enumerate() { - if by_depth.len() <= depth { - by_depth.resize(depth + 1, Vec::new()); - } - by_depth[depth].extend(names); - } - } - let mut tried = BTreeSet::new(); - for names in by_depth { - let mut confirmed = BTreeSet::new(); - for name in names { - if tried.len() >= NAMES_MOST { - return None; - } - let name = placed(&name); - if tried.insert(name.clone()) && class_tables(pe, &name) == BTreeSet::from([table]) { - confirmed.insert(name); - } - } - match confirmed.len() { - 0 => continue, - 1 => return confirmed.into_iter().next(), - _ => return None, - } - } - None -} - -/// Whether `name` is the class name of `table` in `pe`: `class_tables` gives this table alone. -pub fn names_table(pe: &PeFile, name: &str, table: u32) -> bool { - class_tables(pe, name) == BTreeSet::from([table]) -} - #[cfg(test)] mod tests { use super::*; @@ -769,57 +618,13 @@ mod tests { assert!(class_tables(&pe, "BrowserView").is_empty()); } - #[test] - fn nfr6_a_class_name_counts_only_where_it_gives_the_prior_table_in_the_prior_build() { - let prior = class_module("WindowsCaptionButton"); - let prior = PeFile::parse(&prior).unwrap(); - let new = class_module("WindowsCaptionButton"); - let new = PeFile::parse(&new).unwrap(); - let place = crate::row_resolve::class_place(&prior, &new, 0x2400, "WindowsCaptionButton"); - assert_eq!(place, Ok(0x2400)); - // The prior row's table is another one: the name does not tell this table. - let other = crate::row_resolve::class_place(&prior, &new, 0x2200, "WindowsCaptionButton"); - assert!(other.unwrap_err().contains("in the prior build")); - let missing = crate::row_resolve::class_place(&prior, &new, 0x2400, "CustomFloatingCorner"); - assert!(missing.is_err()); - } - - #[test] - fn nfr6_a_class_name_is_read_from_the_prior_build_without_symbols() { - let bytes = class_module("EdgeBrowserFrameViewWin"); - let pe = PeFile::parse(&bytes).unwrap(); - // The table the constructor writes at the object's start is named by the text its - // metadata code loads, and the name gives that table back. - assert_eq!( - class_name_of_table(&pe, 0x2400).as_deref(), - Some("EdgeBrowserFrameViewWin") - ); - assert!(names_table(&pe, "EdgeBrowserFrameViewWin", 0x2400)); - // The provider table is written further into the object, so it names no class. - assert_eq!(class_name_of_table(&pe, 0x2200), None); - assert!(!names_table(&pe, "EdgeBrowserFrameViewWin", 0x2200)); - // A name the metadata code does not load does not name the table. - assert!(!names_table(&pe, "BrowserFrameViewWin", 0x2400)); - } - - #[test] - fn nfr6_a_class_name_is_a_plain_identifier() { - let mut code = class_module("BrowserView"); - let at = 0x400 + 0x1000 + 0x100; - assert_eq!(&code[at..at + 12], b"BrowserView\0"); - let pe = PeFile::parse(&code).unwrap(); - assert_eq!(identifier_at(&pe, 0x2100).as_deref(), Some("BrowserView")); - // A path or a qualified name is not a class name. - code[at + 7] = b':'; - let pe = PeFile::parse(&code).unwrap(); - assert_eq!(identifier_at(&pe, 0x2100), None); - } #[test] fn nfr6_a_table_past_the_start_of_its_object_is_named_with_its_place() { - // A class with several bases has a table for each. The row's table of `BrowserView` is the - // seventh in Edge 156, and a name without the place would give the first. - assert_eq!(name_and_order("BrowserView#6"), ("BrowserView", 6)); - assert_eq!(name_and_order("BrowserView"), ("BrowserView", 0)); + // A class with several bases has a table for each, and a name without the place would give + // the first. + assert_eq!(name_and_order("BrowserView#6"), ("BrowserView", Place::At(6))); + assert_eq!(name_and_order("BrowserView"), ("BrowserView", Place::At(0))); + assert_eq!(name_and_order("SidePanel#view"), ("SidePanel", Place::View)); let store = |table, offset| Store { index: 0, table, @@ -841,6 +646,18 @@ mod tests { assert!(object_tables(&stores[1..3], &stores[1]).is_empty()); } + #[test] + fn nfr6_a_view_part_is_the_seventh_table_before_its_metadata_provider() { + // A derived class's own table, then the View part's table and its six other bases, then + // the metadata provider's table. + let tables: Vec<(i64, u32)> = (0..10).map(|index| (index * 8, 0x100 + index as u32)).collect(); + assert_eq!(place_index(&tables, 8 * 8, Place::View), Some(1)); + assert_eq!(place_index(&tables, 8 * 8, Place::At(3)), Some(3)); + // A provider too near the object's start has no View part before it. + assert_eq!(place_index(&tables, 6 * 8, Place::View), None); + assert_eq!(place_index(&tables, 0x999, Place::View), None); + } + #[test] fn nfr6_the_stack_cookie_is_not_a_functions_result() { // sub rsp; mov rax, [rip+cookie]; xor rax, rsp; mov [rsp+0x28], rax; mov rsi, [rip+static] diff --git a/rivet/platform/windows/src/row_command.rs b/rivet/platform/windows/src/row_command.rs deleted file mode 100644 index 5a46bb9..0000000 --- a/rivet/platform/windows/src/row_command.rs +++ /dev/null @@ -1,505 +0,0 @@ -//! Finds a function a browser command runs from its public command id. -//! -//! `chrome::BrowserCommandController::HandleCommandWithDisposition` runs every browser command -//! through one `switch (id)` (`chrome/browser/ui/browser_command_controller.cc`), and each case -//! calls the command's function first: `case IDC_NEW_TAB` calls `chrome::NewTab(browser_, ...)`. -//! The ids are public (`chrome/app/chrome_command_ids.h`, kept in `command_ids`). A switch that -//! dense compiles to a jump table: the id less the lowest case is checked against the number of -//! cases, then the table gives the case's code. So the case of an id is read from the table, and -//! the function is the first one its code calls. -//! -//! A build holds other switches over command ids, so the reading is checked on the prior build -//! first: the switches whose case for the id calls the prior row's function there tell the lowest -//! case of the dispatch switch, and in the new build only switches with that same lowest case are -//! read. Nothing is taken unless they all name one function. - -use std::collections::BTreeSet; - -use crate::chrome_build::PeFile; -use crate::row_port::x64; - -/// How far a case's code is read for its first call. -const CASE_REACH: usize = 0x80; - -/// A jump table switch: the lowest case it subtracts, the highest index it takes, its table and -/// where an index past it goes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Switch { - pub at: u32, - pub lowest: i64, - pub bound: u32, - pub table: u32, - pub default: u32, -} - -fn i32_at(bytes: &[u8], at: usize) -> Option { - Some(i32::from_le_bytes(bytes.get(at..at + 4)?.try_into().ok()?)) -} - -fn rip_target(rva: u32, length: usize, displacement: i32) -> Option { - u32::try_from(i64::from(rva) + length as i64 + i64::from(displacement)).ok() -} - -/// `lea r64, [rip + d]; movsxd r64, dword [r + index * 4]; add r64, r64; jmp r64` at `at`, as the -/// table it loads. -fn table_jump(bytes: &[u8], at: usize, rva: u32) -> Option { - let code = bytes.get(at..at + 17)?; - let [rex, 0x8D, modrm, ..] = *code else { - return None; - }; - if rex & 0xFB != 0x48 || modrm & 0xC7 != 0x05 { - return None; - } - let register = (((rex >> 2) & 1) << 3) | ((modrm >> 3) & 7); - let table = rip_target(rva, 7, i32_at(code, 3)?)?; - // movsxd with a SIB byte that scales the index by four and takes the table as its base. - let [load_rex, 0x63, load_modrm, sib] = code[7..11] else { - return None; - }; - if load_rex & 0xF8 != 0x48 || load_modrm & 0xC7 != 0x04 || sib >> 6 != 2 { - return None; - } - if ((load_rex & 1) << 3) | (sib & 7) != register { - return None; - } - // add r64, r64 - let [add_rex, add, add_modrm] = code[11..14] else { - return None; - }; - if add_rex & 0xF8 != 0x48 || !matches!(add, 0x01 | 0x03) || add_modrm >> 6 != 3 { - return None; - } - // jmp r64, with a REX prefix for r8 to r15. - let jump = if code[14] == 0x41 { - &code[15..17] - } else { - &code[14..16] - }; - (jump[0] == 0xFF && jump[1] & 0xF8 == 0xE0).then_some(table) -} - -/// The `ja` that ends at `end`, as its target, with where it starts. -fn above_before(bytes: &[u8], end: usize, base: u32) -> Option<(usize, u32)> { - if let Some(start) = end.checked_sub(6) { - if bytes.get(start..start + 2) == Some(&[0x0F, 0x87][..]) { - let target = rip_target(base + start as u32, 6, i32_at(bytes, start + 2)?)?; - return Some((start, target)); - } - } - let start = end.checked_sub(2)?; - let [0x77, rel] = *bytes.get(start..end)? else { - return None; - }; - Some(( - start, - rip_target(base + start as u32, 2, i32::from(rel as i8))?, - )) -} - -/// The `cmp r32, imm` that ends at `end`, as its immediate, with where it starts. -fn compare_before(bytes: &[u8], end: usize) -> Option<(usize, u32)> { - let at = |length: usize| { - let start = end.checked_sub(length)?; - Some((start, bytes.get(start..end)?)) - }; - // cmp eax, imm32 - if let Some((start, [0x3D, ..])) = at(5) { - return Some((start, i32_at(bytes, start + 1)? as u32)); - } - for rex in [false, true] { - let skip = usize::from(rex); - if let Some((start, code)) = at(6 + skip) { - if (!rex || code[0] == 0x41) && code[skip] == 0x81 && code[skip + 1] & 0xF8 == 0xF8 { - return Some((start, i32_at(bytes, start + skip + 2)? as u32)); - } - } - if let Some((start, code)) = at(3 + skip) { - if (!rex || code[0] == 0x41) && code[skip] == 0x83 && code[skip + 1] & 0xF8 == 0xF8 { - return Some((start, code[skip + 2] as i8 as i32 as u32)); - } - } - } - None -} - -/// The lowest case a switch subtracts before `end`: `lea r32, [r - n]`, `add r32, -n` or -/// `sub r32, n`, nearest first. Zero when the switch takes the id as it is. -fn lowest_before(bytes: &[u8], end: usize) -> i64 { - for stop in (end.saturating_sub(16)..=end).rev() { - for start in stop.saturating_sub(7)..stop { - let Some(code) = bytes.get(start..stop) else { - continue; - }; - let skip = usize::from(matches!(code.first(), Some(0x40..=0x4F)) && code.len() > 1); - let rest = &code[skip..]; - let value = match *rest { - // lea r32, [r + disp32] or [r + disp8], with no SIB byte. - [0x8D, modrm, ..] if modrm >> 6 == 2 && modrm & 7 != 4 && rest.len() == 6 => { - i32_at(rest, 2).map(|value| -i64::from(value)) - } - [0x8D, modrm, disp] if modrm >> 6 == 1 && modrm & 7 != 4 => { - Some(-i64::from(disp as i8)) - } - [0x05, ..] if rest.len() == 5 => i32_at(rest, 1).map(|value| -i64::from(value)), - [0x2D, ..] if rest.len() == 5 => i32_at(rest, 1).map(i64::from), - [0x81, modrm, ..] if rest.len() == 6 && modrm & 0xF8 == 0xC0 => { - i32_at(rest, 2).map(|value| -i64::from(value)) - } - [0x81, modrm, ..] if rest.len() == 6 && modrm & 0xF8 == 0xE8 => { - i32_at(rest, 2).map(i64::from) - } - _ => None, - }; - if let Some(value) = value { - return value; - } - } - } - 0 -} - -/// Every jump table switch in the build's code. -pub fn switches(pe: &PeFile) -> Vec { - let mut found = Vec::new(); - for (base, bytes, is_code) in pe.sections() { - if !is_code { - continue; - } - for at in 0..bytes.len().saturating_sub(17) { - if bytes[at + 1] != 0x8D { - continue; - } - let rva = base + at as u32; - let Some(table) = table_jump(bytes, at, rva) else { - continue; - }; - if pe.read(table, 4).is_none() { - continue; - } - // The bound check ends right before the table load, or before a `mov r32, r32` that - // clears the index's upper half. - let Some((above, default)) = [at, at.saturating_sub(2), at.saturating_sub(3)] - .into_iter() - .find_map(|end| above_before(bytes, end, base)) - else { - continue; - }; - let Some((compare, bound)) = compare_before(bytes, above) else { - continue; - }; - found.push(Switch { - at: rva, - lowest: lowest_before(bytes, compare), - bound, - table, - default, - }); - } - } - found -} - -/// Where a switch sends `id`, unless it sends it where it sends an id it has no case for. -pub fn case_of(pe: &PeFile, switch: &Switch, id: i64) -> Option { - let index = u32::try_from(id - switch.lowest).ok()?; - if index > switch.bound { - return None; - } - let entry = i32::from_le_bytes(pe.read(switch.table + index * 4, 4)?.try_into().ok()?); - let case = rip_target(switch.table, 0, entry)?; - (case != switch.default && pe.is_code(case)).then_some(case) -} - -/// The first function the code at `at` calls before it leaves, after one jump it may start with. -pub fn first_call(pe: &PeFile, at: u32) -> Option { - let mut at = at; - let mut followed = false; - let bytes = pe.read(at, CASE_REACH)?; - let mut bytes = bytes.to_vec(); - let mut offset = 0; - while offset < bytes.len() { - let rva = at + offset as u32; - match bytes[offset] { - 0xE8 => return rip_target(rva, 5, i32_at(&bytes, offset + 1)?), - 0xE9 if offset == 0 && !followed => { - at = rip_target(rva, 5, i32_at(&bytes, 1)?)?; - bytes = pe.read(at, CASE_REACH)?.to_vec(); - followed = true; - continue; - } - 0xC3 | 0xE9 | 0xEB | 0xCC => return None, - _ => {} - } - let instruction = x64::decode_body(&bytes[offset..])?; - if instruction.length == 0 { - return None; - } - offset += instruction.length; - } - None -} - -/// The function each switch's case for `id` calls first, with the switch. -pub fn command_calls(pe: &PeFile, id: i64) -> Vec<(Switch, u32)> { - calls_through(pe, &switches(pe), id) -} - -/// The function each of `switches`' case for `id` calls first, with the switch. -fn calls_through(pe: &PeFile, switches: &[Switch], id: i64) -> Vec<(Switch, u32)> { - switches - .iter() - .filter_map(|switch| { - let case = case_of(pe, switch, id)?; - Some((*switch, first_call(pe, case)?)) - }) - .collect() -} - -/// The function the command `id` runs in the new build, read the same way that gives `target` in -/// the prior build: only switches whose lowest case is that of a prior switch that sends the id to -/// `target` count, all of them must call one function, and in the prior build every such switch -/// calls `target`. -pub fn command_place( - old_pe: &PeFile, - new_pe: &PeFile, - target: u32, - id: i64, -) -> Result { - let old = (old_pe, switches(old_pe)); - let new = (new_pe, switches(new_pe)); - command_place_in((old.0, &old.1), (new.0, &new.1), target, id) -} - -/// `command_place` with the switches of both builds already read. -pub fn command_place_in( - old: (&PeFile, &[Switch]), - new: (&PeFile, &[Switch]), - target: u32, - id: i64, -) -> Result { - let prior = calls_through(old.0, old.1, id); - let lowest: BTreeSet = prior - .iter() - .filter(|(_, called)| *called == target) - .map(|(switch, _)| switch.lowest) - .collect(); - if lowest.is_empty() { - return Err(format!( - "no switch of the prior build sends command {id} to it" - )); - } - let others = prior - .iter() - .filter(|(switch, called)| lowest.contains(&switch.lowest) && *called != target) - .count(); - if others > 0 { - return Err(format!( - "{others} switches of the prior build like its dispatch send command {id} elsewhere" - )); - } - let called: BTreeSet = calls_through(new.0, new.1, id) - .into_iter() - .filter(|(switch, _)| lowest.contains(&switch.lowest)) - .map(|(_, called)| called) - .collect(); - match called.into_iter().collect::>().as_slice() { - [only] => Ok(*only), - many => Err(format!( - "command {id} reaches {} functions through the dispatch in the new build", - many.len() - )), - } -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - use crate::row_resolve::tests::{call, module}; - - pub const DISPATCH: u32 = 0x101000; - const OTHER_SWITCH: u32 = 0x101800; - const TABLE: u32 = 0x201000; - const OTHER_TABLE: u32 = 0x203000; - const DEFAULT: u32 = 0x101f00; - const BACK: u32 = 0x102000; - const ELSEWHERE: u32 = 0x104000; - const LOWEST: i32 = 33000; - const NEW_TAB_ID: i64 = 34014; - - fn rel(from: u32, length: u32, to: u32) -> [u8; 4] { - ((i64::from(to) - i64::from(from) - i64::from(length)) as i32).to_le_bytes() - } - - /// A switch at `at` over ids from `lowest` with `bound + 1` cases in the table at `table`: - /// `lea eax, [rdx - lowest]; cmp eax, bound; ja default; lea rcx, [rip + table]; - /// movsxd rax, [rcx + rax * 4]; add rax, rcx; jmp rax`. - fn switch_code(at: u32, lowest: i32, bound: u32, table: u32) -> Vec { - let mut code = vec![0x8D, 0x82]; - code.extend((-lowest).to_le_bytes()); - code.push(0x3D); - code.extend(bound.to_le_bytes()); - code.extend([0x0F, 0x87]); - code.extend(rel(at + code.len() as u32 - 2, 6, DEFAULT)); - code.extend([0x48, 0x8D, 0x0D]); - code.extend(rel(at + code.len() as u32 - 3, 7, table)); - code.extend([0x48, 0x63, 0x04, 0x81, 0x48, 0x01, 0xC8, 0xFF, 0xE0]); - code - } - - /// A case that loads the browser and a constant and calls `to`, then leaves the switch. - fn case_code(at: u32, to: u32) -> Vec { - let mut code = vec![0x48, 0x8B, 0x4E, 0x10, 0xBA, 0x01, 0, 0, 0]; - code.extend(call(at + code.len() as u32, to)); - code.extend([0xEB, 0x00]); - code - } - - /// A table of `bound + 1` entries from `table`, each the distance to `default` except `cases`. - fn table_of(table: u32, bound: u32, cases: &[(u32, u32)]) -> Vec { - let mut bytes = Vec::new(); - for index in 0..=bound { - let to = cases - .iter() - .find(|(case, _)| *case == index) - .map_or(DEFAULT, |(_, to)| *to); - bytes.extend(((i64::from(to) - i64::from(table)) as i32).to_le_bytes()); - } - bytes - } - - /// A build whose dispatch over ids from 33000 sends IDC_BACK to `BACK` and IDC_NEW_TAB to - /// `new_tab`, and that holds a second switch, over ids from 34000, whose case for 34014 calls - /// another function. `new_tab` gets the bytes in `body` once, or at each of `copies`. - pub fn dispatch_module(new_tab: Option, copies: &[u32]) -> Vec { - let bound = 1100; - let back_case = 0x101100; - let new_tab_case = 0x101140; - let other_case = 0x101900; - let mut parts = vec![ - (DISPATCH, switch_code(DISPATCH, LOWEST, bound, TABLE)), - (back_case, case_code(back_case, BACK)), - ( - OTHER_SWITCH, - switch_code(OTHER_SWITCH, 34000, 40, OTHER_TABLE), - ), - (other_case, case_code(other_case, ELSEWHERE)), - (DEFAULT, vec![0xC3]), - (BACK, vec![0xC3]), - (ELSEWHERE, vec![0xC3]), - (OTHER_TABLE, table_of(OTHER_TABLE, 40, &[(14, other_case)])), - ]; - let mut cases = vec![(0, back_case)]; - if let Some(new_tab) = new_tab { - parts.push((new_tab_case, case_code(new_tab_case, new_tab))); - cases.push(((NEW_TAB_ID - i64::from(LOWEST)) as u32, new_tab_case)); - } - parts.push((TABLE, table_of(TABLE, bound, &cases))); - let body = [ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x83, 0xC4, 0x20, 0x5E, 0xC3, - ]; - let mut ranges = vec![(DISPATCH, DISPATCH + 0x40)]; - for at in copies { - parts.push((*at, body.to_vec())); - ranges.push((*at, *at + body.len() as u32)); - } - module(&parts, &ranges) - } - - pub const OLD_NEW_TAB: u32 = 0x103000; - pub const NEW_NEW_TAB: u32 = 0x103400; - - #[test] - fn nfr6_a_switch_case_is_read_from_its_jump_table() { - let bytes = dispatch_module(Some(OLD_NEW_TAB), &[OLD_NEW_TAB]); - let pe = PeFile::parse(&bytes).unwrap(); - let found = switches(&pe); - // The table load follows `lea`, `cmp` and `ja`: 6, 5 and 6 bytes. - let dispatch = found - .iter() - .find(|switch| switch.at == DISPATCH + 17) - .unwrap(); - assert_eq!( - ( - dispatch.lowest, - dispatch.bound, - dispatch.table, - dispatch.default - ), - (i64::from(LOWEST), 1100, TABLE, DEFAULT) - ); - let back = case_of(&pe, dispatch, 33000).and_then(|case| first_call(&pe, case)); - assert_eq!(back, Some(BACK)); - // An id with no case goes where the switch sends any id it does not know. - assert_eq!(case_of(&pe, dispatch, 33001), None); - assert_eq!(case_of(&pe, dispatch, 40000), None); - let mut called: Vec = command_calls(&pe, NEW_TAB_ID) - .into_iter() - .map(|(_, to)| to) - .collect(); - called.sort(); - assert_eq!(called, [OLD_NEW_TAB, ELSEWHERE]); - } - - /// What the resolver makes of `chrome::NewTab` between the two builds, with the places its - /// fingerprint matched off the exception table's function starts. - fn resolve_new_tab(loose: Vec) -> crate::row_resolve::Resolution { - use crate::row_resolve::{resolve, Kind, Wanted}; - use std::collections::BTreeMap; - let old = dispatch_module(Some(OLD_NEW_TAB), &[OLD_NEW_TAB]); - let new = dispatch_module(Some(NEW_NEW_TAB), &[NEW_NEW_TAB]); - let (old, new) = (PeFile::parse(&old).unwrap(), PeFile::parse(&new).unwrap()); - let wanted = BTreeMap::from([( - OLD_NEW_TAB, - Wanted { - kind: Kind::Function, - candidates: None, - class: None, - command: Some(NEW_TAB_ID), - loose, - }, - )]); - let none = BTreeSet::new(); - resolve(&old, &new, &BTreeMap::new(), &wanted, &none, &none) - } - - #[test] - fn nfr6_new_tab_is_taken_where_its_command_and_fingerprint_agree() { - let resolution = resolve_new_tab(vec![NEW_NEW_TAB]); - assert_eq!(resolution.places.get(&OLD_NEW_TAB), Some(&NEW_NEW_TAB)); - assert_eq!( - resolution.settled, - ["0x103000 -> 0x103400 by its fingerprint and its command id"] - ); - // The command id alone is one method. - let alone = resolve_new_tab(Vec::new()); - assert!(alone.places.is_empty()); - let reason = &alone.reasons[&OLD_NEW_TAB]; - assert!( - reason.starts_with("only its command id found it"), - "{reason}" - ); - } - - #[test] - fn nfr6_new_tab_is_found_from_the_new_tab_command() { - let old = dispatch_module(Some(OLD_NEW_TAB), &[OLD_NEW_TAB]); - let new = dispatch_module(Some(NEW_NEW_TAB), &[NEW_NEW_TAB]); - let (old, new) = (PeFile::parse(&old).unwrap(), PeFile::parse(&new).unwrap()); - // Only the dispatch's own switch counts; the other switch's case calls another function. - assert_eq!( - command_place(&old, &new, OLD_NEW_TAB, NEW_TAB_ID), - Ok(NEW_NEW_TAB) - ); - // The prior build must send the command to the prior row's function. - let refused = command_place(&old, &new, 0x103800, NEW_TAB_ID).unwrap_err(); - assert!( - refused.starts_with("no switch of the prior build"), - "{refused}" - ); - // A new build whose dispatch has no case for the command gives nothing. - let gone = dispatch_module(None, &[]); - let gone = PeFile::parse(&gone).unwrap(); - let none = command_place(&old, &gone, OLD_NEW_TAB, NEW_TAB_ID).unwrap_err(); - assert!(none.contains("reaches 0 functions"), "{none}"); - } -} diff --git a/rivet/platform/windows/src/row_find.rs b/rivet/platform/windows/src/row_find.rs new file mode 100644 index 0000000..caa8a7c --- /dev/null +++ b/rivet/platform/windows/src/row_find.rs @@ -0,0 +1,1058 @@ +//! Finds the values of a row in one browser build, from that build's own binary alone. +//! +//! Each value has a description in `rows/descriptions.json`, written from Chromium's public +//! source: the class name its `ui::metadata` gives a views class, the name a `TRACE_EVENT` gives a +//! function, a slot that a public header's declaration order gives, and the readers of +//! `row_recipe`. A description names the source file and the release tag it was written from. No +//! other build is read, and no address of another row is used as an answer. +//! +//! Every step must leave exactly one candidate. A step that leaves none, or more than one, gives +//! no value, and the value is reported as not found with the reason. A description may list +//! variations, such as a trace name before and after a rename, and every variation is tried on +//! every build: the candidates of all of them together must still be exactly one. + +use std::collections::{BTreeMap, BTreeSet, HashSet}; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +use crate::chrome_build::PeFile; +use crate::{row_class, row_recipe, x64}; + +/// The checked-in descriptions. +pub const DESCRIPTIONS: &str = include_str!("../rows/descriptions.json"); + +/// The version of the description format this finder reads. +pub const SCHEMA: u32 = 1; + +/// How many slots of a class table are read at most. +const TABLE_SLOTS: u32 = 512; +/// How far a function body is read for its calls. +const BODY_MOST: u32 = 0x4000; +/// How many parts a chain of moved function parts may have before it counts as broken. +const PATH_DEPTH: usize = 32; + +/// The description file. +#[derive(Debug, Clone, Deserialize)] +pub struct Descriptions { + pub schema: u32, + pub values: Vec, +} + +/// How to find one value of a row. +#[derive(Debug, Clone, Deserialize)] +pub struct Description { + /// The value's path in a row: `frame.` for the frame part, `
.` for the + /// build part. A path that starts with `_` is a step other values use and not a row value. + pub path: String, + /// The public Chromium source files the description was written from. + pub source: Vec, + /// The Chromium release tag of those files. + pub tag: String, + /// Why the description reads the build this way, in a sentence. + #[serde(default)] + pub note: String, + #[serde(flatten)] + pub how: How, +} + +/// The ways a value is found. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum How { + /// The class table of a views class, by the class names `METADATA_HEADER` gives it. With a + /// slot, the function in that slot of the table. + Class { + names: Vec, + #[serde(default)] + part: Part, + #[serde(default)] + slot: Option, + }, + /// The function that uses one of the texts, such as a `TRACE_EVENT` name, then the steps. + Trace { + texts: Vec, + #[serde(default)] + steps: Vec, + }, + /// The class table that holds the function another value found at the slot. + TableOf { function: String, slot: u32 }, + /// The function at a slot of a class table another value found. + TableSlot { table: String, slot: u32 }, + /// The slot of a function in a class table, both found by other values. + SlotOf { table: String, function: String }, + /// The member an accessor another value found reads from `this` with its first instruction. + FirstLoad { function: String }, + /// The size every direct caller of a constructor another value found allocates it with. + AllocationSize { constructor: String }, +} + +/// Which table of a views object a class description means. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Part { + /// The table at the object's start. + #[default] + Object, + /// The table of the object's `views::View` part. + View, +} + +/// A step from one function to another. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum Step { + /// Up to this many times, the function that calls this one from its only call site, while + /// nothing takes this one's address. An optimiser may move a body into a helper with one + /// caller. Stopping early is not a failure. + SoleCaller(u32), + /// The only function that calls this one and is no larger than this many bytes. + OnlyCallerAtMostBytes(u32), + /// The function that calls this one and is itself called from the most places, when it has at + /// least this many times as many call sites as the next one. + MostCallersLead(u32), + /// The function this one calls at this place, counting its direct calls from 0. + CalleeNth(usize), +} + +impl How { + /// The values this one is found from. + pub fn needs(&self) -> Vec<&str> { + match self { + How::Class { .. } | How::Trace { .. } => vec![], + How::TableOf { function, .. } => vec![function], + How::TableSlot { table, .. } => vec![table], + How::SlotOf { table, function } => vec![table, function], + How::FirstLoad { function } => vec![function], + How::AllocationSize { constructor } => vec![constructor], + } + } +} + +/// Reads a description file and checks that every value is described once, from a named source. +pub fn parse(text: &str) -> Result, String> { + let file: Descriptions = + serde_json::from_str(text).map_err(|error| format!("the descriptions are not valid: {error}"))?; + if file.schema != SCHEMA { + return Err(format!( + "the descriptions are schema {}, and this finder reads {SCHEMA}", + file.schema + )); + } + let mut paths = HashSet::new(); + for description in &file.values { + if !paths.insert(description.path.as_str()) { + return Err(format!("{} is described twice", description.path)); + } + if description.source.is_empty() || description.tag.is_empty() { + return Err(format!( + "{} names no public source file and tag", + description.path + )); + } + let empty = match &description.how { + How::Class { names, .. } => names.is_empty(), + How::Trace { texts, .. } => texts.is_empty(), + _ => false, + }; + if empty { + return Err(format!("{} has nothing to look for", description.path)); + } + } + // A value may need one that has no description yet. It is then reported as not found, with + // the value it waits for, so the description is ready when its input gets one. + Ok(file.values) +} + +/// The checked-in descriptions. +pub fn descriptions() -> Result, String> { + parse(DESCRIPTIONS) +} + +/// What the finder made of one build. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] +pub struct Found { + /// Each value found, by path. + pub values: BTreeMap, + /// Each value not found, by path, with the reason. + pub not_found: BTreeMap, +} + +impl Found { + /// The row values only: the steps whose path starts with `_` are left out. + pub fn row_values(&self) -> impl Iterator { + self.values.iter().filter(|(path, _)| !path.starts_with('_')) + } +} + +/// Applies every description to one build. +pub fn find(pe: &PeFile, descriptions: &[Description]) -> Found { + let mut finder = Finder { + pe, + ranges: pe.function_ranges(), + by_path: descriptions + .iter() + .map(|description| (description.path.as_str(), description)) + .collect(), + done: BTreeMap::new(), + busy: BTreeSet::new(), + }; + for description in descriptions { + let _ = finder.value(&description.path); + } + let mut found = Found::default(); + for (path, result) in finder.done { + match result { + Ok(value) => { + found.values.insert(path, value); + } + Err(reason) => { + found.not_found.insert(path, reason); + } + } + } + found +} + +/// The one item of a set, or why there is not one. +fn one(items: &BTreeSet, what: &str) -> Result { + let mut iter = items.iter(); + match (iter.next(), iter.next()) { + (Some(only), None) => Ok(*only), + (None, _) => Err(format!("no {what}")), + _ => Err(format!( + "{} {what}: {}", + items.len(), + items + .iter() + .take(8) + .map(|item| format!("{item:#x}")) + .collect::>() + .join(", ") + )), + } +} + +struct Finder<'d, 'p, 'a> { + pe: &'p PeFile<'a>, + ranges: BTreeMap, + by_path: BTreeMap<&'d str, &'d Description>, + done: BTreeMap>, + busy: BTreeSet, +} + +impl Finder<'_, '_, '_> { + fn value(&mut self, path: &str) -> Result { + if let Some(done) = self.done.get(path) { + return done.clone(); + } + let Some(description) = self.by_path.get(path).copied() else { + return Err(format!("{path} has no description")); + }; + if self.busy.len() > PATH_DEPTH || !self.busy.insert(path.to_owned()) { + return Err(format!("{path} is needed to find itself")); + } + let result = self.run(&description.how); + self.busy.remove(path); + self.done.insert(path.to_owned(), result.clone()); + result + } + + /// An address another value found. + fn need(&mut self, path: &str) -> Result { + if !self.by_path.contains_key(path) { + return Err(format!("needs {path}, which has no description")); + } + let value = self + .value(path) + .map_err(|_| format!("needs {path}, which was not found"))?; + u32::try_from(value).map_err(|_| format!("{path} {value:#x} is not an address")) + } + + fn run(&mut self, how: &How) -> Result { + let pe = self.pe; + match how { + How::Class { names, part, slot } => { + let mut tables = BTreeSet::new(); + for name in names { + let name = match part { + Part::Object => name.clone(), + Part::View => format!("{name}#view"), + }; + tables.extend(row_class::class_tables(pe, &name)); + } + let table = one(&tables, "class tables")?; + match slot { + None => Ok(u64::from(table)), + Some(slot) => self.slot_function(table, *slot).map(u64::from), + } + } + How::Trace { texts, steps } => { + let mut function = self.holder(texts)?; + for step in steps { + function = self.step(function, *step)?; + } + Ok(u64::from(function)) + } + How::TableOf { function, slot } => { + let function = self.need(function)?; + let holders = self.words_holding(function); + let word = one(&holders, "class table words that hold it")?; + let table = word + .checked_sub(slot * 8) + .ok_or("the slot lies before the section")?; + // Every slot up to it must be code, so the slot lies inside one table. + self.slot_function(table, *slot)?; + Ok(u64::from(table)) + } + How::TableSlot { table, slot } => { + let table = self.need(table)?; + self.slot_function(table, *slot).map(u64::from) + } + How::SlotOf { table, function } => { + let (table_at, function_at) = (self.need(table)?, self.need(function)?); + let mut slots = BTreeSet::new(); + for slot in 0..TABLE_SLOTS { + match pe.pointer_rva(table_at + slot * 8) { + Some(entry) if pe.is_code(entry) => { + if entry == function_at { + slots.insert(slot); + } + } + _ => break, + } + } + let slot = one(&slots, "slots that hold it")?; + // The recipe's own check, so the finder and a recipe agree on a slot. + row_recipe::slot_in(pe, (table.as_str(), table_at), (function.as_str(), function_at)) + .and_then(|recipe| match recipe == u64::from(slot) { + true => Ok(recipe), + false => Err(format!("the recipe reads slot {recipe}, not {slot}")), + }) + } + How::FirstLoad { function } => { + let at = self.need(function)?; + row_recipe::member_read_by(pe, (function.as_str(), at)) + } + How::AllocationSize { constructor } => { + let at = self.need(constructor)?; + row_recipe::allocation_size(pe, (constructor.as_str(), at)) + } + } + } + + /// The function at `slot` of the table at `table`, where every slot up to it is code. + fn slot_function(&self, table: u32, slot: u32) -> Result { + let pe = self.pe; + for each in 0..=slot { + let entry = pe.pointer_rva(table + each * 8); + if !entry.is_some_and(|entry| pe.is_code(entry)) { + return Err(format!( + "slot {each} of the table at {table:#x} is not code, so slot {slot} is past its end" + )); + } + } + pe.pointer_rva(table + slot * 8) + .ok_or_else(|| format!("slot {slot} of the table at {table:#x} cannot be read")) + } + + /// The first part of the listed function around an address. + fn function_at(&self, rva: u32) -> Option { + row_class::enclosing(&self.ranges, rva).map(|part| self.pe.primary_part(part)) + } + + /// The one function that loads the address of one of the texts. + fn holder(&self, texts: &[String]) -> Result { + let mut places = BTreeSet::new(); + for text in texts { + places.extend(row_class::texts(self.pe, text)); + } + if places.is_empty() { + return Err("the build holds none of the texts".into()); + } + let mut holders = BTreeSet::new(); + for each in row_class::rip_uses(self.pe, &places) { + if each.word { + continue; + } + let function = self.function_at(each.at).ok_or_else(|| { + format!( + "the code at {:#x} that uses the text lies in no listed function", + each.at + ) + })?; + holders.insert(function); + } + one(&holders, "functions that use the text") + } + + /// Every call site of a function, jumps included. + fn call_sites(&self, function: u32) -> Vec { + row_class::branches_into(self.pe, &BTreeSet::from([function])) + .into_iter() + .map(|(site, _)| site) + .collect() + } + + /// The functions that call `function`, other than itself. + fn callers(&self, function: u32) -> BTreeSet { + self.call_sites(function) + .into_iter() + .filter_map(|site| self.function_at(site)) + .filter(|caller| *caller != function) + .collect() + } + + fn address_taken(&self, function: u32) -> bool { + row_class::rip_uses(self.pe, &BTreeSet::from([function])) + .iter() + .any(|each| !each.word) + } + + fn size(&self, function: u32) -> u32 { + self.ranges + .get(&function) + .map_or(0, |end| end.saturating_sub(function)) + } + + fn step(&self, function: u32, step: Step) -> Result { + match step { + Step::SoleCaller(times) => { + let mut at = function; + for _ in 0..times { + let sites = self.call_sites(at); + let [site] = sites.as_slice() else { + break; + }; + if self.address_taken(at) { + break; + } + match self.function_at(*site) { + Some(caller) if caller != at => at = caller, + _ => break, + } + } + Ok(at) + } + Step::OnlyCallerAtMostBytes(bytes) => { + let small: BTreeSet = self + .callers(function) + .into_iter() + .filter(|caller| (1..=bytes).contains(&self.size(*caller))) + .collect(); + one(&small, &format!("callers of at most {bytes:#x} bytes")) + } + Step::MostCallersLead(times) => { + let mut counted: Vec<(usize, u32)> = self + .callers(function) + .into_iter() + .map(|caller| (self.call_sites(caller).len(), caller)) + .collect(); + counted.sort_unstable_by(|a, b| b.cmp(a)); + match counted.as_slice() { + [] => Err("no callers".into()), + [(_, only)] => Ok(*only), + [(first, top), (second, _), ..] => { + if *first >= (times as usize) * (*second).max(1) { + Ok(*top) + } else { + Err(format!( + "no caller leads by {times} times: {first} call sites against {second}" + )) + } + } + } + } + Step::CalleeNth(index) => { + let calls = self.calls_in(function)?; + calls.get(index).copied().ok_or_else(|| { + format!("{function:#x} makes {} direct calls, not {}", calls.len(), index + 1) + }) + } + } + } + + /// The functions `function` calls directly, in the order of its code. + fn calls_in(&self, function: u32) -> Result, String> { + let end = self + .ranges + .get(&function) + .copied() + .ok_or_else(|| format!("{function:#x} is not a listed function start"))?; + let length = end.saturating_sub(function).min(BODY_MOST) as usize; + let bytes = self + .pe + .read(function, length) + .ok_or_else(|| format!("{function:#x} cannot be read"))?; + let mut calls = Vec::new(); + let mut at = 0; + while at < bytes.len() { + let instruction = x64::decode_body(&bytes[at..]) + .filter(|instruction| instruction.length > 0) + .ok_or_else(|| format!("an instruction at {:#x} cannot be read", function + at as u32))?; + if bytes[at] == 0xE8 && instruction.length == 5 && at + 5 <= bytes.len() { + let relative = i32::from_le_bytes(bytes[at + 1..at + 5].try_into().expect("four bytes")); + let target = i64::from(function) + at as i64 + 5 + i64::from(relative); + if let Some(target) = u32::try_from(target).ok().filter(|target| self.pe.is_code(*target)) { + calls.push(target); + } + } + at += instruction.length; + } + Ok(calls) + } + + /// Every pointer-sized word outside the code that holds the address of `function`. + fn words_holding(&self, function: u32) -> BTreeSet { + let wanted = self.pe.image_base() + u64::from(function); + let mut found = BTreeSet::new(); + for (base, bytes, is_code) in self.pe.sections() { + if is_code { + continue; + } + for at in (0..bytes.len().saturating_sub(7)).step_by(8) { + let word = u64::from_le_bytes(bytes[at..at + 8].try_into().expect("in range")); + if word == wanted { + found.insert(base + at as u32); + } + } + } + found + } +} + +/// The group a value is reported in: its feature, or the window, whose values have no switch. +pub fn group_of(path: &str) -> &'static str { + match path.strip_prefix("frame.") { + Some(_) => WINDOW, + None => crate::row_features::feature_of(path).map_or(WINDOW, |feature| feature.name), + } +} + +/// The group of the values the window cannot do without. +pub const WINDOW: &str = "window"; + +/// How many values of each group were found and not found, and which. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] +pub struct GroupReport { + pub found: Vec, + pub not_found: Vec, +} + +/// The finder's report on one build, by group. +pub fn report(found: &Found) -> BTreeMap { + let mut groups: BTreeMap = BTreeMap::new(); + for (path, value) in found.row_values() { + groups + .entry(group_of(path).to_owned()) + .or_default() + .found + .push(format!("{path}: {value:#x}")); + } + for (path, reason) in found.not_found.iter().filter(|(path, _)| !path.starts_with('_')) { + groups + .entry(group_of(path).to_owned()) + .or_default() + .not_found + .push(format!("{path}: {reason}")); + } + groups +} + +/// How the finder did on one group of a build that has a verified row. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] +pub struct GroupScore { + /// Values found and equal to the verified row. + pub hit: usize, + /// Values found and different from the verified row, with both. Any is a failure. + pub wrong: Vec, + /// Values of the verified row the finder did not find, with the reason. + pub not_found: Vec, + /// Values found that the verified row does not hold, so nothing checks them. + pub unchecked: Vec, +} + +/// The finder's score on a build with a verified row. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] +pub struct Score { + pub groups: BTreeMap, +} + +impl Score { + /// How many values were found wrong. Must be zero. + pub fn wrong(&self) -> usize { + self.groups.values().map(|group| group.wrong.len()).sum() + } +} + +/// The address a build records for what it does not have. +const ABSENT: u64 = 0x7FFF_0000; + +/// Row values that are Rivet's choices or public constants, not facts the binary holds. +fn not_of_the_binary(path: &str) -> bool { + path == "version" + || path.starts_with("version[") + || path == "tabs.new_tab_delay_ms" + || path.starts_with("toolbar.dev.colours") + || path.contains(".signatures") + || crate::command_ids::ROW_PATHS.contains(&path) +} + +/// Every number of a row part, by path, as `row_recipe::number` reads it. +fn numbers(path: &str, value: &Value, out: &mut BTreeMap) { + match value { + Value::Object(object) => { + for (key, item) in object { + let next = if path.is_empty() { + key.clone() + } else { + format!("{path}.{key}") + }; + numbers(&next, item, out); + } + } + Value::Array(items) => { + for (index, item) in items.iter().enumerate() { + numbers(&format!("{path}[{index}]"), item, out); + } + } + _ => { + if let Some(number) = row_recipe::number(value) { + out.insert(path.to_owned(), number); + } + } + } +} + +/// Compares what the finder found with a verified row, `{frame, build}`, value by value. A +/// verified value the row records as nothing (zero or the absent address) counts only when the +/// finder found something there, which is then wrong. +pub fn score(found: &Found, verified: &Value) -> Score { + let mut want = BTreeMap::new(); + let mut frame = BTreeMap::new(); + numbers("", &verified["frame"], &mut frame); + want.extend(frame.into_iter().map(|(path, value)| (format!("frame.{path}"), value))); + numbers("", &verified["build"], &mut want); + want.retain(|path, _| !not_of_the_binary(path)); + let mut score = Score::default(); + for (path, value) in &want { + let group = score.groups.entry(group_of(path).to_owned()).or_default(); + let nothing = *value == 0 || *value == ABSENT; + match found.values.get(path) { + Some(made) if made == value => group.hit += 1, + Some(made) => group + .wrong + .push(format!("{path}: found {made:#x}, verified {value:#x}")), + None if nothing => {} + None => group.not_found.push(match found.not_found.get(path) { + Some(reason) => format!("{path}: {reason}"), + None => format!("{path}: no description"), + }), + } + } + for (path, value) in found.row_values() { + if !want.contains_key(path) { + score + .groups + .entry(group_of(path).to_owned()) + .or_default() + .unchecked + .push(format!("{path}: {value:#x}")); + } + } + score +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::test_module::{call, lea, module, module_with_unwind, table, text}; + use serde_json::json; + + fn describe(path: &str, how: How) -> Description { + Description { + path: path.to_owned(), + source: vec!["chrome/browser/example.cc".into()], + tag: "156.0.8078.80".into(), + note: String::new(), + how, + } + } + + fn trace(texts: &[&str], steps: &[Step]) -> How { + How::Trace { + texts: texts.iter().map(|text| (*text).to_owned()).collect(), + steps: steps.to_vec(), + } + } + + /// `lea rcx, [text]; ret` at `at`. + fn user(at: u32, text_at: u32) -> Vec { + let mut code = lea(at, 1, text_at); + code.push(0xC3); + code + } + + /// `sub rsp, 28h; call to; add rsp, 28h; ret` at `at`: 14 bytes. + fn caller(at: u32, to: u32) -> Vec { + let mut code = vec![0x48, 0x83, 0xEC, 0x28]; + code.extend(call(at + 4, to)); + code.extend([0x48, 0x83, 0xC4, 0x28, 0xC3]); + code + } + + #[test] + fn nfr6_the_checked_in_descriptions_are_valid_and_name_their_source() { + let all = descriptions().unwrap(); + assert!(all.len() >= 10); + for description in &all { + assert!( + description + .source + .iter() + .all(|file| !file.is_empty() && !file.contains(".dll")), + "{}", + description.path + ); + assert!(description.tag.split('.').count() == 4, "{}", description.path); + } + // Values measured to be wrong on some build stay without a description. + for refused in ["omnibox.input_new", "app_window.set_contents", "side_panel.toggle"] { + assert!(all.iter().all(|each| each.path != refused), "{refused}"); + } + } + + #[test] + fn nfr6_a_description_file_is_checked_before_it_is_used() { + // A value that needs an undescribed one is read, and reported as not found when used. + let text = json!({"schema": 1, "values": [ + {"path": "a.slot", "source": ["x.h"], "tag": "1.2.3.4", "kind": "slot_of", + "table": "a.table", "function": "a.function"} + ]}) + .to_string(); + let waiting = parse(&text).unwrap(); + let bytes = module(&[(0x101000, vec![0xC3])], &[(0x101000, 0x101001)]); + let pe = PeFile::parse(&bytes).unwrap(); + assert_eq!( + find(&pe, &waiting).not_found["a.slot"], + "needs a.table, which has no description" + ); + assert!(parse(&json!({"schema": 2, "values": []}).to_string()).is_err()); + let twice = json!({"schema": 1, "values": [ + {"path": "a", "source": ["x.cc"], "tag": "1.2.3.4", "kind": "trace", "texts": ["A"]}, + {"path": "a", "source": ["x.cc"], "tag": "1.2.3.4", "kind": "trace", "texts": ["B"]} + ]}) + .to_string(); + assert!(parse(&twice).unwrap_err().contains("described twice")); + let unsourced = json!({"schema": 1, "values": [ + {"path": "a", "source": [], "tag": "1.2.3.4", "kind": "trace", "texts": ["A"]} + ]}) + .to_string(); + assert!(parse(&unsourced).is_err()); + let steps = json!({"schema": 1, "values": [ + {"path": "a", "source": ["x.cc"], "tag": "1.2.3.4", "kind": "trace", "texts": ["A"], + "steps": [{"sole_caller": 3}, {"only_caller_at_most_bytes": 128}, + {"most_callers_lead": 10}, {"callee_nth": 2}]} + ]}) + .to_string(); + assert_eq!( + parse(&steps).unwrap()[0].how, + trace( + &["A"], + &[ + Step::SoleCaller(3), + Step::OnlyCallerAtMostBytes(128), + Step::MostCallersLead(10), + Step::CalleeNth(2) + ] + ) + ); + } + + #[test] + fn nfr6_a_trace_name_gives_the_one_function_that_uses_it() { + let bytes = module( + &[ + (0x101000, user(0x101000, 0x201000)), + (0x201000, text("WebContentsImpl::OpenURL")), + ], + &[(0x101000, 0x101008)], + ); + let pe = PeFile::parse(&bytes).unwrap(); + let found = find(&pe, &[describe("navigation.open_url", trace(&["WebContentsImpl::OpenURL"], &[]))]); + assert_eq!(found.values["navigation.open_url"], 0x101000); + // A text the build does not hold gives nothing. + let found = find(&pe, &[describe("navigation.open_url", trace(&["Other::Name"], &[]))]); + assert!(found.not_found["navigation.open_url"].contains("none of the texts")); + } + + #[test] + fn nfr6_a_trace_name_two_functions_use_gives_nothing() { + let bytes = module( + &[ + (0x101000, user(0x101000, 0x201000)), + (0x101100, user(0x101100, 0x201000)), + (0x201000, text("AutocompleteController::Start")), + ], + &[(0x101000, 0x101008), (0x101100, 0x101108)], + ); + let pe = PeFile::parse(&bytes).unwrap(); + let found = find(&pe, &[describe("omnibox.start", trace(&["AutocompleteController::Start"], &[]))]); + assert!(found.values.is_empty()); + assert!(found.not_found["omnibox.start"].starts_with("2 functions")); + } + + #[test] + fn nfr6_variations_are_tried_together_and_must_leave_one() { + let bytes = module( + &[ + (0x101000, user(0x101000, 0x201000)), + (0x201000, text("View::LayoutImmediately")), + ], + &[(0x101000, 0x101008)], + ); + let pe = PeFile::parse(&bytes).unwrap(); + let how = trace(&["View::LayoutImmediately", "View::DeprecatedLayoutImmediately"], &[]); + let found = find(&pe, &[describe("layout.layout_immediately", how)]); + assert_eq!(found.values["layout.layout_immediately"], 0x101000); + } + + #[test] + fn nfr6_a_moved_part_of_a_function_counts_as_the_function() { + // The part at 0x101800 continues the function at 0x101000: its unwind data at 0x202000 has + // the chain flag and ends in the entry of 0x101000. + let mut unwind = vec![0x04 << 3, 0, 0, 0]; + unwind.extend(0x101000u32.to_le_bytes()); + unwind.extend(0x101010u32.to_le_bytes()); + unwind.extend(0x202100u32.to_le_bytes()); + let bytes = module_with_unwind( + &[ + (0x101000, vec![0xC3]), + (0x101800, user(0x101800, 0x201000)), + (0x201000, text("generate_rgb_vars")), + (0x202000, unwind), + ], + &[(0x101000, 0x101010, 0x202100), (0x101800, 0x101808, 0x202000)], + ); + let pe = PeFile::parse(&bytes).unwrap(); + assert_eq!(pe.primary_part(0x101800), 0x101000); + assert_eq!(pe.primary_part(0x101000), 0x101000); + let found = find(&pe, &[describe("side_panel.generate_colors_css", trace(&["generate_rgb_vars"], &[]))]); + assert_eq!(found.values["side_panel.generate_colors_css"], 0x101000); + } + + #[test] + fn nfr6_steps_follow_the_one_caller_the_source_describes() { + // The traced body at 0x101000 has one caller, the helper at 0x101100, which a thin wrapper + // at 0x101200 and a large function at 0x101300 both call. + let mut large = caller(0x101300, 0x101100); + large.resize(0x200, 0x90); + let bytes = module( + &[ + (0x101000, user(0x101000, 0x201000)), + (0x101100, caller(0x101100, 0x101000)), + (0x101200, caller(0x101200, 0x101100)), + (0x101300, large), + (0x201000, text("TabStripModel::ActivateTab")), + ], + &[ + (0x101000, 0x101008), + (0x101100, 0x10110e), + (0x101200, 0x10120e), + (0x101300, 0x101500), + ], + ); + let pe = PeFile::parse(&bytes).unwrap(); + let how = trace( + &["TabStripModel::ActivateTab"], + &[Step::SoleCaller(3), Step::OnlyCallerAtMostBytes(0x80)], + ); + let found = find(&pe, &[describe("tabs.activate_tab", how)]); + // The helper has two callers, so the climb stops there, and only one caller is small. + assert_eq!(found.values["tabs.activate_tab"], 0x101200); + // With no size bound, two callers remain and nothing is taken. + let how = trace( + &["TabStripModel::ActivateTab"], + &[Step::SoleCaller(3), Step::OnlyCallerAtMostBytes(0x1000)], + ); + let found = find(&pe, &[describe("tabs.activate_tab", how)]); + assert!(found.not_found["tabs.activate_tab"].starts_with("2 callers")); + // The callee step reads the calls in order. + let how = trace(&["TabStripModel::ActivateTab"], &[Step::SoleCaller(1), Step::CalleeNth(0)]); + let found = find(&pe, &[describe("x", how)]); + assert_eq!(found.values["x"], 0x101000); + } + + #[test] + fn nfr6_a_caller_is_taken_by_its_lead_only() { + // The factory at 0x101000 uses the service name and has two callers: 0x101100, called + // from ten places, and 0x101200, called from one. + let mut parts = vec![ + (0x101000, user(0x101000, 0x201000)), + (0x101100, caller(0x101100, 0x101000)), + (0x101200, caller(0x101200, 0x101000)), + (0x201000, text("AutocompleteClassifier")), + ]; + let mut ranges = vec![(0x101000, 0x101008), (0x101100, 0x10110e), (0x101200, 0x10120e)]; + for index in 0..11u32 { + let at = 0x102000 + index * 0x20; + let to = if index == 0 { 0x101200 } else { 0x101100 }; + parts.push((at, caller(at, to))); + ranges.push((at, at + 14)); + } + let bytes = module(&parts, &ranges); + let pe = PeFile::parse(&bytes).unwrap(); + let lead = |times| { + let how = trace(&["AutocompleteClassifier"], &[Step::MostCallersLead(times)]); + find(&pe, &[describe("omnibox.classifier_for_profile", how)]) + }; + assert_eq!(lead(10).values["omnibox.classifier_for_profile"], 0x101100); + assert!(lead(11).not_found["omnibox.classifier_for_profile"].starts_with("no caller leads")); + } + + #[test] + fn nfr6_a_slot_from_a_public_header_reads_the_table_the_found_function_is_in() { + // OpenURL is slot 1 of the table at 0x203000. Slot 7 and slot 13 are other functions. + let functions: Vec = (0..16).map(|slot| 0x101000 + slot * 0x10).collect(); + let mut parts = vec![ + (0x101010, user(0x101010, 0x201000)), + (0x201000, text("WebContentsImpl::OpenURL")), + (0x203000, table(&functions)), + ]; + let mut ranges = vec![(0x101010, 0x101018)]; + for function in functions.iter().filter(|function| **function != 0x101010) { + parts.push((*function, vec![0xC3])); + ranges.push((*function, function + 1)); + } + let bytes = module(&parts, &ranges); + let pe = PeFile::parse(&bytes).unwrap(); + let descriptions = [ + describe("navigation.open_url", trace(&["WebContentsImpl::OpenURL"], &[])), + describe( + "_web_contents_table", + How::TableOf { + function: "navigation.open_url".into(), + slot: 1, + }, + ), + describe( + "tabs.visible_url", + How::TableSlot { + table: "_web_contents_table".into(), + slot: 13, + }, + ), + describe( + "_open_url_slot", + How::SlotOf { + table: "_web_contents_table".into(), + function: "navigation.open_url".into(), + }, + ), + describe( + "omnibox.browser_context", + How::TableSlot { + table: "_web_contents_table".into(), + slot: 40, + }, + ), + ]; + let found = find(&pe, &descriptions); + assert_eq!(found.values["_web_contents_table"], 0x203000); + assert_eq!(found.values["tabs.visible_url"], 0x1010d0); + assert_eq!(found.values["_open_url_slot"], 1); + // A slot past the table's end is not read as a function. + assert!(found.not_found["omnibox.browser_context"].contains("past its end")); + // Steps are not row values. + assert!(found.row_values().all(|(path, _)| !path.starts_with('_'))); + } + + #[test] + fn nfr6_a_value_whose_input_is_not_found_is_not_found() { + let bytes = module(&[(0x101000, vec![0xC3])], &[(0x101000, 0x101001)]); + let pe = PeFile::parse(&bytes).unwrap(); + let descriptions = [ + describe("navigation.active_web_contents", trace(&["Missing"], &[])), + describe( + "side_panel.browser_offset", + How::FirstLoad { + function: "navigation.active_web_contents".into(), + }, + ), + ]; + let found = find(&pe, &descriptions); + assert_eq!( + found.not_found["side_panel.browser_offset"], + "needs navigation.active_web_contents, which was not found" + ); + } + + #[test] + fn nfr6_a_member_offset_is_read_from_the_accessor_the_finder_found() { + // mov rax, [rcx + 0x558]; ret, which uses the text through a later lea. + let mut accessor = vec![0x48, 0x8B, 0x81, 0x58, 0x05, 0x00, 0x00]; + accessor.extend(lea(0x101007, 2, 0x201000)); + accessor.push(0xC3); + let bytes = module( + &[(0x101000, accessor), (0x201000, text("Browser::GetActiveWebContents"))], + &[(0x101000, 0x10100f)], + ); + let pe = PeFile::parse(&bytes).unwrap(); + let descriptions = [ + describe("tabs.active_web_contents", trace(&["Browser::GetActiveWebContents"], &[])), + describe( + "tabs.browser_in_view", + How::FirstLoad { + function: "tabs.active_web_contents".into(), + }, + ), + ]; + let found = find(&pe, &descriptions); + assert_eq!(found.values["tabs.browser_in_view"], 0x558); + } + + #[test] + fn nfr6_the_finder_is_scored_value_by_value_against_a_verified_row() { + let found = Found { + values: BTreeMap::from([ + ("navigation.open_url".to_owned(), 0x81c7b80), + ("omnibox.classify".to_owned(), 0x63cd11), + ("frame.frame_view_vtable".to_owned(), 0xfce1070), + ("layout.layout".to_owned(), 0x1234), + ("_web_contents_table".to_owned(), 0x5000), + ]), + not_found: BTreeMap::from([( + "side_panel.toggle".to_owned(), + "2 functions that use the text".to_owned(), + )]), + }; + let verified = json!({ + "frame": {"frame_view_vtable": 265162864u64, "version": "156.0.8078.81"}, + "build": { + "version": [156, 0, 8078, 81], + "navigation": {"open_url": "0x81c7b80", "signatures": [["0x81c7b80", "4157"]]}, + "omnibox": {"classify": "0x63cd10"}, + "side_panel": {"toggle": "0x970e610", "browser_offset": "0x560"}, + "tabs": {"new_tab_delay_ms": 0, "tab_object": "0x7fff0000"}, + } + }); + let score = score(&found, &verified); + assert_eq!(score.wrong(), 1); + assert_eq!(score.groups[WINDOW].hit, 2); + assert_eq!( + score.groups["address suggestions"].wrong, + ["omnibox.classify: found 0x63cd11, verified 0x63cd10"] + ); + assert_eq!( + score.groups["sidebar"].not_found, + [ + "side_panel.browser_offset: no description", + "side_panel.toggle: 2 functions that use the text" + ] + ); + assert_eq!(score.groups[WINDOW].unchecked, ["layout.layout: 0x1234"]); + let groups = report(&found); + assert_eq!(groups["sidebar"].not_found.len(), 1); + assert!(groups.values().all(|group| group.found.iter().all(|line| !line.starts_with('_')))); + } +} diff --git a/rivet/platform/windows/src/row_port.rs b/rivet/platform/windows/src/row_port.rs deleted file mode 100644 index eefc0dd..0000000 --- a/rivet/platform/windows/src/row_port.rs +++ /dev/null @@ -1,2938 +0,0 @@ -//! Makes the supported-build row of a new browser build from the row of a prior build. -//! -//! Chromium's source changes little between two builds of a milestone, but every address moves. -//! Each address of the prior row is found again in the new module by its fingerprint, the first -//! instructions of the function without their displacements, or by a slot of a class table that -//! holds such a function. What a fingerprint does not pin down is settled by `row_resolve`, which -//! takes a place only where two independent methods agree. The instruction bytes that guard each -//! hook are then read again from the new module. Values that are not addresses (member offsets, -//! table slots, object sizes) are read again from the new module where `row_recipe` has a recipe -//! for them, or from the instructions that use them. No browser's debug symbols are read: the -//! verified prior row, its fingerprints and the two modules are all the generator has. -//! -//! A row is plain data here, in the form the runtime writes: a `usize` is a `0x` string, and bytes -//! are bare hex. A value this code cannot explain stops the row or turns its feature off: it never -//! reaches people's browsers, and the runtime's own prologue checks stand behind that. - -use std::collections::{BTreeMap, BTreeSet, HashMap}; - -use serde::Serialize; -use serde_json::{json, Value}; - -use crate::chrome_build::{hex, PeFile}; -use crate::row_resolve; - -/// The lowest value taken for an address. Offsets and slots lie below it. -const LOWEST_ADDRESS: u64 = 0x10_0000; -/// The address a build records for what it does not have. -const ABSENT: u64 = 0x7FFF_0000; -/// What the generator found, for the person or job that decides what to do with the row. -#[derive(Debug, Default, Serialize)] -pub struct PortReport { - pub browser: String, - pub version: String, - pub prior_version: String, - pub addresses: usize, - pub mapped: usize, - /// Why this row must not be published without a person. Empty means none was found. - pub review: Vec, - /// Addresses with several possible new places, settled by an independent check. - pub settled: Vec, - pub bytes_changed: Vec, - pub slots_moved: Vec, - /// Values that are not addresses, read again from the new module by their recipes. - pub derived: Vec, - /// Values that are not addresses and have no recipe, so they were carried over. - pub carried: Vec, - /// Optional parts the new build could not supply. The runtime does without them. - pub left_out: Vec, - /// Addresses a fingerprint found in exactly one place of the new build. - pub fingerprinted: Vec, - /// Values that are Rivet's settings rather than facts about the build, kept from the prior row. - pub settings: Vec, - /// Features this row turns off, each with the values that could not be read for it. The row - /// clears those values, so none of the prior build reaches a browser. - pub switched_off: Vec, - /// Values the runtime does not read in this row, written as zero, with the reason. - pub unused: Vec, - /// Values no instruction of the new build gave that the runtime finds by reflection, so the - /// row leaves them out instead of carrying them. - pub reflected: Vec, - /// Addresses no method placed in the new build that only features this row turns off hold, - /// with the values that held them. The row clears those values like the feature's others. - pub unplaced: Vec, - /// Whether every carried value must be settled: the milestone changed, or values were read. - #[serde(skip)] - must_check: bool, - /// The milestone change, when there is one and nothing read the carried values. - #[serde(skip)] - milestone: Option, - /// Why each value that was tried could not be read. - #[serde(skip)] - unread: BTreeMap, - /// Values of features the row turns off whatever the milestone, with the reason: an address - /// that has no place in the new build, or a recipe that failed. - #[serde(skip)] - off_values: BTreeMap, -} - -fn is_address(value: u64) -> bool { - (LOWEST_ADDRESS..ABSENT).contains(&value) -} - -fn read_address(value: &Value) -> Option { - let digits = value.as_str()?.strip_prefix("0x")?; - u64::from_str_radix(digits, 16).ok() -} - -fn write_address(value: u64) -> Value { - Value::String(format!("{value:#x}")) -} - -/// Visits every `0x` value of a row with its path. -fn walk_addresses(path: &str, value: &mut Value, visit: &mut dyn FnMut(&str, &mut Value)) { - match value { - Value::Object(object) => { - for (key, item) in object { - walk_addresses(&format!("{path}.{key}"), item, visit); - } - } - Value::Array(items) => { - for (index, item) in items.iter_mut().enumerate() { - walk_addresses(&format!("{path}[{index}]"), item, visit); - } - } - Value::String(text) if text.starts_with("0x") => visit(path, value), - _ => {} - } -} - -/// The addresses a row holds. -pub fn addresses_of(row: &Value) -> BTreeSet { - let mut found = BTreeSet::new(); - let mut copy = row.clone(); - walk_addresses("", &mut copy, &mut |_, value| { - if let Some(address) = read_address(value).filter(|value| is_address(*value)) { - found.insert(address as u32); - } - }); - found -} - -/// A function's instructions, read as far as this needs them. -pub mod x64 { - /// One decoded instruction: its length, where its RIP-relative displacement or relative branch - /// target is, where a displacement from a register is, as in `[rcx + 0x558]`, and where its - /// immediate value is. Each place is `(offset, size)` within the instruction. - #[derive(Debug, PartialEq, Eq, Clone, Copy)] - pub struct Instruction { - pub length: usize, - pub relative: Option<(usize, usize)>, - pub displacement: Option<(usize, usize)>, - pub immediate: Option<(usize, usize)>, - } - - impl Instruction { - fn plain(length: usize) -> Self { - Self { - length, - relative: None, - displacement: None, - immediate: None, - } - } - - /// An instruction whose last `size` bytes, from `at`, are an immediate value. - fn with_immediate(at: usize, size: usize) -> Self { - Self { - length: at + size, - relative: None, - displacement: None, - immediate: Some((at, size)), - } - } - - /// A branch whose last `size` bytes, from `at`, are the distance to its target. - fn branch(at: usize, size: usize) -> Self { - Self { - length: at + size, - relative: Some((at, size)), - displacement: None, - immediate: None, - } - } - } - - fn modrm(bytes: &[u8], at: usize, immediate: usize) -> Option { - let byte = *bytes.get(at)?; - let (mode, rm) = (byte >> 6, byte & 7); - let mut length = at + 1; - let mut relative = None; - let mut displacement = None; - if mode != 3 && rm == 4 { - let sib = *bytes.get(length)?; - length += 1; - if mode == 0 && sib & 7 == 5 { - displacement = Some((length, 4)); - length += 4; - } - } - match mode { - 0 if rm == 5 => { - relative = Some((length, 4)); - length += 4; - } - 1 => { - displacement = Some((length, 1)); - length += 1; - } - 2 => { - displacement = Some((length, 4)); - length += 4; - } - _ => {} - } - Some(Instruction { - length: length + immediate, - relative, - displacement, - immediate: (immediate > 0).then_some((length, immediate)), - }) - } - - /// Decodes the instruction at the start of `bytes`, or `None` for one this does not know. The - /// list covers what function starts are made of, and anything else goes to a person. - pub fn decode(bytes: &[u8]) -> Option { - decode_with(bytes, false) - } - - /// Decodes as `decode` does, and also the instructions met inside a function body: lock and - /// segment prefixes, string and x87 instructions, VEX encoded vector instructions and more of - /// the two and three byte opcodes. It reads bodies to follow calls and operands, and never - /// judges a guard, so what a hook may copy stays as `decode` says. - pub fn decode_body(bytes: &[u8]) -> Option { - decode_with(bytes, true) - } - - fn decode_with(bytes: &[u8], body: bool) -> Option { - let mut at = 0; - let mut wide_operand = false; - let mut rex_w = false; - loop { - match *bytes.get(at)? { - 0x66 => wide_operand = true, - 0xF2 | 0xF3 => {} - 0xF0 | 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 if body => {} - _ => break, - } - at += 1; - } - if bytes.get(at)? & 0xF0 == 0x40 { - rex_w = bytes[at] & 8 != 0; - at += 1; - } - let opcode = *bytes.get(at)?; - at += 1; - let word = if wide_operand { 2 } else { 4 }; - match opcode { - 0x50..=0x5F | 0x90 | 0xC3 | 0xCC | 0x99 => Some(Instruction::plain(at)), - 0x98 => Some(Instruction::plain(at)), - 0x00..=0x03 - | 0x08..=0x0B - | 0x10..=0x13 - | 0x18..=0x1B - | 0x20..=0x23 - | 0x28..=0x2B - | 0x30..=0x33 - | 0x38..=0x3B - | 0x63 - | 0x84..=0x8B - | 0x8D - | 0x8F - | 0xD0..=0xD3 - | 0xFE - | 0xFF => modrm(bytes, at, 0), - 0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x34 | 0x3C | 0x6A | 0xA8 | 0xB0..=0xB7 => { - Some(Instruction::with_immediate(at, 1)) - } - 0x05 | 0x0D | 0x15 | 0x1D | 0x25 | 0x2D | 0x35 | 0x3D | 0x68 | 0xA9 => { - Some(Instruction::with_immediate(at, word)) - } - 0xB8..=0xBF => Some(Instruction::with_immediate( - at, - if rex_w { 8 } else { word }, - )), - 0x80 | 0x83 | 0xC0 | 0xC1 | 0xC6 | 0x6B => modrm(bytes, at, 1), - 0x81 | 0xC7 | 0x69 => modrm(bytes, at, word), - 0xF6 => { - let immediate = usize::from((bytes.get(at)? >> 3) & 7 < 2); - modrm(bytes, at, immediate) - } - 0xF7 => { - let immediate = if (bytes.get(at)? >> 3) & 7 < 2 { - word - } else { - 0 - }; - modrm(bytes, at, immediate) - } - 0x70..=0x7F | 0xEB => Some(Instruction::branch(at, 1)), - 0xE8 | 0xE9 => Some(Instruction::branch(at, 4)), - 0x0F => { - let second = *bytes.get(at)?; - at += 1; - match second { - 0x80..=0x8F => Some(Instruction::branch(at, 4)), - 0x10..=0x17 - | 0x1E - | 0x1F - | 0x28..=0x2F - | 0x40..=0x6F - | 0x7E - | 0x7F - | 0x90..=0x9F - | 0xAF - | 0xB6 - | 0xB7 - | 0xBE - | 0xBF - | 0xD6 - | 0xEF => modrm(bytes, at, 0), - _ if body => body_two_byte(bytes, at, second), - _ => None, - } - } - _ if body => body_one_byte(bytes, at, opcode), - _ => None, - } - } - - /// One byte opcodes that only a function body holds. `at` is just past the opcode. - fn body_one_byte(bytes: &[u8], at: usize, opcode: u8) -> Option { - match opcode { - 0x91..=0x97 | 0x9C..=0x9F | 0xA4..=0xA7 | 0xAA..=0xAF | 0xC9 | 0xF4 | 0xF5 => { - Some(Instruction::plain(at)) - } - 0xF8..=0xFD => Some(Instruction::plain(at)), - 0xC2 => Some(Instruction::with_immediate(at, 2)), - 0xCD => Some(Instruction::with_immediate(at, 1)), - 0xD8..=0xDF => modrm(bytes, at, 0), - 0xE0..=0xE3 => Some(Instruction::branch(at, 1)), - // Two byte VEX: one payload byte, then an opcode of the 0F map. - 0xC5 => { - let opcode = *bytes.get(at + 1)?; - modrm(bytes, at + 2, vex_immediate(1, opcode)) - } - // Three byte VEX: the map in the first payload byte, then one more payload byte. - 0xC4 => { - let map = bytes.get(at)? & 0x1F; - let opcode = *bytes.get(at + 2)?; - modrm(bytes, at + 3, vex_immediate(map, opcode)) - } - _ => None, - } - } - - /// Whether a VEX instruction of `map` ends in an immediate byte. - fn vex_immediate(map: u8, opcode: u8) -> usize { - match map { - 3 => 1, - 1 => usize::from(matches!(opcode, 0x70..=0x73 | 0xC2 | 0xC4..=0xC6)), - _ => 0, - } - } - - /// Two byte opcodes that only a function body holds. `at` is just past the second byte. - fn body_two_byte(bytes: &[u8], at: usize, second: u8) -> Option { - match second { - 0x0B | 0x31 | 0x77 | 0xA2 | 0xC8..=0xCF => Some(Instruction::plain(at)), - 0x0D - | 0x18..=0x1D - | 0x74..=0x76 - | 0x7C - | 0x7D - | 0xA3 - | 0xA5 - | 0xAB - | 0xAD - | 0xAE - | 0xB0 - | 0xB1 - | 0xB3 - | 0xB8 - | 0xBB - | 0xBC - | 0xBD - | 0xC0 - | 0xC1 - | 0xC3 - | 0xC7 - | 0xD0..=0xD5 - | 0xD7..=0xEE - | 0xF0..=0xFE => modrm(bytes, at, 0), - 0x70..=0x73 | 0xA4 | 0xAC | 0xBA | 0xC2 | 0xC4..=0xC6 => modrm(bytes, at, 1), - 0x38 => modrm(bytes, at + 1, 0), - 0x3A => modrm(bytes, at + 1, 1), - _ => None, - } - } - - /// The instruction boundaries within `bytes`, and whether all of them could be read up to `length`. - pub fn boundaries(bytes: &[u8], length: usize) -> (Vec, bool) { - let mut at = 0; - let mut seen = vec![]; - while at < length { - match decode(&bytes[at..]) { - Some(instruction) => { - at += instruction.length; - seen.push(at); - } - None => return (seen, false), - } - } - (seen, true) - } - - /// The bytes with every relative value blanked, which is what stays the same when only the - /// distance to other code moved. `None` when an instruction cannot be read. - pub fn shape(bytes: &[u8]) -> Option> { - let mut out = bytes.to_vec(); - let mut at = 0; - while at < bytes.len() { - let instruction = decode_tail(&bytes[at..])?; - if let Some((offset, size)) = instruction.relative { - for index in at + offset..(at + offset + size).min(out.len()) { - out[index] = 0; - } - } - at += instruction.length; - } - Some(out) - } - - /// Decodes an instruction that may be cut off by the end of a recorded prologue. - fn decode_tail(bytes: &[u8]) -> Option { - let mut padded = bytes.to_vec(); - padded.resize(bytes.len() + 16, 0); - decode(&padded) - } - - /// Whether any instruction in the bytes depends on where it sits. - pub fn has_relative(bytes: &[u8]) -> Option { - let mut at = 0; - while at < bytes.len() { - let instruction = decode_tail(&bytes[at..])?; - if instruction.relative.is_some() { - return Some(true); - } - at += instruction.length; - } - Some(false) - } - - /// An instruction's bytes with its relative value, displacement and immediate cleared: what - /// stays the same when code moves and members, slots and constants change. - pub fn skeleton(bytes: &[u8], instruction: &Instruction) -> Vec { - let mut out = bytes[..instruction.length.min(bytes.len())].to_vec(); - let fields = [ - instruction.relative, - instruction.displacement, - instruction.immediate, - ]; - for (offset, size) in fields.into_iter().flatten() { - for index in offset..(offset + size).min(out.len()) { - out[index] = 0; - } - } - out - } -} - -/// A byte field with no address field of the same name, and where it was read from. -fn byte_field_address(key: &str) -> Option<(&'static str, u64)> { - Some(match key { - "bounds_bytes" => ("bounds_in_screen", 0), - "page_info_bytes" => ("page_info_path", 0), - "hwnd_for_widget_head" => ("hwnd_for_widget", 0), - "hwnd_for_widget_tail" => ("hwnd_for_widget", 9), - _ => return None, - }) -} - -/// Fields of bytes that are not read from the module at one address: they name things. -const NOT_CODE: &[&str] = &["http_icon_name", "nav_icon_names"]; - -/// Data, rather than instructions, so its shape is not read as code. -const DATA_BYTES: &[&str] = &["page_info_bytes"]; - -/// The value at a path such as `layout.on_paint_slot`. -fn at_path<'a>(row: &'a Value, path: &str) -> &'a Value { - path.split('.').fold(row, |value, key| &value[key]) -} - -/// `(vtable, slot, function)`: a function the runtime replaces in a table, and so a check the new -/// module can answer on its own. A function listed twice settles a folded name. -const VTABLE_SLOTS: &[(&str, &str, &str)] = &[ - ( - "layout.frame_vtable", - "layout.on_paint_slot", - "layout.on_paint", - ), - ( - "layout.caption_vtable", - "layout.caption_paint_slot", - "layout.caption_paint", - ), -]; - -fn usize_at(row: &Value, path: &str) -> Option { - read_address(at_path(row, path)) -} - -/// The bytes of a function short enough to read to its end: its first `ret` with no branch before. -pub(crate) fn whole_function(pe: &PeFile, address: u32) -> Option> { - let bytes = pe.read(address, 48)?; - let mut at = 0; - while at < 32 { - let instruction = x64::decode(&bytes[at..])?; - if instruction.relative.is_some() && bytes[at] != 0x48 && bytes[at] != 0x8B { - return None; - } - at += instruction.length; - if bytes[at - 1] == 0xC3 { - return x64::shape(&bytes[..at]); - } - } - None -} - -fn is_byte_field(key: &str) -> bool { - key.ends_with("_prologue") || key.ends_with("_bytes") || byte_field_address(key).is_some() -} - -/// The bytes a hook overwrites with its jump. -const COPIED_AT_LEAST: usize = 12; - -/// What the runtime may do with a guard, judged from the prior row, which a person verified. -#[derive(Debug, PartialEq, Eq, Clone, Copy)] -pub enum GuardKind { - /// Long enough for a hook, ending on an instruction, and moving nothing that depends on where - /// it sits apart from a last stack cookie load, which the hook relocates. The hook runs a copy - /// of these bytes, so a new function start must have the same properties. - Copyable, - /// Holds a position dependent instruction before its end, and a row may count bytes to it. - Fixed, - /// Too short or cut inside an instruction: it is only ever compared. - Compared, -} - -pub fn guard_kind(bytes: &[u8]) -> GuardKind { - let mut padded = bytes.to_vec(); - padded.resize(bytes.len() + 16, 0); - let mut at = 0; - let mut relative_before_end = false; - while at < bytes.len() { - let Some(instruction) = x64::decode(&padded[at..]) else { - return GuardKind::Compared; - }; - if let Some((offset, size)) = instruction.relative { - let inside = at + offset + size <= bytes.len(); - let is_last_cookie = at + 7 == bytes.len() && bytes[at..at + 3] == [0x48, 0x8B, 0x05]; - relative_before_end |= inside && !is_last_cookie; - if !inside { - return GuardKind::Compared; - } - } - at += instruction.length; - } - match ( - relative_before_end, - at == bytes.len() && bytes.len() >= COPIED_AT_LEAST, - ) { - (true, _) => GuardKind::Fixed, - (false, true) => GuardKind::Copyable, - (false, false) => GuardKind::Compared, - } -} - -/// Reads a guard again from the new module. A hook runs a copy of what it overwrites, so a guard -/// that is copied must stay cut on an instruction, or the copy would crash the browser. -fn read_guard( - label: &str, - address: u64, - old: &[u8], - is_code: bool, - pe: &PeFile, - report: &mut PortReport, -) -> Option> { - let Ok(address) = u32::try_from(address) else { - report - .review - .push(format!("{label}: address {address:#x} out of range")); - return None; - }; - let Some(mut new) = pe.read(address, old.len()).map(<[u8]>::to_vec) else { - report - .review - .push(format!("{label}: {address:#x} lies outside the module")); - return None; - }; - if is_code { - match guard_kind(old) { - GuardKind::Compared => {} - GuardKind::Fixed => { - if x64::shape(old) != x64::shape(&new) { - report.review.push(format!( - "{label}: a row counts bytes into this function start, which changed: {} was {}", - hex_text(&new), - hex_text(old) - )); - } - } - GuardKind::Copyable => { - let window = pe.read(address, old.len() + 16).unwrap_or(&new); - let (seen, complete) = x64::boundaries(window, old.len()); - if complete && !seen.contains(&old.len()) { - // The jump needs twelve bytes, so a shorter guard grows to the next instruction. - let keep = seen - .iter() - .rev() - .find(|end| **end < old.len() && **end >= COPIED_AT_LEAST) - .copied(); - let length = keep.unwrap_or_else(|| { - *seen - .iter() - .find(|end| **end > old.len()) - .unwrap_or(&old.len()) - }); - new = pe.read(address, length).map_or(new, <[u8]>::to_vec); - } - if guard_kind(&new) != GuardKind::Copyable { - report.review.push(format!( - "{label}: a hook could not copy this function start: {} was {}", - hex_text(&new), - hex_text(old) - )); - } - } - } - } - if new != old { - report - .bytes_changed - .push(format!("{label}: {} -> {}", hex_text(old), hex_text(&new))); - } - Some(new) -} - -fn hex_text(bytes: &[u8]) -> String { - bytes.iter().map(|byte| format!("{byte:02x}")).collect() -} - -/// Reads every guard of a row object again from the new module. -fn refresh_guards(path: &str, value: &mut Value, pe: &PeFile, report: &mut PortReport) { - match value { - Value::Object(object) => { - let keys: Vec = object.keys().cloned().collect(); - for key in keys { - let label = format!("{path}.{key}"); - let is_field = is_byte_field(&key) && !NOT_CODE.contains(&key.as_str()); - let old = object[&key].as_str().filter(|_| is_field).and_then(hex); - if let Some(old) = old.filter(|old| !old.is_empty() && old.as_slice() != [0]) { - let (base, distance) = match byte_field_address(&key) { - Some((base, distance)) => (base.to_owned(), distance), - None => ( - key.trim_end_matches("_prologue") - .trim_end_matches("_bytes") - .to_owned(), - 0, - ), - }; - let Some(address) = object.get(&base).and_then(read_address) else { - report - .review - .push(format!("{label}: no address field {base}")); - continue; - }; - if !is_address(address) { - continue; - } - let is_code = !DATA_BYTES.contains(&key.as_str()); - if let Some(new) = - read_guard(&label, address + distance, &old, is_code, pe, report) - { - object.insert(key, Value::String(hex_text(&new))); - } - continue; - } - refresh_guards( - &label, - object.get_mut(&key).expect("listed key"), - pe, - report, - ); - } - } - Value::Array(items) => { - if let [address, Value::String(bytes)] = items.as_mut_slice() { - if let (Some(address), Some(old)) = (read_address(address), hex(bytes)) { - if is_address(address) { - if let Some(new) = read_guard(path, address, &old, true, pe, report) { - *bytes = hex_text(&new); - } - } - return; - } - } - for (index, item) in items.iter_mut().enumerate() { - refresh_guards(&format!("{path}[{index}]"), item, pe, report); - } - } - _ => {} - } -} - -/// Checks the rule that a table slot holds its function, moving a slot that moved. The other fields -/// of a class can move too, and nothing in the module tells, so a moved slot goes to review. -fn check_vtable_slots(build: &mut Value, pe: &PeFile, report: &mut PortReport) { - for (vtable_path, slot_path, function_path) in VTABLE_SLOTS { - let (Some(vtable), Some(function)) = - (usize_at(build, vtable_path), usize_at(build, function_path)) - else { - continue; - }; - let Some(slot) = usize_at(build, slot_path) else { - continue; - }; - if !is_address(vtable) || !is_address(function) { - continue; - } - if pe.pointer_rva(vtable as u32 + slot as u32 * 8) == Some(function as u32) { - continue; - } - match pe.vtable_slot(vtable as u32, function as u32) { - Some(moved) => { - report - .slots_moved - .push(format!("{slot_path}: {slot} -> {moved}")); - report - .review - .push(format!("{slot_path} moved from {slot} to {moved}")); - let (parent, key) = slot_path.split_once('.').expect("a path has a parent"); - build[parent][key] = write_address(u64::from(moved)); - } - None => report.review.push(format!( - "{vtable_path} holds no {function_path} {function:#x}" - )), - } - } -} - -/// `ContentsContainerView::SetRoundedCorners` starts `movss; ucomiss; jne changed; jp parity`. The -/// row records where both go, so they are read from the instructions rather than moved by distance. -fn read_rounded_corners(build: &mut Value, pe: &PeFile, report: &mut PortReport) { - // A row that keeps no destinations does not hook this function. - if !usize_at(build, "split.set_rounded_corners_changed").is_some_and(is_address) { - return; - } - let Some(start) = - usize_at(build, "split.set_rounded_corners").filter(|value| is_address(*value)) - else { - return; - }; - let Some(bytes) = pe.read(start as u32, 13) else { - return; - }; - if bytes[..4] != [0xF3, 0x0F, 0x10, 0x02] || bytes[4..6] != [0x0F, 0x2E] || bytes[11] != 0x75 { - report.review.push(format!( - "split.set_rounded_corners starts differently: {}", - hex_text(bytes) - )); - return; - } - let changed = start + 13 + u64::from(bytes[12]); - build["split"]["set_rounded_corners_changed"] = write_address(changed); - build["split"]["set_rounded_corners_parity"] = write_address(start + 13); -} - -/// Addresses read from instructions above, which no fingerprint finds. -const READ_FROM_CODE: &[&str] = &[ - "split.set_rounded_corners_changed", - "split.set_rounded_corners_parity", -]; - -/// Settles each value no recipe or instruction read from the new build. A value the runtime finds -/// by reflection is left out of the row. A value the runtime does not read in this row is written -/// as zero. A value of a feature the runtime can do without turns -/// that feature off for this build and is cleared, so the rest of the row is not held back by it. -/// Any other value stops the row with its reason, since no feature may run on a value of another -/// build. -fn settle_carried(row: &mut Value, report: &mut PortReport) { - use crate::row_features::{self, Clear, RowFeature}; - let mut off: BTreeMap<&'static str, (&'static RowFeature, Vec)> = BTreeMap::new(); - for (path, reason) in std::mem::take(&mut report.off_values) { - if let Some(feature) = row_features::feature_of(&path) { - row_features::clear_value(&mut row["build"], &path, feature); - report.unread.insert(path.clone(), reason); - off.entry(feature.name) - .or_insert((feature, Vec::new())) - .1 - .push(path); - } - } - let must_check = report.must_check; - let carried = if must_check { - std::mem::take(&mut report.carried) - } else { - Vec::new() - }; - let mut left = Vec::new(); - for path in carried { - if row_features::is_reflected(&path) { - row_features::leave_out(&mut row["build"], &path); - report.unread.remove(&path); - report.reflected.push(format!( - "{path}: left out, the runtime finds it by reflection" - )); - } else if let Some(why) = row_features::unused(&row["build"], &path) { - row_features::clear(&mut row["build"], &path, Clear::Zero); - report.unused.push(format!("{path}: {why}")); - report.unread.remove(&path); - } else if let Some(feature) = row_features::feature_of(&path) { - row_features::clear(&mut row["build"], &path, feature.clear); - off.entry(feature.name) - .or_insert((feature, Vec::new())) - .1 - .push(path); - } else { - left.push(path); - } - } - let mut entries = Vec::new(); - for (name, (_, paths)) in off { - row_features::turn_off(&mut row["build"], name); - let reasons: Vec = paths - .iter() - .map(|path| match report.unread.remove(path) { - Some(reason) => format!("{path} {reason}"), - None => format!("{path} has no recipe"), - }) - .collect(); - report - .switched_off - .push(format!("{name} is off: {}", reasons.join("; "))); - entries.push(json!({"feature": name, "values": paths})); - } - if !entries.is_empty() { - row[row_features::SWITCHED_OFF] = json!(entries); - } - if !must_check { - return; - } - let mut unchecked = Vec::new(); - for path in &left { - match report.unread.remove(path) { - Some(reason) => report.review.push(format!("{path} {reason}")), - None => unchecked.push(path.clone()), - } - } - if !unchecked.is_empty() { - let head = report - .milestone - .clone() - .unwrap_or_else(|| "values were not read".to_owned()); - report.review.push(format!( - "{head}: {} values have no recipe and were carried over unchecked: {}", - unchecked.len(), - unchecked.join(", ") - )); - } - report.carried = left; -} - -/// A copy of the prior row with the new version, and frame addresses in the `0x` form. `carries` -/// says the values with no recipe stay as the prior row has them, so a new milestone stops the -/// row; without it they are read from the new build later, each with its own review line. -fn begin_row(prior: &Value, version: &str, carries: bool) -> (Value, PortReport) { - let mut row = prior.clone(); - let prior_version = prior["frame"]["version"] - .as_str() - .unwrap_or_default() - .to_owned(); - let mut report = PortReport { - browser: prior["build"]["browser"] - .as_str() - .unwrap_or_default() - .to_owned(), - version: version.to_owned(), - prior_version: prior_version.clone(), - ..PortReport::default() - }; - let parts: Vec = version - .split('.') - .filter_map(|part| part.parse().ok()) - .collect(); - if parts.len() != 4 { - report - .review - .push(format!("{} is not a four part version", version)); - } - write_command_ids(&mut row, version, &mut report); - report.carried = crate::row_recipe::without_recipe(&prior["build"]); - report.settings = crate::row_recipe::settings(&prior["build"]); - let milestone_changed = prior_version.split('.').next() != version.split('.').next(); - report.must_check = !carries || milestone_changed; - if carries && milestone_changed { - report.milestone = Some(format!( - "the milestone changed from {prior_version} to {version}" - )); - } - row["build"]["version"] = json!(parts); - row["frame"]["version"] = json!(version); - - let frame_as_addresses = frame_addresses(&row["frame"]); - row["frame_addresses"] = frame_as_addresses; - (row, report) -} - -/// Writes Chromium's public command ids into a row from the table read from Chromium's source, -/// for runtimes that still read them from the row. They are never carried from the prior row: a -/// milestone the table does not know gets zero, which offers no command. A prior row with zero -/// never had the developer bar checked, so it keeps zero. -fn write_command_ids(row: &mut Value, version: &str, report: &mut PortReport) { - let browser = row["build"]["browser"].as_str().unwrap_or_default(); - // Chrome, Edge and Brave carry their Chromium milestone as the first part of their version. - let milestone = matches!(browser, "Google Chrome" | "Microsoft Edge" | "Brave") - .then(|| version.split('.').next()?.parse::().ok()) - .flatten(); - let ids = milestone.and_then(crate::command_ids::dev_tools); - let Some(dev) = row["build"]["toolbar"]["dev"].as_object_mut() else { - return; - }; - for (key, id) in [ - ("inspect", ids.map(|ids| ids.0)), - ("console", ids.map(|ids| ids.1)), - ] { - let Some(prior) = dev.get(key).and_then(Value::as_u64) else { - continue; - }; - let value = if prior == 0 { 0 } else { id.unwrap_or(0) }; - dev.insert(key.to_owned(), json!(value)); - report.derived.push(match (prior == 0, id) { - (true, _) => format!("toolbar.dev.{key}: 0, the prior row offers no developer bar"), - (false, Some(id)) => format!( - "toolbar.dev.{key}: {id}, from chrome_command_ids.h at Chromium {}", - milestone.unwrap_or_default() - ), - (false, None) => format!( - "toolbar.dev.{key}: 0, no command id is read for this build's Chromium milestone" - ), - }); - } -} - -/// The prior row's functions that a browser command runs first, with the command's public id: -/// `chrome::NewTab`, the first call of the `IDC_NEW_TAB` case of the browser's command switch. The -/// id must be the same at the prior and the new build's Chromium milestone, which Chrome, Edge and -/// Brave carry as the first part of their version. -fn command_targets(prior: &Value, version: &str) -> BTreeMap { - let browser = prior["build"]["browser"].as_str().unwrap_or_default(); - if !matches!(browser, "Google Chrome" | "Microsoft Edge" | "Brave") { - return BTreeMap::new(); - } - let milestone = |version: &str| version.split('.').next()?.parse::().ok(); - let prior_version = prior["frame"]["version"].as_str().unwrap_or_default(); - let ids = ( - milestone(prior_version).and_then(crate::command_ids::new_tab), - milestone(version).and_then(crate::command_ids::new_tab), - ); - let (Some(id), Some(same)) = ids else { - return BTreeMap::new(); - }; - let address = - read_address(&prior["build"]["tabs"]["new_tab"]).filter(|value| is_address(*value)); - match address { - Some(address) if id == same => BTreeMap::from([(address as u32, id as i64)]), - _ => BTreeMap::new(), - } -} - -/// Writes the new places into a row and reads every guard and table slot back from the new module. -fn finish_row( - mut row: Value, - moved: &BTreeMap, - pe: &PeFile, - mut report: PortReport, -) -> (Value, PortReport) { - report.mapped = moved.len(); - - let frame_values = row - .as_object_mut() - .and_then(|object| object.remove("frame_addresses")) - .unwrap_or_default(); - let mut unmapped = BTreeSet::new(); - let mut rewrite = |path: &str, value: &mut Value| { - if let Some(address) = read_address(value).filter(|value| is_address(*value)) { - if READ_FROM_CODE.iter().any(|field| path.ends_with(field)) { - return; - } - match moved.get(&(address as u32)) { - Some(place) => *value = write_address(u64::from(*place)), - None => { - unmapped.insert(format!("{path} {address:#x}")); - } - } - } - }; - walk_addresses("", &mut row["build"], &mut rewrite); - let mut frame_values = frame_values; - walk_addresses(".frame", &mut frame_values, &mut rewrite); - report.review.extend( - unmapped - .into_iter() - .map(|field| format!("no new place for {field}")), - ); - apply_frame_addresses(&mut row["frame"], &frame_values); - - // Everything read back from the new module. - read_rounded_corners(&mut row["build"], pe, &mut report); - refresh_guards("build", &mut row["build"], pe, &mut report); - refresh_frame_guard(&mut row["frame"], pe, &mut report); - check_vtable_slots(&mut row["build"], pe, &mut report); - check_frame_slot(&mut row["frame"], pe, &mut report); - // Last, since the recipes read the addresses of the new build. - let derived = crate::row_recipe::derive_row(&mut row["build"], pe); - report.derived.extend(derived.read); - for failure in derived.failed { - // A value of a feature the runtime can do without turns that feature off instead. - let path = failure.split(": ").next().unwrap_or_default(); - if crate::row_features::feature_of(path).is_some() { - report.off_values.insert( - path.to_owned(), - format!("could not be read from the new build: {failure}"), - ); - } else { - report.review.push(format!( - "a value could not be read from the new build: {failure}" - )); - } - } - (row, report) -} - -/// How many bytes of a function a fingerprint holds at most. -const FINGERPRINT_BYTES: usize = 32; -/// A shorter fingerprint matches too many places to mean anything. -const FINGERPRINT_LEAST: usize = 16; -/// The first bytes of a fingerprint, which are searched for, must be plain instruction bytes. -const ANCHOR: usize = 4; -/// How far into a class table a fingerprint looks for a slot it can name. -const SLOTS_SEEN: u32 = 0x80; - -/// The addresses of a row that are found again in a new build. Those read from code are skipped. -fn fingerprint_targets(row: &Value) -> BTreeSet { - let mut row = row.clone(); - row["frame_addresses"] = frame_addresses(&row["frame"]); - let mut found = BTreeSet::new(); - let mut collect = |path: &str, value: &mut Value| { - if READ_FROM_CODE.iter().any(|field| path.ends_with(field)) { - return; - } - if let Some(address) = read_address(value).filter(|value| is_address(*value)) { - found.insert(address as u32); - } - }; - walk_addresses("", &mut row["build"], &mut collect); - walk_addresses(".frame", &mut row["frame_addresses"], &mut collect); - found -} - -/// The start of a function with its displacements cleared, cut at an instruction end. -pub(crate) fn code_print(pe: &PeFile, address: u32) -> Option> { - if !pe.is_code(address) { - return None; - } - let window = pe.read(address, FINGERPRINT_BYTES + 16)?; - // Zeros decode as `add [rax], al` and padding as `int3`: the start of a class table or of the - // gap between functions, never of a function. - if window.starts_with(&[0x00, 0x00]) || window.first() == Some(&0xCC) { - return None; - } - let (ends, _) = x64::boundaries(window, FINGERPRINT_BYTES); - let length = ends - .iter() - .rev() - .find(|end| **end <= FINGERPRINT_BYTES) - .copied()?; - if length < FINGERPRINT_LEAST { - return None; - } - let bytes = &window[..length]; - let shape = x64::shape(bytes)?; - // The anchor is searched for byte by byte, so it may not hold a displacement. - (shape[..ANCHOR] == bytes[..ANCHOR]).then_some(shape) -} - -/// Records, in the row, how the runtime can find each of its addresses in a build with no row. -/// A function is known by its first instructions without their displacements. A class table is -/// known by a slot that holds one of those functions. An address that is neither cannot be found, -/// so then the row gets no fingerprints at all. -pub fn add_fingerprints(row: &mut Value, pe: &PeFile) -> Result<(), String> { - let (prints, missing) = fingerprints_of(row, pe); - if !missing.is_empty() { - return Err(format!("no fingerprint for {}", missing.join(", "))); - } - row["fingerprints"] = Value::Object(prints); - Ok(()) -} - -/// The fingerprint of each address of a row that has one, read from the row's own module, and the -/// addresses that have none. A row made from them leaves those addresses unvouched. -pub fn fingerprints_of(row: &Value, pe: &PeFile) -> (serde_json::Map, Vec) { - let targets = fingerprint_targets(row); - let mut prints = serde_json::Map::new(); - let mut missing = Vec::new(); - let mut functions = BTreeMap::new(); - for target in &targets { - if let Some(shape) = code_print(pe, *target) { - functions.insert(*target, hex_text(&shape)); - } - } - for target in &targets { - let key = format!("{target:#x}"); - if let Some(shape) = functions.get(target) { - prints.insert(key, Value::String(shape.clone())); - continue; - } - let slot = (0..SLOTS_SEEN).find_map(|slot| { - let holds = pe.pointer_rva(target.checked_add(slot * 8)?)?; - functions.contains_key(&holds).then_some((slot, holds)) - }); - match slot { - Some((slot, holds)) => { - prints.insert(key, json!({"slot": slot, "holds": format!("{holds:#x}")})); - } - None => missing.push(key), - } - } - (prints, missing) -} - -/// Every place each function fingerprint matches, in one pass over the code. -pub(crate) fn find_prints(pe: &PeFile, prints: &BTreeMap>) -> BTreeMap> { - let mut by_anchor: HashMap<[u8; ANCHOR], Vec> = HashMap::new(); - let mut first = [false; 256]; - for (target, shape) in prints { - let anchor: [u8; ANCHOR] = shape[..ANCHOR].try_into().expect("checked length"); - first[anchor[0] as usize] = true; - by_anchor.entry(anchor).or_default().push(*target); - } - let mut found: BTreeMap> = BTreeMap::new(); - for (base, bytes, is_code) in pe.sections() { - if !is_code { - continue; - } - for at in 0..bytes.len().saturating_sub(ANCHOR) { - if !first[bytes[at] as usize] { - continue; - } - let anchor: [u8; ANCHOR] = bytes[at..at + ANCHOR].try_into().expect("in range"); - let Some(targets) = by_anchor.get(&anchor) else { - continue; - }; - for target in targets { - let shape = &prints[target]; - let Some(candidate) = bytes.get(at..at + shape.len()) else { - continue; - }; - if x64::shape(candidate).as_deref() == Some(shape.as_slice()) { - found.entry(*target).or_default().push(base + at as u32); - } - } - } - } - found -} - -/// Every class table whose given slot holds a function, by a pointer search over the module. -pub(crate) fn find_table(pe: &PeFile, slot: u32, function: u32) -> Vec { - let value = (pe.image_base() + u64::from(function)).to_le_bytes(); - let mut found = Vec::new(); - for (base, bytes, _) in pe.sections() { - for at in (0..bytes.len().saturating_sub(7)).step_by(8) { - if bytes[at..at + 8] == value { - if let Some(table) = (base + at as u32).checked_sub(slot * 8) { - found.push(table); - } - } - } - } - found -} - -/// Makes the row of a build that has no row from the fingerprints of a verified row of the same -/// milestone, from the new module alone. Each address must match exactly one place, no two addresses may -/// share one, and every function start and table slot is then checked again in the new module the -/// way a ported row is. Any doubt is an error with its reasons, and then the runtime changes -/// nothing in the browser. -pub fn find_row(prior: &Value, version: &str, pe: &PeFile) -> Result> { - let Some(stored) = prior["fingerprints"].as_object() else { - return Err(vec!["the row has no fingerprints".to_owned()]); - }; - let (row, report) = find_candidate(prior, stored, None, &BTreeMap::new(), version, pe); - if !report.review.is_empty() { - return Err(report.review); - } - Ok(row) -} - -/// Makes a candidate row for a new build from `stored`, the fingerprints of the prior row's -/// addresses in the prior build. An address is taken where its fingerprint matches exactly one -/// place. Offsets, slots and sizes with a recipe are read again from the new module. -/// -/// `classes` names the views class of each class table of the prior row, as `prior_classes` reads -/// them. The new row records the names of the tables it placed, by the path of each value, so the -/// next row starts from them. -/// -/// `prior_pe` is the prior row's own module, when the caller has it. A fingerprint taken at a -/// function start its exception table lists then counts only places the new module's exception -/// table also lists, since the same bytes inside another function are not the function. Each -/// address the fingerprints leave open is looked for by `row_resolve`, which takes a place only -/// where two independent methods agree, and each value with no recipe is read from the -/// instructions that use it. An address that stays open and that only features the runtime can do -/// without hold turns those features off and is cleared. Whatever else stays open keeps a review -/// line and its prior value, so such a row is never published as it is. -pub fn find_candidate( - prior: &Value, - stored: &serde_json::Map, - prior_pe: Option<&PeFile>, - classes: &BTreeMap, - version: &str, - pe: &PeFile, -) -> (Value, PortReport) { - let (mut row, mut report) = begin_row(prior, version, prior_pe.is_none()); - let prior_starts = prior_pe.map(PeFile::function_starts).unwrap_or_default(); - let targets = fingerprint_targets(prior); - report.addresses = targets.len(); - let mut functions = BTreeMap::new(); - let mut tables = BTreeMap::new(); - // Each address its fingerprint did not pin down, with its review line, waits for the methods - // that read the prior build next to the new one. - let mut wanted: BTreeMap = BTreeMap::new(); - let commands = command_targets(prior, version); - let want = - |target: u32, kind: row_resolve::Kind, candidates: Option>| row_resolve::Wanted { - kind, - candidates, - class: (kind == row_resolve::Kind::Table) - .then(|| classes.get(&target).cloned()) - .flatten(), - command: (kind == row_resolve::Kind::Function) - .then(|| commands.get(&target).copied()) - .flatten(), - loose: Vec::new(), - }; - for target in &targets { - match stored.get(&format!("{target:#x}")) { - Some(Value::String(text)) => match hex(text).filter(|shape| shape.len() >= ANCHOR) { - Some(shape) => { - functions.insert(*target, shape); - } - None => report - .review - .push(format!("{target:#x}: unreadable fingerprint")), - }, - Some(Value::Object(table)) => { - let slot = table["slot"] - .as_u64() - .and_then(|slot| u32::try_from(slot).ok()); - let holds = read_address(&table["holds"]).map(|holds| holds as u32); - match (slot, holds) { - (Some(slot), Some(holds)) => { - tables.insert(*target, (slot, holds)); - } - _ => report - .review - .push(format!("{target:#x}: unreadable table fingerprint")), - } - } - _ => { - let line = format!("{target:#x}: no fingerprint"); - // Without the prior module no method can place it, but it is still settled with - // the other open addresses, so a feature that is off does not stop the row. - let kind = match prior_pe { - Some(prior_pe) if !prior_pe.is_code(*target) => row_resolve::Kind::Table, - _ => row_resolve::Kind::Function, - }; - wanted.insert(*target, (line, want(*target, kind, None))); - } - } - } - let found = find_prints(pe, &functions); - let new_starts = if prior_starts.is_empty() { - BTreeSet::new() - } else { - pe.function_starts() - }; - let mut moved = BTreeMap::new(); - for target in functions.keys() { - let all = found.get(target).map_or(&[][..], Vec::as_slice); - let places: Vec = all - .iter() - .copied() - .filter(|place| { - // The linker starts whole functions on 16 bytes, and the exception table also - // lists the parts it moves out of a function, which start anywhere. - !prior_starts.contains(target) - || (new_starts.contains(place) && (target % 16 != 0 || *place % 16 == 0)) - }) - .collect(); - let function = row_resolve::Kind::Function; - match places.as_slice() { - [only] => { - moved.insert(*target, *only); - // Says which matches the exception tables checked, for the person reading the report. - let checked = if prior_starts.contains(target) { - " at a function start" - } else { - "" - }; - report - .fingerprinted - .push(format!("{target:#x} -> {only:#x}{checked}")); - } - [] if !all.is_empty() => { - let line = format!( - "{target:#x} matches no function start, of {} places", - all.len() - ); - let mut asked = want(*target, function, None); - asked.loose = all.to_vec(); - wanted.insert(*target, (line, asked)); - } - [] => { - let line = format!("{target:#x} matches no place"); - wanted.insert(*target, (line, want(*target, function, None))); - } - many => { - let line = format!("{target:#x} matches {} places", many.len()); - wanted.insert( - *target, - (line, want(*target, function, Some(many.to_vec()))), - ); - } - } - } - for (target, (slot, holds)) in &tables { - let table = row_resolve::Kind::Table; - let Some(function) = moved.get(holds).copied() else { - let line = format!("{target:#x}: the function in slot {slot} was not found"); - wanted.insert(*target, (line, want(*target, table, None))); - continue; - }; - match find_table(pe, *slot, function).as_slice() { - [only] => { - moved.insert(*target, *only); - report - .fingerprinted - .push(format!("{target:#x} -> {only:#x}")); - } - many => { - let line = format!( - "{target:#x}: {} tables hold {function:#x} in slot {slot}", - many.len() - ); - let candidates = (!many.is_empty()).then(|| many.to_vec()); - wanted.insert(*target, (line, want(*target, table, candidates))); - } - } - } - let mut followed = BTreeMap::new(); - // Each address no method placed, with its review line. Those that only features the runtime - // can do without hold do not stop the row. - let mut open: BTreeMap = BTreeMap::new(); - match prior_pe { - Some(prior_pe) if !wanted.is_empty() => { - let table_targets: BTreeSet = tables - .keys() - .copied() - .chain( - wanted - .iter() - .filter(|(_, (_, want))| want.kind == row_resolve::Kind::Table) - .map(|(target, _)| *target), - ) - .collect(); - let asked: BTreeMap = wanted - .iter() - .map(|(target, (_, want))| (*target, want.clone())) - .collect(); - // The tables a class name was confirmed for in the prior build are the tables of views - // classes the slot shift compares. - let views: BTreeSet = classes.keys().copied().collect(); - let resolution = - row_resolve::resolve(prior_pe, pe, &moved, &asked, &table_targets, &views); - for (target, (line, _)) in &wanted { - match resolution.places.get(target) { - Some(place) => { - moved.insert(*target, *place); - } - None => { - let reason = resolution - .reasons - .get(target) - .map_or("no method was run", String::as_str); - open.insert(*target, format!("{line}; not settled: {reason}")); - } - } - } - report.settled.extend(resolution.settled); - followed = resolution.followed; - } - _ => open.extend(wanted.into_iter().map(|(target, (line, _))| (target, line))), - } - release_unplaced(prior, &mut row, open, &mut report); - let places: BTreeSet = moved.values().copied().collect(); - if places.len() != moved.len() { - report - .review - .push("two addresses found the same place".to_owned()); - } - let (mut row, mut report) = finish_row(row, &moved, pe, report); - if let Some(object) = row.as_object_mut() { - // They describe the prior build, so they would mislead in this row. - object.remove("fingerprints"); - object.remove(CLASSES); - } - record_classes(prior, &mut row, classes, &moved); - if let Some(prior_pe) = prior_pe { - read_carried( - prior, - &mut row, - &moved, - &followed, - prior_pe, - pe, - &mut report, - ); - } - settle_carried(&mut row, &mut report); - (row, report) -} - -/// Settles each address no method placed in the new build. Where every value that holds it belongs -/// to a feature the runtime can do without, or is not read in this row, those values are cleared -/// and the features go off, and the address is listed in the report. An address that a part the -/// window cannot do without holds, the frame or the page area layout, stops the row with its line. -fn release_unplaced( - prior: &Value, - row: &mut Value, - open: BTreeMap, - report: &mut PortReport, -) { - use crate::row_features::{self, Clear}; - if open.is_empty() { - return; - } - let mut holders: BTreeMap> = BTreeMap::new(); - let mut note = |path: &str, value: &mut Value| { - if READ_FROM_CODE.iter().any(|field| path.ends_with(field)) { - return; - } - if let Some(address) = read_address(value).filter(|value| is_address(*value)) { - holders - .entry(address as u32) - .or_default() - .push(path.trim_start_matches('.').to_owned()); - } - }; - let mut build = prior["build"].clone(); - walk_addresses("", &mut build, &mut note); - // The frame part has no feature to turn off, so its paths always stop the row. - let mut frame = frame_addresses(&prior["frame"]); - walk_addresses("frame", &mut frame, &mut note); - for (target, line) in open { - let paths = holders.remove(&target).unwrap_or_default(); - let needed = paths.is_empty() - || paths.iter().any(|path| { - path.starts_with("frame.") - || (row_features::feature_of(path).is_none() - && row_features::unused(&row["build"], path).is_none()) - }); - if needed { - report.review.push(line); - continue; - } - for path in &paths { - match row_features::feature_of(path) { - Some(feature) => { - row_features::clear_value(&mut row["build"], path, feature); - report.off_values.insert( - path.clone(), - format!("has no place in the new build: {line}"), - ); - } - None => { - let why = row_features::unused(&row["build"], path).unwrap_or_default(); - // A list holds no single address, so a value in one becomes zero. - let how = if path.contains('[') { - Clear::Zero - } else { - Clear::Absent - }; - row_features::clear(&mut row["build"], path, how); - report.unused.push(format!("{path}: {why}")); - } - } - } - report - .unplaced - .push(format!("{line}; cleared from {}", paths.join(", "))); - } -} - -/// The value at a path such as `layout.frame_ids[2]` or `toolbar.dev.colours[3][0]`. -fn value_at<'a>(value: &'a Value, path: &str) -> Option<&'a Value> { - let mut current = value; - for part in path.split('.') { - let (key, indexes) = part.split_at(part.find('[').unwrap_or(part.len())); - current = current.get(key)?; - for index in indexes.split(']').filter(|index| !index.is_empty()) { - current = current.get(index.trim_start_matches('[').parse::().ok()?)?; - } - } - Some(current) -} - -fn value_at_mut<'a>(value: &'a mut Value, path: &str) -> Option<&'a mut Value> { - let mut current = value; - for part in path.split('.') { - let (key, indexes) = part.split_at(part.find('[').unwrap_or(part.len())); - current = current.get_mut(key)?; - for index in indexes.split(']').filter(|index| !index.is_empty()) { - current = current.get_mut(index.trim_start_matches('[').parse::().ok()?)?; - } - } - Some(current) -} - -/// Reads each value the recipes leave, a member offset, slot, size or id, from the instructions -/// that use it in the prior build's functions and the same instructions in the new build. A value -/// that cannot be read keeps its reason and stays listed as carried, and `settle_carried` decides -/// what it does to the row, so the row is never published with a value of the prior build. -fn read_carried( - prior: &Value, - row: &mut Value, - moved: &BTreeMap, - followed: &BTreeMap, - prior_pe: &PeFile, - pe: &PeFile, - report: &mut PortReport, -) { - let mut values = Vec::new(); - let mut unreadable = Vec::new(); - for path in std::mem::take(&mut report.carried) { - let items: Vec<(String, &Value)> = match value_at(&prior["build"], &path) { - Some(Value::Array(items)) => items - .iter() - .enumerate() - .map(|(index, item)| (format!("{path}[{index}]"), item)) - .collect(), - Some(item) => vec![(path.clone(), item)], - None => vec![], - }; - if items.is_empty() { - unreadable.push(path); - } - for (path, item) in items { - match crate::row_recipe::number(item) { - Some(value) => values.push((path, value)), - None => unreadable.push(path), - } - } - } - // Each part of the row reads its values from its own functions. - let mut sections: BTreeMap> = BTreeMap::new(); - for (section, part) in prior["build"].as_object().into_iter().flatten() { - let mut part = part.clone(); - let mut pairs = Vec::new(); - walk_addresses("", &mut part, &mut |_, value| { - if let Some(address) = read_address(value).filter(|value| is_address(*value)) { - let address = address as u32; - if let Some(place) = moved.get(&address).filter(|_| prior_pe.is_code(address)) { - pairs.push((address, *place)); - } - } - }); - pairs.sort_unstable(); - pairs.dedup(); - if !pairs.is_empty() { - sections.insert(section.clone(), pairs); - } - } - for reading in row_resolve::read_values(prior_pe, pe, §ions, followed, &values) { - match reading.value { - Ok((value, how)) => { - if let Some(place) = value_at_mut(&mut row["build"], &reading.path) { - *place = if place.is_string() { - write_address(value) - } else { - json!(value) - }; - } - report.derived.push(if value == reading.prior { - format!("{}: {value:#x}, {how}", reading.path) - } else { - format!( - "{}: {:#x} -> {value:#x}, {how}", - reading.path, reading.prior - ) - }); - } - Err(reason) => { - report.unread.insert( - reading.path.clone(), - format!("was not read from the new build: {reason}"), - ); - report.carried.push(reading.path); - } - } - } - for path in unreadable { - report.unread.insert( - path.clone(), - "is not a number this generator can read".to_owned(), - ); - report.carried.push(path); - } -} - -/// The key of a row that names the views class of each of its class tables, by the path of the -/// value that holds the table, as `{"build.layout.frame_vtable": "BrowserFrameViewWin"}`. The -/// runtime reads only `frame` and `build`, so the names change nothing in a browser. -pub const CLASSES: &str = "classes"; - -/// The path of every address a row holds, the frame entry's included, as `build.layout.frame_vtable` -/// or `frame.frame_view_vtable`. -fn address_paths(row: &Value) -> Vec<(String, u32)> { - let mut out = Vec::new(); - let mut note = |path: &str, value: &mut Value| { - if READ_FROM_CODE.iter().any(|field| path.ends_with(field)) { - return; - } - if let Some(address) = read_address(value).filter(|value| is_address(*value)) { - out.push((path.to_owned(), address as u32)); - } - }; - let mut build = row["build"].clone(); - walk_addresses("build", &mut build, &mut note); - let mut frame = frame_addresses(&row["frame"]); - walk_addresses("frame", &mut frame, &mut note); - out -} - -/// The views class of each class table of the prior row, from the build alone. A name the prior -/// row records for the table is taken when it gives exactly that table in the prior module, and -/// a table with no such name is named by the class name its metadata holds, read back from the -/// prior module by `row_class`. Either way the name is the one the class's `BEGIN_METADATA` gives -/// in Chromium's source, and a table no name gives alone has none. -pub fn prior_classes(prior: &Value, prior_pe: &PeFile) -> BTreeMap { - let recorded = prior[CLASSES].as_object(); - let mut out = BTreeMap::new(); - let mut tried = BTreeSet::new(); - for (path, address) in address_paths(prior) { - if prior_pe.is_code(address) || out.contains_key(&address) { - continue; - } - let name = recorded - .and_then(|names| names.get(&path)) - .and_then(Value::as_str) - .filter(|name| crate::row_class::names_table(prior_pe, name, address)) - .map(str::to_owned); - let name = match name { - Some(name) => Some(name), - None if tried.insert(address) => { - crate::row_class::class_name_of_table(prior_pe, address) - } - None => None, - }; - if let Some(name) = name { - out.insert(address, name); - } - } - out -} - -/// Writes into the new row the class name of each class table it placed, by the path of each value -/// that holds the table. -fn record_classes( - prior: &Value, - row: &mut Value, - classes: &BTreeMap, - moved: &BTreeMap, -) { - let mut names = serde_json::Map::new(); - for (path, address) in address_paths(prior) { - if let Some(name) = classes - .get(&address) - .filter(|_| moved.contains_key(&address)) - { - names.insert(path, Value::String(name.clone())); - } - } - if !names.is_empty() { - row[CLASSES] = Value::Object(names); - } -} - -/// The frame entry keeps plain numbers. The walk over a row reads `0x` strings. -fn frame_addresses(frame: &Value) -> Value { - let field = |key: &str| frame[key].as_u64().map_or(Value::Null, write_address); - json!({ - "frame_view_vtable": field("frame_view_vtable"), - "client_view_bounds": field("client_view_bounds"), - "hwnd_for_view": field("hwnd_for_view"), - }) -} - -fn apply_frame_addresses(frame: &mut Value, addresses: &Value) { - for key in ["frame_view_vtable", "client_view_bounds", "hwnd_for_view"] { - if let Some(value) = read_address(&addresses[key]) { - frame[key] = json!(value); - } - } -} - -fn refresh_frame_guard(frame: &mut Value, pe: &PeFile, report: &mut PortReport) { - let (Some(address), Some(old)) = ( - frame["hwnd_for_view"].as_u64(), - frame["hwnd_for_view_prologue"].as_str().and_then(hex), - ) else { - report - .review - .push("the frame entry has no hwnd_for_view".into()); - return; - }; - if let Some(new) = read_guard( - "frame.hwnd_for_view_prologue", - address, - &old, - true, - pe, - report, - ) { - frame["hwnd_for_view_prologue"] = Value::String(hex_text(&new)); - } -} - -fn check_frame_slot(frame: &mut Value, pe: &PeFile, report: &mut PortReport) { - let field = |key: &str| frame[key].as_u64().map(|value| value as u32); - let (Some(vtable), Some(slot), Some(function)) = ( - field("frame_view_vtable"), - field("client_view_slot"), - field("client_view_bounds"), - ) else { - report.review.push("the frame entry is incomplete".into()); - return; - }; - if pe.pointer_rva(vtable + slot * 8) == Some(function) { - return; - } - // A milestone that removes a virtual function moves the slot, and the table itself says where - // the function went, as the recipes of the build's own slots do. - match pe.vtable_slot(vtable, function) { - Some(moved) => { - frame["client_view_slot"] = json!(moved); - report - .derived - .push(format!("frame.client_view_slot: {slot:#x} -> {moved:#x}")); - } - None => report.review.push(format!( - "the frame vtable {vtable:#x} slot {slot} does not hold {function:#x}" - )), - } -} - -/// Leaves `screen_origin`, `[address, first bytes]` of `views::View::ConvertPointToScreen`, out of a -/// row whose prior row had none. A prior row that had it was found again with every other address. -/// The runtime then keeps placing bubbles from the window's monitor, so the row is not stopped. -pub fn leave_out_screen_origin(row: &mut Value, report: &mut PortReport) { - if row["build"]["screen_origin"].is_array() { - return; - } - row["build"]["screen_origin"] = Value::Null; - report - .left_out - .push("build.screen_origin: the prior row has none".to_owned()); -} - -/// The group a value of a row is scored in: its feature, or the window, whose parts cannot be off. -const WINDOW: &str = "window"; - -/// How one feature of a row made without debug symbols compares with the verified row of the same -/// build, value by value. -#[derive(Debug, Default, Serialize, PartialEq, Eq)] -pub struct FeatureScore { - /// Values the made row holds exactly as the verified row does. - pub equal: usize, - /// Values the made row holds differently, with both. Any is a wrong value. - pub different: Vec, - /// Values no method placed in the new build, so the made row still shows the prior build's and - /// a review line stops the row. Not a wrong value: the row is not published. - pub not_found: Vec, - /// Values the made row holds exactly as the prior row did although the verified row differs: - /// nothing read them again. Wrong only in a row no review line stops. - pub carried: Vec, - /// The made row turns the feature off, so none of its values is used. - pub off: bool, - /// Values the made row does not hold or does not use: the runtime finds them by reflection, - /// does not read them in this build, or the prior row did not have them. - pub not_held: Vec, -} - -/// The score of a made row against its answer key: each feature's comparison, and the review lines -/// that stop the row. -#[derive(Debug, Default, Serialize)] -pub struct RowScore { - pub browser: String, - pub version: String, - pub prior_version: String, - pub features: BTreeMap, - pub review: Vec, -} - -impl RowScore { - /// How many values were found but differ from the verified row, with the values carried from - /// the prior build when no review line stops the row. Must be zero. - pub fn wrong(&self) -> usize { - self.features - .values() - .map(|score| match self.review.is_empty() { - true => score.different.len() + score.carried.len(), - false => score.different.len(), - }) - .sum() - } -} - -/// The address a value was read at: the function of a prologue, or the first item of a pair. -fn read_at(path: &str) -> Option { - if let Some(function) = path.strip_suffix("_prologue") { - return Some(function.to_owned()); - } - path.strip_suffix("[1]").map(|pair| format!("{pair}[0]")) -} - -/// Every value a row part holds that is not a list or object, by its path. -fn leaves(path: &str, value: &Value, out: &mut BTreeMap) { - match value { - Value::Object(object) => { - for (key, item) in object { - let next = if path.is_empty() { - key.clone() - } else { - format!("{path}.{key}") - }; - leaves(&next, item, out); - } - } - Value::Array(items) if !items.is_empty() => { - for (index, item) in items.iter().enumerate() { - leaves(&format!("{path}[{index}]"), item, out); - } - } - _ => { - out.insert(path.to_owned(), value.clone()); - } - } -} - -/// Compares a row made from a prior row with the row people verified for the same build. A value of -/// a feature the made row turns off is not compared, since the runtime does not use it. A value the -/// made row leaves out, or writes as zero because this build does not read it, is listed as not -/// held. A value a review line reports as having no new place is listed as not found. Every other -/// value must be equal, and one that differs is listed with both values. -pub fn score_row(made: &Value, report: &PortReport, verified: &Value, prior: &Value) -> RowScore { - let off: BTreeSet<&str> = made[crate::row_features::SWITCHED_OFF] - .as_array() - .map_or(&[][..], Vec::as_slice) - .iter() - .filter_map(|entry| entry["feature"].as_str()) - .collect(); - let unused: BTreeSet<&str> = report - .unused - .iter() - .chain(&report.reflected) - .filter_map(|line| line.split(": ").next()) - .collect(); - let unplaced: BTreeSet = report - .review - .iter() - .filter_map(|line| line.strip_prefix("no new place for .")) - .filter_map(|rest| rest.split(' ').next()) - .map(|path| match path.starts_with("frame.") { - true => path.to_owned(), - false => format!("build.{path}"), - }) - .collect(); - let mut score = RowScore { - browser: report.browser.clone(), - version: report.version.clone(), - prior_version: report.prior_version.clone(), - review: report.review.clone(), - ..RowScore::default() - }; - for part in ["frame", "build"] { - let (mut want, mut have, mut before) = (BTreeMap::new(), BTreeMap::new(), BTreeMap::new()); - leaves("", &verified[part], &mut want); - leaves("", &prior[part], &mut before); - leaves("", &made[part], &mut have); - for (path, value) in want { - let feature = match part { - "build" => { - crate::row_features::feature_of(&path).map_or(WINDOW, |feature| feature.name) - } - _ => WINDOW, - }; - let entry = score.features.entry(feature.to_owned()).or_default(); - if off.contains(feature) { - entry.off = true; - continue; - } - let shown = format!("{part}.{path}"); - match have.get(&path) { - Some(found) if *found == value => entry.equal += 1, - None | Some(Value::Null) => entry.not_held.push(shown), - Some(_) if unused.iter().any(|unused| path.starts_with(unused)) => { - entry.not_held.push(shown) - } - Some(_) if unplaced.contains(&shown) => entry.not_found.push(shown), - // Bytes read at an address with no new place say nothing about the new build. - Some(_) if read_at(&shown).is_some_and(|at| unplaced.contains(&at)) => { - entry.not_found.push(shown) - } - // A part the generator could not confirm is declined, which is not a wrong value. - Some(Value::Bool(false)) => entry.not_found.push(shown), - Some(found) if before.get(&path) == Some(found) => entry - .carried - .push(format!("{shown}: carried {found}, verified {value}")), - Some(found) => entry - .different - .push(format!("{shown}: made {found}, verified {value}")), - } - } - } - score -} - -/// The review items for the parts of the prior row that only a person writes today. A row made -/// without them opens Rivet's frame with those features off, so it goes to a person instead of -/// the table. The runtime names them in the prior row's `hand_only` list. -pub fn hand_only_review(prior: &Value) -> Vec { - prior["hand_only"] - .as_array() - .map_or(&[][..], Vec::as_slice) - .iter() - .filter_map(Value::as_str) - .map(|part| { - format!("the prior row has {part}, which this generator cannot make yet; without it those features would be off") - }) - .collect() -} -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn nfr6_a_row_whose_prior_had_hand_written_parts_goes_to_a_person() { - let prior = serde_json::json!({ - "frame": {}, "build": {}, - "hand_only": ["address bar functions and the app window layout", "page tools", "the bubble anchor"] - }); - let review = hand_only_review(&prior); - assert_eq!(review.len(), 3); - assert!(review[0].contains("address bar functions")); - // A prior row with nothing written by hand adds nothing. - assert!(hand_only_review(&serde_json::json!({ "frame": {}, "build": {} })).is_empty()); - } - const IMAGE_BASE: u64 = 0x1_8000_0000; - - /// A small 64-bit module: one code section at RVA 0x100000, read from the given bytes. - fn module(code: &[(u32, &[u8])]) -> Vec { - let mut bytes = vec![0u8; 0x400]; - bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); - bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); - bytes[0x86..0x88].copy_from_slice(&1u16.to_le_bytes()); - bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes()); - bytes[0x98..0x9a].copy_from_slice(&0x20bu16.to_le_bytes()); - bytes[0x98 + 24..0x98 + 32].copy_from_slice(&IMAGE_BASE.to_le_bytes()); - let header = 0x98 + 240; - bytes[header + 8..header + 12].copy_from_slice(&0x180000u32.to_le_bytes()); - bytes[header + 12..header + 16].copy_from_slice(&0x100000u32.to_le_bytes()); - bytes[header + 20..header + 24].copy_from_slice(&0x400u32.to_le_bytes()); - bytes[header + 36..header + 40].copy_from_slice(&0x2000_0000u32.to_le_bytes()); - bytes.resize(0x400 + 0x10000, 0xCC); - for (rva, data) in code { - let at = 0x400 + (*rva - 0x100000) as usize; - bytes[at..at + data.len()].copy_from_slice(data); - } - bytes - } - - fn prior() -> Value { - json!({ - "frame": { - "browser": "B", "version": "1.0.0.1", "module": "b.dll", - "frame_view_vtable": 0x200000, "client_view_slot": 1, "client_view_bounds": 0x200100, - "hwnd_for_view": 0x200200, "hwnd_for_view_prologue": "4883ec28", - }, - "build": { - "browser": "B", "module": "b.dll", "version": [1, 0, 0, 1], - "toolbar": { - "paint": "0x200300", "paint_prologue": "415741564155415456575553", - "view_layer": "0x20", "missing": "0x7fff0000", - "colours": [[1, 2147483648u32]], - }, - "tabs": {"signatures": [["0x200300", "41574156"]]}, - }, - }) - } - - fn pointer(rva: u32) -> [u8; 8] { - (IMAGE_BASE + u64::from(rva)).to_le_bytes() - } - - /// Places the prior row's addresses where `moved` says, as the fingerprints and `row_resolve` - /// would, and settles the rest of the row the way every new row is settled. - fn port( - prior: &Value, - moved: &[(u32, u32)], - code: &[(u32, &[u8])], - version: &str, - ) -> (Value, PortReport) { - let bytes = module(code); - let pe = PeFile::parse(&bytes).unwrap(); - let (row, mut report) = begin_row(prior, version, true); - report.addresses = addresses_of(&row["build"]).len(); - let moved: BTreeMap = moved.iter().copied().collect(); - let (mut row, mut report) = finish_row(row, &moved, &pe, report); - settle_carried(&mut row, &mut report); - (row, report) - } - - const NEW_PLACES: &[(u32, u32)] = &[ - (0x200000, 0x101000), - (0x200100, 0x101100), - (0x200200, 0x101200), - (0x200300, 0x101300), - ]; - - fn new_code() -> Vec<(u32, Vec)> { - vec![ - (0x101008, pointer(0x101100).to_vec()), - (0x101200, hex("4883ec18").unwrap()), - (0x101300, hex("415741564155415456575553").unwrap()), - ] - } - - fn code_refs(code: &[(u32, Vec)]) -> Vec<(u32, &[u8])> { - code.iter() - .map(|(rva, data)| (*rva, data.as_slice())) - .collect() - } - - #[test] - fn nfr3_a_new_row_takes_the_found_places_and_bytes_from_the_new_module() { - let code = new_code(); - let (row, report) = port(&prior(), NEW_PLACES, &code_refs(&code), "1.0.0.2"); - assert_eq!(report.review, Vec::::new()); - assert_eq!(row["build"]["version"], json!([1, 0, 0, 2])); - assert_eq!(row["frame"]["version"], "1.0.0.2"); - assert_eq!(row["build"]["toolbar"]["paint"], "0x101300"); - assert_eq!(row["build"]["tabs"]["signatures"][0][0], "0x101300"); - assert_eq!(row["frame"]["frame_view_vtable"], 0x101000); - // Bytes come from the new module. - assert_eq!(row["frame"]["hwnd_for_view_prologue"], "4883ec18"); - // Offsets, the absent marker and colours are carried over as they are. - assert_eq!(row["build"]["toolbar"]["view_layer"], "0x20"); - assert_eq!(row["build"]["toolbar"]["missing"], "0x7fff0000"); - assert_eq!(row["build"]["toolbar"]["colours"][0][1], 2147483648u32); - assert!(row.get("frame_addresses").is_none()); - } - - #[test] - fn nfr3_an_address_with_no_new_place_stops_the_row() { - let code = new_code(); - let places: Vec<_> = NEW_PLACES - .iter() - .filter(|(prior, _)| *prior != 0x200300) - .copied() - .collect(); - let (_, report) = port(&prior(), &places, &code_refs(&code), "1.0.0.2"); - assert!( - report - .review - .iter() - .any(|line| line.contains("no new place")), - "{:?}", - report.review - ); - } - - #[test] - fn nfr6_a_command_id_is_not_a_row_value() { - let mut prior = prior(); - prior["build"]["browser"] = json!("Google Chrome"); - prior["frame"]["version"] = json!("157.0.8103.39"); - // A wrong prior value shows that the new row does not copy it. - prior["build"]["toolbar"]["dev"] = json!({"inspect": 1, "console": 2, "colours": []}); - let code = new_code(); - let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "158.0.8127.36"); - assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 40023); - assert_eq!(row["build"]["toolbar"]["dev"]["console"], 40005); - assert!( - !report - .carried - .iter() - .any(|path| path.starts_with("toolbar.dev.inspect") - || path.starts_with("toolbar.dev.console")), - "{:?}", - report.carried - ); - let milestone = report - .review - .iter() - .find(|line| line.contains("milestone")) - .expect("the other values still cross the milestone"); - assert!(!milestone.contains("toolbar.dev.console"), "{milestone}"); - // A milestone whose header was not read offers no command rather than the prior one. - let (row, _) = port(&prior, NEW_PLACES, &code_refs(&code), "199.0.1.1"); - assert_eq!(row["build"]["toolbar"]["dev"]["inspect"], 0); - // A row that never offered the developer bar keeps offering none. - prior["build"]["toolbar"]["dev"] = json!({"inspect": 0, "console": 0, "colours": []}); - let (row, _) = port(&prior, NEW_PLACES, &code_refs(&code), "158.0.8127.36"); - assert_eq!(row["build"]["toolbar"]["dev"]["console"], 0); - } - - /// A prior row whose values that are not addresses all belong to features the runtime can do - /// without, or are not read in this row. - fn prior_with_features() -> Value { - let mut prior = prior(); - let toolbar = prior["build"]["toolbar"].as_object_mut().unwrap(); - toolbar.remove("view_layer"); - toolbar.remove("colours"); - toolbar.insert( - "dev".to_owned(), - json!({"colours": [[321, 4280953905u32], [1597, 0]]}), - ); - prior["build"]["split"] = json!({"supported": true, "outline_member": "0x40"}); - prior["build"]["omnibox"] = json!({"match_size": "0x820"}); - prior["build"]["tabs"]["tab_at"] = json!("0x200300"); - prior["build"]["tabs"]["tab_collection"] = json!("0x30"); - prior - } - - #[test] - fn nfr6_a_feature_with_an_unread_value_is_off_for_that_build() { - let code = new_code(); - let (row, report) = port( - &prior_with_features(), - NEW_PLACES, - &code_refs(&code), - "2.0.0.1", - ); - // Nothing holds the rest of the row back. - assert_eq!(report.review, Vec::::new()); - assert!(report.carried.is_empty(), "{:?}", report.carried); - let build = &row["build"]; - // Each feature with a value of the prior build is off, and the value is gone. - assert_eq!(build["split"]["supported"], false); - assert_eq!(build["split"]["outline_member"], "0x0"); - assert!(build["omnibox"].is_null()); - assert_eq!(build["toolbar"]["dev"]["colours"], json!([])); - let off: Vec<&str> = row[crate::row_features::SWITCHED_OFF] - .as_array() - .unwrap() - .iter() - .map(|entry| entry["feature"].as_str().unwrap()) - .collect(); - assert_eq!( - off, - ["address suggestions", "developer colours", "split view"] - ); - assert_eq!(report.switched_off.len(), 3, "{:?}", report.switched_off); - // A value this build does not use is written as zero, and no feature goes off for it. - assert_eq!(build["tabs"]["tab_collection"], "0x0"); - assert_eq!(report.unused.len(), 1, "{:?}", report.unused); - // The addresses of the row still move to the new build. - assert_eq!(build["tabs"]["tab_at"], "0x101300"); - } - - #[test] - fn nfr6_a_row_without_window_offsets_is_not_blocked() { - // Edge 157's row stopped on values like these. The runtime finds them by class name and the - // view tree, so the new row leaves them out and nothing holds it back. - let mut prior = prior_with_features(); - prior["build"]["layout"] = json!({"frame_browser_window_offset": "0x3b0"}); - prior["build"]["toolbar"]["get_widget_slot"] = json!("0xa"); - let code = new_code(); - let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "2.0.0.1"); - assert_eq!(report.review, Vec::::new()); - assert!(report.carried.is_empty(), "{:?}", report.carried); - assert_eq!(report.reflected.len(), 2, "{:?}", report.reflected); - let build = &row["build"]; - assert!(build["layout"].get("frame_browser_window_offset").is_none()); - assert!(build["toolbar"].get("get_widget_slot").is_none()); - // No feature went off for them. - assert!(!report - .switched_off - .iter() - .any(|line| line.contains("frame_browser_window_offset") - || line.contains("get_widget_slot"))); - } - - #[test] - fn nfr6_a_value_the_window_cannot_do_without_still_stops_the_row() { - let mut prior = prior_with_features(); - prior["build"]["layout"] = json!({"view_bounds_offset": "0x1c8"}); - let code = new_code(); - let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "2.0.0.1"); - assert_eq!(report.carried, ["layout.view_bounds_offset"]); - assert!( - report.review.iter().any(|line| line.contains("milestone") - && line.ends_with("carried over unchecked: layout.view_bounds_offset")), - "{:?}", - report.review - ); - // The features it could do without are still off. - assert_eq!(row["build"]["split"]["supported"], false); - } - - #[test] - fn nfr6_a_row_within_its_milestone_turns_nothing_off() { - let code = new_code(); - let (row, report) = port( - &prior_with_features(), - NEW_PLACES, - &code_refs(&code), - "1.0.0.2", - ); - assert_eq!(report.review, Vec::::new()); - assert!(report.switched_off.is_empty()); - assert_eq!(row["build"]["split"]["supported"], true); - assert!(row.get(crate::row_features::SWITCHED_OFF).is_none()); - } - - #[test] - fn nfr3_a_row_that_crosses_a_milestone_stops_for_review() { - let code = new_code(); - let (_, report) = port(&prior(), NEW_PLACES, &code_refs(&code), "2.0.0.1"); - assert!( - report.review.iter().any(|line| line.contains("milestone")), - "{:?}", - report.review - ); - } - - #[test] - fn nfr3_a_frame_slot_that_no_longer_holds_its_function_stops_the_row() { - let code: Vec<_> = new_code() - .into_iter() - .filter(|(rva, _)| *rva != 0x101008) - .collect(); - let (_, report) = port(&prior(), NEW_PLACES, &code_refs(&code), "1.0.0.2"); - assert!( - report - .review - .iter() - .any(|line| line.contains("does not hold")), - "{:?}", - report.review - ); - } - - #[test] - fn nfr3_a_guard_a_hook_copies_stops_on_an_instruction_in_the_new_build() { - let mut prior = prior(); - // Fifteen bytes that end on an instruction, and a new start where byte fifteen splits one. - prior["build"]["toolbar"]["paint_prologue"] = json!("41574156565755534881ecb8000000"); - let mut code = new_code(); - code[2].1 = hex("4156565755534881eca00000004889ce0000").unwrap(); - let (row, report) = port(&prior, NEW_PLACES, &code_refs(&code), "1.0.0.2"); - assert_eq!( - row["build"]["toolbar"]["paint_prologue"], - "4156565755534881eca0000000" - ); - assert!(report.review.is_empty(), "{:?}", report.review); - } - - #[test] - fn nfr3_addresses_are_told_from_offsets_and_the_absent_marker() { - let row = json!({"a": "0x10", "b": "0xfffff", "c": "0x100000", "d": ["0x7fff0000", "0x4fb01f0"], "e": 1234567, "f": "0xabcd_not"}); - assert_eq!(addresses_of(&row), BTreeSet::from([0x100000, 0x4fb01f0])); - } - - #[test] - fn nfr3_x64_lengths_of_real_function_starts() { - // Chrome 156.0.8078.74 chip text: the frame setup ends at byte 13. - let chip = hex("4156565755534881eca00000004889").unwrap(); - let mut padded = chip.clone(); - padded.resize(40, 0x90); - let (seen, complete) = x64::boundaries(&padded, 15); - assert!(complete); - assert_eq!(&seen[..6], [2, 3, 4, 5, 6, 13]); - assert!(!seen.contains(&15)); - // A stack cookie load is RIP-relative. - let cookie = hex("56574883ec784889ce488b0510640810").unwrap(); - let (seen, _) = x64::boundaries(&cookie, cookie.len()); - assert_eq!(seen.last(), Some(&16)); - assert_eq!(x64::has_relative(&cookie), Some(true)); - assert_eq!(x64::has_relative(&hex("4883ec28").unwrap()), Some(false)); - // Rounded corners: movss, ucomiss with a displacement, jne. - let corners = hex("f30f10020f2e81840400007533").unwrap(); - assert_eq!(x64::boundaries(&corners, 13).0, [4, 11, 13]); - } - - #[test] - fn nfr3_only_the_displacement_differs_between_two_builds_of_a_function() { - let old = hex("5657534883ec5089ce488b0510f0450d").unwrap(); - let new = hex("5657534883ec5089ce488b0590a5330d").unwrap(); - assert_ne!(old, new); - assert_eq!(x64::shape(&old), x64::shape(&new)); - let other = hex("415741565657534883ec4089d34889ce").unwrap(); - assert_ne!(x64::shape(&old), x64::shape(&other)); - } - - #[test] - fn nfr3_guards_are_judged_by_what_a_hook_can_do_with_them() { - let kind = |text| guard_kind(&hex(text).unwrap()); - // Twelve plain bytes, and a frame setup ending in the stack cookie load that hooks relocate. - assert_eq!(kind("415741564155415456575553"), GuardKind::Copyable); - assert_eq!( - kind("5657534883ec5089ce488b0510f0450d"), - GuardKind::Copyable - ); - // Cut inside an instruction, or too short for the jump: only ever compared. - assert_eq!(kind("565755534883ec584889ce48"), GuardKind::Compared); - assert_eq!(kind("4883ec28488b"), GuardKind::Compared); - assert_eq!(kind("564883ec20e8"), GuardKind::Compared); - // A cookie load with more after it, which a row counts bytes to. - assert_eq!(kind("488b0510f0450d4889442420"), GuardKind::Fixed); - } - - #[test] - fn nfr3_an_unknown_instruction_is_not_guessed() { - assert_eq!(x64::decode(&[0x0F, 0x05]), None); - assert_eq!(x64::boundaries(&[0x56, 0xCF, 0x90], 3), (vec![1], false)); - assert_eq!(x64::shape(&[0x56, 0xCF]), None); - } - - #[test] - fn nfr6_the_operands_of_a_body_instruction_are_located() { - // mov rax, [rcx + 0x558]: a displacement of four bytes from the third byte. - let load = x64::decode(&[0x48, 0x8B, 0x81, 0x58, 0x05, 0x00, 0x00]).unwrap(); - assert_eq!(load.displacement, Some((3, 4))); - assert_eq!(load.immediate, None); - // call [rax + 0x2b8]: a table slot read through its displacement. - let call = x64::decode(&[0xFF, 0x90, 0xB8, 0x02, 0x00, 0x00]).unwrap(); - assert_eq!(call.displacement, Some((2, 4))); - // mov edx, 0x9c45, and cmp byte [rcx + 0x30], 1. - let id = x64::decode(&[0xBA, 0x45, 0x9C, 0x00, 0x00]).unwrap(); - assert_eq!(id.immediate, Some((1, 4))); - let compare = x64::decode(&[0x80, 0x79, 0x30, 0x01]).unwrap(); - assert_eq!(compare.displacement, Some((2, 1))); - assert_eq!(compare.immediate, Some((3, 1))); - // lock cmpxchg and a VEX move decode only as body instructions. - let lock = [0xF0, 0x48, 0x0F, 0xB1, 0x51, 0x08]; - assert_eq!(x64::decode(&lock), None); - assert_eq!(x64::decode_body(&lock).unwrap().displacement, Some((5, 1))); - let vex = [0xC5, 0xF8, 0x10, 0x41, 0x10]; - assert_eq!(x64::decode_body(&vex).unwrap().length, 5); - assert_eq!( - x64::skeleton(&[0x48, 0x8B, 0x81, 0x58, 0x05, 0x00, 0x00], &load), - [0x48, 0x8B, 0x81, 0, 0, 0, 0] - ); - } - - /// A verified row whose functions sit at 0x101000 in its module. - fn verified_row() -> Value { - json!({ - "frame": { - "browser": "B", "version": "1.0.0.2", "module": "b.dll", - "frame_view_vtable": 0x101000, "client_view_slot": 1, "client_view_bounds": 0x101100, - "hwnd_for_view": 0x101200, "hwnd_for_view_prologue": "4883ec28", - }, - "build": { - "browser": "B", "module": "b.dll", "version": [1, 0, 0, 2], - "toolbar": { - "paint": "0x101300", "paint_prologue": "415741564155415456575553", - "view_layer": "0x20", "missing": "0x7fff0000", - }, - "tabs": {"signatures": [["0x101300", "41574156"]]}, - }, - }) - } - - /// The same functions `shift` bytes further on, with `displacement` in every RIP-relative - /// field, as the next build of a milestone lays them out. - fn shifted_code(shift: u32, displacement: u8) -> Vec<(u32, Vec)> { - let d = format!("{displacement:02x}"); - vec![ - (0x101008 + shift, pointer(0x101100 + shift).to_vec()), - // mov [rsp+8],rbx; push rdi; sub rsp,20h; mov rax,[rip+d]; xor rax,rsp - ( - 0x101100 + shift, - hex(&format!("48895c2408574883ec20488b05{d}0000004833c4")).unwrap(), - ), - // sub rsp,28h; mov rcx,[rip+d]; call rel32 - ( - 0x101200 + shift, - hex(&format!("4883ec28488b0d{d}000000e8{d}000000")).unwrap(), - ), - // push r15..rbx; sub rsp,0a0h - ( - 0x101300 + shift, - hex("4157415641554154565755534881eca0000000").unwrap(), - ), - ] - } - - fn fingerprinted() -> Value { - let bytes = module(&code_refs(&shifted_code(0, 0x10))); - let pe = PeFile::parse(&bytes).unwrap(); - let mut row = verified_row(); - add_fingerprints(&mut row, &pe).unwrap(); - row - } - - fn no_classes() -> BTreeMap { - BTreeMap::new() - } - - fn find(row: &Value, code: &[(u32, Vec)], version: &str) -> Result> { - let bytes = module(&code_refs(code)); - let pe = PeFile::parse(&bytes).unwrap(); - find_row(row, version, &pe) - } - - #[test] - fn nfr6_an_unknown_build_takes_the_addresses_its_fingerprints_find() { - let row = fingerprinted(); - assert_eq!(row["fingerprints"]["0x101000"]["slot"], 1); - assert_eq!(row["fingerprints"]["0x101000"]["holds"], "0x101100"); - let found = find(&row, &shifted_code(0x2000, 0x44), "1.0.0.3").unwrap(); - assert_eq!(found["build"]["toolbar"]["paint"], "0x103300"); - assert_eq!(found["build"]["tabs"]["signatures"][0][0], "0x103300"); - assert_eq!(found["frame"]["frame_view_vtable"], 0x103000); - assert_eq!(found["frame"]["client_view_bounds"], 0x103100); - assert_eq!(found["frame"]["hwnd_for_view"], 0x103200); - assert_eq!(found["frame"]["version"], "1.0.0.3"); - assert_eq!(found["build"]["version"], json!([1, 0, 0, 3])); - // Values that are not addresses stay, and the prior build's fingerprints do not. - assert_eq!(found["build"]["toolbar"]["view_layer"], "0x20"); - assert!(found.get("fingerprints").is_none()); - assert!(found.get("frame_addresses").is_none()); - } - - #[test] - fn nfr6_a_fingerprint_that_matches_two_places_changes_nothing() { - let mut code = shifted_code(0x2000, 0x44); - code.push(( - 0x105300, - hex("4157415641554154565755534881eca0000000").unwrap(), - )); - let reasons = find(&fingerprinted(), &code, "1.0.0.3").unwrap_err(); - assert!( - reasons - .iter() - .any(|line| line.contains("0x101300 matches 2 places")), - "{reasons:?}" - ); - } - - #[test] - fn nfr6_a_changed_function_start_changes_nothing() { - let mut code = shifted_code(0x2000, 0x44); - // push r15; push r14; push r13; push rbp (was push r12) ... - code[3].1 = hex("4157415641555556575553904881eca0000000").unwrap(); - let reasons = find(&fingerprinted(), &code, "1.0.0.3").unwrap_err(); - assert!( - reasons - .iter() - .any(|line| line.contains("0x101300 matches no place")), - "{reasons:?}" - ); - } - - #[test] - fn nfr6_a_table_that_no_longer_holds_its_function_changes_nothing() { - let code: Vec<_> = shifted_code(0x2000, 0x44) - .into_iter() - .filter(|(rva, _)| *rva != 0x103008) - .collect(); - let reasons = find(&fingerprinted(), &code, "1.0.0.3").unwrap_err(); - assert!( - reasons.iter().any(|line| line.contains("0 tables hold")), - "{reasons:?}" - ); - } - - #[test] - fn nfr6_fingerprints_do_not_cross_a_milestone() { - let reasons = find(&fingerprinted(), &shifted_code(0x2000, 0x44), "2.0.0.1").unwrap_err(); - assert!( - reasons.iter().any(|line| line.contains("milestone")), - "{reasons:?}" - ); - } - - #[test] - fn nfr6_a_row_without_fingerprints_finds_nothing() { - let reasons = find(&verified_row(), &shifted_code(0x2000, 0x44), "1.0.0.3").unwrap_err(); - assert_eq!(reasons, ["the row has no fingerprints"]); - } - - /// The fingerprints of the verified row, read from its own module as the row job reads them - /// when the prior row stored none. - fn prints_of_prior() -> serde_json::Map { - let bytes = module(&code_refs(&shifted_code(0, 0x10))); - let pe = PeFile::parse(&bytes).unwrap(); - let (prints, missing) = fingerprints_of(&verified_row(), &pe); - assert!(missing.is_empty(), "{missing:?}"); - prints - } - - fn candidate( - prints: &serde_json::Map, - code: &[(u32, Vec)], - version: &str, - ) -> (Value, PortReport) { - let bytes = module(&code_refs(code)); - let pe = PeFile::parse(&bytes).unwrap(); - find_candidate( - &verified_row(), - prints, - None, - &BTreeMap::new(), - version, - &pe, - ) - } - - /// `module` with an exception table at 0x10f000 that lists `starts`. - fn with_starts(code: &[(u32, Vec)], starts: &[u32]) -> Vec { - let ranges: Vec<(u32, u32)> = starts.iter().map(|start| (*start, start + 0x20)).collect(); - with_ranges(code, &ranges) - } - - /// `module` with an exception table at 0x10f000 that lists each `(start, end)`. - fn with_ranges(code: &[(u32, Vec)], ranges: &[(u32, u32)]) -> Vec { - let mut table = vec![]; - for (start, end) in ranges { - table.extend_from_slice(&start.to_le_bytes()); - table.extend_from_slice(&end.to_le_bytes()); - table.extend_from_slice(&0u32.to_le_bytes()); - } - let mut code = code.to_vec(); - code.push((0x10f000, table)); - let mut bytes = module(&code_refs(&code)); - let directory = 0x98 + 112 + 24; - bytes[directory..directory + 4].copy_from_slice(&0x10f000u32.to_le_bytes()); - bytes[directory + 4..directory + 8] - .copy_from_slice(&(12 * ranges.len() as u32).to_le_bytes()); - bytes - } - - /// The verified row's paint function, which reads `view_layer` with `loads` past the bytes its - /// fingerprint holds. - fn paint_reading(loads: &str) -> Vec { - let mut bytes = hex("4157415641554154565755534881eca0000000").unwrap(); - bytes.resize(32, 0x90); - bytes.extend(hex(loads).unwrap()); - bytes.push(0xC3); - bytes - } - - /// A candidate row for a build whose paint function reads `view_layer` with `new_loads`, made - /// from the verified row and its build, whose paint function reads it with `prior_loads`. - fn read_view_layer(prior_loads: &str, new_loads: &str) -> (Value, PortReport) { - let ranges = |shift: u32, paint: usize| { - vec![ - (0x101100 + shift, 0x101120 + shift), - (0x101200 + shift, 0x101220 + shift), - (0x101300 + shift, 0x101300 + shift + paint as u32), - ] - }; - let mut old = shifted_code(0, 0x10); - old[3].1 = paint_reading(prior_loads); - let prior_bytes = with_ranges(&old, &ranges(0, old[3].1.len())); - let prior_pe = PeFile::parse(&prior_bytes).unwrap(); - let (prints, missing) = fingerprints_of(&verified_row(), &prior_pe); - assert!(missing.is_empty(), "{missing:?}"); - let mut new = shifted_code(0x2000, 0x44); - new[3].1 = paint_reading(new_loads); - let bytes = with_ranges(&new, &ranges(0x2000, new[3].1.len())); - let pe = PeFile::parse(&bytes).unwrap(); - let classes = BTreeMap::new(); - find_candidate( - &verified_row(), - &prints, - Some(&prior_pe), - &classes, - "1.0.0.3", - &pe, - ) - } - - #[test] - fn nfr6_a_carried_value_is_read_from_the_instructions_that_use_it() { - // mov rax, [rcx + 0x20]; mov rdx, [rcx + 0x20], and the new build moved the member to 0x28. - let (row, report) = read_view_layer( - "488b8120000000488b9120000000", - "488b8128000000488b9128000000", - ); - assert!(report.review.is_empty(), "{:?}", report.review); - assert_eq!(row["build"]["toolbar"]["view_layer"], "0x28"); - assert!(report.carried.is_empty(), "{:?}", report.carried); - assert_eq!( - report.derived, - ["toolbar.view_layer: 0x20 -> 0x28, read at 2 uses in 1 of its functions"] - ); - } - - #[test] - fn nfr6_a_value_no_instruction_gives_stops_the_row() { - // The new build reads the member with a short displacement: not the same instruction. - let (_, report) = read_view_layer("488b8120000000488b9120000000", "488b4128488b5128"); - assert_eq!(report.carried, ["toolbar.view_layer"]); - assert!(report.derived.is_empty(), "{:?}", report.derived); - assert!( - report.review.iter().any(|line| line - .starts_with("toolbar.view_layer was not read from the new build: its 2 uses")), - "{:?}", - report.review - ); - // One use alone is not read either, and neither are uses that disagree. - let (_, report) = read_view_layer("488b8120000000", "488b8128000000"); - assert!( - report - .review - .iter() - .any(|line| line.contains("a second reading is needed")), - "{:?}", - report.review - ); - let (_, report) = read_view_layer( - "488b8120000000488b9120000000", - "488b8128000000488b9130000000", - ); - assert!( - report - .review - .iter() - .any(|line| line.contains("its uses disagree")), - "{:?}", - report.review - ); - } - - #[test] - fn nfr6_a_function_start_is_found_only_at_a_function_start() { - // The paint function's first bytes also open a block inside another function at 0x105300. - let mut code = shifted_code(0x2000, 0x44); - code.push(( - 0x105300, - hex("4157415641554154565755534881eca0000000").unwrap(), - )); - let prior_bytes = with_starts(&shifted_code(0, 0x10), &[0x101100, 0x101200, 0x101300]); - let prior_pe = PeFile::parse(&prior_bytes).unwrap(); - let prior_starts = prior_pe.function_starts(); - assert_eq!(prior_starts.len(), 3); - // The row holds no value without a recipe, so only its addresses are looked for. - let mut verified = verified_row(); - verified["build"]["toolbar"] - .as_object_mut() - .unwrap() - .remove("view_layer"); - let (prints, _) = fingerprints_of(&verified, &prior_pe); - let bytes = with_starts(&code, &[0x103100, 0x103200, 0x103300]); - let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = find_candidate( - &verified, - &prints, - Some(&prior_pe), - &no_classes(), - "1.0.0.3", - &pe, - ); - assert!(report.review.is_empty(), "{:?}", report.review); - assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); - // A part moved out of another function starts where it may, and a whole function does not. - let mut split = shifted_code(0x2000, 0x44); - split.push(( - 0x105308, - hex("4157415641554154565755534881eca0000000").unwrap(), - )); - let bytes = with_starts(&split, &[0x103100, 0x103200, 0x103300, 0x105308]); - let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = find_candidate( - &verified, - &prints, - Some(&prior_pe), - &no_classes(), - "1.0.0.3", - &pe, - ); - assert!(report.review.is_empty(), "{:?}", report.review); - assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); - // Bytes that match only inside another function are no place at all. - let bytes = with_starts(&code, &[0x103100, 0x103200]); - let pe = PeFile::parse(&bytes).unwrap(); - let (_, report) = find_candidate( - &verified, - &prints, - Some(&prior_pe), - &no_classes(), - "1.0.0.3", - &pe, - ); - assert!( - report.review.iter().any(|line| line - .starts_with("0x101300 matches no function start, of 2 places; not settled:")), - "{:?}", - report.review - ); - } - - #[test] - fn nfr6_a_new_build_gets_a_row_from_the_prior_rows_fingerprints_alone() { - let (row, report) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); - assert!(report.review.is_empty(), "{:?}", report.review); - assert_eq!(report.fingerprinted.len(), 4, "{:?}", report.fingerprinted); - assert_eq!(row["build"]["toolbar"]["paint"], "0x103300"); - assert_eq!(row["frame"]["frame_view_vtable"], 0x103000); - assert_eq!(row["frame"]["hwnd_for_view"], 0x103200); - // Values that are not addresses are left to the recipes, and nothing of the prior build stays. - assert_eq!(row["build"]["toolbar"]["view_layer"], "0x20"); - assert!(row.get("fingerprints").is_none()); - } - - #[test] - fn nfr6_an_address_its_fingerprint_does_not_pin_down_is_not_vouched_for() { - // Two places match the paint function: that part keeps its prior value and stops the row, - // and the rest of the row is still found. - let mut code = shifted_code(0x2000, 0x44); - code.push(( - 0x105300, - hex("4157415641554154565755534881eca0000000").unwrap(), - )); - let (row, report) = candidate(&prints_of_prior(), &code, "1.0.0.3"); - assert!( - report - .review - .iter() - .any(|line| line.contains("0x101300 matches 2 places")), - "{:?}", - report.review - ); - assert!(report - .review - .iter() - .any(|line| line.contains("no new place"))); - assert_eq!(row["build"]["toolbar"]["paint"], "0x101300"); - assert_eq!(row["frame"]["hwnd_for_view"], 0x103200); - // An address the prior build gave no fingerprint is not looked for at all. - let mut prints = prints_of_prior(); - prints.remove("0x101200"); - let (_, report) = candidate(&prints, &shifted_code(0x2000, 0x44), "1.0.0.3"); - assert!( - report - .review - .iter() - .any(|line| line == "0x101200: no fingerprint"), - "{:?}", - report.review - ); - } - - #[test] - fn nfr6_unplaced_functions_of_a_feature_that_is_off_do_not_block_the_row() { - // Edge 157's row stopped on functions no method placed, most of which only features the - // runtime can do without hold. The prior build gave this one no fingerprint. - let mut prior = verified_row(); - prior["build"]["split"] = json!({ - "supported": true, - "remove_split": "0x101400", - "remove_split_prologue": "4883ec28488b0d10000000", - "signatures": [["0x101400", "4883ec28"]], - }); - let bytes = module(&code_refs(&shifted_code(0x2000, 0x44))); - let pe = PeFile::parse(&bytes).unwrap(); - let prints = prints_of_prior(); - let (row, report) = find_candidate(&prior, &prints, None, &no_classes(), "1.0.0.3", &pe); - assert_eq!(report.review, Vec::::new()); - assert_eq!(report.unplaced.len(), 1, "{:?}", report.unplaced); - assert!(report.unplaced[0].starts_with("0x101400: no fingerprint")); - assert!(report.unplaced[0].ends_with("split.remove_split, split.signatures[0][0]")); - let build = &row["build"]; - // The feature is off and holds nothing of the prior build. - assert_eq!(build["split"]["supported"], false); - assert_eq!(build["split"]["remove_split"], "0x0"); - assert_eq!(build["split"]["signatures"][0][0], "0x0"); - assert_eq!( - row[crate::row_features::SWITCHED_OFF][0]["feature"], - "split view" - ); - assert!( - report.switched_off[0] - .starts_with("split view is off: split.remove_split has no place"), - "{:?}", - report.switched_off - ); - assert_eq!(report.switched_off.len(), 1, "{:?}", report.switched_off); - // The rest of the row is found. - assert_eq!(build["toolbar"]["paint"], "0x103300"); - - // The same address held by a part the window cannot do without still stops the row. - prior["build"]["layout"] = json!({"frame_vtable": "0x101400"}); - let prints = prints_of_prior(); - let (row, report) = find_candidate(&prior, &prints, None, &no_classes(), "1.0.0.3", &pe); - assert!( - report - .review - .iter() - .any(|line| line == "0x101400: no fingerprint"), - "{:?}", - report.review - ); - assert!(report - .unplaced - .iter() - .all(|line| !line.contains("0x101400"))); - assert_eq!(row["build"]["split"]["supported"], true); - } - - #[test] - fn nfr3_an_address_that_is_neither_code_nor_a_table_gets_no_fingerprints() { - let bytes = module(&code_refs(&shifted_code(0, 0x10))); - let pe = PeFile::parse(&bytes).unwrap(); - let mut row = verified_row(); - // Inside the code section's range but past what the file holds. - row["build"]["toolbar"]["state"] = json!("0x1f0000"); - let error = add_fingerprints(&mut row, &pe).unwrap_err(); - assert!(error.contains("0x1f0000"), "{error}"); - assert!(row.get("fingerprints").is_none()); - } - - #[test] - fn nfr3_a_prior_row_without_screen_origin_gives_a_row_without_it() { - let mut row = prior(); - let mut report = PortReport::default(); - leave_out_screen_origin(&mut row, &mut report); - assert!(row["build"]["screen_origin"].is_null()); - assert_eq!(report.left_out.len(), 1); - assert!(report.review.is_empty()); - // A row that has it keeps the place it was found at. - row["build"]["screen_origin"] = json!(["0x101400", "5657"]); - leave_out_screen_origin(&mut row, &mut report); - assert_eq!(row["build"]["screen_origin"][0], "0x101400"); - } - - #[test] - fn nfr6_a_new_row_records_the_class_names_of_the_tables_it_placed() { - let mut prior = verified_row(); - // A name the prior row recorded is not carried: only names confirmed now are written. - prior[CLASSES] = json!({"build.toolbar.stale": "Stale"}); - let classes = BTreeMap::from([(0x101000, "BrowserFrameViewWin".to_owned())]); - let bytes = module(&code_refs(&shifted_code(0x2000, 0x44))); - let pe = PeFile::parse(&bytes).unwrap(); - let (row, report) = - find_candidate(&prior, &prints_of_prior(), None, &classes, "1.0.0.3", &pe); - assert!(report.review.is_empty(), "{:?}", report.review); - assert_eq!( - row[CLASSES], - json!({"frame.frame_view_vtable": "BrowserFrameViewWin"}) - ); - // With no confirmed name the row records none. - let (row, _) = find_candidate( - &prior, - &prints_of_prior(), - None, - &BTreeMap::new(), - "1.0.0.3", - &pe, - ); - assert!(row.get(CLASSES).is_none()); - } - - #[test] - fn nfr6_every_address_of_a_row_is_known_by_its_path() { - let paths = address_paths(&verified_row()); - assert!(paths.contains(&("frame.frame_view_vtable".to_owned(), 0x101000))); - assert!(paths.contains(&("build.toolbar.paint".to_owned(), 0x101300))); - assert!(paths.contains(&("build.tabs.signatures[0][0]".to_owned(), 0x101300))); - // Offsets and the absent marker are not addresses. - assert!(!paths.iter().any(|(path, _)| path.ends_with("view_layer"))); - assert!(!paths.iter().any(|(path, _)| path.ends_with("missing"))); - } - - #[test] - fn nfr6_a_made_row_is_scored_value_by_value_against_the_verified_row() { - let (made, report) = candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); - let mut verified = made.clone(); - let score = score_row(&made, &report, &verified, &json!({})); - assert_eq!(score.wrong(), 0); - assert!(score.features[WINDOW].equal > 0); - // A value found at another place than the verified one is wrong. - verified["build"]["toolbar"]["paint"] = json!("0x103310"); - let score = score_row(&made, &report, &verified, &json!({})); - assert_eq!(score.wrong(), 1, "{:?}", score.features); - let wrong: Vec<&String> = score.features.values().flat_map(|f| &f.different).collect(); - assert!( - wrong[0].starts_with("build.toolbar.paint: made"), - "{wrong:?}" - ); - // A value a review line reports as unplaced is not found, not wrong. - let (_, mut stopped) = - candidate(&prints_of_prior(), &shifted_code(0x2000, 0x44), "1.0.0.3"); - stopped - .review - .push("no new place for .toolbar.paint 0x101300".into()); - let score = score_row(&made, &stopped, &verified, &json!({})); - assert_eq!(score.wrong(), 0, "{:?}", score.features); - assert_eq!(score.features[WINDOW].not_found, ["build.toolbar.paint"]); - // Bytes read at that address are not found either. - let mut bytes = verified.clone(); - bytes["build"]["toolbar"]["paint_prologue"] = json!("4883ec28"); - let mut read = made.clone(); - read["build"]["toolbar"]["paint_prologue"] = json!("cccccccc"); - let score = score_row(&read, &stopped, &bytes, &json!({})); - assert_eq!(score.wrong(), 0, "{:?}", score.features); - // A value kept from the prior row is wrong only when nothing stops the row. - let mut kept = verified.clone(); - kept["build"]["toolbar"]["paint"] = made["build"]["toolbar"]["paint"].clone(); - kept["build"]["toolbar"]["slot"] = json!(7); - let mut carried = made.clone(); - carried["build"]["toolbar"]["slot"] = json!(8); - let before = json!({"build": {"toolbar": {"slot": 8}}}); - assert_eq!(score_row(&carried, &report, &kept, &before).wrong(), 1); - assert_eq!(score_row(&carried, &stopped, &kept, &before).wrong(), 0); - // A value the made row does not hold is not wrong. - let mut made_less = made.clone(); - made_less["build"]["toolbar"] - .as_object_mut() - .unwrap() - .remove("paint"); - let score = score_row(&made_less, &report, &verified, &json!({})); - assert_eq!(score.wrong(), 0); - // A feature the made row turns off is not compared at all. - let mut off = made.clone(); - off[crate::row_features::SWITCHED_OFF] = json!([{"feature": "split view", "values": []}]); - let mut split = verified.clone(); - split["build"]["split"] = json!({"supported": true, "outline_member": "0x40"}); - off["build"]["split"] = json!({"supported": false, "outline_member": "0x0"}); - let score = score_row(&off, &report, &split, &json!({})); - assert!(score.features["split view"].off); - assert!(score.features["split view"].different.is_empty()); - } -} diff --git a/rivet/platform/windows/src/row_recipe.rs b/rivet/platform/windows/src/row_recipe.rs index 17fda5c..3721144 100644 --- a/rivet/platform/windows/src/row_recipe.rs +++ b/rivet/platform/windows/src/row_recipe.rs @@ -9,15 +9,16 @@ //! fails is reported and never guessed, so its row goes to a person and the runtime keeps the //! feature off. //! -//! The recipes read the row's addresses, so they run after the addresses have moved to the new -//! build. Paths are the row's own field names, as the runtime writes the row. +//! The recipes read the row's addresses. Paths are the row's own field names, as the runtime writes +//! the row. The row finder reads the same values with the same readers, `slot_in`, `member_read_by` +//! and `allocation_size`, from addresses it found in the build itself. use std::collections::BTreeSet; use serde_json::{json, Value}; use crate::chrome_build::PeFile; -use crate::row_port::x64; +use crate::x64; /// The lowest value taken for an address. Offsets and slots lie below it. const LOWEST_ADDRESS: u64 = 0x10_0000; @@ -53,8 +54,7 @@ pub struct Field { pub recipes: &'static [Recipe], } -/// Every value of a row that has a recipe. A value of a row that is not listed here is carried over -/// from the prior row, and the port reports it as such. +/// Every value of a row that has a recipe. pub const FIELDS: &[Field] = &[ Field { path: "tabs.browser_in_view", @@ -209,6 +209,61 @@ fn allocation_sizes(pe: &PeFile, constructor: u32) -> (BTreeSet, usize) { (sizes, calls) } +/// The slot of the function at `target` in the class table at `table`, named `vtable` and +/// `function` in a reason. Its check: every slot up to it points at code, so the slot lies inside +/// one table. +pub fn slot_in( + pe: &PeFile, + (vtable, table): (&str, u32), + (function, target): (&str, u32), +) -> Result { + let slot = (0..TABLE_SLOTS) + .find(|slot| pe.pointer_rva(table + slot * 8) == Some(target)) + .ok_or_else(|| format!("{vtable} {table:#x} holds no {function} {target:#x}"))?; + let inside = (0..=slot).all(|slot| { + pe.pointer_rva(table + slot * 8) + .is_some_and(|entry| pe.is_code(entry)) + }); + if !inside { + return Err(format!( + "slot {slot} of {vtable} {table:#x} lies past the end of its table" + )); + } + Ok(u64::from(slot)) +} + +/// The member the accessor at `target`, named `function` in a reason, reads from `this` with its +/// first instruction. +pub fn member_read_by(pe: &PeFile, (function, target): (&str, u32)) -> Result { + let bytes = pe + .read(target, 8) + .ok_or_else(|| format!("{function} {target:#x} lies outside the module"))?; + first_load(bytes).ok_or_else(|| { + format!( + "{function} {target:#x} does not start by reading a member of this: {}", + bytes + .iter() + .map(|byte| format!("{byte:02x}")) + .collect::() + ) + }) +} + +/// The one size every direct caller of the constructor at `target`, named `constructor` in a +/// reason, allocates its object with. +pub fn allocation_size(pe: &PeFile, (constructor, target): (&str, u32)) -> Result { + let (sizes, calls) = allocation_sizes(pe, target); + let found: Vec = sizes.into_iter().collect(); + match found.as_slice() { + [size] if *size % 8 == 0 && *size >= 0x40 => Ok(*size), + [size] => Err(format!("{constructor} is allocated with {size:#x}, which no object has")), + [] => Err(format!( + "none of the {calls} direct callers of {constructor} {target:#x} allocates with a constant size" + )), + many => Err(format!("the callers of {constructor} allocate {many:#x?}")), + } +} + /// Runs one recipe: `Ok(None)` when the row lacks the addresses it reads. fn run(recipe: &Recipe, build: &Value, pe: &PeFile) -> Result, String> { match *recipe { @@ -217,51 +272,19 @@ fn run(recipe: &Recipe, build: &Value, pe: &PeFile) -> Result, Strin else { return Ok(None); }; - let slot = (0..TABLE_SLOTS) - .find(|slot| pe.pointer_rva(table + slot * 8) == Some(target)) - .ok_or_else(|| format!("{vtable} {table:#x} holds no {function} {target:#x}"))?; - let inside = (0..=slot).all(|slot| { - pe.pointer_rva(table + slot * 8) - .is_some_and(|entry| pe.is_code(entry)) - }); - if !inside { - return Err(format!( - "slot {slot} of {vtable} {table:#x} lies past the end of its table" - )); - } - Ok(Some(u64::from(slot))) + slot_in(pe, (vtable, table), (function, target)).map(Some) } Recipe::FirstLoad { function } => { let Some(target) = address(build, function) else { return Ok(None); }; - let bytes = pe - .read(target, 8) - .ok_or_else(|| format!("{function} {target:#x} lies outside the module"))?; - first_load(bytes).map(Some).ok_or_else(|| { - format!( - "{function} {target:#x} does not start by reading a member of this: {}", - bytes - .iter() - .map(|byte| format!("{byte:02x}")) - .collect::() - ) - }) + member_read_by(pe, (function, target)).map(Some) } Recipe::AllocationSize { constructor } => { let Some(target) = address(build, constructor) else { return Ok(None); }; - let (sizes, calls) = allocation_sizes(pe, target); - let found: Vec = sizes.into_iter().collect(); - match found.as_slice() { - [size] if *size % 8 == 0 && *size >= 0x40 => Ok(Some(*size)), - [size] => Err(format!("{constructor} is allocated with {size:#x}, which no object has")), - [] => Err(format!( - "none of the {calls} direct callers of {constructor} {target:#x} allocates with a constant size" - )), - many => Err(format!("the callers of {constructor} allocate {many:#x?}")), - } + allocation_size(pe, (constructor, target)).map(Some) } } } @@ -326,89 +349,6 @@ pub fn derive_row(build: &mut Value, pe: &PeFile) -> Derived { derived } -/// Values Rivet chooses rather than reads from a build, such as how long it waits before it opens -/// a new tab. The row carries them for the runtime, so they are kept from the prior row. -pub const SETTINGS: &[&str] = &["tabs.new_tab_delay_ms"]; - -/// Lists of `[id, colour]` pairs: the id is a value of the build, and the colour is Rivet's choice. -pub const ID_COLOUR_PAIRS: &[&str] = &["toolbar.dev.colours"]; - -/// The values of a row that are Rivet's settings rather than facts about its build. -pub fn settings(build: &Value) -> Vec { - let mut out: Vec = SETTINGS - .iter() - .filter(|path| number(at_path(build, path)).is_some()) - .map(|path| (*path).to_owned()) - .collect(); - for list in ID_COLOUR_PAIRS { - if let Some(pairs) = at_path(build, list).as_array() { - out.extend((0..pairs.len()).map(|index| format!("{list}[{index}][1]"))); - } - } - out -} - -/// Every number of a row below the address range that no recipe reads: member offsets, slots, -/// sizes, ids and constants that a port can only carry over. Rivet's own settings and Chromium's -/// public command ids are not listed. -pub fn without_recipe(build: &Value) -> Vec { - fn walk(path: &str, value: &Value, out: &mut Vec) { - match value { - Value::Array(items) - if items.len() == 2 - && path - .rsplit_once('[') - .is_some_and(|(list, _)| ID_COLOUR_PAIRS.contains(&list)) => - { - if number(&items[0]).is_some_and(|id| id < LOWEST_ADDRESS) { - out.push(format!("{path}[0]")); - } - } - Value::Object(object) => { - for (key, item) in object { - let next = if path.is_empty() { - key.clone() - } else { - format!("{path}.{key}") - }; - walk(&next, item, out); - } - } - Value::Array(items) => { - // An array of numbers is one value, such as a list of colour ids. - if !items.is_empty() && items.iter().all(|item| number(item).is_some()) { - if items - .iter() - .any(|item| number(item).is_some_and(|value| value < LOWEST_ADDRESS)) - { - out.push(path.to_owned()); - } - return; - } - for (index, item) in items.iter().enumerate() { - walk(&format!("{path}[{index}]"), item, out); - } - } - _ => { - if number(value).is_some_and(|value| value < LOWEST_ADDRESS) { - out.push(path.to_owned()); - } - } - } - } - let mut out = vec![]; - walk("", build, &mut out); - // The version is the build's name, and the fingerprints describe the prior build. - out.retain(|path| { - path != "version" - && !path.starts_with("version[") - && !FIELDS.iter().any(|field| field.path == path) - && !SETTINGS.contains(&path.as_str()) - && !crate::command_ids::ROW_PATHS.contains(&path.as_str()) - }); - out -} - #[cfg(test)] mod tests { use super::*; @@ -582,41 +522,4 @@ mod tests { other => panic!("{other:?}"), } } - - #[test] - fn nfr6_values_with_no_recipe_are_listed_by_path() { - let build = json!({ - "version": [157, 0, 8103, 38], - "tabs": {"browser_in_view": "0x558", "title": "0x00b77780", "groups": true}, - "layout": {"frame_ids": [0x141, 0x142], "view_bounds_offset": "0x1c8"}, - }); - assert_eq!( - without_recipe(&build), - vec!["layout.frame_ids", "layout.view_bounds_offset"] - ); - } - - #[test] - fn nfr6_rivet_settings_are_not_values_of_the_build() { - let build = json!({ - "tabs": {"new_tab_delay_ms": 0, "tab_contents": "0x0"}, - "toolbar": {"dev": {"colours": [[316, 4280953905u32], [2082, 0]], "console": 40005}}, - }); - assert_eq!( - without_recipe(&build), - vec![ - "tabs.tab_contents", - "toolbar.dev.colours[0][0]", - "toolbar.dev.colours[1][0]" - ] - ); - assert_eq!( - settings(&build), - vec![ - "tabs.new_tab_delay_ms", - "toolbar.dev.colours[0][1]", - "toolbar.dev.colours[1][1]" - ] - ); - } } diff --git a/rivet/platform/windows/src/row_resolve.rs b/rivet/platform/windows/src/row_resolve.rs deleted file mode 100644 index 0426b34..0000000 --- a/rivet/platform/windows/src/row_resolve.rs +++ /dev/null @@ -1,2143 +0,0 @@ -//! Finds, in a new build, the functions and class tables that the prior row's fingerprints do not -//! pin down to one place. -//! -//! Each such address is looked for by several independent methods, and a place is taken only when -//! two different methods name the same place and no method names another. The methods read the -//! prior build, whose row a person verified, next to the new build: -//! -//! - calls into it: a function known in both builds calls or loads it from the same spot of its -//! body in both builds; -//! - its calls: in the prior build it calls functions that their own fingerprints find in the new -//! build, and exactly one candidate makes the same calls from the same spots; -//! - its table slot: a class table known in both builds holds it, at the slot that lines up once -//! the slots around it are compared, since a milestone can add or remove a virtual function; -//! - its slot shift: for a virtual function of a views class, the table of a second views class -//! lines the same slot up by the same shift. Every views class derives from `views::View`, whose -//! virtual functions keep one slot in all their tables (`ui/views/view.h`), so a second table -//! confirms the slot number apart from the first; -//! - a text it uses: it refers to a text the new build holds once, and exactly one function there -//! refers to that text; -//! - for a class table, references to it (a function known in both builds loads it from the same -//! spot) and its slots (exactly one candidate holds the same functions in the same slots); -//! - for the class table of a views class, its class name: `row_class` reads the table from the -//! name the class's `ui::metadata` holds, and the same reading must give the prior table in the -//! prior build; -//! - a known caller: a function known in both builds calls it in the prior build, and of the places -//! its fingerprint matched, the caller's new body calls exactly one. Public source tells which -//! function calls which (a frame view's `OnPaint` calls `gfx::Canvas::DrawColor`), and the call -//! is a fact of the caller apart from the fingerprint's bytes, so with the fingerprint it is two -//! methods. Each place a virtual function's table slot settles is a known caller in the next -//! round, so drawing helpers follow the functions they are called from; -//! - its command id: for a function a browser command runs first, the case of the command's public -//! id in the browser's command switch, read by `row_command` the same way in both builds; -//! - its fingerprint: a place a class table or a command id gives that is one of the places the -//! fingerprint matched. Those methods do not search among the fingerprint's places, so the two -//! agree independently. -//! -//! Anything else stays unresolved with its reason, and its row goes to a person. - -use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::fmt; -use std::rc::Rc; - -use crate::chrome_build::PeFile; -use crate::row_port::{code_print, find_prints, find_table, whole_function, x64}; - -/// How many bytes of a function body are read at most. -const BODY_LIMIT: u32 = 0x4000; -/// How far a function the exception table does not list, a leaf, is read at most. -const LEAF_LIMIT: u32 = 0x200; -/// How many instructions before a site name it within its body. -const CONTEXT: usize = 3; -/// How many levels of calls are followed from the functions known in both builds. -const FOLLOW_DEPTH: usize = 3; -/// How many functions are followed at most. -const FOLLOW_LIMIT: usize = 4000; -/// How many slots of a class table are read at most. -const TABLE_SLOTS: u32 = 512; -/// How many slots of a class table are compared to tell one table from another. -/// How many slots a table must share with a known one before the sharing tells anything. -const SIBLING_LEAST: u32 = 8; -const TABLE_SEEN: u32 = 0x80; -/// How many slots on each side of a slot are compared to line two tables up. -const ALIGN_REACH: u32 = 6; -/// How far a milestone may move a slot. -const ALIGN_SHIFT: i64 = 2; -/// How many slots must agree for two tables, or two stretches of them, to be the same. -const ALIGN_LEAST: usize = 3; -/// The shortest text taken as a sign of the function that uses it. -const TEXT_LEAST: usize = 8; -/// The longest text read. -const TEXT_MOST: usize = 256; -/// How many candidates a function with no fingerprint match may have. -const CANDIDATES_MOST: usize = 256; -/// How many times the methods run again with what the last round found. -const ROUNDS: usize = 4; - -/// One instruction of a function body, as far as the methods need it. -#[derive(Debug, Clone)] -pub struct Step { - pub rva: u32, - /// The bytes with the relative value, displacement and immediate cleared. - pub skeleton: Vec, - /// Where a direct call or jump goes. - pub call: Option, - /// What a RIP-relative operand points at: data, a table or a function passed as a callback. - pub reference: Option, - /// A displacement from a register, as `[rcx + 0x558]` holds. - pub displacement: Option, - pub immediate: Option, - /// A call or jump through memory, as `call [rax + 0x2b8]` calls a table slot. - pub indirect: bool, - /// Its operand is the stack: a local variable, or the frame's size. Neither is a value of a row. - pub stack: bool, -} - -/// Whether a memory operand's base is the stack or frame pointer, which hold locals, not members. -fn stack_based(raw: &[u8], displacement: Option<(usize, usize)>) -> bool { - let Some((offset, size)) = displacement else { - return false; - }; - let opcode = opcode_at(raw); - // REX.B names r12 or r13 where the base field says rsp or rbp. - let extended = opcode > 0 && raw[opcode - 1] & 0xF0 == 0x40 && raw[opcode - 1] & 1 != 0; - let mode = if size == 1 { 1 } else { 2 }; - let before = offset.checked_sub(1).and_then(|at| raw.get(at)).copied(); - let base = match before { - // The ModRM byte itself, with no SIB byte after it. - Some(modrm) if modrm >> 6 == mode && modrm & 7 != 4 => modrm & 7, - // A SIB byte, whose low bits name the base. - Some(sib) => sib & 7, - None => return false, - }; - !extended && matches!(base, 4 | 5) -} - -fn signed(bytes: &[u8], field: (usize, usize)) -> Option { - let (offset, size) = field; - let part = bytes.get(offset..offset + size)?; - Some(match size { - 1 => i64::from(part[0] as i8), - 2 => i64::from(i16::from_le_bytes([part[0], part[1]])), - 4 => i64::from(i32::from_le_bytes([part[0], part[1], part[2], part[3]])), - 8 => i64::from_le_bytes(part.try_into().ok()?), - _ => return None, - }) -} - -/// Where the opcode of an instruction is, past its prefixes. -fn opcode_at(raw: &[u8]) -> usize { - let mut at = 0; - while raw.get(at).is_some_and(|byte| { - matches!( - byte, - 0x66 | 0xF2 | 0xF3 | 0xF0 | 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 - ) - }) { - at += 1; - } - if raw.get(at).is_some_and(|byte| byte & 0xF0 == 0x40) { - at += 1; - } - at -} - -fn step(raw: &[u8], instruction: &x64::Instruction, rva: u32) -> Step { - let next = i64::from(rva) + instruction.length as i64; - let opcode = opcode_at(raw); - let first = raw.get(opcode).copied(); - let second = raw.get(opcode + 1).copied(); - let branch = matches!(first, Some(0x70..=0x7F | 0xEB | 0xE0..=0xE3 | 0xE8 | 0xE9)) - || (first == Some(0x0F) && matches!(second, Some(0x80..=0x8F))); - let mut call = None; - let mut reference = None; - if let Some(field) = instruction.relative { - let target = signed(raw, field) - .map(|distance| next + distance) - .and_then(|target| u32::try_from(target).ok()); - if matches!(first, Some(0xE8 | 0xE9)) { - call = target; - } else if !branch { - reference = target; - } - } - Step { - rva, - skeleton: x64::skeleton(raw, instruction), - call, - reference, - displacement: instruction - .displacement - .and_then(|field| signed(raw, field)), - immediate: instruction.immediate.and_then(|field| signed(raw, field)), - indirect: first == Some(0xFF) - && second.is_some_and(|modrm| matches!((modrm >> 3) & 7, 2 | 4)), - // `add rsp, n` and `sub rsp, n` size the frame. - stack: stack_based(raw, instruction.displacement) - || (matches!(first, Some(0x81 | 0x83)) && matches!(second, Some(0xC4 | 0xEC))), - } -} - -/// Reads a function body from its start, as far as its exception table entry or, for a leaf, its -/// padding, and stops at the first instruction it cannot read. -fn read_body(pe: &PeFile, ranges: &BTreeMap, start: u32) -> Vec { - if !pe.is_code(start) { - return vec![]; - } - let listed = ranges.get(&start).copied(); - let length = match listed { - Some(end) => end.saturating_sub(start).min(BODY_LIMIT), - None => LEAF_LIMIT, - } as usize; - let Some(bytes) = pe.read(start, length).or_else(|| pe.read(start, 16)) else { - return vec![]; - }; - let mut steps = Vec::new(); - let mut at = 0; - while at < bytes.len() { - let rest = &bytes[at..]; - if listed.is_none() && rest.starts_with(&[0xCC, 0xCC]) { - break; - } - let Some(instruction) = x64::decode_body(rest) else { - break; - }; - if instruction.length == 0 || instruction.length > rest.len() { - break; - } - steps.push(step( - &rest[..instruction.length], - &instruction, - start + at as u32, - )); - at += instruction.length; - } - steps -} - -/// One build: its module, its function ranges and the bodies read so far. -pub struct Side<'a> { - pub pe: &'a PeFile<'a>, - ranges: BTreeMap, - bodies: HashMap>>, -} - -impl<'a> Side<'a> { - pub fn new(pe: &'a PeFile<'a>) -> Self { - Self { - pe, - ranges: pe.function_ranges(), - bodies: HashMap::new(), - } - } - - pub fn body(&mut self, start: u32) -> Rc> { - if let Some(body) = self.bodies.get(&start) { - return Rc::clone(body); - } - let body = Rc::new(read_body(self.pe, &self.ranges, start)); - self.bodies.insert(start, Rc::clone(&body)); - body - } - - /// The start of the function part that holds an address. - fn enclosing(&self, rva: u32) -> Option { - let (start, end) = self.ranges.range(..=rva).next_back()?; - (rva < *end).then_some(*start) - } - - fn is_start(&self, rva: u32) -> bool { - self.ranges.contains_key(&rva) - } -} - -/// Names the instruction at `index` by the instructions around it, as they stay when code moves. -pub fn context(steps: &[Step], index: usize, before: usize, after: usize) -> Vec { - let first = index.saturating_sub(before); - let last = (index + after).min(steps.len().saturating_sub(1)); - let mut key = vec![(index - first) as u8]; - for step in &steps[first..=last] { - key.push(step.skeleton.len() as u8); - key.extend_from_slice(&step.skeleton); - } - key -} - -/// Where each call or reference of a body points, named by the instructions before it, in order. -fn named_sites(steps: &[Step]) -> HashMap, Vec> { - let mut sites: HashMap, Vec> = HashMap::new(); - for (index, step) in steps.iter().enumerate() { - if let Some(target) = step.call.or(step.reference) { - sites - .entry(context(steps, index, CONTEXT, 0)) - .or_default() - .push(target); - } - } - sites -} - -/// Pairs what the two bodies of one function point at: sites named the same way, which each body -/// has the same number of, in order. -fn pair_sites( - old: &HashMap, Vec>, - new: &HashMap, Vec>, -) -> Vec<(u32, u32)> { - let mut pairs = Vec::new(); - for (key, targets) in old { - if let Some(others) = new.get(key).filter(|others| others.len() == targets.len()) { - pairs.extend(targets.iter().copied().zip(others.iter().copied())); - } - } - pairs.sort_unstable(); - pairs -} - -/// Addresses of the prior build with their places in the new one, found by following the calls -/// and references of functions known in both. An address reached two ways that disagree has none. -#[derive(Debug, Default)] -pub struct Followed { - pub places: BTreeMap, - conflicts: BTreeSet, -} - -impl Followed { - /// Records a pair, and says whether it is new. - fn add(&mut self, old: u32, new: u32) -> bool { - if self.conflicts.contains(&old) { - return false; - } - match self.places.get(&old) { - Some(place) if *place == new => false, - Some(_) => { - self.places.remove(&old); - self.conflicts.insert(old); - false - } - None => { - self.places.insert(old, new); - true - } - } - } - - fn get(&self, old: u32) -> Option { - self.places.get(&old).copied() - } -} - -/// Follows calls and references from the functions known in both builds, a few levels deep. -pub fn follow(old: &mut Side, new: &mut Side, known: &BTreeMap) -> Followed { - let mut followed = Followed::default(); - let mut frontier: Vec<(u32, u32)> = known - .iter() - .map(|(from, to)| (*from, *to)) - .filter(|(from, to)| old.pe.is_code(*from) && new.pe.is_code(*to)) - .collect(); - let mut visited = BTreeSet::new(); - for _ in 0..FOLLOW_DEPTH { - let mut next = Vec::new(); - for (from_old, from_new) in frontier { - if visited.len() >= FOLLOW_LIMIT || !visited.insert(from_old) { - continue; - } - let old_sites = named_sites(&old.body(from_old)); - let new_sites = named_sites(&new.body(from_new)); - for (to_old, to_new) in pair_sites(&old_sites, &new_sites) { - if known.contains_key(&to_old) { - continue; - } - if followed.add(to_old, to_new) && old.pe.is_code(to_old) && new.pe.is_code(to_new) - { - next.push((to_old, to_new)); - } - } - } - frontier = next; - } - followed -} - -/// The calls a function makes, as its prior body names them, to functions whose place in the new -/// build is known: `(site, rank among sites named the same, how many such sites, new place)`. -fn expected_calls( - old: &mut Side, - target: u32, - anchors: &BTreeMap, -) -> Vec<(Vec, usize, usize, u32)> { - let body = old.body(target); - let mut expected = Vec::new(); - for (key, callees) in named_sites(&body) { - for (rank, callee) in callees.iter().enumerate() { - if let Some(place) = anchors.get(callee) { - expected.push((key.clone(), rank, callees.len(), *place)); - } - } - } - expected.sort(); - expected -} - -/// The one candidate that makes the expected calls from the same spots, and contradicts none. -fn by_its_calls( - new: &mut Side, - expected: &[(Vec, usize, usize, u32)], - candidates: &[u32], -) -> Vec { - if expected.is_empty() { - return vec![]; - } - let least = expected.len().min(2); - let mut passing = Vec::new(); - for candidate in candidates { - let theirs = named_sites(&new.body(*candidate)); - let (mut hits, mut misses) = (0, 0); - for (key, rank, count, place) in expected { - match theirs.get(key) { - Some(found) if found.len() == *count => { - if found[*rank] == *place { - hits += 1; - } else { - misses += 1; - } - } - _ => {} - } - } - if misses == 0 && hits >= least { - passing.push(*candidate); - } - } - // Two candidates that both pass cannot be told apart: neither is an answer. - if passing.len() == 1 { - passing - } else { - vec![] - } -} - -/// The functions of a build that call any of `wanted` directly, by the function part each call is in. -fn calls_into(side: &Side, wanted: &BTreeSet) -> BTreeMap> { - let mut found: BTreeMap> = BTreeMap::new(); - if wanted.is_empty() { - return found; - } - for (base, bytes, is_code) in side.pe.sections() { - if !is_code { - continue; - } - for at in 0..bytes.len().saturating_sub(4) { - if !matches!(bytes[at], 0xE8 | 0xE9) { - continue; - } - let distance = - i32::from_le_bytes([bytes[at + 1], bytes[at + 2], bytes[at + 3], bytes[at + 4]]); - let site = base + at as u32; - let Ok(target) = u32::try_from(i64::from(site) + 5 + i64::from(distance)) else { - continue; - }; - if wanted.contains(&target) { - if let Some(start) = side.enclosing(site) { - found.entry(target).or_default().insert(start); - } - } - } - } - found -} - -/// The functions the prior bodies of `targets` call that their own fingerprints find in exactly one -/// place of the new build. They do not depend on the calls followed from known functions. -fn callee_anchors(old: &mut Side, new: &Side, targets: &[u32]) -> BTreeMap { - let mut prints = BTreeMap::new(); - for target in targets { - let body = old.body(*target); - for step in body.iter() { - let callee = step - .call - .or(step.reference.filter(|place| old.pe.is_code(*place))); - if let Some(callee) = callee { - if let Some(print) = code_print(old.pe, callee) { - prints.insert(callee, print); - } - } - } - } - let mut anchors = BTreeMap::new(); - for (callee, places) in find_prints(new.pe, &prints) { - // A print taken at a function start counts only function starts, as for the row itself. - let places: Vec = places - .into_iter() - .filter(|place| !old.is_start(callee) || new.is_start(*place)) - .collect(); - if let [only] = places.as_slice() { - anchors.insert(callee, *only); - } - } - anchors -} - -/// A function as the slots of a class table show it: its fingerprint, or the whole of a short one. -fn entry_shape(pe: &PeFile, function: u32) -> Option> { - code_print(pe, function).or_else(|| whole_function(pe, function)) -} - -fn same_function(old: &Side, new: &Side, known: &BTreeMap, from: u32, to: u32) -> bool { - if let Some(place) = known.get(&from) { - return *place == to; - } - match (entry_shape(old.pe, from), entry_shape(new.pe, to)) { - (Some(left), Some(right)) => left == right, - _ => false, - } -} - -/// The function in a slot of a class table, or `None` past the table's end. -fn entry(pe: &PeFile, table: u32, slot: i64) -> Option { - let slot = u32::try_from(slot).ok()?; - let at = table.checked_add(slot.checked_mul(8)?)?; - pe.pointer_rva(at).filter(|function| pe.is_code(*function)) -} - -/// How far slot `slot` of the old table moved in the new one, judged by the slots around it. -fn line_up( - old: &Side, - new: &Side, - known: &BTreeMap, - tables: (u32, u32), - slot: u32, -) -> Option { - let mut scores = Vec::new(); - for shift in -ALIGN_SHIFT..=ALIGN_SHIFT { - let mut score = 0; - for near in slot.saturating_sub(ALIGN_REACH)..=slot + ALIGN_REACH { - if near == slot { - continue; - } - let from = entry(old.pe, tables.0, i64::from(near)); - let to = entry(new.pe, tables.1, i64::from(near) + shift); - if let (Some(from), Some(to)) = (from, to) { - if same_function(old, new, known, from, to) { - score += 1; - } - } - } - scores.push((score, shift)); - } - scores.sort_by(|left, right| right.0.cmp(&left.0)); - match scores.as_slice() { - [(top, shift), (second, _), ..] if *top >= ALIGN_LEAST && top > second => Some(*shift), - _ => None, - } -} - -/// The places the class tables known in both builds give a function by its slot. -fn by_table_slot( - old: &Side, - new: &Side, - known: &BTreeMap, - tables: &[(u32, u32)], - target: u32, -) -> BTreeSet { - let mut found = BTreeSet::new(); - for pair in tables { - for slot in 0..TABLE_SLOTS { - let Some(function) = entry(old.pe, pair.0, i64::from(slot)) else { - break; - }; - if function != target { - continue; - } - if let Some(shift) = line_up(old, new, known, *pair, slot) { - if let Some(place) = entry(new.pe, pair.1, i64::from(slot) + shift) { - found.insert(place); - } - } - } - } - found -} - -/// The places a views class table gives a function by its slot, where the table of a second views -/// class, known in both builds, lines the same slot up by the same shift. `views` names the prior -/// build's tables of views classes. A slot of `views::View` is the same slot in every views class -/// table, and one of a derived class is the same slot in that class's subclasses, so a slot that two -/// tables line up alike is a slot number found twice, by tables found apart. -fn by_slot_shift( - old: &Side, - new: &Side, - known: &BTreeMap, - tables: &[(u32, u32)], - views: &BTreeSet, - target: u32, -) -> BTreeSet { - let mut found = BTreeSet::new(); - for pair in tables.iter().filter(|pair| views.contains(&pair.0)) { - for slot in 0..TABLE_SLOTS { - let Some(function) = entry(old.pe, pair.0, i64::from(slot)) else { - break; - }; - if function != target { - continue; - } - let Some(shift) = line_up(old, new, known, *pair, slot) else { - continue; - }; - let confirmed = tables - .iter() - .filter(|other| other.0 != pair.0 && views.contains(&other.0)) - .any(|other| line_up(old, new, known, *other, slot) == Some(shift)); - if confirmed { - if let Some(place) = entry(new.pe, pair.1, i64::from(slot) + shift) { - found.insert(place); - } - } - } - } - found -} - -/// The places the known callers of `target` give it among `candidates`: for each function that -/// calls it in the prior build and whose new place is known, the one candidate its new body calls, -/// when it calls exactly one. `callers` holds the prior build's callers of each wanted function. -fn by_known_callers( - new: &mut Side, - known: &BTreeMap, - callers: &BTreeSet, - candidates: &[u32], -) -> BTreeSet { - let mut found = BTreeSet::new(); - if candidates.is_empty() { - return found; - } - for caller in callers { - let Some(place) = known.get(caller).filter(|place| new.pe.is_code(**place)) else { - continue; - }; - let called: BTreeSet = new - .body(*place) - .iter() - .filter_map(|step| step.call) - .filter(|callee| candidates.contains(callee)) - .collect(); - if let [only] = called.into_iter().collect::>()[..] { - found.insert(only); - } - } - found -} - -/// The candidate tables whose slots hold the same functions as the old table, and how many agree. -fn by_slots( - old: &Side, - new: &Side, - known: &BTreeMap, - target: u32, - candidates: &[u32], -) -> Vec { - let mut passing = Vec::new(); - for candidate in candidates { - let (mut seen, mut agreed) = (0, 0); - for slot in 0..TABLE_SEEN { - let Some(function) = entry(old.pe, target, i64::from(slot)) else { - break; - }; - seen += 1; - let agrees = (-1..=1).any(|shift| { - entry(new.pe, *candidate, i64::from(slot) + shift) - .is_some_and(|place| same_function(old, new, known, function, place)) - }); - if agrees { - agreed += 1; - } - } - if agreed >= ALIGN_LEAST && agreed * 2 >= seen { - passing.push(*candidate); - } - } - passing -} - -/// How many of a table's first slots hold the very function another table of the same build holds -/// in that slot. Classes that share a base share the base's functions they do not replace. -fn shared_slots(pe: &PeFile, table: u32, other: u32) -> u32 { - (0..TABLE_SEEN) - .map_while(|slot| { - let slot = i64::from(slot); - Some((entry(pe, table, slot)?, entry(pe, other, slot)?)) - }) - .filter(|(left, right)| left == right) - .count() as u32 -} - -/// Whether `candidate` stands to a table known in both builds as `target` did in the prior build: -/// it shares about as many inherited slots with it. What a class takes from its bases is a fact of -/// the tables apart from the class's name, so it checks the table a name gives. -fn by_sibling(old: &Side, new: &Side, pairs: &[(u32, u32)], target: u32, candidate: u32) -> bool { - pairs - .iter() - .filter(|(from, _)| *from != target) - .any(|(from, to)| { - let before = shared_slots(old.pe, target, *from); - let after = shared_slots(new.pe, candidate, *to); - before >= SIBLING_LEAST && after * 10 >= before * 8 && after * 8 <= before * 10 - }) -} - -/// Tables of the new build that hold, near the same slot, a function the old table holds and -/// whose place is known. -fn table_candidates(old: &Side, new: &Side, known: &BTreeMap, target: u32) -> Vec { - let mut found = BTreeSet::new(); - let mut tried = 0; - for slot in 0..TABLE_SEEN { - let Some(function) = entry(old.pe, target, i64::from(slot)) else { - break; - }; - let Some(place) = known.get(&function).filter(|place| new.pe.is_code(**place)) else { - continue; - }; - for shifted in slot.saturating_sub(1)..=slot + 1 { - found.extend(find_table(new.pe, shifted, *place)); - } - tried += 1; - if tried == 2 { - break; - } - } - found.into_iter().take(CANDIDATES_MOST).collect() -} - -/// A table a function known in both builds loads from the same spot, or a place a few slots into -/// one, which keeps its distance from the table's start. -fn by_reference(followed: &Followed, target: u32) -> Option { - let (from, to) = followed - .places - .range(target.saturating_sub(0x40)..=target) - .next_back()?; - to.checked_add(target - from) -} - -/// The text at an address of a data section, with its terminating zero, when it is plain text. -fn text_at(pe: &PeFile, rva: u32) -> Option> { - if pe.is_code(rva) { - return None; - } - let window = pe - .read(rva, TEXT_MOST + 1) - .or_else(|| pe.read(rva, TEXT_LEAST + 1))?; - let end = window.iter().position(|byte| *byte == 0)?; - let text = &window[..end]; - if text.len() < TEXT_LEAST || !text.iter().all(|byte| (0x20..0x7F).contains(byte)) { - return None; - } - Some(window[..=end].to_vec()) -} - -/// For each text, the functions of a build that load it, when the build holds it exactly once. -fn functions_using(side: &Side, texts: &BTreeSet>) -> BTreeMap, BTreeSet> { - let mut by_head: HashMap<[u8; TEXT_LEAST], Vec<&Vec>> = HashMap::new(); - let mut first = [false; 256]; - for text in texts { - let head: [u8; TEXT_LEAST] = text[..TEXT_LEAST].try_into().expect("checked length"); - first[head[0] as usize] = true; - by_head.entry(head).or_default().push(text); - } - let mut places: BTreeMap<&Vec, Vec> = BTreeMap::new(); - for (base, bytes, is_code) in side.pe.sections() { - if is_code { - continue; - } - for at in 0..bytes.len().saturating_sub(TEXT_LEAST) { - if !first[bytes[at] as usize] { - continue; - } - let head: [u8; TEXT_LEAST] = bytes[at..at + TEXT_LEAST].try_into().expect("in range"); - for text in by_head.get(&head).map_or(&[][..], Vec::as_slice) { - if bytes[at..].starts_with(text) { - places.entry(*text).or_default().push(base + at as u32); - } - } - } - } - let at_address: HashMap> = places - .iter() - .filter_map(|(text, found)| match found.as_slice() { - [only] => Some((*only, *text)), - _ => None, - }) - .collect(); - let mut users: BTreeMap, BTreeSet> = BTreeMap::new(); - for (base, bytes, is_code) in side.pe.sections() { - if !is_code { - continue; - } - // `lea` or `mov` of a register from [rip + disp32]: REX, 8D or 8B, a ModRM of 00 reg 101. - for at in 3..bytes.len().saturating_sub(4) { - if bytes[at - 1] & 0xC7 != 0x05 - || !matches!(bytes[at - 2], 0x8D | 0x8B) - || bytes[at - 3] & 0xF0 != 0x40 - { - continue; - } - let distance = - i32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]); - let site = base + at as u32; - let Ok(target) = u32::try_from(i64::from(site) + 4 + i64::from(distance)) else { - continue; - }; - if let Some(text) = at_address.get(&target) { - if let Some(start) = side.enclosing(site) { - users.entry((*text).clone()).or_default().insert(start); - } - } - } - } - users -} - -/// How many functions on one side of a function are compared by their lengths. -const NEIGHBOURS: usize = 8; - -/// The function starts of a build in order, with every run of `NEIGHBOURS` lengths between them -/// and where it begins. -pub struct Lengths { - starts: Vec, - runs: HashMap, Vec>, -} - -impl Lengths { - pub fn new(starts: &BTreeSet) -> Self { - let starts: Vec = starts.iter().copied().collect(); - let gaps: Vec = starts.windows(2).map(|pair| pair[1] - pair[0]).collect(); - let mut runs: HashMap, Vec> = HashMap::new(); - for (index, run) in gaps.windows(NEIGHBOURS).enumerate() { - let places = runs.entry(run.to_vec()).or_default(); - // A run seen more than twice is no better than one seen twice: it names no place. - if places.len() < 2 { - places.push(index); - } - } - Self { starts, runs } - } - - /// The lengths of the `NEIGHBOURS` functions from the one at `index`. - fn run(&self, index: usize) -> Option> { - let part = self.starts.get(index..=index + NEIGHBOURS)?; - Some(part.windows(2).map(|pair| pair[1] - pair[0]).collect()) - } -} - -/// The place of a function by the functions the linker put beside it. The linker keeps the -/// functions of one source file together and in order, so the lengths of the functions after a -/// function, and of those before it, form a run that a build holds once. A run of the prior build -/// that the new build also holds exactly once gives the place. Both sides must not disagree, and a -/// run of equal lengths, as a row of small stubs has, says nothing. -fn by_neighbours(old: &Lengths, new: &Lengths, target: u32) -> Option { - let index = old.starts.binary_search(&target).ok()?; - let place = |run: Option>, back: usize| -> Option> { - let run = run?; - if run.iter().collect::>().len() < NEIGHBOURS / 2 { - return None; - } - match new.runs.get(&run).map(Vec::as_slice) { - Some([only]) => Some(new.starts.get(only + back).copied()), - Some(_) => Some(None), - None => None, - } - }; - let after = place(old.run(index), 0); - let before = place( - index.checked_sub(NEIGHBOURS).and_then(|from| old.run(from)), - NEIGHBOURS, - ); - match (after.flatten(), before.flatten()) { - (Some(one), Some(other)) => (one == other).then_some(one), - (Some(one), None) | (None, Some(one)) => Some(one), - (None, None) => None, - } -} - -/// How many callers must agree on a place, how many are a crowd, and how many are read. -const VOTERS_LEAST: usize = 3; -const VOTERS_CROWD: usize = 8; -const VOTERS_MOST: usize = 400; - -/// The place of a function by the functions that call it. Each caller is placed by its own -/// neighbours, apart from every other caller, and must make as many direct calls and jumps in both -/// builds. The call that went to the function in the prior build then goes to its new place. One -/// caller is one vote, and the place stands when at least `VOTERS_LEAST` callers name it and at -/// most one in ten names another. Returns the place and its votes. -fn by_callers( - old: &mut Side, - new: &mut Side, - lengths: (&Lengths, &Lengths), - callers: &BTreeSet, - target: u32, -) -> Option<(u32, usize)> { - let mut votes: BTreeMap = BTreeMap::new(); - for caller in callers.iter().take(VOTERS_MOST) { - let Some(place) = by_neighbours(lengths.0, lengths.1, *caller) else { - continue; - }; - let before: Vec = old - .body(*caller) - .iter() - .filter_map(|step| step.call) - .collect(); - let after: Vec = new - .body(place) - .iter() - .filter_map(|step| step.call) - .collect(); - if before.len() != after.len() { - continue; - } - let named: BTreeSet = before - .iter() - .zip(&after) - .filter(|(from, _)| **from == target) - .map(|(_, to)| *to) - .collect(); - if let [only] = named.iter().copied().collect::>()[..] { - *votes.entry(only).or_default() += 1; - } - } - let all: usize = votes.values().sum(); - let (place, most) = votes.into_iter().max_by_key(|(_, count)| *count)?; - (most >= VOTERS_LEAST && (all - most) * 10 <= all).then_some((place, most)) -} - -/// How many instructions a function must have for its shape to say which function it is. -const SHAPE_LEAST: usize = 8; - -/// Whether two functions are the same instructions from start to end, apart from the addresses, -/// member offsets and constants in them. A short function is not asked: many are alike. -fn same_shape(old: &mut Side, new: &mut Side, from: u32, to: u32) -> bool { - let (before, after) = (old.body(from), new.body(to)); - before.len() >= SHAPE_LEAST - && before.len() == after.len() - && before - .iter() - .zip(after.iter()) - .all(|(left, right)| left.skeleton == right.skeleton) -} - -/// Which method gave a place. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] -pub enum Method { - CallsInto, - ItsCalls, - TableSlot, - Text, - References, - Slots, - ClassName, - Fingerprint, - SlotShift, - Command, - KnownCaller, - Sibling, - Neighbours, - Callers, - Crowd, - Shape, -} - -impl fmt::Display for Method { - fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result { - out.write_str(match self { - Method::CallsInto => "calls into it", - Method::ItsCalls => "its calls", - Method::TableSlot => "its table slot", - Method::Text => "a text it uses", - Method::References => "references to it", - Method::Slots => "its slots", - Method::ClassName => "its class name", - Method::Fingerprint => "its fingerprint", - Method::SlotShift => "its slot shift", - Method::Command => "its command id", - Method::KnownCaller => "a known caller", - Method::Sibling => "the slots it shares with a known table", - Method::Neighbours => "the lengths of the functions beside it", - Method::Callers => "the same call in several placed callers", - Method::Crowd => "the number of callers that agree", - Method::Shape => "the same instructions throughout", - }) - } -} - -fn names(methods: &BTreeSet) -> String { - methods - .iter() - .map(Method::to_string) - .collect::>() - .join(" and ") -} - -/// Takes a place only when two different methods name it, no method names another, and it is one -/// of the fingerprint's places where there are any. -pub fn decide( - answers: &[(Method, u32)], - candidates: Option<&[u32]>, -) -> Result<(u32, BTreeSet), String> { - let places: BTreeSet = answers.iter().map(|(_, place)| *place).collect(); - let methods: BTreeSet = answers.iter().map(|(method, _)| *method).collect(); - match places.iter().copied().collect::>().as_slice() { - [] => Err("no method found it".to_owned()), - [place] => { - if candidates.is_some_and(|candidates| !candidates.contains(place)) { - Err(format!( - "{} found {place:#x}, which is not one of its fingerprint's places", - names(&methods) - )) - } else if methods.len() < 2 { - Err(format!( - "only {} found it, at {place:#x}, and a second method is needed", - names(&methods) - )) - } else { - Ok((*place, methods)) - } - } - _ => { - let mut said: Vec = answers - .iter() - .map(|(method, place)| format!("{method} {place:#x}")) - .collect(); - said.sort(); - said.dedup(); - Err(format!("the methods disagree: {}", said.join(", "))) - } - } -} - -/// What an address of the prior row is. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Kind { - Function, - Table, -} - -/// An address the fingerprints did not pin down, with the places they matched, if any. -#[derive(Debug, Clone)] -pub struct Wanted { - pub kind: Kind, - pub candidates: Option>, - /// For a class table, the views class whose name its metadata holds in the prior build. - pub class: Option, - /// For a function a browser command runs first, the command's public id. - pub command: Option, - /// Places the fingerprint matched that the exception table does not list as function starts. - /// They name no place alone, but a place another method finds among them is one the - /// fingerprint agrees with. - pub loose: Vec, -} - -/// The class table a views class name gives in the new build, once the same reading gives the -/// prior table in the prior build. -pub fn class_place( - old_pe: &PeFile, - new_pe: &PeFile, - target: u32, - class: &str, -) -> Result { - let old = crate::row_class::class_tables(old_pe, class); - if old != BTreeSet::from([target]) { - return Err(format!( - "its class name {class} gives {} tables in the prior build, not the prior table alone", - old.len() - )); - } - let new = crate::row_class::class_tables(new_pe, class); - match new.iter().copied().collect::>().as_slice() { - [only] => Ok(*only), - many => Err(format!( - "its class name {class} gives {} tables in the new build", - many.len() - )), - } -} - -/// What the fingerprint adds to the places a class table gives: agreement when the table gives -/// exactly one place and that place is one of the fingerprint's. -pub fn fingerprint_agrees( - given: &BTreeSet, - candidates: Option<&[u32]>, -) -> Option<(Method, u32)> { - let [only] = given.iter().copied().collect::>()[..] else { - return None; - }; - candidates - .is_some_and(|candidates| candidates.contains(&only)) - .then_some((Method::Fingerprint, only)) -} - -/// What the methods found. -#[derive(Debug, Default)] -pub struct Resolution { - /// The new place of each address two methods agree on. - pub places: BTreeMap, - /// For the report: each place and the methods that found it. - pub settled: Vec, - /// Why each other address has no place. - pub reasons: BTreeMap, - /// Functions of the prior build with their places in the new one, as the calls of known - /// functions pair them, for reading values from the same instructions in both builds. - pub followed: BTreeMap, -} - -/// Looks for each wanted address with every method, in rounds, since a place found in one round -/// is known in the next. `known` holds the places the fingerprints found, `tables` names the -/// prior row's addresses that are class tables, and `views` those of them that are tables of views -/// classes. -pub fn resolve( - old_pe: &PeFile, - new_pe: &PeFile, - known: &BTreeMap, - wanted: &BTreeMap, - tables: &BTreeSet, - views: &BTreeSet, -) -> Resolution { - let mut old = Side::new(old_pe); - let mut new = Side::new(new_pe); - let mut known = known.clone(); - let mut resolution = Resolution::default(); - let functions: Vec = wanted - .iter() - .filter(|(_, want)| want.kind == Kind::Function) - .map(|(target, _)| *target) - .collect(); - - // What does not depend on the known places is read once: the callees found by their own - // fingerprints, the functions that call them, and the texts each function uses. - let anchors = callee_anchors(&mut old, &new, &functions); - let mut texts_of: BTreeMap>> = BTreeMap::new(); - for target in &functions { - let body = old.body(*target); - let texts: BTreeSet> = body - .iter() - .filter_map(|step| step.reference) - .filter_map(|place| text_at(old.pe, place)) - .collect(); - texts_of.insert(*target, texts); - } - let all_texts: BTreeSet> = texts_of.values().flatten().cloned().collect(); - let users = functions_using(&new, &all_texts); - let mut seen_anchors = anchors.clone(); - for (from, to) in &known { - if old.pe.is_code(*from) { - seen_anchors.insert(*from, *to); - } - } - let mut expected = BTreeMap::new(); - let mut called = BTreeSet::new(); - for target in &functions { - let calls = expected_calls(&mut old, *target, &seen_anchors); - called.extend(calls.iter().map(|call| call.3)); - expected.insert(*target, calls); - } - let callers = calls_into(&new, &called); - // The prior build's callers of each wanted function with fingerprint places, for the method of - // a known caller. - let prior_callers = calls_into(&old, &functions.iter().copied().collect()); - - // A class name gives a table from the build alone, so it is read once. - let mut by_class = BTreeMap::new(); - let mut class_reasons = BTreeMap::new(); - for (target, want) in wanted { - let Some(class) = want.class.as_deref().filter(|_| want.kind == Kind::Table) else { - continue; - }; - match class_place(old_pe, new_pe, *target, class) { - Ok(place) => { - by_class.insert(*target, place); - } - Err(reason) => { - class_reasons.insert(*target, reason); - } - } - } - - // A command id gives a function from both builds alone, so it is read once. - let mut by_command = BTreeMap::new(); - let commands: Vec<(u32, i64)> = wanted - .iter() - .filter(|(_, want)| want.kind == Kind::Function) - .filter_map(|(target, want)| Some((*target, want.command?))) - .collect(); - if !commands.is_empty() { - let old_switches = crate::row_command::switches(old_pe); - let new_switches = crate::row_command::switches(new_pe); - for (target, id) in commands { - let old = (old_pe, old_switches.as_slice()); - let new = (new_pe, new_switches.as_slice()); - match crate::row_command::command_place_in(old, new, target, id) { - Ok(place) => { - by_command.insert(target, place); - } - Err(reason) => { - class_reasons.insert(target, reason); - } - } - } - } - - let old_lengths = Lengths::new(&old_pe.function_starts()); - let new_lengths = Lengths::new(&new_pe.function_starts()); - - let mut pending: BTreeSet = wanted.keys().copied().collect(); - for _ in 0..ROUNDS { - let followed = follow(&mut old, &mut new, &known); - let table_pairs: Vec<(u32, u32)> = known - .iter() - .filter(|(from, _)| tables.contains(from)) - .map(|(from, to)| (*from, *to)) - .collect(); - let mut found_any = false; - for target in pending.clone() { - let want = &wanted[&target]; - let mut answers = Vec::new(); - match want.kind { - Kind::Function => { - if let Some(place) = followed.get(target) { - answers.push((Method::CallsInto, place)); - } - let calls = &expected[&target]; - let candidates: Vec = match &want.candidates { - Some(list) => list.clone(), - None => calls - .iter() - .flat_map(|call| callers.get(&call.3).into_iter().flatten().copied()) - .collect::>() - .into_iter() - .take(CANDIDATES_MOST) - .collect(), - }; - for place in by_its_calls(&mut new, calls, &candidates) { - answers.push((Method::ItsCalls, place)); - } - let slotted = by_table_slot(&old, &new, &known, &table_pairs, target); - answers.extend(fingerprint_agrees(&slotted, want.candidates.as_deref())); - for place in slotted { - answers.push((Method::TableSlot, place)); - } - for place in by_slot_shift(&old, &new, &known, &table_pairs, views, target) { - answers.push((Method::SlotShift, place)); - } - if let Some(place) = by_text(&texts_of[&target], &users) { - answers.push((Method::Text, place)); - } - let from = prior_callers.get(&target); - if let (Some(list), Some(from)) = (&want.candidates, from) { - // A known caller is a call from a function known in both builds, the same - // kind of fact as the calls into it, so it is never counted beside them and - // the fingerprint's places only limit where it may point. - let given = by_known_callers(&mut new, &known, from, list); - for place in given { - let seen = answers - .iter() - .any(|(method, at)| *method == Method::CallsInto && *at == place); - if !seen { - answers.push((Method::KnownCaller, place)); - } - } - } - if let Some(place) = by_neighbours(&old_lengths, &new_lengths, target) { - // Where a function lies says nothing of its bytes, so the fingerprint - // matching at that place is a second fact. - answers.push((Method::Neighbours, place)); - let matched = want - .candidates - .as_ref() - .is_some_and(|candidates| candidates.contains(&place)) - || want.loose.contains(&place); - if matched { - answers.push((Method::Fingerprint, place)); - } - } - let voted = from.and_then(|callers| { - let lengths = (&old_lengths, &new_lengths); - by_callers(&mut old, &mut new, lengths, callers, target) - }); - if let Some((place, votes)) = voted { - // Callers placed by their neighbours are another fact than the calls - // followed from known functions, but the same kind, so beside those they - // add only what the fingerprint and their number say. - let followed = answers.iter().any(|(method, at)| { - matches!(method, Method::CallsInto | Method::KnownCaller) - && *at == place - }); - if !followed { - answers.push((Method::Callers, place)); - } - let matched = want - .candidates - .as_ref() - .is_some_and(|candidates| candidates.contains(&place)) - || want.loose.contains(&place); - if matched { - answers.push((Method::Fingerprint, place)); - } - if votes >= VOTERS_CROWD { - answers.push((Method::Crowd, place)); - } - } - // The shape of a body is a fact apart from where a table, a text or the - // neighbours put the function. It is not one apart from the calls: functions - // alike in shape are often called from the same places. - let apart = answers.iter().copied().find(|(method, _)| { - matches!( - method, - Method::TableSlot - | Method::SlotShift - | Method::Text - | Method::Neighbours - ) - }); - if let Some((_, place)) = apart { - if same_shape(&mut old, &mut new, target, place) { - answers.push((Method::Shape, place)); - } - } - if let Some(place) = by_command.get(&target).copied() { - answers.push((Method::Command, place)); - let matched = want - .candidates - .as_ref() - .is_some_and(|candidates| candidates.contains(&place)) - || want.loose.contains(&place); - if matched { - answers.push((Method::Fingerprint, place)); - } - } - } - Kind::Table => { - if let Some(place) = by_reference(&followed, target) { - answers.push((Method::References, place)); - } - let mut candidates = match &want.candidates { - Some(list) => list.clone(), - None => table_candidates(&old, &new, &known, target), - }; - // The table a class name gives is also compared slot by slot, which checks - // its structure apart from the name. - if let Some(place) = by_class.get(&target) { - if !candidates.contains(place) { - candidates.push(*place); - } - } - let mut slots = by_slots(&old, &new, &known, target, &candidates); - if let Some(place) = by_class.get(&target).copied() { - answers.push((Method::ClassName, place)); - if by_sibling(&old, &new, &table_pairs, target, place) { - answers.push((Method::Sibling, place)); - } - let given = BTreeSet::from([place]); - answers.extend(fingerprint_agrees(&given, want.candidates.as_deref())); - // Several tables holding the same slots is no answer of their own; the - // class name tells which of them is the class's. - if slots.len() > 1 && slots.contains(&place) { - slots = vec![place]; - } - } - for place in slots { - answers.push((Method::Slots, place)); - } - } - } - // A function may start with a jump over a few bytes to its body, and the exception - // table then lists the body as a start of its own. A method that names the body means - // the function another method names by its real start. - let starts: Vec = answers.iter().map(|(_, place)| *place).collect(); - for (_, place) in &mut answers { - let start = starts.iter().copied().find(|start| { - *start < *place - && *place - *start <= 16 - && new.pe.read(*start, 5).is_some_and(|head| { - head[0] == 0xE9 - && i64::from(*start) - + 5 - + i64::from(i32::from_le_bytes( - head[1..5].try_into().expect("four bytes"), - )) - == i64::from(*place) - }) - }); - if let Some(start) = start { - *place = start; - } - } - match decide(&answers, want.candidates.as_deref()) { - Ok((place, methods)) => { - known.insert(target, place); - resolution.places.insert(target, place); - resolution - .settled - .push(format!("{target:#x} -> {place:#x} by {}", names(&methods))); - resolution.reasons.remove(&target); - pending.remove(&target); - found_any = true; - } - Err(reason) => { - let reason = match class_reasons.get(&target) { - Some(class) => format!("{reason}; {class}"), - None => reason, - }; - resolution.reasons.insert(target, reason); - } - } - } - resolution.followed = followed.places; - if !found_any || pending.is_empty() { - break; - } - } - resolution -} - -/// The one function that uses every text of a target the new build holds once. -fn by_text(texts: &BTreeSet>, users: &BTreeMap, BTreeSet>) -> Option { - let mut common: Option> = None; - for text in texts { - let Some(found) = users.get(text) else { - continue; - }; - common = Some(match common { - Some(common) => common.intersection(found).copied().collect(), - None => found.clone(), - }); - } - let common = common?; - match common.iter().copied().collect::>().as_slice() { - [only] => Some(*only), - _ => None, - } -} - -/// How many instructions on each side of a use name it within its body. -const VALUE_CONTEXT: usize = 2; - -/// Which operand of an instruction holds a value. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Operand { - Displacement, - Immediate, -} - -/// A value of the prior row read again from the new build, or why it could not be. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Reading { - pub path: String, - pub prior: u64, - /// The new value and how it was read. - pub value: Result<(u64, String), String>, -} - -fn keys(steps: &[Step]) -> Vec> { - (0..steps.len()) - .map(|index| context(steps, index, VALUE_CONTEXT, VALUE_CONTEXT)) - .collect() -} - -/// Whether an instruction uses `wanted`: as a member displacement or an immediate for a plain -/// value, or as the displacement of a call through a table for a slot, which is eight bytes each. -fn use_of(step: &Step, wanted: i64, slot: bool) -> Option { - if step.stack { - return None; - } - if slot { - return (step.indirect && step.displacement == Some(wanted)) - .then_some(Operand::Displacement); - } - if step.displacement == Some(wanted) { - Some(Operand::Displacement) - } else if step.immediate == Some(wanted) { - Some(Operand::Immediate) - } else { - None - } -} - -/// Reads one value from the instructions that use it. Each use of `prior` in a prior function body -/// is named by the instructions around it, with their own operands cleared, and the same -/// instruction is looked up in the function's new body. A value is taken only when at least two -/// uses are read and every use read gives the same value. -fn read_value( - old: &mut Side, - new: &mut Side, - pairs: &[(u32, u32)], - prior: u64, - slot: bool, -) -> Result<(u64, String), String> { - if prior == 0 { - return Err("zero is used too widely in code to be told apart".to_owned()); - } - let wanted = if slot { - prior.checked_mul(8) - } else { - Some(prior) - } - .and_then(|value| i64::try_from(value).ok()) - .ok_or_else(|| format!("{prior:#x} is too large to be an operand"))?; - let mut found: Vec<(u64, u32)> = Vec::new(); - let mut uses = 0; - for (from, to) in pairs { - let old_body = old.body(*from); - let new_body = new.body(*to); - let old_keys = keys(&old_body); - let new_keys = keys(&new_body); - for (index, step) in old_body.iter().enumerate() { - let Some(operand) = use_of(step, wanted, slot) else { - continue; - }; - uses += 1; - let key = &old_keys[index]; - let rank = old_keys[..index] - .iter() - .filter(|other| *other == key) - .count(); - let count = old_keys.iter().filter(|other| *other == key).count(); - let theirs: Vec = new_keys - .iter() - .enumerate() - .filter(|(_, other)| *other == key) - .map(|(at, _)| at) - .collect(); - if theirs.len() != count { - continue; - } - let other = &new_body[theirs[rank]]; - let read = match operand { - Operand::Displacement => other.displacement, - Operand::Immediate => other.immediate, - }; - let Some(read) = read.and_then(|read| u64::try_from(read).ok()) else { - continue; - }; - if slot && read % 8 != 0 { - continue; - } - found.push((if slot { read / 8 } else { read }, *from)); - } - } - let values: BTreeSet = found.iter().map(|(value, _)| *value).collect(); - let functions: BTreeSet = found.iter().map(|(_, function)| *function).collect(); - match values.iter().copied().collect::>().as_slice() { - [] if uses == 0 => Err(format!( - "no instruction of the {} functions known in both builds uses {prior:#x}", - pairs.len() - )), - [] => Err(format!( - "its {uses} uses in the prior build were not found in the new one" - )), - [value] if found.len() >= 2 => Ok(( - *value, - format!( - "read at {} uses in {} of its functions", - found.len(), - functions.len() - ), - )), - [value] => Err(format!( - "read at only one use, as {value:#x}, and a second reading is needed" - )), - _ => Err(format!("its uses disagree: {values:#x?}")), - } -} - -/// Reads each value of the prior row that has no recipe from the instructions that use it in the -/// functions of its part of the row, and in the functions they call, in both builds. `sections` -/// pairs the prior and new places of each part's functions, and `followed` pairs the functions -/// the calls of known functions reach. A value's part is the first name of its path, and a value -/// whose name ends in `_slot` is a slot of a class table. -pub fn read_values( - old_pe: &PeFile, - new_pe: &PeFile, - sections: &BTreeMap>, - followed: &BTreeMap, - values: &[(String, u64)], -) -> Vec { - let mut old = Side::new(old_pe); - let mut new = Side::new(new_pe); - let mut pairs_of: BTreeMap<&str, Vec<(u32, u32)>> = BTreeMap::new(); - for (section, pairs) in sections { - let mut all: BTreeSet<(u32, u32)> = pairs.iter().copied().collect(); - for (from, _) in pairs { - let body = old.body(*from); - for step in body.iter() { - if let Some(place) = step.call.and_then(|callee| followed.get(&callee)) { - all.insert((step.call.expect("checked"), *place)); - } - } - } - pairs_of.insert(section.as_str(), all.into_iter().collect()); - } - let mut readings = Vec::new(); - for (path, prior) in values { - let section = path.split('.').next().unwrap_or_default(); - let name = path.rsplit('.').next().unwrap_or_default(); - let slot = name - .split('[') - .next() - .unwrap_or_default() - .ends_with("_slot"); - let pairs = pairs_of.get(section).map_or(&[][..], Vec::as_slice); - readings.push(Reading { - path: path.clone(), - prior: *prior, - value: read_value(&mut old, &mut new, pairs, *prior, slot), - }); - } - readings -} - -#[cfg(test)] -pub(crate) mod tests { - use super::*; - - pub const IMAGE_BASE: u64 = 0x1_8000_0000; - /// Where a fixture keeps its exception table, in its data section. - const EXCEPTIONS: u32 = 0x20f000; - - fn place(rva: u32) -> usize { - if rva >= 0x200000 { - 0x10400 + (rva - 0x200000) as usize - } else { - 0x400 + (rva - 0x100000) as usize - } - } - - /// A 64-bit module with a code section at 0x100000 and a data section at 0x200000, holding - /// the given bytes and an exception table that lists `ranges`. - pub fn module(parts: &[(u32, Vec)], ranges: &[(u32, u32)]) -> Vec { - let mut bytes = vec![0u8; 0x400]; - bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); - bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); - bytes[0x86..0x88].copy_from_slice(&2u16.to_le_bytes()); - bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes()); - bytes[0x98..0x9a].copy_from_slice(&0x20bu16.to_le_bytes()); - bytes[0x98 + 24..0x98 + 32].copy_from_slice(&IMAGE_BASE.to_le_bytes()); - let sections = [ - (0x100000u32, 0x400u32, 0x2000_0000u32), - (0x200000, 0x10400, 0x4000_0000), - ]; - for (index, (rva, raw, flags)) in sections.iter().enumerate() { - let header = 0x98 + 240 + 40 * index; - bytes[header + 8..header + 12].copy_from_slice(&0x10000u32.to_le_bytes()); - bytes[header + 12..header + 16].copy_from_slice(&rva.to_le_bytes()); - bytes[header + 16..header + 20].copy_from_slice(&0x10000u32.to_le_bytes()); - bytes[header + 20..header + 24].copy_from_slice(&raw.to_le_bytes()); - bytes[header + 36..header + 40].copy_from_slice(&flags.to_le_bytes()); - } - bytes.resize(0x400 + 0x20000, 0); - bytes[0x400..0x10400].fill(0xCC); - let mut table = vec![]; - for (start, end) in ranges { - table.extend_from_slice(&start.to_le_bytes()); - table.extend_from_slice(&end.to_le_bytes()); - table.extend_from_slice(&0u32.to_le_bytes()); - } - let directory = 0x98 + 112 + 24; - bytes[directory..directory + 4].copy_from_slice(&EXCEPTIONS.to_le_bytes()); - bytes[directory + 4..directory + 8].copy_from_slice(&(table.len() as u32).to_le_bytes()); - let at = place(EXCEPTIONS); - bytes[at..at + table.len()].copy_from_slice(&table); - for (rva, data) in parts { - let at = place(*rva); - bytes[at..at + data.len()].copy_from_slice(data); - } - bytes - } - - pub fn call(from: u32, to: u32) -> Vec { - let mut bytes = vec![0xE8]; - bytes.extend_from_slice(&((i64::from(to) - i64::from(from) - 5) as i32).to_le_bytes()); - bytes - } - - pub fn table(functions: &[u32]) -> Vec { - functions - .iter() - .flat_map(|function| (IMAGE_BASE + u64::from(*function)).to_le_bytes()) - .collect() - } - - /// sub rsp, 28h; call `to`; add rsp, 28h; ret. - fn caller(at: u32, to: u32) -> Vec { - let mut bytes = vec![0x48, 0x83, 0xEC, 0x28]; - bytes.extend(call(at + 4, to)); - bytes.extend([0x48, 0x83, 0xC4, 0x28, 0xC3]); - bytes - } - - /// push rsi; sub rsp, 20h; mov rsi, rcx; add rsp, 20h; pop rsi; ret. - const TARGET: [u8; 14] = [ - 0x56, 0x48, 0x83, 0xEC, 0x20, 0x48, 0x89, 0xCE, 0x48, 0x83, 0xC4, 0x20, 0x5E, 0xC3, - ]; - - /// `mov eax, n; ret`: a different small function for each slot of a table. - fn small(n: u8) -> Vec { - vec![0xB8, n, 0, 0, 0, 0xC3] - } - - const OLD_CALLER: u32 = 0x101000; - const OLD_TARGET: u32 = 0x101100; - const OLD_TABLE: u32 = 0x200100; - const NEW_CALLER: u32 = 0x103000; - const NEW_TARGETS: [u32; 2] = [0x103100, 0x103200]; - const NEW_TABLE: u32 = 0x200800; - - /// The prior build: a caller of the target, and a table that holds it in slot 3. - fn old_module() -> Vec { - let mut parts = vec![ - (OLD_CALLER, caller(OLD_CALLER, OLD_TARGET)), - (OLD_TARGET, TARGET.to_vec()), - ]; - let mut slots = vec![]; - for n in 0..6u8 { - let at = 0x101400 + 0x10 * u32::from(n); - parts.push((at, small(n))); - slots.push(at); - } - slots.insert(3, OLD_TARGET); - parts.push((OLD_TABLE, table(&slots))); - module( - &parts, - &[(OLD_CALLER, OLD_CALLER + 14), (OLD_TARGET, OLD_TARGET + 14)], - ) - } - - /// The new build: the target's bytes in two places, a caller of the first, and a table that - /// holds `in_table` in slot 3. - fn new_module(in_table: u32) -> Vec { - let mut parts = vec![ - (NEW_CALLER, caller(NEW_CALLER, NEW_TARGETS[0])), - (NEW_TARGETS[0], TARGET.to_vec()), - (NEW_TARGETS[1], TARGET.to_vec()), - ]; - let mut slots = vec![]; - for n in 0..6u8 { - let at = 0x103400 + 0x10 * u32::from(n); - parts.push((at, small(n))); - slots.push(at); - } - slots.insert(3, in_table); - parts.push((NEW_TABLE, table(&slots))); - let ranges = [ - (NEW_CALLER, NEW_CALLER + 14), - (NEW_TARGETS[0], NEW_TARGETS[0] + 14), - (NEW_TARGETS[1], NEW_TARGETS[1] + 14), - ]; - module(&parts, &ranges) - } - - fn run(new_bytes: &[u8], known_table: bool) -> Resolution { - let old_bytes = old_module(); - let old = PeFile::parse(&old_bytes).unwrap(); - let new = PeFile::parse(new_bytes).unwrap(); - let mut known = BTreeMap::from([(OLD_CALLER, NEW_CALLER)]); - if known_table { - known.insert(OLD_TABLE, NEW_TABLE); - } - let wanted = BTreeMap::from([( - OLD_TARGET, - Wanted { - kind: Kind::Function, - candidates: Some(NEW_TARGETS.to_vec()), - class: None, - command: None, - loose: Vec::new(), - }, - )]); - resolve( - &old, - &new, - &known, - &wanted, - &BTreeSet::from([OLD_TABLE]), - &BTreeSet::new(), - ) - } - - #[test] - fn nfr6_a_function_with_several_places_takes_the_one_two_methods_agree_on() { - let resolution = run(&new_module(NEW_TARGETS[0]), true); - assert_eq!(resolution.places.get(&OLD_TARGET), Some(&NEW_TARGETS[0])); - assert_eq!( - resolution.settled, - ["0x101100 -> 0x103100 by calls into it and its table slot and its fingerprint"] - ); - assert!(resolution.reasons.is_empty(), "{:?}", resolution.reasons); - } - - #[test] - fn nfr6_a_class_table_is_taken_where_its_class_name_and_fingerprint_agree() { - // Edge 157's frame table: two tables hold the frame's layout function in slot 24, and its - // class name tells which of them is the frame view's. - let candidates: &[u32] = &[0x11b5_19a8, 0x11b5_2528]; - let by_name = BTreeSet::from([candidates[1]]); - let mut answers = vec![(Method::ClassName, candidates[1])]; - answers.extend(fingerprint_agrees(&by_name, Some(candidates))); - assert_eq!(answers[1], (Method::Fingerprint, candidates[1])); - let (place, methods) = decide(&answers, Some(candidates)).unwrap(); - assert_eq!(place, candidates[1]); - assert_eq!(methods.len(), 2); - // A class name alone is one method. - let alone = decide(&answers[..1], None).unwrap_err(); - assert!(alone.starts_with("only its class name found it"), "{alone}"); - // A place that is not one of the fingerprint's places gets no agreement from it. - assert_eq!( - fingerprint_agrees(&BTreeSet::from([0x11b5_3000]), Some(candidates)), - None - ); - // A table slot that gives two places gives the fingerprint nothing to agree with. - let both: BTreeSet = candidates.iter().copied().collect(); - assert_eq!(fingerprint_agrees(&both, Some(candidates)), None); - assert_eq!(fingerprint_agrees(&by_name, None), None); - } - - #[test] - fn nfr6_methods_that_disagree_leave_the_function_unresolved() { - let resolution = run(&new_module(NEW_TARGETS[1]), true); - assert!(resolution.places.is_empty()); - let reason = &resolution.reasons[&OLD_TARGET]; - assert!(reason.starts_with("the methods disagree: "), "{reason}"); - assert!(reason.contains("calls into it 0x103100"), "{reason}"); - assert!(reason.contains("its table slot 0x103200"), "{reason}"); - } - - #[test] - fn nfr6_one_method_alone_does_not_place_a_function() { - let resolution = run(&new_module(NEW_TARGETS[0]), false); - assert!(resolution.places.is_empty()); - let reason = &resolution.reasons[&OLD_TARGET]; - assert!( - reason.starts_with("only calls into it found it"), - "{reason}" - ); - } - - const VIEW_TARGET: u32 = 0x105000; - const VIEW_TABLE: u32 = 0x201000; - const OTHER_VIEW_TABLE: u32 = 0x201400; - - /// A build with two tables of views classes. The first holds, among small functions, the - /// target in slot 6; the second holds small functions only. In a new build each table gets one - /// more slot at slot 2 when `inserted` says so, as when a milestone adds a virtual function to - /// `views::View`, and the target's code changed, so its fingerprint finds nothing. - fn views_module(new: bool, inserted: [bool; 2]) -> Vec { - let mut parts = vec![]; - let mut ranges = vec![]; - let mut slots = |base: u32, first: u8, holds_target: bool, insert: bool| { - let mut list = vec![]; - for n in 0..12u8 { - let at = base + 0x10 * u32::from(n); - parts.push((at, small(first + n))); - list.push(at); - } - if holds_target { - list.insert(6, VIEW_TARGET); - } - if insert { - let at = base + 0x100; - parts.push((at, small(first + 0x40))); - list.insert(2, at); - } - list - }; - let first = slots(0x105400, 0, true, new && inserted[0]); - let second = slots(0x105800, 0x80, false, new && inserted[1]); - parts.push((VIEW_TABLE, table(&first))); - parts.push((OTHER_VIEW_TABLE, table(&second))); - let mut code = TARGET.to_vec(); - if new { - // mov rsi, rdx instead of mov rsi, rcx. - code[7] = 0xD6; - } - parts.push((VIEW_TARGET, code)); - ranges.push((VIEW_TARGET, VIEW_TARGET + 14)); - module(&parts, &ranges) - } - - fn run_views(inserted: [bool; 2], views: &[u32]) -> Resolution { - let old_bytes = views_module(false, [false; 2]); - let new_bytes = views_module(true, inserted); - let old = PeFile::parse(&old_bytes).unwrap(); - let new = PeFile::parse(&new_bytes).unwrap(); - let known = BTreeMap::from([ - (VIEW_TABLE, VIEW_TABLE), - (OTHER_VIEW_TABLE, OTHER_VIEW_TABLE), - ]); - let wanted = BTreeMap::from([( - VIEW_TARGET, - Wanted { - kind: Kind::Function, - candidates: None, - class: None, - command: None, - loose: Vec::new(), - }, - )]); - let tables = BTreeSet::from([VIEW_TABLE, OTHER_VIEW_TABLE]); - let views: BTreeSet = views.iter().copied().collect(); - resolve(&old, &new, &known, &wanted, &tables, &views) - } - - #[test] - fn nfr6_a_virtual_function_is_read_from_its_views_class_table_by_slot() { - // Both tables moved the slot by one: the slot number is found twice, and the function is - // the one the first table holds there. - let resolution = run_views([true, true], &[VIEW_TABLE, OTHER_VIEW_TABLE]); - assert_eq!(resolution.places.get(&VIEW_TARGET), Some(&VIEW_TARGET)); - assert_eq!( - resolution.settled, - ["0x105000 -> 0x105000 by its table slot and its slot shift"] - ); - } - - #[test] - fn nfr6_a_virtual_function_needs_a_second_views_table_to_agree_on_its_slot() { - // Without a second table of a views class, the slot is found once. - let alone = run_views([true, true], &[VIEW_TABLE]); - assert!(alone.places.is_empty()); - let reason = &alone.reasons[&VIEW_TARGET]; - assert!( - reason.starts_with("only its table slot found it"), - "{reason}" - ); - // A second table that lines the slot up another way confirms nothing. - let apart = run_views([true, false], &[VIEW_TABLE, OTHER_VIEW_TABLE]); - assert!(apart.places.is_empty()); - let reason = &apart.reasons[&VIEW_TARGET]; - assert!( - reason.starts_with("only its table slot found it"), - "{reason}" - ); - } - - /// push rbx; mov ebx, 5; xor eax, eax; call `first`; [call `second`;] nop; pop rbx; ret: a - /// caller whose body around the call changed, so no call site of it pairs with the prior one. - fn changed_caller(at: u32, first: u32, second: Option) -> Vec { - let mut bytes = vec![0x53, 0xBB, 0x05, 0, 0, 0, 0x31, 0xC0]; - bytes.extend(call(at + bytes.len() as u32, first)); - if let Some(second) = second { - bytes.extend(call(at + bytes.len() as u32, second)); - } - bytes.extend([0x90, 0x5B, 0xC3]); - bytes - } - - fn run_known_caller(second: Option) -> Resolution { - let old_bytes = old_module(); - let caller = changed_caller(NEW_CALLER, NEW_TARGETS[0], second); - let new_bytes = module( - &[ - (NEW_CALLER, caller), - (NEW_TARGETS[0], TARGET.to_vec()), - (NEW_TARGETS[1], TARGET.to_vec()), - ], - &[ - (NEW_CALLER, NEW_CALLER + 24), - (NEW_TARGETS[0], NEW_TARGETS[0] + 14), - (NEW_TARGETS[1], NEW_TARGETS[1] + 14), - ], - ); - let old = PeFile::parse(&old_bytes).unwrap(); - let new = PeFile::parse(&new_bytes).unwrap(); - let known = BTreeMap::from([(OLD_CALLER, NEW_CALLER)]); - let wanted = BTreeMap::from([( - OLD_TARGET, - Wanted { - kind: Kind::Function, - candidates: Some(NEW_TARGETS.to_vec()), - class: None, - command: None, - loose: Vec::new(), - }, - )]); - let none = BTreeSet::new(); - resolve(&old, &new, &known, &wanted, &none, &none) - } - - #[test] - fn nfr6_a_drawing_helper_is_not_placed_by_its_caller_alone() { - // The caller, as a frame view's paint calls `DrawColor`, is known in both builds, and of - // the two places the helper's fingerprint matched, its new body calls one. That call is the - // same kind of fact as the calls into it, and the fingerprint matched both places, so it is - // one method and the helper waits for a second one. - let resolution = run_known_caller(None); - assert!(resolution.places.is_empty(), "{:?}", resolution.places); - assert!(resolution.settled.is_empty(), "{:?}", resolution.settled); - } - - #[test] - fn nfr6_a_caller_that_calls_every_fingerprint_place_names_no_helper() { - let resolution = run_known_caller(Some(NEW_TARGETS[1])); - assert!(resolution.places.is_empty()); - assert_eq!(resolution.reasons[&OLD_TARGET], "no method found it"); - } - - #[test] - fn nfr6_a_place_outside_the_fingerprint_matches_is_refused() { - let answers = [(Method::CallsInto, 0x103300), (Method::TableSlot, 0x103300)]; - let refused = decide(&answers, Some(&NEW_TARGETS[..])).unwrap_err(); - assert!( - refused.contains("not one of its fingerprint's places"), - "{refused}" - ); - let (place, methods) = decide(&answers, None).unwrap(); - assert_eq!(place, 0x103300); - assert_eq!(methods.len(), 2); - assert_eq!(decide(&[], None).unwrap_err(), "no method found it"); - } - #[test] - fn nfr6_a_table_a_class_name_gives_is_checked_by_the_slots_it_shares_with_a_known_table() { - // Two classes of one base hold the base's functions in the same slots. Edge 157's caption - // button table was named by its class, and what it shares with the frame's table checks it. - let functions: Vec = (0..12u32).map(|n| 0x101400 + 0x10 * n).collect(); - let mut parts: Vec<(u32, Vec)> = functions - .iter() - .enumerate() - .map(|(n, at)| (*at, small(n as u8))) - .collect(); - let mut own = functions.clone(); - own[10] = 0x101600; - own[11] = 0x101610; - parts.push((0x101600, small(40))); - parts.push((0x101610, small(41))); - // A table of other functions throughout shares nothing. - let other: Vec = (0..12u32).map(|n| 0x101700 + 0x10 * n).collect(); - parts.extend( - other - .iter() - .enumerate() - .map(|(n, at)| (*at, small(50 + n as u8))), - ); - parts.push((0x200100, table(&functions))); - parts.push((0x200300, table(&own))); - parts.push((0x200500, table(&other))); - let bytes = module(&parts, &[]); - let pe = PeFile::parse(&bytes).unwrap(); - assert_eq!(shared_slots(&pe, 0x200300, 0x200100), 10); - let (old, new) = (Side::new(&pe), Side::new(&pe)); - let pairs = [(0x200100, 0x200100)]; - assert!(by_sibling(&old, &new, &pairs, 0x200300, 0x200300)); - assert!(!by_sibling(&old, &new, &pairs, 0x200300, 0x200500)); - // The known table itself is no check of its own place. - assert!(!by_sibling(&old, &new, &pairs, 0x200100, 0x200100)); - } - #[test] - fn nfr6_a_function_is_placed_by_the_lengths_of_the_functions_beside_it() { - let lengths = [0x30, 0x48, 0x21, 0x90, 0x17, 0x64, 0x52, 0x3d, 0x71, 0x2a]; - let starts = |from: u32, lengths: &[u32]| -> BTreeSet { - let mut at = from; - let mut out = BTreeSet::from([at]); - for length in lengths { - at += length; - out.insert(at); - } - out - }; - let old = Lengths::new(&starts(0x1000, &lengths)); - // The new build has another function in front, so every place moved. - let mut moved = vec![0x500]; - moved.extend(lengths); - let new = Lengths::new(&starts(0x2000, &moved)); - assert_eq!(by_neighbours(&old, &new, 0x1000), Some(0x2500)); - assert_eq!(by_neighbours(&old, &new, 0x1030), Some(0x2530)); - // The last functions are placed by those before them. - let last = 0x1000 + lengths.iter().sum::(); - assert_eq!(by_neighbours(&old, &new, last), Some(last + 0x1500)); - // An address that starts no function has no neighbours. - assert_eq!(by_neighbours(&old, &new, 0x1004), None); - // A run the new build holds twice names no place. - let mut twice = moved.clone(); - twice.extend(lengths); - let new = Lengths::new(&starts(0x2000, &twice)); - assert_eq!(by_neighbours(&old, &new, 0x1000), None); - // A row of stubs of one length says nothing. - let old = Lengths::new(&starts(0x1000, &[0x10; 10])); - let new = Lengths::new(&starts(0x2000, &[0x10; 8])); - assert_eq!(by_neighbours(&old, &new, 0x1000), None); - } - #[test] - fn nfr6_a_function_is_placed_by_the_call_several_placed_callers_make() { - // Twelve functions of twelve lengths, the first `calling` of which call the target, which - // comes last. The new build has one more function in front. - let build = |shift: u32, calling: usize, target: u32| -> Vec { - let mut parts = Vec::new(); - let mut ranges = Vec::new(); - let mut at = 0x100000; - if shift > 0 { - parts.push((at, vec![0xC3])); - ranges.push((at, at + shift)); - at += shift; - } - for index in 0..12u32 { - let length = 0x10 + index * 4; - let mut body = Vec::new(); - if (index as usize) < calling { - body.extend(call(at, target)); - } - body.push(0xC3); - parts.push((at, body)); - ranges.push((at, at + length)); - at += length; - } - parts.push((target, vec![0xC3])); - ranges.push((target, target + 0x10)); - module(&parts, &ranges) - }; - let place = |calling: usize| -> Option<(u32, usize)> { - let (old_bytes, new_bytes) = - (build(0, calling, 0x100300), build(0x40, calling, 0x100380)); - let old_pe = PeFile::parse(&old_bytes).unwrap(); - let new_pe = PeFile::parse(&new_bytes).unwrap(); - let lengths = ( - &Lengths::new(&old_pe.function_starts()), - &Lengths::new(&new_pe.function_starts()), - ); - let (mut old, mut new) = (Side::new(&old_pe), Side::new(&new_pe)); - let callers = calls_into(&old, &BTreeSet::from([0x100300])); - by_callers(&mut old, &mut new, lengths, &callers[&0x100300], 0x100300) - }; - assert_eq!(place(3), Some((0x100380, 3))); - // Two callers are too few to stand. - assert_eq!(place(2), None); - } - #[test] - fn nfr6_two_functions_of_the_same_instructions_have_the_same_shape() { - // Nine instructions that read a member, with another offset in the new build. - let body = |offset: u8| -> Vec { - let mut bytes = vec![0x56, 0x57, 0x53, 0x48, 0x83, 0xEC, 0x20]; - bytes.extend([0x48, 0x8B, 0x41, offset]); - bytes.extend([ - 0x48, 0x89, 0xC6, 0x48, 0x83, 0xC4, 0x20, 0x5B, 0x5F, 0x5E, 0xC3, - ]); - bytes - }; - let old_bytes = module(&[(0x100000, body(0x18))], &[(0x100000, 0x100016)]); - let mut other = body(0x10); - other[2] = 0x55; - let new_bytes = module( - &[ - (0x100100, body(0x10)), - (0x100200, other), - (0x100300, vec![0xC3]), - ], - &[ - (0x100100, 0x100116), - (0x100200, 0x100216), - (0x100300, 0x100301), - ], - ); - let old_pe = PeFile::parse(&old_bytes).unwrap(); - let new_pe = PeFile::parse(&new_bytes).unwrap(); - let (mut old, mut new) = (Side::new(&old_pe), Side::new(&new_pe)); - assert!(same_shape(&mut old, &mut new, 0x100000, 0x100100)); - // Another register saved is another function. - assert!(!same_shape(&mut old, &mut new, 0x100000, 0x100200)); - // A short function has no shape of its own. - assert!(!same_shape(&mut new, &mut old, 0x100300, 0x100300)); - } -} diff --git a/rivet/platform/windows/src/test_module.rs b/rivet/platform/windows/src/test_module.rs new file mode 100644 index 0000000..81c72e1 --- /dev/null +++ b/rivet/platform/windows/src/test_module.rs @@ -0,0 +1,95 @@ +//! Small 64-bit modules that tests build byte by byte, so the finder is checked on code whose every +//! instruction is known. + +pub const IMAGE_BASE: u64 = 0x1_8000_0000; +/// Where a module keeps its exception table, in its data section. +const EXCEPTIONS: u32 = 0x20f000; + +fn place(rva: u32) -> usize { + if rva >= 0x200000 { + 0x10400 + (rva - 0x200000) as usize + } else { + 0x400 + (rva - 0x100000) as usize + } +} + +/// A 64-bit module with a code section at 0x100000 and a data section at 0x200000, each 0x10000 +/// long, holding the given bytes and an exception table that lists `ranges`. Code between +/// functions is padding. +pub fn module(parts: &[(u32, Vec)], ranges: &[(u32, u32)]) -> Vec { + let entries: Vec<(u32, u32, u32)> = ranges.iter().map(|(start, end)| (*start, *end, 0)).collect(); + module_with_unwind(parts, &entries) +} + +/// `module`, with the unwind data address of each exception table entry given. +pub fn module_with_unwind(parts: &[(u32, Vec)], entries: &[(u32, u32, u32)]) -> Vec { + let mut bytes = vec![0u8; 0x400]; + bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes()); + bytes[0x80..0x84].copy_from_slice(b"PE\0\0"); + bytes[0x86..0x88].copy_from_slice(&2u16.to_le_bytes()); + bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes()); + bytes[0x98..0x9a].copy_from_slice(&0x20bu16.to_le_bytes()); + bytes[0x98 + 24..0x98 + 32].copy_from_slice(&IMAGE_BASE.to_le_bytes()); + let sections = [ + (0x100000u32, 0x400u32, 0x2000_0000u32), + (0x200000, 0x10400, 0x4000_0000), + ]; + for (index, (rva, raw, flags)) in sections.iter().enumerate() { + let header = 0x98 + 240 + 40 * index; + bytes[header + 8..header + 12].copy_from_slice(&0x10000u32.to_le_bytes()); + bytes[header + 12..header + 16].copy_from_slice(&rva.to_le_bytes()); + bytes[header + 16..header + 20].copy_from_slice(&0x10000u32.to_le_bytes()); + bytes[header + 20..header + 24].copy_from_slice(&raw.to_le_bytes()); + bytes[header + 36..header + 40].copy_from_slice(&flags.to_le_bytes()); + } + bytes.resize(0x400 + 0x20000, 0); + bytes[0x400..0x10400].fill(0xCC); + // The exception table is sorted by start, as a linker writes it. + let mut sorted = entries.to_vec(); + sorted.sort_unstable(); + let mut table = vec![]; + for (start, end, unwind) in sorted { + table.extend_from_slice(&start.to_le_bytes()); + table.extend_from_slice(&end.to_le_bytes()); + table.extend_from_slice(&unwind.to_le_bytes()); + } + let directory = 0x98 + 112 + 24; + bytes[directory..directory + 4].copy_from_slice(&EXCEPTIONS.to_le_bytes()); + bytes[directory + 4..directory + 8].copy_from_slice(&(table.len() as u32).to_le_bytes()); + let at = place(EXCEPTIONS); + bytes[at..at + table.len()].copy_from_slice(&table); + for (rva, data) in parts { + let at = place(*rva); + bytes[at..at + data.len()].copy_from_slice(data); + } + bytes +} + +/// `call to`, placed at `from`. +pub fn call(from: u32, to: u32) -> Vec { + let mut bytes = vec![0xE8]; + bytes.extend_from_slice(&((i64::from(to) - i64::from(from) - 5) as i32).to_le_bytes()); + bytes +} + +/// `lea reg, [rip + to]`, placed at `from`, for `rcx` (`register` 1) and the other low registers. +pub fn lea(from: u32, register: u8, to: u32) -> Vec { + let mut bytes = vec![0x48, 0x8D, 0x05 | (register << 3)]; + bytes.extend_from_slice(&((i64::from(to) - i64::from(from) - 7) as i32).to_le_bytes()); + bytes +} + +/// A class table of the given functions. +pub fn table(functions: &[u32]) -> Vec { + functions + .iter() + .flat_map(|function| (IMAGE_BASE + u64::from(*function)).to_le_bytes()) + .collect() +} + +/// A zero-terminated text. +pub fn text(value: &str) -> Vec { + let mut bytes = value.as_bytes().to_vec(); + bytes.push(0); + bytes +} diff --git a/rivet/platform/windows/src/x64.rs b/rivet/platform/windows/src/x64.rs new file mode 100644 index 0000000..84cc619 --- /dev/null +++ b/rivet/platform/windows/src/x64.rs @@ -0,0 +1,328 @@ +//! A function's instructions, read as far as the row finder needs them. + +/// One decoded instruction: its length, where its RIP-relative displacement or relative branch +/// target is, where a displacement from a register is, as in `[rcx + 0x558]`, and where its +/// immediate value is. Each place is `(offset, size)` within the instruction. +#[derive(Debug, PartialEq, Eq, Clone, Copy)] +pub struct Instruction { + pub length: usize, + pub relative: Option<(usize, usize)>, + pub displacement: Option<(usize, usize)>, + pub immediate: Option<(usize, usize)>, +} + +impl Instruction { + fn plain(length: usize) -> Self { + Self { + length, + relative: None, + displacement: None, + immediate: None, + } + } + + /// An instruction whose last `size` bytes, from `at`, are an immediate value. + fn with_immediate(at: usize, size: usize) -> Self { + Self { + length: at + size, + relative: None, + displacement: None, + immediate: Some((at, size)), + } + } + + /// A branch whose last `size` bytes, from `at`, are the distance to its target. + fn branch(at: usize, size: usize) -> Self { + Self { + length: at + size, + relative: Some((at, size)), + displacement: None, + immediate: None, + } + } +} + +fn modrm(bytes: &[u8], at: usize, immediate: usize) -> Option { + let byte = *bytes.get(at)?; + let (mode, rm) = (byte >> 6, byte & 7); + let mut length = at + 1; + let mut relative = None; + let mut displacement = None; + if mode != 3 && rm == 4 { + let sib = *bytes.get(length)?; + length += 1; + if mode == 0 && sib & 7 == 5 { + displacement = Some((length, 4)); + length += 4; + } + } + match mode { + 0 if rm == 5 => { + relative = Some((length, 4)); + length += 4; + } + 1 => { + displacement = Some((length, 1)); + length += 1; + } + 2 => { + displacement = Some((length, 4)); + length += 4; + } + _ => {} + } + Some(Instruction { + length: length + immediate, + relative, + displacement, + immediate: (immediate > 0).then_some((length, immediate)), + }) +} + +/// Decodes the instruction at the start of `bytes`, or `None` for one this does not know. The +/// list covers what function starts are made of, and anything else goes to a person. +pub fn decode(bytes: &[u8]) -> Option { + decode_with(bytes, false) +} + +/// Decodes as `decode` does, and also the instructions met inside a function body: lock and +/// segment prefixes, string and x87 instructions, VEX encoded vector instructions and more of +/// the two and three byte opcodes. It reads bodies to follow calls and operands, and never +/// judges a guard, so what a hook may copy stays as `decode` says. +pub fn decode_body(bytes: &[u8]) -> Option { + decode_with(bytes, true) +} + +fn decode_with(bytes: &[u8], body: bool) -> Option { + let mut at = 0; + let mut wide_operand = false; + let mut rex_w = false; + loop { + match *bytes.get(at)? { + 0x66 => wide_operand = true, + 0xF2 | 0xF3 => {} + 0xF0 | 0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 if body => {} + _ => break, + } + at += 1; + } + if bytes.get(at)? & 0xF0 == 0x40 { + rex_w = bytes[at] & 8 != 0; + at += 1; + } + let opcode = *bytes.get(at)?; + at += 1; + let word = if wide_operand { 2 } else { 4 }; + match opcode { + 0x50..=0x5F | 0x90 | 0xC3 | 0xCC | 0x99 => Some(Instruction::plain(at)), + 0x98 => Some(Instruction::plain(at)), + 0x00..=0x03 + | 0x08..=0x0B + | 0x10..=0x13 + | 0x18..=0x1B + | 0x20..=0x23 + | 0x28..=0x2B + | 0x30..=0x33 + | 0x38..=0x3B + | 0x63 + | 0x84..=0x8B + | 0x8D + | 0x8F + | 0xD0..=0xD3 + | 0xFE + | 0xFF => modrm(bytes, at, 0), + 0x04 | 0x0C | 0x14 | 0x1C | 0x24 | 0x2C | 0x34 | 0x3C | 0x6A | 0xA8 | 0xB0..=0xB7 => { + Some(Instruction::with_immediate(at, 1)) + } + 0x05 | 0x0D | 0x15 | 0x1D | 0x25 | 0x2D | 0x35 | 0x3D | 0x68 | 0xA9 => { + Some(Instruction::with_immediate(at, word)) + } + 0xB8..=0xBF => Some(Instruction::with_immediate( + at, + if rex_w { 8 } else { word }, + )), + 0x80 | 0x83 | 0xC0 | 0xC1 | 0xC6 | 0x6B => modrm(bytes, at, 1), + 0x81 | 0xC7 | 0x69 => modrm(bytes, at, word), + 0xF6 => { + let immediate = usize::from((bytes.get(at)? >> 3) & 7 < 2); + modrm(bytes, at, immediate) + } + 0xF7 => { + let immediate = if (bytes.get(at)? >> 3) & 7 < 2 { + word + } else { + 0 + }; + modrm(bytes, at, immediate) + } + 0x70..=0x7F | 0xEB => Some(Instruction::branch(at, 1)), + 0xE8 | 0xE9 => Some(Instruction::branch(at, 4)), + 0x0F => { + let second = *bytes.get(at)?; + at += 1; + match second { + 0x80..=0x8F => Some(Instruction::branch(at, 4)), + 0x10..=0x17 + | 0x1E + | 0x1F + | 0x28..=0x2F + | 0x40..=0x6F + | 0x7E + | 0x7F + | 0x90..=0x9F + | 0xAF + | 0xB6 + | 0xB7 + | 0xBE + | 0xBF + | 0xD6 + | 0xEF => modrm(bytes, at, 0), + _ if body => body_two_byte(bytes, at, second), + _ => None, + } + } + _ if body => body_one_byte(bytes, at, opcode), + _ => None, + } +} + +/// One byte opcodes that only a function body holds. `at` is just past the opcode. +fn body_one_byte(bytes: &[u8], at: usize, opcode: u8) -> Option { + match opcode { + 0x91..=0x97 | 0x9C..=0x9F | 0xA4..=0xA7 | 0xAA..=0xAF | 0xC9 | 0xF4 | 0xF5 => { + Some(Instruction::plain(at)) + } + 0xF8..=0xFD => Some(Instruction::plain(at)), + 0xC2 => Some(Instruction::with_immediate(at, 2)), + 0xCD => Some(Instruction::with_immediate(at, 1)), + 0xD8..=0xDF => modrm(bytes, at, 0), + 0xE0..=0xE3 => Some(Instruction::branch(at, 1)), + // Two byte VEX: one payload byte, then an opcode of the 0F map. + 0xC5 => { + let opcode = *bytes.get(at + 1)?; + modrm(bytes, at + 2, vex_immediate(1, opcode)) + } + // Three byte VEX: the map in the first payload byte, then one more payload byte. + 0xC4 => { + let map = bytes.get(at)? & 0x1F; + let opcode = *bytes.get(at + 2)?; + modrm(bytes, at + 3, vex_immediate(map, opcode)) + } + _ => None, + } +} + +/// Whether a VEX instruction of `map` ends in an immediate byte. +fn vex_immediate(map: u8, opcode: u8) -> usize { + match map { + 3 => 1, + 1 => usize::from(matches!(opcode, 0x70..=0x73 | 0xC2 | 0xC4..=0xC6)), + _ => 0, + } +} + +/// Two byte opcodes that only a function body holds. `at` is just past the second byte. +fn body_two_byte(bytes: &[u8], at: usize, second: u8) -> Option { + match second { + 0x0B | 0x31 | 0x77 | 0xA2 | 0xC8..=0xCF => Some(Instruction::plain(at)), + 0x0D + | 0x18..=0x1D + | 0x74..=0x76 + | 0x7C + | 0x7D + | 0xA3 + | 0xA5 + | 0xAB + | 0xAD + | 0xAE + | 0xB0 + | 0xB1 + | 0xB3 + | 0xB8 + | 0xBB + | 0xBC + | 0xBD + | 0xC0 + | 0xC1 + | 0xC3 + | 0xC7 + | 0xD0..=0xD5 + | 0xD7..=0xEE + | 0xF0..=0xFE => modrm(bytes, at, 0), + 0x70..=0x73 | 0xA4 | 0xAC | 0xBA | 0xC2 | 0xC4..=0xC6 => modrm(bytes, at, 1), + 0x38 => modrm(bytes, at + 1, 0), + 0x3A => modrm(bytes, at + 1, 1), + _ => None, + } +} + +/// The instruction boundaries within `bytes`, and whether all of them could be read up to `length`. +pub fn boundaries(bytes: &[u8], length: usize) -> (Vec, bool) { + let mut at = 0; + let mut seen = vec![]; + while at < length { + match decode(&bytes[at..]) { + Some(instruction) => { + at += instruction.length; + seen.push(at); + } + None => return (seen, false), + } + } + (seen, true) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::chrome_build::hex; + + #[test] + fn nfr3_x64_lengths_of_real_function_starts() { + // A frame setup that ends at byte 13. + let chip = hex("4156565755534881eca00000004889").unwrap(); + let mut padded = chip.clone(); + padded.resize(40, 0x90); + let (seen, complete) = boundaries(&padded, 15); + assert!(complete); + assert_eq!(&seen[..6], [2, 3, 4, 5, 6, 13]); + assert!(!seen.contains(&15)); + // A stack cookie load is RIP-relative. + let cookie = hex("56574883ec784889ce488b0510640810").unwrap(); + let (seen, _) = boundaries(&cookie, cookie.len()); + assert_eq!(seen.last(), Some(&16)); + assert!(decode(&cookie[9..]).unwrap().relative.is_some()); + // movss, ucomiss with a displacement, jne. + let corners = hex("f30f10020f2e81840400007533").unwrap(); + assert_eq!(boundaries(&corners, 13).0, [4, 11, 13]); + } + + #[test] + fn nfr3_an_unknown_instruction_is_not_guessed() { + assert_eq!(decode(&[0x0F, 0x05]), None); + assert_eq!(boundaries(&[0x56, 0xCF, 0x90], 3), (vec![1], false)); + } + + #[test] + fn nfr6_the_operands_of_a_body_instruction_are_located() { + // mov rax, [rcx + 0x558]: a displacement of four bytes from the third byte. + let load = decode(&[0x48, 0x8B, 0x81, 0x58, 0x05, 0x00, 0x00]).unwrap(); + assert_eq!(load.displacement, Some((3, 4))); + assert_eq!(load.immediate, None); + // call [rax + 0x2b8]: a table slot read through its displacement. + let call = decode(&[0xFF, 0x90, 0xB8, 0x02, 0x00, 0x00]).unwrap(); + assert_eq!(call.displacement, Some((2, 4))); + // mov edx, 0x9c45, and cmp byte [rcx + 0x30], 1. + let id = decode(&[0xBA, 0x45, 0x9C, 0x00, 0x00]).unwrap(); + assert_eq!(id.immediate, Some((1, 4))); + let compare = decode(&[0x80, 0x79, 0x30, 0x01]).unwrap(); + assert_eq!(compare.displacement, Some((2, 1))); + assert_eq!(compare.immediate, Some((3, 1))); + // lock cmpxchg and a VEX move decode only as body instructions. + let lock = [0xF0, 0x48, 0x0F, 0xB1, 0x51, 0x08]; + assert_eq!(decode(&lock), None); + assert_eq!(decode_body(&lock).unwrap().displacement, Some((5, 1))); + let vex = [0xC5, 0xF8, 0x10, 0x41, 0x10]; + assert_eq!(decode_body(&vex).unwrap().length, 5); + } +} diff --git a/scripts/tests/browser-rows.test.sh b/scripts/tests/browser-rows.test.sh index 111771d..818673e 100755 --- a/scripts/tests/browser-rows.test.sh +++ b/scripts/tests/browser-rows.test.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash -# The scheduled job is what keeps Rivet ahead of browser updates, and it only runs from the default -# branch, so nothing shows a broken one until a build is already missed. These are the promises it -# must keep. +# The scheduled job tests the row finder on each new browser build, and it only runs from the +# default branch, so nothing shows a broken one until a build is already missed. These are the +# promises it must keep. set -uo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" @@ -18,19 +18,20 @@ expect() { expect "runs on a schedule" "schedule:" expect "watches Chrome's version history" "versionhistory.googleapis.com/v1/chrome/platforms/win64/channels" expect "reads versions at any rollout fraction" "filter=endtime=none" -expect "watches Chrome beta for the next milestone" "/beta/versions" expect "watches Edge" "edgeupdates.microsoft.com/api/products" expect "watches Brave" "repos/brave/brave-browser/releases" -expect "proves a row on the real browser" "windows-row-proof.ps1" -expect "does not publish a row that needs review" "steps.made.outputs.for_review == 'false'" -expect "publishes a signed table" "table-sign" -expect "signs with a secret" "secrets.RIVET_TABLE_SIGNING_KEY" -expect "makes each row from the prior row and the prior build's module" 'chrome-builds.exe find "$temp/prior.json" $env:PRIOR_MODULE' -expect "fingerprints a new row from its own module" "chrome-builds.exe fingerprint" -expect "scores the generator against verified rows" "scripts/tests/row-score.ps1" -expect "a score run makes no row" "github.event.inputs.score == ''" -expect "a trial run publishes nothing" "needs.row.result != 'skipped' && !inputs.trial" -expect "a trial run proposes nothing" "steps.made.outputs.for_review == 'true' && !inputs.trial" +expect "runs the finder on one build" 'chrome-builds.exe find "${{ steps.build.outputs.module }}"' +expect "uploads the finder's report" 'finder-${{ matrix.build.browser }}' +expect "scores the finder against verified rows" "scripts/tests/row-score.ps1" +expect "only reads the repository" "contents: read" + +# The job tests the finder. It makes, signs and publishes no row, and opens no pull request. +for forbidden in "table-sign" "table-add" "gh pr create" "gh release upload" "RIVET_TABLE_SIGNING_KEY" "contents: write" "pull-requests: write" "issues: write"; do + if grep -qF -- "$forbidden" "$workflow"; then + echo "browser-rows.yml: the test job must not use '$forbidden'" >&2 + failed=1 + fi +done if [[ -e "$repo_root/.github/workflows/chrome-support.yml" ]]; then echo "chrome-support.yml covers Chrome only and is replaced by browser-rows.yml" >&2 @@ -50,7 +51,7 @@ for promise in RIVET_TABLE_PUBLIC_KEY RIVET_TABLE_URL "releases/download/builds- fi done if grep -qF -- "-AsArray -InputObject" "$workflow"; then - echo "browser-rows.yml: -AsArray -InputObject makes a list inside a list, and the row job then has no build" >&2 + echo "browser-rows.yml: -AsArray -InputObject makes a list inside a list, and the find job then has no build" >&2 failed=1 fi exit "$failed" diff --git a/scripts/tests/no-pdb.test.sh b/scripts/tests/no-pdb.test.sh index 090b618..76196da 100755 --- a/scripts/tests/no-pdb.test.sh +++ b/scripts/tests/no-pdb.test.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash -# Fails if code, scripts or workflows download or read a browser's debug symbols. Rivet and its row -# generator make every row from the verified prior row, its fingerprints and the two builds' -# modules: a maker can ship a build long before its symbols appear, or never publish them, so -# nothing may wait on them. The rows already verified with symbols stay as the starting point. +# Fails if code, scripts or workflows download or read a browser's debug symbols. Rivet's row finder +# finds every value in the build's own binary by descriptions written from public source: a maker +# can ship a build long before its symbols appear, or never publish them, so nothing may wait on +# them. set -uo pipefail repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" diff --git a/scripts/tests/row-score.ps1 b/scripts/tests/row-score.ps1 index 1e1cd81..58345c1 100644 --- a/scripts/tests/row-score.ps1 +++ b/scripts/tests/row-score.ps1 @@ -1,14 +1,14 @@ param( # rivet-rows.exe, which prints the rows Rivet knows. [Parameter(Mandatory = $true)][string]$Rows, - # chrome-builds.exe, the row generator. - [Parameter(Mandatory = $true)][string]$Generator, + # chrome-builds.exe, which holds the row finder. + [Parameter(Mandatory = $true)][string]$Finder, # The checked-in table, whose rows count as verified like those built into rivet-rows. [Parameter(Mandatory = $true)][string]$Table, # Where the modules, rows and scores go. Removed and made again. [Parameter(Mandatory = $true)][string]$Work, - # `browser@prior>new` pairs. Empty means the list below. - [string[]]$Pairs = @(), + # `browser@version` builds. Empty means the list below. + [string[]]$Builds = @(), # Fetches each build with .github/scripts/rows/fetch-browser.ps1. Without it, each module is # taken from `$Modules\\\`. [switch]$Fetch, @@ -16,26 +16,19 @@ param( ) $ErrorActionPreference = 'Stop' -# Scores the row generator against answer keys: builds whose rows people verified, made from -# public symbols before Rivet stopped reading them. Each new row is made without symbols from the -# verified row of an older build, the way the row job makes rows, and compared value by value with -# the verified row of the new build. Per feature it reports values found and equal, values found -# but different, and features the made row turns off because their values were not found. +# Scores the row finder against builds whose rows people verified. The finder reads only the build +# at hand, by the checked-in descriptions, and each value it finds is compared with the verified +# row of the same build. Per feature it reports hits, wrong values and values not found. # -# A value found but different is a wrong value, which would reach people's browsers, so any fails -# this script. A feature turned off is not a failure: the runtime keeps it off. A pair whose builds -# cannot be fetched is reported and skipped, and a run that scores no pair fails, since it measured -# nothing. Nothing is published or proposed. -# -# A build newer than every verified row, such as Chrome 158 while the newest verified row is 157, -# has no answer key and cannot be scored here. -if (-not $Pairs -or $Pairs.Count -eq 0) { - $Pairs = @( - 'Google Chrome@156.0.8078.82>157.0.8103.38', - 'Google Chrome@156.0.8078.82>157.0.8103.39', - 'Google Chrome@156.0.8078.74>156.0.8078.80', - 'Microsoft Edge@156.0.4314.50>156.0.4314.58', - 'Brave@156.1.98.63>157.1.99.55' +# A wrong value would reach people's browsers, so any fails this script. A value not found is not a +# failure: its feature stays off. A build that cannot be fetched is reported and skipped, and a run +# that scores no build fails, since it measured nothing. Nothing is published or proposed. +if (-not $Builds -or $Builds.Count -eq 0) { + $Builds = @( + 'Google Chrome@156.0.8078.81', + 'Google Chrome@156.0.8078.82', + 'Google Chrome@157.0.8103.39', + 'Microsoft Edge@156.0.4314.58' ) } @@ -67,32 +60,28 @@ function Get-VerifiedRow($browser, $version, $file) { $scored = 0 $wrong = 0 $failed = @() -foreach ($pair in $Pairs) { - $browser, $versions = $pair -split '@', 2 - $prior, $new = $versions -split '>', 2 - $slug = ($browser -replace ' ', '-') + "-$prior-to-$new" - $priorRow = Join-Path $Work "$slug-prior.json" +foreach ($build in $Builds) { + $browser, $version = $build -split '@', 2 + $slug = ($browser -replace ' ', '-') + "-$version" $verified = Join-Path $Work "$slug-verified.json" $score = Join-Path $Work "$slug-score.json" try { - Get-VerifiedRow $browser $prior $priorRow - Get-VerifiedRow $browser $new $verified - $priorModule = Find-BuildModule $browser $prior - $module = Find-BuildModule $browser $new + Get-VerifiedRow $browser $version $verified + $module = Find-BuildModule $browser $version } catch { - "skip ${browser} $prior -> ${new}: $_" + "skip ${browser} ${version}: $_" continue } - & $Generator score $priorRow $priorModule $module $verified $score + & $Finder score $module $verified $score switch ($LASTEXITCODE) { 0 { $scored++ } 5 { $scored++; $wrong++ } - default { $failed += "$browser $prior -> $new (chrome-builds exited with $LASTEXITCODE)" } + default { $failed += "$browser $version (chrome-builds exited with $LASTEXITCODE)" } } } -"scored $scored of $($Pairs.Count) pairs; $wrong with a wrong value" -if ($failed.Count -gt 0) { throw "NFR-6: the generator failed on: $($failed -join '; ')" } -if ($wrong -gt 0) { throw 'NFR-6: a row made without symbols holds a value that differs from its verified row.' } -if ($scored -eq 0) { throw 'NFR-6: no pair could be scored, so nothing was measured.' } -'NFR-6: every value the generator found equals the verified row.' +"scored $scored of $($Builds.Count) builds; $wrong with a wrong value" +if ($failed.Count -gt 0) { throw "NFR-6: the finder failed on: $($failed -join '; ')" } +if ($wrong -gt 0) { throw 'NFR-6: the finder found a value that differs from its verified row.' } +if ($scored -eq 0) { throw 'NFR-6: no build could be scored, so nothing was measured.' } +'NFR-6: every value the finder found equals the verified row.'