37 Commits
Author SHA1 Message Date
Lago 22d833d569 Adopt template (default-branch: log HTTP code); AnyPS5: mirror_upstream_releases: true
Repo Forker — Sync (mirror upstream) / sync (push) Successful in 49s
2026-10-14 17:04:07 +02:00
Lago a80fb38311 sync.sh: harden default-branch set — log the HTTP code, not just curl's exit status
curl's exit code is 0 even on a 4xx, so the previous '&& echo success' printed
a false positive whenever the runner's PATCH was rejected (e.g. a token issue)
or failed silently — the default stayed 'forker' with a log claiming it was
set. Now capture '%{http_code}', log 2xx as success and non-2xx as WARN with
the response body, so a real failure is visible and retried on the next run
(the block runs on every sync). (The 3 mirrors were set to their upstream
default 'main' manually; this makes it stick and self-heal.)
2026-10-14 17:04:00 +02:00
Lago f74bbbd4bd sync.sh: default-branch membership test must not SIGPIPE under pipefail
'grep -qxF' exits the instant it matches an early line; with a large branch
list (photocraft's 277) the upstream printf can be killed by SIGPIPE (141)
and 'set -o pipefail' then makes the pipeline non-zero — a false 'not
mirrored (filtered)' even though the branch was just pushed. (AnyPS5's small
list finished before grep -q exited, so it worked there.) Use 'grep -xF'
(no -q: reads ALL input, no early exit) and test the captured output.

Log evidence: same 'main' default — AnyPS5 logged 'forker -> main' (patched)
while photocraft logged 'not mirrored (filtered)' (false negative).
2026-10-14 16:55:18 +02:00
Lago e54a98c845 sync.sh: fix default-branch self-correct (strip whitespace + membership test)
First pass had two bugs: (1) the ls-remote --symref sed captured a trailing
TAB into upstream_default, so 'grep -qxF main<tab>' never matched 'main' and
the block silently took the 'filtered' branch (default left as forker);
(2) the membership test quoted the expansion, joining the last branch with the
next list. Now upstream_default is trimmed of leading/trailing whitespace, and
the test uses 'printf %s\n $mirror_branches $fork_branches' (unquoted, like
the push loop) so each branch is on its own line. Verified: main matches,
multi-word expansion works, nonexistent + empty cases are no-ops.
2026-10-14 16:48:00 +02:00
Lago 0e0bf5bb56 sync.sh: self-correct the fork's default branch to match the upstream's
Generated repos are born with default 'forker' (the only branch at generate
time) and Gitea does not switch it once a pre-set branch later appears
(verified experimentally: pre-PATCH to a non-existent branch is a 200 no-op
until re-applied). So on every run, after the refs are pushed, read the
upstream's default via 'git ls-remote --symref <upstream> HEAD' (anonymous —
golden rule kept; honors the Bearer config for private upstreams) and, if the
fork's default differs, PATCH it — but only to a branch the fork actually has
(a MIRROR_BRANCHES filter may exclude the upstream default; never point at
'forker'). Self-heals both existing repos and future ones, and follows an
upstream default change.
2026-10-14 16:43:39 +02:00
Lago 192465422e sync.sh: retry the upstream fetch on transient network errors (per-job DNS flap)
push_once already retried the fork push, but the UPSTREAM fetch was not: the
per-job container intermittently fails to resolve the upstream host (the same
documented DNS flap), so a 'Could not resolve host: github.com' during fetch
aborted the whole run with no retry (e.g. photocraft #1561). Wrap the fetch
in fetch_once (same retry+backoff+patterns as push_once). PUSH_RETRIES is now
defined before the fetch so both share it. A failed fetch still fails the run
loudly — a stale mirror pushed as success is never wanted.
2026-10-14 16:36:53 +02:00
Lago 17d81b0ef5 sync.sh: push --force (a mirror is an exact copy, upstream is authoritative)
The batched single-pack push exposed a latent bug: one divergent fork ref
(a leftover from an interrupted partial mirror — e.g. an upstream rebase or a
re-tag that changed an object SHA) is a NON-FAST-FORWARD, and a single non-FF
ref rejects the ENTIRE multi-ref pack. On photocraft, feat/present-mode-
override had drifted, so every 277-branch pack was rejected in ~2s.

Since this is a MIRROR (upstream is the source of truth), fork refs that have
drifted must be OVERWRITTEN, not fast-forward-checked. Add --force (not
--force-with-lease: the fork's refs are expected to be stale). The machinery
'forker' branch is excluded from the push loop, so it is never clobbered.
Also: push_once now prints the actual git error on a non-network failure
(previously it swallowed the message, leaving only 'failed after N attempts').

Validated with a regression test: created a divergent commit on a scratch
repo, ran sync.sh, and confirmed the ref was force-overwritten to the
upstream SHA (277 branches + 10 tags in one pack, 4.6s, no rejection).
2026-10-14 11:26:53 +02:00
Lago 486843dd0a sync.sh: batch pushes — one multi-ref pack instead of one push per ref
The per-branch loop opened ~280 separate TLS connections to the fork in a
burst (~280 branches + tags), and the remote dropped the ~20th — every run
aborted with a partial mirror (the persistent red runs on large repos).
Now branches and tags each go out in a SINGLE pack (1 connection); a network
failure retries the whole batch cleanly (re-pushing an already-current ref is
idempotent). Prune pushes are batched too. push_once now also matches the
transient failures a big pack produces (RPC failed / early EOF / remote end
hung up) and backs off a bit longer (5s*attempt).

Verified against a scratch repo (19 branches + 8 tags in 2 packs, 9s, no
failure); scratch deleted after.
2026-10-14 11:04:24 +02:00
Lago 78a40f39ec ui: dedupe cold detectMirrors — one shared probe round per N concurrent callers
Page load fires mirrors+runners+queue simultaneously; each used to trigger
its own ~74-request Gitea probe (thundering herd → Gitea throttled one,
first paint stuck on skeletons). Now a cold/forced compute is stored in
mirrorsCache.pending and concurrent callers await the same round. Verified:
3 simultaneous cold calls all 200; repeat polls ~0.3s. Gitea itself is fast
(single call 130-200ms) — the slowness was request amplification.
2026-10-14 10:46:31 +02:00
Lago ea3fcb7745 ui: fix SWR cache race — instant cache return even while a background refresh runs
While a background refresh was in flight, the next /api/mirrors call fell
through to a full recompute and stacked on the running one, hanging ~30s.
The browser's 10s poll then timed out on the very first data load and the
dashboard stuck on skeletons forever. Now: a stale-but-present cache ALWAYS
returns instantly; a background refresh starts only if none is running.
2026-10-14 10:16:56 +02:00
Lago c87e081c8d ui: fix server performance — parallel mirror probing + stale-while-revalidate cache
Cold /api/mirrors took >30s (serial probing of 36 repos x 2 calls +
unpaginated parity), so the client's 10s poll timed out (500) and the
dashboard stuck on skeletons. Now:
- repo probes run in a concurrency-8 pool; per-mirror enrichment in pool 4
- shared 15s cache + stale-while-revalidate (≤10min: instant answer,
  background refresh) — the 3s queue / 15s runner polls no longer re-probe
- anonymous GitHub parity stays 300s-cached (~1 repo/5min, rate-limit safe)

Cold load ≈ 5s, repeat polls ≈ 0.3s (measured live on git.lago.dev).
2026-10-14 10:10:35 +02:00
Lago 1b3a5f9711 Repo Forker UI: local mirror-management control plane (npx repo-forker-ui)
A dark, dense operator console (Vite + React 18 + TS + Tailwind) that runs
locally and manages every mirror generated from this template:

  cd ui && npm install && npm run build && node bin/repo-forker-ui.js
  → http://127.0.0.1:8731

- Zero-dependency Node server (http + fetch): serves the built app and proxies
  the Gitea API. The token stays on this machine (~/.repo-forker/credentials,
  chmod 600) and is never sent in a URL or committed. Upstream parity checks
  for public GitHub repos are anonymous (golden rule).
- Dashboard: all mirrors with health (ok/stale/failed/running/never), last sync,
  duration, parity vs upstream (branches/tags/releases/assets), 7-day run
  sparkline, re-sync / detail / delete.
- Detail: run history (failed runs expand to the failing log line), live log
  viewer (Gitea ::group::/::notice::/::error:: rendered, tail-pinned auto-scroll,
  3s re-poll while a run is in progress), parity, flat .forker.yaml editor
  (validates schema, preserves quotes, no-op writes create no commit),
  variables, units.
- New-mirror wizard: upstream URL → flat config → 5-step creation
  (generate → UPSTREAM_URL → default branch → config → first sync) with progress.
- Runner: serial queue (maxParallel=1) with wait times + runner states.
- States: offline (cached data + banner), empty, loading skeletons, exact-error
  lines. MOCK=1 mode serves canned data for offline work/audits.

Design per ui/DESIGN.md (committed direction + locked token set); verified with
design_audit on all 5 routes (mock) and live against git.lago.dev (3 mirrors).

Docs: ui/README.md (run), ui/DESIGN.md (spec), ui/VERIFY.md (verification),
ui/API-CONTRACT-NOTES.md (Gitea 28.1.0 API shapes, live-verified).
2026-10-14 09:51:04 +02:00
Lago d5e0a8e265 TODO.md: wording polish (npx UI spec) 2026-10-13 22:01:50 +02:00
Lago e758f539af TODO.md: spec for the local mirror-management UI (npx) — P0/P1/P2, stack notes, done-when criteria. Marked A FUTURE (not started). 2026-10-13 21:58:01 +02:00
Lago eae84e8bff Revert template .forker.yaml to documented default (mirror_upstream_releases: false)
A failed local test (broken cd) flipped the template file again and the
'audit round 1' commit picked it up. The documented template default is
false; individual mirror repos enable it when configured (pdfcraft, AnyPS5).
2026-10-13 21:42:19 +02:00
Lago 11bc5c4e04 AGENTS.md: document the per-job DNS flap + push_once retry, and that the artifact cache service is not configured on this Gitea
Repo Forker — Sync (mirror upstream) / sync (push) Successful in 1m15s
2026-10-13 21:37:12 +02:00
Lago 6ff3d0ae98 sync.sh: retry transient network push failures (per-job DNS flapping)
Two consecutive photocraft syncs failed with 'Could not resolve host:
git.lago.dev' on the fork push. The runner-daemon container resolves DNS
fine (getent 10/10), so it is the ephemeral per-job container's network
that flaps. Retry transient network errors (resolve/connect/timeout) with
backoff; abort non-network failures immediately. set -e safe (catch the
failing command-substitution with '|| rc=$?').
2026-10-13 20:58:11 +02:00
Lago eeb4497b85 Remove stray 'f' file (accidental from a failed local test) 2026-10-13 20:38:54 +02:00
Lago 3393756ec4 Harden Repo Forker (audit round 1)
Correctness:
- sync.sh: prune now checks against the FULL upstream branch set (a branch
  outside the MIRROR_BRANCHES filter but still upstream is no longer deleted
  and re-pushed-away); split the filter on commas AND spaces; the branch push
  loop now guards 'forker' (a same-named upstream branch can't clobber the
  machinery branch) and a failed branch/tag push fails the run instead of being
  masked by '&&'.
- sync.yml: add a per-repo 'concurrency' group so an in-flight sync (cold
  fetch can exceed the 10-min cron interval) isn't overlapped by another
  run — which would double-detect a tag and double-publish a release.
- Release semantics: sync.sh now triggers releases for any tag that LACKS a
  release (not just 'new' tags), so a failed release is retried by the next
  cron tick; release.sh publishes only when there is actual content (build
  assets or an existing upstream release) — a 404 upstream (no release for the
  tag) no longer publishes an empty release.

Robustness (fail loudly, no silent partial releases):
- provider.sh: download_asset and publish_local_release use 'curl --fail' and
  check the exit code / HTTP code and file size; a bad asset download or upload
  now aborts the release instead of being attached/corrupt and then masked by
  the idempotency guard. get_release distinguishes a 404 (no upstream release ->
  '{}') from a hard error (non-zero) from a valid release.

check-unit.sh: the units-API self-heal path now reads top-level 'enabled' (not
config.enabled), PATCHes top-level 'enabled', POSTs when the unit row is
missing, and RE-VERIFIES state after the mutation (a 200 alone no longer counts
as a fix).

Docs & infra:
- .gitignore: stop ignoring the whole runner/ dir — keep runner/docker-compose.yml
  tracked (a fresh fork previously had no documented runner setup); still ignore
  runner/config/ (tokens) and the _svc_*.go scratch files.
- AGENTS.md: correct the generated-vs-forked repo sync procedure (generated repos'
  'forker' is an unrelated snapshot -> reset --hard template/forker + re-apply
  config + force-push); document the release-retry + fail-loud behavior.
- README: clarify GITEA_TOKEN is the built-in Actions secret (not a user secret);
  add a Security notes section (anonymous-by-default upstreams; build_cmd runs with
  tokens in env; tokens persist in the cached .mirror config); note the act_runner
  CLI/registration-API quirk + the working PATCH-to-shared path; mark token_user
  unused; quick-start note that releases need a build or mirror mode.
- runner-check.yml + Makefile: 'runner-check' now actually queries the Gitea
  runner APIs (repo-scoped + shared) instead of unconditionally echoing 'online'.
- runner/docker-compose.yml: align the image pin with the live working version.
2026-10-13 20:38:33 +02:00
t ee2a6c7659 t 2026-10-13 20:37:45 +02:00
Lago f67459e46e sync.yml: no-op with a notice when UPSTREAM_URL is unset
The template repo (and any repo not configured as a mirror) has no
UPSTREAM_URL, so the workflow failed on every trigger — 30/30 runs red.
A pre-check step now skips the rest of the job with a notice.
2026-10-13 19:10:13 +02:00
Lago b1df296439 AGENTS.md: operating instructions for AI agents
Golden rules (no personal/stored credentials for upstreams — anonymous by
default; empty token = no auth header; secrets only in Gitea Actions),
how the cron sync/release/check-unit pipeline works, the verified
Gitea-build quirks (forks lack the Releases unit, GitHub asset
download_url null for tag releases, runner registration gaps), and a
file map. Also: prefer generating from this template over forking
(generated repos are not forks -> full unit set, no 1-fork-per-user
limit).
2026-10-13 17:38:16 +02:00
Lago 9ae78d6e89 Revert template .forker.yaml default to mirror_upstream_releases: false
Accidentally flipped to true by a failed test harness (commit 194a20a).
The documented template default is false; individual forks enable it in the
UI when they want release mirroring.
2026-10-13 17:22:01 +02:00
Lago 194a20a333 forker 2026-10-13 17:10:26 +02:00
Lago cd23a46923 check-unit.sh: detect + fix the missing Releases unit on forks
Gitea creates forks without the Releases unit (DefaultForkRepoUnits =
[Code, PullRequests]), so release assets 404 on the web download route.
check-unit.sh:
  - uses the units API to check + self-heal (enable) on builds that have it
  - falls back to probing the web download URL of the latest release's
    asset; a 404 (with the API by-id path still working) confirms the unit
    is missing and prints the exact one-time UI fix
sync.sh runs it at the end of every sync (never fails the sync on its own);
make check-unit runs it standalone.
2026-10-13 16:42:18 +02:00
Lago f6ad6b84c1 README: correct the fork-404 root cause (missing Releases unit, not a generic fork bug)
Verified on git.lago.dev (Gitea 28.1.0): a fork is created with
DefaultForkRepoUnits = [Code, PullRequests] — no Releases unit — so asset
web downloads 404 at the unit-permission check. Fix: enable the Releases
unit in UI Settings. Also the release source tarball 404s on a fork, so
the old 'source tarball is a reliable fallback' claim was wrong.
2026-10-13 14:39:45 +02:00
Lago bb109f10c1 Fix GitHub asset download (5th bug) + unthrottled web URLs
- download_asset: send 'Accept: application/octet-stream'. For a release
  addressed by tag, GitHub's asset download_url is null so the REST asset
  url is used; without this header it returns the asset's JSON metadata
  (HTTP 200, ~1.8 KB) instead of the binary file.
- provider.sh: when a GitHub asset's download_url is null, resolve it to
  the unthrottled WEB download URL (<clone_base>/releases/download/
  <tag>/<name>). The REST asset endpoint is limited to 60 req/h
  unauthenticated — not enough to mirror ~200 assets. Web URL is not
  subject to that limit.
2026-10-13 14:31:27 +02:00
Lago 6d84d33da8 Fix 4 bugs found in the photocraft end-to-end test
- sync.sh: UPSTREAM_TOKEN is optional (public upstreams need no auth);
  only add the Bearer header when a token is set (an empty Bearer header
  makes GitHub reject the request).
- provider.sh: same empty-token fix for get_release/download_asset;
  GitHub's REST API lives on api.github.com (no /api/v1 prefix) — the old
  code built https://github.com/api/v1/... which 404s.
- release.sh: MIRROR mode no longer requires UPSTREAM_TOKEN (public
  upstreams); use the asset's NAME instead of basename(url) — a GitHub
  download_url ends in the numeric asset id, not the file name.
2026-10-11 18:09:47 +02:00
Lago 9361f192db Purge AppImages (history rewrite); Bearer auth per-URL (drops username/cron-actor bug); docs/index.html architecture webpage 2026-10-11 14:59:09 +02:00
Lago 60647811ca sync.yml: Show config reads UPSTREAM_URL via vars context (user vars are not shell env) 2026-10-11 14:20:17 +02:00
Lago e94a4be368 sync.sh: same-instance credential routing (upstream on own Gitea) 2026-10-11 14:15:34 +02:00
Lago b97c2cfd2d Review round 2: pagination for fork-state API, fixed-string ref compare, provider.sh absolute API URLs + heredoc-stdin fix, cache key per-run, fork-asset quirk documented 2026-10-11 12:24:00 +02:00
Lago 2468eecb26 README: document corrected design (API fork-state, inline release, cache, ephemeral workspace) 2026-10-11 12:15:33 +02:00
Lago 15d8368113 Fix host_of: bare-host-only URLs (GITEA_SERVER_URL) now resolve 2026-10-11 12:14:21 +02:00
Lago 98972f7131 Review fixes: credential protocol parsing, API-based fork state, true-mirror layout, inline new-tag release, idempotency, build_script path, .mirror cache 2026-10-11 12:12:50 +02:00
Lago d67f790c9d Fix sync.sh push --git-dir + absolute cred-helper path 2026-10-11 08:30:19 +02:00
Lago f5ccaf8aba Repo Forker: template for live Gitea mirrors + local releases 2026-10-11 08:28:21 +02:00
2555 changed files with 8540 additions and 452611 deletions

No files matched your search

+49
View File
@@ -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: ""
+38
View File
@@ -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 }}
+35
View File
@@ -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.")'
+82
View File
@@ -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.
-65
View File
@@ -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
-13
View File
@@ -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
-45
View File
@@ -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/**'
-18
View File
@@ -1,18 +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 -->
- [ ] 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 -->
-47
View File
@@ -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 200 --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 }}
-345
View File
@@ -1,345 +0,0 @@
name: Build
on:
push:
branches: [main]
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
workflow_dispatch:
inputs:
pr:
description: Pull request number to build
required: true
type: string
linux:
description: Also build and test on Linux
required: false
default: true
type: boolean
permissions:
contents: read
concurrency:
group: build-${{ github.event_name }}-${{ github.event.pull_request.number || inputs.pr || github.ref }}
cancel-in-progress: ${{ github.event_name != 'push' }}
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 }}
steps:
- uses: actions/github-script@v8
id: gate
env:
PR_NUMBER: ${{ inputs.pr }}
with:
script: |
if (context.eventName === 'push') {
if (context.ref !== 'refs/heads/main') {
throw new Error('Automatic full builds only run on main');
}
core.setOutput('sha', context.sha);
core.setOutput('pr', '');
core.setOutput('head', '');
core.setOutput('relinker', true);
core.setOutput('register-context', true);
core.setOutput('write-watch', true);
core.setOutput('full', true);
await core.summary.addRaw(`Building main at ${context.sha}: all builds and tests enabled`).write();
return;
}
const { owner, repo } = context.repo;
const manual = context.eventName === 'workflow_dispatch';
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]*$/.test(process.env.PR_NUMBER)) {
throw new Error('Enter a positive pull request number');
}
}
const pull_number = manual ? Number(process.env.PR_NUMBER) : context.payload.pull_request.number;
if (!Number.isSafeInteger(pull_number) || pull_number < 1) {
throw new Error('Invalid pull request number');
}
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 (pr.state !== 'open' || pr.base.ref !== 'main') {
throw new Error('The pull request 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('The pull request does not merge cleanly into main; rebase it first');
}
let relinker = manual;
if (!manual) {
const { data: commits } = await github.rest.repos.listCommits({
owner, repo, sha: 'main', author: pr.user.login, per_page: 1
});
relinker = commits.length > 0;
}
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number, per_page: 100 });
const paths = files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean));
const touches = (...prefixes) => files.length >= 3000 ||
paths.some((path) => prefixes.some((prefix) => prefix.endsWith('/') ? path.startsWith(prefix) : path === prefix));
const workflow = '.github/workflows/build.yml';
const libc = 'core/libs/prx/libc/';
relinker = 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', workflow
);
const registerContext = touches('core/libs/tests/register_context/', 'core/libs/tests/RegisterContext.cpp', libc, workflow);
const writeWatch = touches('core/libs/tests/write_watch/', 'core/libs/tests/WriteWatch.cpp', libc, workflow);
const { data: main } = await github.rest.repos.getBranch({ owner, repo, branch: 'main' });
core.setOutput('sha', main.commit.sha);
core.setOutput('pr', String(pull_number));
core.setOutput('head', pr.head.sha);
core.setOutput('relinker', relinker);
core.setOutput('register-context', registerContext);
core.setOutput('write-watch', writeWatch);
core.setOutput('full', manual);
core.info(`PR #${pull_number} at ${pr.head.sha} merged into main at ${main.commit.sha}`);
await core.summary.addRaw(
`PR #${pull_number} at ${pr.head.sha} merged into main at ${main.commit.sha}: full builds ${manual ? 'enabled' : 'disabled'}, ` +
`relinker ${relinker ? 'enabled' : 'skipped: no relinker file changed or the author has no commit in main'}, ` +
`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:
- os: ubuntu-latest
compiler: g++
- os: windows-latest
compiler: g++
- os: macos-latest
compiler: clang++
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: |
git fetch --no-tags --unshallow origin "refs/pull/$PR_NUMBER/head"
if [ "$(git rev-parse FETCH_HEAD)" != "$PR_HEAD" ]; then echo "::error::The pull request 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 FETCH_HEAD; then echo "::error::The pull request does not merge cleanly into main; rebase it first"; exit 1; fi
- 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"
- run: cmake -S . -B build-relinker -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=${{ matrix.compiler }} -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON
- run: cmake --build build-relinker --parallel 3
- run: ctest --test-dir build-relinker --output-on-failure --timeout 120
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
- 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
- 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: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
submodules: true
- 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: |
git fetch --no-tags --unshallow origin "refs/pull/$PR_NUMBER/head"
if [ "$(git rev-parse FETCH_HEAD)" != "$PR_HEAD" ]; then echo "::error::The pull request 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 FETCH_HEAD; then echo "::error::The pull request does not merge cleanly into main; rebase it first"; exit 1; fi
git submodule update --init --recursive
- uses: hendrikmuhs/ccache-action@v1.2.24
with:
key: linux
save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
evict-old-files: job
- name: Install lavapipe and the SDL audio and XRandR development files
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
- id: mesa
run: |
echo "version=$(dpkg-query -W -f='${Version}' mesa-vulkan-drivers)" >> "$GITHUB_OUTPUT"
grep -m1 '^model name' /proc/cpuinfo
echo "cpu=$(grep -E '^(vendor_id|cpu family|model|flags)[[:space:]]*:' /proc/cpuinfo | sort -u | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT"
- uses: actions/cache/restore@v6
with:
path: .mesa-shader-cache
key: mesa-${{ steps.mesa.outputs.version }}-${{ steps.mesa.outputs.cpu }}-${{ github.sha }}
restore-keys: mesa-${{ steps.mesa.outputs.version }}-${{ steps.mesa.outputs.cpu }}-
- run: cmake -S . -B build $CONFIGURE -DANYPS5_ENABLE_SPIRV_TOOLS=ON
- name: Check that every test executable is registered with ctest
run: python3 tools/check_test_registration.py build
- run: cmake --build build
- run: cmake --build build --target libs
- run: ctest --test-dir build --output-on-failure --timeout 120 --parallel 4 --output-log ctest.log --output-junit ctest.xml
env:
ANYPS5_REQUIRE_VULKAN: 1
GALLIUM_OVERRIDE_CPU_CAPS: avx
MESA_SHADER_CACHE_DIR: ${{ github.workspace }}/.mesa-shader-cache
- if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && !cancelled() }}
uses: actions/cache/save@v6
with:
path: .mesa-shader-cache
key: mesa-${{ steps.mesa.outputs.version }}-${{ steps.mesa.outputs.cpu }}-${{ github.sha }}
- run: python3 tools/check_skips.py build/ctest.xml
- 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
SSL_CERT_FILE: C:\Program Files\Git\mingw64\etc\ssl\certs\ca-bundle.crt
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
submodules: true
- 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: |
git fetch --no-tags --unshallow origin "refs/pull/$PR_NUMBER/head"
if [ "$(git rev-parse FETCH_HEAD)" != "$PR_HEAD" ]; then echo "::error::The pull request 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 FETCH_HEAD; then echo "::error::The pull request does not merge cleanly into main; rebase it first"; exit 1; fi
git submodule update --init --recursive
- 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: windows
save: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
evict-old-files: job
- shell: cmd
run: cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown"
- name: Check that every test executable is registered with ctest
shell: cmd
run: python tools/check_test_registration.py build
- shell: cmd
run: cmake --build build
- shell: cmd
run: cmake --build build --target libs
- shell: cmd
run: ctest --test-dir 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: 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
-25
View File
@@ -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 }}
-32
View File
@@ -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"
-38
View File
@@ -1,38 +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'
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 stale ededed 'Conflicting with main and no activity for 7 days'
-55
View File
@@ -1,55 +0,0 @@
name: Pages
on:
push:
branches: [main]
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: 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: Download latest release libraries
env:
GITHUB_TOKEN: ${{ github.token }}
run: python3 tools/build_web.py --build build-wasm --libraries
- 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
-77
View File
@@ -1,77 +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;
}
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 open = new Set(openPRs.filter((p) => p.user.login === pr.user.login).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' });
-70
View File
@@ -1,70 +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 -->'
prev=
for file in "$out"/*.md; do
[ -z "$prev" ] || record "$prev" "$hash"
pr=$(basename "$file" .md)
hash=$(sha256sum "$file" | 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}")" = "$(cat "$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 }}
-42
View File
@@ -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
-38
View File
@@ -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
-141
View File
@@ -1,141 +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:
submodules: true
- 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'
env:
SSL_CERT_FILE: 'C:\Program Files\Git\mingw64\etc\ssl\certs\ca-bundle.crt'
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
- name: Configure Linux
if: matrix.platform == 'linux'
run: cmake -S . -B build $CONFIGURE
- name: Configure Windows
if: matrix.platform == 'windows'
shell: cmd
env:
SSL_CERT_FILE: 'C:\Program Files\Git\mingw64\etc\ssl\certs\ca-bundle.crt'
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
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
publish:
name: Publish release
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/checkout@v7
- 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"; 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
-28
View File
@@ -1,28 +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:
- 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
+18 -106
View File
@@ -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
-39
View File
@@ -1,39 +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/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/LibAtrac9 deleted from 946e05a921.
-1
Submodule 3rdparty/SDL2 deleted from 4b69833bc5.
Submodule 3rdparty/SPIRV-Headers deleted from 01e0577914.
Submodule 3rdparty/SPIRV-Tools deleted from 7f2d9ee926.
Submodule 3rdparty/ffmpeg-core deleted from 9ac4cfd195.
Submodule 3rdparty/freetype deleted from 42608f77f2.
-1
Submodule 3rdparty/glslang deleted from ba1640446f.
Submodule 3rdparty/libjpeg-turbo deleted from c85e6b905b.
Submodule 3rdparty/libusb-cmake deleted from bea6567b63.
-1
Submodule 3rdparty/stb deleted from 2c980bb598.
-1
Submodule 3rdparty/tracy deleted from 30997d5ca6.
+151
View File
@@ -0,0 +1,151 @@
# AGENTS.md — how to operate Repo Forker
Instructions for AI agents (and humans) working on or with this repository.
## 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)
-236
View File
@@ -1,236 +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")
function(add_test_executable target)
add_executable(${target} ${ARGN})
set_target_properties(${target} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "$<1:${ANYPS5_TEST_OUTPUT_DIRECTORY}>")
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}")
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)
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)
if(Python3_Interpreter_FOUND)
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 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 conventions_function_bodies COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_comments.py)
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 test_registration COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_test_registration.py)
add_test(NAME check_skips COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py)
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 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 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 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_body_bom COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_body_bom.py)
add_test(NAME conventions_agent_files COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_agent_files.py)
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 OFF 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)
add_subdirectory(core/shader/recompiler)
add_subdirectory(core/Decoder/Jpeg)
add_subdirectory(core/Decoder/Png)
add_subdirectory(core/libs)
add_subdirectory(core/relinker)
-69
View File
@@ -1,69 +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 (NpCppWebApi over NpWebApi2). 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).
- 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, regardless of the author's previous contributions or the changed files. 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.
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 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.
- 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.
- Changes to the AGC driver, the shader recompiler or VideoOut 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 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.
-338
View File
@@ -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.
+43
View File
@@ -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
+200 -22
View File
@@ -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.
[**Web converter**](https://boykopovar.github.io/AnyPS5/) - files stay on your device.
> 🖥️ **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.
![anyps5_collage1](https://github.com/user-attachments/assets/0f8e13e8-1cb7-4c69-8075-39978e138994)
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).
[Discord](https://discord.gg/BHFztBPUe)
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
```
[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`).
[![libraries](https://boykopovar.github.io/AnyPS5/badge-libraries.svg)](https://boykopovar.github.io/AnyPS5/progress.html) [![shaders](https://boykopovar.github.io/AnyPS5/badge-shaders.svg)](https://boykopovar.github.io/AnyPS5/progress.html)
## Quick start (3 steps)
[![progress map](https://boykopovar.github.io/AnyPS5/progress.svg)](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.
+102
View File
@@ -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.
-118
View File
@@ -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()
-21
View File
@@ -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()
-3
View File
@@ -1,3 +0,0 @@
extern "C" int __cxa_thread_atexit(void (*)(void*), void*, void*) {
return 0;
}
-80
View File
@@ -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,40 +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);
} // namespace Decoder::Jpeg
#endif // DECODER_JPEG_HPP
-109
View File
@@ -1,109 +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:
Handle() : handle(tj3Init(TJINIT_COMPRESS)) {
if (!handle) throw std::runtime_error("Jpeg::Encode: encoder 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;
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::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
-112
View File
@@ -1,112 +0,0 @@
#include "Decoder/Jpeg.hpp"
#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());
return 0;
}
-28
View File
@@ -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()
-55
View File
@@ -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
-214
View File
@@ -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
-224
View File
@@ -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;
}
-477
View File
@@ -1,477 +0,0 @@
if(NOT WIN32)
string(REPLACE "-static " "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ")
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()
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)
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-exports "${LIBC_UNPATCHED}" "${PATCHED_FILE}"
DEPENDS nid_patcher ${LIB_NAME} ${UNPATCHED_FILE} ${LIBC_UNPATCHED}
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()
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)
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_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(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)
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(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_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_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_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(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_ppsa01530_exports_tests tests/GuestPPSA01530Exports.cpp)
target_include_directories(guest_ppsa01530_exports_tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(guest_ppsa01530_exports_tests PRIVATE libkernel libSceJson2 libSceNet libScePad libc)
configure_windows_unwind(guest_ppsa01530_exports_tests)
add_test(NAME guest_ppsa01530_exports COMMAND guest_ppsa01530_exports_tests)
if(WIN32)
set_tests_properties(guest_ppsa01530_exports PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libkernel>")
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()
endif()
-17
View File
@@ -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
-91
View File
@@ -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,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
-110
View File
@@ -1,110 +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 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,14 +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);
}
#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
-15
View File
@@ -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
-12
View File
@@ -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
-17
View File
@@ -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
-14
View File
@@ -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");
}
}
-515
View File
@@ -1,515 +0,0 @@
#include <nid/ElfPatcher.hpp>
#include <nid/NidResolver.hpp>
#include <nid/NidPatcherUtils.hpp>
#include <nid/NidCompute.hpp>
#include <algorithm>
#include <unordered_map>
#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;
}
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 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 == 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 (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;
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;
} 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);
}
}
}
-156
View File
@@ -1,156 +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 <bit>
#include <cstring>
#include <fstream>
#include <stdexcept>
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 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;
}
}
-493
View File
@@ -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));
}
}
-54
View File
@@ -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);
}
}
-68
View File
@@ -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;
}
}
-253
View File
@@ -1,253 +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 <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");
const std::uint32_t rawLimit = ((edataSection.SizeOfRawData + fileAlignment - 1u) / fileAlignment) * fileAlignment;
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::uint32_t requiredSize = stringsRegionStart;
for (std::uint32_t i = 0u; i < exportTable.NumberOfNames; ++i)
requiredSize += static_cast<std::uint32_t>(finalNames[i].size()) + 1u;
if (requiredSize > rawLimit)
throw std::runtime_error("not enough raw space in edata section to repack export names");
std::uint32_t writeOffset = stringsRegionStart;
for (std::uint32_t i = 0u; i < exportTable.NumberOfNames; ++i) {
const std::uint32_t newNameRva = edataSection.VirtualAddress + writeOffset;
const std::size_t newNameFileOffset = static_cast<std::size_t>(edataSection.PointerToRawData) + writeOffset;
if (newNameFileOffset + finalNames[i].size() + 1u > pe.size())
throw std::runtime_error("repack write out of file bounds");
std::memcpy(pe.data() + newNameFileOffset, finalNames[i].data(), finalNames[i].size());
pe[newNameFileOffset + finalNames[i].size()] = 0u;
Write(pe, namesArrayOffset + i * 4u, newNameRva);
writeOffset += static_cast<std::uint32_t>(finalNames[i].size()) + 1u;
}
const std::uint32_t newVirtualSize = std::max(edataSection.VirtualSize, writeOffset);
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);
}
}
}
-80
View File
@@ -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;
}
}
-92
View File
@@ -1,92 +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()));
}
}
int Run(int argc, char* argv[]) {
if (argc < 3) {
std::cerr << "Usage: nid_patcher <library_name> [--preserve-exports <unpatched-library>] <file> [file2 ...]\n";
return 1;
}
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") {
if (hasReference || i + 1 == argc) throw std::runtime_error("--preserve-exports requires exactly one reference library");
hasReference = true;
excludedExports = Nid::ReadExportExclusions(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
-60
View File
@@ -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()
-48
View File
@@ -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()
-75
View File
@@ -1,75 +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
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)
if __name__ == "__main__":
PATCHER = Path(sys.argv.pop(1)).resolve()
unittest.main()
-235
View File
@@ -1,235 +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 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 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_refusals(patcher, directory)
print("NID patcher Mach-O tests passed")
if __name__ == "__main__":
main()
-56
View File
@@ -1,56 +0,0 @@
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from test_macho_nids import build_dylib, exports_of, nid
PATCHER = Path(sys.argv.pop(1)).resolve()
class NativePathTests(unittest.TestCase):
def invoke(self, *arguments):
return subprocess.run([str(PATCHER), "libtest", *map(str, arguments)],
capture_output=True, encoding="utf-8", errors="replace", timeout=10)
def test_non_ascii_directory_and_filename_patch_the_intended_file(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary) / "\u6e2c\u8a66"
root.mkdir()
file = root / "\u043c\u043e\u0434\u0443\u043b\u044c.prx"
file.write_bytes(build_dylib([("_puts_nid_postfix", 0, 0x100)], []))
result = self.invoke(file)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(exports_of(file.read_bytes()), {"_" + nid("puts"): (0, 0x100)})
self.assertIn(str(file), result.stdout)
self.assertEqual(list(root.iterdir()), [file])
def test_non_ascii_export_reference_preserves_the_named_export(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
reference = root / "\u6e2c\u8a66-reference.prx"
original = build_dylib([("_puts", 0, 0x100)], [])
reference.write_bytes(original)
file = root / "target.prx"
file.write_bytes(build_dylib([("_puts_nid_postfix", 0, 0x100), ("_exit_nid_postfix", 0, 0x108)], []))
result = self.invoke("--preserve-exports", reference, file)
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(exports_of(file.read_bytes()), {"_puts_nid_postfix": (0, 0x100), "_" + nid("exit"): (0, 0x108)})
self.assertEqual(reference.read_bytes(), original)
def test_missing_unicode_input_does_not_modify_another_file(self):
with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary)
existing = root / "existing.prx"
existing.write_bytes(b"unchanged")
missing = root / "\u6e2c\u8a66-missing.prx"
result = self.invoke(missing)
self.assertEqual(result.returncode, 2)
self.assertIn(str(missing), result.stderr)
self.assertFalse(missing.exists())
self.assertEqual(existing.read_bytes(), b"unchanged")
if __name__ == "__main__":
unittest.main()
-69
View File
@@ -1,69 +0,0 @@
import struct
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from test_macho_nids import build_dylib, exports_of, nid
def reference(*, headers=False, address=0x2000, ordinal=0):
image = bytearray(1280)
image[:2] = b"MZ"
struct.pack_into("<I", image, 0x3c, 0x40)
struct.pack_into("<IHHIIIHH", image, 0x40, 0x4550, 0x8664, 2, 0, 0, 0, 240, 0x2022)
optional = 0x58
struct.pack_into("<H", image, optional, 0x20b)
struct.pack_into("<I", image, optional + 60, 512)
struct.pack_into("<I", image, optional + 108, 16)
start, rva = (416, 416) if headers else (512, 0x1000)
struct.pack_into("<II", image, optional + 112, rva, 80)
for index, (name, va, offset, size) in enumerate(((b".edata", 0x1000, 512, 256), (b".text", 0x2000, 768, 512))):
struct.pack_into("<8sIIIIIIHHI", image, optional + 240 + index * 40,
name, size, va, size, offset, 0, 0, 0, 0, 0x40000040)
struct.pack_into("<IIHHIIIIIII", image, start, 0, 0, 0, 0, rva + 50, 1, 1, 1, rva + 40, rva + 44, rva + 48)
struct.pack_into("<IIH", image, start + 40, address, rva + 50, ordinal)
name = b"puts_nid_postfix\0"
image[start + 50:start + 50 + len(name)] = name
return image
class ReferenceTests(unittest.TestCase):
def patch_with_reference(self, data):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
source, ref = root / "target.dylib", root / "reference.bin"
original = build_dylib([("_puts_nid_postfix", 0, 0x100), ("_exit_nid_postfix", 0, 0x108)], [])
source.write_bytes(original)
ref.write_bytes(data)
result = subprocess.run([str(PATCHER), "libc", str(source), "--preserve-exports", str(ref)], capture_output=True, text=True)
self.assertEqual(ref.read_bytes(), data)
return result, source.read_bytes(), original
def test_header_resident_export_tables(self):
result, image, _ = self.patch_with_reference(reference(headers=True))
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertEqual(exports_of(image), {"_puts_nid_postfix": (0, 0x100), "_" + nid("exit"): (0, 0x108)})
def test_section_resident_export_tables(self):
result, image, _ = self.patch_with_reference(reference())
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("_puts_nid_postfix", exports_of(image))
def test_null_function_slot_does_not_preserve_a_name(self):
result, image, original = self.patch_with_reference(reference(address=0))
self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("no named exports", result.stdout + result.stderr)
self.assertEqual(image, original)
def test_invalid_name_ordinal_is_rejected_without_changing_target(self):
result, image, original = self.patch_with_reference(reference(ordinal=1))
self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)
self.assertIn("ordinal", result.stdout + result.stderr)
self.assertEqual(image, original)
if __name__ == "__main__":
PATCHER = Path(sys.argv.pop(1)).resolve()
unittest.main()
@@ -1,58 +0,0 @@
import struct
import sys
import unittest
from pathlib import Path
from test_symbol_versions import build_image, symbols, patch, SHOFF, DYNSYM_OFFSET, read_dynsym, sections, DEFINITIONS
class SharedStringTests(unittest.TestCase):
def test_dynamic_names_keep_original_string_when_export_shares_offset(self):
for tag in (1, 14, 15, 29):
with self.subTest(tag=tag):
data = build_image(symbols(False), False)
name_offset = struct.unpack_from("<I", data, DYNSYM_OFFSET + 3 * 24)[0]
struct.pack_into("<H", data, 0x3c, 5)
struct.pack_into("<IIQQQQIIQQ", data, SHOFF + 4 * 64, 0, 6, 2, 0, 0x580, 32, 2, 0, 8, 16)
struct.pack_into("<qQqQ", data, 0x580, tag, name_offset, 0, 0)
result, after = patch(PATCHER, bytes(data), "shared-dynamic.so")
self.assertEqual(result.returncode, 0, result.stderr)
strings = sections(after)[2]
new_offset = struct.unpack_from("<Q", after, 0x588)[0]
start = strings[4] + new_offset
self.assertEqual(after[start:after.index(0, start)].decode(), DEFINITIONS[0][0])
renamed = next(entry[0] for entry in read_dynsym(after) if entry[2] == DEFINITIONS[0][2])
self.assertNotEqual(renamed, DEFINITIONS[0][0])
def test_version_requirement_strings_keep_original_names(self):
data = build_image(symbols(False), False)
name_offset = struct.unpack_from("<I", data, DYNSYM_OFFSET + 3 * 24)[0]
struct.pack_into("<H", data, 0x3c, 5)
struct.pack_into("<IIQQQQIIQQ", data, SHOFF + 4 * 64, 0, 0x6ffffffe, 2, 0, 0x580, 32, 2, 1, 8, 0)
struct.pack_into("<HHIII", data, 0x580, 1, 1, name_offset, 16, 0)
struct.pack_into("<IHHII", data, 0x590, 0, 0, 2, name_offset, 0)
result, after = patch(PATCHER, bytes(data), "shared-version.so")
self.assertEqual(result.returncode, 0, result.stderr)
strings = sections(after)[2]
for field in (0x584, 0x598):
offset = struct.unpack_from("<I", after, field)[0]
start = strings[4] + offset
self.assertEqual(after[start:after.index(0, start)].decode(), DEFINITIONS[0][0])
renamed = next(entry[0] for entry in read_dynsym(after) if entry[2] == DEFINITIONS[0][2])
self.assertNotEqual(renamed, DEFINITIONS[0][0])
def test_local_symbol_keeps_name_shared_with_renamed_global(self):
entries = symbols(False)
entries[1] = (DEFINITIONS[0][0], 1, 9, 2, 0x1500)
data = build_image(entries, False)
data[DYNSYM_OFFSET + 24 + 4] = 2
result, after = patch(PATCHER, bytes(data), "shared-local.so")
self.assertEqual(result.returncode, 0, result.stderr)
names = {value: name for name, _, value in read_dynsym(after)}
self.assertEqual(names[0x1500], DEFINITIONS[0][0])
self.assertNotEqual(names[DEFINITIONS[0][2]], DEFINITIONS[0][0])
if __name__ == "__main__":
PATCHER = Path(sys.argv.pop(1)).resolve()
unittest.main()
-209
View File
@@ -1,209 +0,0 @@
import re
import struct
import subprocess
import sys
import tempfile
from pathlib import Path
SHT_NULL = 0
SHT_STRTAB = 3
SHT_DYNSYM = 11
SHT_GNU_HASH = 0x6FFFFFF6
SHT_GNU_VERDEF = 0x6FFFFFFD
SHT_GNU_VERSYM = 0x6FFFFFFF
SHN_UNDEF = 0
SHN_ABS = 0xFFF1
STB_GLOBAL = 1
STT_FUNC = 2
LIBRARY_NAME = "libsymbols"
DYNSYM_OFFSET = 0x200
DYNSTR_OFFSET = 0x300
HASH_OFFSET = 0x500
VERSYM_OFFSET = 0x580
VERDEF_OFFSET = 0x600
SHOFF = 0x800
BUCKETS = 4
HASHED_FROM = 3
NID_NAME = re.compile(r"^[A-Za-z0-9+-]{11}$")
SONAME = "libsymbols.so"
VERSIONS = [(1, [SONAME]), (2, ["VERS_ONE"]), (3, ["VERS_TWO", "VERS_ONE"])]
MARKERS = [("VERS_ONE", 2, 0x1100), ("VERS_TWO", 3, 0x1101)]
DEFINITIONS = [
("sceAlphaComputeLength", 2, 0x1200),
("sceAlphaCompareStrings", 2, 0x1220),
("sceAlphaFindCharacter", 2, 0x1240),
("sceBetaCopyString", 3, 0x1260),
("sceBetaConcatenateStrings", 3, 0x1280),
("sceBetaSearchCharacter", 3, 0x12A0),
]
IMPORTS = ["jeJEvW13vxk", "e0m0E5Sq2N8"]
def gnu_hash(name):
value = 5381
for byte in name.encode("utf-8"):
value = (value * 33 + byte) & 0xFFFFFFFF
return value
def symbols(versioned):
entries = [(None, 1, SHN_UNDEF, 0, 0)]
entries += [(name, 1, SHN_UNDEF, 0, 0) for name in IMPORTS]
if versioned:
entries += [(name, version, SHN_ABS, 0, value) for name, version, value in MARKERS]
entries += [(name, version, 9, STT_FUNC, value) for name, version, value in DEFINITIONS]
else:
entries += [(name, 1, 9, STT_FUNC, value) for name, _, value in DEFINITIONS]
return entries
def string_table(names):
offsets = {}
table = bytearray(b"\x00")
for name in names:
offsets.setdefault(name, len(table))
table += name.encode("utf-8") + b"\x00"
return table, offsets
def build_image(entries, versioned):
image = bytearray(0x1000)
image[:16] = b"\x7fELF\x02\x01\x01" + bytes(9)
names = [entry[0] for entry in entries if entry[0]]
if versioned:
names += [name for _, version_names in VERSIONS for name in version_names]
strings, offsets = string_table(names)
for index, (name, version, shndx, symbol_type, value) in enumerate(entries):
info = (STB_GLOBAL << 4) | symbol_type
struct.pack_into("<IBBHQQ", image, DYNSYM_OFFSET + index * 24,
offsets[name] if name else 0, info, 0, shndx, value, 0x10 if symbol_type else 0)
image[DYNSTR_OFFSET:DYNSTR_OFFSET + len(strings)] = strings
chain_count = len(entries) - HASHED_FROM
bucket_offset = HASH_OFFSET + 16 + 8
chain_offset = bucket_offset + BUCKETS * 4
struct.pack_into("<IIII", image, HASH_OFFSET, BUCKETS, HASHED_FROM, 1, 6)
for index in range(HASHED_FROM, len(entries)):
name = entries[index][0]
bucket = gnu_hash(name) % BUCKETS
if struct.unpack_from("<I", image, bucket_offset + bucket * 4)[0] == 0:
struct.pack_into("<I", image, bucket_offset + bucket * 4, index)
chain = gnu_hash(name)
if index + 1 == len(entries) or gnu_hash(entries[index + 1][0]) % BUCKETS != bucket:
chain |= 1
struct.pack_into("<I", image, chain_offset + (index - HASHED_FROM) * 4, chain)
verdef_end = 0
if versioned:
for index, (_, version, _, _, _) in enumerate(entries):
struct.pack_into("<H", image, VERSYM_OFFSET + index * 2, version)
position = VERDEF_OFFSET
for version_index, version_names in VERSIONS:
entry_size = 20 + 8 * len(version_names)
struct.pack_into("<HHHHIII", image, position, 1, 1 if version_index == 1 else 0, version_index,
len(version_names), gnu_hash(version_names[0]), 20,
0 if version_index == len(VERSIONS) else entry_size)
aux = position + 20
for name_index, name in enumerate(version_names):
struct.pack_into("<II", image, aux, offsets[name], 0 if name_index + 1 == len(version_names) else 8)
aux += 8
position += entry_size
verdef_end = position
sections = [
(0, SHT_NULL, 0, 0, 0, 0, 0, 0, 0, 0),
(0, SHT_DYNSYM, 2, 0, DYNSYM_OFFSET, len(entries) * 24, 2, 1, 8, 24),
(0, SHT_STRTAB, 2, 0, DYNSTR_OFFSET, len(strings), 0, 0, 1, 0),
(0, SHT_GNU_HASH, 2, 0, HASH_OFFSET, chain_offset - HASH_OFFSET + chain_count * 4, 1, 0, 8, 0),
]
if versioned:
sections.append((0, SHT_GNU_VERSYM, 2, 0, VERSYM_OFFSET, len(entries) * 2, 1, 0, 2, 2))
sections.append((0, SHT_GNU_VERDEF, 2, 0, VERDEF_OFFSET, verdef_end - VERDEF_OFFSET, 2, len(VERSIONS), 4, 0))
struct.pack_into("<HHIQQQIHHHHHH", image, 16, 3, 62, 1, 0, 0, SHOFF, 0, 64, 0, 0, 64, len(sections), 0)
for index, section in enumerate(sections):
struct.pack_into("<IIQQQQIIQQ", image, SHOFF + index * 64, *section)
return image
def sections(image):
shoff, = struct.unpack_from("<Q", image, 0x28)
shentsize, shnum = struct.unpack_from("<HH", image, 0x3A)
return [struct.unpack_from("<IIQQQQIIQQ", image, shoff + index * shentsize) for index in range(shnum)]
def read_dynsym(image):
headers = sections(image)
dynsym = next(section for section in headers if section[1] == SHT_DYNSYM)
strings = headers[dynsym[6]]
entries = []
for index in range(dynsym[5] // 24):
name_offset, _, _, shndx, value, _ = struct.unpack_from("<IBBHQQ", image, dynsym[4] + index * 24)
name = None
if name_offset:
end = image.index(0, strings[4] + name_offset)
name = image[strings[4] + name_offset:end].decode("utf-8")
entries.append((name, shndx, value))
return entries
def patch(patcher, image, filename):
with tempfile.TemporaryDirectory(prefix="anyps5-symbol-versions-") as directory:
path = Path(directory) / filename
path.write_bytes(image)
result = subprocess.run([patcher, LIBRARY_NAME, str(path)], capture_output=True)
return result, path.read_bytes()
def test_versioned_library_is_rejected(patcher):
image = bytes(build_image(symbols(True), True))
assert any(section[1] == SHT_GNU_VERDEF for section in sections(image))
result, on_disk = patch(patcher, image, SONAME)
assert result.returncode == 2, (result.returncode, result.stderr)
message = result.stderr.decode("utf-8", errors="replace")
assert message.startswith("FAIL: "), message
assert ".gnu.version_d" in message, message
assert result.stdout == b"", result.stdout
assert on_disk == image, "the rejected library was written back modified"
def test_unversioned_library_is_still_patched(patcher):
image = bytes(build_image(symbols(False), False))
assert not any(section[1] == SHT_GNU_VERDEF for section in sections(image))
before = read_dynsym(image)
result, patched = patch(patcher, image, SONAME)
assert result.returncode == 0, result.stderr.decode("utf-8", errors="replace")
assert result.stdout.decode("utf-8", errors="replace").startswith("OK: "), result.stdout
after = read_dynsym(patched)
assert len(after) == len(before), (before, after)
assert [entry[0] for entry in after] != [entry[0] for entry in before], "no export was renamed"
for name, _, value in DEFINITIONS:
found = [entry for entry in after if entry[2] == value]
assert len(found) == 1, (name, found)
renamed, shndx, _ = found[0]
assert renamed != name, (name, found)
assert NID_NAME.match(renamed), (name, found)
assert shndx == 9, (name, found)
for name in IMPORTS:
found = [entry for entry in after if entry[0] == name]
assert found == [(name, SHN_UNDEF, 0)], (name, found)
assert len({entry[0] for entry in after if entry[0]}) == len([entry for entry in after if entry[0]])
def main():
patcher = Path(sys.argv[1]).resolve()
test_versioned_library_is_rejected(patcher)
test_unversioned_library_is_still_patched(patcher)
print("NID patcher symbol version tests passed")
if __name__ == "__main__":
main()
-76
View File
@@ -1,76 +0,0 @@
import struct
import sys
import unittest
from pathlib import Path
from test_symbol_versions import build_image, symbols, patch, SHOFF, DYNSTR_OFFSET, sections
VERNEED = 0x580
def image(*, auxiliary=16, count=1, size=32, version=1, auxnext=0, nextrecord=0):
data = build_image(symbols(False), False)
strings = sections(data)[2]
filename = strings[5]
names = b"libfixture.so\0FIXTURE_1\0"
data[DYNSTR_OFFSET + filename:DYNSTR_OFFSET + filename + len(names)] = names
struct.pack_into("<Q", data, SHOFF + 2 * 64 + 32, filename + len(names))
struct.pack_into("<H", data, 0x3c, 5)
struct.pack_into("<IIQQQQIIQQ", data, SHOFF + 4 * 64, 0, 0x6ffffffe, 2, 0, VERNEED, size, 2, 1, 8, 0)
struct.pack_into("<HHIII", data, VERNEED, version, count, filename, auxiliary, nextrecord)
struct.pack_into("<IHHII", data, VERNEED + auxiliary, 0, 0, 2, filename + len(b"libfixture.so\0"), auxnext)
return data
class VersionRequirementsTests(unittest.TestCase):
def test_auxiliary_record_cannot_leave_declared_section(self):
self.reject(image(auxiliary=32))
def test_auxiliary_count_must_match_chain(self):
self.reject(image(count=2))
def test_unsupported_structure_version_is_rejected(self):
self.reject(image(version=2))
def test_invalid_forward_links_and_section_ranges_are_rejected(self):
for fields in ({"auxnext": 16}, {"nextrecord": 64}, {"size": 15},
{"size": 0x10000}, {"auxiliary": 8}, {"count": 2, "auxnext": 8}):
with self.subTest(fields=fields):
self.reject(image(**fields))
def test_valid_multiple_auxiliaries_and_requirements(self):
data = image(count=2, size=80, auxnext=16, nextrecord=48)
original_name = struct.unpack_from("<I", data, VERNEED + 24)[0]
original_file = struct.unpack_from("<I", data, VERNEED + 4)[0]
struct.pack_into("<IHHII", data, VERNEED + 32, 0, 0, 3, original_name, 0)
struct.pack_into("<HHIII", data, VERNEED + 48, 1, 1, original_file, 16, 0)
struct.pack_into("<IHHII", data, VERNEED + 64, 0, 0, 4, original_name, 0)
result, after = patch(PATCHER, bytes(data), "multiple-versions.so")
self.assertEqual(result.returncode, 0, result.stderr)
strings = sections(after)[2]
for position, expected in ((4, b"libfixture.so"), (24, b"FIXTURE_1"),
(40, b"FIXTURE_1"), (52, b"libfixture.so"), (72, b"FIXTURE_1")):
offset = struct.unpack_from("<I", after, VERNEED + position)[0]
start = strings[4] + offset
self.assertEqual(after[start:after.index(0, start)], expected)
def reject(self, data):
result, after = patch(PATCHER, bytes(data), "versions.so")
self.assertEqual(result.returncode, 2, (result.returncode, result.stderr))
self.assertIn(b"version_r", result.stderr)
self.assertEqual(after, data)
def test_valid_names_are_preserved_when_strings_are_rebuilt(self):
data = image()
result, after = patch(PATCHER, bytes(data), "valid-versions.so")
self.assertEqual(result.returncode, 0, result.stderr)
strings = sections(after)[2]
for position, expected in ((VERNEED + 4, b"libfixture.so"), (VERNEED + 16 + 8, b"FIXTURE_1")):
offset = struct.unpack_from("<I", after, position)[0]
start = strings[4] + offset
self.assertEqual(after[start:after.index(0, start)], expected)
if __name__ == "__main__":
PATCHER = Path(sys.argv.pop(1)).resolve()
unittest.main()
-69
View File
@@ -1,69 +0,0 @@
#include <cstdint>
#include <cstddef>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
#include <atomic>
// Audio co-processor batches complete immediately without producing output; audio is silent.
static constexpr int SCE_ACM_ERROR_INVALID_PARAMETER = static_cast<int>(0x80E30002);
static std::atomic<uint32_t> g_nextId{1};
extern "C" {
int APS5_VABI sceAcmBatchStartBuffer(AcmContextId context, const void* batch_commands, size_t batch_size, AcmBatchError* batch_error, AcmBatchId* batch) {
(void)context;
(void)batch_commands;
(void)batch_size;
(void)batch_error;
if (!batch) return SCE_ACM_ERROR_INVALID_PARAMETER;
*batch = g_nextId.fetch_add(1, std::memory_order_relaxed);
return 0;
}
int APS5_VABI sceAcmBatchStartBuffers(AcmContextId context, uint32_t batch_info_count, const AcmBatchInfo* const batch_info[], AcmBatchError* batch_error, AcmBatchId* batch) {
(void)context;
(void)batch_info_count;
(void)batch_info;
(void)batch_error;
if (!batch) return SCE_ACM_ERROR_INVALID_PARAMETER;
*batch = g_nextId.fetch_add(1, std::memory_order_relaxed);
return 0;
}
int APS5_VABI sceAcmBatchWait(AcmContextId context, AcmBatchId batch, uint32_t timeout) {
(void)context;
(void)batch;
(void)timeout;
return 0;
}
int APS5_VABI sceAcmContextCreate(AcmContextId* context) {
if (!context) return SCE_ACM_ERROR_INVALID_PARAMETER;
*context = g_nextId.fetch_add(1, std::memory_order_relaxed);
return 0;
}
int APS5_VABI sceAcmContextDestroy(AcmContextId context) {
(void)context;
return 0;
}
// Builds a convolution-reverb command into a batch; batches execute as no-ops, so nothing is encoded.
int APS5_VABI sceAcm_ConvReverb_SharedInput(void) {
return 0;
}
int APS5_VABI sceAcm_FFT(void) {
return 0;
}
int APS5_VABI sceAcm_Panner(void) {
return 0;
}
int APS5_VABI sceAcmBatchJobPriority(void) {
NotImplemented_nid_no_patch(__func__);
return 0;
}
}
@@ -1,4 +0,0 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_CONTROL_HPP
#define CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_CONTROL_HPP
#endif
@@ -1,4 +0,0 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_DISPATCH_HPP
#define CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_DISPATCH_HPP
#endif
@@ -1,4 +0,0 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_MEMORY_HPP
#define CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_MEMORY_HPP
#endif
@@ -1,4 +0,0 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_SYNC_HPP
#define CORE_LIBS_PRX_LIBSCEAGC_ACB_INCLUDE_SYNC_HPP
#endif
-115
View File
@@ -1,115 +0,0 @@
#include "prx/libSceAgc/Acb/include/Control.hpp"
#include "prx/libSceAgc/Command/include/Control.hpp"
#include "prx/libSceAgc/Command/include/Memory.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include "prx/libSceAgc/DcbState/include/Marker.hpp"
#include "prx/libSceAgcDriver/Execution/include/VideoOutput.hpp"
#include "prx/libSceAgcDriver/Resource/include/Registration.hpp"
#include <cstdint>
#include <cstddef>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
namespace {
std::uint32_t* RejectUnregisteredWorkloadStream(CommandBuffer* buf, std::uint32_t streamId, const char* function) {
if (buf == nullptr || !AgcDriverWorkloadStreamRegistered_nid_postfix(streamId)) return nullptr;
NotImplemented_nid_no_patch(function);
return nullptr;
}
}
extern "C" {
std::uint32_t* APS5_VABI sceAgcAcbAtomicGds_0900(CommandBuffer* buf, std::uint32_t control, std::uint32_t mode, std::uint32_t gdsOp, std::uint32_t src, std::uint16_t offset, std::uint16_t index, std::uint32_t mask, std::uint32_t data, std::uint64_t compareData, std::uint64_t extraData) {
const auto operation = (control & 0xffu) | ((control & 0x200u) << 7u) |
((control & 0x20u) << 13u) | ((control & 0x40u) << 14u) |
((control & 0x20u) == 0 && mode == 1 ? 0x20000u : 0u);
return Agc::Command::Emit(buf, 0x1du, {
operation, ((gdsOp & 1u) << 8u) | (src & 0x3fu), offset, index,
mask & 0x00ff00ffu, data, static_cast<std::uint32_t>(compareData),
static_cast<std::uint32_t>(compareData >> 32u), static_cast<std::uint32_t>(extraData),
static_cast<std::uint32_t>(extraData >> 32u)}, __func__);
}
std::uint32_t* APS5_VABI sceAgcAcbJump(CommandBuffer* buf, std::uint8_t cachePolicy, const std::uint32_t* target, std::uint32_t sizeInDwords) {
return Agc::Command::WriteJump(buf, 1, cachePolicy, target, sizeInDwords, __func__);
}
uint32_t APS5_VABI sceAgcAcbJumpGetSize(void) {
return 16;
}
// Encoded as the custom DISPATCH_RESET NOP packet the driver consumes on compute queues.
uint32_t* APS5_VABI sceAgcAcbResetQueue(CommandBuffer* buf, uint32_t op, uint32_t value) {
(void)value;
Agc::Command::Require(buf != nullptr, __func__, "null command buffer");
constexpr std::uint32_t OpcodeNop = 0x10;
constexpr std::uint32_t CustomDispatchReset = 0x09;
auto* packet = Agc::Command::Allocate(buf, 2, __func__);
packet[0] = Agc::Command::Header(OpcodeNop, 2, CustomDispatchReset << 2);
packet[1] = op;
return packet;
}
std::uint32_t* APS5_VABI sceAgcAcbRewind(CommandBuffer* buf, std::uint32_t initialState) {
return Agc::Command::WriteRewind(buf, initialState, __func__);
}
std::uint32_t APS5_VABI sceAgcAcbRewindGetSize() {
return 8;
}
std::uint32_t* APS5_VABI sceAgcAcbWaitUntilSafeForRendering(CommandBuffer* buf, std::uint32_t videoOutHandle, std::uint32_t displayBufferIndex) {
auto* packet = Agc::Command::Allocate(buf, AgcDriver::RenderingWaitPacketWords, __func__);
packet[0] = AgcDriver::RenderingWaitPacketHeader;
packet[1] = videoOutHandle;
packet[2] = displayBufferIndex;
packet[3] = 0;
return packet;
}
std::uint32_t* APS5_VABI sceAgcAcbSetFlip(CommandBuffer* buf, std::uint32_t videoOutHandle, std::int32_t displayBufferIndex, std::uint32_t flipMode, std::int64_t flipArg) {
(void)buf;
(void)videoOutHandle;
(void)displayBufferIndex;
(void)flipMode;
(void)flipArg;
NotImplemented_nid_no_patch(__func__);
return nullptr;
}
std::uint32_t* APS5_VABI sceAgcAcbSetWorkloadsActive(CommandBuffer* buf, std::uint32_t streamId, const std::uint32_t* workloadIds, std::uint32_t workloadCount) {
(void)workloadIds;
(void)workloadCount;
return RejectUnregisteredWorkloadStream(buf, streamId, __func__);
}
std::uint32_t* APS5_VABI sceAgcAcbSetWorkloadComplete(CommandBuffer* buf, std::uint32_t streamId, std::uint32_t workloadId) {
(void)workloadId;
return RejectUnregisteredWorkloadStream(buf, streamId, __func__);
}
std::uint32_t* APS5_VABI sceAgcAcbSetWorkloadStreamInactive(CommandBuffer* buf, std::uint32_t streamId) {
return RejectUnregisteredWorkloadStream(buf, streamId, __func__);
}
uint32_t* APS5_VABI sceAgcAcbPushMarker(CommandBuffer* buf, const char* str, uint32_t color) {
(void)color;
return Agc::Marker::Push(buf, str, __func__);
}
uint32_t* APS5_VABI sceAgcAcbPopMarker(CommandBuffer* buf) {
return Agc::Marker::Pop(buf, __func__);
}
uint32_t* APS5_VABI sceAgcAcbSetMarker(CommandBuffer* buf, const char* str, uint32_t color) {
(void)color;
auto* packet = Agc::Marker::Push(buf, str, __func__);
Agc::Marker::Pop(buf, __func__);
return packet;
}
}
@@ -1,24 +0,0 @@
#include "prx/libSceAgc/Acb/include/Dispatch.hpp"
#include "prx/libSceAgc/Command/include/Memory.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include <cstdint>
#include <cstddef>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
extern "C" {
uint32_t* APS5_VABI sceAgcAcbDispatchIndirect(CommandBuffer* buf, const volatile void* indirect_args, uint32_t modifier) {
// Compute queues take the argument address directly (DISPATCH_INDIRECT with a 64-bit address).
const auto address = reinterpret_cast<std::uintptr_t>(indirect_args);
Agc::Command::CheckAddress(address, 4, __func__);
Agc::Command::CheckBits(modifier, 0xa038u | 0x41u, __func__);
return Agc::Command::Emit(buf, 0x16u, {static_cast<std::uint32_t>(address), static_cast<std::uint32_t>(address >> 32u), modifier | 0x41u}, __func__);
}
std::uint32_t APS5_VABI sceAgcAcbDispatchIndirectGetSize() {
return 16;
}
}
@@ -1,61 +0,0 @@
#include "prx/libSceAgc/Acb/include/Memory.hpp"
#include "prx/libSceAgc/DcbFlow/include/Memory.hpp"
#include "prx/libSceAgc/Command/include/Memory.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include <cstdint>
#include <cstddef>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
extern "C" {
std::uint32_t* APS5_VABI sceAgcAcbAcquireMem(CommandBuffer* buf, std::uint32_t gcrControl, const volatile void* base, std::uint64_t sizeBytes, std::uint32_t pollCycles) {
return sceAgcDcbAcquireMem(buf, 1, 0, gcrControl, base, sizeBytes, pollCycles);
}
uint32_t APS5_VABI sceAgcAcbAcquireMemGetSize(void) {
return 32;
}
uint32_t* APS5_VABI sceAgcAcbCopyData(CommandBuffer* buf, uint8_t dst, uint8_t dst_cache_policy, uint64_t dst_address, uint8_t src, uint8_t src_cache_policy, uint64_t src_address_or_immediate, uint8_t item_size, uint8_t write_confirm) {
return Agc::Command::WriteCopyData(buf, true, dst, dst_cache_policy, dst_address, src, src_cache_policy, src_address_or_immediate, item_size, write_confirm, __func__);
}
std::uint64_t APS5_VABI sceAgcAcbCopyDataGetSize() {
return 24;
}
std::uint32_t* APS5_VABI sceAgcAcbDmaData(CommandBuffer* buf, std::uint8_t dst, std::uint8_t dstCachePolicy, std::uint64_t dstAddress, std::uint8_t src, std::uint8_t srcCachePolicy, std::uint64_t srcAddress, std::uint32_t numBytes, std::uint8_t waitForPrevious, std::uint8_t writeConfirm) {
return Agc::Command::WriteDma(buf, true, 0, dst, dstCachePolicy, dstAddress, src, srcCachePolicy, srcAddress, numBytes, waitForPrevious, writeConfirm, 0, __func__);
}
std::uint32_t APS5_VABI sceAgcAcbDmaDataGetSize() {
return 28;
}
std::uint32_t* APS5_VABI sceAgcAcbAtomicMem(CommandBuffer* buf, std::uint8_t atomicOp, std::uint8_t command, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t srcData, std::uint64_t compareData, std::uint16_t loopInterval) {
return Agc::Command::WriteAtomicMem(buf, atomicOp, command, cachePolicy, address, srcData, compareData, loopInterval, __func__);
}
std::uint32_t APS5_VABI sceAgcAcbAtomicMemGetSize() {
return 36;
}
std::uint32_t APS5_VABI sceAgcAcbAtomicGdsGetSize() {
return 36;
}
std::uint32_t* APS5_VABI sceAgcAcbPrimeUtcl2(CommandBuffer* buf, const volatile void* address, std::uint32_t sizeInBytes) {
return Agc::Command::WritePrimeUtcl2(buf, address, sizeInBytes, __func__);
}
std::uint32_t APS5_VABI sceAgcAcbPrimeUtcl2GetSize() {
return 20;
}
std::uint32_t* APS5_VABI sceAgcAcbWriteData(CommandBuffer* buf, std::uint8_t dst, std::uint8_t cachePolicy, std::uint64_t address, const void* data, std::uint32_t numDwords, std::uint8_t increment, std::uint8_t writeConfirm) {
return Agc::Command::WriteData(buf, true, dst, cachePolicy, address, data, numDwords, increment, writeConfirm, __func__);
}
}
-54
View File
@@ -1,54 +0,0 @@
#include "prx/libSceAgc/Acb/include/Sync.hpp"
#include "prx/libSceAgc/Command/include/Control.hpp"
#include "prx/libSceAgc/Command/include/Memory.hpp"
#include "prx/libSceAgc/Command/include/Packet.hpp"
#include <cstdint>
#include <cstddef>
#include "SceTypes.hpp"
#include "prx/libc/include/General.hpp"
extern "C" {
uint32_t* APS5_VABI sceAgcAcbCondExec(CommandBuffer* buf, const volatile uint32_t* address, uint32_t num_dwords) {
const auto guestAddress = reinterpret_cast<std::uintptr_t>(address);
Agc::Command::CheckAddress(guestAddress, 4, __func__);
Agc::Command::Require(num_dwords <= 0x3fffu, __func__, "conditional execution range is too large");
return Agc::Command::Emit(buf, 0x22u, {static_cast<std::uint32_t>(guestAddress) & ~3u, static_cast<std::uint32_t>(guestAddress >> 32u), 0, num_dwords & 0x3fffu}, __func__);
}
uint32_t APS5_VABI sceAgcAcbCondExecGetSize(void) {
return 20;
}
std::uint32_t* APS5_VABI sceAgcAcbWaitRegMem(CommandBuffer* buf, std::uint8_t size, std::uint8_t compareFunction, std::uint8_t cachePolicy, const volatile void* address, std::uint64_t reference, std::uint64_t mask, std::uint32_t pollCycles) {
return Agc::Command::WriteWait(buf, size, compareFunction, 0, cachePolicy, address, reference, mask, pollCycles, __func__);
}
std::uint64_t APS5_VABI sceAgcAcbWaitOnAddressGetSize(std::uint8_t size) {
return size == 0 ? 56 : 64;
}
std::uint32_t* APS5_VABI sceAgcAcbEventWrite(CommandBuffer* buf, std::uint8_t eventType, const volatile void* address) {
Agc::Command::CheckBits(eventType, 0x3fu, __func__);
Agc::Command::Require(address == nullptr, __func__, "ACB event address is not supported");
return Agc::Command::Emit(buf, 0x46u, {eventType | (eventType == 7 ? 0x400u : 0u)}, __func__);
}
std::uint64_t APS5_VABI sceAgcAcbEventWriteGetSize(std::uint8_t eventType) {
(void)eventType;
return 8;
}
std::uint32_t APS5_VABI sceAgcAcbQueueEndOfShaderActionGetSize() {
return 32;
}
std::uint32_t* APS5_VABI sceAgcAcbMemSemaphore(CommandBuffer* buf, std::uint8_t action, std::uint8_t clientCode, const volatile void* address) {
const std::uint8_t operation = action != 0 ? 7u : 6u;
const std::uint8_t signalType = clientCode & 1u;
const std::uint8_t waitForMailbox = (clientCode >> 1u) & 1u;
return Agc::Command::WriteMemSemaphore(buf, address, waitForMailbox, signalType, operation, __func__);
}
}
-422
View File
@@ -1,422 +0,0 @@
add_library(libSceAgc SHARED EXCLUDE_FROM_ALL
${CMAKE_CURRENT_SOURCE_DIR}/Unimplemented.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Acb/src/Control.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Acb/src/Dispatch.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Acb/src/Memory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Acb/src/Sync.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Cb/src/Branch.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Cb/src/Dispatch.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Cb/src/Registers.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Cb/src/Sync.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Memory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Control.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Draw.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/RegisterDefaults.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Command/src/Packet.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbDraw/src/DrawIndexed.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbDraw/src/DrawNonIndexed.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbDraw/src/IndexBuffer.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbDraw/src/Instancing.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbDraw/src/Stats.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbFlow/src/Control.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbFlow/src/Dispatch.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbFlow/src/Memory.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbFlow/src/Sync.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/ContextState.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/Display.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/Init.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/Marker.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/Predication.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/Registers.cpp
${CMAKE_CURRENT_SOURCE_DIR}/DcbState/src/Workload.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/Debug.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/PacketInfo.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/Platform.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/RegisterDefaults.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/Semaphore.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/ShaderFusion.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Misc/src/Suspend.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/CondExec.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/Dma.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/IndirectRegisters.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/Jump.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/Nop.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/QueueEndOfPipeAction.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/Rewind.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/WaitRegMem.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Patch/src/Branch.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Predication/src/Predication.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/CreateShader.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/GsOversubscription.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/GsPrimPayload.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/InterpolantMapping.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/LinkShaders.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/PrimState.cpp
${CMAKE_CURRENT_SOURCE_DIR}/Shader/src/ShaderUtils.cpp
)
target_include_directories(libSceAgc PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(libSceAgc PRIVATE libSceAgcDriver libc)
option(APS5_AGC_CREATE_LOG "Logging sceAgcCreateShader Ok status" ON)
target_compile_definitions(libSceAgc PRIVATE
APS5_AGC_CREATE_LOG=$<BOOL:${APS5_AGC_CREATE_LOG}>
)
foreach(runtimeLinkFlag IN ITEMS -static-libgcc -static-libstdc++ -static)
string(REPLACE "${runtimeLinkFlag}" "" CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
endforeach()
add_test_executable(agc_command_tests EXCLUDE_FROM_ALL tests/Commands.cpp)
target_include_directories(agc_command_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_command_tests PRIVATE libSceAgc libSceAgcDriver libc)
configure_windows_unwind(agc_command_tests)
if(BUILD_TESTING)
set_target_properties(agc_command_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_initialization COMMAND agc_command_tests defaults)
add_test(NAME agc_commands COMMAND agc_command_tests)
if(WIN32)
set_tests_properties(agc_initialization agc_commands PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
configure_windows_unwind(libSceAgc)
add_test_executable(agc_platform_tests EXCLUDE_FROM_ALL tests/Platform.cpp)
target_include_directories(agc_platform_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_platform_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_platform_tests)
if(BUILD_TESTING)
set_target_properties(agc_platform_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_platform_tests COMMAND agc_platform_tests)
if(WIN32)
set_tests_properties(agc_platform_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_semaphore_tests EXCLUDE_FROM_ALL tests/Semaphore.cpp)
target_include_directories(agc_semaphore_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_semaphore_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_semaphore_tests)
if(BUILD_TESTING)
set_target_properties(agc_semaphore_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_semaphore_tests COMMAND agc_semaphore_tests)
if(WIN32)
set_tests_properties(agc_semaphore_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_packet_info_tests EXCLUDE_FROM_ALL tests/PacketInfo.cpp)
target_include_directories(agc_packet_info_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_packet_info_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_packet_info_tests)
if(BUILD_TESTING)
set_target_properties(agc_packet_info_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_packet_info_tests COMMAND agc_packet_info_tests)
if(WIN32)
set_tests_properties(agc_packet_info_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_register_command_tests EXCLUDE_FROM_ALL
tests/RegisterCommands.cpp
Command/src/Packet.cpp
Cb/src/Registers.cpp
DcbState/src/Registers.cpp
Patch/src/IndirectRegisters.cpp
)
target_include_directories(agc_register_command_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_register_command_tests PRIVATE libc)
configure_windows_unwind(agc_register_command_tests)
if(BUILD_TESTING)
set_target_properties(agc_register_command_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_register_command_tests COMMAND agc_register_command_tests)
if(WIN32)
set_tests_properties(agc_register_command_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_cb_cond_write_tests EXCLUDE_FROM_ALL
tests/CbCondWrite.cpp
Command/src/Packet.cpp
Command/src/Memory.cpp
Command/src/Control.cpp
Cb/src/Branch.cpp
)
target_include_directories(agc_cb_cond_write_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_cb_cond_write_tests PRIVATE libc)
configure_windows_unwind(agc_cb_cond_write_tests)
if(BUILD_TESTING)
set_target_properties(agc_cb_cond_write_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_cb_cond_write_tests COMMAND agc_cb_cond_write_tests)
if(WIN32)
set_tests_properties(agc_cb_cond_write_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_payload_range_tests EXCLUDE_FROM_ALL tests/PayloadRange.cpp)
target_include_directories(agc_payload_range_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_payload_range_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_payload_range_tests)
if(BUILD_TESTING)
set_target_properties(agc_payload_range_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_payload_range_tests COMMAND agc_payload_range_tests)
if(WIN32)
set_tests_properties(agc_payload_range_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_end_of_shader_action_size_tests EXCLUDE_FROM_ALL tests/EndOfShaderActionSize.cpp)
target_include_directories(agc_end_of_shader_action_size_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_end_of_shader_action_size_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_end_of_shader_action_size_tests)
if(BUILD_TESTING)
set_target_properties(agc_end_of_shader_action_size_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_end_of_shader_action_size_tests COMMAND agc_end_of_shader_action_size_tests)
if(WIN32)
set_tests_properties(agc_end_of_shader_action_size_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_branch_patch_tests EXCLUDE_FROM_ALL
tests/BranchPatch.cpp
Command/src/Packet.cpp
Cb/src/Branch.cpp
Patch/src/Branch.cpp
)
target_include_directories(agc_branch_patch_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_branch_patch_tests PRIVATE libc)
configure_windows_unwind(agc_branch_patch_tests)
if(BUILD_TESTING)
set_target_properties(agc_branch_patch_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_branch_patch_tests COMMAND agc_branch_patch_tests)
if(WIN32)
set_tests_properties(agc_branch_patch_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_predication_tests EXCLUDE_FROM_ALL
tests/Predication.cpp
Command/src/Packet.cpp
Command/src/Control.cpp
DcbState/src/Predication.cpp
DcbDraw/src/IndexBuffer.cpp
Predication/src/Predication.cpp
)
target_include_directories(agc_predication_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_predication_tests PRIVATE libc)
configure_windows_unwind(agc_predication_tests)
if(BUILD_TESTING)
set_target_properties(agc_predication_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_predication_tests COMMAND agc_predication_tests)
if(WIN32)
set_tests_properties(agc_predication_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_shader_fusion_tests EXCLUDE_FROM_ALL tests/ShaderFusion.cpp)
target_include_directories(agc_shader_fusion_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR} ${ANYPS5_SPIRV_HEADERS_INCLUDE_DIR})
target_link_libraries(agc_shader_fusion_tests PRIVATE libSceAgc libSceAgcDriver libc)
set_target_properties(agc_shader_fusion_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_shader_fusion_tests)
if(BUILD_TESTING)
set_target_properties(agc_shader_fusion_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_shader_fusion COMMAND agc_shader_fusion_tests)
set_tests_properties(agc_shader_fusion PROPERTIES SKIP_RETURN_CODE 77)
if(WIN32)
set_tests_properties(agc_shader_fusion PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_context_state_size_tests EXCLUDE_FROM_ALL tests/ContextStateSize.cpp)
target_include_directories(agc_context_state_size_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_context_state_size_tests PRIVATE libSceAgc libc)
configure_windows_unwind(agc_context_state_size_tests)
if(BUILD_TESTING)
set_target_properties(agc_context_state_size_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_context_state_size_tests COMMAND agc_context_state_size_tests)
if(WIN32)
set_tests_properties(agc_context_state_size_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_interpolant_mapping_tests EXCLUDE_FROM_ALL
tests/InterpolantMapping.cpp
Shader/src/InterpolantMapping.cpp
Shader/src/ShaderUtils.cpp
)
target_include_directories(agc_interpolant_mapping_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_interpolant_mapping_tests PRIVATE libSceAgcDriver libc)
set_target_properties(agc_interpolant_mapping_tests PROPERTIES CXX_EXTENSIONS OFF)
configure_windows_unwind(agc_interpolant_mapping_tests)
if(BUILD_TESTING)
set_target_properties(agc_interpolant_mapping_tests PROPERTIES EXCLUDE_FROM_ALL OFF)
add_test(NAME agc_interpolant_mapping COMMAND agc_interpolant_mapping_tests)
if(WIN32)
set_tests_properties(agc_interpolant_mapping PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
if(BUILD_TESTING)
add_test_executable(guest_shader_link_tests
${LIBS_INCLUDE_DIR}/tests/GuestShaderLink.cpp
Shader/src/LinkShaders.cpp
Shader/src/PrimState.cpp
Shader/src/InterpolantMapping.cpp
Shader/src/ShaderUtils.cpp
)
target_include_directories(guest_shader_link_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(guest_shader_link_tests PRIVATE libSceAgc libSceAgcDriver libc)
configure_windows_unwind(guest_shader_link_tests)
add_test(NAME guest_shader_link COMMAND guest_shader_link_tests)
if(WIN32)
set_tests_properties(guest_shader_link PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_gs_oversubscription_tests EXCLUDE_FROM_ALL
tests/GsOversubscription.cpp
Shader/src/GsOversubscription.cpp
)
target_include_directories(agc_gs_oversubscription_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_gs_oversubscription_tests PRIVATE libc)
configure_windows_unwind(agc_gs_oversubscription_tests)
if(BUILD_TESTING)
set_target_properties(agc_gs_oversubscription_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_gs_oversubscription_tests COMMAND agc_gs_oversubscription_tests)
if(WIN32)
set_tests_properties(agc_gs_oversubscription_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_gs_prim_payload_tests EXCLUDE_FROM_ALL
tests/GsPrimPayload.cpp
Shader/src/GsPrimPayload.cpp
)
target_include_directories(agc_gs_prim_payload_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_gs_prim_payload_tests PRIVATE libc)
configure_windows_unwind(agc_gs_prim_payload_tests)
if(BUILD_TESTING)
set_target_properties(agc_gs_prim_payload_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_gs_prim_payload_tests COMMAND agc_gs_prim_payload_tests)
if(WIN32)
set_tests_properties(agc_gs_prim_payload_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_dma_data_tests EXCLUDE_FROM_ALL
tests/DmaData.cpp
Command/src/Packet.cpp
Command/src/Memory.cpp
Acb/src/Memory.cpp
DcbFlow/src/Memory.cpp
)
target_include_directories(agc_dma_data_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_dma_data_tests PRIVATE libc)
configure_windows_unwind(agc_dma_data_tests)
if(BUILD_TESTING)
set_target_properties(agc_dma_data_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_dma_data_tests COMMAND agc_dma_data_tests)
if(WIN32)
set_tests_properties(agc_dma_data_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_write_data_patch_tests EXCLUDE_FROM_ALL
tests/WriteDataPatch.cpp
Command/src/Packet.cpp
Command/src/Memory.cpp
Acb/src/Memory.cpp
DcbFlow/src/Memory.cpp
Patch/src/WaitRegMem.cpp
)
target_include_directories(agc_write_data_patch_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_write_data_patch_tests PRIVATE libc)
configure_windows_unwind(agc_write_data_patch_tests)
if(BUILD_TESTING)
set_target_properties(agc_write_data_patch_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_write_data_patch_tests COMMAND agc_write_data_patch_tests)
if(WIN32)
set_tests_properties(agc_write_data_patch_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_prime_utcl2_tests EXCLUDE_FROM_ALL
tests/PrimeUtcl2.cpp
Command/src/Packet.cpp
Command/src/Memory.cpp
Acb/src/Memory.cpp
DcbFlow/src/Memory.cpp
DcbState/src/Display.cpp
)
target_include_directories(agc_prime_utcl2_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_prime_utcl2_tests PRIVATE libc)
configure_windows_unwind(agc_prime_utcl2_tests)
if(BUILD_TESTING)
set_target_properties(agc_prime_utcl2_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_prime_utcl2_tests COMMAND agc_prime_utcl2_tests)
if(WIN32)
set_tests_properties(agc_prime_utcl2_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_cond_exec_patch_tests EXCLUDE_FROM_ALL
tests/CondExecPatch.cpp
Command/src/Packet.cpp
Command/src/Memory.cpp
Command/src/Control.cpp
DcbFlow/src/Sync.cpp
Acb/src/Sync.cpp
Patch/src/CondExec.cpp
)
target_include_directories(agc_cond_exec_patch_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_cond_exec_patch_tests PRIVATE libc)
configure_windows_unwind(agc_cond_exec_patch_tests)
if(BUILD_TESTING)
set_target_properties(agc_cond_exec_patch_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_cond_exec_patch_tests COMMAND agc_cond_exec_patch_tests)
if(WIN32)
set_tests_properties(agc_cond_exec_patch_tests PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
add_test_executable(agc_shader_helpers_tests EXCLUDE_FROM_ALL
tests/ShaderHelpers.cpp
Shader/src/LinkShaders.cpp
Shader/src/PrimState.cpp
Shader/src/InterpolantMapping.cpp
Shader/src/ShaderUtils.cpp
)
target_include_directories(agc_shader_helpers_tests PRIVATE ${LIBS_INCLUDE_DIR})
target_link_libraries(agc_shader_helpers_tests PRIVATE libc libSceAgcDriver)
configure_windows_unwind(agc_shader_helpers_tests)
if(BUILD_TESTING)
set_target_properties(agc_shader_helpers_tests PROPERTIES EXCLUDE_FROM_ALL FALSE)
add_test(NAME agc_shader_helpers COMMAND agc_shader_helpers_tests)
if(WIN32)
set_tests_properties(agc_shader_helpers PROPERTIES ENVIRONMENT_MODIFICATION
"PATH=path_list_prepend:$<TARGET_FILE_DIR:libc>")
endif()
endif()
@@ -1,4 +0,0 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGC_CB_INCLUDE_BRANCH_HPP
#define CORE_LIBS_PRX_LIBSCEAGC_CB_INCLUDE_BRANCH_HPP
#endif
@@ -1,4 +0,0 @@
#ifndef CORE_LIBS_PRX_LIBSCEAGC_CB_INCLUDE_DISPATCH_HPP
#define CORE_LIBS_PRX_LIBSCEAGC_CB_INCLUDE_DISPATCH_HPP
#endif
Loaded 100 of 2555 files, more files were not shown because too many files have changed in this diff. Show more