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
5324 changed files with 8536 additions and 1065063 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.
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: Bug report
description: A title, homebrew or test stops, crashes or renders wrongly.
labels: [bug]
body:
- type: markdown
attributes:
value: |
Search open and closed issues and pull requests for the error text first, and comment there if it is already reported.
Game bring-up progress belongs in [Discussions](https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up), one thread per title.
A slow scene or a change in speed goes into the [Performance report](https://github.com/boykopovar/AnyPS5/issues/new?template=performance.yml) form, which asks for a [performance trace](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/BUILD.md#performance-trace) and its `tools/trace_digest.py` digest.
- type: input
id: summary
attributes:
label: What happens
description: One sentence, with the exact error text if there is one.
validations:
required: true
- type: input
id: title
attributes:
label: Title, test or build step
description: Title ID and content version (for example PPSAxxxxx 01.000.000), a homebrew with its source, the ctest name, or the build step that fails.
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
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: textarea
id: host_report
attributes:
label: Host report
description: Start the game with `ANYPS5_HOST_REPORT=1` and paste the block it prints to stderr. It holds the OS, CPU, GPU, driver, Vulkan items the GPU lacks, SDL version and the `APS5_*` switches, without paths or user names. See [Host report](https://github.com/boykopovar/AnyPS5/blob/main/docs/user/USAGE.md#host-report).
render: text
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: The commands that were run, environment variables included, and how long it takes to stop.
validations:
required: true
- type: textarea
id: log
attributes:
label: Log
description: The lines around the stop. Setting ANYPS5_LOG_FILE=<path> before the run saves the whole log to a file you can attach.
render: text
validations:
required: true
- type: textarea
id: notes
attributes:
label: What was checked
description: Other devices or commits tried, and whether it is the same every run. Attach the full log and screenshots here.
-8
View File
@@ -1,8 +0,0 @@
blank_issues_enabled: true
contact_links:
- name: Game bring-up
url: https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up
about: Progress of one title, one thread per title ID
- name: Question
url: https://github.com/boykopovar/AnyPS5/discussions/categories/q-a
about: Building, converting and running
-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
-3
View File
@@ -1,3 +0,0 @@
self-hosted-runner:
labels:
- anyps5
-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/**'
-19
View File
@@ -1,19 +0,0 @@
### What
### Tested
<!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. -->
### Checklist
<!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md -->
- [ ] Based on current `main`; no other open PR implements the same functions
- [ ] One topic per PR; follow-ups go in a new PR
- [ ] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md)
- [ ] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file
- [ ] No notes, investigation `.md` files or images added to the repository (attach them to this PR)
- [ ] New third-party code is a submodule built from source
- [ ] Generic behaviour, not specific to one title
- [ ] Depends on: <!-- #PR, or none -->
- [ ] Fixes: <!-- issue it closes as Fixes #N, or none -->
- [ ] Unblocks: <!-- title ID and Game bring-up discussion, e.g. PPSA01325 #3232, or none -->
- [ ] GPUs tested: <!-- for AGC, shader recompiler or VideoOut changes: vendor, model, driver and OS of each GPU the GPU tests ran on; otherwise n/a -->
- [ ] AI-assisted: <!-- yes / no -->
-8
View File
@@ -1,8 +0,0 @@
agc_driver_graphics undefined UBSan stops on the misaligned guest word loads of the ASan build's CopyGuestBytes (Execution/src/GuestMemory.cpp), which #10973 fixes, and then on Graphics/src/DepthSurface.cpp:730, which binds a TextureDetiler reference to a null pointer when the context has no detiler.
agc_driver_graphics_maps_fallback undefined UBSan stops on the misaligned guest word loads of the ASan build's CopyGuestBytes (Execution/src/GuestMemory.cpp), which #10973 fixes, and then on Graphics/src/DepthSurface.cpp:730, which binds a TextureDetiler reference to a null pointer when the context has no detiler.
agc_driver_pm4 undefined UBSan stops on the misaligned guest word loads of the ASan build's CopyGuestBytes (Execution/src/GuestMemory.cpp); #10973 fixes them.
agc_performance_overlay address,undefined Runs past its 30 s ctest TIMEOUT in the sanitizer build on ubuntu-latest (timed out at 30.18 s); it passes without sanitizers, and alone it takes about 19 s; #11555 gives it 120 s in ASan builds.
guest_backtrace address Fails only in ASan builds, with 'guest backtrace: first frame is not in the calling module', because the sanitizer adds a frame to backtrace(); #9240 starts the frames at the caller.
guest_getrlimit address The test lowers RLIMIT_DATA to 1 TiB, below the private memory ASan has already mapped, so ASan's next internal mapping fails with ENOMEM ('failed to allocate ... DTLS_NextBlock').
guest_math address,undefined ubuntu-latest's GCC 15 targets x86-64-v3 and fuses libc's float multiply-adds into FMA, so atanf misses the console bits by one ulp; #11059 builds libc with -ffp-contract=off.
guest_vorbis_dec undefined The bundled libvorbis left-shifts a negative value (3rdparty/vorbis/lib/psy.c:319); #11480 updates libvorbis to the upstream fix.
-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 1000 --json number,headRefOid \
--jq "map({key: (.number | tostring), value: (.headRefOid + \"-$config\")}) | from_entries" > "$RUNNER_TEMP/area-open.json"
jq -r --slurpfile old "$state" 'to_entries[] | select($old[0][.key] != .value) | .key' "$RUNNER_TEMP/area-open.json" | head -n 40 > "$RUNNER_TEMP/area-todo"
jq -c --slurpfile open "$RUNNER_TEMP/area-open.json" --rawfile todo "$RUNNER_TEMP/area-todo" \
'with_entries(select(.key | in($open[0]))) + ($open[0] | with_entries(select(.key | IN($todo | split("\n")[]))))' "$state" > "$RUNNER_TEMP/area-next.json"
{
echo 'numbers<<EOF'
cat "$RUNNER_TEMP/area-todo"
echo EOF
} >> "$GITHUB_OUTPUT"
- if: steps.prs.outputs.numbers != ''
uses: actions/labeler@v7
with:
pr-number: ${{ steps.prs.outputs.numbers }}
- run: mv "$RUNNER_TEMP/area-next.json" "$RUNNER_TEMP/area-state.json"
- uses: actions/cache/save@v6
with:
path: ${{ runner.temp }}/area-state.json
key: area-labels-${{ github.run_id }}
-737
View File
@@ -1,737 +0,0 @@
name: Build
on:
push:
branches: [main]
pull_request:
branches: [main]
types: [opened, synchronize, reopened]
workflow_dispatch:
inputs:
pr:
description: Pull request numbers to build together, separated by spaces or commas (up to 40)
required: true
type: string
linux:
description: Also build and test on Linux
required: false
default: true
type: boolean
full:
description: Run the full Linux and Windows builds (off runs only the relinker builds and tests on Linux, Windows and macOS)
required: false
default: true
type: boolean
select:
description: Build and run only the tests whose build inputs the pull requests change (push builds of main always run every test)
required: false
default: false
type: boolean
permissions:
contents: read
concurrency:
group: build-${{ github.event_name }}-${{ github.event.pull_request.number || inputs.pr || github.ref }}
cancel-in-progress: ${{ 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 }}
mingw-host-tests: ${{ steps.gate.outputs.mingw-host-tests }}
full: ${{ steps.gate.outputs.full }}
relinker-hosts: ${{ steps.gate.outputs.relinker-hosts }}
steps:
- uses: actions/github-script@v8
id: gate
env:
PR_NUMBER: ${{ inputs.pr }}
LINUX_BUILD: ${{ inputs.linux }}
FULL_BUILD: ${{ inputs.full }}
with:
script: |
const { owner, repo } = context.repo;
const workflow = '.github/workflows/build.yml';
const libc = 'core/libs/prx/libc/';
const jobOfLine = (text) => {
let inJobs = false;
let job = '';
return text.split('\n').map((line) => {
if (/^\S/.test(line)) {
inJobs = /^jobs:\s*$/.test(line);
job = '';
} else if (inJobs) {
job = /^ ([\w-]+):\s*$/.exec(line)?.[1] ?? job;
}
return job;
});
};
const patchedJobs = (patch, text) => {
const jobs = jobOfLine(text);
const touched = new Set();
let line = 1;
for (const row of patch.split('\n')) {
const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)/.exec(row);
if (hunk) {
line = Number(hunk[1]);
} else if (row.startsWith('+')) {
touched.add(jobs[line - 1] ?? '');
line += 1;
} else if (row.startsWith('-')) {
touched.add(jobs[line - 2] ?? '').add(jobs[line - 1] ?? '');
} else if (row.startsWith(' ')) {
line += 1;
}
}
return touched;
};
const workflowJobs = new Set();
const readWorkflow = async (files, ref) => {
const file = files.find((file) => file.filename === workflow || file.previous_filename === workflow);
if (!file) {
return;
}
if (file.filename !== workflow || !file.patch) {
workflowJobs.add('*');
return;
}
try {
const { data } = await github.rest.repos.getContent({ owner, repo, path: workflow, ref });
const text = Buffer.from(data.content, 'base64').toString('utf8');
patchedJobs(file.patch, text).forEach((job) => workflowJobs.add(job));
} catch (error) {
core.warning(`Could not read ${workflow} at ${ref}, so every test job runs: ${error.message}`);
workflowJobs.add('*');
}
};
const select = (paths, all) => {
const touches = (...prefixes) => all ||
paths.some((path) => prefixes.some((prefix) => prefix.endsWith('/') ? path.startsWith(prefix) : path === prefix));
const edits = (job) => ['*', '', 'eligibility', job].some((name) => workflowJobs.has(name));
return {
relinker: edits('relinker') || edits('relinker-asan') || touches(
'core/relinker/', libc, 'core/libs/prx/libkernel/AppMetadata/', 'core/libs/tests/ParamJsonParser.cpp',
'core/libs/prx/libkernel/DirectMemory/DirectMemory.hpp', 'core/libs/prx/libkernel/KernelErrors.hpp',
'core/libs/nid/src/NidCompute.cpp', 'core/libs/nid/src/Sha1.cpp',
'core/libs/nid/include/nid/NidCompute.hpp', 'core/libs/nid/include/nid/Sha1.hpp',
'core/libs/prx/libScePad/tests/InputCommandFile.cpp', 'core/libs/prx/libScePad/include/InputCommandFile.hpp',
'core/shader/recompiler/', '.github/pull_request_template.md', '.github/workflows/pr-overlap.yml',
'tools/', 'cmake/', 'CMakeLists.txt'
),
registerContext: edits('register-context') ||
touches('core/libs/tests/register_context/', 'core/libs/tests/RegisterContext.cpp', libc),
writeWatch: edits('write-watch') || touches('core/libs/tests/write_watch/', 'core/libs/tests/WriteWatch.cpp', libc),
mingwHostTests: edits('eligibility') || edits('windows') || touches(
'core/libs/', 'tools/build_mingw_host_only_tests.py', 'tools/build_changed_guest_tests.py', 'tools/tests/test_build_changed_guest_tests.py',
'tools/tests/test_mingw_host_only_test_targets.py', 'CMakeLists.txt'
),
};
};
const relinkerHosts = (full, linux) => JSON.stringify([
...(full && linux ? [] : [{ os: 'ubuntu-latest', compiler: 'g++' }]),
...(full ? [] : [{ os: 'windows-latest', compiler: 'g++' }]),
{ os: 'macos-latest', compiler: 'clang++' },
{ os: 'macos-latest', compiler: 'clang++', architectures: 'x86_64' },
]);
if (context.eventName === 'push') {
if (context.ref !== 'refs/heads/main') {
throw new Error('Automatic full builds only run on main');
}
let paths = [];
let all = true;
if (!/^0+$/.test(context.payload.before)) {
try {
const { data } = await github.rest.repos.compareCommitsWithBasehead({
owner, repo, basehead: `${context.payload.before}...${context.sha}`
});
const files = data.files ?? [];
all = files.length >= 300;
paths = files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean));
await readWorkflow(files, context.sha);
} catch (error) {
core.warning(`Could not list the files of this push, so every test job runs: ${error.message}`);
}
}
const run = select(paths, all);
core.setOutput('sha', context.sha);
core.setOutput('pr', '');
core.setOutput('head', '');
core.setOutput('relinker', run.relinker);
core.setOutput('register-context', run.registerContext);
core.setOutput('write-watch', run.writeWatch);
core.setOutput('mingw-host-tests', false);
core.setOutput('full', true);
core.setOutput('relinker-hosts', relinkerHosts(true, true));
await core.summary.addRaw(
`Building main at ${context.sha}: full builds enabled, ` +
`macOS relinker ${run.relinker ? 'enabled' : 'skipped'}, ` +
`register context tests ${run.registerContext ? 'enabled' : 'skipped'}, write watch tests ${run.writeWatch ? 'enabled' : 'skipped'}`
).write();
return;
}
const manual = context.eventName === 'workflow_dispatch';
const linux = process.env.LINUX_BUILD !== 'false';
const full = manual && process.env.FULL_BUILD !== 'false';
if (manual) {
for (const username of new Set([context.actor, process.env.GITHUB_TRIGGERING_ACTOR])) {
const { data } = await github.rest.repos.getCollaboratorPermissionLevel({ owner, repo, username });
if (!['write', 'maintain', 'admin'].includes(data.permission)) {
throw new Error('Only collaborators with write access can start or rerun builds');
}
}
if (!/^[1-9][0-9]*([ ,]+[1-9][0-9]*){0,39}$/.test(process.env.PR_NUMBER.trim())) {
throw new Error('Enter up to 40 positive pull request numbers separated by spaces or commas');
}
}
const numbers = manual
? [...new Set(process.env.PR_NUMBER.trim().split(/[ ,]+/).map(Number))]
: [context.payload.pull_request.number];
if (numbers.some((pull_number) => !Number.isSafeInteger(pull_number) || pull_number < 1)) {
throw new Error('Invalid pull request number');
}
const pulls = [];
const paths = [];
let truncated = false;
for (const pull_number of numbers) {
let { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
for (let attempt = 0; pr.mergeable === null && attempt < 10; ++attempt) {
await new Promise((resolve) => setTimeout(resolve, 3000));
({ data: pr } = await github.rest.pulls.get({ owner, repo, pull_number }));
}
if (!manual && pr.state !== 'open') {
await core.summary.addRaw(`PR #${pull_number} was ${pr.merged ? 'merged' : 'closed'} before this run started: nothing to build`).write();
return;
}
if (pr.state !== 'open' || pr.base.ref !== 'main') {
throw new Error(`Pull request #${pull_number} must be open and target main`);
}
if (!manual && pr.head.sha !== context.payload.pull_request.head.sha) {
throw new Error('The pull request has newer commits; use the latest run');
}
if (pr.mergeable === false) {
throw new Error(`Pull request #${pull_number} does not merge cleanly into main; rebase it first`);
}
const files = await github.paginate(github.rest.pulls.listFiles, { owner, repo, pull_number, per_page: 100 });
truncated ||= files.length >= 3000;
paths.push(...files.flatMap((file) => [file.filename, file.previous_filename].filter(Boolean)));
await readWorkflow(files, pr.head.sha);
pulls.push({ number: pull_number, head: pr.head.sha });
}
const run = select(paths, truncated);
let relinker = run.relinker;
if (relinker && !manual) {
const author = context.payload.pull_request.user.login;
const { data: commits } = await github.rest.repos.listCommits({
owner, repo, sha: 'main', author, per_page: 1
});
relinker = commits.length > 0;
if (!relinker) {
try {
const { data: mergedPRs } = await github.rest.search.issuesAndPullRequests({
q: `repo:${owner}/${repo} is:pr is:merged base:main author:${author}`,
per_page: 1
});
if (mergedPRs.incomplete_results) {
throw new Error('the search results are incomplete');
}
relinker = mergedPRs.total_count > 0;
} catch (error) {
core.warning(`Skipping the relinker: could not search the merged pull requests of ${author}: ${error.message}`);
}
}
}
const registerContext = run.registerContext;
const writeWatch = run.writeWatch;
const { data: main } = await github.rest.repos.getBranch({ owner, repo, branch: 'main' });
core.setOutput('sha', main.commit.sha);
core.setOutput('pr', pulls.map((pull) => pull.number).join(' '));
core.setOutput('head', pulls.map((pull) => pull.head).join(' '));
core.setOutput('relinker', relinker);
core.setOutput('register-context', registerContext);
core.setOutput('write-watch', writeWatch);
core.setOutput('mingw-host-tests', !manual && run.mingwHostTests);
core.setOutput('full', full);
core.setOutput('relinker-hosts', relinkerHosts(full, linux));
const merged = pulls.map((pull) => `PR #${pull.number} at ${pull.head} merged into main at ${main.commit.sha}`);
merged.forEach((line) => core.info(line));
await core.summary.addRaw(
`${merged.join(', then ')}: full builds ${full ? 'enabled' : 'disabled'}, ` +
`relinker ${relinker ? (full ? (linux ? 'enabled on macOS (the full builds run the Linux and Windows relinker tests)' : 'enabled on Linux and macOS (the full Windows build runs the Windows relinker tests)') : 'enabled') : 'skipped: no relinker file changed, or no commit or merged pull request in main was found for the author'}, ` +
`register context tests ${registerContext ? 'enabled' : 'skipped'}, write watch tests ${writeWatch ? 'enabled' : 'skipped'}`
).write();
relinker:
needs: eligibility
if: ${{ needs.eligibility.outputs.relinker == 'true' }}
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
include: ${{ fromJSON(needs.eligibility.outputs.relinker-hosts) }}
env:
WINLIBS_RELEASE: 15.2.0posix-14.0.0-ucrt-r7
WINLIBS_ZIP: winlibs-x86_64-posix-seh-gcc-15.2.0-mingw-w64ucrt-14.0.0-r7.zip
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
shell: bash
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
git fetch --no-tags --unshallow origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
- if: runner.os == 'Windows'
id: toolchain
uses: actions/cache@v6
with:
path: C:\winlibs
key: ${{ env.WINLIBS_ZIP }}
- if: runner.os == 'Windows' && steps.toolchain.outputs.cache-hit != 'true'
run: |
curl -sSfL -o "$RUNNER_TEMP/winlibs.zip" "https://github.com/brechtsanders/winlibs_mingw/releases/download/$WINLIBS_RELEASE/$WINLIBS_ZIP"
7z x "$RUNNER_TEMP/winlibs.zip" -oC:/winlibs > /dev/null
- if: runner.os == 'Windows'
run: echo 'C:\winlibs\mingw64\bin' >> "$GITHUB_PATH"
- if: ${{ matrix.architectures == 'x86_64' }}
run: sudo softwareupdate --install-rosetta --agree-to-license
- run: cmake -S . -B build-relinker -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_COMPILER=${{ matrix.compiler }} -DANYPS5_RELINKER_ONLY=ON -DBUILD_TESTING=ON -DCMAKE_OSX_ARCHITECTURES=${{ matrix.architectures }}
- run: cmake --build build-relinker --parallel 3
- run: ctest --test-dir build-relinker --output-on-failure --timeout 120 --parallel 4
relinker-asan:
needs: eligibility
if: ${{ needs.eligibility.outputs.relinker == 'true' }}
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
git fetch --no-tags --unshallow origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
- run: cmake -S . -B build-relinker-asan -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=g++ -DANYPS5_RELINKER_ONLY=ON -DANYPS5_ENABLE_ASAN=ON -DBUILD_TESTING=ON
- run: cmake --build build-relinker-asan --parallel 4
- run: ctest --test-dir build-relinker-asan --output-on-failure --timeout 120 --label-regex '^tls_function_coverage$' --no-tests=error
register-context:
needs: eligibility
if: ${{ needs.eligibility.outputs.register-context == 'true' }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, macos-15-intel]
configuration: [Debug, Release]
runs-on: ${{ matrix.os }}
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
shell: bash
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
git fetch --no-tags --unshallow origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
- run: cmake -S core/libs/tests/register_context -B build/register-context -DCMAKE_BUILD_TYPE=${{ matrix.configuration }}
- run: cmake --build build/register-context --parallel
- run: ctest --test-dir build/register-context --output-on-failure --repeat until-fail:3 --no-tests=error
write-watch:
needs: eligibility
if: ${{ needs.eligibility.outputs.write-watch == 'true' }}
strategy:
fail-fast: false
matrix:
os: [macos-15-intel, macos-15]
runs-on: ${{ matrix.os }}
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
shell: bash
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
git fetch --no-tags --unshallow origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
- run: cmake -S core/libs/tests/write_watch -B build/write-watch -DCMAKE_BUILD_TYPE=Release
- run: cmake --build build/write-watch --parallel
- run: ctest --test-dir build/write-watch --output-on-failure --repeat until-fail:3 --no-tests=error
linux:
needs: eligibility
if: ${{ !github.event.repository.fork && (github.event_name == 'push' || (github.event_name == 'workflow_dispatch' && inputs.linux)) && needs.eligibility.outputs.full == 'true' }}
runs-on: [self-hosted, linux, x64, anyps5]
timeout-minutes: 60
env:
CCACHE_DIR: /var/cache/anyps5/ccache
CCACHE_MAXSIZE: 30G
CCACHE_COMPILERCHECK: content
MESA_SHADER_CACHE_DIR: /var/cache/anyps5/mesa
MESA_SHADER_CACHE_MAX_SIZE: 4G
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
submodules: recursive
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
shell: bash
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
fetch_options=()
if [ "$(git rev-parse --is-shallow-repository)" = true ]; then fetch_options+=(--unshallow); fi
git fetch --no-tags "${fetch_options[@]}" origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
git submodule update --init --recursive
- name: Prepare persistent caches
run: |
mkdir -p "$CCACHE_DIR" "$MESA_SHADER_CACHE_DIR"
test -w "$CCACHE_DIR" && test -w "$MESA_SHADER_CACHE_DIR"
ccache --zero-stats
ccache --show-config
dpkg-query -W mesa-vulkan-drivers
grep -m1 '^model name' /proc/cpuinfo
- name: Install the wild linker
shell: bash
env:
WILD_VERSION: 0.10.0
WILD_SHA256: 641265506a7c06cfb03181b8916ab663ec8407855db6d4db7f8450667d105283
run: |
tools=$RUNNER_TOOL_CACHE/wild
mkdir -p "$tools" 2>/dev/null && test -w "$tools" || { tools=$RUNNER_TEMP/wild; mkdir -p "$tools"; }
dir=$tools/$WILD_VERSION
tmp=
probe=$(mktemp -d "$RUNNER_TEMP/wild-probe.XXXXXX")
trap 'rm -rf "$tmp" "$probe"' EXIT
if [ ! -x "$dir/bin/ld" ]; then
tmp=$(mktemp -d "$tools/.wild.XXXXXX")
name=wild-linker-$WILD_VERSION-x86_64-unknown-linux-gnu
curl -fsSL --retry 3 -o "$tmp/$name.tar.gz" "https://github.com/davidlattimore/wild/releases/download/$WILD_VERSION/$name.tar.gz"
echo "$WILD_SHA256 $tmp/$name.tar.gz" | sha256sum -c -
tar -xzf "$tmp/$name.tar.gz" -C "$tmp"
mkdir -p "$tmp/out/bin"
mv "$tmp/$name/wild" "$tmp/out/bin/wild"
ln -s wild "$tmp/out/bin/ld"
mv -T "$tmp/out" "$dir" 2>/dev/null || test -x "$dir/bin/ld"
fi
echo 'int main(void) { return 0; }' > "$probe/main.c"
gcc "-B$dir/bin" "$probe/main.c" -o "$probe/main"
readelf -p .comment "$probe/main" | grep -F "Linker: Wild $WILD_VERSION"
echo "LINKER_FLAGS=-B$dir/bin" >> "$GITHUB_ENV"
- name: Size parallelism to what the shared host has free
run: |
cpus=$(nproc)
busy=$(awk '{ printf "%d", $1 + 0.5 }' /proc/loadavg)
mem_mb=$(awk '/^MemTotal:/ { print int($2 / 1024) }' /proc/meminfo)
slots=$(( (mem_mb - 2048) / 1024 ))
slots=$(( slots < 1 ? 1 : slots ))
tests=$(( cpus - busy ))
tests=$(( tests < 1 ? 1 : tests ))
slot_dir=$CCACHE_DIR/compile-slots
mkdir -p -m 1777 "$slot_dir"
test -w "$slot_dir"
echo "cpus=$cpus load=$busy mem_total_mb=$mem_mb -> build jobs $cpus, cold compiles $slots per host, tests $tests"
echo "CMAKE_BUILD_PARALLEL_LEVEL=$cpus" >> "$GITHUB_ENV"
echo "CTEST_PARALLEL_LEVEL=$tests" >> "$GITHUB_ENV"
echo "CCACHE_PREFIX=$GITHUB_WORKSPACE/tools/compile_slot.sh" >> "$GITHUB_ENV"
echo "ANYPS5_COMPILE_SLOT_DIR=$slot_dir" >> "$GITHUB_ENV"
echo "ANYPS5_COMPILE_SLOTS=$slots" >> "$GITHUB_ENV"
- run: cmake -S . -B build $CONFIGURE -DANYPS5_ENABLE_SPIRV_TOOLS=ON "-DCMAKE_EXE_LINKER_FLAGS=$LINKER_FLAGS" "-DCMAKE_SHARED_LINKER_FLAGS=$LINKER_FLAGS" "-DCMAKE_MODULE_LINKER_FLAGS=$LINKER_FLAGS"
- name: Check that every test executable is registered with ctest
run: python3 tools/check_test_registration.py build
- if: ${{ inputs.select }}
uses: actions/cache/restore@v6
with:
path: test-graph.json
key: test-graph-${{ runner.os }}-${{ needs.eligibility.outputs.sha }}
restore-keys: test-graph-${{ runner.os }}-
- name: Select the tests the change reaches
if: ${{ inputs.select }}
env:
BASE: ${{ needs.eligibility.outputs.sha }}
run: |
git diff --name-only -z "$BASE" HEAD -- > changed.txt
python3 tools/select_tests.py select build test-graph.json changed.txt
- id: build
run: |
if [ -f build/select.ninja ]; then ninja -C build -f select.ninja -j "$CMAKE_BUILD_PARALLEL_LEVEL" -l "$(nproc)" selected; else cmake --build build -- -l "$(nproc)"; fi
- id: libs
run: cmake --build build --target libs -- -l "$(nproc)"
- run: python3 tools/select_tests.py ctest build --test-load "$(nproc)" --output-on-failure --timeout 120 --output-log ctest.log --output-junit ctest.xml
env:
ANYPS5_REQUIRE_VULKAN: 1
GALLIUM_OVERRIDE_CPU_CAPS: avx
- run: python3 tools/check_skips.py build/ctest.xml
- name: Write the test graph of main
if: ${{ !cancelled() && github.event_name == 'push' && steps.build.outcome == 'success' && steps.libs.outcome == 'success' }}
continue-on-error: true
run: python3 tools/select_tests.py dump build test-graph.json
- if: ${{ !cancelled() && github.event_name == 'push' && hashFiles('test-graph.json') != '' }}
continue-on-error: true
uses: actions/cache/save@v6
with:
path: test-graph.json
key: test-graph-${{ runner.os }}-${{ github.sha }}
- name: Report compiler cache statistics
if: ${{ !cancelled() }}
run: ccache --show-stats
- name: Report tests slower than 30 s
if: ${{ !cancelled() }}
shell: bash
run: |
[ -f ctest.log ] || exit 0
awk '/Test +#[0-9]+: / && $NF == "sec" { for (i = 1; i <= NF; i++) if ($i ~ /^#[0-9]+:$/) name = $(i + 1); t = $(NF - 1) + 0; if (t > max[name]) max[name] = t }
END { for (name in max) if (max[name] > 30) printf "::warning title=Slow test::%s took %.1f s on %s; tests must finish in 30 s (CONTRIBUTING.md)\n", name, max[name], ENVIRON["RUNNER_OS"] }' ctest.log
windows:
needs: eligibility
if: ${{ ((github.event_name == 'push' || github.event_name == 'workflow_dispatch') && needs.eligibility.outputs.full == 'true') || (github.event_name == 'pull_request' && needs.eligibility.outputs.mingw-host-tests == 'true') }}
runs-on: windows-latest
timeout-minutes: 45
env:
WINLIBS_RELEASE: 15.2.0posix-14.0.0-ucrt-r7
WINLIBS_ZIP: winlibs-x86_64-posix-seh-gcc-15.2.0-mingw-w64ucrt-14.0.0-r7.zip
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
ref: ${{ needs.eligibility.outputs.sha }}
persist-credentials: false
- name: Merge the pull request into main
if: ${{ needs.eligibility.outputs.head != '' }}
shell: bash
env:
PR_NUMBER: ${{ needs.eligibility.outputs.pr }}
PR_HEAD: ${{ needs.eligibility.outputs.head }}
run: |
read -ra numbers <<< "$PR_NUMBER"
read -ra heads <<< "$PR_HEAD"
refspecs=()
for number in "${numbers[@]}"; do refspecs+=("+refs/pull/$number/head:refs/remotes/pull/$number"); done
git fetch --no-tags --unshallow origin "${refspecs[@]}"
for i in "${!numbers[@]}"; do
if [ "$(git rev-parse "refs/remotes/pull/${numbers[i]}")" != "${heads[i]}" ]; then echo "::error::Pull request #${numbers[i]} has newer commits; start a new build"; exit 1; fi
if ! git -c user.name=ci -c user.email=ci@localhost merge --no-ff --no-edit "refs/remotes/pull/${numbers[i]}"; then echo "::error::Pull request #${numbers[i]} does not merge cleanly into main and the pull requests before it; rebase it first"; exit 1; fi
done
- id: submodules
name: Key the submodules on their commits
run: |
echo "key=$(git ls-files -s | awk '$1 == "160000" { print $2, $4 }' | cat - .gitmodules | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
echo "ffmpeg=$(git rev-parse HEAD:3rdparty/ffmpeg-core)" >> "$GITHUB_OUTPUT"
- id: submodule-cache
uses: actions/cache/restore@v6
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Check out the submodules
run: |
if [ -f "$RUNNER_TEMP/submodule-gitdirs.tar" ]; then tar --force-local -xf "$RUNNER_TEMP/submodule-gitdirs.tar"; fi
git submodule update --init --recursive --depth 1 --jobs 8
- if: steps.submodule-cache.outputs.cache-hit != 'true'
run: tar --force-local -cf "$RUNNER_TEMP/submodule-gitdirs.tar" .git/modules
- if: steps.submodule-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Point the WinLibs CMake at the CA bundle of Git for Windows
run: |
for prefix in ucrt64 mingw64; do
bundle="C:/Program Files/Git/$prefix/etc/ssl/certs/ca-bundle.crt"
if [ -f "$bundle" ]; then echo "SSL_CERT_FILE=$bundle" >> "$GITHUB_ENV"; exit 0; fi
done
echo "::error::No CA bundle found in Git for Windows"; exit 1
- id: toolchain
uses: actions/cache@v6
with:
path: C:\winlibs
key: ${{ env.WINLIBS_ZIP }}
- if: steps.toolchain.outputs.cache-hit != 'true'
run: |
curl -sSfL -o "$RUNNER_TEMP/winlibs.zip" "https://github.com/brechtsanders/winlibs_mingw/releases/download/$WINLIBS_RELEASE/$WINLIBS_ZIP"
7z x "$RUNNER_TEMP/winlibs.zip" -oC:/winlibs > /dev/null
- run: echo 'C:\winlibs\mingw64\bin' >> "$GITHUB_PATH"
- uses: hendrikmuhs/ccache-action@v1.2.24
with:
key: ${{ github.event_name == 'workflow_dispatch' && 'dispatch-windows' || 'windows' }}
restore-keys: ${{ github.event_name == 'workflow_dispatch' && 'windows' || '' }}
save: ${{ github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') }}
evict-old-files: job
- id: ffmpeg-cache
uses: actions/cache/restore@v6
with:
path: build/externals
key: ffmpeg-${{ runner.os }}-${{ steps.submodules.outputs.ffmpeg }}
- id: seed-cache
uses: actions/cache/restore@v6
with:
path: configure-seed.cmake
key: configure-seed-${{ env.WINLIBS_ZIP }}-${{ steps.submodules.outputs.key }}-${{ hashFiles('CMakeLists.txt', 'cmake/**', 'core/libs/CMakeLists.txt', 'tools/configure_seed.py', '.github/workflows/build.yml') }}
- if: github.event_name == 'pull_request'
shell: bash
run: mkdir -p build/.cmake/api/v1/query && touch build/.cmake/api/v1/query/codemodel-v2
- shell: cmd
run: if exist configure-seed.cmake (cmake -C configure-seed.cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown") else (cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown")
- if: steps.seed-cache.outputs.cache-hit != 'true'
shell: cmd
run: python tools/configure_seed.py build/CMakeCache.txt configure-seed.cmake
- if: steps.seed-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: configure-seed.cmake
key: ${{ steps.seed-cache.outputs.cache-primary-key }}
- if: steps.ffmpeg-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: build/externals
key: ${{ steps.ffmpeg-cache.outputs.cache-primary-key }}
- name: Check that every test executable is registered with ctest
shell: cmd
run: python tools/check_test_registration.py build
- if: ${{ inputs.select }}
uses: actions/cache/restore@v6
with:
path: test-graph.json
key: test-graph-${{ runner.os }}-${{ needs.eligibility.outputs.sha }}
restore-keys: test-graph-${{ runner.os }}-
- name: Select the tests the change reaches
if: ${{ inputs.select }}
env:
BASE: ${{ needs.eligibility.outputs.sha }}
shell: cmd
run: |
git diff --name-only -z %BASE% HEAD -- > changed.txt
python tools/select_tests.py select build test-graph.json changed.txt
- id: build
if: github.event_name != 'pull_request'
shell: cmd
run: if exist build\select.ninja (ninja -C build -f select.ninja selected) else (cmake --build build)
- name: List changed files for host-only test linking
if: github.event_name == 'pull_request'
env:
BASE: ${{ needs.eligibility.outputs.sha }}
run: git diff --name-only "$BASE" HEAD > changed.txt
- name: Link changed host-only core/libs test executables
if: github.event_name == 'pull_request'
shell: cmd
run: python tools/build_mingw_host_only_tests.py build changed.txt
- name: Build and run changed guest core/libs tests
if: github.event_name == 'pull_request'
shell: cmd
run: python tools/build_changed_guest_tests.py build changed.txt
- id: libs
if: github.event_name != 'pull_request'
shell: cmd
run: cmake --build build --target libs
- if: github.event_name != 'pull_request'
shell: cmd
run: python tools/select_tests.py ctest build --output-on-failure --timeout 120 --parallel 4 --output-log ctest.log --output-junit ctest.xml
- if: github.event_name != 'pull_request'
run: python tools/check_skips.py build/ctest.xml --job windows
- name: Write the test graph of main
if: ${{ !cancelled() && github.event_name == 'push' && steps.build.outcome == 'success' && steps.libs.outcome == 'success' }}
continue-on-error: true
shell: cmd
run: python tools/select_tests.py dump build test-graph.json
- if: ${{ !cancelled() && github.event_name == 'push' && hashFiles('test-graph.json') != '' }}
continue-on-error: true
uses: actions/cache/save@v6
with:
path: test-graph.json
key: test-graph-${{ runner.os }}-${{ github.sha }}
- name: Report tests slower than 30 s
if: ${{ !cancelled() }}
shell: bash
run: |
[ -f ctest.log ] || exit 0
awk '/Test +#[0-9]+: / && $NF == "sec" { for (i = 1; i <= NF; i++) if ($i ~ /^#[0-9]+:$/) name = $(i + 1); t = $(NF - 1) + 0; if (t > max[name]) max[name] = t }
END { for (name in max) if (max[name] > 30) printf "::warning title=Slow test::%s took %.1f s on %s; tests must finish in 30 s (CONTRIBUTING.md)\n", name, max[name], ENVIRON["RUNNER_OS"] }' ctest.log
-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 }}
-31
View File
@@ -1,31 +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.ref }}
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 current base branch script
env:
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: python3 -I tools/check_conventions.py --base HEAD --head "$HEAD_SHA"
@@ -1,43 +0,0 @@
name: Emscripten library portability
on:
pull_request:
paths:
- .github/workflows/emscripten-libraries.yml
- core/libs/**
push:
branches: [main]
paths:
- .github/workflows/emscripten-libraries.yml
- core/libs/**
permissions:
contents: read
jobs:
library-portability:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Compile native library sources and test guest long doubles
run: |
cmake -S core/libs/tests/emscripten -B build-native -DCMAKE_BUILD_TYPE=Release
cmake --build build-native --parallel 2
ctest --test-dir build-native --output-on-failure
- uses: actions/setup-node@v6
with:
node-version: '26'
- name: Compile memory64 libraries and test conversions and module errors
shell: bash
run: |
ANYPS5_TEST_NODE="$(command -v node)"
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$RUNNER_TEMP/emsdk"
"$RUNNER_TEMP/emsdk/emsdk" install 6.0.12
"$RUNNER_TEMP/emsdk/emsdk" activate 6.0.12
source "$RUNNER_TEMP/emsdk/emsdk_env.sh"
emcmake cmake -S core/libs/tests/emscripten -B build-portable -DCMAKE_BUILD_TYPE=Release -DANYPS5_NODE="$ANYPS5_TEST_NODE"
cmake --build build-portable --parallel 2
ctest --test-dir build-portable --output-on-failure
-44
View File
@@ -1,44 +0,0 @@
name: Fix label
on:
schedule:
- cron: '45 * * * *'
workflow_dispatch:
permissions: {}
concurrency:
group: fix-label
cancel-in-progress: true
jobs:
label:
runs-on: ubuntu-latest
permissions:
issues: read
pull-requests: write
env:
GH_TOKEN: ${{ github.token }}
LABEL: fix error
steps:
- run: |
gh api graphql --paginate -f owner="${GITHUB_REPOSITORY%/*}" -f name="${GITHUB_REPOSITORY#*/}" -f query='
query($owner: String!, $name: String!, $endCursor: String) {
repository(owner: $owner, name: $name) {
pullRequests(states: OPEN, first: 100, after: $endCursor) {
pageInfo { hasNextPage endCursor }
nodes { number closingIssuesReferences { totalCount } labels(first: 100) { nodes { name } } }
}
}
}' --jq '.data.repository.pullRequests.nodes[]
| (.closingIssuesReferences.totalCount > 0) as $fix
| ([.labels.nodes[].name] | index(env.LABEL) != null) as $has
| if $fix and ($has | not) then "add \(.number)" elif $has and ($fix | not) then "remove \(.number)" else empty end' > "$RUNNER_TEMP/fix-todo"
label=$(jq -rn 'env.LABEL | @uri')
while read -r action number; do
if [ "$action" = add ]; then
gh api "repos/$GITHUB_REPOSITORY/issues/$number/labels" -f "labels[]=$LABEL" --silent
else
gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$number/labels/$label" --silent
fi
done < "$RUNNER_TEMP/fix-todo"
-29
View File
@@ -1,29 +0,0 @@
name: Input mapper
on:
push:
branches: [main]
pull_request:
branches: [main]
paths:
- '.github/workflows/input-mapper.yml'
- 'tools/input-mapper/**'
- 'core/libs/prx/libScePad/include/**'
- 'core/libs/prx/libSceVideoOut/src/InputMapping.cpp'
permissions:
contents: read
jobs:
input-mapper:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- uses: actions/setup-node@v7
with:
node-version: '22'
package-manager-cache: false
- run: npm --prefix tools/input-mapper test
-42
View File
@@ -1,42 +0,0 @@
name: Labels
on:
push:
branches: [main]
paths: ['.github/workflows/labels.yml']
workflow_dispatch:
permissions: {}
jobs:
sync:
runs-on: ubuntu-latest
permissions:
issues: write
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
steps:
- run: |
existing=$(gh label list --limit 1000 --json name --jq '.[].name')
label() { grep -qixF -- "$1" <<< "$existing" || gh label create "$1" --color "$2" --description "$3"; }
force_label() { gh label create "$1" --color "$2" --description "$3" --force; }
force_label 'needs rebase' b60205 'Conflicts with main, rebase needed'
force_label 'open PR limit' d93f0b 'Closed over the open PR limit: 1 without merged PRs, 20 with at least 1, none from 20'
force_label ci 5319e7 '.github'
force_label agc 1d76db 'libSceAgc*'
force_label shader 1d76db 'core/shader'
force_label 'unblocks title' 0e8a16 'Names a title ID on the Unblocks line'
force_label perf fef2c0 'Performance change'
force_label 'perf numbers missing' e99695 'perf pull request without a before and after summary line'
label relinker 5319e7 'core/relinker'
label libc fbca04 'libc'
label libkernel d93f0b 'libkernel'
label prx c5def5 'Other PRX libraries'
label build bfd4f2 'CMake, submodules, 3rdparty'
label docs 0075ca 'Documentation'
label 'fix error' d73a4a 'Closes an issue (Fixes #N)'
label stale ededed 'Conflicting with main and no activity for 7 days'
-41
View File
@@ -1,41 +0,0 @@
name: Pages progress
on:
push:
branches: [main]
paths:
- core/libs/prx/**
- core/shader/recompiler/RdnaDecoder/include/RdnaDecoder/RdnaOpcode.hpp
permissions:
contents: read
actions: write
pages: read
concurrency:
group: pages-progress
cancel-in-progress: true
jobs:
progress:
if: ${{ !github.event.repository.fork }}
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Deploy Pages if the progress changed
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
python3 tools/progress.py "$RUNNER_TEMP/progress"
site=$(gh api "repos/$GH_REPO/pages" --jq .html_url)
if curl -fsSL "${site%/}/progress.json?$GITHUB_SHA" -o "$RUNNER_TEMP/deployed.json" &&
cmp -s "$RUNNER_TEMP/deployed.json" "$RUNNER_TEMP/progress/progress.json"; then
echo "Progress unchanged, Pages not deployed" >> "$GITHUB_STEP_SUMMARY"
else
gh workflow run pages.yml --ref main
echo "Progress changed, Pages deployment dispatched" >> "$GITHUB_STEP_SUMMARY"
fi
-56
View File
@@ -1,56 +0,0 @@
name: Pages
on:
push:
branches: [main]
paths:
- .github/workflows/pages.yml
- CMakeLists.txt
- core/relinker/**
- demo/web/**
- tools/build_web.py
- tools/package_release.py
- tools/nid_names.py
- tools/progress.py
- tools/progress_history.py
- tools/rdna_isa.txt
- tools/test_web.py
workflow_dispatch:
release:
types: [published]
workflow_run:
workflows: [Release]
types: [completed]
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
pages:
if: ${{ !github.event.repository.fork && (github.event_name != 'workflow_run' || github.event.workflow_run.conclusion == 'success') }}
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v7
with:
ref: main
fetch-depth: 0
- name: Download matching release converter and libraries
env:
GITHUB_TOKEN: ${{ github.token }}
run: python3 tools/build_web.py --build build-wasm --release
- run: python3 tools/progress.py build-wasm/web
- run: python3 tools/progress_history.py build-wasm/web
- uses: actions/upload-pages-artifact@v5
with:
path: build-wasm/web
- id: deployment
uses: actions/deploy-pages@v5
-101
View File
@@ -1,101 +0,0 @@
name: PR intake
on:
pull_request_target:
branches: [main]
types: [opened, reopened]
permissions: {}
concurrency:
group: pr-intake-${{ github.event.pull_request.number }}
jobs:
intake:
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/github-script@v8
with:
script: |
const { owner, repo } = context.repo;
const pull_number = context.payload.pull_request.number;
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
if (pr.state !== 'open' || pr.base.ref !== 'main') {
return;
}
if (context.payload.action === 'reopened') {
let maintainer = false;
try {
const { data: access } = await github.rest.repos.getCollaboratorPermissionLevel({
owner, repo, username: context.payload.sender.login
});
maintainer = ['admin', 'maintain', 'write'].includes(access.role_name ?? access.permission);
} catch (error) {
core.warning(`Could not check the permission of ${context.payload.sender.login}, so the open PR limit applies: ${error.message}`);
}
if (maintainer) {
try {
await github.rest.issues.removeLabel({ owner, repo, issue_number: pull_number, name: 'open PR limit' });
} catch (error) {
if (error.status !== 404) {
core.warning(`Could not remove the open PR limit label: ${error.message}`);
}
}
return;
}
}
const { data: mergedPRs } = await github.rest.search.issuesAndPullRequests({
q: `repo:${owner}/${repo} is:pr is:merged base:main author:${pr.user.login}`,
per_page: 1
});
if (mergedPRs.incomplete_results || !Number.isSafeInteger(mergedPRs.total_count) || mergedPRs.total_count < 0) {
throw new Error('Could not reliably count merged pull requests');
}
const merged = mergedPRs.total_count;
if (merged >= 20) {
return;
}
const allowedOpen = merged >= 1 ? 20 : 1;
const openPRs = await github.paginate(github.rest.pulls.list, {
owner, repo, state: 'open', base: 'main', per_page: 100
});
const reopened = context.payload.action === 'reopened';
const open = new Set(openPRs
.filter((p) => p.user.login === pr.user.login && (reopened || p.number < pull_number))
.map((p) => p.number));
open.add(pull_number);
if (open.size <= allowedOpen) {
return;
}
const name = 'open PR limit';
try {
await github.rest.issues.getLabel({ owner, repo, name });
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner, repo, name, color: 'd93f0b',
description: 'Closed over the open PR limit: 1 without merged PRs, 20 with at least 1, none from 20'
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
await github.rest.issues.getLabel({ owner, repo, name });
}
}
await github.rest.issues.addLabels({ owner, repo, issue_number: pull_number, labels: [name] });
const body = 'Thank you for your contribution! Authors with no pull requests merged into `main` can have 1 open pull request at a time, authors with at least 1 merged can have 20, and from 20 merged there is no limit. This PR has been automatically closed and labeled "open PR limit" because that limit was reached. This is not a judgment of the quality of your changes: reopen it once one of your open pull requests is merged or closed.';
const comments = await github.paginate(github.rest.issues.listComments, {
owner, repo, issue_number: pull_number, per_page: 100
});
if (!comments.some((comment) => comment.user.login === 'github-actions[bot]' && comment.body === body)) {
await github.rest.issues.createComment({ owner, repo, issue_number: pull_number, body });
}
await github.rest.pulls.update({ owner, repo, pull_number, state: 'closed' });
-35
View File
@@ -1,35 +0,0 @@
name: PR labels
on:
pull_request_target:
branches: [main]
types: [opened, edited, reopened, synchronize]
schedule:
- cron: '45 * * * *'
workflow_dispatch:
permissions: {}
concurrency:
group: pr-labels-${{ github.event.pull_request.number || 'all' }}
jobs:
labels:
runs-on: ubuntu-latest
timeout-minutes: 30
permissions:
contents: read
pull-requests: write
issues: write
steps:
- uses: actions/checkout@v7
- env:
GH_TOKEN: ${{ github.token }}
GITHUB_REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
if [ -n "$PR_NUMBER" ]; then
python3 -I tools/pr_labels.py --pr "$PR_NUMBER"
else
python3 -I tools/pr_labels.py --all
fi
-71
View File
@@ -1,71 +0,0 @@
name: PR overlap
on:
push:
branches: [main]
schedule:
- cron: '15 * * * *'
workflow_dispatch:
permissions: {}
concurrency:
group: pr-overlap
jobs:
overlap:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v7
with:
fetch-depth: 0
- uses: actions/cache/restore@v6
with:
path: ${{ runner.temp }}/overlap-state.json
key: pr-overlap-${{ github.run_id }}
restore-keys: pr-overlap-
- env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
run: |
out=$RUNNER_TEMP/overlap
state=$RUNNER_TEMP/overlap-state.json
python3 tools/pr_overlap.py --base "${{ github.event.repository.default_branch }}" --out "$out"
[ -s "$state" ] || echo '{}' > "$state"
record() { jq --arg pr "$1" --arg h "$2" '.[$pr] = $h' "$state" > "$state.new" && mv "$state.new" "$state"; }
shopt -s nullglob
marker='<!-- pr-overlap -->'
unpinned() { sed -E 's#/blob/[0-9a-f]{40}/#/blob/main/#g'; }
prev=
for file in "$out"/*.md; do
[ -z "$prev" ] || record "$prev" "$hash"
pr=$(basename "$file" .md)
hash=$(unpinned < "$file" | sha256sum | cut -d' ' -f1)
prev=
[ "$(jq -r --arg pr "$pr" '.[$pr] // empty' "$state")" = "$hash" ] && continue
prev=$pr
comment=$(gh api "repos/$GH_REPO/issues/$pr/comments" --paginate \
--jq ".[] | select(.user.login == \"github-actions[bot]\" and (.body | startswith(\"$marker\"))) | [.id, .body] | @json" | head -n1)
id=$(jq -r '.[0] // empty' <<< "${comment:-null}")
if [ -s "$file" ]; then
[ "$(jq -r '.[1]' <<< "${comment:-null}" | unpinned)" = "$(unpinned < "$file")" ] && continue
if [ -n "$id" ]; then
gh api -X PATCH "repos/$GH_REPO/issues/comments/$id" -F body=@"$file" > /dev/null
else
gh pr comment "$pr" --body-file "$file"
fi
elif [ -n "$id" ]; then
gh api -X DELETE "repos/$GH_REPO/issues/comments/$id"
fi
done
[ -z "$prev" ] || record "$prev" "$hash"
reports=$(for file in "$out"/*.md; do basename "$file" .md; done | jq -R . | jq -sc .)
jq -c --argjson keep "$reports" 'with_entries(select(.key | IN($keep[])))' "$state" > "$state.new" && mv "$state.new" "$state"
- if: always()
uses: actions/cache/save@v6
with:
path: ${{ runner.temp }}/overlap-state.json
key: pr-overlap-${{ github.run_id }}
-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
-181
View File
@@ -1,181 +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: false
matrix:
include:
- platform: linux
runner: ubuntu-latest
timeout: 60
- platform: windows
runner: windows-latest
timeout: 60
runs-on: ${{ matrix.runner }}
timeout-minutes: ${{ matrix.timeout }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
submodules: recursive
- name: Point the WinLibs CMake at the CA bundle of Git for Windows
if: matrix.platform == 'windows'
shell: bash
run: |
for prefix in ucrt64 mingw64; do
bundle="C:/Program Files/Git/$prefix/etc/ssl/certs/ca-bundle.crt"
if [ -f "$bundle" ]; then echo "SSL_CERT_FILE=$bundle" >> "$GITHUB_ENV"; exit 0; fi
done
echo "::error::No CA bundle found in Git for Windows"; exit 1
- id: toolchain
if: matrix.platform == 'windows'
uses: actions/cache@v6
with:
path: C:\winlibs
key: ${{ env.WINLIBS_ZIP }}
- if: matrix.platform == 'windows' && steps.toolchain.outputs.cache-hit != 'true'
run: |
curl -sSfL -o "$RUNNER_TEMP/winlibs.zip" "https://github.com/brechtsanders/winlibs_mingw/releases/download/$WINLIBS_RELEASE/$WINLIBS_ZIP"
7z x "$RUNNER_TEMP/winlibs.zip" -oC:/winlibs
- if: matrix.platform == 'windows'
run: echo 'C:\winlibs\mingw64\bin' >> "$GITHUB_PATH"
- uses: hendrikmuhs/ccache-action@v1.2.24
with:
key: ${{ matrix.platform }}
save: false
- name: Install lavapipe for the GPU execution tests and the audio development files
if: matrix.platform == 'linux'
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libvulkan1 mesa-vulkan-drivers libpipewire-0.3-dev libpulse-dev libasound2-dev libxrandr-dev libwayland-dev libxkbcommon-dev libegl-dev libdecor-0-dev
- name: Configure Linux
if: matrix.platform == 'linux'
run: cmake -S . -B build $CONFIGURE
- name: Configure Windows
if: matrix.platform == 'windows'
shell: cmd
run: cmake -S . -B build %CONFIGURE%
- name: Build project and tests (Linux)
if: matrix.platform == 'linux'
run: cmake --build build
- name: Build project and tests (Windows)
if: matrix.platform == 'windows'
shell: cmd
run: cmake --build build
- name: Run tests (Linux)
if: matrix.platform == 'linux'
run: ctest --test-dir build --output-on-failure --timeout 120 --stop-on-failure --no-tests=error -E '^precise_wait$'
env:
ANYPS5_REQUIRE_VULKAN: 1
GALLIUM_OVERRIDE_CPU_CAPS: avx
- name: Run tests (Windows)
if: matrix.platform == 'windows'
shell: cmd
run: ctest --test-dir build --output-on-failure --timeout 120 --stop-on-failure --no-tests=error
- name: Build patched libraries (Linux)
if: matrix.platform == 'linux'
run: cmake --build build --target libs
- name: Build patched libraries (Windows)
if: matrix.platform == 'windows'
shell: cmd
run: cmake --build build --target libs
- name: Package release files
run: python tools/package_release.py --platform "${{ matrix.platform }}" --build build --output dist --version "$RELEASE_TAG"
- uses: actions/upload-artifact@v7
with:
name: release-${{ matrix.platform }}
path: dist/*
if-no-files-found: error
compression-level: 0
web:
name: Build and test web converter
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
- name: Build web converter
shell: bash
run: |
git clone --depth 1 https://github.com/emscripten-core/emsdk.git "$RUNNER_TEMP/emsdk"
"$RUNNER_TEMP/emsdk/emsdk" install 6.0.3
"$RUNNER_TEMP/emsdk/emsdk" activate 6.0.3
source "$RUNNER_TEMP/emsdk/emsdk_env.sh"
emcmake cmake -S . -B build-wasm -DANYPS5_BUILD_WASM=ON -DBUILD_TESTING=OFF -DCMAKE_BUILD_TYPE=Release
cmake --build build-wasm --target relinker_web --parallel 2
- name: Test web converter
run: python3 tools/test_web.py --build build-wasm
- name: Package web converter
shell: bash
run: python3 tools/package_release.py --platform web --build build-wasm --output dist --version "$RELEASE_TAG" --revision "$(git rev-parse HEAD)"
- uses: actions/upload-artifact@v7
with:
name: release-web
path: dist/*
if-no-files-found: error
compression-level: 0
publish:
name: Publish release
needs: [build, web]
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
- uses: actions/download-artifact@v8
with:
pattern: release-*
merge-multiple: true
path: dist
- name: Check release files and collect documentation
shell: bash
run: |
for file in "prx-windows-$RELEASE_TAG.zip" "prx-windows-$RELEASE_TAG.tar.gz" "prx-linux-$RELEASE_TAG.zip" "prx-linux-$RELEASE_TAG.tar.gz" "prx-windows-unpatched-$RELEASE_TAG.zip" "prx-windows-unpatched-$RELEASE_TAG.tar.gz" "prx-linux-unpatched-$RELEASE_TAG.zip" "prx-linux-unpatched-$RELEASE_TAG.tar.gz" "relinker-$RELEASE_TAG.exe" "relinker-$RELEASE_TAG" "web-$RELEASE_TAG.zip"; do
test -s "dist/$file"
done
python tools/package_release.py --docs docs/user --output dist
python tools/package_release.py --platform headers --version "$RELEASE_TAG" --output dist
test -s "dist/prx-headers-$RELEASE_TAG.zip"
test -s "dist/prx-headers-$RELEASE_TAG.tar.gz"
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
-112
View File
@@ -1,112 +0,0 @@
name: Sanitizers
on:
schedule:
- cron: '41 3 * * *'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: sanitizers-${{ github.ref }}
cancel-in-progress: true
env:
CONFIGURE: >-
-G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
-DANYPS5_ENABLE_ASAN=ON
SANITIZER_FLAGS: -g1 -fsanitize=undefined -fno-sanitize=vptr
jobs:
address-undefined:
runs-on: ubuntu-latest
timeout-minutes: 330
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- id: submodules
name: Key the submodules on their commits
run: |
echo "key=$(git ls-files -s | awk '$1 == "160000" { print $2, $4 }' | cat - .gitmodules | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
echo "ffmpeg=$(git rev-parse HEAD:3rdparty/ffmpeg-core)" >> "$GITHUB_OUTPUT"
- id: submodule-cache
uses: actions/cache/restore@v6
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Check out the submodules
run: |
if [ -f "$RUNNER_TEMP/submodule-gitdirs.tar" ]; then tar -xf "$RUNNER_TEMP/submodule-gitdirs.tar"; fi
git submodule update --init --recursive --depth 1 --jobs 8
- if: steps.submodule-cache.outputs.cache-hit != 'true'
run: tar -cf "$RUNNER_TEMP/submodule-gitdirs.tar" .git/modules
- if: steps.submodule-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Install the build and test dependencies
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends ninja-build libx11-dev libxext-dev libxrandr-dev libasound2-dev libpulse-dev mesa-vulkan-drivers
- name: Free disk space for the sanitizer build
run: |
df -h /
sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /opt/hostedtoolcache/CodeQL
df -h /
- uses: hendrikmuhs/ccache-action@v1.2.24
with:
key: sanitizers
max-size: 2G
save: ${{ github.ref == 'refs/heads/main' }}
evict-old-files: job
- id: ffmpeg-cache
uses: actions/cache/restore@v6
with:
path: build/externals
key: ffmpeg-sanitizers-${{ runner.os }}-${{ steps.submodules.outputs.ffmpeg }}
- id: configure
run: cmake -S . -B build $CONFIGURE "-DCMAKE_C_FLAGS=$SANITIZER_FLAGS" "-DCMAKE_CXX_FLAGS=$SANITIZER_FLAGS" "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown"
- if: steps.ffmpeg-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: build/externals
key: ${{ steps.ffmpeg-cache.outputs.cache-primary-key }}
- name: Check that every test executable is registered with ctest
run: python3 tools/check_test_registration.py build
- name: Build, keeping on after a target fails so its tests report as not run
if: ${{ !cancelled() && steps.configure.outcome == 'success' }}
continue-on-error: true
run: cmake --build build -- -k 0
- if: ${{ !cancelled() && steps.configure.outcome == 'success' }}
continue-on-error: true
run: cmake --build build --target libs -- -k 0
- name: Run every test under ASan and UBSan
if: ${{ !cancelled() && steps.configure.outcome == 'success' }}
working-directory: build
env:
ASAN_OPTIONS: detect_leaks=0
UBSAN_OPTIONS: print_stacktrace=1:halt_on_error=1
APS5_SKIP_TIMING_TESTS: 1
run: ctest --output-on-failure --timeout 300 --parallel 4 --output-log ctest.log --output-junit ctest.xml || true
- name: Summarize the sanitizer findings
if: ${{ !cancelled() && steps.configure.outcome == 'success' }}
run: >-
python3 tools/sanitizer_report.py build/ctest.xml --title "ASan and UBSan"
--known .github/sanitizer-known-failures.txt --sanitizer address --sanitizer undefined
--summary "$GITHUB_STEP_SUMMARY"
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: sanitizer-tests
path: |
build/ctest.log
build/ctest.xml
if-no-files-found: ignore
-36
View File
@@ -1,36 +0,0 @@
name: Stale conflicts
on:
schedule:
- cron: '30 3 * * *'
workflow_dispatch:
permissions: {}
jobs:
warn:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- env:
GH_TOKEN: ${{ github.token }}
run: |
gh pr list -R "$GITHUB_REPOSITORY" --label stale -L 1000 --json number,labels \
--jq '.[] | select(all(.labels[]; .name != "needs rebase")) | .number' |
while read -r number; do
gh api -X DELETE "repos/$GITHUB_REPOSITORY/issues/$number/labels/stale" --silent
done
- uses: actions/stale@v11
with:
only-pr-labels: needs rebase
days-before-issue-stale: -1
days-before-issue-close: -1
days-before-pr-stale: 7
days-before-pr-close: -1
stale-pr-label: stale
stale-pr-message: 'This pull request has conflicted with `main` and had no activity for 7 days. Rebase it on current `main` so it can be reviewed and merged. It will not be closed automatically.'
remove-pr-stale-when-updated: true
exempt-draft-pr: true
operations-per-run: 200
-42
View File
@@ -1,42 +0,0 @@
name: Web tests
on:
pull_request:
paths:
- .github/workflows/web-tests.yml
- demo/web/**
- tools/test_web.py
permissions:
contents: read
concurrency:
group: web-tests-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
output-directory:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- uses: actions/checkout@v7
with:
persist-credentials: false
- name: Test archive root selection
shell: bash
run: |
zip_url=$(python3 -c 'from pathlib import Path; import re; print(re.search(r"from \"(https://cdn.jsdelivr.net/[^\"]+)\"", Path("demo/web/archive.mjs").read_text(encoding="utf-8")).group(1))')
curl -fsSL "$zip_url" -o "$RUNNER_TEMP/zip.mjs"
ANYPS5_TEST_ZIP_URL="$zip_url" ANYPS5_TEST_ZIP_PATH="$(python3 -c 'from pathlib import Path; import sys; print(Path(sys.argv[1]).resolve().as_uri())' "$RUNNER_TEMP/zip.mjs")" node demo/web/tests/archive-root.test.mjs demo/web
- name: Check browser module syntax
run: |
node --check demo/web/app.mjs
node --check demo/web/archive.mjs
node --check demo/web/batch.mjs
node --check demo/web/failure-report.mjs
node --check demo/web/output-directory.mjs
node --check demo/web/worker.mjs
- name: Test browser converter helpers
run: node --test demo/web/tests/app.test.mjs demo/web/tests/batch.test.mjs demo/web/tests/failure-report.test.mjs demo/web/tests/output-directory.test.mjs
- name: Test directory writer resources
run: node --test demo/web/tests/directory-writer.test.mjs
-117
View File
@@ -1,117 +0,0 @@
name: Windows MSYS2
on:
schedule:
- cron: '23 8 * * *'
workflow_dispatch:
permissions:
contents: read
concurrency:
group: windows-msys2-${{ github.ref }}
cancel-in-progress: true
env:
CONFIGURE: >-
-G Ninja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=ON
-DCMAKE_C_COMPILER=gcc -DCMAKE_CXX_COMPILER=g++
-DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache
jobs:
windows-msys2:
runs-on: windows-latest
timeout-minutes: 45
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v7
with:
ref: ${{ github.sha }}
persist-credentials: false
- id: submodules
name: Key the submodules on their commits
run: |
echo "key=$(git ls-files -s | awk '$1 == "160000" { print $2, $4 }' | cat - .gitmodules | sha256sum | cut -c1-16)" >> "$GITHUB_OUTPUT"
echo "ffmpeg=$(git rev-parse HEAD:3rdparty/ffmpeg-core)" >> "$GITHUB_OUTPUT"
- id: submodule-cache
uses: actions/cache/restore@v6
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Check out the submodules
run: |
if [ -f "$RUNNER_TEMP/submodule-gitdirs.tar" ]; then tar --force-local -xf "$RUNNER_TEMP/submodule-gitdirs.tar"; fi
git submodule update --init --recursive --depth 1 --jobs 8
- if: steps.submodule-cache.outputs.cache-hit != 'true'
run: tar --force-local -cf "$RUNNER_TEMP/submodule-gitdirs.tar" .git/modules
- if: steps.submodule-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: ${{ runner.temp }}/submodule-gitdirs.tar
key: submodule-gitdirs-${{ runner.os }}-${{ steps.submodules.outputs.key }}
- name: Use the CA bundle of Git for Windows
run: |
for prefix in ucrt64 mingw64; do
bundle="C:/Program Files/Git/$prefix/etc/ssl/certs/ca-bundle.crt"
if [ -f "$bundle" ]; then echo "SSL_CERT_FILE=$bundle" >> "$GITHUB_ENV"; exit 0; fi
done
echo "::error::No CA bundle found in Git for Windows"; exit 1
- id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: UCRT64
update: true
install: >-
mingw-w64-ucrt-x86_64-gcc
mingw-w64-ucrt-x86_64-cmake
mingw-w64-ucrt-x86_64-ninja
- shell: pwsh
env:
MSYS2_LOCATION: ${{ steps.msys2.outputs.msys2-location }}
run: Add-Content -LiteralPath $env:GITHUB_PATH -Value "$env:MSYS2_LOCATION\ucrt64\bin"
- uses: hendrikmuhs/ccache-action@v1.2.24
with:
key: windows-msys2
save: ${{ github.ref == 'refs/heads/main' }}
evict-old-files: job
- id: ffmpeg-cache
uses: actions/cache/restore@v6
with:
path: build/externals
key: ffmpeg-${{ runner.os }}-${{ steps.submodules.outputs.ffmpeg }}
- shell: cmd
run: cmake -S . -B build %CONFIGURE% "-DANYPS5_AGC_EXECUTION_TESTS=F16ToF32Unpack;F64FmaSubnormals;RegistrationPrepareShutdown"
- if: steps.ffmpeg-cache.outputs.cache-hit != 'true'
uses: actions/cache/save@v6
continue-on-error: true
with:
path: build/externals
key: ${{ steps.ffmpeg-cache.outputs.cache-primary-key }}
- name: Check that every test executable is registered with ctest
shell: cmd
run: python tools/check_test_registration.py build
- shell: cmd
run: cmake --build build
- shell: cmd
run: cmake --build build --target libs
- shell: cmd
working-directory: build
run: ctest --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() }}
run: |
[ -f build/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"] }' build/ctest.log
- uses: actions/upload-artifact@v7
if: ${{ !cancelled() }}
with:
name: windows-msys2-tests
path: |
build/ctest.log
build/ctest.xml
if-no-files-found: ignore
+18 -108
View File
@@ -1,113 +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/
/.local/
__pycache__/
*.pyc
*.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
-69
View File
@@ -1,69 +0,0 @@
[submodule "3rdparty/jxrlib"]
path = 3rdparty/jxrlib
url = https://github.com/4creators/jxrlib.git
[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/opus"]
path = 3rdparty/opus
url = https://github.com/xiph/opus.git
[submodule "3rdparty/freetype"]
path = 3rdparty/freetype
url = https://github.com/freetype/freetype.git
[submodule "3rdparty/stb"]
path = 3rdparty/stb
url = https://github.com/nothings/stb.git
[submodule "3rdparty/tracy"]
path = 3rdparty/tracy
url = https://github.com/wolfpld/tracy.git
[submodule "3rdparty/mimalloc"]
path = 3rdparty/mimalloc
url = https://github.com/microsoft/mimalloc.git
[submodule "3rdparty/libjpeg-turbo"]
path = 3rdparty/libjpeg-turbo
url = https://github.com/libjpeg-turbo/libjpeg-turbo.git
[submodule "3rdparty/libusb-cmake"]
path = 3rdparty/libusb-cmake
url = https://github.com/libusb/libusb-cmake.git
[submodule "3rdparty/mbedtls"]
path = 3rdparty/mbedtls
url = https://github.com/Mbed-TLS/mbedtls.git
[submodule "3rdparty/zstd"]
path = 3rdparty/zstd
url = https://github.com/facebook/zstd.git
[submodule "3rdparty/ZArchive"]
path = 3rdparty/ZArchive
url = https://github.com/Exzap/ZArchive.git
[submodule "3rdparty/vgmstream"]
path = 3rdparty/vgmstream
url = https://github.com/vgmstream/vgmstream.git
[submodule "3rdparty/ogg"]
path = 3rdparty/ogg
url = https://github.com/xiph/ogg.git
[submodule "3rdparty/vorbis"]
path = 3rdparty/vorbis
url = https://github.com/xiph/vorbis.git
[submodule "3rdparty/nghttp2"]
path = 3rdparty/nghttp2
url = https://github.com/nghttp2/nghttp2.git
Submodule 3rdparty/LibAtrac9 deleted from 946e05a921.
-1
Submodule 3rdparty/SDL2 deleted from 4b69833bc5.
Submodule 3rdparty/SPIRV-Headers deleted from b824a462d4.
Submodule 3rdparty/SPIRV-Tools deleted from 262bdab481.
Submodule 3rdparty/ZArchive deleted from 965b66c8d6.
Submodule 3rdparty/ffmpeg-core deleted from 9ac4cfd195.
Submodule 3rdparty/freetype deleted from 37515cf56b.
-1
Submodule 3rdparty/glslang deleted from ba1640446f.
-1
Submodule 3rdparty/jxrlib deleted from f752187986.
Submodule 3rdparty/libjpeg-turbo deleted from c85e6b905b.
Submodule 3rdparty/libusb-cmake deleted from bea6567b63.
-1
Submodule 3rdparty/mbedtls deleted from 068ff080b3.
Submodule 3rdparty/mimalloc deleted from f8401befa6.
-1
Submodule 3rdparty/nghttp2 deleted from 85e300c79f.
-1
Submodule 3rdparty/ogg deleted from be05b13e98.
-1
Submodule 3rdparty/opus deleted from 22244de5a7.
-1
Submodule 3rdparty/stb deleted from 2c980bb598.
-1
Submodule 3rdparty/tracy deleted from 30997d5ca6.
Submodule 3rdparty/vgmstream deleted from 7c520e8f9b.
-1
Submodule 3rdparty/vorbis deleted from c2aa86b05e.
-1
Submodule 3rdparty/zstd deleted from f8745da6ff.
+149 -13
View File
@@ -1,15 +1,151 @@
# AGENTS.md
# AGENTS.md — how to operate Repo Forker
AnyPS5 relinks PS5 executables into native Linux or Windows programs that run against reimplemented system libraries; it is not an emulator. The rules are [CONTRIBUTING.md](CONTRIBUTING.md) and [CONVENTIONS](docs/dev/CONVENTIONS.md); these are the ones agents break.
Instructions for AI agents (and humans) working on or with this repository.
- No comments in code, except `#endif` and namespace ends.
- An export you cannot implement calls `NotImplemented_nid_no_patch(__func__)`; never return a made-up success.
- Implement the function for every input. Never special-case a value, ID or path seen in one title's trace; if the general behaviour is unknown, throw and record it in `docs/dev/debt/<library>.md`.
- New third-party code is a submodule at `3rdparty/<name>`: add its `.gitmodules` entry (`git submodule add <url> 3rdparty/<name>`) and build it from source with CMake. Never `find_package` or copy sources in.
- Known gaps go in `docs/dev/debt/<library>.md`; notes, reports and logs go in the pull request. Add no other files.
- Commit subjects and PR titles are Conventional Commits.
- PR body: copy [the template](.github/pull_request_template.md), keep every line, tick every box, and fill `What`, `Tested`, `Depends on` (#N or none), `Unblocks` (title ID and discussion, or none), `GPUs tested` (AGC, shader recompiler, VideoOut; otherwise n/a) and `AI-assisted` (yes or no).
- Before pushing run `python3 tools/check_conventions.py --base origin/main`; before opening run `python3 tools/pr_overlap.py --branch <branch>`.
- Build and test: [BUILD](docs/dev/BUILD.md); a relinker-only change builds with `-DANYPS5_RELINKER_ONLY=ON`.
- A speed claim shows `tools/trace_digest.py` summaries of `main` and of the change from the same machine and scene.
- AGC, shader recompiler and VideoOut changes: run the same focused tests on `main` and the change with `ANYPS5_REQUIRE_VULKAN=1`, `ANYPS5_NO_SHADER_CACHE=1` and `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation` using `ctest --test-dir build -R <pattern> -V` from the same machine and GPU. Confirm neither log contains `was not found but was requested by env var VK_INSTANCE_LAYERS`, then compare the logs and confirm the change adds no new `VUID-` validation errors (`ctest` can report `Passed` when validation errors are logged).
## What this is
A **template**. Each fork/generation of it is a *live mirror* of one upstream
git repo on this Gitea: all branches, all tags, full history, plus releases
produced on the runner. The working tree (the `forker` branch) holds only the
machinery — the upstream's content never enters it.
```
This repo (template) → fork/generate per upstream (Lago/<upstream>)
├── forker branch ← scripts, config, workflows
├── .mirror/ ← bare mirror (gitignored)
└── refs ← upstream branches + tags
```
## Golden rules (non-negotiable)
1. **Never authenticate to upstreams with the operator's personal accounts or
stored credentials.** Public upstreams are fetched **anonymously**:
`sync.sh`/`release.sh` cut `GIT_CONFIG_GLOBAL`/`GIT_CONFIG_SYSTEM` and the
credential helper before any upstream git call, and add a Bearer header
**only** when `UPSTREAM_TOKEN` is explicitly set. Do not "simplify" this
away — a `credential.helper=store` entry must never be offered to
`git fetch`. Do not pass tokens from `~/.git-credentials` into the tool.
2. **An empty token must mean "no auth header", not "Bearer <empty>".**
GitHub rejects empty Bearer headers (401). All code paths (git
`extraHeader`, `provider.sh` curl calls) must branch on token presence.
3. **Secrets live in Gitea Actions Variables/Secrets, never in the repo.**
`UPSTREAM_URL` (variable) and `UPSTREAM_TOKEN` (secret, optional). The
`GITEA_*` values are injected by Gitea Actions automatically.
4. **Keep `.forker.yaml` flat** (`key: value`, no nesting) — `config.sh` is a
simple grep parser.
## How it runs
- **Cron** (`sync.yml`, every 10 min) → `forker/sync.sh`:
1. fetch all branches + tags + history into the bare `.mirror/` (incremental
when `actions/cache` restores it),
2. push refs onto this repo + prune what upstream deleted (fork state is
read via the Gitea **API**, not git state — works on cold mirrors),
3. for each **tag that has no release yet**, run `forker/release.sh <tag>`
inline (a tag-push can't trigger a workflow: the tag points at an upstream
commit whose tree has no `.gitea/workflows`). The "missing release" check
(not "new tag") makes a failed release retry on the next cron tick.
`release.sh` publishes only when there is actual content (build assets or
an existing upstream release) and fails loudly on a bad asset
download/upload — a partial release never masquerades as success.
4. `forker/check-unit.sh` — verifies the **Releases unit** is enabled
(self-heals via the units API when the build exposes it; otherwise
detects the 404 and prints the one-time UI fix).
- `release.sh` = local build (if `build_cmd`/`build_script` set) + optional
upstream-release mirror (metadata + assets via `forker/lib/provider.sh`).
Idempotent: an existing release is skipped, not duplicated.
- `runner-check.yml` — run once per repo to confirm a runner serves it.
**Runners are repo-scoped on this Gitea build**: a runner registered on one
repo does not serve another. Use a **shared** runner (or PATCH the runner
to `"shared":true` — the units/runners APIs are missing here, so UI/DB).
## Known Gitea-build quirks (verified on git.lago.dev, Gitea 28.1.0)
- **Forks are created without the Releases unit**
(`DefaultForkRepoUnits = [Code, PullRequests]`) → release assets 404 on the
web download route (`context.RequireUnitReader`), the source tarball 404s
too, while the API by-id works. Fix: enable the Releases unit
(Settings → Repository, or DB `INSERT INTO repo_unit (repo_id, type) ... 4` —
there is no units API on this build). `check-unit.sh` detects/fixes.
**Prefer generating from this template over forking**: generated repos are
not forks and get the full unit set (and Gitea only allows 1 fork of a
repo per user).
- **GitHub asset gotcha**: for a release addressed by *tag*, the asset
`download_url` is **null** — the API `url` returns JSON metadata unless
`Accept: application/octet-stream` is sent. `provider.sh` instead resolves
to the **web download URL** (`github.com/.../releases/download/<tag>/<file>`),
which is also unthrottled (the REST asset endpoint is 60 req/h
unauthenticated — not enough to mirror ~200 assets).
- Runner registration: the `gitea/act_runner` CLI (old and new) fails on this
build ("instance address is empty"); runner creation via API is 405.
Existing runners can be made shared via `PATCH /api/v1/admin/actions/runners/<id>`.
- `actions/cache` timeouts on this build are handled with
`continue-on-error: true` (cold fetch is still correct). The artifact cache
service itself is NOT configured on this Gitea — every sync is a cold fetch
(correct, slower; the cache steps are kept in case a backend is added).
- **Per-job DNS flapping:** the ephemeral per-job container intermittently
fails to resolve `git.lago.dev` on the fork push (the runner daemon's own
network resolves fine). `sync.sh` therefore wraps every fork push in
`push_once` — retry with backoff on transient network errors (resolve /
connect / timeout), abort immediately on non-network failures.
## Editing the template vs. a mirror repo
- **Template** (this repo): edit on `forker` and `git push`. Mirror repos do
**not** auto-track the template — sync them manually after a template
change:
- **Forked repos** (e.g. `Lago/photocraft`): the `forker` branch *is* a
descendant of the template's, so a normal merge works:
```
git remote add template <template-url>
git fetch template forker
git checkout forker && git merge template/forker
git push origin forker
```
- **Generated repos** (e.g. `Lago/pdfcraft`): the `forker` branch is an
**unrelated snapshot** (no common ancestor — `git merge` fails with
add/add conflicts). Reset it to the template and re-apply the single
per-repo setting, then force-push:
```
git checkout forker
git fetch template forker
git reset --hard template/forker
# re-apply this repo's .forker.yaml setting(s), e.g.:
sed -i 's/^mirror_upstream_releases: false/mirror_upstream_releases: true/' .forker.yaml
git commit -am "Adopt template; enable mirror_upstream_releases"
git push --force origin forker
```
This is safe: `forker` holds only the machinery + config (the upstream
content lives on the mirrored branches), so the snapshot's extra content
is discarded by design.
- **Per-repo config**: edit `.forker.yaml` in the UI on the `forker` branch.
Pushing to `forker` triggers a re-sync.
## Local testing (without the runner)
```
export UPSTREAM_URL=... UPSTREAM_TOKEN= # empty for public upstreams
export GITEA_TOKEN=... GITEA_SERVER_URL=... GITEA_OWNER=... GITEA_REPO=...
bash forker/sync.sh # full mirror (use a scratch repo!)
bash forker/release.sh <tag>
make check-unit
```
Test against a **scratch repo** you delete afterwards; never point the scripts
at a real mirror while experimenting. `GITEA_TOKEN` from Actions is an API
token (Bearer works for API + git); a *password* only works for basic auth —
expect the Bearer API calls to fail when testing with a password.
## File map
- `forker/sync.sh` — mirror worker (fetch/push/prune + inline releases + unit check)
- `forker/release.sh` — local build + upstream-release mirror, idempotent
- `forker/check-unit.sh` — Releases unit detection/self-heal (exit 10 = missing)
- `forker/lib/config.sh` — flat `.forker.yaml` parser
- `forker/lib/provider.sh` — provider-agnostic releases API (github/gitea/codeberg)
- `forker/runner-register.sh` — runner registration (see quirks above)
- `.gitea/workflows/` — sync.yml (cron), release.yml (manual), runner-check.yml
- `runner/docker-compose.yml` — gitea-act-runner in Docker (tracked; the local
`runner/config/` token dir is gitignored)
- `Makefile` — local targets (sync / release / mirror-releases / runner-check /
runner-register / check-unit); `runner-check` queries the Gitea runner APIs
- `docs/index.html` — architecture webpage (static)
-605
View File
@@ -1,605 +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}>")
if(MINGW)
target_sources(${target} PRIVATE $<TARGET_OBJECTS:anyps5_windows_test_exit>)
target_link_options(${target} PRIVATE LINKER:--wrap=main)
endif()
endfunction()
function(configure_host_test_executable target)
if(MINGW)
target_compile_options(${target} PRIVATE -fasynchronous-unwind-tables)
target_link_options(${target} PRIVATE -static -static-libgcc -static-libstdc++)
endif()
endfunction()
function(add_asan_test_options test options)
if(ANYPS5_ENABLE_ASAN)
set_property(TEST ${test} APPEND PROPERTY ENVIRONMENT_MODIFICATION "ASAN_OPTIONS=string_append::${options}")
endif()
endfunction()
option(BUILD_TESTING "Build and register relinker tests" OFF)
option(ANYPS5_RELINKER_ONLY "Build the relinker without system libraries or third-party dependencies" OFF)
option(ANYPS5_BUILD_WASM "Build the browser relinker" OFF)
option(ANYPS5_RELINKER_CLI "Build the native relinker command line" ON)
if(ANYPS5_BUILD_WASM)
if(NOT EMSCRIPTEN)
message(FATAL_ERROR "ANYPS5_BUILD_WASM requires emcmake and Emscripten")
endif()
if(BUILD_TESTING)
message(FATAL_ERROR "Use the native build for C++ tests and the browser tests for WASM")
endif()
set(ANYPS5_RELINKER_CLI OFF CACHE BOOL "Build the native relinker command line" FORCE)
add_subdirectory(core/relinker)
return()
endif()
if(BUILD_TESTING)
enable_testing()
if(MINGW)
get_filename_component(testCompilerDirectory "${CMAKE_CXX_COMPILER}" DIRECTORY)
foreach(runtimeName IN ITEMS libgcc_s_seh-1.dll libstdc++-6.dll libwinpthread-1.dll)
if(NOT EXISTS "${testCompilerDirectory}/${runtimeName}")
if(ANYPS5_RELINKER_ONLY)
continue()
endif()
message(FATAL_ERROR "Cannot locate MinGW runtime: ${runtimeName}")
endif()
file(COPY "${testCompilerDirectory}/${runtimeName}" DESTINATION "${ANYPS5_TEST_OUTPUT_DIRECTORY}")
endforeach()
endif()
endif()
option(ANYPS5_ENABLE_SPIRV_TOOLS "Enable SPIRV-Tools validation and optimization" OFF)
option(ANYPS5_ENABLE_ASAN "Build Linux targets with AddressSanitizer and use an ASan-compatible guest arena range" OFF)
option(ANYPS5_ENABLE_TSAN "Build Linux targets with ThreadSanitizer" 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_LIBRESSL_ORACLE "Build guest_libressl_oracle, which compares libSceLibreSsl with LibreSSL 2.5.4 downloaded from ftp.openbsd.org" OFF)
option(ANYPS5_USE_SYSTEM_DEPS "Resolve SDL2, freetype, Vulkan-Headers, SPIRV-Headers, glslang and SPIRV-Tools from the system instead of the bundled submodules" OFF)
add_compile_definitions(APS5_ENABLE_TIMING_LOG=$<BOOL:${APS5_ENABLE_TIMING_LOG}>)
include(cmake/SystemDeps.cmake)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(CheckCXXSourceCompiles)
function(anyps5_check_cxx_links_standard_library)
set(CMAKE_TRY_COMPILE_TARGET_TYPE EXECUTABLE)
check_cxx_source_compiles("#include <string>\nint main(int argc, char**) { try { throw std::string(static_cast<std::size_t>(argc), 'x'); } catch (const std::string& text) { return static_cast<int>(text.size()) - argc; } }" ANYPS5_CXX_LINKS_STANDARD_LIBRARY)
endfunction()
anyps5_check_cxx_links_standard_library()
if(NOT ANYPS5_CXX_LINKS_STANDARD_LIBRARY)
message(FATAL_ERROR "The C++ compiler ${CMAKE_CXX_COMPILER} cannot link a program that uses the C++ standard library. "
"Set CMAKE_CXX_COMPILER to the C++ driver (g++ or clang++, not gcc or clang) in a new build directory. "
"Supported toolchains are listed in docs/dev/BUILD.md.")
endif()
if(ANYPS5_ENABLE_ASAN AND ANYPS5_ENABLE_TSAN)
message(FATAL_ERROR "ANYPS5_ENABLE_ASAN and ANYPS5_ENABLE_TSAN cannot be combined")
endif()
if(ANYPS5_ENABLE_TSAN)
if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux")
message(FATAL_ERROR "ANYPS5_ENABLE_TSAN is supported only on Linux")
endif()
if(NOT CMAKE_CXX_COMPILER_ID MATCHES "^(GNU|Clang)$")
message(FATAL_ERROR "ANYPS5_ENABLE_TSAN requires GCC or Clang")
endif()
endif()
option(ANYPS5_BUILD_FUZZERS "Build the relinker libFuzzer targets with AddressSanitizer and UndefinedBehaviorSanitizer" OFF)
if(ANYPS5_BUILD_FUZZERS)
if(NOT ANYPS5_RELINKER_ONLY)
message(FATAL_ERROR "ANYPS5_BUILD_FUZZERS requires ANYPS5_RELINKER_ONLY")
endif()
if(NOT CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR APPLE OR WIN32)
message(FATAL_ERROR "ANYPS5_BUILD_FUZZERS requires Clang on Linux")
endif()
set(ANYPS5_RELINKER_CLI OFF CACHE BOOL "Build the native relinker command line" FORCE)
add_compile_options(-fsanitize=address,undefined,fuzzer-no-link -fno-sanitize=function -fno-sanitize-recover=undefined -fno-omit-frame-pointer)
add_link_options(-fsanitize=address,undefined)
elseif(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(ANYPS5_ENABLE_TSAN)
add_compile_options(-fsanitize=thread -fno-omit-frame-pointer)
add_link_options(-fsanitize=thread)
add_compile_definitions(ANYPS5_ENABLE_TSAN=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(MINGW)
add_library(anyps5_windows_test_exit OBJECT cmake/WindowsTestExit.cpp)
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/libs
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ControlFlow/include)
add_test(NAME request_serializer COMMAND request_serializer_tests)
set_tests_properties(request_serializer PROPERTIES TIMEOUT 20)
find_package(Python3 QUIET COMPONENTS Interpreter)
add_test_executable(shader_ir_use_rewrite_tests
core/shader/recompiler/IntermediateRepresentation/tests/UseRewrite.cpp
core/shader/recompiler/IntermediateRepresentation/tests/UseRewriteAllocation.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrValue.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrBlock.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp
core/shader/recompiler/IntermediateRepresentation/src/GuestRegister.cpp)
target_include_directories(shader_ir_use_rewrite_tests PRIVATE
core/shader/recompiler/IntermediateRepresentation/include)
add_test(NAME shader_ir_use_rewrite COMMAND shader_ir_use_rewrite_tests)
set_tests_properties(shader_ir_use_rewrite PROPERTIES TIMEOUT 20)
add_test_executable(shader_ssa_pass_reads_tests
core/shader/recompiler/tests/SsaPassReads.cpp
core/shader/recompiler/Optimization/src/SsaBuilder/SsaPass.cpp
core/shader/recompiler/Optimization/src/SsaBuilder/SsaDefTable.cpp
core/shader/recompiler/Optimization/src/SsaBuilder/SsaVariable.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrProgram.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrValue.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrBlock.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrOpcode.cpp
core/shader/recompiler/IntermediateRepresentation/src/IrType.cpp
core/shader/recompiler/IntermediateRepresentation/src/GuestRegister.cpp)
target_include_directories(shader_ssa_pass_reads_tests PRIVATE
core/shader/recompiler
core/shader/recompiler/IntermediateRepresentation/include
core/shader/recompiler/Optimization/include
core/shader/recompiler/RdnaDecoder/include
core/shader/recompiler/ControlFlow/include)
add_test(NAME shader_ssa_pass_reads COMMAND shader_ssa_pass_reads_tests)
set_tests_properties(shader_ssa_pass_reads PROPERTIES TIMEOUT 20)
add_test_executable(pad_command_file_tests core/libs/prx/libScePad/tests/InputCommandFile.cpp)
target_include_directories(pad_command_file_tests PRIVATE core/libs)
add_test(NAME pad_command_file COMMAND pad_command_file_tests)
set_tests_properties(pad_command_file PROPERTIES TIMEOUT 20)
if(Python3_Interpreter_FOUND)
add_test(NAME mingw_host_only_test_targets COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_mingw_host_only_test_targets.py)
add_test(NAME build_changed_guest_tests COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_changed_guest_tests.py)
add_test(NAME shader_cache_native_paths COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/tests/test_shader_cache_native_paths.py
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler/ShaderCacheVersion.cmake ${CMAKE_COMMAND})
set_tests_properties(shader_cache_native_paths PROPERTIES TIMEOUT 20)
foreach(shard RANGE 0 6)
if(shard EQUAL 0)
set(shader_cache_sources_test_name shader_cache_runtime_sources)
else()
set(shader_cache_sources_test_name shader_cache_runtime_sources_shard_${shard})
endif()
add_test(NAME ${shader_cache_sources_test_name} COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_shader_cache_runtime_sources.py
${CMAKE_CURRENT_SOURCE_DIR}/core/shader/recompiler ${CMAKE_COMMAND} --shard ${shard}/7)
set_tests_properties(${shader_cache_sources_test_name} PROPERTIES TIMEOUT 180)
endforeach()
add_test(NAME tools_nid_name_audit COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_audit_nid_names.py)
set_tests_properties(tools_nid_name_audit PROPERTIES TIMEOUT 20)
add_test(NAME pr_overlap_encoding COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_encoding.py)
add_test(NAME pr_overlap_dependencies COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_dependencies.py)
add_test(NAME pr_overlap_tools COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap.py)
add_test(NAME pr_labels COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_labels.py)
add_test(NAME progress_history COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_history.py ProgressHistoryTests)
add_test(NAME progress_history_output COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress_history.py HistoryReportOutputTests)
set_tests_properties(progress_history_output PROPERTIES TIMEOUT 20)
add_test(NAME progress_report COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_progress.py)
add_test(NAME tools_compdb_inventory COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_compile_database_inventory.py)
set_tests_properties(tools_compdb_inventory PROPERTIES TIMEOUT 20)
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)
if(Python3_VERSION VERSION_GREATER_EQUAL 3.11)
add_test(NAME validate_patch_catalog COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_validate_patch_catalog.py)
endif()
if(NOT APPLE)
add_test(NAME annotate_module COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_annotate_module.py)
set_tests_properties(annotate_module PROPERTIES TIMEOUT 20)
endif()
add_test(NAME unwrap_self COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_unwrap_self.py)
add_test(NAME audit_dump COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_audit_dump.py)
foreach(shard RANGE 0 11)
if(shard EQUAL 0)
set(conventions_test_name conventions_function_bodies)
else()
set(conventions_test_name conventions_function_bodies_shard_${shard})
endif()
add_test(NAME ${conventions_test_name} COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_comments.py --shard ${shard}/12)
set_tests_properties(${conventions_test_name} PROPERTIES TIMEOUT 120)
endforeach()
add_test(NAME performance_csv COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_performance_csv.py)
set_tests_properties(performance_csv PROPERTIES TIMEOUT 20)
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 preview_pad_timeline COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_preview_pad_timeline.py)
set_tests_properties(preview_pad_timeline PROPERTIES TIMEOUT 20)
add_test(NAME conventions_git_errors COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_git.py)
add_test(NAME tools_configure_diff COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_compare_configure_checks.py)
set_tests_properties(tools_configure_diff PROPERTIES TIMEOUT 20)
add_test(NAME conventions_doc_links COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_doc_links.py)
add_test(NAME conventions_unknown_nids COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_unknown_nids.py)
add_test(NAME conventions_debt_length COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_debt_length.py)
add_test(NAME test_registration COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_test_registration.py)
add_test(NAME test_script_registration COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/check_test_registration.py --scripts)
add_test(NAME build_eligibility COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_eligibility.py)
add_test(NAME check_skips_ctest COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips_ctest.py)
set_tests_properties(check_skips_ctest PROPERTIES TIMEOUT 30)
add_test(NAME tools_pe_inventory COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_pe_symbol_inventory.py)
set_tests_properties(tools_pe_inventory PROPERTIES TIMEOUT 20)
add_test(NAME check_skips COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_skips.py)
add_test(NAME sanitizer_report COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_sanitizer_report.py)
add_test(NAME select_tests COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_select_tests.py)
add_test(NAME tools_self_inspect COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_inspect_self.py)
set_tests_properties(tools_self_inspect PROPERTIES TIMEOUT 20)
add_test(NAME check_main_sync COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_main_sync.py CheckMainSyncTests)
set_tests_properties(check_main_sync PROPERTIES TIMEOUT 30)
set(check_main_sync_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_main_sync.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${check_main_sync_source}")
file(STRINGS "${check_main_sync_source}" check_main_sync_classes REGEX "^class [A-Za-z0-9_]*Tests\\(")
foreach(test_class IN LISTS check_main_sync_classes)
string(REGEX REPLACE "^class ([A-Za-z0-9_]+).*" "\\1" test_class "${test_class}")
if(NOT test_class STREQUAL "CheckMainSyncTests")
add_test(NAME check_main_sync_${test_class} COMMAND ${Python3_EXECUTABLE} "${check_main_sync_source}" ${test_class})
set_tests_properties(check_main_sync_${test_class} PROPERTIES TIMEOUT 30)
endif()
endforeach()
set(select_tests_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_select_tests.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${select_tests_source}")
file(STRINGS "${select_tests_source}" select_tests_classes REGEX "^class [A-Za-z0-9_]*Tests\\(")
foreach(test_class IN LISTS select_tests_classes)
string(REGEX REPLACE "^class ([A-Za-z0-9_]+).*" "\\1" test_class "${test_class}")
if(test_class STREQUAL "SelectTests")
set_tests_properties(select_tests PROPERTIES ENVIRONMENT "ANYPS5_SELECT_TEST_CLASS=SelectTests" TIMEOUT 30)
else()
add_test(NAME select_tests_${test_class} COMMAND ${Python3_EXECUTABLE} "${select_tests_source}" ${test_class})
set_tests_properties(select_tests_${test_class} PROPERTIES TIMEOUT 30)
endif()
endforeach()
add_test(NAME configure_seed COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedTests)
add_test(NAME configure_seed_paths COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedPathTests)
add_test(NAME configure_seed_round_trips COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ConfigureSeedRoundTripTests)
add_test(NAME configure_seed_parsing COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_configure_seed.py ChecksParsingTests)
add_test(NAME vulkan_validation_gate_reports COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_vulkan_validation_gate.py ReportTests)
add_test(NAME vulkan_validation_gate_integration COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_vulkan_validation_gate.py IntegrationTests)
add_test(NAME vulkan_validation_gate_attribution COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_vulkan_validation_gate.py AttributionTests)
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 job_reference_errors COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_job_reference_errors.py)
set_tests_properties(job_reference_errors PROPERTIES TIMEOUT 20)
add_test(NAME hardware_oracle_compare COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/hw-oracle/test_compare_results.py)
set_tests_properties(hardware_oracle_compare PROPERTIES TIMEOUT 120)
add_test(NAME pr_overlap_exports COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_exports.py)
add_test(NAME pr_overlap_wrapped_exports COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_wrapped_exports.py)
add_test(NAME pr_overlap_own_branch COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_own_branch.py)
add_test(NAME pr_overlap_errors COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_errors.py)
add_test(NAME pr_overlap_branch_scan COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_branch_scan.py)
add_test(NAME pr_overlap_progress COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_progress.py)
add_test(NAME pr_overlap_pages COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_pages.py)
add_test(NAME pr_overlap_export_cache COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_export_cache.py)
add_test(NAME pr_overlap_fail_closed COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pr_overlap_fail_closed.py)
add_test(NAME nid_database_cache COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_nid_names.py)
add_test(NAME release_package COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_package_release.py)
add_test(NAME web_release COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_web_release.py)
set_tests_properties(web_release PROPERTIES TIMEOUT 20)
add_test(NAME web_library_assets COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_build_web.py)
set_tests_properties(web_library_assets PROPERTIES TIMEOUT 20)
add_test(NAME pad_input COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pad_input.py)
set_tests_properties(pad_input PROPERTIES TIMEOUT 20)
add_test(NAME pad_timeline COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_pad_timeline.py)
set_tests_properties(pad_timeline PROPERTIES TIMEOUT 20)
function(register_check_compile_remaining_tests)
if(TEST check_compile)
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS
"${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py")
file(STRINGS "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py"
check_compile_lines REGEX "^class CheckCompile|^ def test_")
foreach(line IN LISTS check_compile_lines)
if(line MATCHES "^class (CheckCompile[A-Za-z0-9_]*)")
set(check_compile_class "${CMAKE_MATCH_1}")
elseif(NOT check_compile_class MATCHES "^CheckCompile(Fixture|Tests|OutputTests)$")
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${line}")
add_test(NAME check_compile_${check_compile_class}_${test_case} COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py ${check_compile_class}.${test_case})
set_tests_properties(check_compile_${check_compile_class}_${test_case} PROPERTIES TIMEOUT 30)
endif()
endforeach()
endif()
endfunction()
cmake_language(DEFER CALL register_check_compile_remaining_tests)
set(check_compile_modes_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile_modes.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${check_compile_modes_source}")
file(STRINGS "${check_compile_modes_source}" check_compile_modes_cases REGEX "^ def test_")
foreach(test_case IN LISTS check_compile_modes_cases)
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${test_case}")
add_test(NAME check_compile_modes_${test_case} COMMAND ${Python3_EXECUTABLE}
"${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile_modes.py" CheckCompileModeTests.${test_case})
set_tests_properties(check_compile_modes_${test_case} PROPERTIES TIMEOUT 60)
endforeach()
add_test(NAME trace_digest COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_trace_digest.py)
add_test(NAME symbolize_samples COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_symbolize_samples.py)
add_test(NAME ab_split COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_ab_split.py)
set_tests_properties(ab_split PROPERTIES TIMEOUT 20)
add_test(NAME conventions_bom_shebang COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_bom_shebang.py)
set_tests_properties(conventions_bom_shebang PROPERTIES TIMEOUT 20)
add_test(NAME env_reference COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_env_reference.py)
set_tests_properties(env_reference PROPERTIES TIMEOUT 20)
set(env_reference_test_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_env_reference.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${env_reference_test_source}")
file(STRINGS "${env_reference_test_source}" env_reference_cases REGEX "^ def test_")
foreach(test_case IN LISTS env_reference_cases)
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${test_case}")
add_test(NAME conventions_env_reference_${test_case} COMMAND ${Python3_EXECUTABLE}
"${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_env_reference.py" "EnvReferenceDiffTests.${test_case}")
set_tests_properties(conventions_env_reference_${test_case} PROPERTIES TIMEOUT 30)
endforeach()
add_test(NAME conventions_body_bom COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_body_bom.py)
add_test(NAME conventions_blob_reads COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_blob_reads.py)
add_test(NAME conventions_agent_files COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_agent_files.py)
add_test(NAME conventions_alignment COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_alignment.py)
add_test(NAME trace_intervals_csv COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_trace_intervals_csv.py)
set_tests_properties(trace_intervals_csv PROPERTIES TIMEOUT 20)
set(trace_digest_test_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_trace_digest.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${trace_digest_test_source}")
file(STRINGS "${trace_digest_test_source}" trace_digest_cases REGEX "^class |^ def test_")
set(trace_digest_first TRUE)
foreach(test_case IN LISTS trace_digest_cases)
if(test_case MATCHES "^class ([A-Za-z0-9_]+)")
set(trace_digest_class "${CMAKE_MATCH_1}")
else()
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${test_case}")
if(trace_digest_first)
set_tests_properties(trace_digest PROPERTIES
ENVIRONMENT "TRACE_DIGEST_TEST=${trace_digest_class}.${test_case}" TIMEOUT 20)
set(trace_digest_first FALSE)
else()
add_test(NAME trace_digest_${trace_digest_class}_${test_case} COMMAND ${Python3_EXECUTABLE}
"${trace_digest_test_source}" "${trace_digest_class}.${test_case}")
set_tests_properties(trace_digest_${trace_digest_class}_${test_case} PROPERTIES TIMEOUT 20)
endif()
endif()
endforeach()
add_test(NAME tools_headers_manifest COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_public_headers_manifest.py)
set_tests_properties(tools_headers_manifest PROPERTIES TIMEOUT 20)
add_test(NAME conventions_pr_template COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_conventions_pr_template.py)
add_test(NAME check_compile_preprocessor COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile_preprocessor.py)
set_tests_properties(check_compile_preprocessor PROPERTIES TIMEOUT 20)
set(check_compile_test_source "${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py")
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${check_compile_test_source}")
file(STRINGS "${check_compile_test_source}" check_compile_cases REGEX "^class CheckCompile|^ def test_")
foreach(test_case IN LISTS check_compile_cases)
if(test_case MATCHES "^class (CheckCompile[A-Za-z0-9_]*)")
set(check_compile_class "${CMAKE_MATCH_1}")
else()
string(REGEX REPLACE "^ def (test_[A-Za-z0-9_]+).*" "\\1" test_case "${test_case}")
add_test(NAME check_compile_${test_case} COMMAND ${Python3_EXECUTABLE}
"${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_check_compile.py" "${check_compile_class}.${test_case}")
set_tests_properties(check_compile_${test_case} PROPERTIES TIMEOUT 30)
endif()
endforeach()
add_test(NAME tools_seed_check COMMAND ${Python3_EXECUTABLE} ${CMAKE_SOURCE_DIR}/tools/tests/test_check_configure_seed.py)
set_tests_properties(tools_seed_check PROPERTIES TIMEOUT 20)
add_test(NAME performance_compare COMMAND ${Python3_EXECUTABLE}
${CMAKE_CURRENT_SOURCE_DIR}/tools/tests/test_performance_compare.py)
set_tests_properties(performance_compare PROPERTIES TIMEOUT 20)
endif()
endif()
if(ANYPS5_RELINKER_ONLY)
add_subdirectory(core/relinker)
return()
endif()
if(APPLE AND NOT CMAKE_OSX_ARCHITECTURES STREQUAL "x86_64")
message(FATAL_ERROR "The full build on macOS is x86-64 only; configure without CMAKE_OSX_ARCHITECTURES or set it to x86_64")
endif()
set(SDL_SHARED OFF CACHE BOOL "" FORCE)
set(SDL_STATIC ON CACHE BOOL "" FORCE)
set(SDL_TEST OFF CACHE BOOL "" FORCE)
set(SDL_VIDEO ON CACHE BOOL "" FORCE)
set(SDL_RENDER OFF CACHE BOOL "" FORCE)
set(SDL_X11 ON CACHE BOOL "" FORCE)
set(SDL_WAYLAND ON CACHE BOOL "" FORCE)
set(SDL_OPENGL OFF CACHE BOOL "" FORCE)
set(SDL_OPENGLES OFF CACHE BOOL "" FORCE)
set(SDL_VULKAN ON CACHE BOOL "" FORCE)
set(SDL_JOYSTICK ON CACHE BOOL "" FORCE)
set(SDL_HAPTIC OFF CACHE BOOL "" FORCE)
set(SDL_HIDAPI ON CACHE BOOL "" FORCE)
set(SDL_SENSOR OFF CACHE BOOL "" FORCE)
set(SDL_STATIC_PIC ON CACHE BOOL "" FORCE)
if(NOT ANYPS5_USE_SYSTEM_DEPS)
set(ANYPS5_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS}")
set(CMAKE_EXE_LINKER_FLAGS "")
add_subdirectory(3rdparty/SDL2)
set(CMAKE_EXE_LINKER_FLAGS "${ANYPS5_EXE_LINKER_FLAGS}")
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
get_directory_property(ANYPS5_SDL_X11_XRANDR DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_X11_XRANDR)
if(NOT ANYPS5_SDL_X11_XRANDR)
message(FATAL_ERROR "SDL has no XRandR support, so X11 display refresh rates cannot be queried. "
"Install libxrandr-dev (Debian, Ubuntu) or libXrandr-devel (Fedora), "
"enable SDL_X11_XRANDR, then rerun configuration.")
endif()
get_directory_property(ANYPS5_SDL_PIPEWIRE DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_PIPEWIRE)
get_directory_property(ANYPS5_SDL_PULSEAUDIO DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_PULSEAUDIO)
get_directory_property(ANYPS5_SDL_ALSA DIRECTORY 3rdparty/SDL2 DEFINITION HAVE_ALSA)
if(NOT ANYPS5_SDL_PIPEWIRE AND NOT ANYPS5_SDL_PULSEAUDIO AND NOT ANYPS5_SDL_ALSA)
message(FATAL_ERROR "SDL found no PipeWire, PulseAudio or ALSA development files, so audio output would be silent. "
"Install libpipewire-0.3-dev, libpulse-dev and libasound2-dev (Debian, Ubuntu) "
"or pipewire-devel, pulseaudio-libs-devel and alsa-lib-devel (Fedora), then rerun configuration.")
endif()
endif()
endif()
set(ARCHITECTURE x86_64)
add_subdirectory(3rdparty/ffmpeg-core)
if(MINGW)
target_link_libraries(ffmpeg INTERFACE bcrypt ole32 user32 ws2_32)
elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(ffmpeg INTERFACE LINKER:--exclude-libs,ALL)
endif()
if(APS5_ENABLE_TRACY)
include(cmake/Tracy.cmake)
endif()
set(FT_DISABLE_ZLIB ON CACHE BOOL "" FORCE)
set(FT_DISABLE_BZIP2 ON CACHE BOOL "" FORCE)
set(FT_DISABLE_PNG ON CACHE BOOL "" FORCE)
set(FT_DISABLE_HARFBUZZ ON CACHE BOOL "" FORCE)
set(FT_DISABLE_BROTLI ON CACHE BOOL "" FORCE)
set(FT_DISABLE_HVF 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()
include(cmake/Jxr.cmake)
set(LIBUSB_BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
set(LIBUSB_INSTALL_TARGETS OFF CACHE BOOL "" FORCE)
set(LIBUSB_BUILD_TESTING OFF CACHE BOOL "" FORCE)
set(LIBUSB_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
set(LIBUSB_ENABLE_UDEV OFF CACHE BOOL "" FORCE)
add_subdirectory(3rdparty/libusb-cmake EXCLUDE_FROM_ALL)
set_target_properties(usb-1.0 PROPERTIES POSITION_INDEPENDENT_CODE ON)
include(cmake/ZArchive.cmake)
include(cmake/Opus.cmake)
if(WIN32 OR APPLE)
set(MI_BUILD_SHARED ON CACHE BOOL "" FORCE)
set(MI_BUILD_STATIC OFF CACHE BOOL "" FORCE)
set(MI_BUILD_OBJECT OFF CACHE BOOL "" FORCE)
set(MI_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(MI_OVERRIDE ON CACHE BOOL "" FORCE)
set(MI_WIN_REDIRECT ON CACHE BOOL "" FORCE)
set(MI_FREE_IS_CHECKED SHARED CACHE STRING "" FORCE)
add_subdirectory(3rdparty/mimalloc EXCLUDE_FROM_ALL)
if(MINGW)
target_compile_definitions(mimalloc PRIVATE MI_MINGW_UCRT64=1)
target_link_options(mimalloc PRIVATE -static
LINKER:--wrap=malloc,--wrap=calloc,--wrap=realloc,--wrap=free,--wrap=strdup,--wrap=_strdup)
target_sources(mimalloc PRIVATE ${CMAKE_SOURCE_DIR}/core/libs/allocator/RuntimeHeap.c)
endif()
endif()
add_subdirectory(core/shader/recompiler)
add_subdirectory(core/Decoder/Jpeg)
add_subdirectory(core/Decoder/Png)
add_subdirectory(core/libs)
add_subdirectory(core/relinker)
-78
View File
@@ -1,78 +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 exported PS5 function with `APS5_VABI` must have exactly one declaration in a header reachable through the library's `<library>.hpp`. Duplicate declarations in headers, `.cpp` files and tests are forbidden. This is checked by the Python test [`public_headers`](core/libs/tests/test_public_headers.py).**
- 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).
- An export's signature or behaviour taken from a title's call sites or from a library's disassembly follows [reading titles and libraries](docs/dev/REVERSE_ENGINEERING.md): a call site settles the arguments, not what the library does.
- A silent stub is allowed only when it unblocks a title and only affects the UI; add it under Silent stubs in its library's [technical debt](docs/dev/debt/) file.
- Missing imports fail at startup with a clear error; don't replace them with fallbacks that keep running.
- Implement the general behaviour of a function, not what one title happens to need.
- Don't add replacements for modules that titles ship themselves in `sce_module/`, `sce_modules/` or `prx/`: engine or middleware modules (Cohtml, FMOD, GOG Galaxy) and SDK libraries that only wrap other system libraries. The relinker converts and loads the title's own module, and a host library with the same name is left out of `DT_NEEDED`. Only system libraries, which reach the kernel or the hardware, are reimplemented in [core/libs/prx](core/libs/prx). A host copy may still exist for a wrapped library that some dumps lack entirely, like libSceNpCppWebApi: the title's own module wins whenever one is shipped, so it is only ever consulted by titles that ship nothing.
- Avoid non-standard extensions (`__attribute__`, etc.) where standard C++ is enough. Helper symbols that must not become NIDs use the `_nid_no_patch` or `_nid_no_patch_cut` suffix.
- `alignas` takes at most 8192: MinGW GCC, the Windows compiler, rejects static objects aligned above it. A larger block is aligned at run time inside a bigger buffer.
- 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, which include the relinker tests, using the pushed commit without contributor checks. The relinker-only build and tests run separately on macOS, for arm64 and x86_64, and the relinker-only build with the address sanitizer runs on Linux, only when the push changes a file the relinker-only build uses.
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 up to 40 numbers of open pull requests targeting `main`, separated by spaces or commas; they are merged in that order and built together. A collaborator can start the same manual run from the command line, replacing `1234` with the pull request numbers:
```
gh workflow run build.yml --repo boykopovar/AnyPS5 --ref main --field pr=1234
```
This manual run also builds and tests the relinker on Linux, Windows and macOS when the pull request changes a file the relinker-only build uses, regardless of the author's previous contributions. The relinker matrix also runs automatically when a pull request targeting `main` is opened, updated or reopened, if its author already has a commit in `main` and it changes a file the relinker-only build uses; full builds never run automatically for pull requests. Every job that runs automatically for pull requests runs only when the pull request changes its files: a `paths` filter on the `pull_request` trigger, or `needs: eligibility` with an `if` on the files output it sets in `build.yml`. The Conventions check fails a workflow change that adds a job without one. All build jobs build the selected pull request merged into the current `main` (GitHub's merge commit), so a pull request that no longer merges cleanly must be rebased first. New commits require another manual run for full builds.
With `--field full=false`, the manual run skips the full builds and runs only the relinker matrix on Linux, Windows and macOS, if the pull request changes a file the relinker-only build uses, such as the Python tools and their tests in `tools/`.
With `--field linux=false`, the manual run skips the full Linux build and adds Linux to the relinker matrix, if the pull requests change a file the relinker-only build uses. With `--field select=true`, the full builds build and run only the tests whose build inputs the pull requests change; push builds of `main` always run every test.
The Conventions check runs automatically for every contributor, including first-time contributors. It uses the checker from the current tip of the base branch, so rules added after a pull request was opened apply to its next run, and reads pull request Git objects without executing pull request code. The Conventions check runs on every pull request and fails when a rule on this page is broken. It accepts code comments only when the pull request also changes [technical debt](docs/dev/TechnicalDebt.md), the index or a file in `docs/dev/debt/`, and only UTF-8 text files. Run it locally before pushing:
```
python3 tools/check_conventions.py --base origin/main
```
## Branches and pull requests
The [pull request template](.github/pull_request_template.md) is the checklist for these rules.
- One branch per topic, based on current `main`. Follow-up work goes in a new pull request, not into an open one.
- Open pull requests per author are limited by how many of theirs are merged into `main`: 1 with none merged, 20 with at least 1, no limit from 20. A pull request opened or reopened over the limit is closed automatically; reopen it once another one is merged or closed.
- Before starting, check that no open pull request already implements the same functions.
- Keep the branch up to date with `main` and resolve conflicts yourself; rebasing and force-pushing is fine.
- A pull request that conflicts with `main` and has no activity for 7 days is labeled `stale` with a reminder. It is not closed.
- If a pull request needs another one first, say so on the checklist line (`Depends on: #N`; `none` otherwise).
- If a pull request fixes a reported issue, write `Fixes #N` on its checklist line (`none` otherwise). GitHub closes the issue on merge, and the `fix error` label is added within the hour.
- If a pull request fixes a stop or a wrong result seen on a title, name it on the checklist line with the title ID and its [Game bring-up](https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up) discussion (`Unblocks: PPSA01325 #3232`; `none` otherwise). Reviewers review these first. Such a pull request gets the `unblocks title` label.
- For GPU changes, list each tested GPU's vendor, model, driver and OS on the checklist line. CI runs GPU tests only on lavapipe, so reviewers may ask for a run on another vendor before merging.
- Fixes a title needs go to `main` as pull requests. A Game bring-up discussion lists the open pull requests and local changes the title still needs; update the list when one is merged, closed or replaced.
- The PR overlap comment lists open pull requests that change the same lines or exports; agree with their authors which one goes first and declare it with `Depends on`.
- Run the tests before opening the pull request and describe what was tested (OS, title or homebrew).
- A pull request that claims a change in speed shows the summary lines of `main` and of the change, from the same machine and scene, and attaches the traces, captured as the [Performance report](.github/ISSUE_TEMPLATE/performance.yml) issue form describes. A slow scene is reported with the same form. A pull request titled `perf(...)` or `perf:` is labeled `perf`, and `perf numbers missing` until its description holds two valid summary lines with different commits.
- Changes to the AGC driver, the shader recompiler or VideoOut run the same focused tests on `main` and the change with `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation`, `ANYPS5_NO_SHADER_CACHE=1` and `ANYPS5_REQUIRE_VULKAN=1` using `ctest -V` from the same machine and GPU, confirm neither log reports `was not found but was requested by env var VK_INSTANCE_LAYERS`, confirm the change introduces no new `VUID-` validation errors compared with `main`, and name each GPU the GPU tests ran on (vendor, model, driver, OS) on the `GPUs tested` checklist line. CI runs these tests only on lavapipe, and hardware drivers fail where lavapipe and other vendors pass, so a reviewer can ask for a run on another vendor before merging.
- Investigation notes, reports, screenshots and logs go in the pull request, not in the repository. Images for documentation go in the [gist](https://gist.github.com/boykopovar/0e53f2e1426f29ecd41e3b51540b8a90) comments.
- Say whether the change was written with AI assistance. The author of the pull request is responsible for every line of it.
## Documentation
Text in the repository is dry, strict and concise. Record known gaps, unknown NIDs and signatures in [technical debt](docs/dev/TechnicalDebt.md) instead of new files. An entry states the gap first (what differs from the console, what is unverified, what throws) and describes the implemented behaviour only as far as the gap needs it. A pull request that closes a gap removes its entry, or cuts it to what is still open, instead of rewriting it to describe the corrected behaviour. An entry goes in `docs/dev/debt/<name>.md`, named after the first `core/` path it links (`<name>` for `core/libs/prx/<name>/...`, otherwise for `core/<name>/...`), under the same `###` sections as the index; entries that link neither stay in the index. A pull request whose `TechnicalDebt.md` change conflicts after the split rebases and runs `python3 tools/debt_split.py resolve` during the stopped rebase, which moves its added, edited and removed entries to their files; `python3 tools/debt_split.py split` moves entries left in the index.
-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
+198 -24
View File
@@ -1,47 +1,221 @@
**English** | [Português (Brasil)](docs/user/README.pt-BR.md) | [Español](docs/user/README.es.md) | [简体中文](docs/user/README.zh-CN.md) | [Русский](docs/user/README.ru.md)
# Repo Forker
# About
> 📖 **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.
Tool for automatic executables porting to Linux and Windows.
> 🖥️ **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.
The relinker-only build runs on macOS, including Apple silicon.
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).
[**Web converter**](https://boykopovar.github.io/AnyPS5/) - files stay on your device.
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.
![anyps5_collage1](https://github.com/user-attachments/assets/ed2f0b2d-33d3-46d7-ab88-767ca872fc99)
```
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
```
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.
## How it works
[**Discord**](https://discord.gg/BHFztBPUe), [Usage](docs/user/USAGE.md), [Build instructions](docs/dev/BUILD.md), [Architecture](docs/dev/ARCHITECTURE.md), [Technical debt of the project](docs/dev/TechnicalDebt.md), [code style conventions](docs/dev/CONVENTIONS.md), [contributing](CONTRIBUTING.md)
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`).
## Status
## Quick start (3 steps)
[![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)
### 1. Fork this template
In the Gitea UI: **this repo → Fork** → name it after the upstream
(e.g. `Lago/some-upstream`).
[![progress map](https://boykopovar.github.io/AnyPS5/progress.svg)](https://boykopovar.github.io/AnyPS5/progress.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).
[Progress history](https://boykopovar.github.io/AnyPS5/history.html)
Everything non-secret (which branches, how often, build command, artifacts) lives
in **`.forker.yaml`** — edit it in the UI on the `forker` branch.
<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>
> 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.)
Unsupported or unexpected states strictly throw `std::runtime_error`. `what()` is printed to stderr and the process terminates.
### 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:
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`).
- **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.
## Compatibility
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.
Per-game status and test reports live in the [Game bring-up](https://github.com/boykopovar/AnyPS5/discussions/categories/game-bring-up) discussions, one thread per title.
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.
## Input mapping
## Configuration (`.forker.yaml`)
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.
| 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 |
## Disclaimer
## Manual triggers
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.
- **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*.
AnyPS5 is an independent project and is not affiliated with, authorized or endorsed by Sony Interactive Entertainment. "PlayStation" and "PS5" are trademarks of Sony Interactive Entertainment Inc.
Or from a machine that has the repo + env vars: `make sync`,
`make release TAG=v1.2.3`.
## License
## Runner
This project is licensed under the GNU General Public License version 2 only.
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.
-44
View File
@@ -1,44 +0,0 @@
enable_language(C)
set(JXR_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/jxrlib)
function(configure_jxr_native target)
target_include_directories(${target} SYSTEM PRIVATE
${JXR_SOURCE_DIR}/common/include ${JXR_SOURCE_DIR}/image/sys ${JXR_SOURCE_DIR}/jxrgluelib)
target_compile_definitions(${target} PRIVATE DISABLE_PERF_MEASUREMENT)
if(WIN32)
target_compile_definitions(${target} PRIVATE WIN32 __in=)
target_compile_options(${target} PRIVATE -include ${JXR_SOURCE_DIR}/image/sys/strcodec.h)
else()
target_compile_definitions(${target} PRIVATE __ANSI__)
target_compile_options(${target} PRIVATE -include ${CMAKE_SOURCE_DIR}/cmake/JxrCompat.h)
endif()
set_target_properties(${target} PROPERTIES C_STANDARD 99 C_STANDARD_REQUIRED ON
POSITION_INDEPENDENT_CODE ON C_VISIBILITY_PRESET hidden)
endfunction()
add_library(jxr STATIC EXCLUDE_FROM_ALL
${JXR_SOURCE_DIR}/image/sys/adapthuff.c
${JXR_SOURCE_DIR}/image/sys/image.c
${JXR_SOURCE_DIR}/image/sys/strcodec.c
${JXR_SOURCE_DIR}/image/sys/strPredQuant.c
${JXR_SOURCE_DIR}/image/sys/strTransform.c
${JXR_SOURCE_DIR}/image/decode/decode.c
${JXR_SOURCE_DIR}/image/decode/JXRTranscode.c
${JXR_SOURCE_DIR}/image/decode/postprocess.c
${JXR_SOURCE_DIR}/image/decode/segdec.c
${JXR_SOURCE_DIR}/image/decode/strdec.c
${JXR_SOURCE_DIR}/image/decode/strInvTransform.c
${JXR_SOURCE_DIR}/image/decode/strPredQuantDec.c
${JXR_SOURCE_DIR}/image/encode/encode.c
${JXR_SOURCE_DIR}/image/encode/segenc.c
${JXR_SOURCE_DIR}/image/encode/strenc.c
${JXR_SOURCE_DIR}/image/encode/strFwdTransform.c
${JXR_SOURCE_DIR}/image/encode/strPredQuantEnc.c
${JXR_SOURCE_DIR}/jxrgluelib/JXRGlue.c
${JXR_SOURCE_DIR}/jxrgluelib/JXRGlueJxr.c
${JXR_SOURCE_DIR}/jxrgluelib/JXRGluePFC.c
${JXR_SOURCE_DIR}/jxrgluelib/JXRMeta.c)
configure_jxr_native(jxr)
if(UNIX)
target_link_libraries(jxr PRIVATE m)
endif()
-8
View File
@@ -1,8 +0,0 @@
#pragma once
#include <wchar.h>
#include "strcodec.h"
#if defined(__ANSI__) && !defined(WIN32) && !defined(_BIG__ENDIAN_)
U32 _byteswap_ulong(U32 bits);
#endif
-26
View File
@@ -1,26 +0,0 @@
function(add_bundled_opus)
set(BUILD_SHARED_LIBS OFF)
set(BUILD_TESTING OFF)
set(OPUS_BUILD_SHARED_LIBRARY OFF)
set(OPUS_BUILD_TESTING OFF)
set(OPUS_BUILD_PROGRAMS OFF)
set(OPUS_INSTALL_PKG_CONFIG_MODULE OFF)
set(OPUS_INSTALL_CMAKE_CONFIG_MODULE OFF)
set(OPUS_STACK_PROTECTOR OFF)
set(OPUS_FORTIFY_SOURCE OFF)
add_subdirectory(3rdparty/opus EXCLUDE_FROM_ALL)
set_target_properties(opus PROPERTIES POSITION_INDEPENDENT_CODE ON C_VISIBILITY_PRESET hidden)
target_compile_definitions(opus PRIVATE OPUS_EXPORT=)
if(MINGW AND CMAKE_C_COMPILER_ID STREQUAL "GNU")
include(CheckCCompilerFlag)
check_c_compiler_flag("-Wa,-muse-unaligned-vector-move" ANYPS5_ASM_UNALIGNED_VECTOR_MOVE)
if(ANYPS5_ASM_UNALIGNED_VECTOR_MOVE)
target_compile_options(opus PRIVATE -Wa,-muse-unaligned-vector-move)
endif()
endif()
if(MINGW OR CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(opus INTERFACE LINKER:--exclude-libs,libopus.a)
endif()
endfunction()
add_bundled_opus()
-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 2.15 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;
}
-31
View File
@@ -1,31 +0,0 @@
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <process.h>
#include <windows.h>
extern "C" int __real_main(int argc, char** argv);
namespace {
template<typename TFunction>
TFunction LibcFunction(const char* name) {
const HMODULE libc = GetModuleHandleW(L"libc.prx");
if (libc == nullptr) return nullptr;
return reinterpret_cast<TFunction>(reinterpret_cast<void*>(GetProcAddress(libc, name)));
}
}
extern "C" int __wrap_main(int argc, char** argv) {
const int code = __real_main(argc, argv);
const auto terminate = LibcFunction<void (*)(int)>("LibcTerminate_nid_no_patch");
if (terminate == nullptr) return code;
_cexit();
std::cout.flush();
std::clog.flush();
std::cerr.flush();
std::fflush(nullptr);
terminate(code);
return code;
}
-25
View File
@@ -1,25 +0,0 @@
enable_language(C)
set(ZSTD_BUILD_PROGRAMS OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_CONTRIB OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_SHARED OFF CACHE BOOL "" FORCE)
set(ZSTD_BUILD_STATIC ON CACHE BOOL "" FORCE)
set(ZSTD_LEGACY_SUPPORT OFF CACHE BOOL "" FORCE)
set(ZSTD_MULTITHREAD_SUPPORT OFF CACHE BOOL "" FORCE)
add_subdirectory(${CMAKE_SOURCE_DIR}/3rdparty/zstd/build/cmake ${CMAKE_BINARY_DIR}/3rdparty/zstd EXCLUDE_FROM_ALL)
set_target_properties(libzstd_static PROPERTIES POSITION_INDEPENDENT_CODE ON)
set(ZARCHIVE_SOURCE_DIR ${CMAKE_SOURCE_DIR}/3rdparty/ZArchive)
add_library(zarchive STATIC EXCLUDE_FROM_ALL
${ZARCHIVE_SOURCE_DIR}/src/zarchivereader.cpp
${ZARCHIVE_SOURCE_DIR}/src/zarchivewriter.cpp
${ZARCHIVE_SOURCE_DIR}/src/sha_256.c
)
target_include_directories(zarchive SYSTEM PUBLIC ${ZARCHIVE_SOURCE_DIR}/include)
target_compile_features(zarchive PUBLIC cxx_std_20)
target_link_libraries(zarchive PRIVATE libzstd_static)
set_target_properties(zarchive PROPERTIES POSITION_INDEPENDENT_CODE ON)
if(CMAKE_SYSTEM_NAME STREQUAL "Linux")
target_link_options(zarchive INTERFACE LINKER:--exclude-libs,libzarchive.a:libzstd.a)
endif()
-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,48 +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;
std::uint8_t componentIds[4]{};
std::uint8_t samplingFactors[4]{};
bool progressive = false;
bool app0BeforeFrame = false;
};
enum class Sampling {
Yuv444,
Yuv422,
Yuv420,
};
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
std::uint32_t channels, int quality, Sampling sampling = Sampling::Yuv444,
std::uint32_t restartBlocks = 0, std::uint32_t restartRows = 0);
std::optional<Header> ParseHeader(std::span<const std::uint8_t> jpeg);
std::optional<Image> Decode(std::span<const std::uint8_t> jpeg);
std::uint32_t ScaledDimension(std::uint32_t dimension, std::uint32_t denominator);
std::optional<Image> DecodeScaled(std::span<const std::uint8_t> jpeg, std::uint32_t denominator);
} // namespace Decoder::Jpeg
#endif // DECODER_JPEG_HPP
-173
View File
@@ -1,173 +0,0 @@
#include "Decoder/Jpeg.hpp"
#include <climits>
#include <cstddef>
#include <memory>
#include <stdexcept>
#define STB_IMAGE_STATIC
#define STB_IMAGE_IMPLEMENTATION
#define STBI_ONLY_JPEG
#define STBI_NO_STDIO
#include "stb_image.h"
#include "turbojpeg.h"
namespace Decoder::Jpeg {
namespace {
constexpr std::uint32_t MAX_DIMENSION = 0xFFFF;
class Handle {
public:
explicit Handle(int type) : handle(tj3Init(type)) {
if (!handle) throw std::runtime_error(type == TJINIT_COMPRESS ? "Jpeg::Encode: encoder initialization failed" : "Jpeg::DecodeScaled: decoder initialization failed");
}
~Handle() { tj3Destroy(handle); }
Handle(const Handle&) = delete;
Handle& operator=(const Handle&) = delete;
operator tjhandle() const { return handle; }
private:
tjhandle handle;
};
class Buffer {
public:
~Buffer() { tj3Free(data); }
unsigned char* data = nullptr;
};
int toSubsampling(Sampling sampling) {
switch (sampling) {
case Sampling::Yuv444: return TJSAMP_444;
case Sampling::Yuv422: return TJSAMP_422;
case Sampling::Yuv420: return TJSAMP_420;
}
throw std::invalid_argument("Jpeg::Encode: invalid sampling");
}
} // namespace
std::vector<std::uint8_t> Encode(std::span<const std::uint8_t> pixels, std::uint32_t width, std::uint32_t height,
std::uint32_t channels, int quality, Sampling sampling, std::uint32_t restartBlocks,
std::uint32_t restartRows) {
if (width == 0 || height == 0 || width > MAX_DIMENSION || height > MAX_DIMENSION) {
throw std::invalid_argument("Jpeg::Encode: unsupported image size");
}
if (channels != 1 && channels != 3) throw std::invalid_argument("Jpeg::Encode: channels must be 1 or 3");
if (quality < 1 || quality > 100) throw std::invalid_argument("Jpeg::Encode: quality must be 1-100");
if (pixels.size() < static_cast<std::size_t>(width) * height * channels) {
throw std::invalid_argument("Jpeg::Encode: pixel buffer is too small");
}
if (restartBlocks > MAX_DIMENSION || restartRows > MAX_DIMENSION || (restartBlocks != 0 && restartRows != 0)) {
throw std::invalid_argument("Jpeg::Encode: invalid restart interval");
}
const int subsampling = toSubsampling(sampling);
Handle handle(TJINIT_COMPRESS);
if (tj3Set(handle, TJPARAM_QUALITY, quality) < 0 || tj3Set(handle, TJPARAM_SUBSAMP, channels == 1 ? TJSAMP_GRAY : subsampling) < 0) {
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
}
if ((restartBlocks != 0 && tj3Set(handle, TJPARAM_RESTARTBLOCKS, static_cast<int>(restartBlocks)) < 0) ||
(restartRows != 0 && tj3Set(handle, TJPARAM_RESTARTROWS, static_cast<int>(restartRows)) < 0)) {
throw std::runtime_error("Jpeg::Encode: encoder configuration failed");
}
Buffer buffer;
std::size_t size = 0;
const int pixelFormat = channels == 1 ? TJPF_GRAY : TJPF_RGB;
if (tj3Compress8(handle, pixels.data(), static_cast<int>(width), 0, static_cast<int>(height), pixelFormat, &buffer.data, &size) < 0) {
throw std::runtime_error("Jpeg::Encode: encoding failed");
}
return {buffer.data, buffer.data + size};
}
std::uint32_t ScaledDimension(std::uint32_t dimension, std::uint32_t denominator) {
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) {
throw std::invalid_argument("Jpeg::ScaledDimension: the scale must be 1/1, 1/2, 1/4 or 1/8");
}
const tjscalingfactor factor{1, static_cast<int>(denominator)};
return static_cast<std::uint32_t>(TJSCALED(static_cast<std::uint64_t>(dimension), factor));
}
std::optional<Image> DecodeScaled(std::span<const std::uint8_t> jpeg, std::uint32_t denominator) {
if (denominator != 1 && denominator != 2 && denominator != 4 && denominator != 8) {
throw std::invalid_argument("Jpeg::DecodeScaled: the scale must be 1/1, 1/2, 1/4 or 1/8");
}
if (jpeg.empty() || jpeg.size() > INT_MAX) return std::nullopt;
Handle handle(TJINIT_DECOMPRESS);
if (tj3Set(handle, TJPARAM_STOPONWARNING, 1) < 0) throw std::runtime_error("Jpeg::DecodeScaled: decoder configuration failed");
if (tj3DecompressHeader(handle, jpeg.data(), jpeg.size()) < 0) return std::nullopt;
const int colorspace = tj3Get(handle, TJPARAM_COLORSPACE);
if (colorspace == TJCS_CMYK || colorspace == TJCS_YCCK) {
throw std::runtime_error("Jpeg::DecodeScaled: scaled decoding of a CMYK or YCCK image is not implemented");
}
const int width = tj3Get(handle, TJPARAM_JPEGWIDTH);
const int height = tj3Get(handle, TJPARAM_JPEGHEIGHT);
if (width <= 0 || height <= 0) return std::nullopt;
if (tj3SetScalingFactor(handle, tjscalingfactor{1, static_cast<int>(denominator)}) < 0) {
throw std::runtime_error("Jpeg::DecodeScaled: the decoder refused the scaling factor");
}
const std::uint32_t channels = colorspace == TJCS_GRAY ? 1 : 3;
Image image{ScaledDimension(static_cast<std::uint32_t>(width), denominator), ScaledDimension(static_cast<std::uint32_t>(height), denominator), channels, {}};
image.pixels.resize(static_cast<std::size_t>(image.width) * image.height * channels);
if (tj3Decompress8(handle, jpeg.data(), jpeg.size(), image.pixels.data(), 0, channels == 1 ? TJPF_GRAY : TJPF_RGB) < 0) {
return std::nullopt;
}
return image;
}
std::optional<Header> ParseHeader(std::span<const std::uint8_t> jpeg) {
if (jpeg.empty() || jpeg.size() > INT_MAX) return std::nullopt;
int width = 0;
int height = 0;
int channels = 0;
if (!stbi_info_from_memory(jpeg.data(), static_cast<int>(jpeg.size()), &width, &height, &channels)) return std::nullopt;
if (width <= 0 || height <= 0 || channels <= 0) return std::nullopt;
Header header{static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height), static_cast<std::uint32_t>(channels)};
std::size_t offset = 2;
while (offset < jpeg.size()) {
if (jpeg[offset++] != 0xFF) return std::nullopt;
while (offset < jpeg.size() && jpeg[offset] == 0xFF) ++offset;
if (offset == jpeg.size()) return std::nullopt;
const std::uint8_t marker = jpeg[offset++];
if (marker == 0xD9 || marker == 0xDA) return std::nullopt;
if (marker == 0x01 || (marker >= 0xD0 && marker <= 0xD8)) continue;
if (jpeg.size() - offset < 2) return std::nullopt;
const std::size_t length = (static_cast<std::size_t>(jpeg[offset]) << 8) | jpeg[offset + 1];
if (length < 2 || length > jpeg.size() - offset) return std::nullopt;
if (marker == 0xE0) header.app0BeforeFrame = true;
if (marker == 0xC0 || marker == 0xC1 || marker == 0xC2) {
if (length < 8) return std::nullopt;
header.channels = jpeg[offset + 7];
if (header.channels == 0 || header.channels > 4 || length != 8 + 3 * header.channels) return std::nullopt;
header.progressive = marker == 0xC2;
for (std::uint32_t i = 0; i < header.channels; ++i) {
header.componentIds[i] = jpeg[offset + 8 + 3 * i];
header.samplingFactors[i] = jpeg[offset + 9 + 3 * i];
}
return header;
}
offset += length;
}
return std::nullopt;
}
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;
const std::unique_ptr<stbi_uc, decltype(&stbi_image_free)> decoded(
stbi_load_from_memory(jpeg.data(), static_cast<int>(jpeg.size()), &width, &height, &channels, 0), stbi_image_free);
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.get(), decoded.get() + static_cast<std::size_t>(image.width) * image.height * image.channels);
return image;
}
} // namespace Decoder::Jpeg
-180
View File
@@ -1,180 +0,0 @@
#include "Decoder/Jpeg.hpp"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <stdexcept>
#include <utility>
#include <vector>
static void Require(bool value) { if (!value) std::abort(); }
template<typename TFunction>
static bool ThrowsInvalidArgument(TFunction function) {
try {
function();
} catch (const std::invalid_argument&) {
return true;
}
return false;
}
static bool IsJpeg(const std::vector<std::uint8_t>& data) {
return data.size() > 4 && data[0] == 0xFF && data[1] == 0xD8 && data[data.size() - 2] == 0xFF && data.back() == 0xD9;
}
static int Difference(std::uint8_t left, std::uint8_t right) {
return left > right ? left - right : right - left;
}
struct FrameInfo { int components; std::uint8_t sampling; };
static FrameInfo ReadFrame(const std::vector<std::uint8_t>& jpeg) {
std::size_t offset = 2;
while (offset + 3 < jpeg.size()) {
Require(jpeg[offset++] == 0xFF);
while (offset < jpeg.size() && jpeg[offset] == 0xFF) ++offset;
Require(offset < jpeg.size());
const std::uint8_t marker = jpeg[offset++];
if (marker == 0xDA || marker == 0xD9) break;
Require(offset + 1 < jpeg.size());
const std::size_t length = (static_cast<std::size_t>(jpeg[offset]) << 8) | jpeg[offset + 1];
Require(length >= 2 && offset + length <= jpeg.size());
if (marker >= 0xC0 && marker <= 0xC3) return {jpeg[offset + 7], jpeg[offset + 9]};
offset += length;
}
std::abort();
}
int main() {
constexpr std::uint32_t width = 32;
constexpr std::uint32_t height = 24;
std::vector<std::uint8_t> rgb(width * height * 3);
for (std::uint32_t y = 0; y < height; ++y) {
for (std::uint32_t x = 0; x < width; ++x) {
std::uint8_t* pixel = &rgb[(y * width + x) * 3];
pixel[0] = static_cast<std::uint8_t>(x * 8);
pixel[1] = static_cast<std::uint8_t>(y * 10);
pixel[2] = 128;
}
}
const std::vector<std::uint8_t> rgbJpeg = Decoder::Jpeg::Encode(rgb, width, height, 3, 90);
Require(IsJpeg(rgbJpeg));
Require(ReadFrame(rgbJpeg).components == 3 && ReadFrame(rgbJpeg).sampling == 0x11);
const auto rgbImage = Decoder::Jpeg::Decode(rgbJpeg);
Require(rgbImage.has_value());
Require(rgbImage->width == width && rgbImage->height == height && rgbImage->channels == 3);
Require(rgbImage->pixels.size() == rgb.size());
long totalError = 0;
for (std::size_t i = 0; i < rgb.size(); ++i) totalError += Difference(rgb[i], rgbImage->pixels[i]);
Require(totalError / static_cast<long>(rgb.size()) < 4);
std::vector<std::uint8_t> gray(width * height);
for (std::uint32_t y = 0; y < height; ++y) {
for (std::uint32_t x = 0; x < width; ++x) gray[y * width + x] = static_cast<std::uint8_t>((x + y) * 4);
}
const std::vector<std::uint8_t> grayJpeg = Decoder::Jpeg::Encode(gray, width, height, 1, 90);
Require(IsJpeg(grayJpeg));
Require(ReadFrame(grayJpeg).components == 1);
const auto grayImage = Decoder::Jpeg::Decode(grayJpeg);
Require(grayImage.has_value());
Require(grayImage->width == width && grayImage->height == height);
totalError = 0;
for (std::size_t i = 0; i < gray.size(); ++i) totalError += Difference(gray[i], grayImage->pixels[i * grayImage->channels]);
Require(totalError / static_cast<long>(gray.size()) < 4);
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 4, 90); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 0); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 101); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0, height, 3, 90); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, 0x10000, 1, 3, 90); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height + 1, 3, 90); }));
for (const auto [sampling, factor] : {std::pair{Decoder::Jpeg::Sampling::Yuv444, std::uint8_t{0x11}},
std::pair{Decoder::Jpeg::Sampling::Yuv422, std::uint8_t{0x21}},
std::pair{Decoder::Jpeg::Sampling::Yuv420, std::uint8_t{0x22}}}) {
const auto encoded = Decoder::Jpeg::Encode(rgb, 31, 23, 3, 1, sampling);
Require(ReadFrame(encoded).components == 3 && ReadFrame(encoded).sampling == factor);
const auto highQuality = Decoder::Jpeg::Encode(rgb, 31, 23, 3, 100, sampling);
Require(ReadFrame(highQuality).components == 3 && ReadFrame(highQuality).sampling == factor);
}
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, static_cast<Decoder::Jpeg::Sampling>(3)); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, Decoder::Jpeg::Sampling::Yuv444, 1, 1); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, Decoder::Jpeg::Sampling::Yuv444, 0x10000, 0); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::Encode(rgb, width, height, 3, 90, Decoder::Jpeg::Sampling::Yuv444, 0, 0x10000); }));
Require(!Decoder::Jpeg::Decode({}).has_value());
const std::vector<std::uint8_t> garbage{1, 2, 3, 4, 5, 6, 7, 8};
Require(!Decoder::Jpeg::Decode(garbage).has_value());
Require(Decoder::Jpeg::ScaledDimension(7, 1) == 7 && Decoder::Jpeg::ScaledDimension(7, 2) == 4);
Require(Decoder::Jpeg::ScaledDimension(7, 4) == 2 && Decoder::Jpeg::ScaledDimension(7, 8) == 1);
Require(Decoder::Jpeg::ScaledDimension(32, 8) == 4 && Decoder::Jpeg::ScaledDimension(33, 8) == 5 && Decoder::Jpeg::ScaledDimension(1, 8) == 1);
Require(Decoder::Jpeg::ScaledDimension(0xFFFF, 2) == 0x8000);
for (const std::uint32_t denominator : {0u, 3u, 16u}) {
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::ScaledDimension(7, denominator); }));
Require(ThrowsInvalidArgument([&] { Decoder::Jpeg::DecodeScaled(rgbJpeg, denominator); }));
}
const auto boxError = [](const std::vector<std::uint8_t>& source, std::uint32_t sourceWidth, std::uint32_t sourceHeight,
std::uint32_t channels, const Decoder::Jpeg::Image& scaled, std::uint32_t denominator) {
long error = 0;
for (std::uint32_t y = 0; y < scaled.height; ++y) {
for (std::uint32_t x = 0; x < scaled.width; ++x) {
for (std::uint32_t c = 0; c < channels; ++c) {
long sum = 0;
long count = 0;
for (std::uint32_t sy = y * denominator; sy < std::min(sourceHeight, (y + 1) * denominator); ++sy) {
for (std::uint32_t sx = x * denominator; sx < std::min(sourceWidth, (x + 1) * denominator); ++sx) {
sum += source[(static_cast<std::size_t>(sy) * sourceWidth + sx) * channels + c];
++count;
}
}
const auto average = static_cast<std::uint8_t>((sum + count / 2) / count);
error += Difference(average, scaled.pixels[(static_cast<std::size_t>(y) * scaled.width + x) * channels + c]);
}
}
}
return error / static_cast<long>(static_cast<std::size_t>(scaled.width) * scaled.height * channels);
};
for (const std::uint32_t denominator : {1u, 2u, 4u, 8u}) {
const auto scaled = Decoder::Jpeg::DecodeScaled(rgbJpeg, denominator);
Require(scaled.has_value() && scaled->channels == 3);
Require(scaled->width == width / denominator && scaled->height == height / denominator);
Require(scaled->pixels.size() == static_cast<std::size_t>(scaled->width) * scaled->height * 3);
Require(boxError(rgb, width, height, 3, *scaled, denominator) < 4);
const auto grayScaled = Decoder::Jpeg::DecodeScaled(grayJpeg, denominator);
Require(grayScaled.has_value() && grayScaled->channels == 1);
Require(grayScaled->width == width / denominator && grayScaled->height == height / denominator);
Require(boxError(gray, width, height, 1, *grayScaled, denominator) < 4);
}
std::vector<std::uint8_t> odd(31 * 23 * 3);
for (std::uint32_t y = 0; y < 23; ++y) {
for (std::uint32_t x = 0; x < 31; ++x) {
std::uint8_t* pixel = &odd[(y * 31 + x) * 3];
pixel[0] = static_cast<std::uint8_t>(x * 8);
pixel[1] = static_cast<std::uint8_t>(y * 11);
pixel[2] = static_cast<std::uint8_t>(200 - x * 2);
}
}
const auto oddJpeg = Decoder::Jpeg::Encode(odd, 31, 23, 3, 95, Decoder::Jpeg::Sampling::Yuv420);
for (const std::uint32_t denominator : {2u, 4u, 8u}) {
const auto scaled = Decoder::Jpeg::DecodeScaled(oddJpeg, denominator);
Require(scaled.has_value() && scaled->channels == 3);
Require(scaled->width == Decoder::Jpeg::ScaledDimension(31, denominator) && scaled->height == Decoder::Jpeg::ScaledDimension(23, denominator));
Require(boxError(odd, 31, 23, 3, *scaled, denominator) < 8);
}
Require(!Decoder::Jpeg::DecodeScaled({}, 2).has_value());
Require(!Decoder::Jpeg::DecodeScaled(garbage, 2).has_value());
const std::vector<std::uint8_t> truncated(rgbJpeg.begin(), rgbJpeg.begin() + static_cast<std::ptrdiff_t>(rgbJpeg.size() / 2));
Require(!Decoder::Jpeg::DecodeScaled(truncated, 2).has_value());
return 0;
}
-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
-247
View File
@@ -1,247 +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);
}
std::optional<std::uint16_t> readGrayscaleTransparencyKey(std::span<const std::uint8_t> png) {
std::size_t offset = SIGNATURE.size();
if (png.size() < offset || !std::equal(SIGNATURE.begin(), SIGNATURE.end(), png.begin())) return std::nullopt;
std::optional<std::uint16_t> key;
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) return std::nullopt;
if (isChunkType(type, "tRNS")) {
if (length != 2) return std::nullopt;
key = static_cast<std::uint16_t>(png[offset + 8] << 8 | png[offset + 9]);
}
if (isChunkType(type, "IDAT") || isChunkType(type, "IEND")) return key;
offset += CHUNK_OVERHEAD + length;
}
return std::nullopt;
}
void repairGrayscaleTransparency(const Header& header, std::span<const std::uint8_t> png, Image& image) {
if (header.colorType != ColorType::Grayscale || !header.hasTransparency) return;
if (header.bitDepth != 1 && header.bitDepth != 2 && header.bitDepth != 4) return;
const std::optional<std::uint16_t> key = readGrayscaleTransparencyKey(png);
if (!key.has_value()) return;
const std::uint16_t mask = static_cast<std::uint16_t>((1u << header.bitDepth) - 1);
if ((*key & 0xFF) == (*key & mask)) return;
const std::uint8_t transparent = static_cast<std::uint8_t>((*key & mask) * (255u / mask));
for (std::size_t offset = 3; offset < image.pixels.size(); offset += 4) {
image.pixels[offset] = static_cast<std::uint8_t>(image.pixels[offset - 3] == transparent ? 0 : 255);
}
}
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;
const std::unique_ptr<stbi_uc, decltype(&stbi_image_free)> decoded(
stbi_load_from_memory(png.data(), static_cast<int>(png.size()), &width, &height, &channels, 4), stbi_image_free);
if (!decoded) return std::nullopt;
Image image{static_cast<std::uint32_t>(width), static_cast<std::uint32_t>(height), {}};
image.pixels.assign(decoded.get(), decoded.get() + static_cast<std::size_t>(image.width) * image.height * 4);
const std::optional<Header> header = ParseHeader(png);
if (header.has_value()) repairGrayscaleTransparency(*header, png, image);
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
-396
View File
@@ -1,396 +0,0 @@
#include "Decoder/Png.hpp"
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <optional>
#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 const std::uint8_t GRAY1_TRNS[] = {
0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52,
0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0xDC, 0x59, 0x42,
0x27, 0x00, 0x00, 0x00, 0x02, 0x74, 0x52, 0x4E, 0x53, 0x00, 0x02, 0x98, 0x9D, 0xAC, 0x14, 0x00,
0x00, 0x00, 0x0A, 0x49, 0x44, 0x41, 0x54, 0x78, 0xDA, 0x63, 0x70, 0x00, 0x00, 0x00, 0x42, 0x00,
0x41, 0x84, 0xBF, 0x8E, 0x62, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60,
0x82,
};
static const std::uint8_t PNG_SIGNATURE[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};
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 std::uint32_t Crc32(std::span<const std::uint8_t> bytes) {
std::uint32_t crc = 0xFFFFFFFFu;
for (const std::uint8_t byte : bytes) {
crc ^= byte;
for (int bit = 0; bit < 8; ++bit) crc = (crc >> 1) ^ ((crc & 1) != 0 ? 0xEDB88320u : 0u);
}
return ~crc;
}
static std::uint32_t Adler32(std::span<const std::uint8_t> bytes) {
std::uint32_t low = 1;
std::uint32_t high = 0;
for (const std::uint8_t byte : bytes) {
low = (low + byte) % 65521;
high = (high + low) % 65521;
}
return high << 16 | low;
}
static void AppendTestChunk(std::vector<std::uint8_t>& png, const char* type, std::span<const std::uint8_t> data) {
AppendBigEndian32(png, static_cast<std::uint32_t>(data.size()));
const std::size_t start = png.size();
png.insert(png.end(), type, type + 4);
png.insert(png.end(), data.begin(), data.end());
AppendBigEndian32(png, Crc32(std::span<const std::uint8_t>(png.data() + start, png.size() - start)));
}
static std::vector<std::uint8_t> ZlibStore(std::span<const std::uint8_t> bytes) {
Require(bytes.size() <= 0xFFFF);
const std::uint16_t length = static_cast<std::uint16_t>(bytes.size());
const std::uint16_t inverse = static_cast<std::uint16_t>(~length);
std::vector<std::uint8_t> output{0x78, 0x01, 0x01, static_cast<std::uint8_t>(length), static_cast<std::uint8_t>(length >> 8),
static_cast<std::uint8_t>(inverse), static_cast<std::uint8_t>(inverse >> 8)};
output.insert(output.end(), bytes.begin(), bytes.end());
AppendBigEndian32(output, Adler32(bytes));
return output;
}
static std::vector<std::uint8_t> GrayLowBitPng(std::uint8_t bitDepth, std::span<const std::uint8_t> samples,
std::optional<std::uint16_t> transparency,
std::optional<std::uint16_t> precedingTransparency = std::nullopt) {
Require(bitDepth == 1 || bitDepth == 2 || bitDepth == 4);
std::vector<std::uint8_t> rows(1 + (samples.size() * bitDepth + 7) / 8, 0);
std::size_t bit = 0;
for (const std::uint8_t sample : samples) {
Require(sample < (1u << bitDepth));
rows[1 + bit / 8] |= static_cast<std::uint8_t>(sample << (8 - bitDepth - bit % 8));
bit += bitDepth;
}
std::vector<std::uint8_t> ihdr;
AppendBigEndian32(ihdr, static_cast<std::uint32_t>(samples.size()));
AppendBigEndian32(ihdr, 1);
ihdr.insert(ihdr.end(), {bitDepth, 0, 0, 0, 0});
std::vector<std::uint8_t> png(PNG_SIGNATURE, PNG_SIGNATURE + sizeof(PNG_SIGNATURE));
AppendTestChunk(png, "IHDR", ihdr);
if (precedingTransparency.has_value()) {
const std::uint8_t key[2] = {static_cast<std::uint8_t>(*precedingTransparency >> 8), static_cast<std::uint8_t>(*precedingTransparency)};
AppendTestChunk(png, "tRNS", key);
}
if (transparency.has_value()) {
const std::uint8_t key[2] = {static_cast<std::uint8_t>(*transparency >> 8), static_cast<std::uint8_t>(*transparency)};
AppendTestChunk(png, "tRNS", key);
}
AppendTestChunk(png, "IDAT", ZlibStore(rows));
AppendTestChunk(png, "IEND", std::span<const std::uint8_t>());
return png;
}
static std::uint8_t GrayScale(std::uint8_t bitDepth) {
if (bitDepth == 1) return 255;
if (bitDepth == 2) return 85;
return 17;
}
static void RequireGrayTransparency(std::uint8_t bitDepth, std::span<const std::uint8_t> samples, std::uint16_t key,
std::uint8_t transparentSample, std::optional<std::uint16_t> precedingKey = std::nullopt) {
const std::vector<std::uint8_t> png = GrayLowBitPng(bitDepth, samples, key, precedingKey);
const std::vector<std::uint8_t> original = png;
const auto header = Decoder::Png::ParseHeader(png);
Require(header.has_value());
Require(header->width == static_cast<std::uint32_t>(samples.size()) && header->height == 1 && header->bitDepth == bitDepth);
Require(header->colorType == Decoder::Png::ColorType::Grayscale && header->hasTransparency);
const auto image = Decoder::Png::Decode(png);
Require(image.has_value() && image->pixels.size() == samples.size() * 4);
const std::uint8_t scale = GrayScale(bitDepth);
for (std::size_t i = 0; i < samples.size(); ++i) {
const std::uint8_t gray = static_cast<std::uint8_t>(samples[i] * scale);
Require(image->pixels[i * 4] == gray && image->pixels[i * 4 + 1] == gray && image->pixels[i * 4 + 2] == gray);
Require(image->pixels[i * 4 + 3] == (samples[i] == transparentSample ? 0 : 255));
}
Require(png == original);
}
static void RequireGrayOpaque(std::uint8_t bitDepth, std::span<const std::uint8_t> samples) {
const std::vector<std::uint8_t> png = GrayLowBitPng(bitDepth, samples, std::nullopt);
const std::vector<std::uint8_t> original = png;
const auto header = Decoder::Png::ParseHeader(png);
Require(header.has_value() && !header->hasTransparency);
const auto image = Decoder::Png::Decode(png);
Require(image.has_value() && image->pixels.size() == samples.size() * 4);
const std::uint8_t scale = GrayScale(bitDepth);
for (std::size_t i = 0; i < samples.size(); ++i) {
const std::uint8_t gray = static_cast<std::uint8_t>(samples[i] * scale);
Require(image->pixels[i * 4] == gray && image->pixels[i * 4 + 1] == gray && image->pixels[i * 4 + 2] == gray);
Require(image->pixels[i * 4 + 3] == 255);
}
Require(png == original);
}
static void RequireTruncatedTransparency() {
const std::uint8_t samples[] = {0, 1};
const std::vector<std::uint8_t> png = GrayLowBitPng(1, samples, 0x0002);
const std::size_t transparencyOffset = sizeof(PNG_SIGNATURE) + 25;
const std::vector<std::uint8_t> truncated(png.begin(), png.begin() + transparencyOffset + 9);
const std::vector<std::uint8_t> original = truncated;
const auto header = Decoder::Png::ParseHeader(truncated);
Require(header.has_value() && !header->hasTransparency);
(void)Decoder::Png::Decode(truncated);
Require(truncated == original);
}
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 gray1TrnsHeader = Decoder::Png::ParseHeader(GRAY1_TRNS);
Require(gray1TrnsHeader.has_value());
Require(gray1TrnsHeader->width == 2 && gray1TrnsHeader->height == 1 && gray1TrnsHeader->bitDepth == 1);
Require(gray1TrnsHeader->colorType == Decoder::Png::ColorType::Grayscale && gray1TrnsHeader->hasTransparency);
const auto gray1Trns = Decoder::Png::Decode(GRAY1_TRNS);
Require(gray1Trns.has_value());
Require(gray1Trns->pixels == std::vector<std::uint8_t>({0, 0, 0, 0, 255, 255, 255, 255}));
const std::uint8_t gray1Samples[] = {0, 1, 0, 1, 1, 0, 0, 1};
RequireGrayTransparency(1, gray1Samples, 0x0000, 0);
RequireGrayTransparency(1, gray1Samples, 0x0002, 0);
RequireGrayTransparency(1, gray1Samples, 0x0100, 0);
RequireGrayTransparency(1, gray1Samples, 0xFF02, 0);
RequireGrayTransparency(1, gray1Samples, 0xFFFF, 1);
RequireGrayTransparency(1, gray1Samples, 0x0001, 1, 0x0002);
RequireGrayOpaque(1, gray1Samples);
const std::uint8_t gray2Samples[] = {0, 1, 2, 3};
RequireGrayTransparency(2, gray2Samples, 0x0001, 1);
RequireGrayTransparency(2, gray2Samples, 0x0005, 1);
RequireGrayTransparency(2, gray2Samples, 0x0100, 0);
RequireGrayTransparency(2, gray2Samples, 0x0101, 1);
RequireGrayTransparency(2, gray2Samples, 0xFF05, 1);
RequireGrayTransparency(2, gray2Samples, 0xFFFF, 3);
RequireGrayOpaque(2, gray2Samples);
const std::uint8_t gray4Samples[] = {0, 3, 10, 15, 1};
RequireGrayTransparency(4, gray4Samples, 0x0003, 3);
RequireGrayTransparency(4, gray4Samples, 0x0013, 3);
RequireGrayTransparency(4, gray4Samples, 0x0100, 0);
RequireGrayTransparency(4, gray4Samples, 0x0103, 3);
RequireGrayTransparency(4, gray4Samples, 0xFF13, 3);
RequireGrayTransparency(4, gray4Samples, 0xFFFF, 15);
RequireGrayOpaque(4, gray4Samples);
RequireTruncatedTransparency();
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;
}
File diff suppressed because it is too large. Load diff
-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
-102
View File
@@ -1,102 +0,0 @@
#include "PeImportFirst.hpp"
#include <algorithm>
#include <array>
#include <cctype>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iterator>
#include <stdexcept>
namespace Allocator {
namespace {
std::uint32_t read32(const std::vector<unsigned char>& bytes, std::size_t offset) {
if (offset + 4 > bytes.size()) throw std::runtime_error("truncated image");
std::uint32_t value = 0;
std::memcpy(&value, bytes.data() + offset, sizeof(value));
return value;
}
std::uint16_t read16(const std::vector<unsigned char>& bytes, std::size_t offset) {
if (offset + 2 > bytes.size()) throw std::runtime_error("truncated image");
std::uint16_t value = 0;
std::memcpy(&value, bytes.data() + offset, sizeof(value));
return value;
}
std::string lower(std::string text) {
std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return text;
}
}
void MoveImportFirst(std::vector<unsigned char>& bytes, const std::string& dll) {
const auto pe = read32(bytes, 0x3c);
if (read32(bytes, pe) != 0x00004550u) throw std::runtime_error("not a PE image");
const auto sections = read16(bytes, pe + 6);
const auto optionalSize = read16(bytes, pe + 20);
const auto optional = pe + 24;
if (read16(bytes, optional) != 0x20bu) throw std::runtime_error("not a PE32+ image");
constexpr std::size_t ImportDirectory = 112 + 8;
if (optionalSize < ImportDirectory + 8 || read32(bytes, optional + 108) < 2) throw std::runtime_error("the image has no imports");
const auto importRva = read32(bytes, optional + ImportDirectory);
if (importRva == 0) throw std::runtime_error("the image has no imports");
const auto sectionTable = optional + optionalSize;
const auto fileOffset = [&](std::uint32_t rva) -> std::size_t {
for (std::uint16_t index = 0; index < sections; ++index) {
const auto header = sectionTable + index * 40u;
const auto virtualSize = read32(bytes, header + 8);
const auto virtualAddress = read32(bytes, header + 12);
const auto rawSize = read32(bytes, header + 16);
const auto rawOffset = read32(bytes, header + 20);
if (rva >= virtualAddress && rva < virtualAddress + std::max(virtualSize, rawSize)) {
if (rva - virtualAddress >= rawSize) throw std::runtime_error("RVA outside the section's file data");
return rawOffset + (rva - virtualAddress);
}
}
throw std::runtime_error("RVA outside every section");
};
const auto directory = fileOffset(importRva);
constexpr std::size_t DescriptorBytes = 20;
std::vector<std::array<unsigned char, DescriptorBytes>> descriptors;
for (std::size_t offset = directory;; offset += DescriptorBytes) {
if (offset + DescriptorBytes > bytes.size()) throw std::runtime_error("truncated import directory");
std::array<unsigned char, DescriptorBytes> descriptor{};
std::memcpy(descriptor.data(), bytes.data() + offset, DescriptorBytes);
if (std::all_of(descriptor.begin(), descriptor.end(), [](unsigned char value) { return value == 0; })) break;
descriptors.push_back(descriptor);
}
std::size_t found = SIZE_MAX;
for (std::size_t index = 0; index < descriptors.size(); ++index) {
std::uint32_t nameRva = 0;
std::memcpy(&nameRva, descriptors[index].data() + 12, sizeof(nameRva));
const auto nameOffset = fileOffset(nameRva);
if (nameOffset >= bytes.size()) throw std::runtime_error("RVA outside the file data");
const auto terminator = std::find(bytes.begin() + static_cast<std::ptrdiff_t>(nameOffset), bytes.end(), 0);
if (terminator == bytes.end()) throw std::runtime_error("unterminated import name");
const std::string name(bytes.begin() + static_cast<std::ptrdiff_t>(nameOffset), terminator);
if (lower(name) == lower(dll)) found = index;
}
if (found == SIZE_MAX) throw std::runtime_error("the image does not import " + dll);
std::rotate(descriptors.begin(), descriptors.begin() + static_cast<std::ptrdiff_t>(found), descriptors.begin() + static_cast<std::ptrdiff_t>(found) + 1);
for (std::size_t index = 0; index < descriptors.size(); ++index) std::memcpy(bytes.data() + directory + index * DescriptorBytes, descriptors[index].data(), DescriptorBytes);
}
void MoveImportFirstInFile(const std::filesystem::path& path, const std::string& dll) {
std::vector<unsigned char> bytes;
{
std::ifstream input(path, std::ios::binary);
if (!input) throw std::runtime_error("cannot open " + path.string());
bytes.assign(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());
}
MoveImportFirst(bytes, dll);
std::ofstream output(path, std::ios::binary | std::ios::trunc);
if (!output || !output.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()))) throw std::runtime_error("cannot write " + path.string());
}
}
-15
View File
@@ -1,15 +0,0 @@
#ifndef CORE_LIBS_ALLOCATOR_PEIMPORTFIRST_HPP
#define CORE_LIBS_ALLOCATOR_PEIMPORTFIRST_HPP
#include <filesystem>
#include <string>
#include <vector>
namespace Allocator {
void MoveImportFirst(std::vector<unsigned char>& image, const std::string& dll);
void MoveImportFirstInFile(const std::filesystem::path& path, const std::string& dll);
}
#endif
-38
View File
@@ -1,38 +0,0 @@
#include "PeImportFirst.hpp"
#include <cstdio>
#include <exception>
#include <filesystem>
#include <string>
namespace {
int Usage() {
std::fprintf(stderr, "usage: pe_import_first <file> <dll>\n");
return 2;
}
int Run(const std::filesystem::path& file, const std::string& dll) {
try {
Allocator::MoveImportFirstInFile(file, dll);
} catch (const std::exception& error) {
std::fprintf(stderr, "pe_import_first: %s: %s\n", file.string().c_str(), error.what());
return 1;
}
return 0;
}
}
#ifdef _WIN32
int wmain(int argc, wchar_t** argv) {
if (argc != 3) return Usage();
const auto dll = std::filesystem::path(argv[2]).u8string();
return Run(argv[1], std::string(dll.begin(), dll.end()));
}
#else
int main(int argc, char** argv) {
if (argc != 3) return Usage();
return Run(argv[1], argv[2]);
}
#endif
-38
View File
@@ -1,38 +0,0 @@
#include <windows.h>
#include <stdint.h>
#include <string.h>
void* __wrap_malloc(size_t bytes) {
return HeapAlloc(GetProcessHeap(), 0, bytes != 0 ? bytes : 1);
}
void* __wrap_calloc(size_t count, size_t size) {
if (size != 0 && count > SIZE_MAX / size) return NULL;
const size_t bytes = count * size;
return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bytes != 0 ? bytes : 1);
}
void __wrap_free(void* block) {
if (block != NULL) HeapFree(GetProcessHeap(), 0, block);
}
void* __wrap_realloc(void* block, size_t bytes) {
if (block == NULL) return __wrap_malloc(bytes);
if (bytes == 0) {
__wrap_free(block);
return NULL;
}
return HeapReAlloc(GetProcessHeap(), 0, block, bytes);
}
char* __wrap__strdup(const char* text) {
const size_t bytes = strlen(text) + 1;
char* copy = __wrap_malloc(bytes);
if (copy != NULL) memcpy(copy, text, bytes);
return copy;
}
char* __wrap_strdup(const char* text) {
return __wrap__strdup(text);
}
@@ -1,199 +0,0 @@
#include "allocator/PeImportFirst.hpp"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <random>
#include <stdexcept>
#include <string>
#include <vector>
namespace {
constexpr std::size_t PeOffset = 0x40;
constexpr std::size_t OptionalOffset = PeOffset + 24;
constexpr std::size_t OptionalBytes = 240;
constexpr std::uint32_t SectionRva = 0x1000;
constexpr std::size_t SectionOffset = 0x200;
constexpr std::size_t SectionBytes = 0x200;
constexpr std::size_t DescriptorBytes = 20;
void require(bool condition, const std::string& message) {
if (!condition) throw std::runtime_error(message);
}
void put16(std::vector<unsigned char>& bytes, std::size_t offset, std::uint16_t value) {
std::memcpy(bytes.data() + offset, &value, sizeof(value));
}
void put32(std::vector<unsigned char>& bytes, std::size_t offset, std::uint32_t value) {
std::memcpy(bytes.data() + offset, &value, sizeof(value));
}
std::uint32_t get32(const std::vector<unsigned char>& bytes, std::size_t offset) {
std::uint32_t value = 0;
std::memcpy(&value, bytes.data() + offset, sizeof(value));
return value;
}
std::vector<unsigned char> image(const std::vector<std::string>& dlls, std::uint16_t magic = 0x20b, std::uint32_t directories = 16, std::uint16_t optionalBytes = OptionalBytes) {
std::vector<unsigned char> bytes(SectionOffset + SectionBytes, 0);
bytes[0] = 'M';
bytes[1] = 'Z';
put32(bytes, 0x3c, PeOffset);
put32(bytes, PeOffset, 0x00004550u);
put16(bytes, PeOffset + 4, 0x8664);
put16(bytes, PeOffset + 6, 1);
put16(bytes, PeOffset + 20, optionalBytes);
put16(bytes, OptionalOffset, magic);
put32(bytes, OptionalOffset + 108, directories);
put32(bytes, OptionalOffset + 112 + 8, SectionRva);
put32(bytes, OptionalOffset + 112 + 12, static_cast<std::uint32_t>((dlls.size() + 1) * DescriptorBytes));
const auto sectionTable = OptionalOffset + optionalBytes;
std::memcpy(bytes.data() + sectionTable, ".idata", 6);
put32(bytes, sectionTable + 8, SectionBytes);
put32(bytes, sectionTable + 12, SectionRva);
put32(bytes, sectionTable + 16, SectionBytes);
put32(bytes, sectionTable + 20, SectionOffset);
auto name = (dlls.size() + 1) * DescriptorBytes;
for (std::size_t index = 0; index < dlls.size(); ++index) {
const auto descriptor = SectionOffset + index * DescriptorBytes;
put32(bytes, descriptor, static_cast<std::uint32_t>(SectionRva + 0x100 + index * 0x10));
put32(bytes, descriptor + 4, static_cast<std::uint32_t>(index + 1));
put32(bytes, descriptor + 12, static_cast<std::uint32_t>(SectionRva + name));
put32(bytes, descriptor + 16, static_cast<std::uint32_t>(SectionRva + 0x180 + index * 0x10));
std::memcpy(bytes.data() + SectionOffset + name, dlls[index].c_str(), dlls[index].size() + 1);
name += dlls[index].size() + 1;
}
return bytes;
}
std::string importName(const std::vector<unsigned char>& bytes, std::size_t index) {
const auto rva = get32(bytes, SectionOffset + index * DescriptorBytes + 12);
return reinterpret_cast<const char*>(bytes.data() + SectionOffset + (rva - SectionRva));
}
std::vector<unsigned char> descriptor(const std::vector<unsigned char>& bytes, std::size_t index) {
const auto first = bytes.begin() + static_cast<std::ptrdiff_t>(SectionOffset + index * DescriptorBytes);
return {first, first + static_cast<std::ptrdiff_t>(DescriptorBytes)};
}
void writeFile(const std::filesystem::path& path, const std::vector<unsigned char>& bytes) {
std::ofstream output(path, std::ios::binary | std::ios::trunc);
output.write(reinterpret_cast<const char*>(bytes.data()), static_cast<std::streamsize>(bytes.size()));
require(static_cast<bool>(output), "cannot write " + path.string());
}
std::vector<unsigned char> readFile(const std::filesystem::path& path) {
std::ifstream input(path, std::ios::binary);
require(static_cast<bool>(input), "cannot read " + path.string());
return {std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>()};
}
void movesTheNamedImportFirst() {
const auto original = image({"kernel32.dll", "ucrtbase.dll", "mimalloc-redirect.dll", "advapi32.dll"});
auto moved = original;
Allocator::MoveImportFirst(moved, "MIMALLOC-REDIRECT.dll");
require(importName(moved, 0) == "mimalloc-redirect.dll" && importName(moved, 1) == "kernel32.dll" && importName(moved, 2) == "ucrtbase.dll" && importName(moved, 3) == "advapi32.dll",
"the named import did not move first, or the others changed their order");
require(descriptor(moved, 0) == descriptor(original, 2) && descriptor(moved, 1) == descriptor(original, 0) && descriptor(moved, 2) == descriptor(original, 1) && descriptor(moved, 3) == descriptor(original, 3),
"a descriptor did not move whole");
const auto directoryEnd = SectionOffset + 4 * DescriptorBytes;
require(std::equal(moved.begin(), moved.begin() + SectionOffset, original.begin()) && std::equal(moved.begin() + directoryEnd, moved.end(), original.begin() + directoryEnd),
"bytes outside the import descriptors changed");
auto unchanged = original;
Allocator::MoveImportFirst(unchanged, "kernel32.dll");
require(unchanged == original, "moving the first import changed the image");
}
void movesTheImportFirstWithATwoDirectoryOptionalHeader(const std::filesystem::path& directory) {
const auto original = image({"kernel32.dll", "ucrtbase.dll", "mimalloc-redirect.dll", "advapi32.dll"}, 0x20b, 2, 128);
auto moved = original;
Allocator::MoveImportFirst(moved, "mimalloc-redirect.dll");
require(importName(moved, 0) == "mimalloc-redirect.dll" && importName(moved, 1) == "kernel32.dll" && importName(moved, 2) == "ucrtbase.dll" && importName(moved, 3) == "advapi32.dll",
"the import did not move first with a 128-byte optional header holding two directories");
require(descriptor(moved, 0) == descriptor(original, 2) && descriptor(moved, 1) == descriptor(original, 0) && descriptor(moved, 2) == descriptor(original, 1) && descriptor(moved, 3) == descriptor(original, 3),
"a descriptor did not move whole with a 128-byte optional header");
const auto directoryEnd = SectionOffset + 4 * DescriptorBytes;
require(std::equal(moved.begin(), moved.begin() + SectionOffset, original.begin()) && std::equal(moved.begin() + directoryEnd, moved.end(), original.begin() + directoryEnd),
"bytes outside the import descriptors changed with a 128-byte optional header");
auto repeated = moved;
Allocator::MoveImportFirst(repeated, "mimalloc-redirect.dll");
require(repeated == moved, "repeating the move changed the image with a 128-byte optional header");
const auto path = directory / "two-directory.dll";
writeFile(path, original);
Allocator::MoveImportFirstInFile(path, "mimalloc-redirect.dll");
require(readFile(path) == moved, "the file move differs from the in-memory move with a 128-byte optional header");
Allocator::MoveImportFirstInFile(path, "mimalloc-redirect.dll");
require(readFile(path) == moved, "repeating the move changed the file with a 128-byte optional header");
}
void movesTheImportInAFile(const std::filesystem::path& directory) {
const auto path = directory / "moved.dll";
writeFile(path, image({"kernel32.dll", "mimalloc-redirect.dll"}));
Allocator::MoveImportFirstInFile(path, "mimalloc-redirect.dll");
const auto moved = readFile(path);
require(importName(moved, 0) == "mimalloc-redirect.dll" && importName(moved, 1) == "kernel32.dll", "the file's import did not move first");
}
void failsWithoutTouchingTheFile(const std::filesystem::path& directory, const std::string& what, const std::vector<unsigned char>& bytes, const std::string& expected) {
const auto path = directory / (what + ".dll");
writeFile(path, bytes);
try {
Allocator::MoveImportFirstInFile(path, "mimalloc-redirect.dll");
} catch (const std::exception& error) {
require(std::string(error.what()).find(expected) != std::string::npos, what + ": failed with another error: " + error.what());
require(readFile(path) == bytes, what + ": the file changed although the move failed");
return;
}
throw std::runtime_error(what + ": the move did not fail");
}
}
int main() {
auto directory = std::filesystem::temp_directory_path() / std::filesystem::path(u8"aps5-pe-import-first-a\u00e7\u00e3o-\u65e5\u672c-");
directory += std::to_string(std::random_device{}());
try {
std::filesystem::create_directories(directory);
movesTheNamedImportFirst();
movesTheImportFirstWithATwoDirectoryOptionalHeader(directory);
movesTheImportInAFile(directory);
failsWithoutTouchingTheFile(directory, "missing-import", image({"kernel32.dll", "ucrtbase.dll"}), "does not import mimalloc-redirect.dll");
auto truncated = image({"kernel32.dll", "mimalloc-redirect.dll", "ucrtbase.dll"});
truncated.resize(SectionOffset + DescriptorBytes + DescriptorBytes / 2);
failsWithoutTouchingTheFile(directory, "truncated-directory", truncated, "truncated import directory");
failsWithoutTouchingTheFile(directory, "pe32", image({"kernel32.dll", "mimalloc-redirect.dll"}, 0x10b), "not a PE32+ image");
auto undeclared = image({"kernel32.dll", "mimalloc-redirect.dll"});
put32(undeclared, OptionalOffset + 108, 0);
failsWithoutTouchingTheFile(directory, "directory-count-zero", undeclared, "the image has no imports");
auto oneDirectory = image({"kernel32.dll", "mimalloc-redirect.dll"});
put32(oneDirectory, OptionalOffset + 108, 1);
failsWithoutTouchingTheFile(directory, "directory-count-one", oneDirectory, "the image has no imports");
auto shortHeader = image({"kernel32.dll", "mimalloc-redirect.dll"});
put16(shortHeader, PeOffset + 20, 112);
failsWithoutTouchingTheFile(directory, "optional-header-without-imports", shortHeader, "the image has no imports");
auto incompleteEntry = image({"kernel32.dll", "mimalloc-redirect.dll"}, 0x20b, 2, 128);
put16(incompleteEntry, PeOffset + 20, 127);
failsWithoutTouchingTheFile(directory, "optional-header-incomplete-import-entry", incompleteEntry, "the image has no imports");
auto unterminated = image({"kernel32.dll", "mimalloc-redirect.dll"});
unterminated.resize(SectionOffset + 3 * DescriptorBytes + 13 + 21);
failsWithoutTouchingTheFile(directory, "unterminated-name", unterminated, "unterminated import name");
auto outsideFile = image({"kernel32.dll", "mimalloc-redirect.dll", "ucrtbase.dll"});
put32(outsideFile, SectionOffset + 2 * DescriptorBytes + 12, static_cast<std::uint32_t>(SectionRva + 0x1ff));
outsideFile.resize(0x300);
failsWithoutTouchingTheFile(directory, "name-past-the-file", outsideFile, "RVA outside the file data");
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
std::error_code ignored;
std::filesystem::remove_all(directory, ignored);
return 1;
}
std::filesystem::remove_all(directory);
std::cout << "pe import first tests passed\n";
return 0;
}
@@ -1,15 +0,0 @@
#ifndef NID_BINARYPATCHERFACTORY_HPP
#define NID_BINARYPATCHERFACTORY_HPP
#include <nid/IBinaryPatcher.hpp>
#include <cstdint>
#include <memory>
#include <vector>
namespace Nid {
std::unique_ptr<IBinaryPatcher> MakePatcher(const std::vector<std::uint8_t>& binary);
}
#endif
-122
View File
@@ -1,122 +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_Phdr {
std::uint32_t p_type;
std::uint32_t p_flags;
std::uint64_t p_offset;
std::uint64_t p_vaddr;
std::uint64_t p_paddr;
std::uint64_t p_filesz;
std::uint64_t p_memsz;
std::uint64_t p_align;
};
struct Elf64_Shdr {
std::uint32_t sh_name;
std::uint32_t sh_type;
std::uint64_t sh_flags;
std::uint64_t sh_addr;
std::uint64_t sh_offset;
std::uint64_t sh_size;
std::uint32_t sh_link;
std::uint32_t sh_info;
std::uint64_t sh_addralign;
std::uint64_t sh_entsize;
};
struct Elf64_Sym {
std::uint32_t st_name;
std::uint8_t st_info;
std::uint8_t st_other;
std::uint16_t st_shndx;
std::uint64_t st_value;
std::uint64_t st_size;
};
struct Elf64_Rela {
std::uint64_t r_offset;
std::uint64_t r_info;
std::int64_t r_addend;
};
struct Elf64_Dyn {
std::int64_t d_tag;
std::uint64_t d_val;
};
struct Elf64_Verneed {
std::uint16_t vn_version;
std::uint16_t vn_cnt;
std::uint32_t vn_file;
std::uint32_t vn_aux;
std::uint32_t vn_next;
};
struct Elf64_Vernaux {
std::uint32_t vna_hash;
std::uint16_t vna_flags;
std::uint16_t vna_other;
std::uint32_t vna_name;
std::uint32_t vna_next;
};
struct GnuHashLayout {
std::uint32_t NBuckets;
std::uint32_t SymOffset;
std::uint32_t BloomSize;
std::uint32_t BloomShift;
std::size_t BloomOffset;
std::size_t BucketsOffset;
std::size_t ChainOffset;
};
constexpr std::int64_t kDtNeeded = 1;
constexpr std::int64_t kDtSoname = 14;
constexpr std::int64_t kDtRpath = 15;
constexpr std::int64_t kDtRunpath = 29;
constexpr std::int64_t kDtNull = 0;
inline bool IsDynamicNameTag(std::int64_t tag) {
return tag == kDtNeeded || tag == kDtSoname || tag == kDtRpath || tag == kDtRunpath;
}
constexpr std::uint32_t kShtDynamic = 6u;
constexpr std::uint32_t kShtHash = 5u;
constexpr std::uint32_t kShtGnuVerdef = 0x6ffffffdu;
constexpr std::uint32_t kShtGnuVerneed = 0x6ffffffeu;
constexpr std::uint32_t kShtDynsym = 11u;
constexpr std::uint32_t kShtGnuHash = 0x6ffffff6u;
constexpr std::uint32_t kShtRela = 4u;
constexpr std::uint32_t kShtGnuVersym = 0x6fffffffu;
constexpr std::uint8_t kStbLocal = 0u;
constexpr std::uint16_t kShnUndef = 0u;
class ElfNidPatcher final : public IBinaryPatcher {
public:
void PatchNids(std::vector<std::uint8_t>& binary, const std::string& libraryName, const std::unordered_set<std::string>& excludedExports, const PatchOptions& options = {}) const override;
};
}
#endif
@@ -1,16 +0,0 @@
#ifndef NID_EXPORTEXCLUSIONS_HPP
#define NID_EXPORTEXCLUSIONS_HPP
#include <string>
#include <unordered_set>
namespace Nid {
std::string NormalizeExportName(const std::string& name);
std::unordered_set<std::string> ReadExportExclusions(const std::string& path);
std::unordered_set<std::string> ReadExportList(const std::string& path);
bool WriteExportList(const std::string& referencePath, const std::string& path);
}
#endif
@@ -1,25 +0,0 @@
#ifndef NID_IBINARYPATCHER_HPP
#define NID_IBINARYPATCHER_HPP
#include <cstdint>
#include <string>
#include <unordered_set>
#include <vector>
namespace Nid {
struct PatchOptions {
bool executable = false;
bool onlySce = false;
};
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 PatchOptions& options = {}) 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 PatchOptions& options = {}) 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
-22
View File
@@ -1,22 +0,0 @@
#ifndef NID_NIDRESOLVER_HPP
#define NID_NIDRESOLVER_HPP
#include <nid/IBinaryPatcher.hpp>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace Nid {
bool IsSceImport(const std::string& name);
std::unordered_map<std::string, std::string> ResolveImportNids(const std::vector<std::string>& names, const std::unordered_set<std::string>& excluded, const PatchOptions& options);
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 PatchOptions& options = {}) const override;
};
}
#endif
Loaded 100 of 5324 files, more files were not shown because too many files have changed in this diff. Show more