Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22d833d569 | ||
|
|
a80fb38311 | ||
|
|
f74bbbd4bd | ||
|
|
e54a98c845 | ||
|
|
0e0bf5bb56 | ||
|
|
192465422e | ||
|
|
17d81b0ef5 | ||
|
|
486843dd0a | ||
|
|
78a40f39ec | ||
|
|
ea3fcb7745 | ||
|
|
c87e081c8d | ||
|
|
1b3a5f9711 | ||
|
|
d5e0a8e265 | ||
|
|
e758f539af | ||
|
|
eae84e8bff | ||
|
|
11bc5c4e04 | ||
|
|
6ff3d0ae98 | ||
|
|
eeb4497b85 | ||
|
|
3393756ec4 | ||
|
|
ee2a6c7659 | ||
|
|
f67459e46e | ||
|
|
b1df296439 | ||
|
|
9ae78d6e89 | ||
|
|
194a20a333 | ||
|
|
cd23a46923 | ||
|
|
f6ad6b84c1 | ||
|
|
bb109f10c1 | ||
|
|
6d84d33da8 | ||
|
|
9361f192db | ||
|
|
60647811ca | ||
|
|
e94a4be368 | ||
|
|
b97c2cfd2d | ||
|
|
2468eecb26 | ||
|
|
15d8368113 | ||
|
|
98972f7131 | ||
|
|
d67f790c9d | ||
|
|
f5ccaf8aba |
No files matched your search
@@ -0,0 +1,49 @@
|
||||
# .forker.yaml — per-fork configuration for Repo Forker.
|
||||
#
|
||||
# The upstream URL and its token are NOT set here. They are set in the Gitea UI:
|
||||
# Settings -> Actions -> Variables & Secrets
|
||||
# UPSTREAM_URL = https://github.com/owner/repo.git (any provider)
|
||||
# UPSTREAM_TOKEN = <token that can read the upstream>
|
||||
# This keeps secrets out of the repo. Everything below is non-secret.
|
||||
#
|
||||
# All values are optional; sensible defaults apply when a key is absent.
|
||||
|
||||
# (unused — Bearer auth needs no username; retained for compatibility)
|
||||
token_user: oauth2
|
||||
|
||||
# Mirror all tags (true/false). Default: true
|
||||
mirror_tags: true
|
||||
|
||||
# Prune branches that were deleted upstream (true/false). Default: true
|
||||
mirror_prune: true
|
||||
|
||||
# Which upstream branches to mirror. "*" = all (default).
|
||||
# Comma-separated list to restrict, e.g. "main,develop" (stray spaces
|
||||
# tolerated). NOTE: pruning is always checked against the FULL upstream
|
||||
# branch set, so a branch outside this filter but still upstream is never
|
||||
# deleted.
|
||||
mirror_branches: "*"
|
||||
|
||||
# When a new upstream tag is mirrored, automatically build + publish a release
|
||||
# on this Gitea (true/false). Default: true
|
||||
on_new_tag: true
|
||||
|
||||
# Also mirror the upstream's existing releases (metadata + assets) via the
|
||||
# provider API (true/false). Default: false
|
||||
mirror_upstream_releases: true
|
||||
|
||||
# Build commands run inside the tag's working tree to produce release assets.
|
||||
# Multiple commands are ';'-separated. Leave empty to skip the local build and
|
||||
# only mirror upstream release assets.
|
||||
# build_cmd: "make && go build -o dist/app ."
|
||||
build_cmd: ""
|
||||
|
||||
# Optional: point to a custom build script (path relative to the forker branch)
|
||||
# instead of build_cmd. If set, build_cmd is ignored.
|
||||
# build_script: "forker/build-custom.sh"
|
||||
build_script: ""
|
||||
|
||||
# Artifacts to attach to the locally-built release. Space-separated globs,
|
||||
# relative to the tag's working tree.
|
||||
# artifacts: "dist/*"
|
||||
artifacts: ""
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Repo Forker — Release (build + publish)
|
||||
|
||||
# Produces a release on this Gitea fork. Two modes (see .forker.yaml):
|
||||
# BUILD — checkout the tag's working tree, run the configured build command,
|
||||
# publish the release (tag + assets) on this Gitea.
|
||||
# MIRROR — mirror the upstream's existing release (metadata + assets).
|
||||
#
|
||||
# NOTE: this workflow is triggered MANUALLY from the UI (workflow_dispatch).
|
||||
# Automatic releases on new tags are handled INLINE by sync.sh, because a
|
||||
# mirrored tag points at an upstream commit whose tree has no .gitea/workflows,
|
||||
# so a "push: tags" trigger would never find this file. See sync.sh.
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: 'Tag to release'
|
||||
required: true
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Run release
|
||||
run: |
|
||||
export GITEA_REPO="${GITEA_OWNER_REPO##*/}"
|
||||
bash forker/release.sh "$TAG"
|
||||
env:
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_OWNER: ${{ gitea.repository_owner }}
|
||||
GITEA_OWNER_REPO: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
UPSTREAM_TOKEN: ${{ secrets.UPSTREAM_TOKEN }}
|
||||
TAG: ${{ inputs.tag }}
|
||||
@@ -0,0 +1,35 @@
|
||||
name: Repo Forker — Runner check
|
||||
|
||||
# Verifies a runner is available for this repo before relying on the cron sync
|
||||
# and local builds. Run it once after forking (or when a sync run is "pending"
|
||||
# for a long time — that usually means no runner is registered for this repo).
|
||||
#
|
||||
# In this Gitea build, runners are repo-scoped: a runner registered on one repo
|
||||
# does NOT serve another. Register a runner for this repo (see README, "Runner").
|
||||
|
||||
on:
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Confirm a runner picked this job up
|
||||
run: |
|
||||
echo "A runner is online and serving this job."
|
||||
echo "OS=$RUNNER_OS Arch=$RUNNER_ARCH"
|
||||
|
||||
- name: Which runner(s) serve this repo
|
||||
env:
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
run: |
|
||||
# The repo-level API does NOT list shared runners, so check the
|
||||
# shared (instance) list too and report which serves the repo.
|
||||
# (The Gitea Actions token has admin scope in this setup; with a
|
||||
# plain repo token the admin call 403s and we say so, not hide it.)
|
||||
curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/repos/${GITEA_OWNER}/${GITEA_REPO}/actions/runners" > /tmp/repo_runners.json
|
||||
curl -sS --max-time 20 -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
"$GITEA_SERVER_URL/api/v1/admin/actions/runners?limit=50" > /tmp/shared_runners.json
|
||||
python3 -c 'import json; R=json.load(open("/tmp/repo_runners.json")).get("runners",[]); S=[r for r in json.load(open("/tmp/shared_runners.json")).get("runners",[]) if r.get("shared")]; print("Repo-scoped runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in R) or "(none)")); print("Shared runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in S) or "(none)")); print("OK: a runner serves this repo." if (R or S) else "WARNING: no runner (repo-scoped or shared) registered - cron runs will stay queued.")'
|
||||
@@ -0,0 +1,82 @@
|
||||
name: Repo Forker — Sync (mirror upstream)
|
||||
|
||||
# Periodically mirrors the upstream repo (all branches, tags, full history) into
|
||||
# this Gitea fork. This is the "worker" job.
|
||||
#
|
||||
# One-time setup (Gitea UI):
|
||||
# Settings -> Actions -> Variables & Secrets
|
||||
# UPSTREAM_URL = https://github.com/owner/repo.git (any provider)
|
||||
# UPSTREAM_TOKEN = <secret: token that can read the upstream>
|
||||
# GITEA_* values below are injected automatically by Gitea Actions.
|
||||
|
||||
on:
|
||||
schedule:
|
||||
# "very periodically" — every 10 minutes. Tune to taste (5-field cron).
|
||||
- cron: '*/10 * * * *'
|
||||
workflow_dispatch: {} # manual trigger from the UI
|
||||
push:
|
||||
branches: [forker] # re-sync when the forker config changes
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
# A cold full-history fetch can exceed the 10-min cron interval (or a
|
||||
# push/dispatch can land mid-run); without this, two overlapping runs
|
||||
# both see the same tag as "missing release" and both build/publish —
|
||||
# duplicate releases + double builds. Serialize per repo (do NOT
|
||||
# cancel-in-progress: an in-flight sync must finish).
|
||||
concurrency:
|
||||
group: sync-${{ gitea.repository }}
|
||||
steps:
|
||||
# A repo without UPSTREAM_URL (e.g. the template itself) is not a mirror:
|
||||
# skip the whole job with a notice instead of failing.
|
||||
- name: Upstream configured?
|
||||
id: check
|
||||
env:
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
run: |
|
||||
if [ -z "$UPSTREAM_URL" ]; then
|
||||
echo "::notice::UPSTREAM_URL is not set — this repo is not configured as a mirror (e.g. the template). No-op."
|
||||
echo "configured=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "configured=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Checkout
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Restore mirror cache
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
uses: actions/cache@v4
|
||||
continue-on-error: true # no cache service configured? continue cold — still correct
|
||||
with:
|
||||
path: .mirror
|
||||
# Unique per run so saves never conflict; restore-keys pulls the most
|
||||
# recent saved mirror (incremental fetch). No cache → full fetch, still
|
||||
# correct.
|
||||
key: forker-mirror-${{ github.run_id }}
|
||||
restore-keys: |
|
||||
forker-mirror-
|
||||
|
||||
- name: Show config
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
run: |
|
||||
echo "UPSTREAM_URL=${UPSTREAM_URL:?set in Gitea UI (Variables & Secrets)}"
|
||||
echo "Gitea repo: ${{ gitea.repository }}"
|
||||
env:
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
|
||||
- name: Run sync
|
||||
if: steps.check.outputs.configured == 'true'
|
||||
run: |
|
||||
# gitea.repository is "owner/repo"; extract just the repo name.
|
||||
export GITEA_REPO="${GITEA_OWNER_REPO##*/}"
|
||||
bash forker/sync.sh
|
||||
env:
|
||||
GITEA_SERVER_URL: ${{ gitea.server_url }}
|
||||
GITEA_OWNER: ${{ gitea.repository_owner }}
|
||||
GITEA_OWNER_REPO: ${{ gitea.repository }}
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
UPSTREAM_URL: ${{ vars.UPSTREAM_URL }}
|
||||
UPSTREAM_TOKEN: ${{ secrets.UPSTREAM_TOKEN }}
|
||||
@@ -1,81 +0,0 @@
|
||||
title: "Game name (PPSA00000)"
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
One thread per title, for every platform: search this category for the title ID first. If a thread exists, reply there, also when your OS or GPU differs from the one it reports.
|
||||
Name the discussion `Game name (title ID)`, for example `DOOM Shareware (PPSA99666)`, without the platform.
|
||||
Bug reports and implementation work belong in issues and pull requests; link them here as the blocker.
|
||||
Per-game progress is also tracked on the [blocker map](https://alxcbtw.github.io/anyps5-roadmap/), built from public GitHub data. Only share material you have the right to distribute.
|
||||
- type: checkboxes
|
||||
id: searched
|
||||
attributes:
|
||||
label: Existing thread
|
||||
options:
|
||||
- label: I searched this category for the title ID and no thread exists for this title on any platform.
|
||||
required: true
|
||||
- type: input
|
||||
id: title
|
||||
attributes:
|
||||
label: Title
|
||||
description: Name and title ID from `sce_sys/param.json`.
|
||||
placeholder: DOOM Shareware (PPSA99666)
|
||||
validations:
|
||||
required: true
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
### First report
|
||||
The fields below describe one run. Other systems and content versions are added to the thread as replies.
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Content version tested
|
||||
description: The content version from `sce_sys/param.json`.
|
||||
placeholder: 01.001.001
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: commit
|
||||
attributes:
|
||||
label: AnyPS5 commit
|
||||
description: The `main` commit that was built, or the release that was used, and any pull requests merged on top.
|
||||
validations:
|
||||
required: true
|
||||
- type: input
|
||||
id: system
|
||||
attributes:
|
||||
label: System tested
|
||||
description: OS, GPU and driver version, and the compiler if you built it yourself.
|
||||
placeholder: Arch Linux, GCC 16.2.1, RTX 5080 (NVIDIA 615.78.08)
|
||||
validations:
|
||||
required: true
|
||||
- type: dropdown
|
||||
id: reached
|
||||
attributes:
|
||||
label: Furthest point
|
||||
options:
|
||||
- Does not convert
|
||||
- Stops before the first frame
|
||||
- Logos or loading screen
|
||||
- Menu
|
||||
- In game
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: seen
|
||||
attributes:
|
||||
label: What is shown
|
||||
description: The last screen that was seen, the frame rate there, and what works or is missing (picture, audio, input).
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: blocker
|
||||
attributes:
|
||||
label: Current blocker
|
||||
description: The line where it stops, the issue that tracks it, and the open pull requests and local changes the title still needs.
|
||||
- type: textarea
|
||||
id: steps
|
||||
attributes:
|
||||
label: How it was run
|
||||
description: Commands and environment variables, and what the title needed beyond the usage guide.
|
||||
@@ -1,65 +0,0 @@
|
||||
name: Performance report
|
||||
description: A slow scene or a change in speed, measured with a performance trace so that reports can be compared.
|
||||
title: "perf: "
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Capture the scene with `APS5_TRACE_FRAMES=<start>:<count>` (presents; `APS5_TRACE_SECONDS=<start>:<length>` also works), as described under [Performance trace](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/BUILD.md#performance-trace). It writes `aps5-trace-<commit>-<pid>.json.gz` and appends one line to `aps5-summary.jsonl`.
|
||||
|
||||
- Run the scene once and restart the title, so the shader and pipeline caches are warm.
|
||||
- Use the same scene, window, resolution and settings for every capture you compare.
|
||||
- Set no other `APS5_TRACE_*` or `APS5_PROFILE_*` switch and do not redirect the log; they cost time.
|
||||
- Capture the base and the change on the same machine in the same session.
|
||||
|
||||
A trace holds timings, scope and thread names and counts, no game data. The summary line names the GPU, driver and OS.
|
||||
- type: input
|
||||
id: scene
|
||||
attributes:
|
||||
label: Title and scene
|
||||
description: Title ID and what the window covers (menu, level, position, cutscene).
|
||||
placeholder: PPSA01325, main menu after the intro
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: observed
|
||||
attributes:
|
||||
label: What is slow or what changed
|
||||
description: What you see (frame time, stutter, a phase that grew) and, for a comparison, the two commits.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: summary
|
||||
attributes:
|
||||
label: Summary lines
|
||||
description: The line of aps5-summary.jsonl for each capture. It holds the commit, the APS5_* switches, GPU, driver, OS, resolution and frame times.
|
||||
render: json
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: trace
|
||||
attributes:
|
||||
label: Traces
|
||||
description: Attach each aps5-trace-<commit>-<pid>.json.gz (drag it into this field). They open in ui.perfetto.dev.
|
||||
validations:
|
||||
required: true
|
||||
- type: textarea
|
||||
id: digest
|
||||
attributes:
|
||||
label: Digest
|
||||
description: The output of `python3 tools/trace_digest.py <trace>` (with `--stacks <file>.collapsed.txt` if you sampled the worker).
|
||||
- type: textarea
|
||||
id: stacks
|
||||
attributes:
|
||||
label: Worker stacks
|
||||
description: Optional. The collapsed-stack file of APS5_SAMPLE_WORKER (<file stem>.collapsed.txt), attached. It opens in speedscope.app.
|
||||
- type: checkboxes
|
||||
id: protocol
|
||||
attributes:
|
||||
label: Capture
|
||||
options:
|
||||
- label: The caches were warm (the scene ran once and the title was restarted)
|
||||
required: true
|
||||
- label: No other APS5_TRACE_* or APS5_PROFILE_* switch was set and the log was not redirected
|
||||
required: true
|
||||
- label: Captures compared here come from the same machine, scene and settings
|
||||
@@ -1,3 +0,0 @@
|
||||
self-hosted-runner:
|
||||
labels:
|
||||
- anyps5
|
||||
@@ -1,13 +0,0 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
groups:
|
||||
actions:
|
||||
patterns:
|
||||
- '*'
|
||||
commit-message:
|
||||
prefix: ci
|
||||
open-pull-requests-limit: 1
|
||||
@@ -1,45 +0,0 @@
|
||||
relinker:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'core/relinker/**'
|
||||
|
||||
shader:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'core/shader/**'
|
||||
|
||||
agc:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'core/libs/prx/libSceAgc*/**'
|
||||
|
||||
libc:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'core/libs/prx/libc/**'
|
||||
|
||||
libkernel:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: 'core/libs/prx/libkernel/**'
|
||||
|
||||
prx:
|
||||
- changed-files:
|
||||
- all-globs-to-any-file:
|
||||
- 'core/libs/prx/**'
|
||||
- '!core/libs/prx/libSceAgc*/**'
|
||||
- '!core/libs/prx/libc/**'
|
||||
- '!core/libs/prx/libkernel/**'
|
||||
|
||||
build:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- '**/CMakeLists.txt'
|
||||
- '**/*.cmake'
|
||||
- '.gitmodules'
|
||||
- '3rdparty/**'
|
||||
|
||||
docs:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file:
|
||||
- '**/*.md'
|
||||
- 'docs/**'
|
||||
|
||||
ci:
|
||||
- changed-files:
|
||||
- any-glob-to-any-file: '.github/**'
|
||||
@@ -1,19 +0,0 @@
|
||||
### What
|
||||
|
||||
### Tested
|
||||
<!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. -->
|
||||
|
||||
### Checklist
|
||||
<!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md -->
|
||||
- [ ] Based on current `main`; no other open PR implements the same functions
|
||||
- [ ] One topic per PR; follow-ups go in a new PR
|
||||
- [ ] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md)
|
||||
- [ ] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file
|
||||
- [ ] No notes, investigation `.md` files or images added to the repository (attach them to this PR)
|
||||
- [ ] New third-party code is a submodule built from source
|
||||
- [ ] Generic behaviour, not specific to one title
|
||||
- [ ] Depends on: <!-- #PR, or none -->
|
||||
- [ ] Fixes: <!-- issue it closes as Fixes #N, or none -->
|
||||
- [ ] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none -->
|
||||
- [ ] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a -->
|
||||
- [ ] AI-assisted: <!-- yes / no -->
|
||||
@@ -1,47 +0,0 @@
|
||||
name: Area labels
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ${{ runner.temp }}/area-state.json
|
||||
key: area-labels-${{ github.run_id }}
|
||||
restore-keys: area-labels-
|
||||
- id: prs
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
state=$RUNNER_TEMP/area-state.json
|
||||
[ -s "$state" ] || echo '{}' > "$state"
|
||||
config=$(gh api "repos/$GITHUB_REPOSITORY/contents/.github/labeler.yml" --jq .sha)
|
||||
gh pr list -R "$GITHUB_REPOSITORY" --base "${{ github.event.repository.default_branch }}" -L 1000 --json number,headRefOid \
|
||||
--jq "map({key: (.number | tostring), value: (.headRefOid + \"-$config\")}) | from_entries" > "$RUNNER_TEMP/area-open.json"
|
||||
jq -r --slurpfile old "$state" 'to_entries[] | select($old[0][.key] != .value) | .key' "$RUNNER_TEMP/area-open.json" | head -n 40 > "$RUNNER_TEMP/area-todo"
|
||||
jq -c --slurpfile open "$RUNNER_TEMP/area-open.json" --rawfile todo "$RUNNER_TEMP/area-todo" \
|
||||
'with_entries(select(.key | in($open[0]))) + ($open[0] | with_entries(select(.key | IN($todo | split("\n")[]))))' "$state" > "$RUNNER_TEMP/area-next.json"
|
||||
{
|
||||
echo 'numbers<<EOF'
|
||||
cat "$RUNNER_TEMP/area-todo"
|
||||
echo EOF
|
||||
} >> "$GITHUB_OUTPUT"
|
||||
- if: steps.prs.outputs.numbers != ''
|
||||
uses: actions/labeler@v7
|
||||
with:
|
||||
pr-number: ${{ steps.prs.outputs.numbers }}
|
||||
- run: mv "$RUNNER_TEMP/area-next.json" "$RUNNER_TEMP/area-state.json"
|
||||
- uses: actions/cache/save@v6
|
||||
with:
|
||||
path: ${{ runner.temp }}/area-state.json
|
||||
key: area-labels-${{ github.run_id }}
|
||||
@@ -1,706 +0,0 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
types: [opened, synchronize, reopened]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr:
|
||||
description: Pull request numbers to build together, separated by spaces or commas (up to 40)
|
||||
required: true
|
||||
type: string
|
||||
linux:
|
||||
description: Also build and test on Linux
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
full:
|
||||
description: Run the full Linux and Windows builds (off runs only the relinker builds and tests on Linux, Windows and macOS)
|
||||
required: false
|
||||
default: true
|
||||
type: boolean
|
||||
select:
|
||||
description: Build and run only the tests whose build inputs the pull requests change (push builds of main always run every test)
|
||||
required: false
|
||||
default: false
|
||||
type: boolean
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: build-${{ github.event_name }}-${{ github.event.pull_request.number || inputs.pr || github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CONFIGURE: >-
|
||||
-G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
|
||||
-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
|
||||
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
|
||||
|
||||
jobs:
|
||||
eligibility:
|
||||
if: github.event_name == 'pull_request' || github.ref == 'refs/heads/main'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
outputs:
|
||||
sha: ${{ steps.gate.outputs.sha }}
|
||||
pr: ${{ steps.gate.outputs.pr }}
|
||||
head: ${{ steps.gate.outputs.head }}
|
||||
relinker: ${{ steps.gate.outputs.relinker }}
|
||||
register-context: ${{ steps.gate.outputs.register-context }}
|
||||
write-watch: ${{ steps.gate.outputs.write-watch }}
|
||||
full: ${{ steps.gate.outputs.full }}
|
||||
relinker-hosts: ${{ steps.gate.outputs.relinker-hosts }}
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
id: gate
|
||||
env:
|
||||
PR_NUMBER: ${{ inputs.pr }}
|
||||
LINUX_BUILD: ${{ inputs.linux }}
|
||||
FULL_BUILD: ${{ inputs.full }}
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const workflow = '.github/workflows/build.yml';
|
||||
const libc = 'core/libs/prx/libc/';
|
||||
const jobOfLine = (text) => {
|
||||
let inJobs = false;
|
||||
let job = '';
|
||||
return text.split('\n').map((line) => {
|
||||
if (/^\S/.test(line)) {
|
||||
inJobs = /^jobs:\s*$/.test(line);
|
||||
job = '';
|
||||
} else if (inJobs) {
|
||||
job = /^ ([\w-]+):\s*$/.exec(line)?.[1] ?? job;
|
||||
}
|
||||
return job;
|
||||
});
|
||||
};
|
||||
const patchedJobs = (patch, text) => {
|
||||
const jobs = jobOfLine(text);
|
||||
const touched = new Set();
|
||||
let line = 1;
|
||||
for (const row of patch.split('\n')) {
|
||||
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(row);
|
||||
if (hunk) {
|
||||
line = Number(hunk[1]);
|
||||
} else if (row.startsWith('+')) {
|
||||
touched.add(jobs[line - 1] ?? '');
|
||||
line += 1;
|
||||
} else if (row.startsWith('-')) {
|
||||
touched.add(jobs[line - 2] ?? '').add(jobs[line - 1] ?? '');
|
||||
} else if (row.startsWith(' ')) {
|
||||
line += 1;
|
||||
}
|
||||
}
|
||||
return touched;
|
||||
};
|
||||
const workflowJobs = new Set();
|
||||
const readWorkflow = async (files, ref) => {
|
||||
const file = files.find((file) => file.filename === workflow || file.previous_filename === workflow);
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
if (file.filename !== workflow || !file.patch) {
|
||||
workflowJobs.add('*');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const { data } = await github.rest.repos.getContent({ owner, repo, path: workflow, ref });
|
||||
const text = Buffer.from(data.content, 'base64').toString('utf8');
|
||||
patchedJobs(file.patch, text).forEach((job) => workflowJobs.add(job));
|
||||
} catch (error) {
|
||||
core.warning(`Could not read ${workflow} at ${ref}, so every test job runs: ${error.message}`);
|
||||
workflowJobs.add('*');
|
||||
}
|
||||
};
|
||||
const select = (paths, all) => {
|
||||
const touches = (...prefixes) => all ||
|
||||
paths.some((path) => prefixes.some((prefix) => prefix.endsWith('/') ? path.startsWith(prefix) : path === prefix));
|
||||
const edits = (job) => ['*', '', 'eligibility', job].some((name) => workflowJobs.has(name));
|
||||
return {
|
||||
relinker: edits('relinker') || touches(
|
||||
'core/relinker/', libc, 'core/libs/prx/libkernel/AppMetadata/', 'core/libs/tests/ParamJsonParser.cpp',
|
||||
'core/shader/recompiler/tests/CacheFileReadTests.cpp', 'core/shader/recompiler/ShaderCacheDirectory.hpp',
|
||||
'tools/', 'cmake/', 'CMakeLists.txt'
|
||||
),
|
||||
registerContext: edits('register-context') ||
|
||||
touches('core/libs/tests/register_context/', 'core/libs/tests/RegisterContext.cpp', libc),
|
||||
writeWatch: edits('write-watch') || touches('core/libs/tests/write_watch/', 'core/libs/tests/WriteWatch.cpp', libc),
|
||||
};
|
||||
};
|
||||
const relinkerHosts = (full, linux) => JSON.stringify([
|
||||
...(full && linux ? [] : [{ os: 'ubuntu-latest', compiler: 'g++' }]),
|
||||
...(full ? [] : [{ os: 'windows-latest', compiler: 'g++' }]),
|
||||
{ os: 'macos-latest', compiler: 'clang++' },
|
||||
{ os: 'macos-latest', compiler: 'clang++', architectures: 'x86_64' },
|
||||
]);
|
||||
if (context.eventName === 'push') {
|
||||
if (context.ref !== 'refs/heads/main') {
|
||||
throw new Error('Automatic full builds only run on main');
|
||||
}
|
||||
let paths = [];
|
||||
let all = true;
|
||||
if (!/^0+$/.test(context.payload.before)) {
|
||||
try {
|
||||
const { data } = await github.rest.repos.compareCommitsWithBasehead({
|
||||
owner, repo, basehead: `${context.payload.before}...${context.sha}`
|
||||
});
|
||||
const files = data.files ?? [];
|
||||
all = files.length >= 300;
|
||||
paths = files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean));
|
||||
await readWorkflow(files, context.sha);
|
||||
} catch (error) {
|
||||
core.warning(`Could not list the files of this push, so every test job runs: ${error.message}`);
|
||||
}
|
||||
}
|
||||
const run = select(paths, all);
|
||||
core.setOutput('sha', context.sha);
|
||||
core.setOutput('pr', '');
|
||||
core.setOutput('head', '');
|
||||
core.setOutput('relinker', run.relinker);
|
||||
core.setOutput('register-context', run.registerContext);
|
||||
core.setOutput('write-watch', run.writeWatch);
|
||||
core.setOutput('full', true);
|
||||
core.setOutput('relinker-hosts', relinkerHosts(true, true));
|
||||
await core.summary.addRaw(
|
||||
`Building main at ${context.sha}: full builds enabled, ` +
|
||||
`macOS relinker ${run.relinker ? 'enabled' : 'skipped'}, ` +
|
||||
`register context tests ${run.registerContext ? 'enabled' : 'skipped'}, write watch tests ${run.writeWatch ? 'enabled' : 'skipped'}`
|
||||
).write();
|
||||
return;
|
||||
}
|
||||
const manual = context.eventName === 'workflow_dispatch';
|
||||
const linux = process.env.LINUX_BUILD !== 'false';
|
||||
const full = manual && process.env.FULL_BUILD !== 'false';
|
||||
if (manual) {
|
||||
for (const username of new Set([context.actor, process.env.GITHUB_TRIGGERING_ACTOR])) {
|
||||
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username });
|
||||
if (!['write', 'maintain', 'admin'].includes(data.permission)) {
|
||||
throw new Error('Only collaborators with write access can start or rerun builds');
|
||||
}
|
||||
}
|
||||
if (!/^[1-9][0-9]*([ ,]+[1-9][0-9]*){0,39}$/.test(process.env.PR_NUMBER.trim())) {
|
||||
throw new Error('Enter up to 40 positive pull request numbers separated by spaces or commas');
|
||||
}
|
||||
}
|
||||
const numbers = manual
|
||||
? [...new Set(process.env.PR_NUMBER.trim().split(/[ ,]+/).map(Number))]
|
||||
: [context.payload.pull_request.number];
|
||||
if (numbers.some((pull_number) => !Number.isSafeInteger(pull_number) || pull_number < 1)) {
|
||||
throw new Error('Invalid pull request number');
|
||||
}
|
||||
const pulls = [];
|
||||
const paths = [];
|
||||
let truncated = false;
|
||||
for (const pull_number of numbers) {
|
||||
let { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
|
||||
for (let attempt = 0; pr.mergeable === null && attempt < 10; ++attempt) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 3000));
|
||||
({ data: pr } = await github.rest.pulls.get({ owner, repo, pull_number }));
|
||||
}
|
||||
if (!manual && pr.state !== 'open') {
|
||||
await core.summary.addRaw(`PR #${pull_number} was ${pr.merged ? 'merged' : 'closed'} before this run started: nothing to build`).write();
|
||||
return;
|
||||
}
|
||||
if (pr.state !== 'open' || pr.base.ref !== 'main') {
|
||||
throw new Error(`Pull request #${pull_number} must be open and target main`);
|
||||
}
|
||||
if (!manual && pr.head.sha !== context.payload.pull_request.head.sha) {
|
||||
throw new Error('The pull request has newer commits; use the latest run');
|
||||
}
|
||||
if (pr.mergeable === false) {
|
||||
throw new Error(`Pull request #${pull_number} does not merge cleanly into main; rebase it first`);
|
||||
}
|
||||
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number, per_page: 100 });
|
||||
truncated ||= files.length >= 3000;
|
||||
paths.push(...files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)));
|
||||
await readWorkflow(files, pr.head.sha);
|
||||
pulls.push({ number: pull_number, head: pr.head.sha });
|
||||
}
|
||||
const run = select(paths, truncated);
|
||||
let relinker = run.relinker;
|
||||
if (relinker && !manual) {
|
||||
const author = context.payload.pull_request.user.login;
|
||||
const { data: commits } = await github.rest.repos.listCommits({
|
||||
owner, repo, sha: 'main', author, per_page: 1
|
||||
});
|
||||
relinker = commits.length > 0;
|
||||
if (!relinker) {
|
||||
try {
|
||||
const { data: mergedPRs } = await github.rest.search.issuesAndPullRequests({
|
||||
q: `repo:${owner}/${repo} is:pr is:merged base:main author:${author}`,
|
||||
per_page: 1
|
||||
});
|
||||
if (mergedPRs.incomplete_results) {
|
||||
throw new Error('the search results are incomplete');
|
||||
}
|
||||
relinker = mergedPRs.total_count > 0;
|
||||
} catch (error) {
|
||||
core.warning(`Skipping the relinker: could not search the merged pull requests of ${author}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const registerContext = run.registerContext;
|
||||
const writeWatch = run.writeWatch;
|
||||
const { data: main } = await github.rest.repos.getBranch({ owner, repo, branch: 'main' });
|
||||
core.setOutput('sha', main.commit.sha);
|
||||
core.setOutput('pr', pulls.map((pull) => pull.number).join(' '));
|
||||
core.setOutput('head', pulls.map((pull) => pull.head).join(' '));
|
||||
core.setOutput('relinker', relinker);
|
||||
core.setOutput('register-context', registerContext);
|
||||
core.setOutput('write-watch', writeWatch);
|
||||
core.setOutput('full', full);
|
||||
core.setOutput('relinker-hosts', relinkerHosts(full, linux));
|
||||
const merged = pulls.map((pull) => `PR #${pull.number} at ${pull.head} merged into main at ${main.commit.sha}`);
|
||||
merged.forEach((line) => core.info(line));
|
||||
await core.summary.addRaw(
|
||||
`${merged.join(', then ')}: full builds ${full ? 'enabled' : 'disabled'}, ` +
|
||||
`relinker ${relinker ? (full ? (linux ? 'enabled on macOS (the full builds run the Linux and Windows relinker tests)' : 'enabled on Linux and macOS (the full Windows build runs the Windows relinker tests)') : 'enabled') : 'skipped: no relinker file changed, or no commit or merged pull request in main was found for the author'}, ` +
|
||||
`register context tests ${registerContext ? 'enabled' : 'skipped'}, write watch tests ${writeWatch ? 'enabled' : 'skipped'}`
|
||||
).write();
|
||||
|
||||
relinker:
|
||||
needs: eligibility
|
||||
if: ${{ needs.eligibility.outputs.relinker == 'true' }}
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 15
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.eligibility.outputs.relinker-hosts) }}
|
||||
env:
|
||||
WINLIBS_RELEASE: 15.2.0posix-14.0.0-ucrt-r7
|
||||
WINLIBS_ZIP: winlibs-x86_64-posix-seh-gcc-15.2.0-mingw-w64ucrt-14.0.0-r7.zip
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.eligibility.outputs.sha }}
|
||||
persist-credentials: false
|
||||
- name: Merge the pull request into main
|
||||
if: ${{ needs.eligibility.outputs.head != '' }}
|
||||
shell: bash
|
||||
env:
|
||||
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
|
||||
PR_HEAD: ${{ needs.eligibility.outputs.head }}
|
||||
run: |
|
||||
read -ra numbers <<< "$PR_NUMBER"
|
||||
read -ra heads <<< "$PR_HEAD"
|
||||
refspecs=()
|
||||
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
|
||||
git fetch --no-tags --unshallow origin "${refspecs[@]}"
|
||||
for i in "${!numbers[@]}"; do
|
||||
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
|
||||
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
|
||||
done
|
||||
- if: runner.os == 'Windows'
|
||||
id: toolchain
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: C:\winlibs
|
||||
key: ${{ env.WINLIBS_ZIP }}
|
||||
- if: runner.os == 'Windows' && steps.toolchain.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
curl -sSfL -o "$RUNNER_TEMP/winlibs.zip" "https://github.com/brechtsanders/winlibs_mingw/releases/download/$WINLIBS_RELEASE/$WINLIBS_ZIP"
|
||||
7z x "$RUNNER_TEMP/winlibs.zip" -oC:/winlibs > /dev/null
|
||||
- if: runner.os == 'Windows'
|
||||
run: echo 'C:\winlibs\mingw64\bin' >> "$GITHUB_PATH"
|
||||
- if: ${{ matrix.architectures == 'x86_64' }}
|
||||
run: sudo softwareupdate --install-rosetta --agree-to-license
|
||||
- run: cmake -S . -B build-relinker -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=${{ matrix.compiler }} -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON -DCMAKE_OSX_ARCHITECTURES=${{ matrix.architectures }}
|
||||
- run: cmake --build build-relinker --parallel 3
|
||||
- run: ctest --test-dir build-relinker --output-on-failure --timeout 120 --parallel 4
|
||||
|
||||
relinker-asan:
|
||||
needs: eligibility
|
||||
if: ${{ needs.eligibility.outputs.relinker == 'true' }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.eligibility.outputs.sha }}
|
||||
persist-credentials: false
|
||||
- name: Merge the pull request into main
|
||||
if: ${{ needs.eligibility.outputs.head != '' }}
|
||||
env:
|
||||
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
|
||||
PR_HEAD: ${{ needs.eligibility.outputs.head }}
|
||||
run: |
|
||||
read -ra numbers <<< "$PR_NUMBER"
|
||||
read -ra heads <<< "$PR_HEAD"
|
||||
refspecs=()
|
||||
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
|
||||
git fetch --no-tags --unshallow origin "${refspecs[@]}"
|
||||
for i in "${!numbers[@]}"; do
|
||||
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
|
||||
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
|
||||
done
|
||||
- run: cmake -S . -B build-relinker-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=g++ -DANYPS5_RELINKER_ONLY=ON -DANYPS5_ENABLE_ASAN=ON -DBUILD_TESTING=ON
|
||||
- run: cmake --build build-relinker-asan --parallel 4
|
||||
- run: ctest --test-dir build-relinker-asan --output-on-failure --timeout 120 --label-regex '^tls_function_coverage$' --no-tests=error
|
||||
|
||||
register-context:
|
||||
needs: eligibility
|
||||
if: ${{ needs.eligibility.outputs.register-context == 'true' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-15-intel]
|
||||
configuration: [Debug, Release]
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.eligibility.outputs.sha }}
|
||||
persist-credentials: false
|
||||
- name: Merge the pull request into main
|
||||
if: ${{ needs.eligibility.outputs.head != '' }}
|
||||
shell: bash
|
||||
env:
|
||||
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
|
||||
PR_HEAD: ${{ needs.eligibility.outputs.head }}
|
||||
run: |
|
||||
read -ra numbers <<< "$PR_NUMBER"
|
||||
read -ra heads <<< "$PR_HEAD"
|
||||
refspecs=()
|
||||
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
|
||||
git fetch --no-tags --unshallow origin "${refspecs[@]}"
|
||||
for i in "${!numbers[@]}"; do
|
||||
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
|
||||
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
|
||||
done
|
||||
- run: cmake -S core/libs/tests/register_context -B build/register-context -DCMAKE_BUILD_TYPE=${{ matrix.configuration }}
|
||||
- run: cmake --build build/register-context --parallel
|
||||
- run: ctest --test-dir build/register-context --output-on-failure --repeat until-fail:3 --no-tests=error
|
||||
|
||||
write-watch:
|
||||
needs: eligibility
|
||||
if: ${{ needs.eligibility.outputs.write-watch == 'true' }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [macos-15-intel, macos-15]
|
||||
runs-on: ${{ matrix.os }}
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.eligibility.outputs.sha }}
|
||||
persist-credentials: false
|
||||
- name: Merge the pull request into main
|
||||
if: ${{ needs.eligibility.outputs.head != '' }}
|
||||
shell: bash
|
||||
env:
|
||||
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
|
||||
PR_HEAD: ${{ needs.eligibility.outputs.head }}
|
||||
run: |
|
||||
read -ra numbers <<< "$PR_NUMBER"
|
||||
read -ra heads <<< "$PR_HEAD"
|
||||
refspecs=()
|
||||
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
|
||||
git fetch --no-tags --unshallow origin "${refspecs[@]}"
|
||||
for i in "${!numbers[@]}"; do
|
||||
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
|
||||
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
|
||||
done
|
||||
- run: cmake -S core/libs/tests/write_watch -B build/write-watch -DCMAKE_BUILD_TYPE=Release
|
||||
- run: cmake --build build/write-watch --parallel
|
||||
- run: ctest --test-dir build/write-watch --output-on-failure --repeat until-fail:3 --no-tests=error
|
||||
|
||||
linux:
|
||||
needs: eligibility
|
||||
if: ${{ (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.linux)) && needs.eligibility.outputs.full == 'true' }}
|
||||
runs-on: [self-hosted, linux, x64, anyps5]
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CCACHE_DIR: /var/cache/anyps5/ccache
|
||||
CCACHE_MAXSIZE: 30G
|
||||
CCACHE_COMPILERCHECK: content
|
||||
MESA_SHADER_CACHE_DIR: /var/cache/anyps5/mesa
|
||||
MESA_SHADER_CACHE_MAX_SIZE: 4G
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.eligibility.outputs.sha }}
|
||||
persist-credentials: false
|
||||
submodules: recursive
|
||||
- name: Merge the pull request into main
|
||||
if: ${{ needs.eligibility.outputs.head != '' }}
|
||||
shell: bash
|
||||
env:
|
||||
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
|
||||
PR_HEAD: ${{ needs.eligibility.outputs.head }}
|
||||
run: |
|
||||
read -ra numbers <<< "$PR_NUMBER"
|
||||
read -ra heads <<< "$PR_HEAD"
|
||||
refspecs=()
|
||||
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
|
||||
fetch_options=()
|
||||
if [ "$(git rev-parse --is-shallow-repository)" = true ]; then fetch_options+=(--unshallow); fi
|
||||
git fetch --no-tags "${fetch_options[@]}" origin "${refspecs[@]}"
|
||||
for i in "${!numbers[@]}"; do
|
||||
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
|
||||
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
|
||||
done
|
||||
git submodule update --init --recursive
|
||||
- name: Prepare persistent caches
|
||||
run: |
|
||||
mkdir -p "$CCACHE_DIR" "$MESA_SHADER_CACHE_DIR"
|
||||
test -w "$CCACHE_DIR" && test -w "$MESA_SHADER_CACHE_DIR"
|
||||
ccache --zero-stats
|
||||
ccache --show-config
|
||||
dpkg-query -W mesa-vulkan-drivers
|
||||
grep -m1 '^model name' /proc/cpuinfo
|
||||
- name: Install the wild linker
|
||||
shell: bash
|
||||
env:
|
||||
WILD_VERSION: 0.10.0
|
||||
WILD_SHA256: 641265506a7c06cfb03181b8916ab663ec8407855db6d4db7f8450667d105283
|
||||
run: |
|
||||
tools=$RUNNER_TOOL_CACHE/wild
|
||||
mkdir -p "$tools" 2>/dev/null && test -w "$tools" || { tools=$RUNNER_TEMP/wild; mkdir -p "$tools"; }
|
||||
dir=$tools/$WILD_VERSION
|
||||
tmp=
|
||||
probe=$(mktemp -d "$RUNNER_TEMP/wild-probe.XXXXXX")
|
||||
trap 'rm -rf "$tmp" "$probe"' EXIT
|
||||
if [ ! -x "$dir/bin/ld" ]; then
|
||||
tmp=$(mktemp -d "$tools/.wild.XXXXXX")
|
||||
name=wild-linker-$WILD_VERSION-x86_64-unknown-linux-gnu
|
||||
curl -fsSL --retry 3 -o "$tmp/$name.tar.gz" "https://github.com/davidlattimore/wild/releases/download/$WILD_VERSION/$name.tar.gz"
|
||||
echo "$WILD_SHA256 $tmp/$name.tar.gz" | sha256sum -c -
|
||||
tar -xzf "$tmp/$name.tar.gz" -C "$tmp"
|
||||
mkdir -p "$tmp/out/bin"
|
||||
mv "$tmp/$name/wild" "$tmp/out/bin/wild"
|
||||
ln -s wild "$tmp/out/bin/ld"
|
||||
mv -T "$tmp/out" "$dir" 2>/dev/null || test -x "$dir/bin/ld"
|
||||
fi
|
||||
echo 'int main(void) { return 0; }' > "$probe/main.c"
|
||||
gcc "-B$dir/bin" "$probe/main.c" -o "$probe/main"
|
||||
readelf -p .comment "$probe/main" | grep -F "Linker: Wild $WILD_VERSION"
|
||||
echo "LINKER_FLAGS=-B$dir/bin" >> "$GITHUB_ENV"
|
||||
- name: Size parallelism to what the shared host has free
|
||||
run: |
|
||||
cpus=$(nproc)
|
||||
busy=$(awk '{ printf "%d", $1 + 0.5 }' /proc/loadavg)
|
||||
mem_mb=$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo)
|
||||
slots=$(( (mem_mb - 2048) / 1024 ))
|
||||
slots=$(( slots < 1 ? 1 : slots ))
|
||||
tests=$(( cpus - busy ))
|
||||
tests=$(( tests < 1 ? 1 : tests ))
|
||||
slot_dir=$CCACHE_DIR/compile-slots
|
||||
mkdir -p -m 1777 "$slot_dir"
|
||||
test -w "$slot_dir"
|
||||
echo "cpus=$cpus load=$busy mem_total_mb=$mem_mb -> build jobs $cpus, cold compiles $slots per host, tests $tests"
|
||||
echo "CMAKE_BUILD_PARALLEL_LEVEL=$cpus" >> "$GITHUB_ENV"
|
||||
echo "CTEST_PARALLEL_LEVEL=$tests" >> "$GITHUB_ENV"
|
||||
echo "CCACHE_PREFIX=$GITHUB_WORKSPACE/tools/compile_slot.sh" >> "$GITHUB_ENV"
|
||||
echo "ANYPS5_COMPILE_SLOT_DIR=$slot_dir" >> "$GITHUB_ENV"
|
||||
echo "ANYPS5_COMPILE_SLOTS=$slots" >> "$GITHUB_ENV"
|
||||
- run: cmake -S . -B build $CONFIGURE -DANYPS5_ENABLE_SPIRV_TOOLS=ON "-DCMAKE_EXE_LINKER_FLAGS=$LINKER_FLAGS" "-DCMAKE_SHARED_LINKER_FLAGS=$LINKER_FLAGS" "-DCMAKE_MODULE_LINKER_FLAGS=$LINKER_FLAGS"
|
||||
- name: Check that every test executable is registered with ctest
|
||||
run: python3 tools/check_test_registration.py build
|
||||
- if: ${{ inputs.select }}
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: test-graph.json
|
||||
key: test-graph-${{ runner.os }}-${{ needs.eligibility.outputs.sha }}
|
||||
restore-keys: test-graph-${{ runner.os }}-
|
||||
- name: Select the tests the change reaches
|
||||
if: ${{ inputs.select }}
|
||||
env:
|
||||
BASE: ${{ needs.eligibility.outputs.sha }}
|
||||
run: |
|
||||
git diff --name-only "$BASE" HEAD > changed.txt
|
||||
python3 tools/select_tests.py select build test-graph.json changed.txt
|
||||
- id: build
|
||||
run: |
|
||||
if [ -f build/select.ninja ]; then ninja -C build -f select.ninja -j "$CMAKE_BUILD_PARALLEL_LEVEL" -l "$(nproc)" selected; else cmake --build build -- -l "$(nproc)"; fi
|
||||
- id: libs
|
||||
run: cmake --build build --target libs -- -l "$(nproc)"
|
||||
- run: python3 tools/select_tests.py ctest build --test-load "$(nproc)" --output-on-failure --timeout 120 --output-log ctest.log --output-junit ctest.xml
|
||||
env:
|
||||
ANYPS5_REQUIRE_VULKAN: 1
|
||||
GALLIUM_OVERRIDE_CPU_CAPS: avx
|
||||
- run: python3 tools/check_skips.py build/ctest.xml
|
||||
- name: Write the test graph of main
|
||||
if: ${{ !cancelled() && github.event_name == 'push' && steps.build.outcome == 'success' && steps.libs.outcome == 'success' }}
|
||||
continue-on-error: true
|
||||
run: python3 tools/select_tests.py dump build test-graph.json
|
||||
- if: ${{ !cancelled() && github.event_name == 'push' && hashFiles('test-graph.json') != '' }}
|
||||
continue-on-error: true
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: test-graph.json
|
||||
key: test-graph-${{ runner.os }}-${{ github.sha }}
|
||||
- name: Report compiler cache statistics
|
||||
if: ${{ !cancelled() }}
|
||||
run: ccache --show-stats
|
||||
- name: Report tests slower than 30 s
|
||||
if: ${{ !cancelled() }}
|
||||
shell: bash
|
||||
run: |
|
||||
[ -f ctest.log ] || exit 0
|
||||
awk '/Test +#[0-9]+: / && $NF == "sec" { for (i = 1; i <= NF; i++) if ($i ~ /^#[0-9]+:$/) name = $(i + 1); t = $(NF - 1) + 0; if (t > max[name]) max[name] = t }
|
||||
END { for (name in max) if (max[name] > 30) printf "::warning title=Slow test::%s took %.1f s on %s; tests must finish in 30 s (CONTRIBUTING.md)\n", name, max[name], ENVIRON["RUNNER_OS"] }' ctest.log
|
||||
|
||||
windows:
|
||||
needs: eligibility
|
||||
if: ${{ (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.eligibility.outputs.full == 'true' }}
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
WINLIBS_RELEASE: 15.2.0posix-14.0.0-ucrt-r7
|
||||
WINLIBS_ZIP: winlibs-x86_64-posix-seh-gcc-15.2.0-mingw-w64ucrt-14.0.0-r7.zip
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ needs.eligibility.outputs.sha }}
|
||||
persist-credentials: false
|
||||
- name: Merge the pull request into main
|
||||
if: ${{ needs.eligibility.outputs.head != '' }}
|
||||
shell: bash
|
||||
env:
|
||||
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
|
||||
PR_HEAD: ${{ needs.eligibility.outputs.head }}
|
||||
run: |
|
||||
read -ra numbers <<< "$PR_NUMBER"
|
||||
read -ra heads <<< "$PR_HEAD"
|
||||
refspecs=()
|
||||
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
|
||||
git fetch --no-tags --unshallow origin "${refspecs[@]}"
|
||||
for i in "${!numbers[@]}"; do
|
||||
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
|
||||
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
|
||||
done
|
||||
- id: submodules
|
||||
name: Key the submodules on their commits
|
||||
run: |
|
||||
echo "key=$(git ls-files -s | awk '$1 == "160000" { print $2, $4 }' | cat - .gitmodules | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
|
||||
echo "ffmpeg=$(git rev-parse HEAD:3rdparty/ffmpeg-core)" >> "$GITHUB_OUTPUT"
|
||||
- id: submodule-cache
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ${{ runner.temp }}/submodule-gitdirs.tar
|
||||
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
|
||||
- name: Check out the submodules
|
||||
run: |
|
||||
if [ -f "$RUNNER_TEMP/submodule-gitdirs.tar" ]; then tar --force-local -xf "$RUNNER_TEMP/submodule-gitdirs.tar"; fi
|
||||
git submodule update --init --recursive --depth 1 --jobs 8
|
||||
- if: steps.submodule-cache.outputs.cache-hit != 'true'
|
||||
run: tar --force-local -cf "$RUNNER_TEMP/submodule-gitdirs.tar" .git/modules
|
||||
- if: steps.submodule-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
path: ${{ runner.temp }}/submodule-gitdirs.tar
|
||||
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
|
||||
- name: Point the WinLibs CMake at the CA bundle of Git for Windows
|
||||
run: |
|
||||
for prefix in ucrt64 mingw64; do
|
||||
bundle="C:/Program Files/Git/$prefix/etc/ssl/certs/ca-bundle.crt"
|
||||
if [ -f "$bundle" ]; then echo "SSL_CERT_FILE=$bundle" >> "$GITHUB_ENV"; exit 0; fi
|
||||
done
|
||||
echo "::error::No CA bundle found in Git for Windows"; exit 1
|
||||
- id: toolchain
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: C:\winlibs
|
||||
key: ${{ env.WINLIBS_ZIP }}
|
||||
- if: steps.toolchain.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
curl -sSfL -o "$RUNNER_TEMP/winlibs.zip" "https://github.com/brechtsanders/winlibs_mingw/releases/download/$WINLIBS_RELEASE/$WINLIBS_ZIP"
|
||||
7z x "$RUNNER_TEMP/winlibs.zip" -oC:/winlibs > /dev/null
|
||||
- run: echo 'C:\winlibs\mingw64\bin' >> "$GITHUB_PATH"
|
||||
- uses: hendrikmuhs/ccache-action@v1.2.24
|
||||
with:
|
||||
key: ${{ github.event_name == 'workflow_dispatch' && 'dispatch-windows' || 'windows' }}
|
||||
restore-keys: ${{ github.event_name == 'workflow_dispatch' && 'windows' || '' }}
|
||||
save: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }}
|
||||
evict-old-files: job
|
||||
- id: ffmpeg-cache
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: build/externals
|
||||
key: ffmpeg-${{ runner.os }}-${{ steps.submodules.outputs.ffmpeg }}
|
||||
- id: seed-cache
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: configure-seed.cmake
|
||||
key: configure-seed-${{ env.WINLIBS_ZIP }}-${{ steps.submodules.outputs.key }}-${{ hashFiles('CMakeLists.txt', 'cmake/**', 'core/libs/CMakeLists.txt', '.github/workflows/build.yml') }}
|
||||
- shell: cmd
|
||||
run: if exist configure-seed.cmake (cmake -C configure-seed.cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown") else (cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown")
|
||||
- if: steps.seed-cache.outputs.cache-hit != 'true'
|
||||
shell: cmd
|
||||
run: python tools/configure_seed.py build/CMakeCache.txt configure-seed.cmake
|
||||
- if: steps.seed-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
path: configure-seed.cmake
|
||||
key: ${{ steps.seed-cache.outputs.cache-primary-key }}
|
||||
- if: steps.ffmpeg-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v6
|
||||
continue-on-error: true
|
||||
with:
|
||||
path: build/externals
|
||||
key: ${{ steps.ffmpeg-cache.outputs.cache-primary-key }}
|
||||
- name: Check that every test executable is registered with ctest
|
||||
shell: cmd
|
||||
run: python tools/check_test_registration.py build
|
||||
- if: ${{ inputs.select }}
|
||||
uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: test-graph.json
|
||||
key: test-graph-${{ runner.os }}-${{ needs.eligibility.outputs.sha }}
|
||||
restore-keys: test-graph-${{ runner.os }}-
|
||||
- name: Select the tests the change reaches
|
||||
if: ${{ inputs.select }}
|
||||
env:
|
||||
BASE: ${{ needs.eligibility.outputs.sha }}
|
||||
shell: cmd
|
||||
run: |
|
||||
git diff --name-only %BASE% HEAD > changed.txt
|
||||
python tools/select_tests.py select build test-graph.json changed.txt
|
||||
- id: build
|
||||
shell: cmd
|
||||
run: if exist build\select.ninja (ninja -C build -f select.ninja selected) else (cmake --build build)
|
||||
- id: libs
|
||||
shell: cmd
|
||||
run: cmake --build build --target libs
|
||||
- shell: cmd
|
||||
run: python tools/select_tests.py ctest build --output-on-failure --timeout 120 --parallel 4 --output-log ctest.log --output-junit ctest.xml
|
||||
- run: python tools/check_skips.py build/ctest.xml --job windows
|
||||
- name: Write the test graph of main
|
||||
if: ${{ !cancelled() && github.event_name == 'push' && steps.build.outcome == 'success' && steps.libs.outcome == 'success' }}
|
||||
continue-on-error: true
|
||||
shell: cmd
|
||||
run: python tools/select_tests.py dump build test-graph.json
|
||||
- if: ${{ !cancelled() && github.event_name == 'push' && hashFiles('test-graph.json') != '' }}
|
||||
continue-on-error: true
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: test-graph.json
|
||||
key: test-graph-${{ runner.os }}-${{ github.sha }}
|
||||
- name: Report tests slower than 30 s
|
||||
if: ${{ !cancelled() }}
|
||||
shell: bash
|
||||
run: |
|
||||
[ -f ctest.log ] || exit 0
|
||||
awk '/Test +#[0-9]+: / && $NF == "sec" { for (i = 1; i <= NF; i++) if ($i ~ /^#[0-9]+:$/) name = $(i + 1); t = $(NF - 1) + 0; if (t > max[name]) max[name] = t }
|
||||
END { for (name in max) if (max[name] > 30) printf "::warning title=Slow test::%s took %.1f s on %s; tests must finish in 30 s (CONTRIBUTING.md)\n", name, max[name], ENVIRON["RUNNER_OS"] }' ctest.log
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
name: Conflict label
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: '0 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: conflict-label
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: eps1lon/actions-label-merge-conflict@v3
|
||||
with:
|
||||
dirtyLabel: needs rebase
|
||||
repoToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,32 +0,0 @@
|
||||
name: Conventions
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened, edited]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: conventions-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
conventions:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event.pull_request.base.sha }}
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
- name: Fetch pull request objects without checking out its code
|
||||
env:
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: git fetch --no-tags origin "$HEAD_SHA"
|
||||
- name: Check conventions with the trusted base script
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: python3 -I tools/check_conventions.py --base "$BASE_SHA" --head "$HEAD_SHA"
|
||||
@@ -1,44 +0,0 @@
|
||||
name: Fix label
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '45 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: fix-label
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
label:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: read
|
||||
pull-requests: write
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
LABEL: fix error
|
||||
steps:
|
||||
- run: |
|
||||
gh api graphql --paginate -f owner="${GITHUB_REPOSITORY%/*}" -f name="${GITHUB_REPOSITORY#*/}" -f query='
|
||||
query($owner: String!, $name: String!, $endCursor: String) {
|
||||
repository(owner: $owner, name: $name) {
|
||||
pullRequests(states: OPEN, first: 100, after: $endCursor) {
|
||||
pageInfo { hasNextPage endCursor }
|
||||
nodes { number closingIssuesReferences { totalCount } labels(first: 100) { nodes { name } } }
|
||||
}
|
||||
}
|
||||
}' --jq '.data.repository.pullRequests.nodes[]
|
||||
| (.closingIssuesReferences.totalCount > 0) as $fix
|
||||
| ([.labels.nodes[].name] | index(env.LABEL) != null) as $has
|
||||
| if $fix and ($has | not) then "add \(.number)" elif $has and ($fix | not) then "remove \(.number)" else empty end' > "$RUNNER_TEMP/fix-todo"
|
||||
label=$(jq -rn 'env.LABEL | @uri')
|
||||
while read -r action number; do
|
||||
if [ "$action" = add ]; then
|
||||
gh api "repos/$GITHUB_REPOSITORY/issues/$number/labels" -f "labels[]=$LABEL" --silent
|
||||
else
|
||||
gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$number/labels/$label" --silent
|
||||
fi
|
||||
done < "$RUNNER_TEMP/fix-todo"
|
||||
@@ -1,42 +0,0 @@
|
||||
|
||||
name: Labels
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths: ['.github/workflows/labels.yml']
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
sync:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
steps:
|
||||
- run: |
|
||||
existing=$(gh label list --limit 1000 --json name --jq '.[].name')
|
||||
label() { grep -qixF -- "$1" <<< "$existing" || gh label create "$1" --color "$2" --description "$3"; }
|
||||
force_label() { gh label create "$1" --color "$2" --description "$3" --force; }
|
||||
|
||||
force_label 'needs rebase' b60205 'Conflicts with main, rebase needed'
|
||||
force_label 'open PR limit' d93f0b 'Closed over the open PR limit: 1 without merged PRs, 20 with at least 1, none from 20'
|
||||
force_label ci 5319e7 '.github'
|
||||
force_label agc 1d76db 'libSceAgc*'
|
||||
force_label shader 1d76db 'core/shader'
|
||||
force_label 'unblocks title' 0e8a16 'Names a title ID on the Unblocks line'
|
||||
force_label perf fef2c0 'Performance change'
|
||||
force_label 'perf numbers missing' e99695 'perf pull request without a before and after summary line'
|
||||
|
||||
label relinker 5319e7 'core/relinker'
|
||||
label libc fbca04 'libc'
|
||||
label libkernel d93f0b 'libkernel'
|
||||
label prx c5def5 'Other PRX libraries'
|
||||
label build bfd4f2 'CMake, submodules, 3rdparty'
|
||||
label docs 0075ca 'Documentation'
|
||||
label 'fix error' d73a4a 'Closes an issue (Fixes #N)'
|
||||
label stale ededed 'Conflicting with main and no activity for 7 days'
|
||||
@@ -1,40 +0,0 @@
|
||||
name: Pages progress
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- core/libs/prx/**
|
||||
- core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
pages: read
|
||||
|
||||
concurrency:
|
||||
group: pages-progress
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
progress:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Deploy Pages if the progress changed
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
run: |
|
||||
python3 tools/progress.py "$RUNNER_TEMP/progress"
|
||||
site=$(gh api "repos/$GH_REPO/pages" --jq .html_url)
|
||||
if curl -fsSL "${site%/}/progress.json?$GITHUB_SHA" -o "$RUNNER_TEMP/deployed.json" &&
|
||||
cmp -s "$RUNNER_TEMP/deployed.json" "$RUNNER_TEMP/progress/progress.json"; then
|
||||
echo "Progress unchanged, Pages not deployed" >> "$GITHUB_STEP_SUMMARY"
|
||||
else
|
||||
gh workflow run pages.yml --ref main
|
||||
echo "Progress changed, Pages deployment dispatched" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
@@ -1,56 +0,0 @@
|
||||
name: Pages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- .github/workflows/pages.yml
|
||||
- CMakeLists.txt
|
||||
- core/relinker/**
|
||||
- demo/web/**
|
||||
- tools/build_web.py
|
||||
- tools/package_release.py
|
||||
- tools/nid_names.py
|
||||
- tools/progress.py
|
||||
- tools/progress_history.py
|
||||
- tools/rdna_isa.txt
|
||||
- tools/test_web.py
|
||||
workflow_dispatch:
|
||||
release:
|
||||
types: [published]
|
||||
workflow_run:
|
||||
workflows: [Release]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pages: write
|
||||
id-token: write
|
||||
|
||||
concurrency:
|
||||
group: pages
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
pages:
|
||||
if: github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
environment:
|
||||
name: github-pages
|
||||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
- name: Download matching release converter and libraries
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: python3 tools/build_web.py --build build-wasm --release
|
||||
- run: python3 tools/progress.py build-wasm/web
|
||||
- run: python3 tools/progress_history.py build-wasm/web
|
||||
- uses: actions/upload-pages-artifact@v5
|
||||
with:
|
||||
path: build-wasm/web
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v5
|
||||
@@ -1,101 +0,0 @@
|
||||
name: PR intake
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
branches: [main]
|
||||
types: [opened, reopened]
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: pr-intake-${{ github.event.pull_request.number }}
|
||||
|
||||
jobs:
|
||||
intake:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const { owner, repo } = context.repo;
|
||||
const pull_number = context.payload.pull_request.number;
|
||||
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
|
||||
if (pr.state !== 'open' || pr.base.ref !== 'main') {
|
||||
return;
|
||||
}
|
||||
if (context.payload.action === 'reopened') {
|
||||
let maintainer = false;
|
||||
try {
|
||||
const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({
|
||||
owner, repo, username: context.payload.sender.login
|
||||
});
|
||||
maintainer = ['admin', 'maintain', 'write'].includes(access.role_name ?? access.permission);
|
||||
} catch (error) {
|
||||
core.warning(`Could not check the permission of ${context.payload.sender.login}, so the open PR limit applies: ${error.message}`);
|
||||
}
|
||||
if (maintainer) {
|
||||
try {
|
||||
await github.rest.issues.removeLabel({ owner, repo, issue_number: pull_number, name: 'open PR limit' });
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
core.warning(`Could not remove the open PR limit label: ${error.message}`);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
const { data: mergedPRs } = await github.rest.search.issuesAndPullRequests({
|
||||
q: `repo:${owner}/${repo} is:pr is:merged base:main author:${pr.user.login}`,
|
||||
per_page: 1
|
||||
});
|
||||
if (mergedPRs.incomplete_results || !Number.isSafeInteger(mergedPRs.total_count) || mergedPRs.total_count < 0) {
|
||||
throw new Error('Could not reliably count merged pull requests');
|
||||
}
|
||||
const merged = mergedPRs.total_count;
|
||||
if (merged >= 20) {
|
||||
return;
|
||||
}
|
||||
const allowedOpen = merged >= 1 ? 20 : 1;
|
||||
const openPRs = await github.paginate(github.rest.pulls.list, {
|
||||
owner, repo, state: 'open', base: 'main', per_page: 100
|
||||
});
|
||||
const reopened = context.payload.action === 'reopened';
|
||||
const open = new Set(openPRs
|
||||
.filter((p) => p.user.login === pr.user.login && (reopened || p.number < pull_number))
|
||||
.map((p) => p.number));
|
||||
open.add(pull_number);
|
||||
if (open.size <= allowedOpen) {
|
||||
return;
|
||||
}
|
||||
const name = 'open PR limit';
|
||||
try {
|
||||
await github.rest.issues.getLabel({ owner, repo, name });
|
||||
} catch (error) {
|
||||
if (error.status !== 404) {
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
await github.rest.issues.createLabel({
|
||||
owner, repo, name, color: 'd93f0b',
|
||||
description: 'Closed over the open PR limit: 1 without merged PRs, 20 with at least 1, none from 20'
|
||||
});
|
||||
} catch (createError) {
|
||||
if (createError.status !== 422) {
|
||||
throw createError;
|
||||
}
|
||||
await github.rest.issues.getLabel({ owner, repo, name });
|
||||
}
|
||||
}
|
||||
await github.rest.issues.addLabels({ owner, repo, issue_number: pull_number, labels: [name] });
|
||||
const body = 'Thank you for your contribution! Authors with no pull requests merged into `main` can have 1 open pull request at a time, authors with at least 1 merged can have 20, and from 20 merged there is no limit. This PR has been automatically closed and labeled "open PR limit" because that limit was reached. This is not a judgment of the quality of your changes: reopen it once one of your open pull requests is merged or closed.';
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner, repo, issue_number: pull_number, per_page: 100
|
||||
});
|
||||
if (!comments.some((comment) => comment.user.login === 'github-actions[bot]' && comment.body === body)) {
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: pull_number, body });
|
||||
}
|
||||
await github.rest.pulls.update({ owner, repo, pull_number, state: 'closed' });
|
||||
@@ -1,35 +0,0 @@
|
||||
name: PR labels
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
branches: [main]
|
||||
types: [opened, edited, reopened, synchronize]
|
||||
schedule:
|
||||
- cron: '45 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: pr-labels-${{ github.event.pull_request.number || 'all' }}
|
||||
|
||||
jobs:
|
||||
labels:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GITHUB_REPOSITORY: ${{ github.repository }}
|
||||
PR_NUMBER: ${{ github.event.pull_request.number }}
|
||||
run: |
|
||||
if [ -n "$PR_NUMBER" ]; then
|
||||
python3 -I tools/pr_labels.py --pr "$PR_NUMBER"
|
||||
else
|
||||
python3 -I tools/pr_labels.py --all
|
||||
fi
|
||||
@@ -1,71 +0,0 @@
|
||||
name: PR overlap
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: '15 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
concurrency:
|
||||
group: pr-overlap
|
||||
|
||||
jobs:
|
||||
overlap:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/cache/restore@v6
|
||||
with:
|
||||
path: ${{ runner.temp }}/overlap-state.json
|
||||
key: pr-overlap-${{ github.run_id }}
|
||||
restore-keys: pr-overlap-
|
||||
- env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
run: |
|
||||
out=$RUNNER_TEMP/overlap
|
||||
state=$RUNNER_TEMP/overlap-state.json
|
||||
python3 tools/pr_overlap.py --base "${{ github.event.repository.default_branch }}" --out "$out"
|
||||
[ -s "$state" ] || echo '{}' > "$state"
|
||||
record() { jq --arg pr "$1" --arg h "$2" '.[$pr] = $h' "$state" > "$state.new" && mv "$state.new" "$state"; }
|
||||
shopt -s nullglob
|
||||
marker='<!-- pr-overlap -->'
|
||||
unpinned() { sed -E 's#/blob/[0-9a-f]{40}/#/blob/main/#g'; }
|
||||
prev=
|
||||
for file in "$out"/*.md; do
|
||||
[ -z "$prev" ] || record "$prev" "$hash"
|
||||
pr=$(basename "$file" .md)
|
||||
hash=$(unpinned < "$file" | sha256sum | cut -d' ' -f1)
|
||||
prev=
|
||||
[ "$(jq -r --arg pr "$pr" '.[$pr] // empty' "$state")" = "$hash" ] && continue
|
||||
prev=$pr
|
||||
comment=$(gh api "repos/$GH_REPO/issues/$pr/comments" --paginate \
|
||||
--jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | [.id, .body] | @json" | head -n1)
|
||||
id=$(jq -r '.[0] // empty' <<< "${comment:-null}")
|
||||
if [ -s "$file" ]; then
|
||||
[ "$(jq -r '.[1]' <<< "${comment:-null}" | unpinned)" = "$(unpinned < "$file")" ] && continue
|
||||
if [ -n "$id" ]; then
|
||||
gh api -X PATCH "repos/$GH_REPO/issues/comments/$id" -F body=@"$file" > /dev/null
|
||||
else
|
||||
gh pr comment "$pr" --body-file "$file"
|
||||
fi
|
||||
elif [ -n "$id" ]; then
|
||||
gh api -X DELETE "repos/$GH_REPO/issues/comments/$id"
|
||||
fi
|
||||
done
|
||||
[ -z "$prev" ] || record "$prev" "$hash"
|
||||
reports=$(for file in "$out"/*.md; do basename "$file" .md; done | jq -R . | jq -sc .)
|
||||
jq -c --argjson keep "$reports" 'with_entries(select(.key | IN($keep[])))' "$state" > "$state.new" && mv "$state.new" "$state"
|
||||
- if: always()
|
||||
uses: actions/cache/save@v6
|
||||
with:
|
||||
path: ${{ runner.temp }}/overlap-state.json
|
||||
key: pr-overlap-${{ github.run_id }}
|
||||
@@ -1,42 +0,0 @@
|
||||
name: Progress comment
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [Progress report]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
comment:
|
||||
if: github.event.workflow_run.conclusion == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: progress-report
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ github.token }}
|
||||
- env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
RUN_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
run: |
|
||||
pr=$(cat pr)
|
||||
[[ $pr =~ ^[0-9]+$ ]] || exit 1
|
||||
[ "$(gh pr view "$pr" --json headRefOid --jq .headRefOid)" = "$RUN_SHA" ] || exit 0
|
||||
marker='<!-- progress-report -->'
|
||||
id=$(gh api "repos/$GH_REPO/issues/$pr/comments" --paginate \
|
||||
--jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | .id" | head -n1)
|
||||
if [ -f report.md ]; then
|
||||
printf '%s\n%s' "$marker" "$(cat report.md)" > body.md
|
||||
if [ -n "$id" ]; then
|
||||
gh api -X PATCH "repos/$GH_REPO/issues/comments/$id" -F body=@body.md > /dev/null
|
||||
else
|
||||
gh pr comment "$pr" --body-file body.md
|
||||
fi
|
||||
elif [ -n "$id" ]; then
|
||||
gh api -X DELETE "repos/$GH_REPO/issues/comments/$id"
|
||||
fi
|
||||
@@ -1,38 +0,0 @@
|
||||
name: Progress report
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'core/libs/prx/**'
|
||||
- 'tools/progress.py'
|
||||
- '.github/workflows/progress-report.yml'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
report:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 2
|
||||
- env:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: |
|
||||
out=$RUNNER_TEMP/out report=$RUNNER_TEMP/report
|
||||
git worktree add --detach "$RUNNER_TEMP/base" HEAD^1
|
||||
python3 tools/progress.py --root "$RUNNER_TEMP/base" "$out/base"
|
||||
python3 tools/progress.py "$out/head"
|
||||
mkdir "$report"
|
||||
echo "$PR" > "$report/pr"
|
||||
body=$(python3 tools/progress.py --compare "$out/base/progress.json" "$out/head/progress.json")
|
||||
if [ -n "$body" ]; then
|
||||
printf '### Progress report (%s → %s)\n\n%s\n' "$(git rev-parse --short HEAD^1)" "${HEAD_SHA::7}" "$body" > "$report/report.md"
|
||||
cat "$report/report.md" >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: progress-report
|
||||
path: ${{ runner.temp }}/report
|
||||
@@ -1,178 +0,0 @@
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
RELEASE_TAG: ${{ github.ref_name }}
|
||||
CONFIGURE: >-
|
||||
-G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
|
||||
-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
|
||||
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
|
||||
WINLIBS_RELEASE: 15.2.0posix-14.0.0-ucrt-r7
|
||||
WINLIBS_ZIP: winlibs-x86_64-posix-seh-gcc-15.2.0-mingw-w64ucrt-14.0.0-r7.zip
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build and test (${{ matrix.platform }})
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux
|
||||
runner: ubuntu-latest
|
||||
timeout: 30
|
||||
- platform: windows
|
||||
runner: windows-latest
|
||||
timeout: 45
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: ${{ matrix.timeout }}
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
submodules: recursive
|
||||
- name: Point the WinLibs CMake at the CA bundle of Git for Windows
|
||||
if: matrix.platform == 'windows'
|
||||
shell: bash
|
||||
run: |
|
||||
for prefix in ucrt64 mingw64; do
|
||||
bundle="C:/Program Files/Git/$prefix/etc/ssl/certs/ca-bundle.crt"
|
||||
if [ -f "$bundle" ]; then echo "SSL_CERT_FILE=$bundle" >> "$GITHUB_ENV"; exit 0; fi
|
||||
done
|
||||
echo "::error::No CA bundle found in Git for Windows"; exit 1
|
||||
- id: toolchain
|
||||
if: matrix.platform == 'windows'
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: C:\winlibs
|
||||
key: ${{ env.WINLIBS_ZIP }}
|
||||
- if: matrix.platform == 'windows' && steps.toolchain.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
curl -sSfL -o "$RUNNER_TEMP/winlibs.zip" "https://github.com/brechtsanders/winlibs_mingw/releases/download/$WINLIBS_RELEASE/$WINLIBS_ZIP"
|
||||
7z x "$RUNNER_TEMP/winlibs.zip" -oC:/winlibs
|
||||
- if: matrix.platform == 'windows'
|
||||
run: echo 'C:\winlibs\mingw64\bin' >> "$GITHUB_PATH"
|
||||
- uses: hendrikmuhs/ccache-action@v1.2.24
|
||||
with:
|
||||
key: ${{ matrix.platform }}
|
||||
save: false
|
||||
- name: Install lavapipe for the GPU execution tests and the audio development files
|
||||
if: matrix.platform == 'linux'
|
||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libvulkan1 mesa-vulkan-drivers libpipewire-0.3-dev libpulse-dev libasound2-dev libxrandr-dev libwayland-dev libxkbcommon-dev libegl-dev libdecor-0-dev
|
||||
- name: Configure Linux
|
||||
if: matrix.platform == 'linux'
|
||||
run: cmake -S . -B build $CONFIGURE
|
||||
- name: Configure Windows
|
||||
if: matrix.platform == 'windows'
|
||||
shell: cmd
|
||||
run: cmake -S . -B build %CONFIGURE%
|
||||
- name: Build project and tests (Linux)
|
||||
if: matrix.platform == 'linux'
|
||||
run: cmake --build build
|
||||
- name: Build project and tests (Windows)
|
||||
if: matrix.platform == 'windows'
|
||||
shell: cmd
|
||||
run: cmake --build build
|
||||
- name: Run tests (Linux)
|
||||
if: matrix.platform == 'linux'
|
||||
run: ctest --test-dir build --output-on-failure --timeout 120 --stop-on-failure --no-tests=error -E '^precise_wait$'
|
||||
env:
|
||||
ANYPS5_REQUIRE_VULKAN: 1
|
||||
GALLIUM_OVERRIDE_CPU_CAPS: avx
|
||||
- name: Run tests (Windows)
|
||||
if: matrix.platform == 'windows'
|
||||
shell: cmd
|
||||
run: ctest --test-dir build --output-on-failure --timeout 120 --stop-on-failure --no-tests=error
|
||||
- name: Build patched libraries (Linux)
|
||||
if: matrix.platform == 'linux'
|
||||
run: cmake --build build --target libs
|
||||
- name: Build patched libraries (Windows)
|
||||
if: matrix.platform == 'windows'
|
||||
shell: cmd
|
||||
run: cmake --build build --target libs
|
||||
- name: Package release files
|
||||
run: python tools/package_release.py --platform "${{ matrix.platform }}" --build build --output dist --version "$RELEASE_TAG"
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-${{ matrix.platform }}
|
||||
path: dist/*
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
web:
|
||||
name: Build and test web converter
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
- name: Build web converter
|
||||
shell: bash
|
||||
run: |
|
||||
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$RUNNER_TEMP/emsdk"
|
||||
"$RUNNER_TEMP/emsdk/emsdk" install 6.0.3
|
||||
"$RUNNER_TEMP/emsdk/emsdk" activate 6.0.3
|
||||
source "$RUNNER_TEMP/emsdk/emsdk_env.sh"
|
||||
emcmake cmake -S . -B build-wasm -DANYPS5_BUILD_WASM=ON -DBUILD_TESTING=OFF -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build-wasm --target relinker_web --parallel 2
|
||||
- name: Test web converter
|
||||
run: python3 tools/test_web.py --build build-wasm
|
||||
- name: Package web converter
|
||||
shell: bash
|
||||
run: python3 tools/package_release.py --platform web --build build-wasm --output dist --version "$RELEASE_TAG" --revision "$(git rev-parse HEAD)"
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: release-web
|
||||
path: dist/*
|
||||
if-no-files-found: error
|
||||
compression-level: 0
|
||||
|
||||
publish:
|
||||
name: Publish release
|
||||
needs: [build, web]
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
GH_REPO: ${{ github.repository }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
pattern: release-*
|
||||
merge-multiple: true
|
||||
path: dist
|
||||
- name: Check release files and collect documentation
|
||||
shell: bash
|
||||
run: |
|
||||
for file in "prx-windows-$RELEASE_TAG.zip" "prx-windows-$RELEASE_TAG.tar.gz" "prx-linux-$RELEASE_TAG.zip" "prx-linux-$RELEASE_TAG.tar.gz" "relinker-$RELEASE_TAG.exe" "relinker-$RELEASE_TAG" "web-$RELEASE_TAG.zip"; do
|
||||
test -s "dist/$file"
|
||||
done
|
||||
python tools/package_release.py --docs docs/user --output dist
|
||||
chmod +x "dist/relinker-$RELEASE_TAG"
|
||||
- name: Prepare release notes
|
||||
shell: bash
|
||||
run: |
|
||||
gh api --method POST "repos/$GH_REPO/releases/generate-notes" -f tag_name="$RELEASE_TAG" > "$RUNNER_TEMP/release-notes.json"
|
||||
python tools/prepare_release_notes.py --input "$RUNNER_TEMP/release-notes.json" --body "$RUNNER_TEMP/release-body.md" --full dist/release-notes.md
|
||||
- name: Create draft and upload files
|
||||
run: gh release create "$RELEASE_TAG" dist/* --verify-tag --draft --title "$RELEASE_TAG" --notes-file "$RUNNER_TEMP/release-body.md"
|
||||
- name: Publish complete release
|
||||
run: gh release edit "$RELEASE_TAG" --draft=false
|
||||
@@ -1,36 +0,0 @@
|
||||
name: Stale conflicts
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '30 3 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions: {}
|
||||
|
||||
jobs:
|
||||
warn:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
issues: write
|
||||
pull-requests: write
|
||||
steps:
|
||||
- env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
gh pr list -R "$GITHUB_REPOSITORY" --label stale -L 1000 --json number,labels \
|
||||
--jq '.[] | select(all(.labels[]; .name != "needs rebase")) | .number' |
|
||||
while read -r number; do
|
||||
gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$number/labels/stale" --silent
|
||||
done
|
||||
- uses: actions/stale@v11
|
||||
with:
|
||||
only-pr-labels: needs rebase
|
||||
days-before-issue-stale: -1
|
||||
days-before-issue-close: -1
|
||||
days-before-pr-stale: 7
|
||||
days-before-pr-close: -1
|
||||
stale-pr-label: stale
|
||||
stale-pr-message: 'This pull request has conflicted with `main` and had no activity for 7 days. Rebase it on current `main` so it can be reviewed and merged. It will not be closed automatically.'
|
||||
remove-pr-stale-when-updated: true
|
||||
exempt-draft-pr: true
|
||||
operations-per-run: 200
|
||||
@@ -1,39 +0,0 @@
|
||||
name: Web tests
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- .github/workflows/web-tests.yml
|
||||
- demo/web/**
|
||||
- tools/test_web.py
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: web-tests-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
output-directory:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
persist-credentials: false
|
||||
- name: Test archive root selection
|
||||
shell: bash
|
||||
run: |
|
||||
zip_url=$(python3 -c 'from pathlib import Path; import re; print(re.search(r"from \"(https://cdn.jsdelivr.net/[^\"]+)\"", Path("demo/web/archive.mjs").read_text(encoding="utf-8")).group(1))')
|
||||
curl -fsSL "$zip_url" -o "$RUNNER_TEMP/zip.mjs"
|
||||
ANYPS5_TEST_ZIP_URL="$zip_url" ANYPS5_TEST_ZIP_PATH="$(python3 -c 'from pathlib import Path; import sys; print(Path(sys.argv[1]).resolve().as_uri())' "$RUNNER_TEMP/zip.mjs")" node demo/web/tests/archive-root.test.mjs demo/web
|
||||
- name: Check browser module syntax
|
||||
run: |
|
||||
node --check demo/web/app.mjs
|
||||
node --check demo/web/archive.mjs
|
||||
node --check demo/web/batch.mjs
|
||||
node --check demo/web/output-directory.mjs
|
||||
node --check demo/web/worker.mjs
|
||||
- name: Test browser converter helpers
|
||||
run: node --test demo/web/tests/batch.test.mjs demo/web/tests/output-directory.test.mjs
|
||||
+18
-106
@@ -1,111 +1,23 @@
|
||||
*.d
|
||||
# The bare mirror holds upstream objects; never commit it.
|
||||
.mirror/
|
||||
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
*.ilk
|
||||
*.pdb
|
||||
|
||||
*.so
|
||||
*.so.*
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
|
||||
_SaveData/
|
||||
_sd/
|
||||
|
||||
build/
|
||||
build_tools/
|
||||
b/
|
||||
Build/
|
||||
build-*/
|
||||
cmake-build-debug/
|
||||
cmake-build-release/
|
||||
cmake-build-*/
|
||||
CMakeFiles/
|
||||
CMakeCache.txt
|
||||
cmake_install.cmake
|
||||
Makefile
|
||||
install_manifest.txt
|
||||
compile_commands.json
|
||||
vcpkg_installed/
|
||||
Testing/
|
||||
tests/sdf/
|
||||
.cache/
|
||||
|
||||
sqlce_wasm.js
|
||||
sqlce_wasm.wasm
|
||||
emsdk/
|
||||
build-wasm/
|
||||
# Local runner config (contains tokens) — but KEEP runner/docker-compose.yml
|
||||
# tracked, otherwise a fresh fork has no documented runner setup at all.
|
||||
# (The runner/_svc_*.go files are untracked Gitea-source scratch snippets.)
|
||||
runner/config/
|
||||
runner/_svc_*.go
|
||||
*.runner.conf
|
||||
|
||||
# OS / editor noise
|
||||
.DS_Store
|
||||
*.swp
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
|
||||
__pycache__/
|
||||
*.pyo
|
||||
*.pyd
|
||||
*.egg
|
||||
*.egg-info/
|
||||
dist/
|
||||
|
||||
*.dwo
|
||||
|
||||
.pytest_cache/
|
||||
coverage.xml
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
*.tmp
|
||||
*.log
|
||||
*.bak
|
||||
*.swp
|
||||
|
||||
raw/
|
||||
images/
|
||||
sessions/
|
||||
downloads/
|
||||
|
||||
*.tar.gz
|
||||
*.zip
|
||||
*.whl
|
||||
*.env
|
||||
*.sdf
|
||||
|
||||
*.bat
|
||||
*.jpg
|
||||
*.png
|
||||
|
||||
*.json
|
||||
!demo/web/i18n/*.json
|
||||
|
||||
!/assets/*.jpg
|
||||
!/assets/*.png
|
||||
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
cookies.txt
|
||||
|
||||
.env
|
||||
.env.local
|
||||
# stray binaries that are never part of this template
|
||||
*.AppImage
|
||||
*.appimage
|
||||
.superdesign/
|
||||
ui/node_modules/
|
||||
ui/dist/
|
||||
ui/*.log
|
||||
-51
@@ -1,51 +0,0 @@
|
||||
[submodule "3rdparty/SDL2"]
|
||||
path = 3rdparty/SDL2
|
||||
url = https://github.com/libsdl-org/SDL.git
|
||||
[submodule "3rdparty/Vulkan-Headers"]
|
||||
path = 3rdparty/Vulkan-Headers
|
||||
url = https://github.com/KhronosGroup/Vulkan-Headers.git
|
||||
[submodule "3rdparty/SPIRV-Headers"]
|
||||
path = 3rdparty/SPIRV-Headers
|
||||
url = https://github.com/KhronosGroup/SPIRV-Headers.git
|
||||
[submodule "3rdparty/SPIRV-Tools"]
|
||||
path = 3rdparty/SPIRV-Tools
|
||||
url = https://github.com/KhronosGroup/SPIRV-Tools.git
|
||||
[submodule "3rdparty/glslang"]
|
||||
path = 3rdparty/glslang
|
||||
url = https://github.com/KhronosGroup/glslang.git
|
||||
[submodule "3rdparty/VulkanMemoryAllocator"]
|
||||
path = 3rdparty/VulkanMemoryAllocator
|
||||
url = https://github.com/GPUOpen-LibrariesAndSDKs/VulkanMemoryAllocator.git
|
||||
[submodule "3rdparty/LibAtrac9"]
|
||||
path = 3rdparty/LibAtrac9
|
||||
url = https://github.com/shadps4-emu/ext-LibAtrac9.git
|
||||
[submodule "3rdparty/ffmpeg-core"]
|
||||
path = 3rdparty/ffmpeg-core
|
||||
url = https://github.com/KytyPS5/ext-ffmpeg-core.git
|
||||
[submodule "3rdparty/freetype"]
|
||||
path = 3rdparty/freetype
|
||||
url = https://github.com/freetype/freetype.git
|
||||
[submodule "3rdparty/stb"]
|
||||
path = 3rdparty/stb
|
||||
url = https://github.com/nothings/stb.git
|
||||
[submodule "3rdparty/tracy"]
|
||||
path = 3rdparty/tracy
|
||||
url = https://github.com/wolfpld/tracy.git
|
||||
[submodule "3rdparty/mimalloc"]
|
||||
path = 3rdparty/mimalloc
|
||||
url = https://github.com/microsoft/mimalloc.git
|
||||
[submodule "3rdparty/libjpeg-turbo"]
|
||||
path = 3rdparty/libjpeg-turbo
|
||||
url = https://github.com/libjpeg-turbo/libjpeg-turbo.git
|
||||
[submodule "3rdparty/libusb-cmake"]
|
||||
path = 3rdparty/libusb-cmake
|
||||
url = https://github.com/libusb/libusb-cmake.git
|
||||
[submodule "3rdparty/mbedtls"]
|
||||
path = 3rdparty/mbedtls
|
||||
url = https://github.com/Mbed-TLS/mbedtls.git
|
||||
[submodule "3rdparty/zstd"]
|
||||
path = 3rdparty/zstd
|
||||
url = https://github.com/facebook/zstd.git
|
||||
[submodule "3rdparty/ZArchive"]
|
||||
path = 3rdparty/ZArchive
|
||||
url = https://github.com/Exzap/ZArchive.git
|
||||
Vendored
-1
Submodule 3rdparty/LibAtrac9 deleted from 946e05a921.
Vendored
-1
Submodule 3rdparty/SDL2 deleted from 4b69833bc5.
Vendored
-1
Submodule 3rdparty/SPIRV-Headers deleted from 01e0577914.
Vendored
-1
Submodule 3rdparty/SPIRV-Tools deleted from 7f2d9ee926.
Vendored
-1
Submodule 3rdparty/Vulkan-Headers deleted from 2fa203425e.
Vendored
-1
Submodule 3rdparty/VulkanMemoryAllocator deleted from a1d434708c.
Vendored
-1
Submodule 3rdparty/ZArchive deleted from 965b66c8d6.
Vendored
-1
Submodule 3rdparty/ffmpeg-core deleted from 9ac4cfd195.
Vendored
-1
Submodule 3rdparty/freetype deleted from 42608f77f2.
Vendored
-1
Submodule 3rdparty/glslang deleted from ba1640446f.
Vendored
-1
Submodule 3rdparty/libjpeg-turbo deleted from c85e6b905b.
Vendored
-1
Submodule 3rdparty/libusb-cmake deleted from bea6567b63.
Vendored
-1
Submodule 3rdparty/mbedtls deleted from 068ff080b3.
Vendored
-1
Submodule 3rdparty/mimalloc deleted from f8401befa6.
Vendored
-1
Submodule 3rdparty/stb deleted from 2c980bb598.
Vendored
-1
Submodule 3rdparty/tracy deleted from 30997d5ca6.
Vendored
-1
Submodule 3rdparty/zstd deleted from f8745da6ff.
@@ -1,15 +1,151 @@
|
||||
# AGENTS.md
|
||||
# AGENTS.md — how to operate Repo Forker
|
||||
|
||||
AnyPS5 relinks PS5 executables into native Linux or Windows programs that run against reimplemented system libraries; it is not an emulator. The rules are [CONTRIBUTING.md](CONTRIBUTING.md) and [CONVENTIONS](docs/dev/CONVENTIONS.md); these are the ones agents break.
|
||||
Instructions for AI agents (and humans) working on or with this repository.
|
||||
|
||||
- No comments in code, except `#endif` and namespace ends.
|
||||
- An export you cannot implement calls `NotImplemented_nid_no_patch(__func__)`; never return a made-up success.
|
||||
- Implement the function for every input. Never special-case a value, ID or path seen in one title's trace; if the general behaviour is unknown, throw and record it in `docs/dev/debt/<library>.md`.
|
||||
- New third-party code is a submodule at `3rdparty/<name>`: add its `.gitmodules` entry (`git submodule add <url> 3rdparty/<name>`) and build it from source with CMake. Never `find_package` or copy sources in.
|
||||
- Known gaps go in `docs/dev/debt/<library>.md`; notes, reports and logs go in the pull request. Add no other files.
|
||||
- Commit subjects and PR titles are Conventional Commits.
|
||||
- PR body: copy [the template](.github/pull_request_template.md), keep every line, tick every box, and fill `What`, `Tested`, `Depends on` (#N or none), `Unblocks` (title ID and discussion, or none), `GPUs tested` (AGC, shader recompiler, VideoOut; otherwise n/a) and `AI-assisted` (yes or no).
|
||||
- Before pushing run `python3 tools/check_conventions.py --base origin/main`; before opening run `python3 tools/pr_overlap.py --branch <branch>`.
|
||||
- Build and test: [BUILD](docs/dev/BUILD.md); a relinker-only change builds with `-DANYPS5_RELINKER_ONLY=ON`.
|
||||
- A speed claim shows `tools/trace_digest.py` summaries of `main` and of the change from the same machine and scene.
|
||||
- AGC, shader recompiler and VideoOut changes: run the same focused tests on `main` and the change with `ANYPS5_REQUIRE_VULKAN=1`, `ANYPS5_NO_SHADER_CACHE=1` and `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation` using `ctest --test-dir build -R <pattern> -V` from the same machine and GPU. Confirm neither log contains `was not found but was requested by env var VK_INSTANCE_LAYERS`, then compare the logs and confirm the change adds no new `VUID-` validation errors (`ctest` can report `Passed` when validation errors are logged).
|
||||
## What this is
|
||||
|
||||
A **template**. Each fork/generation of it is a *live mirror* of one upstream
|
||||
git repo on this Gitea: all branches, all tags, full history, plus releases
|
||||
produced on the runner. The working tree (the `forker` branch) holds only the
|
||||
machinery — the upstream's content never enters it.
|
||||
|
||||
```
|
||||
This repo (template) → fork/generate per upstream (Lago/<upstream>)
|
||||
├── forker branch ← scripts, config, workflows
|
||||
├── .mirror/ ← bare mirror (gitignored)
|
||||
└── refs ← upstream branches + tags
|
||||
```
|
||||
|
||||
## Golden rules (non-negotiable)
|
||||
|
||||
1. **Never authenticate to upstreams with the operator's personal accounts or
|
||||
stored credentials.** Public upstreams are fetched **anonymously**:
|
||||
`sync.sh`/`release.sh` cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the
|
||||
credential helper before any upstream git call, and add a Bearer header
|
||||
**only** when `UPSTREAM_TOKEN` is explicitly set. Do not "simplify" this
|
||||
away — a `credential.helper=store` entry must never be offered to
|
||||
`git fetch`. Do not pass tokens from `~/.git-credentials` into the tool.
|
||||
2. **An empty token must mean "no auth header", not "Bearer <empty>".**
|
||||
GitHub rejects empty Bearer headers (401). All code paths (git
|
||||
`extraHeader`, `provider.sh` curl calls) must branch on token presence.
|
||||
3. **Secrets live in Gitea Actions Variables/Secrets, never in the repo.**
|
||||
`UPSTREAM_URL` (variable) and `UPSTREAM_TOKEN` (secret, optional). The
|
||||
`GITEA_*` values are injected by Gitea Actions automatically.
|
||||
4. **Keep `.forker.yaml` flat** (`key: value`, no nesting) — `config.sh` is a
|
||||
simple grep parser.
|
||||
|
||||
## How it runs
|
||||
|
||||
- **Cron** (`sync.yml`, every 10 min) → `forker/sync.sh`:
|
||||
1. fetch all branches + tags + history into the bare `.mirror/` (incremental
|
||||
when `actions/cache` restores it),
|
||||
2. push refs onto this repo + prune what upstream deleted (fork state is
|
||||
read via the Gitea **API**, not git state — works on cold mirrors),
|
||||
3. for each **tag that has no release yet**, run `forker/release.sh <tag>`
|
||||
inline (a tag-push can't trigger a workflow: the tag points at an upstream
|
||||
commit whose tree has no `.gitea/workflows`). The "missing release" check
|
||||
(not "new tag") makes a failed release retry on the next cron tick.
|
||||
`release.sh` publishes only when there is actual content (build assets or
|
||||
an existing upstream release) and fails loudly on a bad asset
|
||||
download/upload — a partial release never masquerades as success.
|
||||
4. `forker/check-unit.sh` — verifies the **Releases unit** is enabled
|
||||
(self-heals via the units API when the build exposes it; otherwise
|
||||
detects the 404 and prints the one-time UI fix).
|
||||
- `release.sh` = local build (if `build_cmd`/`build_script` set) + optional
|
||||
upstream-release mirror (metadata + assets via `forker/lib/provider.sh`).
|
||||
Idempotent: an existing release is skipped, not duplicated.
|
||||
- `runner-check.yml` — run once per repo to confirm a runner serves it.
|
||||
**Runners are repo-scoped on this Gitea build**: a runner registered on one
|
||||
repo does not serve another. Use a **shared** runner (or PATCH the runner
|
||||
to `"shared":true` — the units/runners APIs are missing here, so UI/DB).
|
||||
|
||||
## Known Gitea-build quirks (verified on git.lago.dev, Gitea 28.1.0)
|
||||
|
||||
- **Forks are created without the Releases unit**
|
||||
(`DefaultForkRepoUnits = [Code, PullRequests]`) → release assets 404 on the
|
||||
web download route (`context.RequireUnitReader`), the source tarball 404s
|
||||
too, while the API by-id works. Fix: enable the Releases unit
|
||||
(Settings → Repository, or DB `INSERT INTO repo_unit (repo_id, type) ... 4` —
|
||||
there is no units API on this build). `check-unit.sh` detects/fixes.
|
||||
**Prefer generating from this template over forking**: generated repos are
|
||||
not forks and get the full unit set (and Gitea only allows 1 fork of a
|
||||
repo per user).
|
||||
- **GitHub asset gotcha**: for a release addressed by *tag*, the asset
|
||||
`download_url` is **null** — the API `url` returns JSON metadata unless
|
||||
`Accept: application/octet-stream` is sent. `provider.sh` instead resolves
|
||||
to the **web download URL** (`github.com/.../releases/download/<tag>/<file>`),
|
||||
which is also unthrottled (the REST asset endpoint is 60 req/h
|
||||
unauthenticated — not enough to mirror ~200 assets).
|
||||
- Runner registration: the `gitea/act_runner` CLI (old and new) fails on this
|
||||
build ("instance address is empty"); runner creation via API is 405.
|
||||
Existing runners can be made shared via `PATCH /api/v1/admin/actions/runners/<id>`.
|
||||
- `actions/cache` timeouts on this build are handled with
|
||||
`continue-on-error: true` (cold fetch is still correct). The artifact cache
|
||||
service itself is NOT configured on this Gitea — every sync is a cold fetch
|
||||
(correct, slower; the cache steps are kept in case a backend is added).
|
||||
- **Per-job DNS flapping:** the ephemeral per-job container intermittently
|
||||
fails to resolve `git.lago.dev` on the fork push (the runner daemon's own
|
||||
network resolves fine). `sync.sh` therefore wraps every fork push in
|
||||
`push_once` — retry with backoff on transient network errors (resolve /
|
||||
connect / timeout), abort immediately on non-network failures.
|
||||
|
||||
## Editing the template vs. a mirror repo
|
||||
|
||||
- **Template** (this repo): edit on `forker` and `git push`. Mirror repos do
|
||||
**not** auto-track the template — sync them manually after a template
|
||||
change:
|
||||
- **Forked repos** (e.g. `Lago/photocraft`): the `forker` branch *is* a
|
||||
descendant of the template's, so a normal merge works:
|
||||
```
|
||||
git remote add template <template-url>
|
||||
git fetch template forker
|
||||
git checkout forker && git merge template/forker
|
||||
git push origin forker
|
||||
```
|
||||
- **Generated repos** (e.g. `Lago/pdfcraft`): the `forker` branch is an
|
||||
**unrelated snapshot** (no common ancestor — `git merge` fails with
|
||||
add/add conflicts). Reset it to the template and re-apply the single
|
||||
per-repo setting, then force-push:
|
||||
```
|
||||
git checkout forker
|
||||
git fetch template forker
|
||||
git reset --hard template/forker
|
||||
# re-apply this repo's .forker.yaml setting(s), e.g.:
|
||||
sed -i 's/^mirror_upstream_releases: false/mirror_upstream_releases: true/' .forker.yaml
|
||||
git commit -am "Adopt template; enable mirror_upstream_releases"
|
||||
git push --force origin forker
|
||||
```
|
||||
This is safe: `forker` holds only the machinery + config (the upstream
|
||||
content lives on the mirrored branches), so the snapshot's extra content
|
||||
is discarded by design.
|
||||
- **Per-repo config**: edit `.forker.yaml` in the UI on the `forker` branch.
|
||||
Pushing to `forker` triggers a re-sync.
|
||||
|
||||
## Local testing (without the runner)
|
||||
|
||||
```
|
||||
export UPSTREAM_URL=... UPSTREAM_TOKEN= # empty for public upstreams
|
||||
export GITEA_TOKEN=... GITEA_SERVER_URL=... GITEA_OWNER=... GITEA_REPO=...
|
||||
bash forker/sync.sh # full mirror (use a scratch repo!)
|
||||
bash forker/release.sh <tag>
|
||||
make check-unit
|
||||
```
|
||||
Test against a **scratch repo** you delete afterwards; never point the scripts
|
||||
at a real mirror while experimenting. `GITEA_TOKEN` from Actions is an API
|
||||
token (Bearer works for API + git); a *password* only works for basic auth —
|
||||
expect the Bearer API calls to fail when testing with a password.
|
||||
|
||||
## File map
|
||||
|
||||
- `forker/sync.sh` — mirror worker (fetch/push/prune + inline releases + unit check)
|
||||
- `forker/release.sh` — local build + upstream-release mirror, idempotent
|
||||
- `forker/check-unit.sh` — Releases unit detection/self-heal (exit 10 = missing)
|
||||
- `forker/lib/config.sh` — flat `.forker.yaml` parser
|
||||
- `forker/lib/provider.sh` — provider-agnostic releases API (github/gitea/codeberg)
|
||||
- `forker/runner-register.sh` — runner registration (see quirks above)
|
||||
- `.gitea/workflows/` — sync.yml (cron), release.yml (manual), runner-check.yml
|
||||
- `runner/docker-compose.yml` — gitea-act-runner in Docker (tracked; the local
|
||||
`runner/config/` token dir is gitignored)
|
||||
- `Makefile` — local targets (sync / release / mirror-releases / runner-check /
|
||||
runner-register / check-unit); `runner-check` queries the Gitea runner APIs
|
||||
- `docs/index.html` — architecture webpage (static)
|
||||
-360
@@ -1,360 +0,0 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
if(CMAKE_HOST_APPLE AND NOT ANYPS5_RELINKER_ONLY)
|
||||
set(CMAKE_APPLE_SILICON_PROCESSOR x86_64 CACHE STRING "Host processor CMake reports on Apple silicon")
|
||||
set(CMAKE_OSX_ARCHITECTURES x86_64 CACHE STRING "Architectures built on macOS")
|
||||
endif()
|
||||
project(Relinker CXX)
|
||||
|
||||
set(ANYPS5_TEST_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/tests")
|
||||
set(ANYPS5_WINDOWS_TEST_EXIT "${CMAKE_CURRENT_SOURCE_DIR}/cmake/WindowsTestExit.cpp")
|
||||
|
||||
function(add_test_executable target)
|
||||
add_executable(${target} ${ARGN})
|
||||
set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>")
|
||||
if(MINGW)
|
||||
target_sources(${target} PRIVATE "${ANYPS5_WINDOWS_TEST_EXIT}")
|
||||
target_link_options(${target} PRIVATE LINKER:--wrap=main)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
function(add_asan_test_options test options)
|
||||
if(ANYPS5_ENABLE_ASAN)
|
||||
set_property(TEST ${test} APPEND PROPERTY ENVIRONMENT_MODIFICATION "ASAN_OPTIONS=string_append::${options}")
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
option(BUILD_TESTING "Build and register relinker tests" OFF)
|
||||
option(ANYPS5_RELINKER_ONLY "Build the relinker without system libraries or third-party dependencies" OFF)
|
||||
option(ANYPS5_BUILD_WASM "Build the browser relinker" OFF)
|
||||
if(ANYPS5_BUILD_WASM)
|
||||
if(NOT EMSCRIPTEN)
|
||||
message(FATAL_ERROR "ANYPS5_BUILD_WASM requires emcmake and Emscripten")
|
||||
endif()
|
||||
if(BUILD_TESTING)
|
||||
message(FATAL_ERROR "Use the native build for C++ tests and the browser tests for WASM")
|
||||
endif()
|
||||
set(ANYPS5_RELINKER_CLI OFF CACHE BOOL "Build the native relinker command line" FORCE)
|
||||
add_subdirectory(core/relinker)
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
enable_testing()
|
||||
if(MINGW)
|
||||
get_filename_component(testCompilerDirectory "${CMAKE_CXX_COMPILER}" DIRECTORY)
|
||||
foreach(runtimeName IN ITEMS libgcc_s_seh-1.dll libstdc++-6.dll libwinpthread-1.dll)
|
||||
if(NOT EXISTS "${testCompilerDirectory}/${runtimeName}")
|
||||
if(ANYPS5_RELINKER_ONLY)
|
||||
continue()
|
||||
endif()
|
||||
message(FATAL_ERROR "Cannot locate MinGW runtime: ${runtimeName}")
|
||||
endif()
|
||||
file(COPY "${testCompilerDirectory}/${runtimeName}" DESTINATION "${ANYPS5_TEST_OUTPUT_DIRECTORY}")
|
||||
endforeach()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
option(ANYPS5_ENABLE_SPIRV_TOOLS "Enable SPIRV-Tools validation and optimization" OFF)
|
||||
option(ANYPS5_ENABLE_ASAN "Build Linux targets with AddressSanitizer and use an ASan-compatible guest arena range" OFF)
|
||||
option(APS5_ENABLE_TIMING_LOG "Write frame timings asynchronously to frame-timing.log" OFF)
|
||||
option(APS5_ENABLE_TRACY "Build the Tracy profiler client and report performance timer scopes as Tracy zones" OFF)
|
||||
option(ANYPS5_USE_SYSTEM_DEPS "Resolve SDL2, freetype, Vulkan-Headers, SPIRV-Headers, glslang and SPIRV-Tools from the system instead of the bundled submodules" OFF)
|
||||
add_compile_definitions(APS5_ENABLE_TIMING_LOG=$<BOOL:${APS5_ENABLE_TIMING_LOG}>)
|
||||
include(cmake/SystemDeps.cmake)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
include(CheckCXXSourceCompiles)
|
||||
function(anyps5_check_cxx_links_standard_library)
|
||||
set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE)
|
||||
check_cxx_source_compiles("#include <string>\nint main(int argc, char**) { try { throw std::string(static_cast<std::size_t>(argc), 'x'); } catch (const std::string& text) { return static_cast<int>(text.size()) - argc; } }" ANYPS5_CXX_LINKS_STANDARD_LIBRARY)
|
||||
endfunction()
|
||||
anyps5_check_cxx_links_standard_library()
|
||||
if(NOT ANYPS5_CXX_LINKS_STANDARD_LIBRARY)
|
||||
message(FATAL_ERROR "The C++ compiler ${CMAKE_CXX_COMPILER} cannot link a program that uses the C++ standard library. "
|
||||
"Set CMAKE_CXX_COMPILER to the C++ driver (g++ or clang++, not gcc or clang) in a new build directory. "
|
||||
"Supported toolchains are listed in docs/dev/BUILD.md.")
|
||||
endif()
|
||||
|
||||
if(ANYPS5_ENABLE_ASAN)
|
||||
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
message(FATAL_ERROR "ANYPS5_ENABLE_ASAN is supported only on Linux")
|
||||
endif()
|
||||
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "^(GNU|Clang)$")
|
||||
message(FATAL_ERROR "ANYPS5_ENABLE_ASAN requires GCC or Clang")
|
||||
endif()
|
||||
add_compile_options(-fsanitize=address -fno-omit-frame-pointer)
|
||||
add_link_options(-fsanitize=address)
|
||||
add_compile_definitions(ANYPS5_ENABLE_ASAN=1)
|
||||
elseif(NOT APPLE)
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static -static-libgcc -static-libstdc++")
|
||||
endif()
|
||||
|
||||
if(APPLE AND NOT ANYPS5_RELINKER_ONLY)
|
||||
add_compile_options($<$<COMPILE_LANGUAGE:CXX>:-fexperimental-library>)
|
||||
add_link_options(-fexperimental-library)
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_test_executable(shader_cache_file_read_tests
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/CacheFileReadTests.cpp)
|
||||
target_include_directories(shader_cache_file_read_tests PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler)
|
||||
add_test(NAME shader_cache_file_read COMMAND shader_cache_file_read_tests)
|
||||
set_tests_properties(shader_cache_file_read PROPERTIES TIMEOUT 20)
|
||||
add_test_executable(request_serializer_tests
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/RequestSerializerTests.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/src/RequestSerializer.cpp)
|
||||
target_include_directories(request_serializer_tests PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include)
|
||||
add_test(NAME request_serializer COMMAND request_serializer_tests)
|
||||
set_tests_properties(request_serializer PROPERTIES TIMEOUT 20)
|
||||
find_package(Python3 QUIET COMPONENTS Interpreter)
|
||||
add_test_executable(shader_ir_use_rewrite_tests
|
||||
core/shader/recompiler/IntermediateRepresentation/tests/UseRewrite.cpp
|
||||
core/shader/recompiler/IntermediateRepresentation/tests/UseRewriteAllocation.cpp
|
||||
core/shader/recompiler/IntermediateRepresentation/src/IrValue.cpp
|
||||
core/shader/recompiler/IntermediateRepresentation/src/IrBlock.cpp
|
||||
core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp
|
||||
core/shader/recompiler/IntermediateRepresentation/src/GuestRegister.cpp)
|
||||
target_include_directories(shader_ir_use_rewrite_tests PRIVATE
|
||||
core/shader/recompiler/IntermediateRepresentation/include)
|
||||
add_test(NAME shader_ir_use_rewrite COMMAND shader_ir_use_rewrite_tests)
|
||||
set_tests_properties(shader_ir_use_rewrite PROPERTIES TIMEOUT 20)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME shader_cache_native_paths COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/test_shader_cache_native_paths.py
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ShaderCacheVersion.cmake ${CMAKE_COMMAND})
|
||||
set_tests_properties(shader_cache_native_paths PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME shader_cache_runtime_sources COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_shader_cache_runtime_sources.py
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler ${CMAKE_COMMAND})
|
||||
set_tests_properties(shader_cache_runtime_sources PROPERTIES TIMEOUT 180)
|
||||
add_test(NAME pr_overlap_encoding COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_encoding.py)
|
||||
add_test(NAME pr_overlap_dependencies COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_dependencies.py)
|
||||
add_test(NAME pr_overlap_tools COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap.py)
|
||||
add_test(NAME pr_labels COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_labels.py)
|
||||
add_test(NAME progress_history COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_history.py)
|
||||
add_test(NAME progress_report COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress.py)
|
||||
add_test(NAME progress_encoding COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_encoding.py)
|
||||
add_test(NAME progress_render_sliver COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_render_sliver.py)
|
||||
add_test(NAME progress_wrappers COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_wrappers.py)
|
||||
add_test(NAME progress_read_encoding COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_read_encoding.py)
|
||||
add_test(NAME import_audit COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_import_audit.py)
|
||||
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py)
|
||||
foreach(shard RANGE 0 11)
|
||||
if(shard EQUAL 0)
|
||||
set(conventions_test_name conventions_function_bodies)
|
||||
else()
|
||||
set(conventions_test_name conventions_function_bodies_shard_${shard})
|
||||
endif()
|
||||
add_test(NAME ${conventions_test_name} COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_comments.py --shard ${shard}/12)
|
||||
set_tests_properties(${conventions_test_name} PROPERTIES TIMEOUT 30)
|
||||
endforeach()
|
||||
add_test(NAME conventions_wrapped_declarations COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_wrapped_declarations.py)
|
||||
add_test(NAME conventions_ci_gate COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_ci_gate.py)
|
||||
add_test(NAME conventions_doc_links COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_doc_links.py)
|
||||
add_test(NAME conventions_unknown_nids COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_unknown_nids.py)
|
||||
add_test(NAME conventions_debt_length COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_debt_length.py)
|
||||
add_test(NAME test_registration COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_test_registration.py)
|
||||
add_test(NAME build_eligibility COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_eligibility.py)
|
||||
add_test(NAME check_skips COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py)
|
||||
add_test(NAME select_tests COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_select_tests.py)
|
||||
add_test(NAME check_main_sync COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_main_sync.py)
|
||||
add_test(NAME configure_seed COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedTests)
|
||||
add_test(NAME configure_seed_paths COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedPathTests)
|
||||
add_test(NAME configure_seed_round_trips COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedRoundTripTests)
|
||||
add_test(NAME configure_seed_parsing COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ChecksParsingTests)
|
||||
add_test(NAME stubgen COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_stubgen.py)
|
||||
add_test(NAME debt_split COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_debt_split.py)
|
||||
add_test(NAME stubgen_stdout_newlines COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_stubgen_stdout_newlines.py)
|
||||
add_test(NAME hardware_oracle COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/hw-oracle/test_hw_oracle.py)
|
||||
add_test(NAME hardware_oracle_compare COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/hw-oracle/test_compare_results.py)
|
||||
set_tests_properties(hardware_oracle_compare PROPERTIES TIMEOUT 120)
|
||||
add_test(NAME pr_overlap_exports COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_exports.py)
|
||||
add_test(NAME pr_overlap_wrapped_exports COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_wrapped_exports.py)
|
||||
add_test(NAME pr_overlap_own_branch COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_own_branch.py)
|
||||
add_test(NAME pr_overlap_errors COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_errors.py)
|
||||
add_test(NAME nid_database_cache COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_nid_names.py)
|
||||
add_test(NAME release_package COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_package_release.py)
|
||||
add_test(NAME web_release COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_web_release.py)
|
||||
set_tests_properties(web_release PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME web_library_assets COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_web.py)
|
||||
set_tests_properties(web_library_assets PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME pad_input COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pad_input.py)
|
||||
set_tests_properties(pad_input PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME trace_digest COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_trace_digest.py)
|
||||
add_test(NAME conventions_bom_shebang COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_bom_shebang.py)
|
||||
set_tests_properties(conventions_bom_shebang PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME env_reference COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_env_reference.py)
|
||||
set_tests_properties(env_reference PROPERTIES TIMEOUT 20)
|
||||
add_test(NAME conventions_env_reference COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_env_reference.py)
|
||||
set_tests_properties(conventions_env_reference PROPERTIES TIMEOUT 60)
|
||||
add_test(NAME conventions_body_bom COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_body_bom.py)
|
||||
add_test(NAME conventions_blob_reads COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_blob_reads.py)
|
||||
add_test(NAME conventions_agent_files COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_agent_files.py)
|
||||
add_test(NAME conventions_pr_template COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_pr_template.py)
|
||||
add_test(NAME check_compile COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py)
|
||||
add_test(NAME performance_compare COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_performance_compare.py)
|
||||
set_tests_properties(performance_compare PROPERTIES TIMEOUT 20)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
if(ANYPS5_RELINKER_ONLY)
|
||||
add_subdirectory(core/relinker)
|
||||
return()
|
||||
endif()
|
||||
|
||||
if(APPLE AND NOT CMAKE_OSX_ARCHITECTURES STREQUAL "x86_64")
|
||||
message(FATAL_ERROR "The full build on macOS is x86-64 only; configure without CMAKE_OSX_ARCHITECTURES or set it to x86_64")
|
||||
endif()
|
||||
|
||||
set(SDL_SHARED OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_STATIC ON CACHE BOOL "" FORCE)
|
||||
set(SDL_TEST OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_VIDEO ON CACHE BOOL "" FORCE)
|
||||
set(SDL_RENDER OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_X11 ON CACHE BOOL "" FORCE)
|
||||
set(SDL_WAYLAND ON CACHE BOOL "" FORCE)
|
||||
set(SDL_OPENGL OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_OPENGLES OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_VULKAN ON CACHE BOOL "" FORCE)
|
||||
set(SDL_JOYSTICK ON CACHE BOOL "" FORCE)
|
||||
set(SDL_HAPTIC OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_HIDAPI ON CACHE BOOL "" FORCE)
|
||||
set(SDL_SENSOR OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_STATIC_PIC ON CACHE BOOL "" FORCE)
|
||||
if(NOT ANYPS5_USE_SYSTEM_DEPS)
|
||||
set(ANYPS5_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "")
|
||||
add_subdirectory(3rdparty/SDL2)
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${ANYPS5_EXE_LINKER_FLAGS}")
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
get_directory_property(ANYPS5_SDL_X11_XRANDR DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_X11_XRANDR)
|
||||
if(NOT ANYPS5_SDL_X11_XRANDR)
|
||||
message(FATAL_ERROR "SDL has no XRandR support, so X11 display refresh rates cannot be queried. "
|
||||
"Install libxrandr-dev (Debian, Ubuntu) or libXrandr-devel (Fedora), "
|
||||
"enable SDL_X11_XRANDR, then rerun configuration.")
|
||||
endif()
|
||||
get_directory_property(ANYPS5_SDL_PIPEWIRE DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_PIPEWIRE)
|
||||
get_directory_property(ANYPS5_SDL_PULSEAUDIO DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_PULSEAUDIO)
|
||||
get_directory_property(ANYPS5_SDL_ALSA DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_ALSA)
|
||||
if(NOT ANYPS5_SDL_PIPEWIRE AND NOT ANYPS5_SDL_PULSEAUDIO AND NOT ANYPS5_SDL_ALSA)
|
||||
message(FATAL_ERROR "SDL found no PipeWire, PulseAudio or ALSA development files, so audio output would be silent. "
|
||||
"Install libpipewire-0.3-dev, libpulse-dev and libasound2-dev (Debian, Ubuntu) "
|
||||
"or pipewire-devel, pulseaudio-libs-devel and alsa-lib-devel (Fedora), then rerun configuration.")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
set(ARCHITECTURE x86_64)
|
||||
add_subdirectory(3rdparty/ffmpeg-core)
|
||||
if(MINGW)
|
||||
target_link_libraries(ffmpeg INTERFACE bcrypt ole32 user32 ws2_32)
|
||||
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(ffmpeg INTERFACE LINKER:--exclude-libs,ALL)
|
||||
endif()
|
||||
|
||||
if(APS5_ENABLE_TRACY)
|
||||
include(cmake/Tracy.cmake)
|
||||
endif()
|
||||
|
||||
set(FT_DISABLE_ZLIB ON CACHE BOOL "" FORCE)
|
||||
set(FT_DISABLE_BZIP2 ON CACHE BOOL "" FORCE)
|
||||
set(FT_DISABLE_PNG ON CACHE BOOL "" FORCE)
|
||||
set(FT_DISABLE_HARFBUZZ ON CACHE BOOL "" FORCE)
|
||||
set(FT_DISABLE_BROTLI ON CACHE BOOL "" FORCE)
|
||||
set(SKIP_INSTALL_ALL ON CACHE BOOL "" FORCE)
|
||||
if(NOT ANYPS5_USE_SYSTEM_DEPS)
|
||||
add_subdirectory(3rdparty/freetype EXCLUDE_FROM_ALL)
|
||||
set_target_properties(freetype PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
if(WIN32)
|
||||
get_target_property(freetypeSources freetype SOURCES)
|
||||
list(FILTER freetypeSources EXCLUDE REGEX "ftver\\.rc$")
|
||||
set_target_properties(freetype PROPERTIES SOURCES "${freetypeSources}")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(LIBUSB_BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_INSTALL_TARGETS OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_BUILD_TESTING OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
set(LIBUSB_ENABLE_UDEV OFF CACHE BOOL "" FORCE)
|
||||
add_subdirectory(3rdparty/libusb-cmake EXCLUDE_FROM_ALL)
|
||||
set_target_properties(usb-1.0 PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
include(cmake/ZArchive.cmake)
|
||||
if(WIN32)
|
||||
set(MI_BUILD_SHARED ON CACHE BOOL "" FORCE)
|
||||
set(MI_BUILD_STATIC OFF CACHE BOOL "" FORCE)
|
||||
set(MI_BUILD_OBJECT OFF CACHE BOOL "" FORCE)
|
||||
set(MI_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(MI_OVERRIDE ON CACHE BOOL "" FORCE)
|
||||
set(MI_WIN_REDIRECT ON CACHE BOOL "" FORCE)
|
||||
set(MI_FREE_IS_CHECKED SHARED CACHE STRING "" FORCE)
|
||||
add_subdirectory(3rdparty/mimalloc EXCLUDE_FROM_ALL)
|
||||
if(MINGW)
|
||||
target_compile_definitions(mimalloc PRIVATE MI_MINGW_UCRT64=1)
|
||||
target_link_options(mimalloc PRIVATE -static
|
||||
LINKER:--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=free,--wrap=strdup,--wrap=_strdup)
|
||||
target_sources(mimalloc PRIVATE ${CMAKE_SOURCE_DIR}/core/libs/allocator/RuntimeHeap.c)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
add_subdirectory(core/shader/recompiler)
|
||||
add_subdirectory(core/Decoder/Jpeg)
|
||||
add_subdirectory(core/Decoder/Png)
|
||||
add_subdirectory(core/libs)
|
||||
add_subdirectory(core/relinker)
|
||||
@@ -1,73 +0,0 @@
|
||||
# Contributing
|
||||
|
||||
## Code
|
||||
|
||||
- Follow the [coding conventions](docs/dev/CONVENTIONS.md): naming, no comments except [technical debt](docs/dev/TechnicalDebt.md), Conventional Commits.
|
||||
- Every function either does exactly what it is supposed to or throws. Unimplemented exports call `NotImplemented_nid_no_patch(__func__)` (see [libSceAudioIn](core/libs/prx/libSceAudioIn/Export.cpp)).
|
||||
- Pull requests that add or change shader instruction semantics say where they come from: measured on hardware (which GPU and what was checked, e.g. with the [hardware oracle](docs/dev/HW_ORACLE.md)) or the exact source (ISA section, LLVM, ACO or Mesa file). Reviewers check the semantics on hardware. Cases the source doesn't settle throw, and behaviour not verified on hardware is recorded in [technical debt](docs/dev/TechnicalDebt.md).
|
||||
- A silent stub is allowed only when it unblocks a title and only affects the UI; add it under Silent stubs in its library's [technical debt](docs/dev/debt/) file.
|
||||
- Missing imports fail at startup with a clear error; don't replace them with fallbacks that keep running.
|
||||
- Implement the general behaviour of a function, not what one title happens to need.
|
||||
- Don't add replacements for modules that titles ship themselves in `sce_module/`, `sce_modules/` or `prx/`: engine or middleware modules (Cohtml, FMOD, GOG Galaxy) and SDK libraries that only wrap other system libraries. The relinker converts and loads the title's own module, and a host library with the same name is left out of `DT_NEEDED`. Only system libraries, which reach the kernel or the hardware, are reimplemented in [core/libs/prx](core/libs/prx). A host copy may still exist for a wrapped library that some dumps lack entirely, like libSceNpCppWebApi: the title's own module wins whenever one is shipped, so it is only ever consulted by titles that ship nothing.
|
||||
- Avoid non-standard extensions (`__attribute__`, etc.) where standard C++ is enough. Helper symbols that must not become NIDs use the `_nid_no_patch` or `_nid_no_patch_cut` suffix.
|
||||
- The relinker uses only the C++20 standard library.
|
||||
- Third-party code is added as a submodule under `3rdparty/` and built from source, not found on the system. With `ANYPS5_USE_SYSTEM_DEPS=ON` the packages packaged by the distributions (SDL2, freetype, Vulkan-Headers, SPIRV-Headers, glslang and SPIRV-Tools) come from the system instead; that resolution lives in [cmake/SystemDeps.cmake](cmake/SystemDeps.cmake) and the default build never reads the system.
|
||||
- Don't add tests that only check that a symbol is exported: a missing export already fails at startup.
|
||||
- Each test finishes in 30 s on the CI runners, Vulkan tests included (Linux runs them on lavapipe), counting the first run with no shader cache. ctest runs in parallel there, so a slow test competes for the cores and times out on some runs and not others. Split or shrink a test that gets close instead of raising its timeout. CI reports every test over 30 s as a warning on the pull request.
|
||||
|
||||
## Build and test
|
||||
|
||||
Toolchains are listed in the [build instructions](docs/dev/BUILD.md).
|
||||
|
||||
For relinker changes, use the [relinker-only build](docs/dev/BUILD.md#relinker-only) to build and test without third-party submodules, system libraries or a GPU. It also works on macOS. Changes to system libraries or shaders still need the full build and relevant runtime tests.
|
||||
|
||||
```
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
|
||||
cmake --build build
|
||||
ctest --test-dir build --output-on-failure
|
||||
```
|
||||
|
||||
Python 3 is optional; without it some relinker tests are not registered.
|
||||
|
||||
Every push to `main`, including a merged pull request, automatically runs full Linux and Windows builds and tests and the relinker matrix on Linux, Windows and macOS, using the pushed commit without contributor checks.
|
||||
|
||||
For pull requests, full Linux and Windows builds and tests run only when a collaborator with write access selects Actions > Build > Run workflow on `main` and enters an open pull request number targeting `main`. A collaborator can start the same manual run from the command line, replacing `1234` with the pull request number:
|
||||
|
||||
```
|
||||
gh workflow run build.yml --repo boykopovar/AnyPS5 --ref main --field pr=1234
|
||||
```
|
||||
|
||||
This manual run also builds and tests the relinker on Linux, Windows and macOS when the pull request changes a file the relinker-only build uses, regardless of the author's previous contributions. The relinker matrix also runs automatically when a pull request targeting `main` is opened, updated or reopened, if its author already has a commit in `main` and it changes a file the relinker-only build uses; full builds never run automatically for pull requests. Every job that runs automatically for pull requests runs only when the pull request changes its files: a `paths` filter on the `pull_request` trigger, or `needs: eligibility` with an `if` on the files output it sets in `build.yml`. The Conventions check fails a workflow change that adds a job without one. All build jobs build the selected pull request merged into the current `main` (GitHub's merge commit), so a pull request that no longer merges cleanly must be rebased first. New commits require another manual run for full builds.
|
||||
|
||||
With `--field full=false`, the manual run skips the full builds and runs only the relinker matrix on Linux, Windows and macOS, if the pull request changes a file the relinker-only build uses, such as the Python tools and their tests in `tools/`.
|
||||
|
||||
The Conventions check runs automatically for every contributor, including first-time contributors. It uses the base branch checker and reads pull request Git objects without executing pull request code. The Conventions check runs on every pull request and fails when a rule on this page is broken. It accepts code comments only when the pull request also changes [technical debt](docs/dev/TechnicalDebt.md), the index or a file in `docs/dev/debt/`, and only UTF-8 text files. Run it locally before pushing:
|
||||
|
||||
```
|
||||
python3 tools/check_conventions.py --base origin/main
|
||||
```
|
||||
|
||||
## Branches and pull requests
|
||||
|
||||
The [pull request template](.github/pull_request_template.md) is the checklist for these rules.
|
||||
|
||||
- One branch per topic, based on current `main`. Follow-up work goes in a new pull request, not into an open one.
|
||||
- Open pull requests per author are limited by how many of theirs are merged into `main`: 1 with none merged, 20 with at least 1, no limit from 20. A pull request opened or reopened over the limit is closed automatically; reopen it once another one is merged or closed.
|
||||
- Before starting, check that no open pull request already implements the same functions.
|
||||
- Keep the branch up to date with `main` and resolve conflicts yourself; rebasing and force-pushing is fine.
|
||||
- A pull request that conflicts with `main` and has no activity for 7 days is labeled `stale` with a reminder. It is not closed.
|
||||
- If a pull request needs another one first, say so on the checklist line (`Depends on: #N`; `none` otherwise).
|
||||
- If a pull request fixes a reported issue, write `Fixes #N` on its checklist line (`none` otherwise). GitHub closes the issue on merge, and the `fix error` label is added within the hour.
|
||||
- If a pull request fixes a stop or a wrong result seen on a title, name it on the checklist line with the title ID and its [Game bring-up](https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up) discussion (`Unblocks: PPSA01325 #3232`; `none` otherwise). Reviewers review these first. Such a pull request gets the `unblocks title` label.
|
||||
- For GPU changes, list each tested GPU's vendor, model, driver and OS on the checklist line. CI runs GPU tests only on lavapipe, so reviewers may ask for a run on another vendor before merging.
|
||||
- Fixes a title needs go to `main` as pull requests. A Game bring-up discussion lists the open pull requests and local changes the title still needs; update the list when one is merged, closed or replaced.
|
||||
- The PR overlap comment lists open pull requests that change the same lines or exports; agree with their authors which one goes first and declare it with `Depends on`.
|
||||
- Run the tests before opening the pull request and describe what was tested (OS, title or homebrew).
|
||||
- A pull request that claims a change in speed shows the summary lines of `main` and of the change, from the same machine and scene, and attaches the traces, captured as the [Performance report](.github/ISSUE_TEMPLATE/performance.yml) issue form describes. A slow scene is reported with the same form. A pull request titled `perf(...)` or `perf:` is labeled `perf`, and `perf numbers missing` until its description holds two valid summary lines with different commits.
|
||||
- Changes to the AGC driver, the shader recompiler or VideoOut run the same focused tests on `main` and the change with `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`, `ANYPS5_NO_SHADER_CACHE=1` and `ANYPS5_REQUIRE_VULKAN=1` using `ctest -V` from the same machine and GPU, confirm neither log reports `was not found but was requested by env var VK_INSTANCE_LAYERS`, confirm the change introduces no new `VUID-` validation errors compared with `main`, and name each GPU the GPU tests ran on (vendor, model, driver, OS) on the `GPUs tested` checklist line. CI runs these tests only on lavapipe, and hardware drivers fail where lavapipe and other vendors pass, so a reviewer can ask for a run on another vendor before merging.
|
||||
- Investigation notes, reports, screenshots and logs go in the pull request, not in the repository. Images for documentation go in the [gist](https://gist.github.com/boykopovar/0e53f2e1426f29ecd41e3b51540b8a90) comments.
|
||||
- Say whether the change was written with AI assistance. The author of the pull request is responsible for every line of it.
|
||||
|
||||
## Documentation
|
||||
|
||||
Text in the repository is dry, strict and concise. Record known gaps, unknown NIDs and signatures in [technical debt](docs/dev/TechnicalDebt.md) instead of new files. An entry states the gap first (what differs from the console, what is unverified, what throws) and describes the implemented behaviour only as far as the gap needs it. A pull request that closes a gap removes its entry, or cuts it to what is still open, instead of rewriting it to describe the corrected behaviour. An entry goes in `docs/dev/debt/<name>.md`, named after the first `core/` path it links (`<name>` for `core/libs/prx/<name>/...`, otherwise for `core/<name>/...`), under the same `###` sections as the index; entries that link neither stay in the index. A pull request whose `TechnicalDebt.md` change conflicts after the split rebases and runs `python3 tools/debt_split.py resolve` during the stopped rebase, which moves its added, edited and removed entries to their files; `python3 tools/debt_split.py split` moves entries left in the index.
|
||||
@@ -1,338 +0,0 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 2, June 1991
|
||||
|
||||
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||
<https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
License is intended to guarantee your freedom to share and change free
|
||||
software--to make sure the software is free for all its users. This
|
||||
General Public License applies to most of the Free Software
|
||||
Foundation's software and to any other program whose authors commit to
|
||||
using it. (Some other Free Software Foundation software is covered by
|
||||
the GNU Lesser General Public License instead.) You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
this service if you wish), that you receive source code or can get it
|
||||
if you want it, that you can change the software or use pieces of it
|
||||
in new free programs; and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
anyone to deny you these rights or to ask you to surrender the rights.
|
||||
These restrictions translate to certain responsibilities for you if you
|
||||
distribute copies of the software, or if you modify it.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must give the recipients all the rights that
|
||||
you have. You must make sure that they, too, receive or can get the
|
||||
source code. And you must show them these terms so they know their
|
||||
rights.
|
||||
|
||||
We protect your rights with two steps: (1) copyright the software, and
|
||||
(2) offer you this license which gives you legal permission to copy,
|
||||
distribute and/or modify the software.
|
||||
|
||||
Also, for each author's protection and ours, we want to make certain
|
||||
that everyone understands that there is no warranty for this free
|
||||
software. If the software is modified by someone else and passed on, we
|
||||
want its recipients to know that what they have is not the original, so
|
||||
that any problems introduced by others will not reflect on the original
|
||||
authors' reputations.
|
||||
|
||||
Finally, any free program is threatened constantly by software
|
||||
patents. We wish to avoid the danger that redistributors of a free
|
||||
program will individually obtain patent licenses, in effect making the
|
||||
program proprietary. To prevent this, we have made it clear that any
|
||||
patent must be licensed for everyone's free use or not licensed at all.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License applies to any program or other work which contains
|
||||
a notice placed by the copyright holder saying it may be distributed
|
||||
under the terms of this General Public License. The "Program", below,
|
||||
refers to any such program or work, and a "work based on the Program"
|
||||
means either the Program or any derivative work under copyright law:
|
||||
that is to say, a work containing the Program or a portion of it,
|
||||
either verbatim or with modifications and/or translated into another
|
||||
language. (Hereinafter, translation is included without limitation in
|
||||
the term "modification".) Each licensee is addressed as "you".
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running the Program is not restricted, and the output from the Program
|
||||
is covered only if its contents constitute a work based on the
|
||||
Program (independent of having been made by running the Program).
|
||||
Whether that is true depends on what the Program does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Program's
|
||||
source code as you receive it, in any medium, provided that you
|
||||
conspicuously and appropriately publish on each copy an appropriate
|
||||
copyright notice and disclaimer of warranty; keep intact all the
|
||||
notices that refer to this License and to the absence of any warranty;
|
||||
and give any other recipients of the Program a copy of this License
|
||||
along with the Program.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy, and
|
||||
you may at your option offer warranty protection in exchange for a fee.
|
||||
|
||||
2. You may modify your copy or copies of the Program or any portion
|
||||
of it, thus forming a work based on the Program, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) You must cause the modified files to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
b) You must cause any work that you distribute or publish, that in
|
||||
whole or in part contains or is derived from the Program or any
|
||||
part thereof, to be licensed as a whole at no charge to all third
|
||||
parties under the terms of this License.
|
||||
|
||||
c) If the modified program normally reads commands interactively
|
||||
when run, you must cause it, when started running for such
|
||||
interactive use in the most ordinary way, to print or display an
|
||||
announcement including an appropriate copyright notice and a
|
||||
notice that there is no warranty (or else, saying that you provide
|
||||
a warranty) and that users may redistribute the program under
|
||||
these conditions, and telling the user how to view a copy of this
|
||||
License. (Exception: if the Program itself is interactive but
|
||||
does not normally print such an announcement, your work based on
|
||||
the Program is not required to print an announcement.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Program,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Program, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Program.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Program
|
||||
with the Program (or with a work based on the Program) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may copy and distribute the Program (or a work based on it,
|
||||
under Section 2) in object code or executable form under the terms of
|
||||
Sections 1 and 2 above provided that you also do one of the following:
|
||||
|
||||
a) Accompany it with the complete corresponding machine-readable
|
||||
source code, which must be distributed under the terms of Sections
|
||||
1 and 2 above on a medium customarily used for software interchange; or,
|
||||
|
||||
b) Accompany it with a written offer, valid for at least three
|
||||
years, to give any third party, for a charge no more than your
|
||||
cost of physically performing source distribution, a complete
|
||||
machine-readable copy of the corresponding source code, to be
|
||||
distributed under the terms of Sections 1 and 2 above on a medium
|
||||
customarily used for software interchange; or,
|
||||
|
||||
c) Accompany it with the information you received as to the offer
|
||||
to distribute corresponding source code. (This alternative is
|
||||
allowed only for noncommercial distribution and only if you
|
||||
received the program in object code or executable form with such
|
||||
an offer, in accord with Subsection b above.)
|
||||
|
||||
The source code for a work means the preferred form of the work for
|
||||
making modifications to it. For an executable work, complete source
|
||||
code means all the source code for all modules it contains, plus any
|
||||
associated interface definition files, plus the scripts used to
|
||||
control compilation and installation of the executable. However, as a
|
||||
special exception, the source code distributed need not include
|
||||
anything that is normally distributed (in either source or binary
|
||||
form) with the major components (compiler, kernel, and so on) of the
|
||||
operating system on which the executable runs, unless that component
|
||||
itself accompanies the executable.
|
||||
|
||||
If distribution of executable or object code is made by offering
|
||||
access to copy from a designated place, then offering equivalent
|
||||
access to copy the source code from the same place counts as
|
||||
distribution of the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
4. You may not copy, modify, sublicense, or distribute the Program
|
||||
except as expressly provided under this License. Any attempt
|
||||
otherwise to copy, modify, sublicense or distribute the Program is
|
||||
void, and will automatically terminate your rights under this License.
|
||||
However, parties who have received copies, or rights, from you under
|
||||
this License will not have their licenses terminated so long as such
|
||||
parties remain in full compliance.
|
||||
|
||||
5. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Program or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Program (or any work based on the
|
||||
Program), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Program or works based on it.
|
||||
|
||||
6. Each time you redistribute the Program (or any work based on the
|
||||
Program), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute or modify the Program subject to
|
||||
these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties to
|
||||
this License.
|
||||
|
||||
7. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Program at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Program by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Program.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under
|
||||
any particular circumstance, the balance of the section is intended to
|
||||
apply and the section as a whole is intended to apply in other
|
||||
circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system, which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
8. If the distribution and/or use of the Program is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Program under this License
|
||||
may add an explicit geographical distribution limitation excluding
|
||||
those countries, so that distribution is permitted only in or among
|
||||
countries not thus excluded. In such case, this License incorporates
|
||||
the limitation as if written in the body of this License.
|
||||
|
||||
9. The Free Software Foundation may publish revised and/or new versions
|
||||
of the General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Program
|
||||
specifies a version number of this License which applies to it and "any
|
||||
later version", you have the option of following the terms and conditions
|
||||
either of that version or of any later version published by the Free
|
||||
Software Foundation. If the Program does not specify a version number of
|
||||
this License, you may choose any version ever published by the Free Software
|
||||
Foundation.
|
||||
|
||||
10. If you wish to incorporate parts of the Program into other free
|
||||
programs whose distribution conditions are different, write to the author
|
||||
to ask for permission. For software which is copyrighted by the Free
|
||||
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||
make exceptions for this. Our decision will be guided by the two goals
|
||||
of preserving the free status of all derivatives of our free software and
|
||||
of promoting the sharing and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||
REPAIR OR CORRECTION.
|
||||
|
||||
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software; you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation; either version 2 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License along
|
||||
with this program; if not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program is interactive, make it output a short notice like this
|
||||
when it starts in an interactive mode:
|
||||
|
||||
Gnomovision version 69, Copyright (C) year name of author
|
||||
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, the commands you use may
|
||||
be called something other than `show w' and `show c'; they could even be
|
||||
mouse-clicks or menu items--whatever suits your program.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||
|
||||
<signature of Moe Ghoul>, 1 April 1989
|
||||
Moe Ghoul, President of Vice
|
||||
|
||||
This General Public License does not permit incorporating your program into
|
||||
proprietary programs. If your program is a subroutine library, you may
|
||||
consider it more useful to permit linking proprietary applications with the
|
||||
library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License.
|
||||
@@ -0,0 +1,43 @@
|
||||
# Repo Forker — convenience targets.
|
||||
# Most work happens in the Gitea Actions workflows; these targets are for local
|
||||
# use (dry-runs, runner setup) and for debugging on the runner.
|
||||
|
||||
CONFIG_FILE ?= .forker.yaml
|
||||
|
||||
.PHONY: help sync release mirror-releases runner-check runner-register check-unit
|
||||
|
||||
help:
|
||||
@echo "Repo Forker targets:"
|
||||
@echo " sync Run a manual sync (needs UPSTREAM_* + GITEA_* env)"
|
||||
@echo " release TAG=x Run a release for tag x"
|
||||
@echo " mirror-releases Mirror upstream releases for a tag (release.sh MIRROR)"
|
||||
@echo " runner-check Run the runner-check workflow logic locally"
|
||||
@echo " runner-register Register a shared gitea-act-runner (see README)"
|
||||
@echo " check-unit Verify the Releases unit is enabled (fork quirk)"
|
||||
|
||||
sync:
|
||||
bash forker/sync.sh
|
||||
|
||||
release:
|
||||
@test -n "$(TAG)" || (echo "make release TAG=<tag>"; exit 1)
|
||||
bash forker/release.sh "$(TAG)"
|
||||
|
||||
mirror-releases:
|
||||
@test -n "$(TAG)" || (echo "make mirror-releases TAG=<tag>"; exit 1)
|
||||
bash forker/release.sh "$(TAG)"
|
||||
|
||||
runner-check:
|
||||
@test -n "$(GITEA_SERVER_URL)" -a -n "$(GITEA_TOKEN)" -a -n "$(GITEA_OWNER)" -a -n "$(GITEA_REPO)" \
|
||||
|| { echo "needs GITEA_SERVER_URL/GITEA_TOKEN/GITEA_OWNER/GITEA_REPO (or run the workflow instead)"; exit 1; }
|
||||
@curl -sS --max-time 20 -H "Authorization: Bearer $(GITEA_TOKEN)" \
|
||||
"$(GITEA_SERVER_URL)/api/v1/repos/$(GITEA_OWNER)/$(GITEA_REPO)/actions/runners" > /tmp/rc_repo.json
|
||||
@curl -sS --max-time 20 -H "Authorization: Bearer $(GITEA_TOKEN)" \
|
||||
"$(GITEA_SERVER_URL)/api/v1/admin/actions/runners?limit=50" > /tmp/rc_shared.json || true
|
||||
@python3 -c 'import json; R=json.load(open("/tmp/rc_repo.json")).get("runners",[]); S=[r for r in json.load(open("/tmp/rc_shared.json")).get("runners",[]) if r.get("shared")]; print("Repo-scoped runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in R) or "(none)")); print("Shared runners: "+(", ".join("%s (%s)"%(r["name"],r["status"]) for r in S) or "(none)")); print("OK: a runner serves this repo." if (R or S) else "WARNING: no runner (repo-scoped or shared) registered - cron runs will stay queued.")'
|
||||
@rm -f /tmp/rc_repo.json /tmp/rc_shared.json
|
||||
|
||||
runner-register:
|
||||
bash forker/runner-register.sh
|
||||
|
||||
check-unit:
|
||||
bash forker/check-unit.sh
|
||||
@@ -1,43 +1,221 @@
|
||||
# About
|
||||
# Repo Forker
|
||||
|
||||
Tool for automatic executables porting to Linux and Windows.
|
||||
> 📖 **Documentación y arquitectura interactiva:** [docs/index.html](docs/index.html) — qué es, cómo funciona, cómo crear un fork paso a paso, runner, config y limitaciones.
|
||||
|
||||
The relinker-only build runs on macOS, including Apple silicon.
|
||||
> 🖥️ **UI de gestión local (mirrors):** [ui/README.md](ui/README.md) — `cd ui && npm install && npm run build && node bin/repo-forker-ui.js` → http://127.0.0.1:8731. Crea/elimina/monitorea mirrors, paridad vs upstream, logs en vivo, cola del runner.
|
||||
|
||||
[**Web converter**](https://boykopovar.github.io/AnyPS5/) - files stay on your device.
|
||||
Turn **any** git repo (GitHub, Gitea, Codeberg, …) into a **live mirror on your
|
||||
Gitea** — all branches, all tags, full commit history — synced very
|
||||
periodically by a Gitea Actions runner (your "gitea worker"), with releases
|
||||
produced **locally on the runner** (and optionally mirrored from the upstream).
|
||||
|
||||

|
||||
This repo is a **template**. You **fork** it once per upstream; the fork *is*
|
||||
the mirror. The upstream's content never touches the working tree: upstream
|
||||
objects live in a bare mirror (`.mirror/`, gitignored) and are pushed as refs
|
||||
so they show up in the Gitea UI.
|
||||
|
||||
Includes a [relinker](core/relinker) that converts executable to the target system's native format and implementations of [system prx libraries](core/libs/prx) suitable for dynamic linking. No emulation or separate runtime process.
|
||||
```
|
||||
Fork of this template (Lago/<upstream>)
|
||||
├── working tree (forker branch) ← the machinery: scripts, config, workflows
|
||||
├── .mirror/ ← bare mirror of the upstream (gitignored)
|
||||
└── refs: <upstream branches> + <tags> ← visible in the Gitea UI
|
||||
```
|
||||
|
||||
[**Discord**](https://discord.gg/BHFztBPUe), [Usage](docs/user/USAGE.md), [Build instructions](docs/dev/BUILD.md), [Architecture](docs/dev/ARCHITECTURE.md), [Technical debt of the project](docs/dev/TechnicalDebt.md), [code style conventions](docs/dev/CONVENTIONS.md), [contributing](CONTRIBUTING.md)
|
||||
## How it works
|
||||
|
||||
## Status
|
||||
1. **Sync (the worker).** A cron workflow runs every N minutes. `sync.sh` fetches
|
||||
all branches + tags + full history from the upstream into a true bare mirror
|
||||
(`.mirror/`), then pushes them onto this fork and **prunes** what the upstream
|
||||
deleted. The fork's current state is read via the Gitea API (not git state),
|
||||
so prune + change-detection work even when the workspace is wiped between
|
||||
runs. `actions/cache` restores `.mirror/` when possible → incremental fetches.
|
||||
2. **Release (local build).** When sync detects a **new tag**, it invokes
|
||||
`release.sh` inline: checkout the tag's tree, run your build command **on the
|
||||
runner**, publish the release (tag + assets) on this Gitea. (A tag-push can't
|
||||
trigger a workflow on its own — the tag points at an upstream commit whose
|
||||
tree has no `.gitea/workflows` — so sync does it.) Re-running is idempotent:
|
||||
an existing release is skipped, not duplicated.
|
||||
3. **Release (mirror, optional).** If enabled, the upstream's existing release
|
||||
(metadata + assets) is copied over via the provider API
|
||||
(GitHub / Gitea / Codeberg — auto-detected in `forker/lib/provider.sh`).
|
||||
|
||||
[](https://boykopovar.github.io/AnyPS5/progress.html) [](https://boykopovar.github.io/AnyPS5/progress.html)
|
||||
## Quick start (3 steps)
|
||||
|
||||
[](https://boykopovar.github.io/AnyPS5/progress.html)
|
||||
### 1. Fork this template
|
||||
In the Gitea UI: **this repo → Fork** → name it after the upstream
|
||||
(e.g. `Lago/some-upstream`).
|
||||
|
||||
[Progress history](https://boykopovar.github.io/AnyPS5/history.html)
|
||||
### 2. Point it at the upstream (the "remote")
|
||||
In the fork: **Settings → Actions → Variables & Secrets**
|
||||
- **Variable** `UPSTREAM_URL` = `https://github.com/owner/repo.git` (any provider)
|
||||
- **Secret** `UPSTREAM_TOKEN` = *(optional — only for private upstreams.)*
|
||||
Public upstreams are mirrored **anonymously** and the tool never
|
||||
authenticates against them: the global/system git config and the
|
||||
credential helper are cut for all upstream git calls, so a stored
|
||||
`~/.git-credentials` entry is never used. Only set a token when the
|
||||
upstream is private (or you need a higher API rate for mirrored
|
||||
releases).
|
||||
|
||||
<sub>* System libraries: percentage of the functions known to the project so far (declared in [core/libs/prx](core/libs/prx)), not of every PS5 system function. The total grows as more functions are declared.</sub>
|
||||
Everything non-secret (which branches, how often, build command, artifacts) lives
|
||||
in **`.forker.yaml`** — edit it in the UI on the `forker` branch.
|
||||
|
||||
Unsupported or unexpected states strictly throw `std::runtime_error`. `what()` is printed to stderr and the process terminates.
|
||||
> The `GITEA_*` values (server URL, owner, repo, token) are injected
|
||||
> automatically by Gitea Actions — you don't set them. (`GITEA_TOKEN` in the
|
||||
> workflow env block is Gitea's **built-in** Actions secret, not a
|
||||
> user-created secret — don't create one.)
|
||||
|
||||
The [shader recompiler](core/shader/recompiler/Recompiler.cpp) successfully produces SPIR-V (validated via [Spirv-Tools](3rdparty/SPIRV-Tools) when built with `ANYPS5_ENABLE_SPIRV_TOOLS`).
|
||||
### 3. Make sure a runner serves this repo
|
||||
In this Gitea build, **runners are repo-scoped**: a runner registered on one
|
||||
repo does **not** serve another. So either:
|
||||
|
||||
## Compatibility
|
||||
- **Shared runner (recommended, one-time):** register a single runner that serves
|
||||
**all** repos. See [Runner](#runner).
|
||||
- **Per-repo runner:** register a runner for this specific repo.
|
||||
|
||||
Per-game progress (stage reached, open blockers, libraries and GPU coverage) is tracked on the [blocker map](https://alxcbtw.github.io/anyps5-roadmap/), a community project built from public GitHub data ([source](https://github.com/AlxcBTW/anyps5-roadmap)). Test reports go in the [Game bring-up](https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up) discussions, one thread per title.
|
||||
Then trigger **Settings → Actions → "Repo Forker — Runner check"** and confirm it
|
||||
completes. If sync runs stay *pending* for a long time, no runner is serving
|
||||
this repo.
|
||||
|
||||
## Input mapping
|
||||
That's it. The cron sync starts pulling the upstream in, and releases are
|
||||
produced locally when tags appear. Note: with the template defaults
|
||||
(`build_cmd` empty, `mirror_upstream_releases: false`) there is nothing to
|
||||
build, so new tags are mirrored as **refs only** — set a `build_cmd` /
|
||||
`build_script` (or `mirror_upstream_releases: true`) for releases to appear.
|
||||
|
||||
SDL-mapped game controllers are supported, including analog sticks and triggers. Keyboard and mouse controls can be configured with an `anyps5-input.ini` file. See [input mapping](docs/user/INPUT_MAPPING.md) for the supported devices and configuration format.
|
||||
## Configuration (`.forker.yaml`)
|
||||
|
||||
## Disclaimer
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `token_user` | `oauth2` | *(unused — Bearer auth needs no username; retained for compatibility)* |
|
||||
| `mirror_tags` | `true` | Mirror all tags |
|
||||
| `mirror_prune` | `true` | Prune branches deleted upstream |
|
||||
| `mirror_branches` | `*` | `*` = all, or a comma list (`main,develop`) |
|
||||
| `on_new_tag` | `true` | Build+publish a release when a new tag is mirrored |
|
||||
| `mirror_upstream_releases` | `false` | Also copy the upstream's release (metadata + assets) |
|
||||
| `build_cmd` | — | Build command(s), `;`-separated, run in the tag's tree |
|
||||
| `build_script` | — | Path to a custom build script (overrides `build_cmd`) |
|
||||
| `artifacts` | — | Space-separated globs of files to attach to the release |
|
||||
|
||||
This project is intended for interoperability, research, preservation, and compatibility purposes. It does not include, distribute, or require copyrighted software, firmware, cryptographic keys, or proprietary libraries. Users are responsible for ensuring that any binaries used with this project are obtained and used in accordance with applicable laws and their respective license terms.
|
||||
## Manual triggers
|
||||
|
||||
## License
|
||||
- **Sync now:** Settings → Actions → *Repo Forker — Sync* → Run workflow.
|
||||
- **Release a tag:** Settings → Actions → *Repo Forker — Release* → Run workflow
|
||||
→ enter the tag.
|
||||
- **Check the runner:** Settings → Actions → *Repo Forker — Runner check*.
|
||||
|
||||
This project is licensed under the GNU General Public License version 2 only.
|
||||
Or from a machine that has the repo + env vars: `make sync`,
|
||||
`make release TAG=v1.2.3`.
|
||||
|
||||
## Runner
|
||||
|
||||
The sync (cron) and the local release build both need a **Gitea Actions runner**
|
||||
serving the repo. In this build, runners are **repo-scoped**, so the clean path
|
||||
is a **shared runner** registered once:
|
||||
|
||||
```bash
|
||||
# install gitea-act-runner (see the Gitea runner docs), then:
|
||||
GITEA_SERVER_URL=https://git.lago.dev \
|
||||
GITEA_TOKEN=<admin-token> \
|
||||
GITEA_OWNER=Lago GITEA_REPO=any \
|
||||
bash forker/runner-register.sh shared
|
||||
|
||||
# then start it (e.g. via docker, see runner/docker-compose.yml)
|
||||
gitea-act-runner run
|
||||
```
|
||||
|
||||
`forker/runner-register.sh` auto-generates a registration token via
|
||||
`POST /api/v1/admin/actions/runners/registration-token` (verified working on this
|
||||
instance) and registers either a **shared** runner or a **per-repo** one.
|
||||
|
||||
> The existing online runner on this instance (id 3, `496cfb9f4583`,
|
||||
> `ubuntu-latest/24.04/22.04`) is registered to `Lago/Tide` only — it will not
|
||||
> serve your forks. Register a shared runner (or one per repo) as above.
|
||||
|
||||
> **This Gitea build quirk (verified):** the `act_runner` CLI fails to
|
||||
> register ("instance address is empty") on both `gitea/act_runner:0.6.1`
|
||||
> and `0.2.13`, and the runner-creation API returns 405. The path that
|
||||
> **does** work: take an existing registered runner and PATCH it to shared:
|
||||
> ```bash
|
||||
> curl -X PATCH "$GITEA_SERVER_URL/api/v1/admin/actions/runners/<id>" \
|
||||
> -H "Authorization: Bearer $GITEA_TOKEN" \
|
||||
> -d '{"name":"gitea-runner-forker","labels":["ubuntu-latest"],"shared":true,"disabled":false}'
|
||||
> ```
|
||||
> then point a `gitea/act_runner:0.6.1` container at its config
|
||||
> (`runner/docker-compose.yml`).
|
||||
|
||||
## Repository layout
|
||||
|
||||
```
|
||||
repo-forker/
|
||||
├── .gitea/workflows/
|
||||
│ ├── sync.yml # cron: mirror upstream (the "worker"); restores .mirror cache
|
||||
│ ├── release.yml # MANUAL only (a tag push can't trigger it); see sync.sh
|
||||
│ └── runner-check.yml # verify a runner serves this repo
|
||||
├── forker/
|
||||
│ ├── sync.sh # true-mirror fetch + push + prune + inline new-tag release + unit check
|
||||
│ ├── release.sh # local build + publish release (± mirror upstream), idempotent
|
||||
│ ├── runner-register.sh # register a shared / per-repo runner
|
||||
│ ├── check-unit.sh # verify/fix the Releases unit (Gitea fork quirk)
|
||||
│ └── lib/
|
||||
│ ├── config.sh # load .forker.yaml
|
||||
│ └── provider.sh # detect provider + releases API (Gitea/GitHub/Codeberg)
|
||||
├── .mirror/ # bare mirror (gitignored, cached by the workflow)
|
||||
├── .forker.yaml # per-fork config (non-secret)
|
||||
├── Makefile
|
||||
├── runner/docker-compose.yml
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## Notes & limitations
|
||||
|
||||
- **Releases are not git objects.** Git only carries the *tag*; release *assets*
|
||||
live on the Gitea. "Local release" = build on the runner + upload via the
|
||||
Gitea API. Mirroring upstream assets works anonymously for public upstreams
|
||||
(a token is only needed for private ones).
|
||||
- **Ephemeral workspace.** The Gitea runner wipes the workspace between runs.
|
||||
`sync.sh` is written to not depend on leftover git state: it re-reads the fork's
|
||||
current refs via the API every run. `actions/cache` on `.mirror/` makes the
|
||||
fetch incremental when it hits; a cold cache just means a full-history fetch
|
||||
(correct, slower).
|
||||
- **Tags point at upstream commits.** That's intentional — it keeps commit
|
||||
hashes identical to the upstream. It also means the workflow can't be
|
||||
triggered *by the tag* (the tag's tree has no workflows), so sync triggers
|
||||
releases inline.
|
||||
- **Provider differences** (releases API, token username) are isolated in
|
||||
`forker/lib/provider.sh`; the rest is provider-agnostic.
|
||||
- **Secrets stay out of the repo.** Upstream URL/token are Gitea Actions
|
||||
Variables/Secrets; the Gitea token is the built-in `GITEA_TOKEN`.
|
||||
- **Runner is the hard dependency.** Without a runner serving the repo, the cron
|
||||
sync and local builds won't run — run the *Runner check* first.
|
||||
- **Gitea forks ship without the Releases unit → asset downloads 404.**
|
||||
Root cause found on this instance (verified in the Gitea source + DB): a fork
|
||||
is created with `DefaultForkRepoUnits = [Code, PullRequests]` — **no
|
||||
Releases unit** — while normal repos get it. So release *assets* uploaded to
|
||||
a fork repo are listed in the API (by-id works) but the web
|
||||
`browser_download_url` returns 404 at the unit-permission check, and the
|
||||
release *source tarball* 404s too.
|
||||
**Detected + fixed:** `sync.sh` runs `check-unit.sh` at the end of every
|
||||
sync — it self-heals via the units API on builds that expose it, and on
|
||||
this build (no units API) it detects the 404 (confirming the API by-id
|
||||
path still works) and prints the exact one-time fix: UI → Settings →
|
||||
Repository → enable the **Releases** unit. `make check-unit` runs it
|
||||
standalone.
|
||||
|
||||
## Security notes
|
||||
|
||||
- **Upstreams are fetched anonymously by default.** `sync.sh` / `release.sh`
|
||||
cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the credential helper before
|
||||
any upstream git call, and add a Bearer header **only** when `UPSTREAM_TOKEN`
|
||||
is set. A stored `~/.git-credentials` entry is therefore *never* offered to
|
||||
`git fetch` — a public upstream is a pure anonymous fetch.
|
||||
- **`build_cmd` / `build_script` run with the tokens in the environment.**
|
||||
`release.sh` keeps `GITEA_TOKEN` and `UPSTREAM_TOKEN` set so it can fetch the
|
||||
tag's tree and publish assets. Any repo member can edit `.forker.yaml`, so a
|
||||
malicious `build_cmd` could exfiltrate both tokens. Treat `build_cmd` /
|
||||
`build_script` as **trusted code with credential access** — only put commands
|
||||
you (or the repo owners) trust there.
|
||||
- **Tokens briefly persist in the cached `.mirror/` git config.** The per-URL
|
||||
`http.<url>.extraHeader` Bearer header is written into `.mirror/config`, and
|
||||
`.mirror/` is the `actions/cache` path. The cache is repo-scoped (not
|
||||
committed), but a cache-service reader can read it until the next save
|
||||
overwrites it. The tokens are never written into the repo itself.
|
||||
@@ -0,0 +1,102 @@
|
||||
# TODO — a futuro
|
||||
|
||||
## [UI] Gestión local de mirrors (npx)
|
||||
|
||||
Una web local (arrancable con `npx`) para gestionar todo el ecosistema de
|
||||
Repo Forker desde un solo lugar, sin tocar API/curl/DB.
|
||||
|
||||
### Idea
|
||||
```
|
||||
npx repo-forker-ui # -> http://localhost:8731 (o el puerto libre)
|
||||
```
|
||||
El UI habla con la API de Gitea (con un token que el usuario pega una vez,
|
||||
guardado localmente — nunca en el repo) y ejecuta las mismas operaciones que
|
||||
los scripts, pero de forma guiada.
|
||||
|
||||
### Features (por prioridad)
|
||||
|
||||
**P0 — Gestión de mirrors (el corazón):**
|
||||
- **Crear un mirror**: pega la URL del upstream (GitHub/Gitea/Codeberg/otro)
|
||||
+ nombre → el UI hace lo que se hace hoy por API/curl:
|
||||
1. `POST /repos/{owner}/repo-forker/generate` con `git_content: true`
|
||||
2. crea la variable `UPSTREAM_URL` (`POST .../actions/variables/UPSTREAM_URL`)
|
||||
3. `PATCH` default branch → la del upstream (o `main`)
|
||||
4. activa `mirror_upstream_releases` en la rama `forker` (reset + re-apply,
|
||||
el procedimiento de AGENTS.md para repos generados)
|
||||
5. dispara el primer `sync.yml` (dispatch) y muestra el progreso
|
||||
- **Lista de mirrors**: todos los repos generados desde `repo-forker`
|
||||
(detectables por la rama `forker` + la variable `UPSTREAM_URL`), con:
|
||||
- estado del último `sync.yml` (green/red, timestamp, duración)
|
||||
- branches / tags / releases / assets (vs upstream — paridad)
|
||||
- unidades activas (Code/Issues/PR/Releases/...)
|
||||
- **Stats y gráficas** (por mirror y agregado):
|
||||
- timeline de runs (success/failure/queued) — sparkline de los últimos 7 días
|
||||
- tiempo de sync por run (cold vs incremental — la caché, cuando exista)
|
||||
- assets por release (barras), crecimiento de branches/tags
|
||||
- latencia de mirror: commits upstream sin replicar todavía
|
||||
- **Eliminar un mirror**: delete del repo (con confirmación + advertencia de
|
||||
lo que se pierde; el template queda intacto)
|
||||
- **Re-sincronizar / forzar**: dispatch manual de `sync.yml` / `release.yml` /
|
||||
`runner-check.yml` desde la UI
|
||||
- **Config per-repo**: editar `.forker.yaml` (los campos conocidos:
|
||||
`mirror_branches`, `mirror_tags`, `mirror_prune`, `mirror_upstream_releases`,
|
||||
`build_cmd`, `build_script`, `artifacts`, `on_new_tag`) con validación de
|
||||
esquema plano (el parser es grep — el UI debe mantenerlo plano)
|
||||
- **Variables & secrets**: listar/crear/borrar las Variables de Actions
|
||||
(`UPSTREAM_URL`, `UPSTREAM_TOKEN` opcional) — los secrets solo se crean,
|
||||
no se leen (la API no los devuelve)
|
||||
|
||||
**P1 — Observabilidad:**
|
||||
- **Cola del runner**: runs `queued`/`in_progress` en vivo (polling), con
|
||||
tiempo de espera — el runner es serial (maxParallel=1), así que una vista
|
||||
de "fila" es muy útil
|
||||
- **Logs en vivo** de un run (stream del log del job, con el
|
||||
`::group::`/`::notice::` de Gitea Actions renderizado)
|
||||
- **Diagnóstico de un run fallido**: extraer la línea de error del log y
|
||||
sugerir la causa (DNS flap, cache timeout, token, unidad Releases)
|
||||
- **Unidades**: ver/quitar/habilitar la unidad Releases (con fallback a DB
|
||||
cuando la API no existe — este build)
|
||||
- **Alerta** de mirror "desactualizado" (última sync > N min con runner idle)
|
||||
|
||||
**P2 — Extras:**
|
||||
- **Generar desde otros templates**: que el UI permita usar cualquier repo
|
||||
marcado `template: true` (no solo repo-forker)
|
||||
- **Import de config**: pegar un `.forker.yaml` y aplicarlo
|
||||
- **Export del estado**: snapshot JSON de todos los mirrors (para backups /
|
||||
re-crear después de una catástrofe)
|
||||
- **Comparador de paridad**: side-by-side upstream vs fork (branches/tags/
|
||||
releases) con diff visual (lo que falta se marca)
|
||||
|
||||
### Notas de diseño
|
||||
|
||||
- **Stack sugerido**: Vite + React (o SvelteKit) + Tailwind; el backend
|
||||
"npx" puede ser un thin server Node que solo hace proxy + auth al Gitea
|
||||
(el UI puede ser 100% client-side si el token se guarda en `localStorage`;
|
||||
el proxy solo evita CORS y esconde el token de los logs del navegador).
|
||||
- **Auth**: el usuario pega su token Gitea (o basic) una vez; se guarda en
|
||||
`~/.repo-forker/credentials` (chmod 600) o `localStorage` según el modo.
|
||||
NUNCA se sube al repo.
|
||||
- **Idempotencia**: todas las acciones de creación deben ser idempotentes
|
||||
(re-crear el mirror con el mismo nombre → "ya existe" + enlazar).
|
||||
- **No duplicar lógica**: las operaciones (generate, variable, default branch,
|
||||
forker reset+re-apply, dispatch) ya están probadas en esta sesión — el UI
|
||||
las reproduce tal cual, no inventa variantes.
|
||||
- **Modo offline**: la UI debe funcionar aunque el Gitea esté caído (los
|
||||
últimos datos cacheados + estado "offline").
|
||||
|
||||
### Criterio de "hecho" (P0)
|
||||
|
||||
1. `npx repo-forker-ui` arranca y se conecta a un Gitea (URL + token).
|
||||
2. Desde la UI: crear un mirror de un repo GitHub público → aparece en la
|
||||
lista con su primer sync en verde y paridad correcta.
|
||||
3. Eliminar un mirror desde la UI (con confirmación).
|
||||
4. Ver en la UI: últimos 20 runs de cada mirror, paridad de
|
||||
branches/tags/releases, y el log del último run.
|
||||
5. Re-sincronizar (dispatch) desde la UI.
|
||||
|
||||
### Estado: **A FUTURO — no empezar sin revisar esta spec**
|
||||
|
||||
La infraestructura ya soporta todo lo que el UI necesita (APIs de generate,
|
||||
variables, dispatch, runners, releases; scripts de sync con retry; `check-unit`;
|
||||
cron de limpieza en tizona). Faltan decisiones: stack, nombre del paquete,
|
||||
y si el modo "solo client-side con token en localStorage" es suficiente.
|
||||
@@ -1,118 +0,0 @@
|
||||
set(ANYPS5_VULKAN_HEADERS_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/3rdparty/Vulkan-Headers/include")
|
||||
set(ANYPS5_SPIRV_HEADERS_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/3rdparty/SPIRV-Headers/include")
|
||||
set(ANYPS5_SDL2_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/3rdparty/SDL2/include")
|
||||
set(ANYPS5_GLSLANG_INCLUDE_DIRS "${CMAKE_SOURCE_DIR}/3rdparty/glslang")
|
||||
set(ANYPS5_SPIRV_HEADERS_SOURCE_DIR "${CMAKE_SOURCE_DIR}/3rdparty/SPIRV-Headers")
|
||||
set(ANYPS5_GLSLANG_SOURCE_DIR "${CMAKE_SOURCE_DIR}/3rdparty/glslang")
|
||||
|
||||
if(NOT ANYPS5_USE_SYSTEM_DEPS)
|
||||
return()
|
||||
endif()
|
||||
|
||||
include(CheckCXXSourceCompiles)
|
||||
|
||||
find_package(SDL2 CONFIG REQUIRED)
|
||||
if(NOT TARGET SDL2::SDL2)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: SDL2 was found but does not provide SDL2::SDL2")
|
||||
endif()
|
||||
add_library(SDL2-static INTERFACE)
|
||||
target_link_libraries(SDL2-static INTERFACE SDL2::SDL2)
|
||||
get_target_property(ANYPS5_SDL2_INCLUDE_DIR SDL2::SDL2 INTERFACE_INCLUDE_DIRECTORIES)
|
||||
if(NOT ANYPS5_SDL2_INCLUDE_DIR)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: SDL2::SDL2 exposes no INTERFACE_INCLUDE_DIRECTORIES")
|
||||
endif()
|
||||
set(ANYPS5_SDL2_PROBE_INCLUDES ${ANYPS5_SDL2_INCLUDE_DIR})
|
||||
foreach(_dir IN LISTS ANYPS5_SDL2_INCLUDE_DIR)
|
||||
list(APPEND ANYPS5_SDL2_PROBE_INCLUDES "${_dir}/SDL2")
|
||||
endforeach()
|
||||
list(REMOVE_DUPLICATES ANYPS5_SDL2_PROBE_INCLUDES)
|
||||
set(CMAKE_REQUIRED_INCLUDES ${ANYPS5_SDL2_PROBE_INCLUDES})
|
||||
check_cxx_source_compiles("#include \"SDL_config.h\"\n#ifndef SDL_JOYSTICK_HIDAPI\n#error SDL_JOYSTICK_HIDAPI is not defined\n#endif\nint main() { return 0; }" ANYPS5_SDL2_HAS_HIDAPI)
|
||||
unset(CMAKE_REQUIRED_INCLUDES)
|
||||
if(NOT ANYPS5_SDL2_HAS_HIDAPI)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: the system SDL2 does not define SDL_JOYSTICK_HIDAPI, so a DualSense gets no light bar, touchpad or trigger effects and the disk audio driver does not preserve the requested format; sdl2-compat (SDL3 underneath) and SDL2 builds with HIDAPI disabled both fail the pad and audio tests; install a real SDL2 2.x built with HIDAPI")
|
||||
endif()
|
||||
|
||||
find_package(Freetype REQUIRED)
|
||||
if(NOT TARGET Freetype::Freetype)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: freetype was found but does not provide Freetype::Freetype")
|
||||
endif()
|
||||
add_library(freetype INTERFACE)
|
||||
target_link_libraries(freetype INTERFACE Freetype::Freetype)
|
||||
|
||||
find_package(VulkanHeaders CONFIG REQUIRED)
|
||||
if(NOT TARGET Vulkan::Headers)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: Vulkan-Headers was found but does not provide Vulkan::Headers")
|
||||
endif()
|
||||
get_target_property(ANYPS5_VULKAN_HEADERS_INCLUDE_DIR Vulkan::Headers INTERFACE_INCLUDE_DIRECTORIES)
|
||||
if(NOT ANYPS5_VULKAN_HEADERS_INCLUDE_DIR)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: Vulkan::Headers exposes no INTERFACE_INCLUDE_DIRECTORIES")
|
||||
endif()
|
||||
set(CMAKE_REQUIRED_INCLUDES ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR})
|
||||
check_cxx_source_compiles("#include <vulkan/vulkan.h>\nint main() { VkPhysicalDeviceMaintenance8FeaturesKHR features{}; (void)features; return 0; }" ANYPS5_VULKAN_HAS_MAINTENANCE8)
|
||||
unset(CMAKE_REQUIRED_INCLUDES)
|
||||
if(NOT ANYPS5_VULKAN_HAS_MAINTENANCE8)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: the system Vulkan-Headers do not provide VkPhysicalDeviceMaintenance8FeaturesKHR (VK_KHR_maintenance8), which the agc driver uses; install Vulkan-Headers 1.4.310 or newer")
|
||||
endif()
|
||||
|
||||
find_package(SPIRV-Headers CONFIG REQUIRED)
|
||||
if(NOT TARGET SPIRV-Headers::SPIRV-Headers)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: SPIRV-Headers was found but does not provide SPIRV-Headers::SPIRV-Headers")
|
||||
endif()
|
||||
get_target_property(ANYPS5_SPIRV_HEADERS_INCLUDE_DIR SPIRV-Headers::SPIRV-Headers INTERFACE_INCLUDE_DIRECTORIES)
|
||||
if(NOT ANYPS5_SPIRV_HEADERS_INCLUDE_DIR)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: SPIRV-Headers::SPIRV-Headers exposes no INTERFACE_INCLUDE_DIRECTORIES")
|
||||
endif()
|
||||
|
||||
find_package(glslang CONFIG REQUIRED)
|
||||
if(NOT TARGET glslang::glslang OR NOT TARGET glslang::SPIRV)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: glslang was found but does not provide glslang::glslang and glslang::SPIRV")
|
||||
endif()
|
||||
add_library(glslang INTERFACE)
|
||||
target_link_libraries(glslang INTERFACE glslang::glslang)
|
||||
add_library(SPIRV INTERFACE)
|
||||
target_link_libraries(SPIRV INTERFACE glslang::SPIRV)
|
||||
find_path(ANYPS5_GLSLANG_PUBLIC_INCLUDE_DIR NAMES glslang/Public/ShaderLang.h)
|
||||
if(NOT ANYPS5_GLSLANG_PUBLIC_INCLUDE_DIR)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: glslang/Public/ShaderLang.h was not found; the glslang headers are incomplete")
|
||||
endif()
|
||||
set(ANYPS5_GLSLANG_SPIRV_INCLUDE_DIR "${ANYPS5_GLSLANG_PUBLIC_INCLUDE_DIR}/glslang")
|
||||
if(NOT EXISTS "${ANYPS5_GLSLANG_SPIRV_INCLUDE_DIR}/SPIRV/GlslangToSpv.h")
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: ${ANYPS5_GLSLANG_SPIRV_INCLUDE_DIR}/SPIRV/GlslangToSpv.h was not found")
|
||||
endif()
|
||||
set(ANYPS5_GLSLANG_INCLUDE_DIRS "${ANYPS5_GLSLANG_PUBLIC_INCLUDE_DIR};${ANYPS5_GLSLANG_SPIRV_INCLUDE_DIR}")
|
||||
|
||||
find_program(ANYPS5_GLSLANG_STANDALONE_EXECUTABLE NAMES glslang glslangValidator)
|
||||
if(NOT ANYPS5_GLSLANG_STANDALONE_EXECUTABLE)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: the glslang compiler (glslang or glslangValidator) was not found; install the glslang tools package")
|
||||
endif()
|
||||
add_executable(glslang-standalone IMPORTED GLOBAL)
|
||||
set_target_properties(glslang-standalone PROPERTIES IMPORTED_LOCATION "${ANYPS5_GLSLANG_STANDALONE_EXECUTABLE}")
|
||||
|
||||
if(ANYPS5_ENABLE_SPIRV_TOOLS)
|
||||
find_package(SPIRV-Tools-opt CONFIG REQUIRED)
|
||||
if(NOT TARGET SPIRV-Tools-opt)
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: SPIRV-Tools was found but does not provide SPIRV-Tools-opt")
|
||||
endif()
|
||||
if(NOT TARGET SPIRV-Tools-static)
|
||||
if(TARGET SPIRV-Tools)
|
||||
add_library(SPIRV-Tools-static INTERFACE)
|
||||
target_link_libraries(SPIRV-Tools-static INTERFACE SPIRV-Tools)
|
||||
else()
|
||||
message(FATAL_ERROR "ANYPS5_USE_SYSTEM_DEPS: SPIRV-Tools was found but provides neither SPIRV-Tools-static nor SPIRV-Tools")
|
||||
endif()
|
||||
endif()
|
||||
endif()
|
||||
|
||||
set(ANYPS5_SYSTEM_DEPS_STAMP "")
|
||||
list(APPEND ANYPS5_SYSTEM_DEPS_PACKAGES VulkanHeaders SPIRV-Headers glslang)
|
||||
if(ANYPS5_ENABLE_SPIRV_TOOLS)
|
||||
list(APPEND ANYPS5_SYSTEM_DEPS_PACKAGES SPIRV-Tools-opt)
|
||||
endif()
|
||||
foreach(_package IN LISTS ANYPS5_SYSTEM_DEPS_PACKAGES)
|
||||
set(_version "unknown")
|
||||
if(DEFINED ${_package}_VERSION)
|
||||
set(_version "${${_package}_VERSION}")
|
||||
endif()
|
||||
string(APPEND ANYPS5_SYSTEM_DEPS_STAMP " ${_package}=${_version}")
|
||||
endforeach()
|
||||
@@ -1,21 +0,0 @@
|
||||
set(TRACY_ENABLE ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_STATIC OFF CACHE BOOL "" FORCE)
|
||||
set(TRACY_ON_DEMAND ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_ONLY_LOCALHOST ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_CRASH_HANDLER ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_CODE_TRANSFER ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_SAMPLING ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_SYSTEM_TRACING ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_CALLSTACK ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_FRAME_IMAGE ON CACHE BOOL "" FORCE)
|
||||
set(TRACY_NO_VERIFY ON CACHE BOOL "" FORCE)
|
||||
set(CMAKE_DISABLE_FIND_PACKAGE_rocprofiler-sdk ON)
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdparty/tracy ${CMAKE_BINARY_DIR}/3rdparty/tracy EXCLUDE_FROM_ALL)
|
||||
|
||||
if(MINGW)
|
||||
target_sources(TracyClient PRIVATE ${CMAKE_CURRENT_LIST_DIR}/TracyThreadExit.cpp)
|
||||
target_compile_definitions(TracyClient PRIVATE TRACY_DELAYED_INIT)
|
||||
get_target_property(tracyInterfaceDefinitions TracyClient INTERFACE_COMPILE_DEFINITIONS)
|
||||
list(FILTER tracyInterfaceDefinitions EXCLUDE REGEX "^(WINVER|_WIN32_WINNT)=")
|
||||
set_target_properties(TracyClient PROPERTIES INTERFACE_COMPILE_DEFINITIONS "${tracyInterfaceDefinitions}")
|
||||
endif()
|
||||
@@ -1,3 +0,0 @@
|
||||
extern "C" int __cxa_thread_atexit(void (*)(void*), void*, void*) {
|
||||
return 0;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
#include <process.h>
|
||||
#include <windows.h>
|
||||
|
||||
extern "C" int __real_main(int argc, char** argv);
|
||||
|
||||
namespace {
|
||||
|
||||
template<typename TFunction>
|
||||
TFunction LibcFunction(const char* name) {
|
||||
const HMODULE libc = GetModuleHandleW(L"libc.prx");
|
||||
if (libc == nullptr) return nullptr;
|
||||
return reinterpret_cast<TFunction>(reinterpret_cast<void*>(GetProcAddress(libc, name)));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C" int __wrap_main(int argc, char** argv) {
|
||||
const int code = __real_main(argc, argv);
|
||||
const auto terminate = LibcFunction<void (*)(int)>("LibcTerminate_nid_no_patch");
|
||||
if (terminate == nullptr) return code;
|
||||
_cexit();
|
||||
std::cout.flush();
|
||||
std::clog.flush();
|
||||
std::cerr.flush();
|
||||
std::fflush(nullptr);
|
||||
terminate(code);
|
||||
return code;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
enable_language(C)
|
||||
|
||||
set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)
|
||||
set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)
|
||||
set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)
|
||||
set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)
|
||||
set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)
|
||||
set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)
|
||||
set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdparty/zstd/build/cmake ${CMAKE_BINARY_DIR}/3rdparty/zstd EXCLUDE_FROM_ALL)
|
||||
set_target_properties(libzstd_static PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
|
||||
set(ZARCHIVE_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/ZArchive)
|
||||
add_library(zarchive STATIC EXCLUDE_FROM_ALL
|
||||
${ZARCHIVE_SOURCE_DIR}/src/zarchivereader.cpp
|
||||
${ZARCHIVE_SOURCE_DIR}/src/zarchivewriter.cpp
|
||||
${ZARCHIVE_SOURCE_DIR}/src/sha_256.c
|
||||
)
|
||||
target_include_directories(zarchive SYSTEM PUBLIC ${ZARCHIVE_SOURCE_DIR}/include)
|
||||
target_compile_features(zarchive PUBLIC cxx_std_20)
|
||||
target_link_libraries(zarchive PRIVATE libzstd_static)
|
||||
set_target_properties(zarchive PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(zarchive INTERFACE LINKER:--exclude-libs,libzarchive.a:libzstd.a)
|
||||
endif()
|
||||
@@ -1,80 +0,0 @@
|
||||
function(add_jpeg_decoder target runtimeTarget)
|
||||
if(NOT TARGET "${runtimeTarget}")
|
||||
message(FATAL_ERROR "JPEG decoder requires an existing runtime target: ${runtimeTarget}")
|
||||
endif()
|
||||
|
||||
include(ExternalProject)
|
||||
if(NOT TARGET jpeg_turbo_external)
|
||||
set(jpeg_turbo_prefix "${CMAKE_BINARY_DIR}/libjpeg-turbo")
|
||||
if(WIN32)
|
||||
if(MSVC)
|
||||
set(jpeg_turbo_library "${jpeg_turbo_prefix}/lib/turbojpeg-static.lib")
|
||||
else()
|
||||
set(jpeg_turbo_library "${jpeg_turbo_prefix}/lib/libturbojpeg.a")
|
||||
endif()
|
||||
else()
|
||||
set(jpeg_turbo_library "${jpeg_turbo_prefix}/lib/libturbojpeg.a")
|
||||
endif()
|
||||
file(MAKE_DIRECTORY "${jpeg_turbo_prefix}/include")
|
||||
set(jpeg_turbo_platform_args)
|
||||
if(APPLE)
|
||||
list(APPEND jpeg_turbo_platform_args
|
||||
-DCMAKE_OSX_ARCHITECTURES=${CMAKE_OSX_ARCHITECTURES}
|
||||
-DCMAKE_APPLE_SILICON_PROCESSOR=${CMAKE_APPLE_SILICON_PROCESSOR})
|
||||
endif()
|
||||
ExternalProject_Add(jpeg_turbo_external
|
||||
SOURCE_DIR "${PROJECT_SOURCE_DIR}/3rdparty/libjpeg-turbo"
|
||||
BINARY_DIR "${CMAKE_BINARY_DIR}/libjpeg-turbo-build"
|
||||
INSTALL_DIR "${jpeg_turbo_prefix}"
|
||||
CMAKE_ARGS
|
||||
-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}
|
||||
-DCMAKE_INSTALL_PREFIX=${jpeg_turbo_prefix}
|
||||
-DBUILD_SHARED_LIBS=OFF
|
||||
-DENABLE_STATIC=ON
|
||||
-DENABLE_SHARED=OFF
|
||||
-DWITH_SIMD=OFF
|
||||
-DWITH_TURBOJPEG=ON
|
||||
-DWITH_TOOLS=OFF
|
||||
-DWITH_TESTS=OFF
|
||||
-DCMAKE_INSTALL_LIBDIR=lib
|
||||
-DCMAKE_C_VISIBILITY_PRESET=hidden
|
||||
-DCMAKE_VISIBILITY_INLINES_HIDDEN=ON
|
||||
-DCMAKE_POSITION_INDEPENDENT_CODE=ON
|
||||
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}
|
||||
-DCMAKE_MAKE_PROGRAM=${CMAKE_MAKE_PROGRAM}
|
||||
-DCMAKE_C_COMPILER_LAUNCHER=${CMAKE_C_COMPILER_LAUNCHER}
|
||||
-DCMAKE_CXX_COMPILER_LAUNCHER=${CMAKE_CXX_COMPILER_LAUNCHER}
|
||||
${jpeg_turbo_platform_args}
|
||||
BUILD_BYPRODUCTS
|
||||
"${jpeg_turbo_library}"
|
||||
)
|
||||
add_library(jpeg_turbo STATIC IMPORTED GLOBAL)
|
||||
set_target_properties(jpeg_turbo PROPERTIES
|
||||
IMPORTED_LOCATION "${jpeg_turbo_library}"
|
||||
INTERFACE_INCLUDE_DIRECTORIES "${PROJECT_SOURCE_DIR}/3rdparty/libjpeg-turbo/src;${jpeg_turbo_prefix}/include"
|
||||
)
|
||||
add_dependencies(jpeg_turbo jpeg_turbo_external)
|
||||
endif()
|
||||
|
||||
add_library(${target} STATIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/src/Jpeg.cpp)
|
||||
target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/include)
|
||||
target_include_directories(${target} SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb)
|
||||
target_link_libraries(${target} PRIVATE ${runtimeTarget} jpeg_turbo)
|
||||
set_target_properties(${target} PROPERTIES
|
||||
CXX_EXTENSIONS OFF
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_test_executable(${target}_tests ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/tests/Jpeg.cpp)
|
||||
target_link_libraries(${target}_tests PRIVATE ${target})
|
||||
configure_windows_unwind(${target}_tests)
|
||||
add_test(NAME ${target} COMMAND ${target}_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(${target} PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:${runtimeTarget}>")
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
@@ -1,44 +0,0 @@
|
||||
#ifndef DECODER_JPEG_HPP
|
||||
#define DECODER_JPEG_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Decoder::Jpeg {
|
||||
|
||||
struct Image {
|
||||
std::uint32_t width;
|
||||
std::uint32_t height;
|
||||
std::uint32_t channels;
|
||||
std::vector<std::uint8_t> pixels;
|
||||
};
|
||||
|
||||
struct Header {
|
||||
std::uint32_t width;
|
||||
std::uint32_t height;
|
||||
std::uint32_t channels;
|
||||
};
|
||||
|
||||
enum class Sampling {
|
||||
Yuv444,
|
||||
Yuv422,
|
||||
Yuv420,
|
||||
};
|
||||
|
||||
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
|
||||
std::uint32_t channels, int quality, Sampling sampling = Sampling::Yuv444,
|
||||
std::uint32_t restartBlocks = 0, std::uint32_t restartRows = 0);
|
||||
|
||||
std::optional<Header> ParseHeader(std::span<const std::uint8_t> jpeg);
|
||||
|
||||
std::optional<Image> Decode(std::span<const std::uint8_t> jpeg);
|
||||
|
||||
std::uint32_t ScaledDimension(std::uint32_t dimension, std::uint32_t denominator);
|
||||
|
||||
std::optional<Image> DecodeScaled(std::span<const std::uint8_t> jpeg, std::uint32_t denominator);
|
||||
|
||||
} // namespace Decoder::Jpeg
|
||||
|
||||
#endif // DECODER_JPEG_HPP
|
||||
@@ -1,146 +0,0 @@
|
||||
#include "Decoder/Jpeg.hpp"
|
||||
|
||||
#include <climits>
|
||||
#include <cstddef>
|
||||
#include <stdexcept>
|
||||
|
||||
#define STB_IMAGE_STATIC
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STBI_ONLY_JPEG
|
||||
#define STBI_NO_STDIO
|
||||
#include "stb_image.h"
|
||||
#include "turbojpeg.h"
|
||||
|
||||
namespace Decoder::Jpeg {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr std::uint32_t MAX_DIMENSION = 0xFFFF;
|
||||
|
||||
class Handle {
|
||||
public:
|
||||
explicit Handle(int type) : handle(tj3Init(type)) {
|
||||
if (!handle) throw std::runtime_error(type == TJINIT_COMPRESS ? "Jpeg::Encode: encoder initialization failed" : "Jpeg::DecodeScaled: decoder initialization failed");
|
||||
}
|
||||
~Handle() { tj3Destroy(handle); }
|
||||
Handle(const Handle&) = delete;
|
||||
Handle& operator=(const Handle&) = delete;
|
||||
operator tjhandle() const { return handle; }
|
||||
|
||||
private:
|
||||
tjhandle handle;
|
||||
};
|
||||
|
||||
class Buffer {
|
||||
public:
|
||||
~Buffer() { tj3Free(data); }
|
||||
unsigned char* data = nullptr;
|
||||
};
|
||||
|
||||
int toSubsampling(Sampling sampling) {
|
||||
switch (sampling) {
|
||||
case Sampling::Yuv444: return TJSAMP_444;
|
||||
case Sampling::Yuv422: return TJSAMP_422;
|
||||
case Sampling::Yuv420: return TJSAMP_420;
|
||||
}
|
||||
throw std::invalid_argument("Jpeg::Encode: invalid sampling");
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
|
||||
std::uint32_t channels, int quality, Sampling sampling, std::uint32_t restartBlocks,
|
||||
std::uint32_t restartRows) {
|
||||
if (width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION) {
|
||||
throw std::invalid_argument("Jpeg::Encode: unsupported image size");
|
||||
}
|
||||
if (channels != 1 && channels != 3) throw std::invalid_argument("Jpeg::Encode: channels must be 1 or 3");
|
||||
if (quality < 1 || quality > 100) throw std::invalid_argument("Jpeg::Encode: quality must be 1-100");
|
||||
if (pixels.size() < static_cast<std::size_t>(width) * height * channels) {
|
||||
throw std::invalid_argument("Jpeg::Encode: pixel buffer is too small");
|
||||
}
|
||||
if (restartBlocks > MAX_DIMENSION || restartRows > MAX_DIMENSION || (restartBlocks != 0 && restartRows != 0)) {
|
||||
throw std::invalid_argument("Jpeg::Encode: invalid restart interval");
|
||||
}
|
||||
const int subsampling = toSubsampling(sampling);
|
||||
Handle handle(TJINIT_COMPRESS);
|
||||
if (tj3Set(handle, TJPARAM_QUALITY, quality) < 0 || tj3Set(handle, TJPARAM_SUBSAMP, channels == 1 ? TJSAMP_GRAY : subsampling) < 0) {
|
||||
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
|
||||
}
|
||||
if ((restartBlocks != 0 && tj3Set(handle, TJPARAM_RESTARTBLOCKS, static_cast<int>(restartBlocks)) < 0) ||
|
||||
(restartRows != 0 && tj3Set(handle, TJPARAM_RESTARTROWS, static_cast<int>(restartRows)) < 0)) {
|
||||
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
|
||||
}
|
||||
Buffer buffer;
|
||||
std::size_t size = 0;
|
||||
const int pixelFormat = channels == 1 ? TJPF_GRAY : TJPF_RGB;
|
||||
if (tj3Compress8(handle, pixels.data(), static_cast<int>(width), 0, static_cast<int>(height), pixelFormat, &buffer.data, &size) < 0) {
|
||||
throw std::runtime_error("Jpeg::Encode: encoding failed");
|
||||
}
|
||||
return {buffer.data, buffer.data + size};
|
||||
}
|
||||
|
||||
std::uint32_t ScaledDimension(std::uint32_t dimension, std::uint32_t denominator) {
|
||||
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) {
|
||||
throw std::invalid_argument("Jpeg::ScaledDimension: the scale must be 1/1, 1/2, 1/4 or 1/8");
|
||||
}
|
||||
const tjscalingfactor factor{1, static_cast<int>(denominator)};
|
||||
return static_cast<std::uint32_t>(TJSCALED(static_cast<std::uint64_t>(dimension), factor));
|
||||
}
|
||||
|
||||
std::optional<Image> DecodeScaled(std::span<const std::uint8_t> jpeg, std::uint32_t denominator) {
|
||||
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) {
|
||||
throw std::invalid_argument("Jpeg::DecodeScaled: the scale must be 1/1, 1/2, 1/4 or 1/8");
|
||||
}
|
||||
if (jpeg.empty() || jpeg.size() > INT_MAX) return std::nullopt;
|
||||
|
||||
Handle handle(TJINIT_DECOMPRESS);
|
||||
if (tj3Set(handle, TJPARAM_STOPONWARNING, 1) < 0) throw std::runtime_error("Jpeg::DecodeScaled: decoder configuration failed");
|
||||
if (tj3DecompressHeader(handle, jpeg.data(), jpeg.size()) < 0) return std::nullopt;
|
||||
const int colorspace = tj3Get(handle, TJPARAM_COLORSPACE);
|
||||
if (colorspace == TJCS_CMYK || colorspace == TJCS_YCCK) {
|
||||
throw std::runtime_error("Jpeg::DecodeScaled: scaled decoding of a CMYK or YCCK image is not implemented");
|
||||
}
|
||||
const int width = tj3Get(handle, TJPARAM_JPEGWIDTH);
|
||||
const int height = tj3Get(handle, TJPARAM_JPEGHEIGHT);
|
||||
if (width <= 0 || height <= 0) return std::nullopt;
|
||||
if (tj3SetScalingFactor(handle, tjscalingfactor{1, static_cast<int>(denominator)}) < 0) {
|
||||
throw std::runtime_error("Jpeg::DecodeScaled: the decoder refused the scaling factor");
|
||||
}
|
||||
|
||||
const std::uint32_t channels = colorspace == TJCS_GRAY ? 1 : 3;
|
||||
Image image{ScaledDimension(static_cast<std::uint32_t>(width), denominator), ScaledDimension(static_cast<std::uint32_t>(height), denominator), channels, {}};
|
||||
image.pixels.resize(static_cast<std::size_t>(image.width) * image.height * channels);
|
||||
if (tj3Decompress8(handle, jpeg.data(), jpeg.size(), image.pixels.data(), 0, channels == 1 ? TJPF_GRAY : TJPF_RGB) < 0) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
std::optional<Header> ParseHeader(std::span<const std::uint8_t> jpeg) {
|
||||
if (jpeg.empty() || jpeg.size() > INT_MAX) return std::nullopt;
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int channels = 0;
|
||||
if (!stbi_info_from_memory(jpeg.data(), static_cast<int>(jpeg.size()), &width, &height, &channels)) return std::nullopt;
|
||||
if (width <= 0 || height <= 0 || channels <= 0) return std::nullopt;
|
||||
return Header{static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height), static_cast<std::uint32_t>(channels)};
|
||||
}
|
||||
|
||||
std::optional<Image> Decode(std::span<const std::uint8_t> jpeg) {
|
||||
if (jpeg.empty() || jpeg.size() > INT_MAX) return std::nullopt;
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int channels = 0;
|
||||
stbi_uc* decoded = stbi_load_from_memory(jpeg.data(), static_cast<int>(jpeg.size()), &width, &height, &channels, 0);
|
||||
if (!decoded) return std::nullopt;
|
||||
|
||||
Image image{static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height), static_cast<std::uint32_t>(channels), {}};
|
||||
image.pixels.assign(decoded, decoded + static_cast<std::size_t>(image.width) * image.height * image.channels);
|
||||
stbi_image_free(decoded);
|
||||
return image;
|
||||
}
|
||||
|
||||
} // namespace Decoder::Jpeg
|
||||
@@ -1,180 +0,0 @@
|
||||
#include "Decoder/Jpeg.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
static void Require(bool value) { if (!value) std::abort(); }
|
||||
|
||||
template<typename TFunction>
|
||||
static bool ThrowsInvalidArgument(TFunction function) {
|
||||
try {
|
||||
function();
|
||||
} catch (const std::invalid_argument&) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool IsJpeg(const std::vector<std::uint8_t>& data) {
|
||||
return data.size() > 4 && data[0] == 0xFF && data[1] == 0xD8 && data[data.size() - 2] == 0xFF && data.back() == 0xD9;
|
||||
}
|
||||
|
||||
static int Difference(std::uint8_t left, std::uint8_t right) {
|
||||
return left > right ? left - right : right - left;
|
||||
}
|
||||
|
||||
struct FrameInfo { int components; std::uint8_t sampling; };
|
||||
|
||||
static FrameInfo ReadFrame(const std::vector<std::uint8_t>& jpeg) {
|
||||
std::size_t offset = 2;
|
||||
while (offset + 3 < jpeg.size()) {
|
||||
Require(jpeg[offset++] == 0xFF);
|
||||
while (offset < jpeg.size() && jpeg[offset] == 0xFF) ++offset;
|
||||
Require(offset < jpeg.size());
|
||||
const std::uint8_t marker = jpeg[offset++];
|
||||
if (marker == 0xDA || marker == 0xD9) break;
|
||||
Require(offset + 1 < jpeg.size());
|
||||
const std::size_t length = (static_cast<std::size_t>(jpeg[offset]) << 8) | jpeg[offset + 1];
|
||||
Require(length >= 2 && offset + length <= jpeg.size());
|
||||
if (marker >= 0xC0 && marker <= 0xC3) return {jpeg[offset + 7], jpeg[offset + 9]};
|
||||
offset += length;
|
||||
}
|
||||
std::abort();
|
||||
}
|
||||
|
||||
int main() {
|
||||
constexpr std::uint32_t width = 32;
|
||||
constexpr std::uint32_t height = 24;
|
||||
|
||||
std::vector<std::uint8_t> rgb(width * height * 3);
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
std::uint8_t* pixel = &rgb[(y * width + x) * 3];
|
||||
pixel[0] = static_cast<std::uint8_t>(x * 8);
|
||||
pixel[1] = static_cast<std::uint8_t>(y * 10);
|
||||
pixel[2] = 128;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<std::uint8_t> rgbJpeg = Decoder::Jpeg::Encode(rgb, width, height, 3, 90);
|
||||
Require(IsJpeg(rgbJpeg));
|
||||
Require(ReadFrame(rgbJpeg).components == 3 && ReadFrame(rgbJpeg).sampling == 0x11);
|
||||
const auto rgbImage = Decoder::Jpeg::Decode(rgbJpeg);
|
||||
Require(rgbImage.has_value());
|
||||
Require(rgbImage->width == width && rgbImage->height == height && rgbImage->channels == 3);
|
||||
Require(rgbImage->pixels.size() == rgb.size());
|
||||
long totalError = 0;
|
||||
for (std::size_t i = 0; i < rgb.size(); ++i) totalError += Difference(rgb[i], rgbImage->pixels[i]);
|
||||
Require(totalError / static_cast<long>(rgb.size()) < 4);
|
||||
|
||||
std::vector<std::uint8_t> gray(width * height);
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
for (std::uint32_t x = 0; x < width; ++x) gray[y * width + x] = static_cast<std::uint8_t>((x + y) * 4);
|
||||
}
|
||||
const std::vector<std::uint8_t> grayJpeg = Decoder::Jpeg::Encode(gray, width, height, 1, 90);
|
||||
Require(IsJpeg(grayJpeg));
|
||||
Require(ReadFrame(grayJpeg).components == 1);
|
||||
const auto grayImage = Decoder::Jpeg::Decode(grayJpeg);
|
||||
Require(grayImage.has_value());
|
||||
Require(grayImage->width == width && grayImage->height == height);
|
||||
totalError = 0;
|
||||
for (std::size_t i = 0; i < gray.size(); ++i) totalError += Difference(gray[i], grayImage->pixels[i * grayImage->channels]);
|
||||
Require(totalError / static_cast<long>(gray.size()) < 4);
|
||||
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 4, 90); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 0); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 101); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0, height, 3, 90); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0x10000, 1, 3, 90); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height + 1, 3, 90); }));
|
||||
|
||||
for (const auto [sampling, factor] : {std::pair{Decoder::Jpeg::Sampling::Yuv444, std::uint8_t{0x11}},
|
||||
std::pair{Decoder::Jpeg::Sampling::Yuv422, std::uint8_t{0x21}},
|
||||
std::pair{Decoder::Jpeg::Sampling::Yuv420, std::uint8_t{0x22}}}) {
|
||||
const auto encoded = Decoder::Jpeg::Encode(rgb, 31, 23, 3, 1, sampling);
|
||||
Require(ReadFrame(encoded).components == 3 && ReadFrame(encoded).sampling == factor);
|
||||
const auto highQuality = Decoder::Jpeg::Encode(rgb, 31, 23, 3, 100, sampling);
|
||||
Require(ReadFrame(highQuality).components == 3 && ReadFrame(highQuality).sampling == factor);
|
||||
}
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, static_cast<Decoder::Jpeg::Sampling>(3)); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, Decoder::Jpeg::Sampling::Yuv444, 1, 1); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, Decoder::Jpeg::Sampling::Yuv444, 0x10000, 0); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, Decoder::Jpeg::Sampling::Yuv444, 0, 0x10000); }));
|
||||
|
||||
Require(!Decoder::Jpeg::Decode({}).has_value());
|
||||
const std::vector<std::uint8_t> garbage{1, 2, 3, 4, 5, 6, 7, 8};
|
||||
Require(!Decoder::Jpeg::Decode(garbage).has_value());
|
||||
|
||||
Require(Decoder::Jpeg::ScaledDimension(7, 1) == 7 && Decoder::Jpeg::ScaledDimension(7, 2) == 4);
|
||||
Require(Decoder::Jpeg::ScaledDimension(7, 4) == 2 && Decoder::Jpeg::ScaledDimension(7, 8) == 1);
|
||||
Require(Decoder::Jpeg::ScaledDimension(32, 8) == 4 && Decoder::Jpeg::ScaledDimension(33, 8) == 5 && Decoder::Jpeg::ScaledDimension(1, 8) == 1);
|
||||
Require(Decoder::Jpeg::ScaledDimension(0xFFFF, 2) == 0x8000);
|
||||
for (const std::uint32_t denominator : {0u, 3u, 16u}) {
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::ScaledDimension(7, denominator); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::DecodeScaled(rgbJpeg, denominator); }));
|
||||
}
|
||||
|
||||
const auto boxError = [](const std::vector<std::uint8_t>& source, std::uint32_t sourceWidth, std::uint32_t sourceHeight,
|
||||
std::uint32_t channels, const Decoder::Jpeg::Image& scaled, std::uint32_t denominator) {
|
||||
long error = 0;
|
||||
for (std::uint32_t y = 0; y < scaled.height; ++y) {
|
||||
for (std::uint32_t x = 0; x < scaled.width; ++x) {
|
||||
for (std::uint32_t c = 0; c < channels; ++c) {
|
||||
long sum = 0;
|
||||
long count = 0;
|
||||
for (std::uint32_t sy = y * denominator; sy < std::min(sourceHeight, (y + 1) * denominator); ++sy) {
|
||||
for (std::uint32_t sx = x * denominator; sx < std::min(sourceWidth, (x + 1) * denominator); ++sx) {
|
||||
sum += source[(static_cast<std::size_t>(sy) * sourceWidth + sx) * channels + c];
|
||||
++count;
|
||||
}
|
||||
}
|
||||
const auto average = static_cast<std::uint8_t>((sum + count / 2) / count);
|
||||
error += Difference(average, scaled.pixels[(static_cast<std::size_t>(y) * scaled.width + x) * channels + c]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return error / static_cast<long>(static_cast<std::size_t>(scaled.width) * scaled.height * channels);
|
||||
};
|
||||
|
||||
for (const std::uint32_t denominator : {1u, 2u, 4u, 8u}) {
|
||||
const auto scaled = Decoder::Jpeg::DecodeScaled(rgbJpeg, denominator);
|
||||
Require(scaled.has_value() && scaled->channels == 3);
|
||||
Require(scaled->width == width / denominator && scaled->height == height / denominator);
|
||||
Require(scaled->pixels.size() == static_cast<std::size_t>(scaled->width) * scaled->height * 3);
|
||||
Require(boxError(rgb, width, height, 3, *scaled, denominator) < 4);
|
||||
|
||||
const auto grayScaled = Decoder::Jpeg::DecodeScaled(grayJpeg, denominator);
|
||||
Require(grayScaled.has_value() && grayScaled->channels == 1);
|
||||
Require(grayScaled->width == width / denominator && grayScaled->height == height / denominator);
|
||||
Require(boxError(gray, width, height, 1, *grayScaled, denominator) < 4);
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> odd(31 * 23 * 3);
|
||||
for (std::uint32_t y = 0; y < 23; ++y) {
|
||||
for (std::uint32_t x = 0; x < 31; ++x) {
|
||||
std::uint8_t* pixel = &odd[(y * 31 + x) * 3];
|
||||
pixel[0] = static_cast<std::uint8_t>(x * 8);
|
||||
pixel[1] = static_cast<std::uint8_t>(y * 11);
|
||||
pixel[2] = static_cast<std::uint8_t>(200 - x * 2);
|
||||
}
|
||||
}
|
||||
const auto oddJpeg = Decoder::Jpeg::Encode(odd, 31, 23, 3, 95, Decoder::Jpeg::Sampling::Yuv420);
|
||||
for (const std::uint32_t denominator : {2u, 4u, 8u}) {
|
||||
const auto scaled = Decoder::Jpeg::DecodeScaled(oddJpeg, denominator);
|
||||
Require(scaled.has_value() && scaled->channels == 3);
|
||||
Require(scaled->width == Decoder::Jpeg::ScaledDimension(31, denominator) && scaled->height == Decoder::Jpeg::ScaledDimension(23, denominator));
|
||||
Require(boxError(odd, 31, 23, 3, *scaled, denominator) < 8);
|
||||
}
|
||||
|
||||
Require(!Decoder::Jpeg::DecodeScaled({}, 2).has_value());
|
||||
Require(!Decoder::Jpeg::DecodeScaled(garbage, 2).has_value());
|
||||
const std::vector<std::uint8_t> truncated(rgbJpeg.begin(), rgbJpeg.begin() + static_cast<std::ptrdiff_t>(rgbJpeg.size() / 2));
|
||||
Require(!Decoder::Jpeg::DecodeScaled(truncated, 2).has_value());
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
function(add_png_decoder target runtimeTarget)
|
||||
if(NOT TARGET "${runtimeTarget}")
|
||||
message(FATAL_ERROR "PNG decoder requires an existing runtime target: ${runtimeTarget}")
|
||||
endif()
|
||||
|
||||
add_library(${target} STATIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/src/Png.cpp)
|
||||
target_include_directories(${target} PUBLIC ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/include)
|
||||
target_include_directories(${target} SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb)
|
||||
target_link_libraries(${target} PRIVATE ${runtimeTarget})
|
||||
set_target_properties(${target} PROPERTIES
|
||||
CXX_EXTENSIONS OFF
|
||||
CXX_VISIBILITY_PRESET hidden
|
||||
VISIBILITY_INLINES_HIDDEN ON
|
||||
POSITION_INDEPENDENT_CODE ON
|
||||
)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_test_executable(${target}_tests ${CMAKE_CURRENT_FUNCTION_LIST_DIR}/tests/Png.cpp)
|
||||
target_include_directories(${target}_tests SYSTEM PRIVATE ${PROJECT_SOURCE_DIR}/3rdparty/stb)
|
||||
target_link_libraries(${target}_tests PRIVATE ${target})
|
||||
configure_windows_unwind(${target}_tests)
|
||||
add_test(NAME ${target} COMMAND ${target}_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(${target} PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:${runtimeTarget}>")
|
||||
endif()
|
||||
endif()
|
||||
endfunction()
|
||||
@@ -1,55 +0,0 @@
|
||||
#ifndef DECODER_PNG_HPP
|
||||
#define DECODER_PNG_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
namespace Decoder::Png {
|
||||
|
||||
enum class ColorType : std::uint8_t {
|
||||
Grayscale = 0,
|
||||
Rgb = 2,
|
||||
Palette = 3,
|
||||
GrayscaleAlpha = 4,
|
||||
Rgba = 6,
|
||||
};
|
||||
|
||||
struct Header {
|
||||
std::uint32_t width;
|
||||
std::uint32_t height;
|
||||
std::uint8_t bitDepth;
|
||||
ColorType colorType;
|
||||
bool interlaced;
|
||||
bool hasTransparency;
|
||||
};
|
||||
|
||||
struct Image {
|
||||
std::uint32_t width;
|
||||
std::uint32_t height;
|
||||
std::vector<std::uint8_t> pixels;
|
||||
};
|
||||
|
||||
std::optional<Header> ParseHeader(std::span<const std::uint8_t> png);
|
||||
|
||||
std::optional<Image> Decode(std::span<const std::uint8_t> png);
|
||||
|
||||
inline constexpr std::uint8_t FILTER_NONE = 1 << 0;
|
||||
inline constexpr std::uint8_t FILTER_SUB = 1 << 1;
|
||||
inline constexpr std::uint8_t FILTER_UP = 1 << 2;
|
||||
inline constexpr std::uint8_t FILTER_AVERAGE = 1 << 3;
|
||||
inline constexpr std::uint8_t FILTER_PAETH = 1 << 4;
|
||||
inline constexpr std::uint8_t FILTER_ALL = FILTER_NONE | FILTER_SUB | FILTER_UP | FILTER_AVERAGE | FILTER_PAETH;
|
||||
|
||||
struct EncodeOptions {
|
||||
int compressionLevel = 8;
|
||||
std::uint8_t filters = FILTER_ALL;
|
||||
};
|
||||
|
||||
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
|
||||
std::uint32_t channels, EncodeOptions options = {});
|
||||
|
||||
} // namespace Decoder::Png
|
||||
|
||||
#endif // DECODER_PNG_HPP
|
||||
@@ -1,214 +0,0 @@
|
||||
#include "Decoder/Png.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <climits>
|
||||
#include <cstddef>
|
||||
#include <cstdlib>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
|
||||
#define STB_IMAGE_WRITE_STATIC
|
||||
#define STB_IMAGE_WRITE_IMPLEMENTATION
|
||||
#define STBI_WRITE_NO_STDIO
|
||||
#include "stb_image_write.h"
|
||||
|
||||
#define STB_IMAGE_STATIC
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STBI_ONLY_PNG
|
||||
#define STBI_NO_STDIO
|
||||
#include "stb_image.h"
|
||||
|
||||
namespace Decoder::Png {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr std::array<std::uint8_t, 8> SIGNATURE = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
|
||||
constexpr std::size_t CHUNK_OVERHEAD = 12;
|
||||
constexpr std::size_t IHDR_SIZE = 13;
|
||||
constexpr std::uint32_t MAX_DIMENSION = 0x7FFFFFFF;
|
||||
constexpr std::uint8_t FILTER_TYPE_COUNT = 5;
|
||||
constexpr std::array<std::uint8_t, 5> COLOR_TYPE_BY_CHANNELS = {0, 0, 4, 2, 6};
|
||||
constexpr std::array<std::uint32_t, 256> CRC_TABLE = [] {
|
||||
std::array<std::uint32_t, 256> table{};
|
||||
for (std::uint32_t index = 0; index < table.size(); ++index) {
|
||||
std::uint32_t value = index;
|
||||
for (int bit = 0; bit < 8; ++bit) value = (value >> 1) ^ ((value & 1) != 0 ? 0xEDB88320u : 0u);
|
||||
table[index] = value;
|
||||
}
|
||||
return table;
|
||||
}();
|
||||
|
||||
std::uint32_t readBigEndian32(const std::uint8_t* bytes) {
|
||||
return static_cast<std::uint32_t>(bytes[0]) << 24 | static_cast<std::uint32_t>(bytes[1]) << 16
|
||||
| static_cast<std::uint32_t>(bytes[2]) << 8 | static_cast<std::uint32_t>(bytes[3]);
|
||||
}
|
||||
|
||||
bool isChunkType(const std::uint8_t* bytes, const char* type) {
|
||||
return std::equal(bytes, bytes + 4, type);
|
||||
}
|
||||
|
||||
bool isValidFormat(std::uint8_t bitDepth, std::uint8_t colorType) {
|
||||
switch (colorType) {
|
||||
case 0:
|
||||
return bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8 || bitDepth == 16;
|
||||
case 3:
|
||||
return bitDepth == 1 || bitDepth == 2 || bitDepth == 4 || bitDepth == 8;
|
||||
case 2:
|
||||
case 4:
|
||||
case 6:
|
||||
return bitDepth == 8 || bitDepth == 16;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void appendBigEndian32(std::vector<std::uint8_t>& output, std::uint32_t value) {
|
||||
for (int shift = 24; shift >= 0; shift -= 8) output.push_back(static_cast<std::uint8_t>(value >> shift));
|
||||
}
|
||||
|
||||
void appendChunk(std::vector<std::uint8_t>& output, const char* type, std::span<const std::uint8_t> data) {
|
||||
appendBigEndian32(output, static_cast<std::uint32_t>(data.size()));
|
||||
const std::size_t checkedFrom = output.size();
|
||||
output.insert(output.end(), type, type + 4);
|
||||
output.insert(output.end(), data.begin(), data.end());
|
||||
std::uint32_t crc = 0xFFFFFFFFu;
|
||||
for (std::size_t i = checkedFrom; i < output.size(); ++i) crc = (crc >> 8) ^ CRC_TABLE[(crc ^ output[i]) & 0xFF];
|
||||
appendBigEndian32(output, ~crc);
|
||||
}
|
||||
|
||||
int paethPredictor(int left, int up, int upLeft) {
|
||||
const int estimate = left + up - upLeft;
|
||||
const int leftDistance = std::abs(estimate - left);
|
||||
const int upDistance = std::abs(estimate - up);
|
||||
const int upLeftDistance = std::abs(estimate - upLeft);
|
||||
if (leftDistance <= upDistance && leftDistance <= upLeftDistance) return left;
|
||||
return upDistance <= upLeftDistance ? up : upLeft;
|
||||
}
|
||||
|
||||
std::uint64_t filterRow(const std::uint8_t* row, const std::uint8_t* previousRow, std::size_t rowSize, std::size_t pixelSize,
|
||||
std::uint8_t filterType, std::uint8_t* filtered) {
|
||||
std::uint64_t cost = 0;
|
||||
for (std::size_t i = 0; i < rowSize; ++i) {
|
||||
const int left = i >= pixelSize ? row[i - pixelSize] : 0;
|
||||
const int up = previousRow ? previousRow[i] : 0;
|
||||
const int upLeft = previousRow && i >= pixelSize ? previousRow[i - pixelSize] : 0;
|
||||
int prediction = 0;
|
||||
switch (filterType) {
|
||||
case 1:
|
||||
prediction = left;
|
||||
break;
|
||||
case 2:
|
||||
prediction = up;
|
||||
break;
|
||||
case 3:
|
||||
prediction = (left + up) >> 1;
|
||||
break;
|
||||
case 4:
|
||||
prediction = paethPredictor(left, up, upLeft);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
filtered[i] = static_cast<std::uint8_t>(row[i] - prediction);
|
||||
cost += filtered[i] < 0x80 ? filtered[i] : 0x100u - filtered[i];
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<Header> ParseHeader(std::span<const std::uint8_t> png) {
|
||||
const std::size_t firstChunk = SIGNATURE.size();
|
||||
if (png.size() < firstChunk + CHUNK_OVERHEAD + IHDR_SIZE) return std::nullopt;
|
||||
if (!std::equal(SIGNATURE.begin(), SIGNATURE.end(), png.begin())) return std::nullopt;
|
||||
if (readBigEndian32(&png[firstChunk]) != IHDR_SIZE || !isChunkType(&png[firstChunk + 4], "IHDR")) return std::nullopt;
|
||||
|
||||
const std::uint8_t* ihdr = &png[firstChunk + 8];
|
||||
Header header{};
|
||||
header.width = readBigEndian32(ihdr);
|
||||
header.height = readBigEndian32(ihdr + 4);
|
||||
header.bitDepth = ihdr[8];
|
||||
header.colorType = static_cast<ColorType>(ihdr[9]);
|
||||
header.interlaced = ihdr[12] == 1;
|
||||
if (header.width == 0 || header.height == 0 || header.width > MAX_DIMENSION || header.height > MAX_DIMENSION) return std::nullopt;
|
||||
if (!isValidFormat(ihdr[8], ihdr[9]) || ihdr[10] != 0 || ihdr[11] != 0 || ihdr[12] > 1) return std::nullopt;
|
||||
|
||||
std::size_t offset = firstChunk + CHUNK_OVERHEAD + IHDR_SIZE;
|
||||
while (png.size() - offset >= CHUNK_OVERHEAD) {
|
||||
const std::uint32_t length = readBigEndian32(&png[offset]);
|
||||
const std::uint8_t* type = &png[offset + 4];
|
||||
if (length > png.size() - offset - CHUNK_OVERHEAD) break;
|
||||
if (isChunkType(type, "tRNS")) header.hasTransparency = true;
|
||||
if (isChunkType(type, "tRNS") || isChunkType(type, "IDAT") || isChunkType(type, "IEND")) break;
|
||||
offset += CHUNK_OVERHEAD + length;
|
||||
}
|
||||
return header;
|
||||
}
|
||||
|
||||
std::optional<Image> Decode(std::span<const std::uint8_t> png) {
|
||||
if (png.empty() || png.size() > INT_MAX) return std::nullopt;
|
||||
|
||||
int width = 0;
|
||||
int height = 0;
|
||||
int channels = 0;
|
||||
stbi_uc* decoded = stbi_load_from_memory(png.data(), static_cast<int>(png.size()), &width, &height, &channels, 4);
|
||||
if (!decoded) return std::nullopt;
|
||||
|
||||
Image image{static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height), {}};
|
||||
image.pixels.assign(decoded, decoded + static_cast<std::size_t>(image.width) * image.height * 4);
|
||||
stbi_image_free(decoded);
|
||||
return image;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
|
||||
std::uint32_t channels, EncodeOptions options) {
|
||||
if (channels < 1 || channels > 4) throw std::invalid_argument("Png::Encode: channels must be 1-4");
|
||||
if (options.compressionLevel < 0 || options.compressionLevel > 9 || options.filters == 0 || (options.filters & ~FILTER_ALL) != 0) {
|
||||
throw std::invalid_argument("Png::Encode: unsupported options");
|
||||
}
|
||||
const std::uint64_t rowSize = static_cast<std::uint64_t>(width) * channels;
|
||||
if (width == 0 || height == 0 || rowSize > INT_MAX || (rowSize + 1) * height > INT_MAX) {
|
||||
throw std::invalid_argument("Png::Encode: unsupported image size");
|
||||
}
|
||||
if (pixels.size() < rowSize * height) {
|
||||
throw std::invalid_argument("Png::Encode: pixel buffer is too small");
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> filtered((rowSize + 1) * height);
|
||||
std::vector<std::uint8_t> candidate(rowSize);
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
const std::uint8_t* row = pixels.data() + rowSize * y;
|
||||
const std::uint8_t* previousRow = y == 0 ? nullptr : row - rowSize;
|
||||
std::uint8_t* filteredRow = filtered.data() + (rowSize + 1) * y;
|
||||
std::uint64_t bestCost = UINT64_MAX;
|
||||
for (std::uint8_t filterType = 0; filterType < FILTER_TYPE_COUNT; ++filterType) {
|
||||
if ((options.filters & (1u << filterType)) == 0) continue;
|
||||
const std::uint64_t cost =filterRow(row, previousRow, rowSize, channels, filterType, candidate.data());
|
||||
if (cost >= bestCost) continue;
|
||||
bestCost = cost;
|
||||
filteredRow[0] = filterType;
|
||||
std::copy(candidate.begin(), candidate.end(), filteredRow + 1);
|
||||
}
|
||||
}
|
||||
|
||||
int compressedSize = 0;
|
||||
const std::unique_ptr<unsigned char, void (*)(unsigned char*)> compressed(
|
||||
stbi_zlib_compress(filtered.data(), static_cast<int>(filtered.size()), &compressedSize, options.compressionLevel),
|
||||
[](unsigned char* memory) { STBIW_FREE(memory); });
|
||||
if (!compressed) throw std::runtime_error("Png::Encode: encoding failed");
|
||||
|
||||
std::vector<std::uint8_t> header;
|
||||
appendBigEndian32(header, width);
|
||||
appendBigEndian32(header, height);
|
||||
header.insert(header.end(), {8, COLOR_TYPE_BY_CHANNELS[channels], 0, 0, 0});
|
||||
|
||||
std::vector<std::uint8_t> output(SIGNATURE.begin(), SIGNATURE.end());
|
||||
output.reserve(SIGNATURE.size() + 3 * CHUNK_OVERHEAD + IHDR_SIZE + static_cast<std::size_t>(compressedSize));
|
||||
appendChunk(output, "IHDR", header);
|
||||
appendChunk(output, "IDAT", std::span<const std::uint8_t>(compressed.get(), static_cast<std::size_t>(compressedSize)));
|
||||
appendChunk(output, "IEND", {});
|
||||
return output;
|
||||
}
|
||||
|
||||
} // namespace Decoder::Png
|
||||
@@ -1,224 +0,0 @@
|
||||
#include "Decoder/Png.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
#define STB_IMAGE_STATIC
|
||||
#define STB_IMAGE_IMPLEMENTATION
|
||||
#define STBI_ONLY_PNG
|
||||
#define STBI_NO_STDIO
|
||||
#include "stb_image.h"
|
||||
|
||||
static void Require(bool value) { if (!value) std::abort(); }
|
||||
|
||||
template<typename TFunction>
|
||||
static bool ThrowsInvalidArgument(TFunction function) {
|
||||
try {
|
||||
function();
|
||||
} catch (const std::invalid_argument&) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static const std::uint8_t PALETTE_TRNS[] = {
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
|
||||
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x02, 0x03, 0x00, 0x00, 0x00, 0x0F, 0xD8, 0xE5,
|
||||
0xB7, 0x00, 0x00, 0x00, 0x0C, 0x50, 0x4C, 0x54, 0x45, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00,
|
||||
0x00, 0xFF, 0xFF, 0xFF, 0x00, 0xD6, 0x02, 0x8F, 0x7B, 0x00, 0x00, 0x00, 0x04, 0x74, 0x52, 0x4E,
|
||||
0x53, 0xFF, 0x00, 0xFF, 0x80, 0x13, 0x0A, 0x1E, 0x39, 0x00, 0x00, 0x00, 0x0C, 0x49, 0x44, 0x41,
|
||||
0x54, 0x78, 0x9C, 0x63, 0x10, 0x60, 0xD8, 0x00, 0x00, 0x00, 0xE4, 0x00, 0xC1, 0x27, 0xA8, 0xE8,
|
||||
0x57, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
|
||||
};
|
||||
|
||||
static const std::uint8_t GRAY16[] = {
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
|
||||
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x81, 0xD9, 0xFC,
|
||||
0x15, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x10, 0x32, 0x59, 0x7D,
|
||||
0x16, 0x00, 0x03, 0x0C, 0x01, 0xBF, 0x6E, 0xB9, 0xC6, 0x5D, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
|
||||
0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,
|
||||
};
|
||||
|
||||
static const std::uint8_t GRAY1[] = {
|
||||
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
|
||||
0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0xCB, 0x7B, 0xD2,
|
||||
0xEE, 0x00, 0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x88, 0x04, 0x00, 0x00,
|
||||
0x5B, 0x00, 0x5A, 0x7C, 0xA5, 0x93, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE,
|
||||
0x42, 0x60, 0x82,
|
||||
};
|
||||
|
||||
static void AppendBigEndian32(std::vector<std::uint8_t>& bytes, std::uint32_t value) {
|
||||
for (int shift = 24; shift >= 0; shift -= 8) bytes.push_back(static_cast<std::uint8_t>(value >> shift));
|
||||
}
|
||||
|
||||
static std::vector<std::uint8_t> HeaderOnly(std::uint32_t width, std::uint32_t height, std::uint8_t bitDepth,
|
||||
std::uint8_t colorType, std::uint8_t interlace) {
|
||||
std::vector<std::uint8_t> bytes{0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 13, 'I', 'H', 'D', 'R'};
|
||||
AppendBigEndian32(bytes, width);
|
||||
AppendBigEndian32(bytes, height);
|
||||
bytes.insert(bytes.end(), {bitDepth, colorType, 0, 0, interlace, 0, 0, 0, 0});
|
||||
bytes.insert(bytes.end(), {0, 0, 0, 0, 'I', 'E', 'N', 'D', 0, 0, 0, 0});
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static void RequireRoundTrip(std::uint32_t channels, Decoder::Png::ColorType colorType) {
|
||||
constexpr std::uint32_t width = 20;
|
||||
constexpr std::uint32_t height = 10;
|
||||
std::vector<std::uint8_t> pixels(width * height * channels);
|
||||
for (std::size_t i = 0; i < pixels.size(); ++i) pixels[i] = static_cast<std::uint8_t>(i * 37 + 11);
|
||||
|
||||
const std::vector<std::uint8_t> png = Decoder::Png::Encode(pixels, width, height, channels);
|
||||
const auto header = Decoder::Png::ParseHeader(png);
|
||||
Require(header.has_value());
|
||||
Require(header->width == width && header->height == height && header->bitDepth == 8);
|
||||
Require(header->colorType == colorType && !header->interlaced && !header->hasTransparency);
|
||||
|
||||
const auto image = Decoder::Png::Decode(png);
|
||||
Require(image.has_value());
|
||||
Require(image->width == width && image->height == height && image->pixels.size() == width * height * 4);
|
||||
for (std::size_t pixel = 0; pixel < width * height; ++pixel) {
|
||||
const std::uint8_t* in = &pixels[pixel * channels];
|
||||
const std::uint8_t* out = &image->pixels[pixel * 4];
|
||||
const bool gray = channels <= 2;
|
||||
Require(out[0] == in[0]);
|
||||
Require(out[1] == (gray ? in[0] : in[1]));
|
||||
Require(out[2] == (gray ? in[0] : in[2]));
|
||||
const bool hasAlpha = channels == 2 || channels == 4;
|
||||
Require(out[3] == (hasAlpha ? in[channels - 1] : 255));
|
||||
}
|
||||
}
|
||||
|
||||
static std::vector<std::uint8_t> RowFilters(const std::vector<std::uint8_t>& png, std::uint32_t height, std::uint32_t rowSize) {
|
||||
std::vector<std::uint8_t> stream;
|
||||
for (std::size_t offset = 8; offset + 12 <= png.size();) {
|
||||
const std::size_t length = static_cast<std::size_t>(png[offset]) << 24 | static_cast<std::size_t>(png[offset + 1]) << 16
|
||||
| static_cast<std::size_t>(png[offset + 2]) << 8 | png[offset + 3];
|
||||
Require(length <= png.size() - offset - 12);
|
||||
const std::uint8_t* data = png.data() + offset + 8;
|
||||
if (std::equal(data - 4, data, "IDAT")) stream.insert(stream.end(), data, data + length);
|
||||
offset += 12 + length;
|
||||
}
|
||||
|
||||
int size = 0;
|
||||
char* rows = stbi_zlib_decode_malloc(reinterpret_cast<const char*>(stream.data()), static_cast<int>(stream.size()), &size);
|
||||
Require(rows && static_cast<std::size_t>(size) == static_cast<std::size_t>(height) * (rowSize + 1));
|
||||
std::vector<std::uint8_t> filters;
|
||||
for (std::uint32_t y = 0; y < height; ++y) filters.push_back(static_cast<std::uint8_t>(rows[y * (rowSize + 1)]));
|
||||
stbi_image_free(rows);
|
||||
return filters;
|
||||
}
|
||||
|
||||
static void RequireFilterSets(std::uint32_t channels) {
|
||||
constexpr std::uint32_t width = 16;
|
||||
constexpr std::uint32_t height = 6;
|
||||
const std::uint32_t rowSize = width * channels;
|
||||
std::vector<std::uint8_t> pixels(rowSize * height);
|
||||
std::uint32_t noise = 12345;
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
for (std::uint32_t i = 0; i < rowSize; ++i) {
|
||||
noise = noise * 1103515245u + 12345u;
|
||||
pixels[y * rowSize + i] = y == 2 ? static_cast<std::uint8_t>(noise >> 16) : static_cast<std::uint8_t>(i / channels * 8);
|
||||
}
|
||||
}
|
||||
std::copy_n(pixels.begin() + 2 * rowSize, rowSize, pixels.begin() + 3 * rowSize);
|
||||
|
||||
for (std::uint8_t filters = 1; filters <= Decoder::Png::FILTER_ALL; ++filters) {
|
||||
const std::vector<std::uint8_t> png = Decoder::Png::Encode(pixels, width, height, channels, {6, filters});
|
||||
for (const std::uint8_t filter : RowFilters(png, height, rowSize)) Require(filter < 5 && (filters >> filter & 1) != 0);
|
||||
|
||||
const auto image = Decoder::Png::Decode(png);
|
||||
Require(image.has_value() && image->width == width && image->height == height);
|
||||
for (std::size_t pixel = 0; pixel < width * height; ++pixel) {
|
||||
Require(image->pixels[pixel * 4] == pixels[pixel * channels]);
|
||||
Require(image->pixels[pixel * 4 + 3] == (channels % 2 == 0 ? pixels[pixel * channels + channels - 1] : 255));
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<std::uint8_t> subOrUp = RowFilters(
|
||||
Decoder::Png::Encode(pixels, width, height, channels, {6, Decoder::Png::FILTER_SUB | Decoder::Png::FILTER_UP}), height, rowSize);
|
||||
Require(subOrUp[0] == 1 && subOrUp[1] == 2 && subOrUp[3] == 2 && subOrUp[4] == 1 && subOrUp[5] == 2);
|
||||
}
|
||||
|
||||
int main() {
|
||||
RequireRoundTrip(1, Decoder::Png::ColorType::Grayscale);
|
||||
RequireRoundTrip(2, Decoder::Png::ColorType::GrayscaleAlpha);
|
||||
RequireRoundTrip(3, Decoder::Png::ColorType::Rgb);
|
||||
RequireRoundTrip(4, Decoder::Png::ColorType::Rgba);
|
||||
for (const std::uint32_t channels : {1, 2, 3, 4}) RequireFilterSets(channels);
|
||||
|
||||
const auto paletteHeader = Decoder::Png::ParseHeader(PALETTE_TRNS);
|
||||
Require(paletteHeader.has_value());
|
||||
Require(paletteHeader->width == 2 && paletteHeader->height == 2 && paletteHeader->bitDepth == 2);
|
||||
Require(paletteHeader->colorType == Decoder::Png::ColorType::Palette && paletteHeader->hasTransparency);
|
||||
for (const std::size_t size : {std::size_t{69}, std::size_t{71}}) {
|
||||
const auto truncated = Decoder::Png::ParseHeader(std::span<const std::uint8_t>(PALETTE_TRNS, size));
|
||||
Require(truncated.has_value() && !truncated->hasTransparency);
|
||||
}
|
||||
const auto completeTransparency = Decoder::Png::ParseHeader(std::span<const std::uint8_t>(PALETTE_TRNS, 73));
|
||||
Require(completeTransparency.has_value() && completeTransparency->hasTransparency);
|
||||
const auto palette = Decoder::Png::Decode(PALETTE_TRNS);
|
||||
Require(palette.has_value());
|
||||
Require(palette->pixels == std::vector<std::uint8_t>({255, 0, 0, 255, 0, 255, 0, 0, 0, 0, 255, 255, 255, 255, 0, 128}));
|
||||
|
||||
const auto gray16Header = Decoder::Png::ParseHeader(GRAY16);
|
||||
Require(gray16Header.has_value() && gray16Header->bitDepth == 16 && gray16Header->colorType == Decoder::Png::ColorType::Grayscale);
|
||||
const auto gray16 = Decoder::Png::Decode(GRAY16);
|
||||
Require(gray16.has_value());
|
||||
Require(gray16->pixels == std::vector<std::uint8_t>({0x12, 0x12, 0x12, 255, 0xAB, 0xAB, 0xAB, 255}));
|
||||
|
||||
const auto gray1Header = Decoder::Png::ParseHeader(GRAY1);
|
||||
Require(gray1Header.has_value() && gray1Header->bitDepth == 1 && gray1Header->width == 8);
|
||||
const auto gray1 = Decoder::Png::Decode(GRAY1);
|
||||
Require(gray1.has_value());
|
||||
const std::uint8_t levels[8] = {0, 255, 0, 255, 255, 0, 0, 255};
|
||||
for (int i = 0; i < 8; ++i) Require(gray1->pixels[i * 4] == levels[i] && gray1->pixels[i * 4 + 3] == 255);
|
||||
|
||||
const auto interlaced = Decoder::Png::ParseHeader(HeaderOnly(3, 4, 8, 6, 1));
|
||||
Require(interlaced.has_value() && interlaced->interlaced && !interlaced->hasTransparency);
|
||||
Require(!Decoder::Png::ParseHeader(HeaderOnly(0, 4, 8, 6, 0)).has_value());
|
||||
Require(!Decoder::Png::ParseHeader(HeaderOnly(3, 4, 8, 5, 0)).has_value());
|
||||
Require(!Decoder::Png::ParseHeader(HeaderOnly(3, 4, 16, 3, 0)).has_value());
|
||||
Require(!Decoder::Png::ParseHeader(HeaderOnly(3, 4, 8, 6, 2)).has_value());
|
||||
std::vector<std::uint8_t> badSignature = HeaderOnly(3, 4, 8, 6, 0);
|
||||
badSignature[1] = 'X';
|
||||
Require(!Decoder::Png::ParseHeader(badSignature).has_value());
|
||||
std::vector<std::uint8_t> hugeChunk = HeaderOnly(3, 4, 8, 6, 0);
|
||||
hugeChunk[33] = 0xFF;
|
||||
hugeChunk[37] = 't';
|
||||
hugeChunk[38] = 'E';
|
||||
hugeChunk[39] = 'X';
|
||||
hugeChunk[40] = 't';
|
||||
const auto hugeChunkHeader = Decoder::Png::ParseHeader(hugeChunk);
|
||||
Require(hugeChunkHeader.has_value() && !hugeChunkHeader->hasTransparency);
|
||||
Require(!Decoder::Png::ParseHeader(std::span<const std::uint8_t>(PALETTE_TRNS, 32)).has_value());
|
||||
|
||||
Require(!Decoder::Png::Decode({}).has_value());
|
||||
Require(!Decoder::Png::Decode(std::span<const std::uint8_t>(PALETTE_TRNS, 60)).has_value());
|
||||
const std::vector<std::uint8_t> garbage{1, 2, 3, 4, 5, 6, 7, 8};
|
||||
Require(!Decoder::Png::Decode(garbage).has_value());
|
||||
|
||||
const std::vector<std::uint8_t> pixels(16 * 4);
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 0); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 5); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 0, 4, 4); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 5, 4); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {10, Decoder::Png::FILTER_ALL}); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {8, 0}); }));
|
||||
Require(ThrowsInvalidArgument([&] { Decoder::Png::Encode(pixels, 4, 4, 4, {8, Decoder::Png::FILTER_ALL + 1}); }));
|
||||
|
||||
std::vector<std::uint8_t> gradient(64 * 64 * 3);
|
||||
for (std::size_t i = 0; i < gradient.size(); ++i) gradient[i] = static_cast<std::uint8_t>(i / 3 % 64 * 4);
|
||||
const auto stored = Decoder::Png::Encode(gradient, 64, 64, 3, {0, Decoder::Png::FILTER_NONE});
|
||||
const auto compressed = Decoder::Png::Encode(gradient, 64, 64, 3, {9, Decoder::Png::FILTER_SUB});
|
||||
Require(compressed.size() < stored.size());
|
||||
for (const auto& png : {stored, compressed}) {
|
||||
const auto image = Decoder::Png::Decode(png);
|
||||
Require(image.has_value() && image->width == 64 && image->height == 64);
|
||||
for (std::size_t pixel = 0; pixel < 64 * 64; ++pixel) Require(image->pixels[pixel * 4] == gradient[pixel * 3]);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,659 +0,0 @@
|
||||
if(NOT WIN32)
|
||||
foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
|
||||
string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
|
||||
endforeach()
|
||||
string(STRIP "${CMAKE_EXE_LINKER_FLAGS}" CMAKE_EXE_LINKER_FLAGS)
|
||||
endif()
|
||||
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
include(CheckPIESupported)
|
||||
check_pie_supported(LANGUAGES C CXX)
|
||||
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
|
||||
endif()
|
||||
|
||||
if(APPLE)
|
||||
set(ANYPS5_PRX_RPATH "@loader_path")
|
||||
else()
|
||||
set(ANYPS5_PRX_RPATH "$ORIGIN")
|
||||
endif()
|
||||
|
||||
add_executable(nid_patcher
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/Sha1.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/NidCompute.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/NidResolver.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/ExportExclusions.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/ElfNidPatcher.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/PeNidPatcher.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/MachONidPatcher.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/BinaryPatcherFactory.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/src/main.cpp
|
||||
)
|
||||
|
||||
target_include_directories(nid_patcher PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/nid/include)
|
||||
target_compile_features(nid_patcher PRIVATE cxx_std_20)
|
||||
|
||||
if(MINGW)
|
||||
target_link_options(nid_patcher PRIVATE -municode -static -static-libgcc -static-libstdc++)
|
||||
include(CheckCXXSourceCompiles)
|
||||
set(CMAKE_REQUIRED_FLAGS -fno-asynchronous-unwind-tables)
|
||||
check_cxx_source_compiles("#ifdef __USING_SJLJ_EXCEPTIONS__\n#error\n#endif\nint main() { return 0; }" ANYPS5_MINGW_DWARF_EXCEPTIONS)
|
||||
unset(CMAKE_REQUIRED_FLAGS)
|
||||
if(NOT ANYPS5_MINGW_DWARF_EXCEPTIONS)
|
||||
message(FATAL_ERROR "${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION} selects SjLj exceptions with -fno-asynchronous-unwind-tables; the libraries need DWARF unwinding. Use the MinGW-w64 toolchain listed in docs/dev/BUILD.md.")
|
||||
endif()
|
||||
add_compile_options(-fno-asynchronous-unwind-tables)
|
||||
endif()
|
||||
|
||||
function(configure_windows_unwind target)
|
||||
if(MINGW)
|
||||
if(NOT EXISTS "${CMAKE_OBJCOPY}")
|
||||
message(FATAL_ERROR "Windows DWARF unwinding requires objcopy")
|
||||
endif()
|
||||
add_custom_command(TARGET ${target} POST_BUILD
|
||||
COMMAND "${CMAKE_OBJCOPY}" --rename-section .eh_frame=.ehfram "$<TARGET_FILE:${target}>"
|
||||
VERBATIM
|
||||
)
|
||||
endif()
|
||||
endfunction()
|
||||
|
||||
if(MINGW)
|
||||
foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
|
||||
string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
|
||||
endforeach()
|
||||
|
||||
if(NOT EXISTS "${CMAKE_RANLIB}")
|
||||
message(FATAL_ERROR "Stable import libraries require ranlib")
|
||||
endif()
|
||||
list(LENGTH CMAKE_CXX_CREATE_SHARED_LIBRARY linkCommandCount)
|
||||
string(FIND "${CMAKE_CXX_CREATE_SHARED_LIBRARY}" "-Wl,--out-implib,<TARGET_IMPLIB> " implibOption)
|
||||
if(NOT linkCommandCount EQUAL 1 OR implibOption EQUAL -1)
|
||||
message(FATAL_ERROR "Expected one shared library link command that writes -Wl,--out-implib,<TARGET_IMPLIB>: ${CMAKE_CXX_CREATE_SHARED_LIBRARY}")
|
||||
endif()
|
||||
string(REPLACE "-Wl,--out-implib,<TARGET_IMPLIB> " "-Wl,--out-implib,<TARGET_IMPLIB>.new " linkCommand "${CMAKE_CXX_CREATE_SHARED_LIBRARY}")
|
||||
set(CMAKE_CXX_CREATE_SHARED_LIBRARY
|
||||
"\"${CMAKE_COMMAND}\" -E env SOURCE_DATE_EPOCH=0 ${linkCommand}"
|
||||
"\"${CMAKE_RANLIB}\" -D <TARGET_IMPLIB>.new"
|
||||
"\"${CMAKE_COMMAND}\" -E copy_if_different <TARGET_IMPLIB>.new <TARGET_IMPLIB>"
|
||||
)
|
||||
endif()
|
||||
|
||||
set(LIBC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/prx/libc)
|
||||
add_library(libc SHARED EXCLUDE_FROM_ALL)
|
||||
set(LIBS_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
add_subdirectory(${LIBC_DIR} ${CMAKE_CURRENT_BINARY_DIR}/prx/libc)
|
||||
target_include_directories(libc PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
configure_windows_unwind(libc)
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(libc PRIVATE LINKER:-z,now)
|
||||
target_link_options(libc INTERFACE LINKER:--no-as-needed)
|
||||
endif()
|
||||
|
||||
set(UNPATCHED_DIR ${CMAKE_CURRENT_BINARY_DIR}/libs/unpatched)
|
||||
set(PATCHED_DIR ${CMAKE_CURRENT_BINARY_DIR}/libs)
|
||||
set(IMPLIB_DIR ${PATCHED_DIR}/implib)
|
||||
|
||||
set_target_properties(libc PROPERTIES
|
||||
PREFIX ""
|
||||
SUFFIX .prx
|
||||
RUNTIME_OUTPUT_DIRECTORY ${UNPATCHED_DIR}
|
||||
LIBRARY_OUTPUT_DIRECTORY ${UNPATCHED_DIR}
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${IMPLIB_DIR}
|
||||
BUILD_WITH_INSTALL_RPATH ON
|
||||
INSTALL_RPATH "${ANYPS5_PRX_RPATH}"
|
||||
)
|
||||
|
||||
set(LIBC_UNPATCHED ${UNPATCHED_DIR}/libc.prx)
|
||||
set(LIBC_PATCHED ${PATCHED_DIR}/libc.prx)
|
||||
set(LIBC_EXPORT_LIST ${CMAKE_CURRENT_BINARY_DIR}/libc.exports)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${LIBC_EXPORT_LIST}
|
||||
COMMAND $<TARGET_FILE:nid_patcher> --write-export-list ${LIBC_UNPATCHED} ${LIBC_EXPORT_LIST}
|
||||
DEPENDS nid_patcher libc ${LIBC_UNPATCHED}
|
||||
COMMENT "Listing libc exports"
|
||||
)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${LIBC_PATCHED}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${LIBC_UNPATCHED} ${LIBC_PATCHED}
|
||||
COMMAND $<TARGET_FILE:nid_patcher> libc ${LIBC_PATCHED}
|
||||
DEPENDS nid_patcher libc ${LIBC_UNPATCHED}
|
||||
COMMENT "Patching NIDs for libc"
|
||||
)
|
||||
|
||||
file(GLOB LIBS_DIRS LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/prx/*)
|
||||
list(REMOVE_ITEM LIBS_DIRS ${LIBC_DIR})
|
||||
|
||||
set(PATCHED_OUTPUTS ${LIBC_PATCHED})
|
||||
|
||||
foreach(LIB_DIR ${LIBS_DIRS})
|
||||
if(IS_DIRECTORY ${LIB_DIR})
|
||||
get_filename_component(LIB_NAME ${LIB_DIR} NAME)
|
||||
|
||||
if(EXISTS ${LIB_DIR}/CMakeLists.txt)
|
||||
set(LIBS_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
add_subdirectory(${LIB_DIR} ${CMAKE_CURRENT_BINARY_DIR}/prx/${LIB_NAME})
|
||||
else()
|
||||
add_library(${LIB_NAME} SHARED EXCLUDE_FROM_ALL ${LIB_DIR}/Export.cpp)
|
||||
target_include_directories(${LIB_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
configure_windows_unwind(${LIB_NAME})
|
||||
endif()
|
||||
|
||||
if(LIB_NAME STREQUAL "libkernel")
|
||||
target_link_libraries(${LIB_NAME} PUBLIC libc)
|
||||
else()
|
||||
target_link_libraries(${LIB_NAME} PRIVATE libkernel PUBLIC libc)
|
||||
endif()
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
target_link_options(${LIB_NAME} PRIVATE LINKER:-z,now)
|
||||
endif()
|
||||
if(WIN32 AND LIB_NAME STREQUAL "libSceNet")
|
||||
target_link_libraries(${LIB_NAME} PRIVATE ws2_32)
|
||||
target_compile_definitions(${LIB_NAME} PRIVATE _WIN32_WINNT=0x0602)
|
||||
elseif(WIN32 AND LIB_NAME STREQUAL "libSceNetCtl")
|
||||
target_link_libraries(${LIB_NAME} PRIVATE ws2_32 iphlpapi)
|
||||
target_compile_definitions(${LIB_NAME} PRIVATE _WIN32_WINNT=0x0602)
|
||||
endif()
|
||||
|
||||
set_target_properties(${LIB_NAME} PROPERTIES
|
||||
PREFIX ""
|
||||
SUFFIX .prx
|
||||
RUNTIME_OUTPUT_DIRECTORY ${UNPATCHED_DIR}
|
||||
LIBRARY_OUTPUT_DIRECTORY ${UNPATCHED_DIR}
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${IMPLIB_DIR}
|
||||
BUILD_WITH_INSTALL_RPATH ON
|
||||
INSTALL_RPATH "${ANYPS5_PRX_RPATH}"
|
||||
)
|
||||
|
||||
set(UNPATCHED_FILE ${UNPATCHED_DIR}/${LIB_NAME}.prx)
|
||||
set(PATCHED_FILE ${PATCHED_DIR}/${LIB_NAME}.prx)
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT ${PATCHED_FILE}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy ${UNPATCHED_FILE} ${PATCHED_FILE}
|
||||
COMMAND $<TARGET_FILE:nid_patcher> ${LIB_NAME} --preserve-export-list "${LIBC_EXPORT_LIST}" "${PATCHED_FILE}"
|
||||
DEPENDS nid_patcher ${LIB_NAME} ${UNPATCHED_FILE} ${LIBC_EXPORT_LIST}
|
||||
COMMENT "Patching NIDs for ${LIB_NAME}"
|
||||
)
|
||||
|
||||
list(APPEND PATCHED_OUTPUTS ${PATCHED_FILE})
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
if(APS5_ENABLE_TRACY)
|
||||
set_target_properties(TracyClient PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY ${UNPATCHED_DIR}
|
||||
LIBRARY_OUTPUT_DIRECTORY ${UNPATCHED_DIR}
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${IMPLIB_DIR}
|
||||
)
|
||||
set(TRACY_CLIENT_COPIED ${CMAKE_CURRENT_BINARY_DIR}/TracyClient.copied)
|
||||
add_custom_command(
|
||||
OUTPUT ${TRACY_CLIENT_COPIED}
|
||||
COMMAND ${CMAKE_COMMAND} -E make_directory ${PATCHED_DIR}
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:TracyClient> ${PATCHED_DIR}
|
||||
COMMAND ${CMAKE_COMMAND} -E touch ${TRACY_CLIENT_COPIED}
|
||||
DEPENDS TracyClient
|
||||
COMMENT "Copying the Tracy client next to the patched libraries"
|
||||
)
|
||||
list(APPEND PATCHED_OUTPUTS ${TRACY_CLIENT_COPIED})
|
||||
endif()
|
||||
|
||||
if(TARGET mimalloc)
|
||||
add_executable(pe_import_first ${CMAKE_CURRENT_SOURCE_DIR}/allocator/PeImportFirstMain.cpp ${CMAKE_CURRENT_SOURCE_DIR}/allocator/PeImportFirst.cpp)
|
||||
target_compile_features(pe_import_first PRIVATE cxx_std_20)
|
||||
if(MINGW)
|
||||
target_compile_options(pe_import_first PRIVATE -fasynchronous-unwind-tables)
|
||||
target_link_options(pe_import_first PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_custom_command(
|
||||
OUTPUT ${PATCHED_DIR}/mimalloc.dll
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:mimalloc> ${PATCHED_DIR}/mimalloc.dll
|
||||
COMMAND $<TARGET_FILE:pe_import_first> ${PATCHED_DIR}/mimalloc.dll mimalloc-redirect.dll
|
||||
DEPENDS mimalloc pe_import_first
|
||||
COMMENT "Copying mimalloc.dll beside the libraries, its redirection module imported first"
|
||||
)
|
||||
add_custom_command(
|
||||
OUTPUT ${PATCHED_DIR}/mimalloc-redirect.dll
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE_DIR:mimalloc>/mimalloc-redirect.dll ${PATCHED_DIR}/mimalloc-redirect.dll
|
||||
DEPENDS mimalloc
|
||||
COMMENT "Copying mimalloc-redirect.dll beside the libraries"
|
||||
)
|
||||
list(APPEND PATCHED_OUTPUTS ${PATCHED_DIR}/mimalloc.dll ${PATCHED_DIR}/mimalloc-redirect.dll)
|
||||
endif()
|
||||
|
||||
add_custom_target(libs DEPENDS ${PATCHED_OUTPUTS})
|
||||
|
||||
if(BUILD_TESTING)
|
||||
add_test_executable(guest_posix_scalar_io_tests tests/GuestPosixScalarIo.cpp)
|
||||
target_include_directories(guest_posix_scalar_io_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_posix_scalar_io_tests PRIVATE libkernel libc)
|
||||
configure_windows_unwind(guest_posix_scalar_io_tests)
|
||||
add_test(NAME guest_posix_scalar_io COMMAND guest_posix_scalar_io_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_posix_scalar_io PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
|
||||
endif()
|
||||
add_test_executable(nid_buffer_validation_tests nid/tests/BufferValidation.cpp)
|
||||
target_include_directories(nid_buffer_validation_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/nid/include)
|
||||
target_compile_features(nid_buffer_validation_tests PRIVATE cxx_std_20)
|
||||
if(MINGW)
|
||||
target_compile_options(nid_buffer_validation_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME nid_buffer_validation COMMAND nid_buffer_validation_tests)
|
||||
set_tests_properties(nid_buffer_validation PROPERTIES TIMEOUT 10)
|
||||
|
||||
add_test_executable(pe_import_first_tests allocator/tests/PeImportFirstTests.cpp allocator/PeImportFirst.cpp)
|
||||
target_include_directories(pe_import_first_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_compile_features(pe_import_first_tests PRIVATE cxx_std_20)
|
||||
if(MINGW)
|
||||
target_compile_options(pe_import_first_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME pe_import_first COMMAND pe_import_first_tests)
|
||||
set_tests_properties(pe_import_first PROPERTIES TIMEOUT 10)
|
||||
|
||||
find_package(Python3 QUIET COMPONENTS Interpreter)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME nid_gnu_hash COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_gnu_hash.py $<TARGET_FILE:nid_patcher>)
|
||||
add_test(NAME nid_elf_duplicates COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_elf_duplicates.py $<TARGET_FILE:nid_patcher>)
|
||||
add_test(NAME nid_patcher_macho COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_macho_nids.py $<TARGET_FILE:nid_patcher>)
|
||||
add_test(NAME nid_patcher_native_paths COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_native_paths.py $<TARGET_FILE:nid_patcher>)
|
||||
set_tests_properties(nid_patcher_native_paths PROPERTIES TIMEOUT 20)
|
||||
endif()
|
||||
add_test_executable(patched_libraries_tests tests/PatchedLibraries.cpp)
|
||||
add_dependencies(patched_libraries_tests libs)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME nid_pe_references COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_pe_references.py $<TARGET_FILE:nid_patcher>)
|
||||
endif()
|
||||
if(MINGW)
|
||||
target_compile_options(patched_libraries_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
target_link_options(patched_libraries_tests PRIVATE -static -static-libgcc -static-libstdc++)
|
||||
endif()
|
||||
add_test(NAME patched_libraries COMMAND patched_libraries_tests ${PATCHED_DIR})
|
||||
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
|
||||
add_library(host_libstdcxx_exception_module SHARED tests/HostLibstdcxxExceptionModule.cpp)
|
||||
target_link_libraries(host_libstdcxx_exception_module PRIVATE ${PATCHED_DIR}/libc.prx)
|
||||
add_dependencies(host_libstdcxx_exception_module libs)
|
||||
add_test_executable(host_libstdcxx_exception_tests tests/HostLibstdcxxException.cpp)
|
||||
target_link_libraries(host_libstdcxx_exception_tests PRIVATE host_libstdcxx_exception_module ${PATCHED_DIR}/libc.prx)
|
||||
add_dependencies(host_libstdcxx_exception_tests libs)
|
||||
set_target_properties(host_libstdcxx_exception_module host_libstdcxx_exception_tests PROPERTIES BUILD_RPATH ${PATCHED_DIR})
|
||||
add_test(NAME host_libstdcxx_exception COMMAND host_libstdcxx_exception_tests)
|
||||
set_tests_properties(host_libstdcxx_exception PROPERTIES TIMEOUT 20)
|
||||
endif()
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME nid_elf_layout COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_elf_layout.py $<TARGET_FILE:nid_patcher>)
|
||||
endif()
|
||||
add_test_executable(guest_kernel_sys_tests tests/GuestKernelSys.cpp)
|
||||
target_include_directories(guest_kernel_sys_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_kernel_sys_tests PRIVATE libkernel_sys libkernel libc)
|
||||
configure_windows_unwind(guest_kernel_sys_tests)
|
||||
add_test(NAME guest_kernel_sys COMMAND guest_kernel_sys_tests)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME nid_verneed COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_verneed.py $<TARGET_FILE:nid_patcher>)
|
||||
endif()
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_kernel_sys PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel_sys>")
|
||||
endif()
|
||||
if(APPLE)
|
||||
add_subdirectory(tests/write_watch)
|
||||
add_subdirectory(tests/guest_arena)
|
||||
endif()
|
||||
if(WIN32)
|
||||
add_test_executable(windows_write_watch_tests tests/WindowsWriteWatch.cpp)
|
||||
target_include_directories(windows_write_watch_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_compile_definitions(windows_write_watch_tests PRIVATE _WIN32_WINNT=0x0A00)
|
||||
if(MINGW)
|
||||
target_compile_options(windows_write_watch_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME windows_write_watch COMMAND windows_write_watch_tests)
|
||||
set_tests_properties(windows_write_watch PROPERTIES TIMEOUT 20)
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
add_test_executable(undeliverable_host_exception_tests tests/UndeliverableHostException.cpp)
|
||||
add_dependencies(undeliverable_host_exception_tests libc)
|
||||
add_test(NAME undeliverable_host_exception COMMAND undeliverable_host_exception_tests $<TARGET_FILE:libc>)
|
||||
set_tests_properties(undeliverable_host_exception PROPERTIES
|
||||
PASS_REGULAR_EXPRESSION "C\\+\\+ exception St9bad_alloc raised on thread [0-9]+ cannot be delivered: 0x[0-9a-f]+ undeliverable_host_exception_tests\\.exe\\+0x[0-9a-f]+ has no unwind data")
|
||||
endif()
|
||||
|
||||
add_test_executable(crash_text_tests tests/CrashText.cpp)
|
||||
target_include_directories(crash_text_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
if(MINGW)
|
||||
target_compile_options(crash_text_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME crash_text COMMAND crash_text_tests)
|
||||
|
||||
if(WIN32)
|
||||
add_test_executable(windows_crash_text_tests tests/WindowsCrashText.cpp)
|
||||
add_dependencies(windows_crash_text_tests libc)
|
||||
if(MINGW)
|
||||
target_compile_options(windows_crash_text_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME windows_crash_text COMMAND windows_crash_text_tests $<TARGET_FILE:libc>)
|
||||
set_tests_properties(windows_crash_text PROPERTIES TIMEOUT 20
|
||||
PASS_REGULAR_EXPRESSION "faulting[^~]*FATAL: unhandled exception 0xc0000005[^~]* \\[r12\\] \"allocation failed in the heap\"[\r\n]+ \\[r13\\] u\"LowLevelFatalError \\[File:Unknown\\] \\[Line: 42\\] Out of memory\"[\r\n]+ \\[r14\\] \"PAGE END\"[.][.][.]"
|
||||
FAIL_REGULAR_EXPRESSION "\\[rbx\\] u?\"|did not fault")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_voice_port_attr_tests tests/GuestVoicePortAttr.cpp)
|
||||
target_include_directories(guest_voice_port_attr_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_voice_port_attr_tests PRIVATE libSceVoice libc)
|
||||
configure_windows_unwind(guest_voice_port_attr_tests)
|
||||
add_test(NAME guest_voice_port_attr COMMAND guest_voice_port_attr_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_voice_port_attr PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceVoice>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_move_tests tests/GuestMove.cpp)
|
||||
target_include_directories(guest_move_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_move_tests PRIVATE libSceMove libc)
|
||||
configure_windows_unwind(guest_move_tests)
|
||||
add_test(NAME guest_move COMMAND guest_move_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_move PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceMove>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_offline_imports_tests tests/GuestOfflineImports.cpp)
|
||||
target_include_directories(guest_offline_imports_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_offline_imports_tests PRIVATE libSceHttp libSceNpEntitlementAccess libSceRudp libc)
|
||||
configure_windows_unwind(guest_offline_imports_tests)
|
||||
add_test(NAME guest_offline_imports COMMAND guest_offline_imports_tests)
|
||||
if(Python3_Interpreter_FOUND)
|
||||
add_test(NAME nid_shared_strings COMMAND ${Python3_EXECUTABLE}
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/nid/tests/test_shared_strings.py $<TARGET_FILE:nid_patcher>)
|
||||
endif()
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_offline_imports PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceHttp>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_signin_dialog_tests tests/GuestSigninDialog.cpp)
|
||||
target_include_directories(guest_signin_dialog_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_signin_dialog_tests PRIVATE libSceSigninDialog libc)
|
||||
configure_windows_unwind(guest_signin_dialog_tests)
|
||||
add_test(NAME guest_signin_dialog COMMAND guest_signin_dialog_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_signin_dialog PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSigninDialog>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_usb_storage_dialog_tests tests/GuestUsbStorageDialog.cpp)
|
||||
target_include_directories(guest_usb_storage_dialog_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_usb_storage_dialog_tests PRIVATE libSceUsbStorageDialog libc)
|
||||
configure_windows_unwind(guest_usb_storage_dialog_tests)
|
||||
add_test(NAME guest_usb_storage_dialog COMMAND guest_usb_storage_dialog_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_usb_storage_dialog PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceUsbStorageDialog>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_game_live_streaming_tests tests/GuestGameLiveStreaming.cpp)
|
||||
target_include_directories(guest_game_live_streaming_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_game_live_streaming_tests PRIVATE libSceGameLiveStreaming libc)
|
||||
configure_windows_unwind(guest_game_live_streaming_tests)
|
||||
add_test(NAME guest_game_live_streaming COMMAND guest_game_live_streaming_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_game_live_streaming PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceGameLiveStreaming>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_netctl_ap_tests tests/GuestNetCtlAp.cpp)
|
||||
target_include_directories(guest_netctl_ap_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_netctl_ap_tests PRIVATE libSceNetCtlAp libc)
|
||||
configure_windows_unwind(guest_netctl_ap_tests)
|
||||
add_test(NAME guest_netctl_ap COMMAND guest_netctl_ap_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_netctl_ap PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNetCtlAp>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_netctl_ap_dialog_tests tests/GuestNetCtlApDialog.cpp)
|
||||
target_include_directories(guest_netctl_ap_dialog_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_netctl_ap_dialog_tests PRIVATE libSceNetCtlApDialog libc)
|
||||
configure_windows_unwind(guest_netctl_ap_dialog_tests)
|
||||
add_test(NAME guest_netctl_ap_dialog COMMAND guest_netctl_ap_dialog_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_netctl_ap_dialog PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNetCtlApDialog>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_np_auth_tests tests/GuestNpAuth.cpp)
|
||||
target_include_directories(guest_np_auth_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_np_auth_tests PRIVATE libSceNpAuth libc)
|
||||
configure_windows_unwind(guest_np_auth_tests)
|
||||
add_test(NAME guest_np_auth COMMAND guest_np_auth_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_np_auth PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpAuth>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_rudp_status_tests tests/GuestRudpStatus.cpp)
|
||||
target_include_directories(guest_rudp_status_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_rudp_status_tests PRIVATE libSceRudp libc)
|
||||
configure_windows_unwind(guest_rudp_status_tests)
|
||||
add_test(NAME guest_rudp_status COMMAND guest_rudp_status_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_rudp_status PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceRudp>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_rudp_context_queries_tests tests/GuestRudpContextQueries.cpp)
|
||||
target_include_directories(guest_rudp_context_queries_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_rudp_context_queries_tests PRIVATE libSceRudp libc)
|
||||
configure_windows_unwind(guest_rudp_context_queries_tests)
|
||||
add_test(NAME guest_rudp_context_queries COMMAND guest_rudp_context_queries_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_rudp_context_queries PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceRudp>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_rudp_pump_tests tests/GuestRudpPump.cpp)
|
||||
target_include_directories(guest_rudp_pump_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_rudp_pump_tests PRIVATE libSceRudp libc)
|
||||
configure_windows_unwind(guest_rudp_pump_tests)
|
||||
add_test(NAME guest_rudp_pump COMMAND guest_rudp_pump_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_rudp_pump PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceRudp>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_rudp_context_lifecycle_tests tests/GuestRudpContextLifecycle.cpp)
|
||||
target_include_directories(guest_rudp_context_lifecycle_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_rudp_context_lifecycle_tests PRIVATE libSceRudp libc)
|
||||
configure_windows_unwind(guest_rudp_context_lifecycle_tests)
|
||||
add_test(NAME guest_rudp_context_lifecycle COMMAND guest_rudp_context_lifecycle_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_rudp_context_lifecycle PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceRudp>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_memory_pool_stats_tests tests/GuestMemoryPoolStats.cpp)
|
||||
target_include_directories(guest_memory_pool_stats_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_memory_pool_stats_tests PRIVATE libSceSsl libSceHttp2 libSceNet libkernel libc)
|
||||
configure_windows_unwind(guest_memory_pool_stats_tests)
|
||||
add_test(NAME guest_memory_pool_stats COMMAND guest_memory_pool_stats_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_memory_pool_stats PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSsl>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_system_gesture_tests tests/GuestSystemGesture.cpp)
|
||||
target_include_directories(guest_system_gesture_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_system_gesture_tests PRIVATE libSceSystemGesture libc)
|
||||
configure_windows_unwind(guest_system_gesture_tests)
|
||||
add_test(NAME guest_system_gesture COMMAND guest_system_gesture_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_system_gesture PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSystemGesture>")
|
||||
endif()
|
||||
|
||||
if(UNIX AND (CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$" OR CMAKE_OSX_ARCHITECTURES STREQUAL "x86_64"))
|
||||
add_subdirectory(tests/register_context)
|
||||
endif()
|
||||
|
||||
add_test_executable(savedata_memory_metadata_tests tests/SaveDataMemoryMetadata.cpp)
|
||||
target_include_directories(savedata_memory_metadata_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(savedata_memory_metadata_tests PRIVATE libSceSaveData.native)
|
||||
configure_windows_unwind(savedata_memory_metadata_tests)
|
||||
add_test(NAME savedata_memory_metadata COMMAND savedata_memory_metadata_tests)
|
||||
if(MINGW)
|
||||
target_compile_options(savedata_memory_metadata_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
if(WIN32)
|
||||
set_tests_properties(savedata_memory_metadata PROPERTIES
|
||||
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
|
||||
endif()
|
||||
add_test_executable(savedata_memory_growth_tests tests/SaveDataMemoryGrowth.cpp)
|
||||
target_include_directories(savedata_memory_growth_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(savedata_memory_growth_tests PRIVATE libSceSaveData.native)
|
||||
configure_windows_unwind(savedata_memory_growth_tests)
|
||||
if(MINGW)
|
||||
target_compile_options(savedata_memory_growth_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME savedata_memory_growth COMMAND savedata_memory_growth_tests)
|
||||
add_test(NAME savedata_memory_growth_read_failure COMMAND savedata_memory_growth_tests read-failure)
|
||||
set_tests_properties(savedata_memory_growth_read_failure PROPERTIES SKIP_RETURN_CODE 77)
|
||||
if(WIN32)
|
||||
set_tests_properties(savedata_memory_growth savedata_memory_growth_read_failure PROPERTIES
|
||||
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
|
||||
endif()
|
||||
add_test_executable(savedata_memory_journal_tests tests/SaveDataMemoryJournal.cpp)
|
||||
target_include_directories(savedata_memory_journal_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(savedata_memory_journal_tests PRIVATE libSceSaveData.native)
|
||||
configure_windows_unwind(savedata_memory_journal_tests)
|
||||
if(MINGW)
|
||||
target_compile_options(savedata_memory_journal_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME savedata_memory_journal COMMAND savedata_memory_journal_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(savedata_memory_journal PROPERTIES
|
||||
ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
|
||||
endif()
|
||||
add_library(host_thread_local_test_library SHARED tests/HostThreadLocalLibrary.cpp)
|
||||
set_target_properties(host_thread_local_test_library PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>")
|
||||
target_include_directories(host_thread_local_test_library PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
add_test_executable(host_thread_local_tests tests/HostThreadLocal.cpp)
|
||||
target_link_libraries(host_thread_local_tests PRIVATE host_thread_local_test_library)
|
||||
if(MINGW)
|
||||
target_compile_options(host_thread_local_test_library PRIVATE -fasynchronous-unwind-tables)
|
||||
target_compile_options(host_thread_local_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME host_thread_local COMMAND host_thread_local_tests)
|
||||
set_tests_properties(host_thread_local PROPERTIES TIMEOUT 15)
|
||||
if(MINGW)
|
||||
add_test(NAME prx_thread_local_destructors COMMAND ${CMAKE_COMMAND} -DNM=${CMAKE_NM} -DOBJDUMP=${CMAKE_OBJDUMP}
|
||||
-DMODULES=$<TARGET_FILE_DIR:libc> -P ${CMAKE_CURRENT_SOURCE_DIR}/tests/ThreadLocalDestructors.cmake)
|
||||
set_tests_properties(prx_thread_local_destructors PROPERTIES TIMEOUT 300)
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_np_cpp_web_api_intrusive_ptr_tests tests/GuestNpCppWebApiIntrusivePtr.cpp)
|
||||
target_include_directories(guest_np_cpp_web_api_intrusive_ptr_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_np_cpp_web_api_intrusive_ptr_tests PRIVATE libSceNpCppWebApi libc)
|
||||
configure_windows_unwind(guest_np_cpp_web_api_intrusive_ptr_tests)
|
||||
add_test(NAME guest_np_cpp_web_api_intrusive_ptr COMMAND guest_np_cpp_web_api_intrusive_ptr_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_np_cpp_web_api_intrusive_ptr PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpCppWebApi>")
|
||||
endif()
|
||||
|
||||
add_test_executable(savedata_core_write_replacement_tests tests/SaveDataWriteReplacement.cpp)
|
||||
target_include_directories(savedata_core_write_replacement_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(savedata_core_write_replacement_tests PRIVATE libSceSaveData)
|
||||
configure_windows_unwind(savedata_core_write_replacement_tests)
|
||||
add_test(NAME savedata_core_write_replacement COMMAND savedata_core_write_replacement_tests)
|
||||
|
||||
add_test_executable(savedata_native_write_replacement_tests tests/SaveDataWriteReplacement.cpp)
|
||||
target_include_directories(savedata_native_write_replacement_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_compile_definitions(savedata_native_write_replacement_tests PRIVATE SAVEDATA_NATIVE_BACKEND)
|
||||
target_link_libraries(savedata_native_write_replacement_tests PRIVATE libSceSaveData.native)
|
||||
configure_windows_unwind(savedata_native_write_replacement_tests)
|
||||
add_test(NAME savedata_native_write_replacement COMMAND savedata_native_write_replacement_tests)
|
||||
|
||||
add_test_executable(savedata_replace_file_failure_tests tests/SaveDataFileWriteFailure.cpp)
|
||||
target_include_directories(savedata_replace_file_failure_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
configure_windows_unwind(savedata_replace_file_failure_tests)
|
||||
add_test(NAME savedata_replace_file_failure COMMAND savedata_replace_file_failure_tests)
|
||||
|
||||
add_test_executable(guest_crt_tests tests/GuestCrt.cpp)
|
||||
target_include_directories(guest_crt_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_crt_tests PRIVATE libSceAmpr libc)
|
||||
configure_windows_unwind(guest_crt_tests)
|
||||
add_test(NAME guest_crt COMMAND guest_crt_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_crt PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAmpr>")
|
||||
endif()
|
||||
|
||||
if(MINGW)
|
||||
target_compile_options(savedata_core_write_replacement_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
target_compile_options(savedata_native_write_replacement_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
target_compile_options(savedata_replace_file_failure_tests PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
if(WIN32)
|
||||
set_tests_properties(savedata_core_write_replacement PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData>")
|
||||
set_tests_properties(savedata_native_write_replacement PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceSaveData.native>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_posix_random_tests tests/GuestPosixRandom.cpp)
|
||||
target_include_directories(guest_posix_random_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_posix_random_tests PRIVATE libScePosixForWebKit)
|
||||
configure_windows_unwind(guest_posix_random_tests)
|
||||
add_test(NAME guest_posix_random COMMAND guest_posix_random_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_posix_random PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libScePosixForWebKit>")
|
||||
endif()
|
||||
|
||||
add_test_executable(MemoryPoolTest
|
||||
tests/MemoryPoolTest.cpp
|
||||
prx/libkernel/DirectMemory/MemoryPool.cpp
|
||||
)
|
||||
target_include_directories(MemoryPoolTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
if(MINGW)
|
||||
target_compile_options(MemoryPoolTest PRIVATE -fasynchronous-unwind-tables)
|
||||
endif()
|
||||
add_test(NAME MemoryPoolTest COMMAND MemoryPoolTest)
|
||||
|
||||
add_test_executable(guest_acm_tests tests/GuestAcm.cpp)
|
||||
target_include_directories(guest_acm_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_acm_tests PRIVATE libSceAcm libc)
|
||||
configure_windows_unwind(guest_acm_tests)
|
||||
add_test(NAME guest_acm COMMAND guest_acm_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_acm PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceAcm>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_voice_chat_tests tests/GuestVoiceChat.cpp)
|
||||
target_include_directories(guest_voice_chat_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_voice_chat_tests PRIVATE libSceVoiceChat libc)
|
||||
configure_windows_unwind(guest_voice_chat_tests)
|
||||
add_test(NAME guest_voice_chat COMMAND guest_voice_chat_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_voice_chat PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceVoiceChat>")
|
||||
endif()
|
||||
|
||||
add_test_executable(guest_np_game_intent_tests tests/GuestNpGameIntent.cpp)
|
||||
target_include_directories(guest_np_game_intent_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(guest_np_game_intent_tests PRIVATE libSceNpGameIntent libc)
|
||||
configure_windows_unwind(guest_np_game_intent_tests)
|
||||
add_test(NAME guest_np_game_intent COMMAND guest_np_game_intent_tests)
|
||||
if(WIN32)
|
||||
set_tests_properties(guest_np_game_intent PROPERTIES ENVIRONMENT_MODIFICATION
|
||||
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libSceNpGameIntent>")
|
||||
endif()
|
||||
endif()
|
||||
@@ -1,17 +0,0 @@
|
||||
#ifndef CORE_LIBS_HITLOG_HPP
|
||||
#define CORE_LIBS_HITLOG_HPP
|
||||
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
|
||||
#define APS5_HIT(tag, ...) \
|
||||
do { \
|
||||
static std::atomic<int> aps5HitCount{0}; \
|
||||
if (aps5HitCount.fetch_add(1, std::memory_order_relaxed) < 3) { \
|
||||
std::fprintf(stderr, "[" tag "] " __VA_ARGS__); \
|
||||
std::fputc('\n', stderr); \
|
||||
std::fflush(stderr); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#endif // CORE_LIBS_HITLOG_HPP
|
||||
@@ -1,91 +0,0 @@
|
||||
#ifndef CORE_LIBS_SCE_SHADERS_HPP
|
||||
#define CORE_LIBS_SCE_SHADERS_HPP
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
struct ShaderSharp {
|
||||
std::uint16_t offset_dw : 15;
|
||||
std::uint16_t size : 1;
|
||||
};
|
||||
|
||||
struct ShaderRegister {
|
||||
std::uint32_t offset;
|
||||
std::uint32_t value;
|
||||
};
|
||||
|
||||
struct ShaderUserData {
|
||||
std::uint16_t* direct_resource_offset;
|
||||
ShaderSharp* sharp_resource_offset[4];
|
||||
std::uint16_t eud_size_dw;
|
||||
std::uint16_t srt_size_dw;
|
||||
std::uint16_t direct_resource_count;
|
||||
std::uint16_t sharp_resource_count[4];
|
||||
};
|
||||
|
||||
struct ShaderRegisterRange {
|
||||
std::uint16_t start;
|
||||
std::uint16_t end;
|
||||
};
|
||||
|
||||
struct ShaderDrawModifier {
|
||||
std::uint32_t enbl_start_vertex_offset : 1;
|
||||
std::uint32_t enbl_start_index_offset : 1;
|
||||
std::uint32_t enbl_start_instance_offset : 1;
|
||||
std::uint32_t enbl_draw_index : 1;
|
||||
std::uint32_t enbl_user_vgprs : 1;
|
||||
std::uint32_t render_target_slice_offset : 3;
|
||||
std::uint32_t fuse_draws : 1;
|
||||
std::uint32_t compiler_flags : 23;
|
||||
std::uint32_t is_default : 1;
|
||||
std::uint32_t reserved : 31;
|
||||
};
|
||||
|
||||
struct ShaderSpecialRegs {
|
||||
ShaderRegister ge_cntl;
|
||||
ShaderRegister vgt_shader_stages_en;
|
||||
std::uint32_t dispatch_modifier;
|
||||
ShaderRegisterRange user_data_range;
|
||||
ShaderDrawModifier draw_modifier;
|
||||
ShaderRegister vgt_gs_out_prim_type;
|
||||
ShaderRegister ge_user_vgpr_en;
|
||||
};
|
||||
|
||||
struct ShaderSemantic {
|
||||
std::uint32_t semantic : 8;
|
||||
std::uint32_t hardware_mapping : 8;
|
||||
std::uint32_t size_in_elements : 4;
|
||||
std::uint32_t is_f16 : 2;
|
||||
std::uint32_t is_flat_shaded : 1;
|
||||
std::uint32_t is_linear : 1;
|
||||
std::uint32_t is_custom : 1;
|
||||
std::uint32_t static_vb_index : 1;
|
||||
std::uint32_t static_attribute : 1;
|
||||
std::uint32_t reserved : 1;
|
||||
std::uint32_t default_value : 2;
|
||||
std::uint32_t default_value_hi : 2;
|
||||
};
|
||||
|
||||
struct Shader {
|
||||
std::uint32_t file_header;
|
||||
std::uint32_t version;
|
||||
ShaderUserData* user_data;
|
||||
const volatile void* code;
|
||||
ShaderRegister* cx_registers;
|
||||
ShaderRegister* sh_registers;
|
||||
ShaderSpecialRegs* specials;
|
||||
ShaderSemantic* input_semantics;
|
||||
ShaderSemantic* output_semantics;
|
||||
std::uint32_t header_size;
|
||||
std::uint32_t shader_size;
|
||||
std::uint32_t embedded_constant_buffer_size_dqw;
|
||||
std::uint32_t target;
|
||||
std::uint32_t num_input_semantics;
|
||||
std::uint16_t scratch_size_dw_per_thread;
|
||||
std::uint16_t num_output_semantics;
|
||||
std::uint16_t special_sizes_bytes;
|
||||
std::uint8_t type;
|
||||
std::uint8_t num_cx_registers;
|
||||
std::uint8_t num_sh_registers;
|
||||
};
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,93 +0,0 @@
|
||||
#include "PeImportFirst.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Allocator {
|
||||
|
||||
namespace {
|
||||
|
||||
std::uint32_t read32(const std::vector<unsigned char>& bytes, std::size_t offset) {
|
||||
if (offset + 4 > bytes.size()) throw std::runtime_error("truncated image");
|
||||
std::uint32_t value = 0;
|
||||
std::memcpy(&value, bytes.data() + offset, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::uint16_t read16(const std::vector<unsigned char>& bytes, std::size_t offset) {
|
||||
if (offset + 2 > bytes.size()) throw std::runtime_error("truncated image");
|
||||
std::uint16_t value = 0;
|
||||
std::memcpy(&value, bytes.data() + offset, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::string lower(std::string text) {
|
||||
std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
|
||||
return text;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void MoveImportFirst(std::vector<unsigned char>& bytes, const std::string& dll) {
|
||||
const auto pe = read32(bytes, 0x3c);
|
||||
if (read32(bytes, pe) != 0x00004550u) throw std::runtime_error("not a PE image");
|
||||
const auto sections = read16(bytes, pe + 6);
|
||||
const auto optionalSize = read16(bytes, pe + 20);
|
||||
const auto optional = pe + 24;
|
||||
if (read16(bytes, optional) != 0x20bu) throw std::runtime_error("not a PE32+ image");
|
||||
const auto importRva = read32(bytes, optional + 112 + 8);
|
||||
if (importRva == 0) throw std::runtime_error("the image has no imports");
|
||||
const auto sectionTable = optional + optionalSize;
|
||||
const auto fileOffset = [&](std::uint32_t rva) -> std::size_t {
|
||||
for (std::uint16_t index = 0; index < sections; ++index) {
|
||||
const auto header = sectionTable + index * 40u;
|
||||
const auto virtualSize = read32(bytes, header + 8);
|
||||
const auto virtualAddress = read32(bytes, header + 12);
|
||||
const auto rawSize = read32(bytes, header + 16);
|
||||
const auto rawOffset = read32(bytes, header + 20);
|
||||
if (rva >= virtualAddress && rva < virtualAddress + std::max(virtualSize, rawSize)) {
|
||||
if (rva - virtualAddress >= rawSize) throw std::runtime_error("RVA outside the section's file data");
|
||||
return rawOffset + (rva - virtualAddress);
|
||||
}
|
||||
}
|
||||
throw std::runtime_error("RVA outside every section");
|
||||
};
|
||||
const auto directory = fileOffset(importRva);
|
||||
constexpr std::size_t DescriptorBytes = 20;
|
||||
std::vector<std::array<unsigned char, DescriptorBytes>> descriptors;
|
||||
std::size_t found = SIZE_MAX;
|
||||
for (std::size_t offset = directory;; offset += DescriptorBytes) {
|
||||
if (offset + DescriptorBytes > bytes.size()) throw std::runtime_error("truncated import directory");
|
||||
std::array<unsigned char, DescriptorBytes> descriptor{};
|
||||
std::memcpy(descriptor.data(), bytes.data() + offset, DescriptorBytes);
|
||||
if (std::all_of(descriptor.begin(), descriptor.end(), [](unsigned char value) { return value == 0; })) break;
|
||||
const auto nameOffset = fileOffset(read32(bytes, offset + 12));
|
||||
std::string name;
|
||||
for (auto at = nameOffset; at < bytes.size() && bytes[at] != 0; ++at) name.push_back(static_cast<char>(bytes[at]));
|
||||
if (lower(name) == lower(dll)) found = descriptors.size();
|
||||
descriptors.push_back(descriptor);
|
||||
}
|
||||
if (found == SIZE_MAX) throw std::runtime_error("the image does not import " + dll);
|
||||
std::rotate(descriptors.begin(), descriptors.begin() + static_cast<std::ptrdiff_t>(found), descriptors.begin() + static_cast<std::ptrdiff_t>(found) + 1);
|
||||
for (std::size_t index = 0; index < descriptors.size(); ++index) std::memcpy(bytes.data() + directory + index * DescriptorBytes, descriptors[index].data(), DescriptorBytes);
|
||||
}
|
||||
|
||||
void MoveImportFirstInFile(const std::string& path, const std::string& dll) {
|
||||
std::vector<unsigned char> bytes;
|
||||
{
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
if (!input) throw std::runtime_error("cannot open " + path);
|
||||
bytes.assign(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());
|
||||
}
|
||||
MoveImportFirst(bytes, dll);
|
||||
std::ofstream output(path, std::ios::binary | std::ios::trunc);
|
||||
if (!output || !output.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()))) throw std::runtime_error("cannot write " + path);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
#ifndef CORE_LIBS_ALLOCATOR_PEIMPORTFIRST_HPP
|
||||
#define CORE_LIBS_ALLOCATOR_PEIMPORTFIRST_HPP
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Allocator {
|
||||
|
||||
void MoveImportFirst(std::vector<unsigned char>& image, const std::string& dll);
|
||||
void MoveImportFirstInFile(const std::string& path, const std::string& dll);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,18 +0,0 @@
|
||||
#include "PeImportFirst.hpp"
|
||||
|
||||
#include <cstdio>
|
||||
#include <exception>
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc != 3) {
|
||||
std::fprintf(stderr, "usage: pe_import_first <file> <dll>\n");
|
||||
return 2;
|
||||
}
|
||||
try {
|
||||
Allocator::MoveImportFirstInFile(argv[1], argv[2]);
|
||||
} catch (const std::exception& error) {
|
||||
std::fprintf(stderr, "pe_import_first: %s: %s\n", argv[1], error.what());
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
void* __wrap_malloc(size_t bytes) {
|
||||
return HeapAlloc(GetProcessHeap(), 0, bytes != 0 ? bytes : 1);
|
||||
}
|
||||
|
||||
void* __wrap_calloc(size_t count, size_t size) {
|
||||
if (size != 0 && count > SIZE_MAX / size) return NULL;
|
||||
const size_t bytes = count * size;
|
||||
return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bytes != 0 ? bytes : 1);
|
||||
}
|
||||
|
||||
void __wrap_free(void* block) {
|
||||
if (block != NULL) HeapFree(GetProcessHeap(), 0, block);
|
||||
}
|
||||
|
||||
void* __wrap_realloc(void* block, size_t bytes) {
|
||||
if (block == NULL) return __wrap_malloc(bytes);
|
||||
if (bytes == 0) {
|
||||
__wrap_free(block);
|
||||
return NULL;
|
||||
}
|
||||
return HeapReAlloc(GetProcessHeap(), 0, block, bytes);
|
||||
}
|
||||
|
||||
char* __wrap__strdup(const char* text) {
|
||||
const size_t bytes = strlen(text) + 1;
|
||||
char* copy = __wrap_malloc(bytes);
|
||||
if (copy != NULL) memcpy(copy, text, bytes);
|
||||
return copy;
|
||||
}
|
||||
|
||||
char* __wrap_strdup(const char* text) {
|
||||
return __wrap__strdup(text);
|
||||
}
|
||||
@@ -1,156 +0,0 @@
|
||||
#include "allocator/PeImportFirst.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iterator>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr std::size_t PeOffset = 0x40;
|
||||
constexpr std::size_t OptionalOffset = PeOffset + 24;
|
||||
constexpr std::size_t OptionalBytes = 240;
|
||||
constexpr std::size_t SectionTable = OptionalOffset + OptionalBytes;
|
||||
constexpr std::uint32_t SectionRva = 0x1000;
|
||||
constexpr std::size_t SectionOffset = 0x200;
|
||||
constexpr std::size_t SectionBytes = 0x200;
|
||||
constexpr std::size_t DescriptorBytes = 20;
|
||||
|
||||
void require(bool condition, const std::string& message) {
|
||||
if (!condition) throw std::runtime_error(message);
|
||||
}
|
||||
|
||||
void put16(std::vector<unsigned char>& bytes, std::size_t offset, std::uint16_t value) {
|
||||
std::memcpy(bytes.data() + offset, &value, sizeof(value));
|
||||
}
|
||||
|
||||
void put32(std::vector<unsigned char>& bytes, std::size_t offset, std::uint32_t value) {
|
||||
std::memcpy(bytes.data() + offset, &value, sizeof(value));
|
||||
}
|
||||
|
||||
std::uint32_t get32(const std::vector<unsigned char>& bytes, std::size_t offset) {
|
||||
std::uint32_t value = 0;
|
||||
std::memcpy(&value, bytes.data() + offset, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::vector<unsigned char> image(const std::vector<std::string>& dlls, std::uint16_t magic = 0x20b) {
|
||||
std::vector<unsigned char> bytes(SectionOffset + SectionBytes, 0);
|
||||
bytes[0] = 'M';
|
||||
bytes[1] = 'Z';
|
||||
put32(bytes, 0x3c, PeOffset);
|
||||
put32(bytes, PeOffset, 0x00004550u);
|
||||
put16(bytes, PeOffset + 4, 0x8664);
|
||||
put16(bytes, PeOffset + 6, 1);
|
||||
put16(bytes, PeOffset + 20, OptionalBytes);
|
||||
put16(bytes, OptionalOffset, magic);
|
||||
put32(bytes, OptionalOffset + 108, 16);
|
||||
put32(bytes, OptionalOffset + 112 + 8, SectionRva);
|
||||
put32(bytes, OptionalOffset + 112 + 12, static_cast<std::uint32_t>((dlls.size() + 1) * DescriptorBytes));
|
||||
std::memcpy(bytes.data() + SectionTable, ".idata", 6);
|
||||
put32(bytes, SectionTable + 8, SectionBytes);
|
||||
put32(bytes, SectionTable + 12, SectionRva);
|
||||
put32(bytes, SectionTable + 16, SectionBytes);
|
||||
put32(bytes, SectionTable + 20, SectionOffset);
|
||||
auto name = (dlls.size() + 1) * DescriptorBytes;
|
||||
for (std::size_t index = 0; index < dlls.size(); ++index) {
|
||||
const auto descriptor = SectionOffset + index * DescriptorBytes;
|
||||
put32(bytes, descriptor, static_cast<std::uint32_t>(SectionRva + 0x100 + index * 0x10));
|
||||
put32(bytes, descriptor + 4, static_cast<std::uint32_t>(index + 1));
|
||||
put32(bytes, descriptor + 12, static_cast<std::uint32_t>(SectionRva + name));
|
||||
put32(bytes, descriptor + 16, static_cast<std::uint32_t>(SectionRva + 0x180 + index * 0x10));
|
||||
std::memcpy(bytes.data() + SectionOffset + name, dlls[index].c_str(), dlls[index].size() + 1);
|
||||
name += dlls[index].size() + 1;
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
std::string importName(const std::vector<unsigned char>& bytes, std::size_t index) {
|
||||
const auto rva = get32(bytes, SectionOffset + index * DescriptorBytes + 12);
|
||||
return reinterpret_cast<const char*>(bytes.data() + SectionOffset + (rva - SectionRva));
|
||||
}
|
||||
|
||||
std::vector<unsigned char> descriptor(const std::vector<unsigned char>& bytes, std::size_t index) {
|
||||
const auto first = bytes.begin() + static_cast<std::ptrdiff_t>(SectionOffset + index * DescriptorBytes);
|
||||
return {first, first + static_cast<std::ptrdiff_t>(DescriptorBytes)};
|
||||
}
|
||||
|
||||
void writeFile(const std::filesystem::path& path, const std::vector<unsigned char>& bytes) {
|
||||
std::ofstream output(path, std::ios::binary | std::ios::trunc);
|
||||
output.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
|
||||
require(static_cast<bool>(output), "cannot write " + path.string());
|
||||
}
|
||||
|
||||
std::vector<unsigned char> readFile(const std::filesystem::path& path) {
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
require(static_cast<bool>(input), "cannot read " + path.string());
|
||||
return {std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
|
||||
}
|
||||
|
||||
void movesTheNamedImportFirst() {
|
||||
const auto original = image({"kernel32.dll", "ucrtbase.dll", "mimalloc-redirect.dll", "advapi32.dll"});
|
||||
auto moved = original;
|
||||
Allocator::MoveImportFirst(moved, "MIMALLOC-REDIRECT.dll");
|
||||
require(importName(moved, 0) == "mimalloc-redirect.dll" && importName(moved, 1) == "kernel32.dll" && importName(moved, 2) == "ucrtbase.dll" && importName(moved, 3) == "advapi32.dll",
|
||||
"the named import did not move first, or the others changed their order");
|
||||
require(descriptor(moved, 0) == descriptor(original, 2) && descriptor(moved, 1) == descriptor(original, 0) && descriptor(moved, 2) == descriptor(original, 1) && descriptor(moved, 3) == descriptor(original, 3),
|
||||
"a descriptor did not move whole");
|
||||
const auto directoryEnd = SectionOffset + 4 * DescriptorBytes;
|
||||
require(std::equal(moved.begin(), moved.begin() + SectionOffset, original.begin()) && std::equal(moved.begin() + directoryEnd, moved.end(), original.begin() + directoryEnd),
|
||||
"bytes outside the import descriptors changed");
|
||||
auto unchanged = original;
|
||||
Allocator::MoveImportFirst(unchanged, "kernel32.dll");
|
||||
require(unchanged == original, "moving the first import changed the image");
|
||||
}
|
||||
|
||||
void movesTheImportInAFile(const std::filesystem::path& directory) {
|
||||
const auto path = directory / "moved.dll";
|
||||
writeFile(path, image({"kernel32.dll", "mimalloc-redirect.dll"}));
|
||||
Allocator::MoveImportFirstInFile(path.string(), "mimalloc-redirect.dll");
|
||||
const auto moved = readFile(path);
|
||||
require(importName(moved, 0) == "mimalloc-redirect.dll" && importName(moved, 1) == "kernel32.dll", "the file's import did not move first");
|
||||
}
|
||||
|
||||
void failsWithoutTouchingTheFile(const std::filesystem::path& directory, const std::string& what, const std::vector<unsigned char>& bytes, const std::string& expected) {
|
||||
const auto path = directory / (what + ".dll");
|
||||
writeFile(path, bytes);
|
||||
try {
|
||||
Allocator::MoveImportFirstInFile(path.string(), "mimalloc-redirect.dll");
|
||||
} catch (const std::exception& error) {
|
||||
require(std::string(error.what()).find(expected) != std::string::npos, what + ": failed with another error: " + error.what());
|
||||
require(readFile(path) == bytes, what + ": the file changed although the move failed");
|
||||
return;
|
||||
}
|
||||
throw std::runtime_error(what + ": the move did not fail");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
const auto directory = std::filesystem::temp_directory_path() / ("aps5-pe-import-first-" + std::to_string(std::random_device{}()));
|
||||
try {
|
||||
std::filesystem::create_directories(directory);
|
||||
movesTheNamedImportFirst();
|
||||
movesTheImportInAFile(directory);
|
||||
failsWithoutTouchingTheFile(directory, "missing-import", image({"kernel32.dll", "ucrtbase.dll"}), "does not import mimalloc-redirect.dll");
|
||||
auto truncated = image({"kernel32.dll", "mimalloc-redirect.dll", "ucrtbase.dll"});
|
||||
truncated.resize(SectionOffset + DescriptorBytes + DescriptorBytes / 2);
|
||||
failsWithoutTouchingTheFile(directory, "truncated-directory", truncated, "truncated import directory");
|
||||
failsWithoutTouchingTheFile(directory, "pe32", image({"kernel32.dll", "mimalloc-redirect.dll"}, 0x10b), "not a PE32+ image");
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
std::error_code ignored;
|
||||
std::filesystem::remove_all(directory, ignored);
|
||||
return 1;
|
||||
}
|
||||
std::filesystem::remove_all(directory);
|
||||
std::cout << "pe import first tests passed\n";
|
||||
return 0;
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
#ifndef NID_BINARYPATCHERFACTORY_HPP
|
||||
#define NID_BINARYPATCHERFACTORY_HPP
|
||||
|
||||
#include <nid/IBinaryPatcher.hpp>
|
||||
#include <cstdint>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::unique_ptr<IBinaryPatcher> MakePatcher(const std::vector<std::uint8_t>& binary);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,111 +0,0 @@
|
||||
#ifndef NID_ELFPATCHER_HPP
|
||||
#define NID_ELFPATCHER_HPP
|
||||
|
||||
#include <nid/IBinaryPatcher.hpp>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
struct Elf64_Ehdr {
|
||||
std::uint8_t e_ident[16];
|
||||
std::uint16_t e_type;
|
||||
std::uint16_t e_machine;
|
||||
std::uint32_t e_version;
|
||||
std::uint64_t e_entry;
|
||||
std::uint64_t e_phoff;
|
||||
std::uint64_t e_shoff;
|
||||
std::uint32_t e_flags;
|
||||
std::uint16_t e_ehsize;
|
||||
std::uint16_t e_phentsize;
|
||||
std::uint16_t e_phnum;
|
||||
std::uint16_t e_shentsize;
|
||||
std::uint16_t e_shnum;
|
||||
std::uint16_t e_shstrndx;
|
||||
};
|
||||
|
||||
struct Elf64_Shdr {
|
||||
std::uint32_t sh_name;
|
||||
std::uint32_t sh_type;
|
||||
std::uint64_t sh_flags;
|
||||
std::uint64_t sh_addr;
|
||||
std::uint64_t sh_offset;
|
||||
std::uint64_t sh_size;
|
||||
std::uint32_t sh_link;
|
||||
std::uint32_t sh_info;
|
||||
std::uint64_t sh_addralign;
|
||||
std::uint64_t sh_entsize;
|
||||
};
|
||||
|
||||
struct Elf64_Sym {
|
||||
std::uint32_t st_name;
|
||||
std::uint8_t st_info;
|
||||
std::uint8_t st_other;
|
||||
std::uint16_t st_shndx;
|
||||
std::uint64_t st_value;
|
||||
std::uint64_t st_size;
|
||||
};
|
||||
|
||||
struct Elf64_Rela {
|
||||
std::uint64_t r_offset;
|
||||
std::uint64_t r_info;
|
||||
std::int64_t r_addend;
|
||||
};
|
||||
|
||||
struct Elf64_Dyn {
|
||||
std::int64_t d_tag;
|
||||
std::uint64_t d_val;
|
||||
};
|
||||
|
||||
struct Elf64_Verneed {
|
||||
std::uint16_t vn_version;
|
||||
std::uint16_t vn_cnt;
|
||||
std::uint32_t vn_file;
|
||||
std::uint32_t vn_aux;
|
||||
std::uint32_t vn_next;
|
||||
};
|
||||
|
||||
struct Elf64_Vernaux {
|
||||
std::uint32_t vna_hash;
|
||||
std::uint16_t vna_flags;
|
||||
std::uint16_t vna_other;
|
||||
std::uint32_t vna_name;
|
||||
std::uint32_t vna_next;
|
||||
};
|
||||
|
||||
struct GnuHashLayout {
|
||||
std::uint32_t NBuckets;
|
||||
std::uint32_t SymOffset;
|
||||
std::uint32_t BloomSize;
|
||||
std::uint32_t BloomShift;
|
||||
std::size_t BloomOffset;
|
||||
std::size_t BucketsOffset;
|
||||
std::size_t ChainOffset;
|
||||
};
|
||||
|
||||
constexpr std::int64_t kDtNeeded = 1;
|
||||
constexpr std::int64_t kDtSoname = 14;
|
||||
constexpr std::int64_t kDtRpath = 15;
|
||||
constexpr std::int64_t kDtRunpath = 29;
|
||||
constexpr std::int64_t kDtNull = 0;
|
||||
|
||||
inline bool IsDynamicNameTag(std::int64_t tag) {
|
||||
return tag == kDtNeeded || tag == kDtSoname || tag == kDtRpath || tag == kDtRunpath;
|
||||
}
|
||||
constexpr std::uint32_t kShtDynamic = 6u;
|
||||
constexpr std::uint32_t kShtHash = 5u;
|
||||
constexpr std::uint32_t kShtGnuVerdef = 0x6ffffffdu;
|
||||
constexpr std::uint32_t kShtGnuVerneed = 0x6ffffffeu;
|
||||
constexpr std::uint32_t kShtDynsym = 11u;
|
||||
constexpr std::uint32_t kShtGnuHash = 0x6ffffff6u;
|
||||
constexpr std::uint32_t kShtRela = 4u;
|
||||
constexpr std::uint32_t kShtGnuVersym = 0x6fffffffu;
|
||||
constexpr std::uint8_t kStbLocal = 0u;
|
||||
constexpr std::uint16_t kShnUndef = 0u;
|
||||
|
||||
class ElfNidPatcher final : public IBinaryPatcher {
|
||||
public:
|
||||
void PatchNids(std::vector<std::uint8_t>& binary, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const override;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,16 +0,0 @@
|
||||
#ifndef NID_EXPORTEXCLUSIONS_HPP
|
||||
#define NID_EXPORTEXCLUSIONS_HPP
|
||||
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::string NormalizeExportName(const std::string& name);
|
||||
std::unordered_set<std::string> ReadExportExclusions(const std::string& path);
|
||||
std::unordered_set<std::string> ReadExportList(const std::string& path);
|
||||
bool WriteExportList(const std::string& referencePath, const std::string& path);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,20 +0,0 @@
|
||||
#ifndef NID_IBINARYPATCHER_HPP
|
||||
#define NID_IBINARYPATCHER_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
class IBinaryPatcher {
|
||||
public:
|
||||
virtual ~IBinaryPatcher() = default;
|
||||
|
||||
virtual void PatchNids(std::vector<std::uint8_t>& binary, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const = 0;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,30 +0,0 @@
|
||||
#ifndef CORE_LIBS_NID_MACHONIDPATCHER_HPP
|
||||
#define CORE_LIBS_NID_MACHONIDPATCHER_HPP
|
||||
|
||||
#include <nid/IBinaryPatcher.hpp>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
constexpr std::uint32_t kMachOMagic64 = 0xfeedfacfu;
|
||||
|
||||
struct MachOExport {
|
||||
std::string Name;
|
||||
std::uint64_t Flags = 0;
|
||||
std::uint64_t Address = 0;
|
||||
std::uint64_t Other = 0;
|
||||
std::string ImportName;
|
||||
};
|
||||
|
||||
std::vector<MachOExport> ReadMachOExports(const std::vector<std::uint8_t>& binary);
|
||||
|
||||
class MachONidPatcher final : public IBinaryPatcher {
|
||||
public:
|
||||
void PatchNids(std::vector<std::uint8_t>& binary, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const override;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,15 +0,0 @@
|
||||
#ifndef NID_NATIVEPATH_HPP
|
||||
#define NID_NATIVEPATH_HPP
|
||||
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
|
||||
namespace Nid::Internal {
|
||||
|
||||
inline std::filesystem::path NativePath(const std::string& path) {
|
||||
return std::filesystem::path(std::u8string(path.begin(), path.end()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,12 +0,0 @@
|
||||
#ifndef NID_NIDCOMPUTE_HPP
|
||||
#define NID_NIDCOMPUTE_HPP
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::string ComputeNid(const std::string& symbolName, const std::string& libraryName);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,88 +0,0 @@
|
||||
#ifndef NID_NIDPATCHERUTILS_HPP
|
||||
#define NID_NIDPATCHERUTILS_HPP
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
namespace Internal {
|
||||
|
||||
constexpr char kNidPostfix[] = "_nid_postfix";
|
||||
constexpr std::size_t kNidPostfixLen = sizeof(kNidPostfix) - 1u;
|
||||
constexpr char kNidNoPatch[] = "_nid_no_patch";
|
||||
constexpr std::size_t kNidNoPatchLen = sizeof(kNidNoPatch) - 1u;
|
||||
constexpr char kNidNoPatchCut[] = "_nid_no_patch_cut";
|
||||
constexpr std::size_t kNidNoPatchCutLen = sizeof(kNidNoPatchCut) - 1u;
|
||||
constexpr char kNidDisambigMarker[] = "_nid_disambig";
|
||||
constexpr std::size_t kNidDisambigMarkerLen = sizeof(kNidDisambigMarker) - 1u;
|
||||
constexpr char kSDLPrefix[] = "SDL_";
|
||||
constexpr std::size_t kSDLPrefixLen = sizeof(kSDLPrefix) - 1u;
|
||||
|
||||
|
||||
inline bool IsNidNoPatch(const std::string& name) {
|
||||
return (
|
||||
name.size() >= kNidNoPatchLen &&
|
||||
name.compare(name.size() - kNidNoPatchLen, kNidNoPatchLen, kNidNoPatch) == 0
|
||||
) || name.compare(0, kSDLPrefixLen, kSDLPrefix) == 0;
|
||||
}
|
||||
|
||||
inline bool IsNidNoPatchCut(const std::string& name) {
|
||||
return name.size() >= kNidNoPatchCutLen &&
|
||||
name.compare(name.size() - kNidNoPatchCutLen, kNidNoPatchCutLen, kNidNoPatchCut) == 0;
|
||||
}
|
||||
|
||||
inline std::string StripNidNoPatchCut(const std::string& name) {
|
||||
return name.substr(0u, name.size() - kNidNoPatchCutLen);
|
||||
}
|
||||
|
||||
inline std::string StripNidPostfix(const std::string& name) {
|
||||
std::string result = name;
|
||||
if (result.size() >= kNidPostfixLen &&
|
||||
result.compare(result.size() - kNidPostfixLen, kNidPostfixLen, kNidPostfix) == 0) {
|
||||
result.resize(result.size() - kNidPostfixLen);
|
||||
}
|
||||
const auto disambigPos = result.rfind(kNidDisambigMarker);
|
||||
if (disambigPos != std::string::npos) {
|
||||
const auto suffixStart = disambigPos + kNidDisambigMarkerLen;
|
||||
const bool allDigits = std::all_of(
|
||||
result.begin() + static_cast<std::ptrdiff_t>(suffixStart), result.end(),
|
||||
[](unsigned char c) { return std::isdigit(c) != 0; }
|
||||
);
|
||||
if (allDigits && suffixStart < result.size())
|
||||
result.resize(disambigPos);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
T Read(const std::vector<std::uint8_t>& buf, std::size_t offset) {
|
||||
if (offset > buf.size() || sizeof(T) > buf.size() - offset) throw std::runtime_error("read out of bounds");
|
||||
T v;
|
||||
std::memcpy(&v, buf.data() + offset, sizeof(T));
|
||||
return v;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void Write(std::vector<std::uint8_t>& buf, std::size_t offset, const T& v) {
|
||||
if (offset > buf.size() || sizeof(T) > buf.size() - offset) throw std::runtime_error("write out of bounds");
|
||||
std::memcpy(buf.data() + offset, &v, sizeof(T));
|
||||
}
|
||||
|
||||
inline std::string ReadCStr(const std::vector<std::uint8_t>& buf, std::size_t offset) {
|
||||
if (offset >= buf.size()) throw std::runtime_error("cstr offset out of bounds");
|
||||
std::string s;
|
||||
while (offset < buf.size() && buf[offset] != 0u)
|
||||
s.push_back(static_cast<char>(buf[offset++]));
|
||||
if (offset == buf.size()) throw std::runtime_error("unterminated cstr");
|
||||
return s;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,17 +0,0 @@
|
||||
#ifndef NID_NIDRESOLVER_HPP
|
||||
#define NID_NIDRESOLVER_HPP
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::string ResolveOneName(const std::string& funcName);
|
||||
|
||||
std::unordered_map<std::string, std::string> ResolveNids(const std::vector<std::string>& exportedNames, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,47 +0,0 @@
|
||||
#ifndef CORE_LIBS_NID_PENIDPATCHER_HPP
|
||||
#define CORE_LIBS_NID_PENIDPATCHER_HPP
|
||||
|
||||
#include <nid/IBinaryPatcher.hpp>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
struct PeDataDirectory {
|
||||
std::uint32_t VirtualAddress;
|
||||
std::uint32_t Size;
|
||||
};
|
||||
|
||||
struct PeExportDirectory {
|
||||
std::uint32_t Characteristics;
|
||||
std::uint32_t TimeDateStamp;
|
||||
std::uint16_t MajorVersion;
|
||||
std::uint16_t MinorVersion;
|
||||
std::uint32_t Name;
|
||||
std::uint32_t Base;
|
||||
std::uint32_t NumberOfFunctions;
|
||||
std::uint32_t NumberOfNames;
|
||||
std::uint32_t AddressOfFunctions;
|
||||
std::uint32_t AddressOfNames;
|
||||
std::uint32_t AddressOfNameOrdinals;
|
||||
};
|
||||
|
||||
struct PeSectionHeader {
|
||||
std::uint8_t Name[8];
|
||||
std::uint32_t VirtualSize;
|
||||
std::uint32_t VirtualAddress;
|
||||
std::uint32_t SizeOfRawData;
|
||||
std::uint32_t PointerToRawData;
|
||||
std::uint32_t PointerToRelocations;
|
||||
std::uint32_t PointerToLinenumbers;
|
||||
std::uint16_t NumberOfRelocations;
|
||||
std::uint16_t NumberOfLinenumbers;
|
||||
std::uint32_t Characteristics;
|
||||
};
|
||||
|
||||
class PeNidPatcher final : public IBinaryPatcher {
|
||||
public:
|
||||
void PatchNids(std::vector<std::uint8_t>& binary, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const override;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,14 +0,0 @@
|
||||
#ifndef NID_SHA1_HPP
|
||||
#define NID_SHA1_HPP
|
||||
|
||||
#include <cstdint>
|
||||
#include <array>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::array<std::uint8_t, 20> Sha1(const std::vector<std::uint8_t>& data);
|
||||
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,19 +0,0 @@
|
||||
#include <nid/BinaryPatcherFactory.hpp>
|
||||
#include <nid/ElfPatcher.hpp>
|
||||
#include <nid/MachONidPatcher.hpp>
|
||||
#include <nid/PeNidPatcher.hpp>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::unique_ptr<IBinaryPatcher> MakePatcher(const std::vector<std::uint8_t>& binary) {
|
||||
if (binary.size() >= 4 && binary[0] == 0x7f && binary[1] == 'E' && binary[2] == 'L' && binary[3] == 'F')
|
||||
return std::make_unique<ElfNidPatcher>();
|
||||
if (binary.size() >= 2 && binary[0] == 'M' && binary[1] == 'Z')
|
||||
return std::make_unique<PeNidPatcher>();
|
||||
if (binary.size() >= 4 && binary[0] == 0xcf && binary[1] == 0xfa && binary[2] == 0xed && binary[3] == 0xfe)
|
||||
return std::make_unique<MachONidPatcher>();
|
||||
throw std::runtime_error("unrecognized binary format");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,570 +0,0 @@
|
||||
#include <nid/ElfPatcher.hpp>
|
||||
#include <nid/NidResolver.hpp>
|
||||
#include <nid/NidPatcherUtils.hpp>
|
||||
#include <nid/NidCompute.hpp>
|
||||
#include <algorithm>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
namespace {
|
||||
|
||||
|
||||
void RequireElfRange(const std::vector<std::uint8_t>& elf, std::uint64_t offset, std::uint64_t size, const char* table) {
|
||||
if (offset > elf.size() || size > elf.size() - offset)
|
||||
throw std::runtime_error(std::string("invalid ELF ") + table + " range");
|
||||
}
|
||||
|
||||
std::uint32_t GnuHash(const std::string& name) {
|
||||
std::uint32_t h = 5381u;
|
||||
for (const unsigned char c : name)
|
||||
h = h * 33u + c;
|
||||
return h;
|
||||
}
|
||||
|
||||
std::uint32_t SysvHash(const std::string& name) {
|
||||
std::uint32_t hash = 0u;
|
||||
for (const unsigned char byte : name) {
|
||||
hash = (hash << 4u) + byte;
|
||||
const auto high = hash & 0xf0000000u;
|
||||
hash ^= high >> 24u;
|
||||
hash &= ~high;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
void ValidateSysvHash(const std::vector<std::uint8_t>& elf, std::size_t offset, std::size_t size, std::size_t symCount) {
|
||||
using namespace Internal;
|
||||
RequireElfRange(elf, offset, size, "hash");
|
||||
if (size < 8u) throw std::runtime_error("invalid ELF hash header");
|
||||
const auto buckets = Read<std::uint32_t>(elf, offset);
|
||||
const auto chains = Read<std::uint32_t>(elf, offset + 4u);
|
||||
if (!buckets || chains != symCount || 8u + (std::uint64_t{buckets} + chains) * 4u > size)
|
||||
throw std::runtime_error("invalid ELF hash geometry");
|
||||
}
|
||||
|
||||
void RebuildSysvHash(std::vector<std::uint8_t>& elf, std::size_t offset, const std::vector<std::string>& symbolNames) {
|
||||
using namespace Internal;
|
||||
const auto bucketCount = Read<std::uint32_t>(elf, offset);
|
||||
std::vector<std::uint32_t> buckets(bucketCount, 0u);
|
||||
std::vector<std::uint32_t> chains(symbolNames.size(), 0u);
|
||||
for (std::size_t index = 1u; index < symbolNames.size(); ++index) {
|
||||
if (symbolNames[index].empty()) continue;
|
||||
const auto bucket = SysvHash(symbolNames[index]) % bucketCount;
|
||||
chains[index] = buckets[bucket];
|
||||
buckets[bucket] = static_cast<std::uint32_t>(index);
|
||||
}
|
||||
for (std::size_t index = 0u; index < buckets.size(); ++index)
|
||||
Write(elf, offset + 8u + index * 4u, buckets[index]);
|
||||
for (std::size_t index = 0u; index < chains.size(); ++index)
|
||||
Write(elf, offset + 8u + buckets.size() * 4u + index * 4u, chains[index]);
|
||||
}
|
||||
|
||||
|
||||
GnuHashLayout ReadGnuHashLayout(const std::vector<std::uint8_t>& elf, std::size_t sectionOffset) {
|
||||
using namespace Internal;
|
||||
GnuHashLayout layout{};
|
||||
layout.NBuckets = Read<std::uint32_t>(elf, sectionOffset + 0u);
|
||||
layout.SymOffset = Read<std::uint32_t>(elf, sectionOffset + 4u);
|
||||
layout.BloomSize = Read<std::uint32_t>(elf, sectionOffset + 8u);
|
||||
layout.BloomShift = Read<std::uint32_t>(elf, sectionOffset + 12u);
|
||||
layout.BloomOffset = sectionOffset + 16u;
|
||||
layout.BucketsOffset = layout.BloomOffset + static_cast<std::size_t>(layout.BloomSize) * 8u;
|
||||
layout.ChainOffset = layout.BucketsOffset + static_cast<std::size_t>(layout.NBuckets) * 4u;
|
||||
return layout;
|
||||
}
|
||||
|
||||
void ValidateGnuHash(const std::vector<std::uint8_t>& elf, std::size_t offset, std::size_t size, std::size_t symCount) {
|
||||
if (offset > elf.size() || size > elf.size() - offset || size < 16u)
|
||||
throw std::runtime_error("invalid gnu.hash section range");
|
||||
const auto layout = ReadGnuHashLayout(elf, offset);
|
||||
if (layout.SymOffset > symCount || !layout.BloomSize || (layout.BloomSize & (layout.BloomSize - 1u)) ||
|
||||
layout.BloomShift >= 32u || (!layout.NBuckets && layout.SymOffset != symCount))
|
||||
throw std::runtime_error("invalid gnu.hash geometry");
|
||||
const std::uint64_t required = 16u + std::uint64_t{layout.BloomSize} * 8u +
|
||||
std::uint64_t{layout.NBuckets} * 4u + (symCount - layout.SymOffset) * 4u;
|
||||
if (required > size) throw std::runtime_error("gnu.hash section too small to rebuild in place");
|
||||
}
|
||||
|
||||
void ReorderDynSymForGnuHash(
|
||||
std::vector<std::uint8_t>& elf,
|
||||
std::size_t dynSymOffset,
|
||||
std::size_t symCount,
|
||||
std::uint32_t symOffset,
|
||||
std::uint32_t bucketCount,
|
||||
std::vector<std::string>& symbolNames,
|
||||
std::vector<std::uint32_t>& oldToNewIndex
|
||||
) {
|
||||
using namespace Internal;
|
||||
|
||||
std::vector<std::uint32_t> movableIndices;
|
||||
for (std::uint32_t i = symOffset; i < symCount; ++i)
|
||||
movableIndices.push_back(i);
|
||||
|
||||
std::stable_sort(
|
||||
movableIndices.begin(), movableIndices.end(),
|
||||
[&](const std::uint32_t lhs, const std::uint32_t rhs) {
|
||||
return GnuHash(symbolNames[lhs]) % bucketCount < GnuHash(symbolNames[rhs]) % bucketCount;
|
||||
}
|
||||
);
|
||||
|
||||
std::vector<Elf64_Sym> reorderedSyms(symCount);
|
||||
std::vector<std::string> reorderedNames(symCount);
|
||||
|
||||
for (std::uint32_t i = 0u; i < symOffset; ++i) {
|
||||
reorderedSyms[i] = Read<Elf64_Sym>(elf, dynSymOffset + i * sizeof(Elf64_Sym));
|
||||
reorderedNames[i] = symbolNames[i];
|
||||
oldToNewIndex[i] = i;
|
||||
}
|
||||
|
||||
for (std::size_t position = 0u; position < movableIndices.size(); ++position) {
|
||||
const std::uint32_t oldIndex = movableIndices[position];
|
||||
const std::uint32_t newIndex = symOffset + static_cast<std::uint32_t>(position);
|
||||
reorderedSyms[newIndex] = Read<Elf64_Sym>(elf, dynSymOffset + oldIndex * sizeof(Elf64_Sym));
|
||||
reorderedNames[newIndex] = symbolNames[oldIndex];
|
||||
oldToNewIndex[oldIndex] = newIndex;
|
||||
}
|
||||
|
||||
for (std::size_t i = 0u; i < symCount; ++i)
|
||||
Write(elf, dynSymOffset + i * sizeof(Elf64_Sym), reorderedSyms[i]);
|
||||
|
||||
symbolNames = std::move(reorderedNames);
|
||||
}
|
||||
|
||||
void FixupRelocationSymbolIndices(
|
||||
std::vector<std::uint8_t>& elf,
|
||||
const Elf64_Ehdr& ehdr,
|
||||
std::uint32_t dynSymSectionIndex,
|
||||
const std::vector<std::uint32_t>& oldToNewIndex
|
||||
) {
|
||||
using namespace Internal;
|
||||
|
||||
for (std::uint16_t i = 0u; i < ehdr.e_shnum; ++i) {
|
||||
const std::size_t shOffset = static_cast<std::size_t>(ehdr.e_shoff) + i * sizeof(Elf64_Shdr);
|
||||
const auto shdr = Read<Elf64_Shdr>(elf, shOffset);
|
||||
if (shdr.sh_type != kShtRela) continue;
|
||||
if (shdr.sh_link != dynSymSectionIndex) continue;
|
||||
|
||||
const std::size_t relaOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
const std::size_t relaCount = static_cast<std::size_t>(shdr.sh_size) / sizeof(Elf64_Rela);
|
||||
|
||||
for (std::size_t r = 0u; r < relaCount; ++r) {
|
||||
const std::size_t entryOffset = relaOffset + r * sizeof(Elf64_Rela);
|
||||
const auto rela = Read<Elf64_Rela>(elf, entryOffset);
|
||||
|
||||
const auto oldSymIndex = static_cast<std::uint32_t>(rela.r_info >> 32u);
|
||||
if (oldSymIndex >= oldToNewIndex.size()) continue;
|
||||
|
||||
const std::uint32_t newSymIndex = oldToNewIndex[oldSymIndex];
|
||||
const auto relType = static_cast<std::uint32_t>(rela.r_info & 0xffffffffu);
|
||||
const std::uint64_t newInfo = (static_cast<std::uint64_t>(newSymIndex) << 32u) | relType;
|
||||
|
||||
Write(elf, entryOffset + offsetof(Elf64_Rela, r_info), newInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RebuildGnuHash(
|
||||
std::vector<std::uint8_t>& elf,
|
||||
std::size_t sectionOffset,
|
||||
std::size_t sectionSize,
|
||||
std::size_t symCount,
|
||||
const std::vector<std::string>& symbolNames
|
||||
) {
|
||||
using namespace Internal;
|
||||
|
||||
const GnuHashLayout layout = ReadGnuHashLayout(elf, sectionOffset);
|
||||
|
||||
const std::size_t chainCount = symCount - layout.SymOffset;
|
||||
const std::size_t requiredSize = layout.ChainOffset - sectionOffset + chainCount * 4u;
|
||||
if (requiredSize > sectionSize)
|
||||
throw std::runtime_error("gnu.hash section too small to rebuild in place");
|
||||
|
||||
std::vector<std::uint32_t> hashes(symCount, 0u);
|
||||
for (std::size_t i = layout.SymOffset; i < symCount; ++i)
|
||||
hashes[i] = GnuHash(symbolNames[i]);
|
||||
|
||||
std::vector<std::uint64_t> bloom(layout.BloomSize, 0u);
|
||||
for (std::size_t i = layout.SymOffset; i < symCount; ++i) {
|
||||
const std::uint32_t h = hashes[i];
|
||||
const std::uint32_t wordIndex = (h / 64u) % layout.BloomSize;
|
||||
const std::uint32_t bit1 = h % 64u;
|
||||
const std::uint32_t bit2 = (h >> layout.BloomShift) % 64u;
|
||||
bloom[wordIndex] |= (std::uint64_t{1} << bit1);
|
||||
bloom[wordIndex] |= (std::uint64_t{1} << bit2);
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> buckets(layout.NBuckets, 0u);
|
||||
std::vector<std::uint32_t> chain(chainCount, 0u);
|
||||
|
||||
for (std::size_t i = layout.SymOffset; i < symCount; ++i) {
|
||||
const std::uint32_t bucketIndex = hashes[i] % layout.NBuckets;
|
||||
if (buckets[bucketIndex] == 0u)
|
||||
buckets[bucketIndex] = static_cast<std::uint32_t>(i);
|
||||
}
|
||||
|
||||
for (std::size_t i = layout.SymOffset; i < symCount; ++i) {
|
||||
const std::uint32_t bucketIndex = hashes[i] % layout.NBuckets;
|
||||
const bool isLastInBucket = (i + 1u == symCount) || (hashes[i + 1u] % layout.NBuckets != bucketIndex);
|
||||
chain[i - layout.SymOffset] = isLastInBucket ? (hashes[i] | 1u) : (hashes[i] & ~std::uint32_t{1});
|
||||
}
|
||||
|
||||
for (std::uint32_t bloomIndex = 0u; bloomIndex < layout.BloomSize; ++bloomIndex)
|
||||
Write(elf, layout.BloomOffset + bloomIndex * 8u, bloom[bloomIndex]);
|
||||
|
||||
for (std::uint32_t bucketIndex = 0u; bucketIndex < layout.NBuckets; ++bucketIndex)
|
||||
Write(elf, layout.BucketsOffset + bucketIndex * 4u, buckets[bucketIndex]);
|
||||
|
||||
for (std::size_t i = 0u; i < chainCount; ++i)
|
||||
Write(elf, layout.ChainOffset + i * 4u, chain[i]);
|
||||
|
||||
if (requiredSize < sectionSize)
|
||||
std::memset(elf.data() + sectionOffset + requiredSize, 0, sectionSize - requiredSize);
|
||||
}
|
||||
|
||||
void RemapDynamicNeededOffsets(
|
||||
std::vector<std::uint8_t>& elf,
|
||||
const Elf64_Ehdr& ehdr,
|
||||
const std::vector<std::pair<std::uint32_t, std::uint32_t>>& oldToNewOffset
|
||||
) {
|
||||
using namespace Internal;
|
||||
|
||||
for (std::uint16_t i = 0u; i < ehdr.e_shnum; ++i) {
|
||||
const std::size_t shOffset = static_cast<std::size_t>(ehdr.e_shoff) + i * sizeof(Elf64_Shdr);
|
||||
const auto shdr = Read<Elf64_Shdr>(elf, shOffset);
|
||||
if (shdr.sh_type != kShtDynamic) continue;
|
||||
|
||||
const std::size_t dynOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
const std::size_t dynCount = static_cast<std::size_t>(shdr.sh_size) / sizeof(Elf64_Dyn);
|
||||
|
||||
for (std::size_t d = 0u; d < dynCount; ++d) {
|
||||
const std::size_t entryOffset = dynOffset + d * sizeof(Elf64_Dyn);
|
||||
const auto dyn = Read<Elf64_Dyn>(elf, entryOffset);
|
||||
if (!IsDynamicNameTag(dyn.d_tag)) continue;
|
||||
|
||||
const auto oldNameOffset = static_cast<std::uint32_t>(dyn.d_val);
|
||||
const auto mapped = std::find_if(
|
||||
oldToNewOffset.begin(), oldToNewOffset.end(),
|
||||
[&](const auto& entry) { return entry.first == oldNameOffset; }
|
||||
);
|
||||
if (mapped == oldToNewOffset.end()) continue;
|
||||
|
||||
Write(elf, entryOffset + offsetof(Elf64_Dyn, d_val), static_cast<std::uint64_t>(mapped->second));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct VersionNameField {
|
||||
std::size_t Offset;
|
||||
std::uint32_t Name;
|
||||
};
|
||||
|
||||
std::vector<VersionNameField> ReadVersionNameFields(const std::vector<std::uint8_t>& elf, const Elf64_Ehdr& ehdr) {
|
||||
using namespace Internal;
|
||||
std::vector<VersionNameField> fields;
|
||||
for (std::uint16_t i = 0u; i < ehdr.e_shnum; ++i) {
|
||||
const auto section = Read<Elf64_Shdr>(elf, static_cast<std::size_t>(ehdr.e_shoff) + i * sizeof(Elf64_Shdr));
|
||||
if (section.sh_type != kShtGnuVerneed || section.sh_size == 0u) continue;
|
||||
if (section.sh_offset > elf.size() || section.sh_size > elf.size() - section.sh_offset)
|
||||
throw std::runtime_error("invalid .gnu.version_r section range");
|
||||
const auto location = [&](std::uint64_t relative, std::size_t size) {
|
||||
if (relative > section.sh_size || size > section.sh_size - relative)
|
||||
throw std::runtime_error(".gnu.version_r record outside section");
|
||||
return static_cast<std::size_t>(section.sh_offset + relative);
|
||||
};
|
||||
const auto advance = [&](std::uint64_t current, std::uint32_t step, std::size_t size) {
|
||||
if (step < size || step > section.sh_size - current)
|
||||
throw std::runtime_error("invalid .gnu.version_r record link");
|
||||
return current + step;
|
||||
};
|
||||
std::uint64_t current = 0u;
|
||||
while (true) {
|
||||
const auto offset = location(current, sizeof(Elf64_Verneed));
|
||||
const auto need = Read<Elf64_Verneed>(elf, offset);
|
||||
if (need.vn_version != 1u) throw std::runtime_error("unsupported .gnu.version_r structure version");
|
||||
fields.push_back({offset + offsetof(Elf64_Verneed, vn_file), need.vn_file});
|
||||
if (need.vn_cnt != 0u) {
|
||||
auto auxiliary = advance(current, need.vn_aux, sizeof(Elf64_Verneed));
|
||||
for (std::uint16_t index = 0u; index < need.vn_cnt; ++index) {
|
||||
const auto auxOffset = location(auxiliary, sizeof(Elf64_Vernaux));
|
||||
const auto aux = Read<Elf64_Vernaux>(elf, auxOffset);
|
||||
fields.push_back({auxOffset + offsetof(Elf64_Vernaux, vna_name), aux.vna_name});
|
||||
if (index + 1u == need.vn_cnt) {
|
||||
if (aux.vna_next != 0u) throw std::runtime_error(".gnu.version_r auxiliary count mismatch");
|
||||
} else {
|
||||
auxiliary = advance(auxiliary, aux.vna_next, sizeof(Elf64_Vernaux));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (need.vn_next == 0u) break;
|
||||
current = advance(current, need.vn_next, sizeof(Elf64_Verneed));
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
void RemapVerneedOffsets(
|
||||
std::vector<std::uint8_t>& elf,
|
||||
const Elf64_Ehdr& ehdr,
|
||||
const std::vector<std::pair<std::uint32_t, std::uint32_t>>& oldToNewOffset
|
||||
) {
|
||||
using namespace Internal;
|
||||
for (const auto& field : ReadVersionNameFields(elf, ehdr)) {
|
||||
const auto mapped = std::find_if(oldToNewOffset.begin(), oldToNewOffset.end(),
|
||||
[&](const auto& entry) { return entry.first == field.Name; });
|
||||
if (mapped != oldToNewOffset.end()) Write(elf, field.Offset, mapped->second);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> CollectDynamicNameOffsets(const std::vector<std::uint8_t>& elf, const Elf64_Ehdr& ehdr) {
|
||||
using namespace Internal;
|
||||
|
||||
std::vector<std::uint32_t> offsets;
|
||||
|
||||
for (std::uint16_t i = 0u; i < ehdr.e_shnum; ++i) {
|
||||
const std::size_t shOffset = static_cast<std::size_t>(ehdr.e_shoff) + i * sizeof(Elf64_Shdr);
|
||||
const auto shdr = Read<Elf64_Shdr>(elf, shOffset);
|
||||
if (shdr.sh_type != kShtDynamic) continue;
|
||||
|
||||
const std::size_t dynOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
const std::size_t dynCount = static_cast<std::size_t>(shdr.sh_size) / sizeof(Elf64_Dyn);
|
||||
|
||||
for (std::size_t d = 0u; d < dynCount; ++d) {
|
||||
const auto dyn = Read<Elf64_Dyn>(elf, dynOffset + d * sizeof(Elf64_Dyn));
|
||||
if (dyn.d_tag == kDtNull) break;
|
||||
if (!IsDynamicNameTag(dyn.d_tag)) continue;
|
||||
offsets.push_back(static_cast<std::uint32_t>(dyn.d_val));
|
||||
}
|
||||
}
|
||||
|
||||
return offsets;
|
||||
}
|
||||
|
||||
std::vector<std::uint32_t> CollectVerneedNameOffsets(const std::vector<std::uint8_t>& elf, const Elf64_Ehdr& ehdr) {
|
||||
std::vector<std::uint32_t> offsets;
|
||||
for (const auto& field : ReadVersionNameFields(elf, ehdr)) offsets.push_back(field.Name);
|
||||
return offsets;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void ElfNidPatcher::PatchNids(std::vector<std::uint8_t>& elf, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const {
|
||||
using namespace Internal;
|
||||
|
||||
if (elf.size() < sizeof(Elf64_Ehdr)) throw std::runtime_error("file too small");
|
||||
if (elf[4] != 2) throw std::runtime_error("not ELF64");
|
||||
|
||||
const auto ehdr = Read<Elf64_Ehdr>(elf, 0u);
|
||||
if (ehdr.e_ident[5] != 1 || ehdr.e_shentsize != sizeof(Elf64_Shdr))
|
||||
throw std::runtime_error("unsupported ELF byte order or section header size");
|
||||
RequireElfRange(elf, ehdr.e_shoff, std::uint64_t{ehdr.e_shnum} * sizeof(Elf64_Shdr), "section table");
|
||||
|
||||
std::size_t dynSymOffset = 0u, dynSymSize = 0u;
|
||||
std::size_t gnuHashOffset = 0u, gnuHashSize = 0u;
|
||||
std::size_t sysvHashOffset = 0u, sysvHashSize = 0u;
|
||||
std::uint32_t sysvHashLink = 0u;
|
||||
std::size_t versymOffset = 0u;
|
||||
std::uint32_t dynSymSectionIndex = 0u;
|
||||
std::uint32_t gnuHashSymOffset = 0u;
|
||||
for (std::uint16_t i = 0u; i < ehdr.e_shnum; ++i) {
|
||||
const std::size_t shOffset = static_cast<std::size_t>(ehdr.e_shoff) + i * sizeof(Elf64_Shdr);
|
||||
const auto shdr = Read<Elf64_Shdr>(elf, shOffset);
|
||||
if (shdr.sh_type == kShtDynsym) {
|
||||
if (shdr.sh_entsize != sizeof(Elf64_Sym) || shdr.sh_size % sizeof(Elf64_Sym) || shdr.sh_link >= ehdr.e_shnum)
|
||||
throw std::runtime_error("invalid ELF dynsym layout");
|
||||
RequireElfRange(elf, shdr.sh_offset, shdr.sh_size, "dynsym");
|
||||
dynSymOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
dynSymSize = static_cast<std::size_t>(shdr.sh_size);
|
||||
dynSymSectionIndex = i;
|
||||
}
|
||||
if (shdr.sh_type == kShtGnuHash) {
|
||||
gnuHashOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
gnuHashSize = static_cast<std::size_t>(shdr.sh_size);
|
||||
}
|
||||
if (shdr.sh_type == kShtHash) {
|
||||
sysvHashOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
sysvHashSize = static_cast<std::size_t>(shdr.sh_size);
|
||||
sysvHashLink = shdr.sh_link;
|
||||
}
|
||||
if (shdr.sh_type == kShtGnuVersym)
|
||||
versymOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
if (shdr.sh_type == kShtGnuVerdef)
|
||||
throw std::runtime_error("unsupported .gnu.version_d section: symbol version definitions cannot be preserved");
|
||||
}
|
||||
|
||||
if (dynSymOffset == 0u) throw std::runtime_error("no .dynsym section");
|
||||
|
||||
const std::size_t symCount = dynSymSize / sizeof(Elf64_Sym);
|
||||
if (symCount == 0u) throw std::runtime_error(".dynsym is empty");
|
||||
if (sysvHashOffset != 0u) {
|
||||
if (sysvHashLink != dynSymSectionIndex) throw std::runtime_error("invalid ELF hash symbol table link");
|
||||
ValidateSysvHash(elf, sysvHashOffset, sysvHashSize, symCount);
|
||||
}
|
||||
if (gnuHashOffset != 0u) {
|
||||
ValidateGnuHash(elf, gnuHashOffset, gnuHashSize, symCount);
|
||||
gnuHashSymOffset = Read<std::uint32_t>(elf, gnuHashOffset + 4u);
|
||||
}
|
||||
|
||||
const std::size_t dynStrSectionLink = [&]() -> std::size_t {
|
||||
for (std::uint16_t i = 0u; i < ehdr.e_shnum; ++i) {
|
||||
const std::size_t shOffset = static_cast<std::size_t>(ehdr.e_shoff) + i * sizeof(Elf64_Shdr);
|
||||
const auto shdr = Read<Elf64_Shdr>(elf, shOffset);
|
||||
if (shdr.sh_type == kShtDynsym) return static_cast<std::size_t>(shdr.sh_link);
|
||||
}
|
||||
throw std::runtime_error("cannot find dynsym sh_link");
|
||||
}();
|
||||
|
||||
std::size_t dynStrOffset = 0u, dynStrSize = 0u;
|
||||
{
|
||||
const std::size_t shOffset = static_cast<std::size_t>(ehdr.e_shoff) + dynStrSectionLink * sizeof(Elf64_Shdr);
|
||||
const auto shdr = Read<Elf64_Shdr>(elf, shOffset);
|
||||
if (shdr.sh_type != 3) throw std::runtime_error("invalid ELF dynstr section type");
|
||||
RequireElfRange(elf, shdr.sh_offset, shdr.sh_size, "dynstr");
|
||||
dynStrOffset = static_cast<std::size_t>(shdr.sh_offset);
|
||||
dynStrSize = static_cast<std::size_t>(shdr.sh_size);
|
||||
}
|
||||
|
||||
if (dynStrOffset == 0u) throw std::runtime_error("no .dynstr section");
|
||||
|
||||
const std::vector<std::uint8_t> origDynStr(
|
||||
elf.begin() + static_cast<std::ptrdiff_t>(dynStrOffset),
|
||||
elf.begin() + static_cast<std::ptrdiff_t>(dynStrOffset + dynStrSize)
|
||||
);
|
||||
|
||||
std::vector<std::string> exportedNames;
|
||||
for (std::size_t i = 1u; i < symCount; ++i) {
|
||||
const std::size_t symOffset = dynSymOffset + i * sizeof(Elf64_Sym);
|
||||
const auto sym = Read<Elf64_Sym>(elf, symOffset);
|
||||
if (sym.st_name == 0u) continue;
|
||||
const std::uint8_t binding = sym.st_info >> 4u;
|
||||
if (binding == kStbLocal || sym.st_shndx == kShnUndef) continue;
|
||||
const std::string symName = ReadCStr(origDynStr, sym.st_name);
|
||||
if (symName.empty()) continue;
|
||||
exportedNames.push_back(symName);
|
||||
}
|
||||
|
||||
const auto nidMap = ResolveNids(exportedNames, libraryName, excludedExports);
|
||||
|
||||
struct SymbolNameUse {
|
||||
std::size_t symIndex;
|
||||
std::uint32_t oldNameOffset;
|
||||
std::string newValue;
|
||||
};
|
||||
|
||||
std::vector<SymbolNameUse> uses;
|
||||
std::unordered_map<std::string, std::pair<std::uint64_t, std::uint16_t>> patchedExports;
|
||||
for (std::size_t i = 1u; i < symCount; ++i) {
|
||||
const std::size_t symOffset = dynSymOffset + i * sizeof(Elf64_Sym);
|
||||
const auto sym = Read<Elf64_Sym>(elf, symOffset);
|
||||
if (sym.st_name == 0u) continue;
|
||||
|
||||
const std::uint8_t binding = sym.st_info >> 4u;
|
||||
const bool isPatchable = binding != kStbLocal && sym.st_shndx != kShnUndef;
|
||||
|
||||
const std::string symName = ReadCStr(origDynStr, sym.st_name);
|
||||
if (symName.empty()) continue;
|
||||
|
||||
std::string newValue = symName;
|
||||
if (isPatchable) {
|
||||
const auto it = nidMap.find(symName);
|
||||
if (it != nidMap.end())
|
||||
newValue = it->second;
|
||||
const auto [existing, inserted] = patchedExports.try_emplace(newValue, sym.st_value, sym.st_shndx);
|
||||
if (!inserted && existing->second != std::pair{sym.st_value, sym.st_shndx})
|
||||
throw std::runtime_error("duplicate patched export name: " + newValue);
|
||||
} else if (binding != kStbLocal && sym.st_shndx == kShnUndef) {
|
||||
const bool isUnversioned = versymOffset == 0u ||
|
||||
(Read<std::uint16_t>(elf, versymOffset + i * sizeof(std::uint16_t)) <= 1u);
|
||||
const bool hasNidPostfix = symName.size() >= kNidPostfixLen &&
|
||||
symName.compare(symName.size() - kNidPostfixLen, kNidPostfixLen, kNidPostfix) == 0;
|
||||
const bool hasScePrefix = symName.size() >= 3u &&
|
||||
std::tolower(static_cast<unsigned char>(symName[0])) == 's' &&
|
||||
std::tolower(static_cast<unsigned char>(symName[1])) == 'c' &&
|
||||
std::tolower(static_cast<unsigned char>(symName[2])) == 'e';
|
||||
if (isUnversioned && (hasNidPostfix || hasScePrefix))
|
||||
newValue = ResolveOneName(symName);
|
||||
}
|
||||
|
||||
uses.push_back(SymbolNameUse{i, sym.st_name, newValue});
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::uint32_t, std::string>> names;
|
||||
const auto addName = [&](std::uint32_t oldOffset, std::string value) {
|
||||
const auto existing = std::find_if(
|
||||
names.begin(), names.end(),
|
||||
[&](const auto& entry) { return entry.first == oldOffset && entry.second == value; }
|
||||
);
|
||||
if (existing == names.end()) names.emplace_back(oldOffset, std::move(value));
|
||||
};
|
||||
for (const auto& use : uses) addName(use.oldNameOffset, use.newValue);
|
||||
|
||||
std::vector<std::uint32_t> preservedOffsets = CollectDynamicNameOffsets(elf, ehdr);
|
||||
const std::vector<std::uint32_t> verneedOffsets = CollectVerneedNameOffsets(elf, ehdr);
|
||||
preservedOffsets.insert(preservedOffsets.end(), verneedOffsets.begin(), verneedOffsets.end());
|
||||
for (const auto oldOffset : preservedOffsets) addName(oldOffset, ReadCStr(origDynStr, oldOffset));
|
||||
|
||||
std::vector<std::string> values;
|
||||
for (const auto& name : names) values.push_back(name.second);
|
||||
std::sort(values.begin(), values.end(), [](const std::string& left, const std::string& right) {
|
||||
return std::lexicographical_compare(right.rbegin(), right.rend(), left.rbegin(), left.rend());
|
||||
});
|
||||
values.erase(std::unique(values.begin(), values.end()), values.end());
|
||||
|
||||
std::vector<std::uint8_t> newDynStr;
|
||||
newDynStr.push_back(0u);
|
||||
std::unordered_map<std::string, std::uint32_t> valueOffsets;
|
||||
const std::string* previous = nullptr;
|
||||
std::uint32_t previousOffset = 0u;
|
||||
for (const auto& value : values) {
|
||||
if (previous && previous->size() >= value.size() &&
|
||||
previous->compare(previous->size() - value.size(), value.size(), value) == 0) {
|
||||
valueOffsets.emplace(value, previousOffset + static_cast<std::uint32_t>(previous->size() - value.size()));
|
||||
continue;
|
||||
}
|
||||
previousOffset = static_cast<std::uint32_t>(newDynStr.size());
|
||||
previous = &value;
|
||||
valueOffsets.emplace(value, previousOffset);
|
||||
newDynStr.insert(newDynStr.end(), value.begin(), value.end());
|
||||
newDynStr.push_back(0u);
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::uint32_t, std::uint32_t>> preservedToNewOffset;
|
||||
for (const auto offset : preservedOffsets)
|
||||
preservedToNewOffset.emplace_back(offset, valueOffsets.at(ReadCStr(origDynStr, offset)));
|
||||
|
||||
if (newDynStr.size() > dynStrSize) {
|
||||
throw std::runtime_error(
|
||||
"rebuilt .dynstr (" + std::to_string(newDynStr.size()) + " bytes) exceeds original section size (" +
|
||||
std::to_string(dynStrSize) + " bytes) - relinking with a larger section is required"
|
||||
);
|
||||
}
|
||||
newDynStr.resize(dynStrSize, 0u);
|
||||
|
||||
std::vector<std::string> newSymbolNames(symCount);
|
||||
for (const auto& use : uses) {
|
||||
newSymbolNames[use.symIndex] = use.newValue;
|
||||
Write(elf, dynSymOffset + use.symIndex * sizeof(Elf64_Sym) + offsetof(Elf64_Sym, st_name), valueOffsets.at(use.newValue));
|
||||
}
|
||||
|
||||
std::memcpy(elf.data() + dynStrOffset, newDynStr.data(), newDynStr.size());
|
||||
|
||||
RemapDynamicNeededOffsets(elf, ehdr, preservedToNewOffset);
|
||||
RemapVerneedOffsets(elf, ehdr, preservedToNewOffset);
|
||||
|
||||
if (gnuHashOffset != 0u) {
|
||||
const auto bucketCount = Read<std::uint32_t>(elf, gnuHashOffset);
|
||||
std::vector<std::uint32_t> oldToNewIndex(symCount);
|
||||
ReorderDynSymForGnuHash(elf, dynSymOffset, symCount, gnuHashSymOffset, bucketCount, newSymbolNames, oldToNewIndex);
|
||||
FixupRelocationSymbolIndices(elf, ehdr, dynSymSectionIndex, oldToNewIndex);
|
||||
RebuildGnuHash(elf, gnuHashOffset, gnuHashSize, symCount, newSymbolNames);
|
||||
}
|
||||
if (sysvHashOffset != 0u) RebuildSysvHash(elf, sysvHashOffset, newSymbolNames);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,204 +0,0 @@
|
||||
#include <nid/ExportExclusions.hpp>
|
||||
#include <nid/ElfPatcher.hpp>
|
||||
#include <nid/PeNidPatcher.hpp>
|
||||
#include <nid/MachONidPatcher.hpp>
|
||||
#include <nid/NidPatcherUtils.hpp>
|
||||
#include <nid/NativePath.hpp>
|
||||
#include <algorithm>
|
||||
#include <bit>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
namespace {
|
||||
|
||||
void RequireRange(const std::vector<std::uint8_t>& binary, std::uint64_t offset, std::uint64_t size) {
|
||||
if (offset > binary.size() || size > binary.size() - offset) throw std::runtime_error("export reference range out of bounds");
|
||||
}
|
||||
|
||||
template<typename TValue>
|
||||
TValue ReadValue(const std::vector<std::uint8_t>& binary, std::uint64_t offset) {
|
||||
RequireRange(binary, offset, sizeof(TValue));
|
||||
TValue value;
|
||||
std::memcpy(&value, binary.data() + offset, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
std::string ReadName(const std::vector<std::uint8_t>& binary, std::uint64_t offset, std::uint64_t size) {
|
||||
RequireRange(binary, offset, size);
|
||||
if (size == 0) throw std::runtime_error("empty export reference name range");
|
||||
const auto start = reinterpret_cast<const char*>(binary.data() + offset);
|
||||
const auto end = static_cast<const char*>(std::memchr(start, 0, size));
|
||||
if (!end || end == start) throw std::runtime_error("invalid export reference name");
|
||||
return {start, end};
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> ReadPeExports(const std::vector<std::uint8_t>& binary) {
|
||||
const std::uint64_t header = ReadValue<std::uint32_t>(binary, 0x3c);
|
||||
if (ReadValue<std::uint32_t>(binary, header) != 0x4550) throw std::runtime_error("invalid reference PE signature");
|
||||
const auto sectionCount = ReadValue<std::uint16_t>(binary, header + 6);
|
||||
const auto optionalSize = ReadValue<std::uint16_t>(binary, header + 20);
|
||||
const auto optional = header + 24;
|
||||
RequireRange(binary, optional, optionalSize);
|
||||
const auto magic = ReadValue<std::uint16_t>(binary, optional);
|
||||
if (magic != 0x20b && magic != 0x10b) throw std::runtime_error("unsupported reference PE optional header");
|
||||
const std::uint64_t directoryOffset = magic == 0x20b ? 112 : 96;
|
||||
if (optionalSize < directoryOffset + sizeof(PeDataDirectory)) throw std::runtime_error("missing reference PE export directory");
|
||||
if (ReadValue<std::uint32_t>(binary, optional + directoryOffset - 4) == 0) throw std::runtime_error("missing reference PE data directories");
|
||||
const auto directory = ReadValue<PeDataDirectory>(binary, optional + directoryOffset);
|
||||
if (!directory.VirtualAddress || directory.Size < sizeof(PeExportDirectory)) throw std::runtime_error("missing reference PE exports");
|
||||
const auto sections = optional + optionalSize;
|
||||
RequireRange(binary, sections, std::uint64_t{sectionCount} * sizeof(PeSectionHeader));
|
||||
const auto headersSize = ReadValue<std::uint32_t>(binary, optional + 60);
|
||||
const auto mapRva = [&](std::uint32_t rva, std::uint64_t size) -> std::uint64_t {
|
||||
if (rva < headersSize && size <= headersSize - rva) {
|
||||
RequireRange(binary, rva, size);
|
||||
return rva;
|
||||
}
|
||||
for (std::uint16_t index = 0; index < sectionCount; ++index) {
|
||||
const auto section = ReadValue<PeSectionHeader>(binary, sections + std::uint64_t{index} * sizeof(PeSectionHeader));
|
||||
if (rva < section.VirtualAddress) continue;
|
||||
const std::uint64_t relative = rva - section.VirtualAddress;
|
||||
if (relative >= section.SizeOfRawData || size > section.SizeOfRawData - relative) continue;
|
||||
const auto offset = std::uint64_t{section.PointerToRawData} + relative;
|
||||
RequireRange(binary, offset, size);
|
||||
return offset;
|
||||
}
|
||||
throw std::runtime_error("unmapped reference PE export RVA");
|
||||
};
|
||||
const auto table = ReadValue<PeExportDirectory>(binary, mapRva(directory.VirtualAddress, sizeof(PeExportDirectory)));
|
||||
if (!table.NumberOfNames) throw std::runtime_error("reference PE has no named exports");
|
||||
const auto names = mapRva(table.AddressOfNames, std::uint64_t{table.NumberOfNames} * 4);
|
||||
const auto ordinals = mapRva(table.AddressOfNameOrdinals, std::uint64_t{table.NumberOfNames} * 2);
|
||||
const auto functions = mapRva(table.AddressOfFunctions, std::uint64_t{table.NumberOfFunctions} * 4);
|
||||
std::unordered_set<std::string> result;
|
||||
for (std::uint32_t index = 0; index < table.NumberOfNames; ++index) {
|
||||
const auto ordinal = ReadValue<std::uint16_t>(binary, ordinals + std::uint64_t{index} * 2);
|
||||
if (ordinal >= table.NumberOfFunctions) throw std::runtime_error("invalid reference PE export ordinal");
|
||||
if (!ReadValue<std::uint32_t>(binary, functions + std::uint64_t{ordinal} * 4)) continue;
|
||||
const auto rva = ReadValue<std::uint32_t>(binary, names + std::uint64_t{index} * 4);
|
||||
const auto offset = mapRva(rva, 1);
|
||||
auto name = ReadName(binary, offset, binary.size() - offset);
|
||||
mapRva(rva, name.size() + 1);
|
||||
if (!result.insert(name).second) throw std::runtime_error("duplicate reference export: " + name);
|
||||
}
|
||||
if (result.empty()) throw std::runtime_error("reference PE has no named exports");
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> ReadElfExports(const std::vector<std::uint8_t>& binary) {
|
||||
const auto header = ReadValue<Elf64_Ehdr>(binary, 0);
|
||||
if (header.e_ident[4] != 2 || header.e_ident[5] != 1 || header.e_shentsize != sizeof(Elf64_Shdr)) throw std::runtime_error("unsupported reference ELF layout");
|
||||
RequireRange(binary, header.e_shoff, std::uint64_t{header.e_shnum} * sizeof(Elf64_Shdr));
|
||||
std::unordered_set<std::string> result;
|
||||
for (std::uint16_t index = 0; index < header.e_shnum; ++index) {
|
||||
const auto section = ReadValue<Elf64_Shdr>(binary, header.e_shoff + std::uint64_t{index} * sizeof(Elf64_Shdr));
|
||||
if (section.sh_type != kShtDynsym) continue;
|
||||
if (section.sh_entsize != sizeof(Elf64_Sym) || section.sh_size % sizeof(Elf64_Sym) || section.sh_link >= header.e_shnum) throw std::runtime_error("invalid reference ELF symbol table");
|
||||
RequireRange(binary, section.sh_offset, section.sh_size);
|
||||
const auto strings = ReadValue<Elf64_Shdr>(binary, header.e_shoff + std::uint64_t{section.sh_link} * sizeof(Elf64_Shdr));
|
||||
if (strings.sh_type != 3) throw std::runtime_error("invalid reference ELF string table");
|
||||
RequireRange(binary, strings.sh_offset, strings.sh_size);
|
||||
for (std::uint64_t offset = 0; offset < section.sh_size; offset += sizeof(Elf64_Sym)) {
|
||||
const auto symbol = ReadValue<Elf64_Sym>(binary, section.sh_offset + offset);
|
||||
const auto binding = symbol.st_info >> 4;
|
||||
const auto visibility = symbol.st_other & 3;
|
||||
if (symbol.st_shndx == kShnUndef || (binding != 1 && binding != 2 && binding != 10) || (visibility != 0 && visibility != 3)) continue;
|
||||
if (symbol.st_name >= strings.sh_size) throw std::runtime_error("invalid reference ELF export name");
|
||||
result.insert(ReadName(binary, strings.sh_offset + symbol.st_name, strings.sh_size - symbol.st_name));
|
||||
}
|
||||
}
|
||||
if (result.empty()) throw std::runtime_error("reference ELF has no exports");
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string ReadText(const std::string& path, std::ifstream& input) {
|
||||
std::string text{std::istreambuf_iterator<char>(input), {}};
|
||||
if (input.bad()) throw std::runtime_error("cannot read export list: " + path);
|
||||
return text;
|
||||
}
|
||||
|
||||
std::string FormatExportList(const std::unordered_set<std::string>& exports) {
|
||||
std::vector<std::string> names(exports.begin(), exports.end());
|
||||
std::ranges::sort(names);
|
||||
std::string text;
|
||||
for (const auto& name : names) {
|
||||
if (name.find('\n') != std::string::npos) throw std::runtime_error("export name contains a line break: " + name);
|
||||
text += name;
|
||||
text += '\n';
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::string NormalizeExportName(const std::string& name) {
|
||||
if (name.ends_with(Internal::kNidPostfix)) return name.substr(0, name.size() - Internal::kNidPostfixLen);
|
||||
return name;
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> ReadExportExclusions(const std::string& path) {
|
||||
if constexpr (std::endian::native != std::endian::little) throw std::runtime_error("export references require a little-endian host");
|
||||
std::ifstream input(Internal::NativePath(path), std::ios::binary | std::ios::ate);
|
||||
if (!input) throw std::runtime_error("cannot open export reference: " + path);
|
||||
const auto size = input.tellg();
|
||||
if (size <= 0) throw std::runtime_error("empty or unreadable export reference: " + path);
|
||||
std::vector<std::uint8_t> binary(static_cast<std::size_t>(size));
|
||||
input.seekg(0);
|
||||
if (!input.read(reinterpret_cast<char*>(binary.data()), static_cast<std::streamsize>(binary.size()))) throw std::runtime_error("cannot read export reference: " + path);
|
||||
std::unordered_set<std::string> exports;
|
||||
if (binary.size() >= 2 && binary[0] == 'M' && binary[1] == 'Z') {
|
||||
exports = ReadPeExports(binary);
|
||||
} else if (binary.size() >= 4 && binary[0] == 0x7f && binary[1] == 'E' && binary[2] == 'L' && binary[3] == 'F') {
|
||||
exports = ReadElfExports(binary);
|
||||
} else if (binary.size() >= 4 && binary[0] == 0xcf && binary[1] == 0xfa && binary[2] == 0xed && binary[3] == 0xfe) {
|
||||
for (const auto& entry : ReadMachOExports(binary)) {
|
||||
if (entry.Name.size() < 2 || entry.Name[0] != '_') throw std::runtime_error("invalid reference Mach-O export: " + entry.Name);
|
||||
if (!exports.insert(entry.Name.substr(1)).second) throw std::runtime_error("duplicate reference export: " + entry.Name);
|
||||
}
|
||||
if (exports.empty()) throw std::runtime_error("reference Mach-O has no exports");
|
||||
} else {
|
||||
throw std::runtime_error("unrecognized export reference format: " + path);
|
||||
}
|
||||
std::unordered_set<std::string> result;
|
||||
result.reserve(exports.size());
|
||||
for (const auto& name : exports) {
|
||||
auto normalized = NormalizeExportName(name);
|
||||
if (normalized.empty()) throw std::runtime_error("empty normalized export reference name");
|
||||
result.insert(std::move(normalized));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::unordered_set<std::string> ReadExportList(const std::string& path) {
|
||||
std::ifstream input(path, std::ios::binary);
|
||||
if (!input) throw std::runtime_error("cannot open export list: " + path);
|
||||
const auto text = ReadText(path, input);
|
||||
if (text.empty() || text.back() != '\n') throw std::runtime_error("malformed export list: " + path);
|
||||
std::unordered_set<std::string> result;
|
||||
for (std::size_t start = 0; start < text.size();) {
|
||||
const auto end = text.find('\n', start);
|
||||
if (end == start) throw std::runtime_error("empty name in export list: " + path);
|
||||
auto name = text.substr(start, end - start);
|
||||
if (!result.insert(name).second) throw std::runtime_error("duplicate name in export list: " + name);
|
||||
start = end + 1;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool WriteExportList(const std::string& referencePath, const std::string& path) {
|
||||
const auto text = FormatExportList(ReadExportExclusions(referencePath));
|
||||
if (std::ifstream existing(path, std::ios::binary); existing && ReadText(path, existing) == text) return false;
|
||||
std::ofstream output(path, std::ios::binary | std::ios::trunc);
|
||||
if (!output) throw std::runtime_error("cannot write export list: " + path);
|
||||
output.write(text.data(), static_cast<std::streamsize>(text.size()));
|
||||
output.close();
|
||||
if (!output) throw std::runtime_error("cannot write export list: " + path);
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,493 +0,0 @@
|
||||
#include <nid/MachONidPatcher.hpp>
|
||||
#include <nid/NidResolver.hpp>
|
||||
#include <nid/NidPatcherUtils.hpp>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
namespace {
|
||||
|
||||
using Internal::Read;
|
||||
using Internal::Write;
|
||||
|
||||
constexpr std::uint32_t kLcSegment64 = 0x19;
|
||||
constexpr std::uint32_t kLcCodeSignature = 0x1d;
|
||||
constexpr std::uint32_t kLcDyldInfo = 0x22;
|
||||
constexpr std::uint32_t kLcDyldInfoOnly = 0x80000022u;
|
||||
constexpr std::uint32_t kLcDyldExportsTrie = 0x80000033u;
|
||||
constexpr std::uint32_t kLcDyldChainedFixups = 0x80000034u;
|
||||
constexpr std::uint32_t kLcLoadDylib = 0x0c;
|
||||
constexpr std::uint32_t kLcLoadWeakDylib = 0x80000018u;
|
||||
constexpr std::uint32_t kLcReexportDylib = 0x8000001fu;
|
||||
constexpr std::uint32_t kLcLazyLoadDylib = 0x20;
|
||||
constexpr std::uint32_t kLcLoadUpwardDylib = 0x80000023u;
|
||||
|
||||
constexpr std::uint64_t kExportWeakDefinition = 0x04;
|
||||
constexpr std::uint64_t kExportReexport = 0x08;
|
||||
constexpr std::uint64_t kExportStubAndResolver = 0x10;
|
||||
|
||||
constexpr std::uint32_t kImportFormatPlain = 1;
|
||||
constexpr std::uint32_t kImportFormatAddend = 2;
|
||||
constexpr std::uint32_t kImportFormatAddend64 = 3;
|
||||
|
||||
constexpr std::uint64_t kPageSize = 0x1000;
|
||||
|
||||
struct MachHeader64 {
|
||||
std::uint32_t Magic;
|
||||
std::uint32_t CpuType;
|
||||
std::uint32_t CpuSubtype;
|
||||
std::uint32_t FileType;
|
||||
std::uint32_t CommandCount;
|
||||
std::uint32_t CommandBytes;
|
||||
std::uint32_t Flags;
|
||||
std::uint32_t Reserved;
|
||||
};
|
||||
|
||||
struct LoadCommand {
|
||||
std::uint32_t Cmd;
|
||||
std::uint32_t Size;
|
||||
};
|
||||
|
||||
struct SegmentCommand64 {
|
||||
std::uint32_t Cmd;
|
||||
std::uint32_t Size;
|
||||
char Name[16];
|
||||
std::uint64_t VmAddress;
|
||||
std::uint64_t VmSize;
|
||||
std::uint64_t FileOffset;
|
||||
std::uint64_t FileSize;
|
||||
std::uint32_t MaxProtection;
|
||||
std::uint32_t InitProtection;
|
||||
std::uint32_t SectionCount;
|
||||
std::uint32_t Flags;
|
||||
};
|
||||
|
||||
struct LinkeditDataCommand {
|
||||
std::uint32_t Cmd;
|
||||
std::uint32_t Size;
|
||||
std::uint32_t DataOffset;
|
||||
std::uint32_t DataSize;
|
||||
};
|
||||
|
||||
struct DyldInfoCommand {
|
||||
std::uint32_t Cmd;
|
||||
std::uint32_t Size;
|
||||
std::uint32_t RebaseOffset;
|
||||
std::uint32_t RebaseSize;
|
||||
std::uint32_t BindOffset;
|
||||
std::uint32_t BindSize;
|
||||
std::uint32_t WeakBindOffset;
|
||||
std::uint32_t WeakBindSize;
|
||||
std::uint32_t LazyBindOffset;
|
||||
std::uint32_t LazyBindSize;
|
||||
std::uint32_t ExportOffset;
|
||||
std::uint32_t ExportSize;
|
||||
};
|
||||
|
||||
struct ChainedFixupsHeader {
|
||||
std::uint32_t Version;
|
||||
std::uint32_t StartsOffset;
|
||||
std::uint32_t ImportsOffset;
|
||||
std::uint32_t SymbolsOffset;
|
||||
std::uint32_t ImportsCount;
|
||||
std::uint32_t ImportsFormat;
|
||||
std::uint32_t SymbolsFormat;
|
||||
};
|
||||
|
||||
void RequireRange(const std::vector<std::uint8_t>& binary, std::uint64_t offset, std::uint64_t size) {
|
||||
if (offset > binary.size() || size > binary.size() - offset) throw std::runtime_error("Mach-O range out of bounds");
|
||||
}
|
||||
|
||||
std::uint64_t ReadUleb(const std::vector<std::uint8_t>& data, std::size_t& cursor, std::size_t end) {
|
||||
std::uint64_t value = 0;
|
||||
unsigned shift = 0;
|
||||
for (;;) {
|
||||
if (cursor >= end) throw std::runtime_error("truncated uleb128 in export trie");
|
||||
const auto byte = data[cursor++];
|
||||
if (shift >= 64 || (shift == 63 && (byte & 0x7e) != 0)) throw std::runtime_error("uleb128 overflow in export trie");
|
||||
value |= std::uint64_t{byte & 0x7fu} << shift;
|
||||
if ((byte & 0x80) == 0) return value;
|
||||
shift += 7;
|
||||
}
|
||||
}
|
||||
|
||||
void WriteUleb(std::vector<std::uint8_t>& out, std::uint64_t value) {
|
||||
do {
|
||||
std::uint8_t byte = value & 0x7f;
|
||||
value >>= 7;
|
||||
if (value != 0) byte |= 0x80;
|
||||
out.push_back(byte);
|
||||
} while (value != 0);
|
||||
}
|
||||
|
||||
std::size_t UlebSize(std::uint64_t value) {
|
||||
std::size_t size = 1;
|
||||
while (value >>= 7) ++size;
|
||||
return size;
|
||||
}
|
||||
|
||||
std::string ReadTrieString(const std::vector<std::uint8_t>& data, std::size_t& cursor, std::size_t end) {
|
||||
const auto start = cursor;
|
||||
while (cursor < end && data[cursor] != 0) ++cursor;
|
||||
if (cursor >= end) throw std::runtime_error("unterminated string in export trie");
|
||||
std::string text(reinterpret_cast<const char*>(data.data() + start), cursor - start);
|
||||
++cursor;
|
||||
return text;
|
||||
}
|
||||
|
||||
struct Image {
|
||||
MachHeader64 Header {};
|
||||
std::vector<std::size_t> Commands;
|
||||
};
|
||||
|
||||
Image ParseImage(const std::vector<std::uint8_t>& binary) {
|
||||
Image image;
|
||||
image.Header = Read<MachHeader64>(binary, 0);
|
||||
if (image.Header.Magic != kMachOMagic64) throw std::runtime_error("not a 64-bit little-endian Mach-O image");
|
||||
RequireRange(binary, sizeof(MachHeader64), image.Header.CommandBytes);
|
||||
std::size_t cursor = sizeof(MachHeader64);
|
||||
const auto end = cursor + image.Header.CommandBytes;
|
||||
for (std::uint32_t index = 0; index < image.Header.CommandCount; ++index) {
|
||||
if (cursor + sizeof(LoadCommand) > end) throw std::runtime_error("load command out of bounds");
|
||||
const auto command = Read<LoadCommand>(binary, cursor);
|
||||
if (command.Size < sizeof(LoadCommand) || command.Size % 8 != 0 || command.Size > end - cursor) throw std::runtime_error("invalid load command size");
|
||||
image.Commands.push_back(cursor);
|
||||
cursor += command.Size;
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
struct TrieLocation {
|
||||
std::size_t OffsetField;
|
||||
std::size_t SizeField;
|
||||
};
|
||||
|
||||
std::optional<TrieLocation> FindTrie(const std::vector<std::uint8_t>& binary, const Image& image) {
|
||||
std::optional<TrieLocation> found;
|
||||
for (const auto offset : image.Commands) {
|
||||
const auto cmd = Read<LoadCommand>(binary, offset).Cmd;
|
||||
std::optional<TrieLocation> here;
|
||||
if (cmd == kLcDyldExportsTrie) here = TrieLocation{offset + offsetof(LinkeditDataCommand, DataOffset), offset + offsetof(LinkeditDataCommand, DataSize)};
|
||||
else if (cmd == kLcDyldInfo || cmd == kLcDyldInfoOnly) {
|
||||
if (Read<DyldInfoCommand>(binary, offset).ExportSize != 0)
|
||||
here = TrieLocation{offset + offsetof(DyldInfoCommand, ExportOffset), offset + offsetof(DyldInfoCommand, ExportSize)};
|
||||
}
|
||||
if (!here) continue;
|
||||
if (found) throw std::runtime_error("Mach-O image has more than one export trie");
|
||||
found = here;
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
void ParseTrieNode(const std::vector<std::uint8_t>& data, std::size_t start, std::size_t end, std::size_t node, std::string& prefix, std::set<std::size_t>& visited, std::vector<MachOExport>& out) {
|
||||
if (node >= end - start) throw std::runtime_error("export trie node out of bounds");
|
||||
if (!visited.insert(node).second) throw std::runtime_error("export trie has a cycle");
|
||||
std::size_t cursor = start + node;
|
||||
const auto terminalSize = ReadUleb(data, cursor, end);
|
||||
if (terminalSize > end - cursor) throw std::runtime_error("export trie terminal out of bounds");
|
||||
const auto children = cursor + terminalSize;
|
||||
if (terminalSize != 0) {
|
||||
MachOExport entry;
|
||||
entry.Name = prefix;
|
||||
entry.Flags = ReadUleb(data, cursor, children);
|
||||
if (entry.Flags & kExportReexport) {
|
||||
entry.Other = ReadUleb(data, cursor, children);
|
||||
entry.ImportName = ReadTrieString(data, cursor, children);
|
||||
} else {
|
||||
entry.Address = ReadUleb(data, cursor, children);
|
||||
if (entry.Flags & kExportStubAndResolver) entry.Other = ReadUleb(data, cursor, children);
|
||||
}
|
||||
out.push_back(std::move(entry));
|
||||
}
|
||||
cursor = children;
|
||||
if (cursor >= end) throw std::runtime_error("export trie child count out of bounds");
|
||||
const auto childCount = data[cursor++];
|
||||
for (unsigned index = 0; index < childCount; ++index) {
|
||||
const auto label = ReadTrieString(data, cursor, end);
|
||||
const auto child = ReadUleb(data, cursor, end);
|
||||
const auto length = prefix.size();
|
||||
prefix += label;
|
||||
ParseTrieNode(data, start, end, static_cast<std::size_t>(child), prefix, visited, out);
|
||||
prefix.resize(length);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<MachOExport> ParseTrie(const std::vector<std::uint8_t>& binary, std::uint32_t offset, std::uint32_t size) {
|
||||
RequireRange(binary, offset, size);
|
||||
std::vector<MachOExport> exports;
|
||||
if (size == 0) return exports;
|
||||
std::string prefix;
|
||||
std::set<std::size_t> visited;
|
||||
ParseTrieNode(binary, offset, std::size_t{offset} + size, 0, prefix, visited, exports);
|
||||
return exports;
|
||||
}
|
||||
|
||||
class TrieBuilder {
|
||||
public:
|
||||
explicit TrieBuilder(const std::vector<MachOExport>& exports) {
|
||||
for (const auto& entry : exports) Insert(entry);
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> Build() {
|
||||
std::vector<Node*> order;
|
||||
Collect(&root, order);
|
||||
for (bool changed = true; changed;) {
|
||||
changed = false;
|
||||
std::uint64_t offset = 0;
|
||||
for (auto* node : order) {
|
||||
if (node->Offset != offset) {
|
||||
node->Offset = offset;
|
||||
changed = true;
|
||||
}
|
||||
offset += NodeSize(*node);
|
||||
}
|
||||
}
|
||||
std::vector<std::uint8_t> out;
|
||||
for (auto* node : order) {
|
||||
if (out.size() != node->Offset) throw std::runtime_error("export trie layout mismatch");
|
||||
const auto terminal = TerminalBytes(*node);
|
||||
WriteUleb(out, terminal.size());
|
||||
out.insert(out.end(), terminal.begin(), terminal.end());
|
||||
if (node->Children.size() > 255) throw std::runtime_error("export trie node has too many children");
|
||||
out.push_back(static_cast<std::uint8_t>(node->Children.size()));
|
||||
for (const auto& [label, child] : node->Children) {
|
||||
out.insert(out.end(), label.begin(), label.end());
|
||||
out.push_back(0);
|
||||
WriteUleb(out, child->Offset);
|
||||
}
|
||||
}
|
||||
while (out.size() % 8 != 0) out.push_back(0);
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
struct Node {
|
||||
std::vector<std::pair<std::string, std::unique_ptr<Node>>> Children;
|
||||
std::optional<MachOExport> Entry;
|
||||
std::uint64_t Offset = 0;
|
||||
};
|
||||
|
||||
Node root;
|
||||
|
||||
void Insert(const MachOExport& entry) {
|
||||
Node* node = &root;
|
||||
std::string_view rest = entry.Name;
|
||||
while (!rest.empty()) {
|
||||
bool descended = false;
|
||||
for (auto& [label, child] : node->Children) {
|
||||
std::size_t common = 0;
|
||||
while (common < label.size() && common < rest.size() && label[common] == rest[common]) ++common;
|
||||
if (common == 0) continue;
|
||||
if (common < label.size()) {
|
||||
auto middle = std::make_unique<Node>();
|
||||
middle->Children.emplace_back(label.substr(common), std::move(child));
|
||||
label.resize(common);
|
||||
child = std::move(middle);
|
||||
}
|
||||
node = child.get();
|
||||
rest.remove_prefix(common);
|
||||
descended = true;
|
||||
break;
|
||||
}
|
||||
if (!descended) {
|
||||
node->Children.emplace_back(std::string(rest), std::make_unique<Node>());
|
||||
node = node->Children.back().second.get();
|
||||
rest = {};
|
||||
}
|
||||
}
|
||||
if (node->Entry) throw std::runtime_error("duplicate patched export name: " + entry.Name);
|
||||
node->Entry = entry;
|
||||
}
|
||||
|
||||
static void Collect(Node* node, std::vector<Node*>& order) {
|
||||
order.push_back(node);
|
||||
for (auto& [label, child] : node->Children) Collect(child.get(), order);
|
||||
}
|
||||
|
||||
static std::vector<std::uint8_t> TerminalBytes(const Node& node) {
|
||||
std::vector<std::uint8_t> bytes;
|
||||
if (!node.Entry) return bytes;
|
||||
const auto& entry = *node.Entry;
|
||||
WriteUleb(bytes, entry.Flags);
|
||||
if (entry.Flags & kExportReexport) {
|
||||
WriteUleb(bytes, entry.Other);
|
||||
bytes.insert(bytes.end(), entry.ImportName.begin(), entry.ImportName.end());
|
||||
bytes.push_back(0);
|
||||
} else {
|
||||
WriteUleb(bytes, entry.Address);
|
||||
if (entry.Flags & kExportStubAndResolver) WriteUleb(bytes, entry.Other);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
static std::uint64_t NodeSize(const Node& node) {
|
||||
const auto terminal = TerminalBytes(node).size();
|
||||
std::uint64_t size = UlebSize(terminal) + terminal + 1;
|
||||
for (const auto& [label, child] : node.Children) size += label.size() + 1 + UlebSize(child->Offset);
|
||||
return size;
|
||||
}
|
||||
};
|
||||
|
||||
std::string StripUnderscore(const std::string& name) {
|
||||
return !name.empty() && name[0] == '_' ? name.substr(1) : name;
|
||||
}
|
||||
|
||||
bool IsGuestFacingImport(const std::string& name) {
|
||||
using namespace Internal;
|
||||
const bool hasNidPostfix = name.size() >= kNidPostfixLen && name.compare(name.size() - kNidPostfixLen, kNidPostfixLen, kNidPostfix) == 0;
|
||||
const bool hasScePrefix = name.size() >= 3u &&
|
||||
std::tolower(static_cast<unsigned char>(name[0])) == 's' &&
|
||||
std::tolower(static_cast<unsigned char>(name[1])) == 'c' &&
|
||||
std::tolower(static_cast<unsigned char>(name[2])) == 'e';
|
||||
return hasNidPostfix || hasScePrefix;
|
||||
}
|
||||
|
||||
std::vector<bool> DylibOrdinalsArePrx(const std::vector<std::uint8_t>& binary, const Image& image) {
|
||||
std::vector<bool> result;
|
||||
for (const auto offset : image.Commands) {
|
||||
const auto command = Read<LoadCommand>(binary, offset);
|
||||
if (command.Cmd != kLcLoadDylib && command.Cmd != kLcLoadWeakDylib && command.Cmd != kLcReexportDylib && command.Cmd != kLcLazyLoadDylib && command.Cmd != kLcLoadUpwardDylib) continue;
|
||||
const auto nameOffset = Read<std::uint32_t>(binary, offset + 8);
|
||||
if (nameOffset >= command.Size) throw std::runtime_error("dylib name out of bounds");
|
||||
const auto name = Internal::ReadCStr(binary, offset + nameOffset);
|
||||
result.push_back(name.size() >= 4 && name.compare(name.size() - 4, 4, ".prx") == 0);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void PatchChainedImports(std::vector<std::uint8_t>& binary, const Image& image) {
|
||||
std::optional<LinkeditDataCommand> fixups;
|
||||
for (const auto offset : image.Commands) {
|
||||
const auto cmd = Read<LoadCommand>(binary, offset).Cmd;
|
||||
if (cmd == kLcDyldChainedFixups) fixups = Read<LinkeditDataCommand>(binary, offset);
|
||||
if ((cmd == kLcDyldInfo || cmd == kLcDyldInfoOnly)) {
|
||||
const auto info = Read<DyldInfoCommand>(binary, offset);
|
||||
if (info.BindSize != 0 || info.LazyBindSize != 0 || info.WeakBindSize != 0) throw std::runtime_error("Mach-O bind opcodes are not supported; link with chained fixups");
|
||||
}
|
||||
}
|
||||
if (!fixups || fixups->DataSize == 0) return;
|
||||
RequireRange(binary, fixups->DataOffset, fixups->DataSize);
|
||||
const auto base = std::size_t{fixups->DataOffset};
|
||||
const auto header = Read<ChainedFixupsHeader>(binary, base);
|
||||
if (header.Version != 0) throw std::runtime_error("unsupported chained fixups version");
|
||||
if (header.SymbolsFormat != 0) throw std::runtime_error("compressed chained fixup symbols are not supported");
|
||||
const std::size_t entrySize = header.ImportsFormat == kImportFormatPlain ? 4 : header.ImportsFormat == kImportFormatAddend ? 8 : header.ImportsFormat == kImportFormatAddend64 ? 16 : 0;
|
||||
if (entrySize == 0) throw std::runtime_error("unsupported chained import format");
|
||||
if (header.ImportsOffset > fixups->DataSize || std::uint64_t{header.ImportsCount} * entrySize > fixups->DataSize - header.ImportsOffset || header.SymbolsOffset > fixups->DataSize)
|
||||
throw std::runtime_error("chained imports out of bounds");
|
||||
const auto symbols = base + header.SymbolsOffset;
|
||||
const auto symbolsEnd = base + fixups->DataSize;
|
||||
const auto prx = DylibOrdinalsArePrx(binary, image);
|
||||
|
||||
struct Import { std::uint32_t NameOffset; std::uint32_t Ordinal; };
|
||||
std::vector<Import> imports;
|
||||
for (std::uint32_t index = 0; index < header.ImportsCount; ++index) {
|
||||
const auto at = base + header.ImportsOffset + index * entrySize;
|
||||
if (header.ImportsFormat == kImportFormatAddend64) {
|
||||
const auto raw = Read<std::uint64_t>(binary, at);
|
||||
imports.push_back({static_cast<std::uint32_t>(raw >> 32), static_cast<std::uint32_t>(raw & 0xffff)});
|
||||
} else {
|
||||
const auto raw = Read<std::uint32_t>(binary, at);
|
||||
imports.push_back({raw >> 9, raw & 0xff});
|
||||
}
|
||||
}
|
||||
std::set<std::uint32_t> nameOffsets;
|
||||
for (const auto& item : imports) nameOffsets.insert(item.NameOffset);
|
||||
std::set<std::uint32_t> rewritten;
|
||||
for (const auto& item : imports) {
|
||||
const bool special = header.ImportsFormat == kImportFormatAddend64 ? item.Ordinal >= 0xfff0 : item.Ordinal >= 0xf0;
|
||||
if (item.Ordinal == 0 || special || item.Ordinal > prx.size() || !prx[item.Ordinal - 1]) continue;
|
||||
if (rewritten.contains(item.NameOffset)) continue;
|
||||
const auto at = symbols + item.NameOffset;
|
||||
if (at >= symbolsEnd) throw std::runtime_error("chained import name out of bounds");
|
||||
const auto name = Internal::ReadCStr(binary, at);
|
||||
if (at + name.size() >= symbolsEnd) throw std::runtime_error("unterminated chained import name");
|
||||
const auto bare = StripUnderscore(name);
|
||||
if (bare == name || !IsGuestFacingImport(bare)) continue;
|
||||
const auto patched = "_" + ResolveOneName(bare);
|
||||
if (patched.size() > name.size()) throw std::runtime_error("import NID longer than original name: " + name);
|
||||
const auto inside = nameOffsets.upper_bound(item.NameOffset);
|
||||
if (inside != nameOffsets.end() && *inside <= item.NameOffset + name.size()) throw std::runtime_error("chained import names share storage: " + name);
|
||||
std::memcpy(binary.data() + at, patched.data(), patched.size());
|
||||
std::fill(binary.begin() + static_cast<std::ptrdiff_t>(at + patched.size()), binary.begin() + static_cast<std::ptrdiff_t>(at + name.size() + 1), 0);
|
||||
rewritten.insert(item.NameOffset);
|
||||
}
|
||||
}
|
||||
|
||||
void WriteTrie(std::vector<std::uint8_t>& binary, const Image& image, const TrieLocation& location, const std::vector<std::uint8_t>& trie) {
|
||||
const auto oldOffset = Read<std::uint32_t>(binary, location.OffsetField);
|
||||
const auto oldSize = Read<std::uint32_t>(binary, location.SizeField);
|
||||
if (trie.size() <= oldSize) {
|
||||
std::copy(trie.begin(), trie.end(), binary.begin() + oldOffset);
|
||||
std::fill(binary.begin() + oldOffset + static_cast<std::ptrdiff_t>(trie.size()), binary.begin() + oldOffset + oldSize, 0);
|
||||
Write(binary, location.SizeField, static_cast<std::uint32_t>(trie.size()));
|
||||
return;
|
||||
}
|
||||
std::optional<std::size_t> linkedit;
|
||||
for (const auto offset : image.Commands) {
|
||||
const auto cmd = Read<LoadCommand>(binary, offset).Cmd;
|
||||
if (cmd == kLcCodeSignature) throw std::runtime_error("signed Mach-O images cannot grow their export trie");
|
||||
if (cmd != kLcSegment64) continue;
|
||||
const auto segment = Read<SegmentCommand64>(binary, offset);
|
||||
if (std::strncmp(segment.Name, "__LINKEDIT", sizeof(segment.Name)) == 0) linkedit = offset;
|
||||
}
|
||||
if (!linkedit) throw std::runtime_error("Mach-O image has no __LINKEDIT segment");
|
||||
auto segment = Read<SegmentCommand64>(binary, *linkedit);
|
||||
if (segment.FileOffset + segment.FileSize != binary.size()) throw std::runtime_error("__LINKEDIT does not end the file");
|
||||
const auto newOffset = (binary.size() + 7) & ~std::size_t{7};
|
||||
if (newOffset + trie.size() > 0xffffffffu) throw std::runtime_error("export trie offset overflow");
|
||||
binary.resize(newOffset, 0);
|
||||
binary.insert(binary.end(), trie.begin(), trie.end());
|
||||
std::fill(binary.begin() + oldOffset, binary.begin() + oldOffset + oldSize, 0);
|
||||
segment.FileSize = binary.size() - segment.FileOffset;
|
||||
segment.VmSize = std::max(segment.VmSize, (segment.FileSize + kPageSize - 1) & ~(kPageSize - 1));
|
||||
Write(binary, *linkedit, segment);
|
||||
Write(binary, location.OffsetField, static_cast<std::uint32_t>(newOffset));
|
||||
Write(binary, location.SizeField, static_cast<std::uint32_t>(trie.size()));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::vector<MachOExport> ReadMachOExports(const std::vector<std::uint8_t>& binary) {
|
||||
const auto image = ParseImage(binary);
|
||||
const auto location = FindTrie(binary, image);
|
||||
if (!location) return {};
|
||||
return ParseTrie(binary, Read<std::uint32_t>(binary, location->OffsetField), Read<std::uint32_t>(binary, location->SizeField));
|
||||
}
|
||||
|
||||
void MachONidPatcher::PatchNids(std::vector<std::uint8_t>& binary, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const {
|
||||
const auto image = ParseImage(binary);
|
||||
const auto location = FindTrie(binary, image);
|
||||
if (!location) throw std::runtime_error("no export trie");
|
||||
auto exports = ParseTrie(binary, Read<std::uint32_t>(binary, location->OffsetField), Read<std::uint32_t>(binary, location->SizeField));
|
||||
if (exports.empty()) throw std::runtime_error("no exported names");
|
||||
|
||||
std::vector<std::string> names;
|
||||
names.reserve(exports.size());
|
||||
for (const auto& entry : exports) {
|
||||
if (entry.Name.empty() || entry.Name[0] != '_') throw std::runtime_error("exported name without a C underscore: " + entry.Name);
|
||||
names.push_back(entry.Name.substr(1));
|
||||
}
|
||||
const auto nidMap = ResolveNids(names, libraryName, excludedExports);
|
||||
for (std::size_t index = 0; index < exports.size(); ++index) {
|
||||
const auto& name = names[index];
|
||||
const bool marked = name.ends_with(Internal::kNidPostfix) || Internal::IsNidNoPatch(name) || Internal::IsNidNoPatchCut(name);
|
||||
if ((exports[index].Flags & kExportWeakDefinition) != 0 && !marked) continue;
|
||||
const auto found = nidMap.find(name);
|
||||
if (found == nidMap.end()) throw std::runtime_error("symbol not in nid map: " + name);
|
||||
exports[index].Name = "_" + found->second;
|
||||
}
|
||||
WriteTrie(binary, image, *location, TrieBuilder(exports).Build());
|
||||
PatchChainedImports(binary, ParseImage(binary));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
#include <nid/NidCompute.hpp>
|
||||
#include <nid/Sha1.hpp>
|
||||
#include <stdexcept>
|
||||
#include <cstdint>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
constexpr uint8_t kNidSuffix[16] = {
|
||||
0x51, 0x8D, 0x64, 0xA6, 0x35, 0xDE, 0xD8, 0xC1,
|
||||
0xE6, 0xB0, 0x39, 0xB1, 0xC3, 0xE5, 0x52, 0x30
|
||||
};
|
||||
|
||||
constexpr char kBase64S[] =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-";
|
||||
|
||||
std::string ComputeNid(const std::string& symbolName, const std::string& libraryName) {
|
||||
if (symbolName.empty())
|
||||
throw std::invalid_argument("symbolName is empty");
|
||||
|
||||
std::vector<uint8_t> input;
|
||||
input.reserve(symbolName.size() + 16u);
|
||||
for (char c : symbolName)
|
||||
input.push_back(static_cast<uint8_t>(c));
|
||||
for (uint8_t b : kNidSuffix)
|
||||
input.push_back(b);
|
||||
|
||||
const auto digest = Sha1(input);
|
||||
|
||||
uint8_t reversed[8];
|
||||
for (int i = 0; i < 8; i++)
|
||||
reversed[i] = digest[7 - i];
|
||||
|
||||
char nid[12];
|
||||
int nidIndex = 0;
|
||||
for (int i = 0; i < 6; i += 3) {
|
||||
const uint32_t triple = (static_cast<uint32_t>(reversed[i]) << 16) |
|
||||
(static_cast<uint32_t>(reversed[i + 1]) << 8) |
|
||||
static_cast<uint32_t>(reversed[i + 2]);
|
||||
nid[nidIndex++] = kBase64S[(triple >> 18) & 0x3F];
|
||||
nid[nidIndex++] = kBase64S[(triple >> 12) & 0x3F];
|
||||
nid[nidIndex++] = kBase64S[(triple >> 6) & 0x3F];
|
||||
nid[nidIndex++] = kBase64S[triple & 0x3F];
|
||||
}
|
||||
const uint32_t tail = (static_cast<uint32_t>(reversed[6]) << 16) |
|
||||
(static_cast<uint32_t>(reversed[7]) << 8);
|
||||
nid[nidIndex++] = kBase64S[(tail >> 18) & 0x3F];
|
||||
nid[nidIndex++] = kBase64S[(tail >> 12) & 0x3F];
|
||||
nid[nidIndex++] = kBase64S[(tail >> 6) & 0x3F];
|
||||
nid[11] = '\0';
|
||||
|
||||
return std::string(nid, 11);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
#include <nid/NidResolver.hpp>
|
||||
#include <nid/ExportExclusions.hpp>
|
||||
#include <nid/NidCompute.hpp>
|
||||
#include <nid/NidPatcherUtils.hpp>
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
std::string ResolveOneName(const std::string& funcName) {
|
||||
using namespace Internal;
|
||||
|
||||
if (IsNidNoPatchCut(funcName))
|
||||
return StripNidNoPatchCut(funcName);
|
||||
if (IsNidNoPatch(funcName))
|
||||
return funcName;
|
||||
|
||||
return ComputeNid(StripNidPostfix(funcName), "");
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, std::string> ResolveNids(const std::vector<std::string>& exportedNames, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) {
|
||||
using namespace Internal;
|
||||
|
||||
std::unordered_set<std::string> nameSet(exportedNames.begin(), exportedNames.end());
|
||||
|
||||
if (nameSet.size() != exportedNames.size()) {
|
||||
for (std::size_t i = 0u; i < exportedNames.size(); ++i) {
|
||||
for (std::size_t j = i + 1u; j < exportedNames.size(); ++j) {
|
||||
if (exportedNames[i] == exportedNames[j])
|
||||
throw std::runtime_error("duplicate exported symbol \"" + exportedNames[i] + "\" in library \"" + libraryName + "\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::unordered_map<std::string, std::string> result;
|
||||
result.reserve(exportedNames.size());
|
||||
|
||||
for (const std::string& name : exportedNames) {
|
||||
if (excludedExports.contains(NormalizeExportName(name))) {
|
||||
result[name] = name;
|
||||
continue;
|
||||
}
|
||||
if (IsNidNoPatchCut(name)) {
|
||||
result[name] = StripNidNoPatchCut(name);
|
||||
continue;
|
||||
}
|
||||
if (IsNidNoPatch(name)) {
|
||||
result[name] = name;
|
||||
continue;
|
||||
}
|
||||
|
||||
const std::string stripped = StripNidPostfix(name);
|
||||
const bool hasPostfix = stripped != name;
|
||||
|
||||
if (!hasPostfix && nameSet.count(name + kNidPostfix)) {
|
||||
result[name] = name;
|
||||
continue;
|
||||
}
|
||||
|
||||
result[name] = ComputeNid(stripped, libraryName);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,312 +0,0 @@
|
||||
#include <nid/PeNidPatcher.hpp>
|
||||
#include <nid/NidResolver.hpp>
|
||||
#include <nid/NidPatcherUtils.hpp>
|
||||
#include <nid/NidCompute.hpp>
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
namespace {
|
||||
|
||||
std::size_t FindSectionOffsetByRva(const std::vector<std::uint8_t>& pe, std::uint32_t rva, std::uint32_t peHeaderOffset, std::uint16_t numberOfSections, std::uint32_t sizeOfOptionalHeader) {
|
||||
const std::size_t sectionTableOffset = static_cast<std::size_t>(peHeaderOffset) + 4u + 20u + sizeOfOptionalHeader;
|
||||
for (std::uint16_t i = 0u; i < numberOfSections; ++i) {
|
||||
const std::size_t sectionOffset = sectionTableOffset + i * sizeof(PeSectionHeader);
|
||||
if (sectionOffset + sizeof(PeSectionHeader) > pe.size()) throw std::runtime_error("section header out of bounds");
|
||||
const auto section = Internal::Read<PeSectionHeader>(pe, sectionOffset);
|
||||
const std::uint32_t effectiveSize = section.VirtualSize != 0u ? section.VirtualSize : section.SizeOfRawData;
|
||||
if (rva >= section.VirtualAddress && rva < section.VirtualAddress + effectiveSize)
|
||||
return sectionOffset;
|
||||
}
|
||||
throw std::runtime_error("rva not mapped to any section");
|
||||
}
|
||||
|
||||
std::size_t RvaToOffset(const std::vector<std::uint8_t>& pe, std::uint32_t rva, std::uint32_t peHeaderOffset, std::uint16_t numberOfSections, std::uint32_t sizeOfOptionalHeader) {
|
||||
const std::size_t sectionOffset = FindSectionOffsetByRva(pe, rva, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
const auto section = Internal::Read<PeSectionHeader>(pe, sectionOffset);
|
||||
return static_cast<std::size_t>(section.PointerToRawData) + (rva - section.VirtualAddress);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void PeNidPatcher::PatchNids(std::vector<std::uint8_t>& pe, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports) const {
|
||||
using namespace Internal;
|
||||
|
||||
if (pe.size() < 0x40) throw std::runtime_error("file too small");
|
||||
|
||||
const auto peHeaderOffset = Read<std::uint32_t>(pe, 0x3cu);
|
||||
if (static_cast<std::size_t>(peHeaderOffset) + 4u > pe.size()) throw std::runtime_error("invalid pe header offset");
|
||||
if (pe[peHeaderOffset] != 'P' || pe[peHeaderOffset + 1u] != 'E' || pe[peHeaderOffset + 2u] != 0u || pe[peHeaderOffset + 3u] != 0u)
|
||||
throw std::runtime_error("not a PE file");
|
||||
|
||||
const std::size_t coffHeaderOffset = static_cast<std::size_t>(peHeaderOffset) + 4u;
|
||||
const auto numberOfSections = Read<std::uint16_t>(pe, coffHeaderOffset + 2u);
|
||||
const auto sizeOfOptionalHeader = Read<std::uint16_t>(pe, coffHeaderOffset + 16u);
|
||||
if (sizeOfOptionalHeader == 0u) throw std::runtime_error("no optional header");
|
||||
|
||||
const std::size_t sectionTableOffset = coffHeaderOffset + 20u + sizeOfOptionalHeader;
|
||||
const auto symbolTable = Read<std::uint32_t>(pe, coffHeaderOffset + 8u);
|
||||
const auto symbolCount = Read<std::uint32_t>(pe, coffHeaderOffset + 12u);
|
||||
for (std::uint16_t i = 0; i < numberOfSections; ++i) {
|
||||
const auto offset = sectionTableOffset + i * sizeof(PeSectionHeader);
|
||||
auto section = Read<PeSectionHeader>(pe, offset);
|
||||
if (pe[offset] != '/' || !symbolTable) continue;
|
||||
const std::string reference(reinterpret_cast<const char*>(pe.data() + offset), 8);
|
||||
const auto stringOffset = std::stoul(reference.substr(1));
|
||||
const auto name = ReadCStr(pe, static_cast<std::size_t>(symbolTable) + static_cast<std::size_t>(symbolCount) * 18 + stringOffset);
|
||||
if (name == ".eh_frame") {
|
||||
const char shortName[8] = ".ehfram";
|
||||
std::memcpy(pe.data() + offset, shortName, 8);
|
||||
}
|
||||
}
|
||||
|
||||
const std::size_t optionalHeaderOffset = coffHeaderOffset + 20u;
|
||||
const auto magic = Read<std::uint16_t>(pe, optionalHeaderOffset);
|
||||
|
||||
std::size_t dataDirectoryOffset;
|
||||
if (magic == 0x20bu) {
|
||||
dataDirectoryOffset = optionalHeaderOffset + 112u;
|
||||
} else if (magic == 0x10bu) {
|
||||
dataDirectoryOffset = optionalHeaderOffset + 96u;
|
||||
} else {
|
||||
throw std::runtime_error("unsupported optional header magic");
|
||||
}
|
||||
|
||||
const auto exportDir = Read<PeDataDirectory>(pe, dataDirectoryOffset);
|
||||
if (exportDir.VirtualAddress == 0u) throw std::runtime_error("no export directory");
|
||||
|
||||
const std::size_t exportDirOffset = RvaToOffset(pe, exportDir.VirtualAddress, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
const auto exportTable = Read<PeExportDirectory>(pe, exportDirOffset);
|
||||
|
||||
if (exportTable.NumberOfNames == 0u) throw std::runtime_error("no exported names");
|
||||
|
||||
const std::size_t namesArrayOffset = RvaToOffset(pe, exportTable.AddressOfNames, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
const std::size_t ordinalsArrayOffset = RvaToOffset(pe, exportTable.AddressOfNameOrdinals, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
|
||||
std::vector<std::uint32_t> nameRvas(exportTable.NumberOfNames);
|
||||
std::vector<std::string> names(exportTable.NumberOfNames);
|
||||
for (std::uint32_t i = 0u; i < exportTable.NumberOfNames; ++i) {
|
||||
const auto nameRva = Read<std::uint32_t>(pe, namesArrayOffset + i * 4u);
|
||||
const std::size_t nameOffset = RvaToOffset(pe, nameRva, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
const std::string name = ReadCStr(pe, nameOffset);
|
||||
if (name.empty()) throw std::runtime_error("empty exported name");
|
||||
nameRvas[i] = nameRva;
|
||||
names[i] = name;
|
||||
}
|
||||
|
||||
const auto nidMap = ResolveNids(names, libraryName, excludedExports);
|
||||
|
||||
const std::size_t edataSectionOffset = FindSectionOffsetByRva(pe, exportDir.VirtualAddress, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
const auto edataSection = Read<PeSectionHeader>(pe, edataSectionOffset);
|
||||
|
||||
const auto fileAlignment = Read<std::uint32_t>(pe, optionalHeaderOffset + 36u);
|
||||
if (fileAlignment == 0u) throw std::runtime_error("invalid file alignment");
|
||||
|
||||
std::uint32_t stringsRegionStart = std::numeric_limits<std::uint32_t>::max();
|
||||
for (std::uint32_t i = 0u; i < exportTable.NumberOfNames; ++i) {
|
||||
const std::uint32_t rvaFromSection = nameRvas[i] - edataSection.VirtualAddress;
|
||||
if (rvaFromSection < stringsRegionStart) stringsRegionStart = rvaFromSection;
|
||||
}
|
||||
if (stringsRegionStart == std::numeric_limits<std::uint32_t>::max())
|
||||
throw std::runtime_error("could not determine strings region start");
|
||||
|
||||
std::uint32_t rawLimit = ((edataSection.SizeOfRawData + fileAlignment - 1u) / fileAlignment) * fileAlignment;
|
||||
const auto dllName = ReadCStr(pe, RvaToOffset(pe, exportTable.Name, peHeaderOffset, numberOfSections, sizeOfOptionalHeader));
|
||||
const bool repackDllName = exportTable.Name >= edataSection.VirtualAddress &&
|
||||
exportTable.Name - edataSection.VirtualAddress < rawLimit;
|
||||
if (repackDllName) stringsRegionStart = std::min(stringsRegionStart, exportTable.Name - edataSection.VirtualAddress);
|
||||
struct Forwarder {
|
||||
std::size_t EntryOffset;
|
||||
std::string Target;
|
||||
};
|
||||
std::vector<Forwarder> forwarders;
|
||||
std::vector<std::uint32_t> directRvas;
|
||||
const auto functionsArrayOffset = RvaToOffset(pe, exportTable.AddressOfFunctions, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
for (std::uint32_t index = 0u; index < exportTable.NumberOfFunctions; ++index) {
|
||||
const auto entryOffset = functionsArrayOffset + index * sizeof(std::uint32_t);
|
||||
const auto rva = Read<std::uint32_t>(pe, entryOffset);
|
||||
if (rva < exportDir.VirtualAddress || std::uint64_t{rva} - exportDir.VirtualAddress >= exportDir.Size) {
|
||||
directRvas.push_back(rva);
|
||||
continue;
|
||||
}
|
||||
const auto target = ReadCStr(pe, RvaToOffset(pe, rva, peHeaderOffset, numberOfSections, sizeOfOptionalHeader));
|
||||
if (target.size() + 1u > exportDir.Size - (rva - exportDir.VirtualAddress))
|
||||
throw std::runtime_error("forwarder string outside export directory");
|
||||
forwarders.push_back({entryOffset, target});
|
||||
stringsRegionStart = std::min(stringsRegionStart, rva - edataSection.VirtualAddress);
|
||||
}
|
||||
for (const auto rva : directRvas) {
|
||||
if (rva >= edataSection.VirtualAddress && rva - edataSection.VirtualAddress >= stringsRegionStart)
|
||||
rawLimit = std::min(rawLimit, rva - edataSection.VirtualAddress);
|
||||
}
|
||||
const auto reserveTable = [&](std::uint32_t rva, std::uint64_t size) {
|
||||
if (rva < edataSection.VirtualAddress || rva - edataSection.VirtualAddress >= rawLimit) return;
|
||||
const auto end = std::uint64_t{rva - edataSection.VirtualAddress} + size;
|
||||
if (end > rawLimit) throw std::runtime_error("export table outside edata section");
|
||||
stringsRegionStart = std::max(stringsRegionStart, static_cast<std::uint32_t>(end));
|
||||
};
|
||||
reserveTable(exportDir.VirtualAddress, sizeof(PeExportDirectory));
|
||||
reserveTable(exportTable.AddressOfFunctions, std::uint64_t{exportTable.NumberOfFunctions} * 4u);
|
||||
reserveTable(exportTable.AddressOfNames, std::uint64_t{exportTable.NumberOfNames} * 4u);
|
||||
reserveTable(exportTable.AddressOfNameOrdinals, std::uint64_t{exportTable.NumberOfNames} * 2u);
|
||||
|
||||
std::vector<std::string> finalNames(exportTable.NumberOfNames);
|
||||
for (std::uint32_t i = 0u; i < exportTable.NumberOfNames; ++i) {
|
||||
const auto it = nidMap.find(names[i]);
|
||||
if (it == nidMap.end()) throw std::runtime_error("symbol not in nid map: " + names[i]);
|
||||
finalNames[i] = it->second;
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> strings;
|
||||
std::unordered_map<std::string, std::uint32_t> stringRvas;
|
||||
const auto storeString = [&](const std::string& name) {
|
||||
const auto existing = stringRvas.find(name);
|
||||
if (existing != stringRvas.end()) return existing->second;
|
||||
const auto rva = edataSection.VirtualAddress + stringsRegionStart + static_cast<std::uint32_t>(strings.size());
|
||||
stringRvas.emplace(name, rva);
|
||||
strings.insert(strings.end(), name.begin(), name.end());
|
||||
strings.push_back(0u);
|
||||
return rva;
|
||||
};
|
||||
std::vector<std::uint32_t> forwarderRvas;
|
||||
for (const auto& forwarder : forwarders) forwarderRvas.push_back(storeString(forwarder.Target));
|
||||
if (!forwarders.empty() && (std::uint64_t{edataSection.VirtualAddress} + stringsRegionStart < exportDir.VirtualAddress ||
|
||||
std::uint64_t{edataSection.VirtualAddress} + stringsRegionStart + strings.size() > std::uint64_t{exportDir.VirtualAddress} + exportDir.Size))
|
||||
throw std::runtime_error("not enough export directory space to repack forwarders");
|
||||
const auto dllNameRva = repackDllName ? storeString(dllName) : exportTable.Name;
|
||||
std::vector<std::uint32_t> finalNameRvas;
|
||||
for (const auto& name : finalNames) finalNameRvas.push_back(storeString(name));
|
||||
const auto requiredSize = std::uint64_t{stringsRegionStart} + strings.size();
|
||||
if (requiredSize > rawLimit)
|
||||
throw std::runtime_error("not enough raw space in edata section to repack export names");
|
||||
const auto directoryEnd = std::max(std::uint64_t{exportDir.VirtualAddress} + exportDir.Size,
|
||||
std::uint64_t{edataSection.VirtualAddress} + requiredSize);
|
||||
for (const auto rva : directRvas) {
|
||||
if (rva != 0u && rva >= exportDir.VirtualAddress && std::uint64_t{rva} < directoryEnd)
|
||||
throw std::runtime_error("repacked export directory would cover a direct export");
|
||||
}
|
||||
const auto directorySize = directoryEnd - exportDir.VirtualAddress;
|
||||
if (directorySize > std::numeric_limits<std::uint32_t>::max()) throw std::runtime_error("export directory too large");
|
||||
const auto stringFileOffset = static_cast<std::size_t>(edataSection.PointerToRawData) + stringsRegionStart;
|
||||
if (stringFileOffset > pe.size() || strings.size() > pe.size() - stringFileOffset)
|
||||
throw std::runtime_error("repack write out of file bounds");
|
||||
std::memcpy(pe.data() + stringFileOffset, strings.data(), strings.size());
|
||||
for (std::size_t index = 0u; index < finalNameRvas.size(); ++index)
|
||||
Write(pe, namesArrayOffset + index * 4u, finalNameRvas[index]);
|
||||
for (std::size_t index = 0u; index < forwarders.size(); ++index)
|
||||
Write(pe, forwarders[index].EntryOffset, forwarderRvas[index]);
|
||||
Write(pe, exportDirOffset + offsetof(PeExportDirectory, Name), dllNameRva);
|
||||
Write(pe, dataDirectoryOffset + offsetof(PeDataDirectory, Size), static_cast<std::uint32_t>(directorySize));
|
||||
|
||||
const std::uint32_t newVirtualSize = std::max(edataSection.VirtualSize, static_cast<std::uint32_t>(requiredSize));
|
||||
auto patchedSection = edataSection;
|
||||
patchedSection.VirtualSize = newVirtualSize;
|
||||
Write(pe, edataSectionOffset, patchedSection);
|
||||
|
||||
struct ExportName {
|
||||
std::string Name;
|
||||
std::uint32_t Rva;
|
||||
std::uint16_t Ordinal;
|
||||
};
|
||||
|
||||
std::vector<ExportName> exportNames;
|
||||
exportNames.reserve(exportTable.NumberOfNames);
|
||||
for (std::size_t i = 0; i < exportTable.NumberOfNames; ++i) {
|
||||
const auto nameRva = Read<std::uint32_t>(pe, namesArrayOffset + i * sizeof(std::uint32_t));
|
||||
const auto ordinal = Read<std::uint16_t>(pe, ordinalsArrayOffset + i * sizeof(std::uint16_t));
|
||||
if (ordinal >= exportTable.NumberOfFunctions)
|
||||
throw std::runtime_error("export name ordinal out of bounds");
|
||||
const auto nameOffset = RvaToOffset(pe, nameRva, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
exportNames.push_back({ReadCStr(pe, nameOffset), nameRva, ordinal});
|
||||
}
|
||||
std::sort(exportNames.begin(), exportNames.end(), [](const ExportName& left, const ExportName& right) { return left.Name < right.Name; });
|
||||
for (std::size_t i = 0; i < exportNames.size(); ++i) {
|
||||
if (i != 0 && exportNames[i - 1].Name == exportNames[i].Name)
|
||||
throw std::runtime_error("duplicate patched export name: " + exportNames[i].Name);
|
||||
Write(pe, namesArrayOffset + i * sizeof(std::uint32_t), exportNames[i].Rva);
|
||||
Write(pe, ordinalsArrayOffset + i * sizeof(std::uint16_t), exportNames[i].Ordinal);
|
||||
}
|
||||
|
||||
constexpr std::size_t kImportDirIndex = 1u;
|
||||
if (dataDirectoryOffset + (kImportDirIndex + 1u) * sizeof(PeDataDirectory) > pe.size())
|
||||
return;
|
||||
|
||||
const auto importDir = Read<PeDataDirectory>(pe, dataDirectoryOffset + kImportDirIndex * sizeof(PeDataDirectory));
|
||||
if (importDir.VirtualAddress == 0u || importDir.Size == 0u)
|
||||
return;
|
||||
|
||||
struct PeImportDescriptor {
|
||||
std::uint32_t OriginalFirstThunk;
|
||||
std::uint32_t TimeDateStamp;
|
||||
std::uint32_t ForwarderChain;
|
||||
std::uint32_t Name;
|
||||
std::uint32_t FirstThunk;
|
||||
};
|
||||
|
||||
std::size_t importDescOffset = RvaToOffset(pe, importDir.VirtualAddress, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
|
||||
while (true) {
|
||||
if (importDescOffset + sizeof(PeImportDescriptor) > pe.size())
|
||||
throw std::runtime_error("import descriptor out of bounds");
|
||||
|
||||
const auto desc = Read<PeImportDescriptor>(pe, importDescOffset);
|
||||
if (desc.OriginalFirstThunk == 0u && desc.FirstThunk == 0u)
|
||||
break;
|
||||
|
||||
const std::uint32_t thunkRva = desc.OriginalFirstThunk != 0u ? desc.OriginalFirstThunk : desc.FirstThunk;
|
||||
std::size_t thunkOffset = RvaToOffset(pe, thunkRva, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
|
||||
const bool is64 = magic == 0x20bu;
|
||||
const std::size_t thunkEntrySize = is64 ? 8u : 4u;
|
||||
const std::uint64_t ordinalFlag = is64 ? (std::uint64_t{1} << 63u) : (std::uint64_t{1} << 31u);
|
||||
|
||||
while (true) {
|
||||
if (thunkOffset + thunkEntrySize > pe.size())
|
||||
throw std::runtime_error("thunk entry out of bounds");
|
||||
|
||||
const std::uint64_t thunk = is64
|
||||
? Read<std::uint64_t>(pe, thunkOffset)
|
||||
: static_cast<std::uint64_t>(Read<std::uint32_t>(pe, thunkOffset));
|
||||
|
||||
if (thunk == 0u)
|
||||
break;
|
||||
|
||||
if (!(thunk & ordinalFlag)) {
|
||||
const auto hintNameRva = static_cast<std::uint32_t>(thunk & 0x7fffffffffffffffu);
|
||||
const std::size_t hintNameOffset = RvaToOffset(pe, hintNameRva, peHeaderOffset, numberOfSections, sizeOfOptionalHeader);
|
||||
if (hintNameOffset + 2u >= pe.size())
|
||||
throw std::runtime_error("import by name out of bounds");
|
||||
|
||||
const std::string funcName = ReadCStr(pe, hintNameOffset + 2u);
|
||||
if (!funcName.empty()) {
|
||||
const bool hasNidPostfix = funcName.size() >= kNidPostfixLen &&
|
||||
funcName.compare(funcName.size() - kNidPostfixLen, kNidPostfixLen, kNidPostfix) == 0;
|
||||
const bool hasScePrefix = funcName.size() >= 3u &&
|
||||
std::tolower(static_cast<unsigned char>(funcName[0])) == 's' &&
|
||||
std::tolower(static_cast<unsigned char>(funcName[1])) == 'c' &&
|
||||
std::tolower(static_cast<unsigned char>(funcName[2])) == 'e';
|
||||
if (hasNidPostfix || hasScePrefix) {
|
||||
const std::string nid = ResolveOneName(funcName);
|
||||
if (nid.size() > funcName.size())
|
||||
throw std::runtime_error("import NID longer than original name: " + funcName);
|
||||
std::memcpy(pe.data() + hintNameOffset + 2u, nid.data(), nid.size());
|
||||
pe[hintNameOffset + 2u + nid.size()] = 0u;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
thunkOffset += thunkEntrySize;
|
||||
}
|
||||
|
||||
importDescOffset += sizeof(PeImportDescriptor);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
#include <nid/Sha1.hpp>
|
||||
#include <cstdint>
|
||||
#include <array>
|
||||
#include <vector>
|
||||
|
||||
namespace Nid {
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr std::uint32_t _rotl32(std::uint32_t x, unsigned n) {
|
||||
return (x << n) | (x >> (32u - n));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
std::array<std::uint8_t, 20> Sha1(const std::vector<std::uint8_t>& data) {
|
||||
std::uint32_t h0 = 0x67452301u;
|
||||
std::uint32_t h1 = 0xEFCDAB89u;
|
||||
std::uint32_t h2 = 0x98BADCFEu;
|
||||
std::uint32_t h3 = 0x10325476u;
|
||||
std::uint32_t h4 = 0xC3D2E1F0u;
|
||||
|
||||
std::vector<std::uint8_t> msg(data);
|
||||
|
||||
const std::uint64_t bitLen = static_cast<std::uint64_t>(data.size()) * 8u;
|
||||
|
||||
msg.push_back(0x80u);
|
||||
while ((msg.size() % 64u) != 56u)
|
||||
msg.push_back(0x00u);
|
||||
|
||||
for (int i = 7; i >= 0; --i)
|
||||
msg.push_back(static_cast<std::uint8_t>((bitLen >> (i * 8u)) & 0xffu));
|
||||
|
||||
for (std::size_t offset = 0; offset < msg.size(); offset += 64u) {
|
||||
std::uint32_t w[80];
|
||||
for (int i = 0; i < 16; ++i) {
|
||||
w[i] = (static_cast<std::uint32_t>(msg[offset + i * 4u + 0u]) << 24u)
|
||||
| (static_cast<std::uint32_t>(msg[offset + i * 4u + 1u]) << 16u)
|
||||
| (static_cast<std::uint32_t>(msg[offset + i * 4u + 2u]) << 8u)
|
||||
| (static_cast<std::uint32_t>(msg[offset + i * 4u + 3u]));
|
||||
}
|
||||
for (int i = 16; i < 80; ++i)
|
||||
w[i] = _rotl32(w[i-3] ^ w[i-8] ^ w[i-14] ^ w[i-16], 1u);
|
||||
|
||||
std::uint32_t a = h0, b = h1, c = h2, d = h3, e = h4;
|
||||
|
||||
for (int i = 0; i < 80; ++i) {
|
||||
std::uint32_t f, k;
|
||||
if (i < 20) {
|
||||
f = (b & c) | ((~b) & d);
|
||||
k = 0x5A827999u;
|
||||
} else if (i < 40) {
|
||||
f = b ^ c ^ d;
|
||||
k = 0x6ED9EBA1u;
|
||||
} else if (i < 60) {
|
||||
f = (b & c) | (b & d) | (c & d);
|
||||
k = 0x8F1BBCDCu;
|
||||
} else {
|
||||
f = b ^ c ^ d;
|
||||
k = 0xCA62C1D6u;
|
||||
}
|
||||
std::uint32_t temp = _rotl32(a, 5u) + f + e + k + w[i];
|
||||
e = d; d = c; c = _rotl32(b, 30u); b = a; a = temp;
|
||||
}
|
||||
|
||||
h0 += a; h1 += b; h2 += c; h3 += d; h4 += e;
|
||||
}
|
||||
|
||||
std::array<std::uint8_t, 20> digest;
|
||||
auto _put = [&](int base, std::uint32_t v) {
|
||||
digest[base+0] = static_cast<std::uint8_t>(v >> 24u);
|
||||
digest[base+1] = static_cast<std::uint8_t>(v >> 16u);
|
||||
digest[base+2] = static_cast<std::uint8_t>(v >> 8u);
|
||||
digest[base+3] = static_cast<std::uint8_t>(v);
|
||||
};
|
||||
_put(0, h0); _put(4, h1); _put(8, h2); _put(12, h3); _put(16, h4);
|
||||
return digest;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
#include <nid/BinaryPatcherFactory.hpp>
|
||||
#include <nid/ExportExclusions.hpp>
|
||||
#include <nid/NativePath.hpp>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
std::vector<std::uint8_t> _readFile(const std::string& path) {
|
||||
std::ifstream f(Nid::Internal::NativePath(path), std::ios::binary);
|
||||
if (!f) throw std::runtime_error("cannot open: " + path);
|
||||
return {std::istreambuf_iterator<char>(f), {}};
|
||||
}
|
||||
|
||||
void _writeFile(const std::string& path, const std::vector<std::uint8_t>& data) {
|
||||
std::ofstream f(Nid::Internal::NativePath(path), std::ios::binary);
|
||||
if (!f) throw std::runtime_error("cannot write: " + path);
|
||||
f.write(reinterpret_cast<const char*>(data.data()), static_cast<std::streamsize>(data.size()));
|
||||
f.close();
|
||||
if (!f) throw std::runtime_error("cannot write: " + path);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int Run(int argc, char* argv[]) {
|
||||
if (argc < 3) {
|
||||
std::cerr << "Usage: nid_patcher <library_name> [--preserve-exports <unpatched-library> | --preserve-export-list <export-list>] <file> [file2 ...]\n"
|
||||
" nid_patcher --write-export-list <unpatched-library> <export-list>\n";
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (std::string(argv[1]) == "--write-export-list") {
|
||||
if (argc != 4) {
|
||||
std::cerr << "FAIL: --write-export-list requires a reference library and an export list\n";
|
||||
return 2;
|
||||
}
|
||||
try {
|
||||
std::cout << (Nid::WriteExportList(argv[2], argv[3]) ? "WROTE: " : "UNCHANGED: ") << argv[3] << "\n";
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "FAIL: " << argv[3] << ": " << e.what() << "\n";
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const std::string libraryName = argv[1];
|
||||
std::unordered_set<std::string> excludedExports;
|
||||
std::vector<std::string> paths;
|
||||
try {
|
||||
bool hasReference = false;
|
||||
for (int i = 2; i < argc; ++i) {
|
||||
const std::string argument = argv[i];
|
||||
if (argument == "--preserve-exports" || argument == "--preserve-export-list") {
|
||||
if (hasReference || i + 1 == argc) throw std::runtime_error(argument + " requires exactly one reference");
|
||||
hasReference = true;
|
||||
excludedExports = argument == "--preserve-exports" ? Nid::ReadExportExclusions(argv[++i]) : Nid::ReadExportList(argv[++i]);
|
||||
} else {
|
||||
if (argument.starts_with("--")) throw std::runtime_error("unknown option: " + argument);
|
||||
paths.push_back(argument);
|
||||
}
|
||||
}
|
||||
if (paths.empty()) throw std::runtime_error("no files to patch");
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "FAIL: " << e.what() << '\n';
|
||||
return 2;
|
||||
}
|
||||
|
||||
for (const std::string& path : paths) {
|
||||
try {
|
||||
auto binary = _readFile(path);
|
||||
const auto patcher = Nid::MakePatcher(binary);
|
||||
patcher->PatchNids(binary, libraryName, excludedExports);
|
||||
_writeFile(path, binary);
|
||||
std::cout << "OK: " << path << "\n";
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "FAIL: " << path << ": " << e.what() << "\n";
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
int wmain(int argc, wchar_t* argv[]) {
|
||||
try {
|
||||
std::vector<std::string> values;
|
||||
values.reserve(static_cast<std::size_t>(argc));
|
||||
for (int index = 0; index < argc; ++index) {
|
||||
const auto utf8 = std::filesystem::path(argv[index]).u8string();
|
||||
values.emplace_back(utf8.begin(), utf8.end());
|
||||
}
|
||||
std::vector<char*> arguments;
|
||||
arguments.reserve(values.size());
|
||||
for (auto& value : values) arguments.push_back(value.data());
|
||||
return Run(argc, arguments.data());
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "FAIL: " << error.what() << '\n';
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
#else
|
||||
int main(int argc, char* argv[]) {
|
||||
return Run(argc, argv);
|
||||
}
|
||||
#endif
|
||||
@@ -1,60 +0,0 @@
|
||||
#include <nid/NidPatcherUtils.hpp>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
void Require(bool condition) {
|
||||
if (!condition) throw std::runtime_error("NID buffer validation failed");
|
||||
}
|
||||
|
||||
template<typename TAction>
|
||||
void RequireRejected(TAction action) {
|
||||
try { action(); }
|
||||
catch (const std::runtime_error&) { return; }
|
||||
throw std::runtime_error("Malformed NID buffer was accepted");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main() {
|
||||
try {
|
||||
using namespace Nid::Internal;
|
||||
const std::vector<std::uint8_t> unterminated{'n', 'a', 'm', 'e'};
|
||||
RequireRejected([&] { ReadCStr(unterminated, 0); });
|
||||
RequireRejected([&] { ReadCStr(unterminated, 3); });
|
||||
const std::vector<std::uint8_t> strings{'a', 0, 'b', 'c', 0};
|
||||
Require(ReadCStr(strings, 0) == "a");
|
||||
Require(ReadCStr(strings, 1).empty());
|
||||
Require(ReadCStr(strings, 2) == "bc");
|
||||
Require(ReadCStr(strings, 4).empty());
|
||||
RequireRejected([&] { ReadCStr(strings, strings.size()); });
|
||||
RequireRejected([&] { ReadCStr({}, 0); });
|
||||
|
||||
std::vector<std::uint8_t> bytes(8, 0xa5);
|
||||
const std::uint64_t value = 0x1020304050607080;
|
||||
Write(bytes, 0, value);
|
||||
Require(Read<std::uint64_t>(bytes, 0) == value);
|
||||
Write<std::uint32_t>(bytes, 4, 0x12345678);
|
||||
Require(Read<std::uint32_t>(bytes, 4) == 0x12345678);
|
||||
const auto before = bytes;
|
||||
for (const auto offset : {std::size_t{5}, std::size_t{8}, std::size_t{9},
|
||||
std::numeric_limits<std::size_t>::max(), std::numeric_limits<std::size_t>::max() - 1,
|
||||
std::numeric_limits<std::size_t>::max() - 3}) {
|
||||
RequireRejected([&] { Read<std::uint32_t>(bytes, offset); });
|
||||
RequireRejected([&] { Write<std::uint32_t>(bytes, offset, 0); });
|
||||
Require(bytes == before);
|
||||
}
|
||||
RequireRejected([&] { Read<std::uint64_t>(bytes, 1); });
|
||||
std::vector<std::uint8_t> empty;
|
||||
RequireRejected([&] { Read<std::uint8_t>(empty, 0); });
|
||||
RequireRejected([&] { Write<std::uint8_t>(empty, 0, 0); });
|
||||
std::cout << "NID buffer validation passed\n";
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
DT_NULL = 0
|
||||
DT_NEEDED = 1
|
||||
DT_SONAME = 14
|
||||
DT_RPATH = 15
|
||||
DT_RUNPATH = 29
|
||||
SHT_DYNAMIC = 6
|
||||
|
||||
|
||||
def dynamic_strings(image):
|
||||
shoff, = struct.unpack_from("<Q", image, 0x28)
|
||||
shentsize, shnum = struct.unpack_from("<HH", image, 0x3A)
|
||||
sections = [struct.unpack_from("<IIQQQQIIQQ", image, shoff + index * shentsize) for index in range(shnum)]
|
||||
dynamic = next(section for section in sections if section[1] == SHT_DYNAMIC)
|
||||
strings = sections[dynamic[6]]
|
||||
entries = []
|
||||
for position in range(dynamic[4], dynamic[4] + dynamic[5], 16):
|
||||
tag, value = struct.unpack_from("<qQ", image, position)
|
||||
if tag == DT_NULL:
|
||||
break
|
||||
if tag in (DT_NEEDED, DT_SONAME, DT_RPATH, DT_RUNPATH):
|
||||
assert value < strings[5], (tag, value)
|
||||
start = strings[4] + value
|
||||
entries.append((tag, image[start:image.index(0, start)].decode()))
|
||||
return entries
|
||||
|
||||
|
||||
def main():
|
||||
entries = dynamic_strings(Path(sys.argv[1]).read_bytes())
|
||||
runpaths = [value for tag, value in entries if tag in (DT_RPATH, DT_RUNPATH)]
|
||||
assert runpaths == ["$ORIGIN"], entries
|
||||
needed = [value for tag, value in entries if tag == DT_NEEDED]
|
||||
assert needed and all(re.fullmatch(r"[\w.+-]+\.so(\.\d+)*", name) for name in needed), entries
|
||||
print("NID patcher dynamic string tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,69 +0,0 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from test_symbol_versions import build_image, patch, read_dynsym, IMPORTS, NID_NAME, SHN_UNDEF, STT_FUNC
|
||||
|
||||
|
||||
def nid(name):
|
||||
digest = hashlib.sha1(name.encode() + bytes.fromhex("518d64a635ded8c1e6b039b1c3e55230")).digest()
|
||||
return base64.b64encode(digest[:8][::-1]).decode().rstrip("=").replace("/", "-")
|
||||
|
||||
|
||||
def image(names, addresses=None):
|
||||
if addresses is None:
|
||||
addresses = [0x1200 + index * 0x20 for index in range(len(names))]
|
||||
entries = [(None, 1, SHN_UNDEF, 0, 0)]
|
||||
entries += [(name, 1, SHN_UNDEF, 0, 0) for name in IMPORTS]
|
||||
entries += [(name, 1, 9, STT_FUNC, address) for name, address in zip(names, addresses)]
|
||||
return bytes(build_image(entries, False))
|
||||
|
||||
|
||||
class ElfDuplicateTests(unittest.TestCase):
|
||||
def test_exports_patched_to_one_name_are_rejected(self):
|
||||
cases = (
|
||||
["sceAlphaComputeLength", "sceAlphaComputeLength_nid_disambig1", "sceBetaCopyString"],
|
||||
["sceAlphaComputeLength_nid_postfix", "sceAlphaComputeLength_nid_disambig12", "sceBetaCopyString"],
|
||||
["sceBetaCopyString", "sceAlphaComputeLength_nid_no_patch", "sceAlphaComputeLength_nid_no_patch_nid_no_patch_cut"],
|
||||
)
|
||||
for names in cases:
|
||||
with self.subTest(names=names):
|
||||
before = image(names)
|
||||
result, after = patch(PATCHER, before, "duplicates.so")
|
||||
self.assertEqual(result.returncode, 2, (result.returncode, result.stderr))
|
||||
self.assertIn(b"duplicate patched export name", result.stderr)
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_aliases_of_one_address_are_patched(self):
|
||||
names = ["sceAlphaComputeLength", "sceAlphaComputeLength_nid_postfix", "sceAlphaComputeLength_nid_no_patch_cut", "sceBetaCopyString"]
|
||||
result, after = patch(PATCHER, image(names, [0x1200, 0x1200, 0x1200, 0x1220]), "aliases.so")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
patched = [(entry[0], entry[2]) for entry in read_dynsym(after) if entry[1] == 9]
|
||||
self.assertEqual(sorted(name for name, address in patched if address == 0x1200),
|
||||
sorted(["sceAlphaComputeLength", "sceAlphaComputeLength", nid("sceAlphaComputeLength")]))
|
||||
self.assertEqual([name for name, address in patched if address == 0x1220], [nid("sceBetaCopyString")])
|
||||
self.assertTrue(NID_NAME.match(nid("sceAlphaComputeLength")))
|
||||
|
||||
def test_aliases_of_different_addresses_are_rejected(self):
|
||||
names = ["sceAlphaComputeLength", "sceAlphaComputeLength_nid_postfix", "sceAlphaComputeLength_nid_no_patch_cut"]
|
||||
before = image(names, [0x1200, 0x1200, 0x1220])
|
||||
result, after = patch(PATCHER, before, "aliases.so")
|
||||
self.assertEqual(result.returncode, 2, (result.returncode, result.stderr))
|
||||
self.assertIn(b"duplicate patched export name: sceAlphaComputeLength", result.stderr)
|
||||
self.assertEqual(after, before)
|
||||
|
||||
def test_distinct_exports_are_still_patched(self):
|
||||
names = ["sceAlphaComputeLength_nid_disambig1", "sceBetaCopyString_nid_postfix", "sceGammaKeep_nid_no_patch_cut"]
|
||||
result, after = patch(PATCHER, image(names), "distinct.so")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
patched = [entry[0] for entry in read_dynsym(after) if entry[1] == 9]
|
||||
self.assertEqual(len(patched), 3)
|
||||
self.assertEqual(len(set(patched)), 3)
|
||||
self.assertIn("sceGammaKeep", patched)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
PATCHER = Path(sys.argv.pop(1)).resolve()
|
||||
unittest.main()
|
||||
@@ -1,48 +0,0 @@
|
||||
import struct
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from test_symbol_versions import build_image, symbols, patch, SHOFF
|
||||
|
||||
|
||||
class ElfLayoutTests(unittest.TestCase):
|
||||
def test_declared_layout_must_match_supported_tables(self):
|
||||
changes = ((5, "B", 2), (0x3a, "H", 32),
|
||||
(SHOFF + 64 + 56, "Q", 8),
|
||||
(SHOFF + 64 + 32, "Q", len(symbols(False)) * 24 + 1),
|
||||
(SHOFF + 128 + 4, "I", 1))
|
||||
for offset, kind, value in changes:
|
||||
with self.subTest(offset=offset, value=value):
|
||||
image = build_image(symbols(False), False)
|
||||
struct.pack_into("<" + kind, image, offset, value)
|
||||
self.reject(image)
|
||||
|
||||
def test_table_ranges_and_links_are_checked(self):
|
||||
changes = ((0x28, "Q", 0x10000),
|
||||
(SHOFF + 64 + 24, "Q", 0xff0),
|
||||
(SHOFF + 64 + 40, "I", 100),
|
||||
(SHOFF + 128 + 24, "Q", 0xff0),
|
||||
(SHOFF + 128 + 32, "Q", 0xffffffffffffffff))
|
||||
for offset, kind, value in changes:
|
||||
with self.subTest(offset=offset, value=value):
|
||||
image = build_image(symbols(False), False)
|
||||
struct.pack_into("<" + kind, image, offset, value)
|
||||
self.reject(image)
|
||||
|
||||
def reject(self, image):
|
||||
result, after = patch(PATCHER, bytes(image), "layout.so")
|
||||
self.assertEqual(result.returncode, 2, (result.returncode, result.stderr))
|
||||
self.assertRegex(result.stderr.decode(), "ELF|dynsym|dynstr")
|
||||
self.assertEqual(after, image)
|
||||
|
||||
def test_valid_supported_layout_still_patches(self):
|
||||
image = build_image(symbols(False), False)
|
||||
result, after = patch(PATCHER, bytes(image), "valid-layout.so")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertNotEqual(after, image)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
PATCHER = Path(sys.argv.pop(1)).resolve()
|
||||
unittest.main()
|
||||
@@ -1,157 +0,0 @@
|
||||
import struct
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from test_symbol_versions import build_image, symbols, patch, HASH_OFFSET, SHOFF, read_dynsym, gnu_hash, sections
|
||||
|
||||
|
||||
def sysv_hash(name):
|
||||
value = 0
|
||||
for byte in name.encode("utf-8"):
|
||||
value = ((value << 4) + byte) & 0xFFFFFFFF
|
||||
high = value & 0xF0000000
|
||||
value = (value ^ (high >> 24)) & ~high
|
||||
return value
|
||||
|
||||
|
||||
def sysv_lookup(image, name):
|
||||
table = next(section for section in sections(image) if section[1] == 5)
|
||||
buckets, chains = struct.unpack_from("<II", image, table[4])
|
||||
entries = read_dynsym(image)
|
||||
index = struct.unpack_from("<I", image, table[4] + 8 + (sysv_hash(name) % buckets) * 4)[0]
|
||||
visited = set()
|
||||
while index:
|
||||
if index >= chains or index in visited:
|
||||
raise AssertionError("invalid SysV hash chain")
|
||||
visited.add(index)
|
||||
if entries[index][0] == name:
|
||||
return index
|
||||
index = struct.unpack_from("<I", image, table[4] + 8 + buckets * 4 + index * 4)[0]
|
||||
return None
|
||||
|
||||
|
||||
class GnuHashTests(unittest.TestCase):
|
||||
def image(self, buckets=4, bloom=1, shift=6, symoffset=3):
|
||||
image = build_image(symbols(False), False)
|
||||
count = len(symbols(False))
|
||||
struct.pack_into("<IIII", image, HASH_OFFSET, buckets, symoffset, bloom, shift)
|
||||
size = 16 + 8 * bloom + 4 * buckets + 4 * max(0, count - symoffset)
|
||||
struct.pack_into("<Q", image, SHOFF + 3 * 64 + 32, size)
|
||||
return image
|
||||
|
||||
def test_non_power_of_two_bloom_is_rejected(self):
|
||||
self.reject(self.image(bloom=3))
|
||||
|
||||
def test_hash_shift_outside_word_is_rejected(self):
|
||||
self.reject(self.image(shift=32))
|
||||
|
||||
def test_unsafe_geometry_is_rejected(self):
|
||||
for fields in ({"bloom": 0}, {"buckets": 0}, {"symoffset": 100}):
|
||||
with self.subTest(fields=fields):
|
||||
self.reject(self.image(**fields))
|
||||
|
||||
def test_declared_section_extent_is_checked(self):
|
||||
for size in (12, 16, 0x10000):
|
||||
with self.subTest(size=size):
|
||||
image = self.image()
|
||||
struct.pack_into("<Q", image, SHOFF + 3 * 64 + 32, size)
|
||||
self.reject(image)
|
||||
|
||||
def reject(self, image):
|
||||
result, after = patch(PATCHER, bytes(image), "geometry.so")
|
||||
self.assertEqual(result.returncode, 2, (result.returncode, result.stderr))
|
||||
self.assertIn(b"gnu.hash", result.stderr)
|
||||
self.assertEqual(after, image)
|
||||
|
||||
def test_rebuilt_hash_finds_every_export(self):
|
||||
image = self.image(bloom=2)
|
||||
result, after = patch(PATCHER, image, "valid.so")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
entries = read_dynsym(after)
|
||||
buckets, first, bloom, shift = struct.unpack_from("<4I", after, HASH_OFFSET)
|
||||
bucket_offset = HASH_OFFSET + 16 + bloom * 8
|
||||
chain_offset = bucket_offset + buckets * 4
|
||||
for index in range(first, len(entries)):
|
||||
name = entries[index][0]
|
||||
hashed = gnu_hash(name)
|
||||
word = struct.unpack_from("<Q", after, HASH_OFFSET + 16 + ((hashed // 64) % bloom) * 8)[0]
|
||||
self.assertTrue(word & (1 << (hashed % 64)))
|
||||
self.assertTrue(word & (1 << ((hashed >> shift) % 64)))
|
||||
start = struct.unpack_from("<I", after, bucket_offset + (hashed % buckets) * 4)[0]
|
||||
found = False
|
||||
for candidate in range(start, len(entries)):
|
||||
value = struct.unpack_from("<I", after, chain_offset + (candidate - first) * 4)[0]
|
||||
if (value | 1) == (hashed | 1) and entries[candidate][0] == name:
|
||||
found = True
|
||||
if value & 1:
|
||||
break
|
||||
self.assertTrue(found, name)
|
||||
|
||||
def test_empty_hash_with_no_buckets_is_supported(self):
|
||||
image = self.image(buckets=0, symoffset=len(symbols(False)))
|
||||
result, after = patch(PATCHER, image, "empty.so")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(struct.unpack_from("<I", after, HASH_OFFSET)[0], 0)
|
||||
|
||||
|
||||
class SysvHashTests(unittest.TestCase):
|
||||
def image(self, both, buckets):
|
||||
entries = symbols(False)
|
||||
entries.append(("retained_nid_no_patch", 1, 9, 2, 0x1400))
|
||||
entries[3:] = sorted(entries[3:], key=lambda entry: gnu_hash(entry[0]) % 4)
|
||||
image = build_image(entries, False)
|
||||
offset = 0x600
|
||||
size = 8 + (buckets + len(entries)) * 4
|
||||
struct.pack_into("<II", image, offset, buckets, len(entries))
|
||||
for index, entry in enumerate(entries[1:], 1):
|
||||
bucket_offset = offset + 8 + (sysv_hash(entry[0]) % buckets) * 4
|
||||
head = struct.unpack_from("<I", image, bucket_offset)[0]
|
||||
struct.pack_into("<I", image, offset + 8 + buckets * 4 + index * 4, head)
|
||||
struct.pack_into("<I", image, bucket_offset, index)
|
||||
section = (0, 5, 2, 0, offset, size, 1, 0, 4, 4)
|
||||
struct.pack_into("<IIQQQQIIQQ", image, SHOFF + (4 if both else 3) * 64, *section)
|
||||
if both:
|
||||
struct.pack_into("<H", image, 0x3C, 5)
|
||||
return image
|
||||
|
||||
def test_rebuilt_sysv_hash_finds_renamed_and_preserved_symbols(self):
|
||||
for both in (False, True):
|
||||
for buckets in (1, 3, 7):
|
||||
with self.subTest(both=both, buckets=buckets):
|
||||
image = self.image(both, buckets)
|
||||
before = read_dynsym(image)
|
||||
for name, _, _ in before[1:]:
|
||||
self.assertIsNotNone(sysv_lookup(image, name), name)
|
||||
result, after = patch(PATCHER, image, "sysv.so")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
entries = read_dynsym(after)
|
||||
if not both:
|
||||
self.assertEqual([(entry[1], entry[2]) for entry in entries],
|
||||
[(entry[1], entry[2]) for entry in before])
|
||||
else:
|
||||
self.assertNotEqual([entry[2] for entry in entries], [entry[2] for entry in before])
|
||||
for index, (name, _, _) in enumerate(entries[1:], 1):
|
||||
self.assertEqual(sysv_lookup(after, name), index, name)
|
||||
self.assertEqual(entries[sysv_lookup(after, "retained_nid_no_patch")][2], 0x1400)
|
||||
for name, _, value in before[3:]:
|
||||
if name != "retained_nid_no_patch":
|
||||
self.assertIsNone(sysv_lookup(after, name), name)
|
||||
renamed = next(entry[0] for entry in entries if entry[2] == value)
|
||||
self.assertRegex(renamed, r"^[A-Za-z0-9+-]{11}$")
|
||||
self.assertIsNone(sysv_lookup(after, "missing_nid_no_patch"))
|
||||
|
||||
def test_invalid_sysv_geometry_is_rejected_without_writing(self):
|
||||
for field, value in ((0, 0), (4, 1000), (4, 1)):
|
||||
with self.subTest(field=field, value=value):
|
||||
image = self.image(False, 3)
|
||||
struct.pack_into("<I", image, 0x600 + field, value)
|
||||
result, after = patch(PATCHER, image, "invalid-sysv.so")
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn(b"hash", result.stderr)
|
||||
self.assertEqual(after, image)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
PATCHER = Path(sys.argv.pop(1)).resolve()
|
||||
unittest.main()
|
||||
@@ -1,284 +0,0 @@
|
||||
"""Check nid_patcher on small byte-built Mach-O dylibs: the export trie, the chained imports and what it refuses."""
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
SUFFIX = bytes([0x51, 0x8D, 0x64, 0xA6, 0x35, 0xDE, 0xD8, 0xC1, 0xE6, 0xB0, 0x39, 0xB1, 0xC3, 0xE5, 0x52, 0x30])
|
||||
BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-"
|
||||
|
||||
LC_SEGMENT_64 = 0x19
|
||||
LC_LOAD_DYLIB = 0x0C
|
||||
LC_CODE_SIGNATURE = 0x1D
|
||||
LC_DYLD_INFO_ONLY = 0x80000022
|
||||
LC_DYLD_EXPORTS_TRIE = 0x80000033
|
||||
LC_DYLD_CHAINED_FIXUPS = 0x80000034
|
||||
EXPORT_WEAK = 0x04
|
||||
PAGE = 0x1000
|
||||
|
||||
|
||||
def nid(name):
|
||||
digest = hashlib.sha1(name.encode() + SUFFIX).digest()
|
||||
reversed_bytes = digest[:8][::-1]
|
||||
text = ""
|
||||
for index in (0, 3):
|
||||
triple = (reversed_bytes[index] << 16) | (reversed_bytes[index + 1] << 8) | reversed_bytes[index + 2]
|
||||
text += BASE64[(triple >> 18) & 63] + BASE64[(triple >> 12) & 63] + BASE64[(triple >> 6) & 63] + BASE64[triple & 63]
|
||||
tail = (reversed_bytes[6] << 16) | (reversed_bytes[7] << 8)
|
||||
return text + BASE64[(tail >> 18) & 63] + BASE64[(tail >> 12) & 63] + BASE64[(tail >> 6) & 63]
|
||||
|
||||
|
||||
def uleb(value):
|
||||
out = bytearray()
|
||||
while True:
|
||||
byte = value & 0x7F
|
||||
value >>= 7
|
||||
out.append(byte | (0x80 if value else 0))
|
||||
if not value:
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def read_uleb(data, position):
|
||||
value = shift = 0
|
||||
while True:
|
||||
byte = data[position]
|
||||
position += 1
|
||||
value |= (byte & 0x7F) << shift
|
||||
if not byte & 0x80:
|
||||
return value, position
|
||||
shift += 7
|
||||
|
||||
|
||||
def build_trie(entries):
|
||||
offsets = [0] * len(entries)
|
||||
for _ in range(8):
|
||||
root = bytearray(b"\0") + bytes([len(entries)])
|
||||
for (name, _, _), offset in zip(entries, offsets):
|
||||
root += name.encode() + b"\0" + uleb(offset)
|
||||
nodes = []
|
||||
for name, flags, address in entries:
|
||||
terminal = uleb(flags) + uleb(address)
|
||||
nodes.append(uleb(len(terminal)) + terminal + b"\0")
|
||||
position, expected = len(root), []
|
||||
for node in nodes:
|
||||
expected.append(position)
|
||||
position += len(node)
|
||||
if expected == offsets:
|
||||
break
|
||||
offsets = expected
|
||||
trie = bytes(root) + b"".join(nodes)
|
||||
return trie + bytes(-len(trie) % 8)
|
||||
|
||||
|
||||
def parse_trie(data, start, size):
|
||||
found = {}
|
||||
|
||||
def walk(node, prefix):
|
||||
position = start + node
|
||||
terminal, position = read_uleb(data, position)
|
||||
children = position + terminal
|
||||
if terminal:
|
||||
flags, position = read_uleb(data, position)
|
||||
address, position = read_uleb(data, position)
|
||||
found[prefix] = (flags, address)
|
||||
count = data[children]
|
||||
position = children + 1
|
||||
for _ in range(count):
|
||||
end = data.index(0, position)
|
||||
label = data[position:end].decode()
|
||||
child, position = read_uleb(data, end + 1)
|
||||
walk(child, prefix + label)
|
||||
|
||||
if size:
|
||||
walk(0, "")
|
||||
return found
|
||||
|
||||
|
||||
def build_fixups(imports):
|
||||
symbols = bytearray(b"\0")
|
||||
entries = []
|
||||
for name, ordinal in imports:
|
||||
entries.append(ordinal | (len(symbols) << 9))
|
||||
symbols += name.encode() + b"\0"
|
||||
imports_offset = 32
|
||||
header = struct.pack("<7I", 0, 28, imports_offset, imports_offset + 4 * len(imports), len(imports), 1, 0)
|
||||
blob = header + struct.pack("<I", 0) + b"".join(struct.pack("<I", entry) for entry in entries) + bytes(symbols)
|
||||
return blob + bytes(-len(blob) % 8)
|
||||
|
||||
|
||||
def dylib_command(path):
|
||||
name = path.encode() + b"\0"
|
||||
size = (24 + len(name) + 7) & ~7
|
||||
return struct.pack("<IIIIII", LC_LOAD_DYLIB, size, 24, 2, 0x10000, 0x10000) + name.ljust(size - 24, b"\0")
|
||||
|
||||
|
||||
def build_dylib(exports, imports, signed=False, bind_opcodes=False):
|
||||
trie = build_trie(exports)
|
||||
fixups = build_fixups(imports)
|
||||
linkedit = bytearray(trie + fixups)
|
||||
trie_command = (struct.pack("<IIII", LC_DYLD_EXPORTS_TRIE, 16, PAGE, len(trie)))
|
||||
fixups_command = struct.pack("<IIII", LC_DYLD_CHAINED_FIXUPS, 16, PAGE + len(trie), len(fixups))
|
||||
if bind_opcodes:
|
||||
trie_command = struct.pack("<IIIIIIIIIIII", LC_DYLD_INFO_ONLY, 48, 0, 0, PAGE, 8, 0, 0, 0, 0, PAGE, len(trie))
|
||||
extra = [trie_command, fixups_command, dylib_command("@rpath/libkernel.prx"), dylib_command("/usr/lib/libSystem.B.dylib")]
|
||||
if signed:
|
||||
extra.append(struct.pack("<IIII", LC_CODE_SIGNATURE, 16, PAGE + len(linkedit), 0))
|
||||
text = struct.pack("<II16sQQQQiiII", LC_SEGMENT_64, 72, b"__TEXT", 0, PAGE, 0, PAGE, 5, 5, 0, 0)
|
||||
link = struct.pack("<II16sQQQQiiII", LC_SEGMENT_64, 72, b"__LINKEDIT", PAGE, PAGE, PAGE, len(linkedit), 1, 1, 0, 0)
|
||||
body = text + link + b"".join(extra)
|
||||
header = struct.pack("<IIIIIIII", 0xFEEDFACF, 0x01000007, 3, 6, 2 + len(extra), len(body), 0, 0)
|
||||
image = bytearray(header + body)
|
||||
image += bytes(PAGE - len(image))
|
||||
image += linkedit
|
||||
return bytes(image)
|
||||
|
||||
|
||||
def command_fields(data):
|
||||
offset, found = 32, {}
|
||||
for _ in range(struct.unpack_from("<I", data, 16)[0]):
|
||||
cmd, size = struct.unpack_from("<II", data, offset)
|
||||
found.setdefault(cmd, []).append(offset)
|
||||
offset += size
|
||||
return found
|
||||
|
||||
|
||||
def segment(data, name):
|
||||
for offset in command_fields(data)[LC_SEGMENT_64]:
|
||||
fields = struct.unpack_from("<16sQQQQ", data, offset + 8)
|
||||
if fields[0].rstrip(b"\0").decode() == name:
|
||||
return offset, fields[1:]
|
||||
raise AssertionError(name)
|
||||
|
||||
|
||||
def chained_imports(data):
|
||||
offset = command_fields(data)[LC_DYLD_CHAINED_FIXUPS][0]
|
||||
base, size = struct.unpack_from("<II", data, offset + 8)
|
||||
_, _, imports_offset, symbols_offset, count, _, _ = struct.unpack_from("<7I", data, base)
|
||||
result = []
|
||||
for index in range(count):
|
||||
raw, = struct.unpack_from("<I", data, base + imports_offset + 4 * index)
|
||||
start = base + symbols_offset + (raw >> 9)
|
||||
result.append((data[start:data.index(0, start)].decode(), raw & 0xFF))
|
||||
return result
|
||||
|
||||
|
||||
def patch(patcher, directory, name, image):
|
||||
path = Path(directory) / name
|
||||
path.write_bytes(image)
|
||||
result = subprocess.run([str(patcher), "libtest", str(path)], capture_output=True, text=True, timeout=30)
|
||||
return result, path
|
||||
|
||||
|
||||
def exports_of(data):
|
||||
offset = command_fields(data)[LC_DYLD_EXPORTS_TRIE][0]
|
||||
start, size = struct.unpack_from("<II", data, offset + 8)
|
||||
return parse_trie(data, start, size)
|
||||
|
||||
|
||||
def check_shrinking(patcher, directory):
|
||||
exports = [("_puts_nid_postfix", 0, 0x100), ("_exit_nid_postfix", 0, 0x108), ("_weak_inline", EXPORT_WEAK, 0x110)]
|
||||
imports = [("_malloc", 2), ("_puts_nid_postfix", 1), ("_sceKernelFoo", 1), ("_helper", 1), ("_exit_nid_postfix", 2)]
|
||||
result, path = patch(patcher, directory, "shrink.dylib", build_dylib(exports, imports))
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
data = path.read_bytes()
|
||||
assert exports_of(data) == {"_" + nid("puts"): (0, 0x100), "_" + nid("exit"): (0, 0x108), "_weak_inline": (EXPORT_WEAK, 0x110)}, exports_of(data)
|
||||
assert chained_imports(data) == [("_malloc", 2), ("_" + nid("puts"), 1), ("_" + nid("sceKernelFoo"), 1), ("_helper", 1), ("_exit_nid_postfix", 2)], chained_imports(data)
|
||||
assert len(data) == len(build_dylib(exports, imports)), "the image changed size"
|
||||
|
||||
|
||||
def check_growing(patcher, directory):
|
||||
original = build_dylib([("_ab", 0, 0x100), ("_cd", 0, 0x108)], [])
|
||||
result, path = patch(patcher, directory, "grow.dylib", original)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
data = path.read_bytes()
|
||||
assert exports_of(data) == {"_" + nid("ab"): (0, 0x100), "_" + nid("cd"): (0, 0x108)}, exports_of(data)
|
||||
offset, (vmaddr, vmsize, fileoff, filesize) = segment(data, "__LINKEDIT")
|
||||
assert fileoff + filesize == len(data) and vmsize >= filesize and len(data) > len(original), (fileoff, filesize, len(data))
|
||||
trie_offset, trie_size = struct.unpack_from("<II", data, command_fields(data)[LC_DYLD_EXPORTS_TRIE][0] + 8)
|
||||
assert trie_offset >= len(original) and trie_offset + trie_size <= len(data) and trie_offset % 8 == 0, (trie_offset, trie_size)
|
||||
|
||||
|
||||
def check_preserved(patcher, directory):
|
||||
reference = Path(directory) / "reference.dylib"
|
||||
reference.write_bytes(build_dylib([("_puts", 0, 0x100)], []))
|
||||
path = Path(directory) / "preserve.dylib"
|
||||
path.write_bytes(build_dylib([("_puts_nid_postfix", 0, 0x100), ("_exit_nid_postfix", 0, 0x108)], []))
|
||||
result = subprocess.run([str(patcher), "libtest", "--preserve-exports", str(reference), str(path)], capture_output=True, text=True, timeout=30)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert exports_of(path.read_bytes()) == {"_puts_nid_postfix": (0, 0x100), "_" + nid("exit"): (0, 0x108)}, exports_of(path.read_bytes())
|
||||
|
||||
|
||||
def write_export_list(patcher, reference, listing):
|
||||
return subprocess.run([str(patcher), "--write-export-list", str(reference), str(listing)], capture_output=True, text=True, timeout=30)
|
||||
|
||||
|
||||
def check_export_list(patcher, directory):
|
||||
reference = Path(directory) / "listed.dylib"
|
||||
listing = Path(directory) / "listed.exports"
|
||||
reference.write_bytes(build_dylib([("_puts_nid_postfix", 0, 0x100), ("_exit", 0, 0x108)], []))
|
||||
result = write_export_list(patcher, reference, listing)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert listing.read_bytes() == b"exit\nputs\n", listing.read_bytes()
|
||||
|
||||
os.utime(listing, ns=(1_000_000_000_000_000_000, 1_000_000_000_000_000_000))
|
||||
reference.write_bytes(build_dylib([("_exit", 0, 0x110), ("_puts_nid_postfix", 0, 0x118)], []))
|
||||
result = write_export_list(patcher, reference, listing)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert listing.stat().st_mtime_ns == 1_000_000_000_000_000_000, "an unchanged export list was rewritten"
|
||||
|
||||
reference.write_bytes(build_dylib([("_puts", 0, 0x100)], []))
|
||||
result = write_export_list(patcher, reference, listing)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert listing.read_bytes() == b"puts\n", listing.read_bytes()
|
||||
assert listing.stat().st_mtime_ns != 1_000_000_000_000_000_000, "a changed export list kept its time"
|
||||
|
||||
path = Path(directory) / "listed-preserve.dylib"
|
||||
path.write_bytes(build_dylib([("_puts_nid_postfix", 0, 0x100), ("_exit_nid_postfix", 0, 0x108)], []))
|
||||
result = subprocess.run([str(patcher), "libtest", "--preserve-export-list", str(listing), str(path)], capture_output=True, text=True, timeout=30)
|
||||
assert result.returncode == 0, (result.stdout, result.stderr)
|
||||
assert exports_of(path.read_bytes()) == {"_puts_nid_postfix": (0, 0x100), "_" + nid("exit"): (0, 0x108)}, exports_of(path.read_bytes())
|
||||
|
||||
malformed_lists = [
|
||||
("unterminated", b"puts", "malformed export list"),
|
||||
("blank", b"puts\n\nexit\n", "empty name in export list"),
|
||||
("twice", b"puts\nputs\n", "duplicate name in export list"),
|
||||
("empty", b"", "malformed export list"),
|
||||
]
|
||||
for name, content, message in malformed_lists:
|
||||
malformed = Path(directory) / (name + ".exports")
|
||||
malformed.write_bytes(content)
|
||||
target = Path(directory) / (name + ".dylib")
|
||||
target.write_bytes(build_dylib([("_puts_nid_postfix", 0, 0x100)], []))
|
||||
result = subprocess.run([str(patcher), "libtest", "--preserve-export-list", str(malformed), str(target)], capture_output=True, text=True, timeout=30)
|
||||
assert result.returncode != 0 and message in result.stdout + result.stderr, (name, result.stdout, result.stderr)
|
||||
result = subprocess.run([str(patcher), "libtest", "--preserve-exports", str(reference), "--preserve-export-list", str(listing), str(path)], capture_output=True, text=True, timeout=30)
|
||||
assert result.returncode != 0 and "exactly one reference" in result.stdout + result.stderr, (result.stdout, result.stderr)
|
||||
|
||||
|
||||
def check_refusals(patcher, directory):
|
||||
growing = [("_ab", 0, 0x100), ("_cd", 0, 0x108)]
|
||||
result, _ = patch(patcher, directory, "signed.dylib", build_dylib(growing, [], signed=True))
|
||||
assert result.returncode != 0 and "signed Mach-O images cannot grow their export trie" in result.stdout + result.stderr, (result.stdout, result.stderr)
|
||||
result, _ = patch(patcher, directory, "opcodes.dylib", build_dylib([("_puts_nid_postfix", 0, 0x100)], [], bind_opcodes=True))
|
||||
assert result.returncode != 0 and "bind opcodes are not supported" in result.stdout + result.stderr, (result.stdout, result.stderr)
|
||||
result, _ = patch(patcher, directory, "long.dylib", build_dylib([("_puts_nid_postfix", 0, 0x100)], [("_sceXy", 1)]))
|
||||
assert result.returncode != 0 and "import NID longer than original name" in result.stdout + result.stderr, (result.stdout, result.stderr)
|
||||
|
||||
|
||||
def main():
|
||||
patcher = Path(sys.argv[1]).resolve()
|
||||
with tempfile.TemporaryDirectory(prefix="anyps5-macho-nid-") as directory:
|
||||
check_shrinking(patcher, directory)
|
||||
check_growing(patcher, directory)
|
||||
check_preserved(patcher, directory)
|
||||
check_export_list(patcher, directory)
|
||||
check_refusals(patcher, directory)
|
||||
print("NID patcher Mach-O tests passed")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loaded 100 of 3383 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user