mirror of
https://github.com/InstanceBrick/nightcap.git
synced 2026-10-17 21:00:47 +02:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b19bd8406f | ||
|
|
cd46538eb8 | ||
|
|
eca5f395eb | ||
|
|
26767e925c | ||
|
|
01a0e40463 | ||
|
|
a11e833e06 | ||
|
|
b9bce36824 | ||
|
|
14c8a55211 | ||
|
|
5c5422fa02 | ||
|
|
9b041ec2ac | ||
|
|
5f83c4a64f | ||
|
|
a9d8e3185e | ||
|
|
67a9f4db97 | ||
|
|
f07daccc82 | ||
|
|
2eef4f966f | ||
|
|
41003efb09 | ||
|
|
29a0f03a90 | ||
|
|
5a27aa0366 | ||
|
|
c99a55dc54 | ||
|
|
30d50f15d1 | ||
|
|
ab940acfb5 | ||
|
|
719b1fdd22 | ||
|
|
1fa2e116b3 | ||
|
|
35359f3575 | ||
|
|
40237fae72 | ||
|
|
ad6a3c3147 | ||
|
|
d982cd9506 | ||
|
|
65adb3bddc | ||
|
|
47e23df2e0 | ||
|
|
c0ff1842ee | ||
|
|
e073947b91 | ||
|
|
66de662e5b | ||
|
|
6c3631058c | ||
|
|
6829fd00ed | ||
|
|
8be3618cd5 | ||
|
|
265b476440 | ||
|
|
ff905fe5b7 | ||
|
|
02108a9bb1 | ||
|
|
7dd32335ca | ||
|
|
5ed6ed5e84 | ||
|
|
cef1b3ec4a | ||
|
|
8bde1a1c0d | ||
|
|
60e9c5c3ef | ||
|
|
d76e1b6f54 | ||
|
|
33c06c063e | ||
|
|
9e8afb233a | ||
|
|
7fda1eb239 | ||
|
|
f128e28b83 | ||
|
|
718e67f9e1 | ||
|
|
c6c354fdb1 | ||
|
|
25930d14ff | ||
|
|
854969457f | ||
|
|
65030d8df1 | ||
|
|
0be5e808c5 | ||
|
|
1b030a57eb | ||
|
|
2f5527b8b5 | ||
|
|
579cedbf1d | ||
|
|
a7b90e5919 | ||
|
|
3bba795ea3 | ||
|
|
5ce4487d4f | ||
|
|
c544389dd0 | ||
|
|
bdb84142d7 |
No files matched your search
@@ -11,14 +11,14 @@ body:
|
||||
value: |
|
||||
Please include enough detail for someone else to reproduce the bug.
|
||||
|
||||
Use any language you are comfortable with. The maintainer can read Russian and English directly, so either is preferred. If you are more comfortable in another language, use it.
|
||||
Use any language you are comfortable with.
|
||||
|
||||
Please write issues and pull requests yourself. Do not use AI-generated text.
|
||||
Please write issues and pull requests yourself.
|
||||
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
label: Mocktail version
|
||||
label: Nightcap version
|
||||
description: Provide the release version, package version, or commit hash.
|
||||
placeholder: "For example: v0.4.0 or 1a2b3c4"
|
||||
validations:
|
||||
@@ -37,7 +37,7 @@ body:
|
||||
id: installation
|
||||
attributes:
|
||||
label: Installation method
|
||||
description: Tell us how Mocktail was installed or built.
|
||||
description: Tell us how Nightcap was installed or built.
|
||||
placeholder: "For example: AppImage, Flatpak, AUR, or built from source"
|
||||
validations:
|
||||
required: true
|
||||
@@ -56,7 +56,7 @@ body:
|
||||
label: Steps to reproduce
|
||||
description: List the smallest reliable sequence of actions that triggers the problem.
|
||||
placeholder: |
|
||||
1. Start Mocktail with ...
|
||||
1. Start Nightcap with ...
|
||||
2. Open ...
|
||||
3. Select ...
|
||||
4. Observe ...
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
# Modified by vii from komaruworld/mocktail. See README "About this fork".
|
||||
name: Feature request
|
||||
description: Suggest an improvement or a new capability for Mocktail
|
||||
description: Suggest an improvement or a new capability for Nightcap
|
||||
title: "[Feature]: "
|
||||
labels:
|
||||
- enhancement
|
||||
@@ -10,9 +11,9 @@ body:
|
||||
value: |
|
||||
Describe what you want to change and why it would be useful.
|
||||
|
||||
Use any language you are comfortable with. The maintainer can read Russian and English directly, so either is preferred. If you are more comfortable in another language, use it.
|
||||
Use any language you are comfortable with.
|
||||
|
||||
Please write issues and pull requests yourself. Do not use AI-generated text.
|
||||
Please write issues and pull requests yourself.
|
||||
|
||||
- type: textarea
|
||||
id: problem
|
||||
@@ -26,7 +27,7 @@ body:
|
||||
id: proposal
|
||||
attributes:
|
||||
label: Proposed solution
|
||||
description: Describe how you would like Mocktail to behave.
|
||||
description: Describe how you would like Nightcap to behave.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
<!-- Briefly describe what this pull request adds, changes, or removes. Write it yourself and do not use AI-generated text. Link the issue with "Closes #123" or "Fixes #123". -->
|
||||
<!-- Modified by vii from komaruworld/mocktail. See README "About this fork". -->
|
||||
<!-- Briefly describe what this pull request adds, changes, or removes. Link the issue with "Closes #123" or "Fixes #123". -->
|
||||
|
||||
Closes #
|
||||
+16
-74
@@ -1,8 +1,6 @@
|
||||
name: Publish AUR packages
|
||||
name: Check AUR packages
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -13,8 +11,8 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish AUR packages
|
||||
metadata:
|
||||
name: Refresh AUR metadata
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
@@ -27,10 +25,9 @@ jobs:
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
package_dir="$GITHUB_WORKSPACE/packaging/aur/mocktail-git"
|
||||
version="$(sed -n \
|
||||
's/^[[:space:]]*VERSION[[:space:]]\+\([0-9][0-9.]*\).*/\1/p' \
|
||||
CMakeLists.txt | head -n 1)"
|
||||
package_dir="$GITHUB_WORKSPACE/packaging/aur/nightcap-git"
|
||||
version="$(git describe --tags --abbrev=0 --match='v[0-9]*')"
|
||||
version="${version#v}"
|
||||
[[ "$version" =~ ^[0-9]+(\.[0-9]+)*$ ]]
|
||||
pkgver="${version}.r$(git rev-list --count HEAD).g$(git rev-parse --short=7 HEAD)"
|
||||
sed -i "s/^pkgver=.*/pkgver=${pkgver}/" "$package_dir/PKGBUILD"
|
||||
@@ -39,76 +36,21 @@ jobs:
|
||||
--volume "$package_dir:/pkg" \
|
||||
archlinux:base-devel bash -Eeuo pipefail -c '
|
||||
useradd --create-home builder
|
||||
install -d -o builder -g builder /tmp/mocktail-git
|
||||
install -d -o builder -g builder /tmp/nightcap-git
|
||||
install -o builder -g builder -m 0644 \
|
||||
/pkg/PKGBUILD /tmp/mocktail-git/PKGBUILD
|
||||
/pkg/PKGBUILD /tmp/nightcap-git/PKGBUILD
|
||||
runuser -u builder -- bash -c \
|
||||
"cd /tmp/mocktail-git && makepkg --printsrcinfo" \
|
||||
"cd /tmp/nightcap-git && makepkg --printsrcinfo" \
|
||||
> /pkg/.SRCINFO
|
||||
'
|
||||
|
||||
grep -Fqx "pkgver=${pkgver}" "$package_dir/PKGBUILD"
|
||||
grep -Fqx $'\tpkgver = '"${pkgver}" "$package_dir/.SRCINFO"
|
||||
printf 'AUR_PKGVER=%s\n' "$pkgver" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Publish to the AUR
|
||||
shell: bash
|
||||
env:
|
||||
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
|
||||
AUR_SSH_KEY_PASSPHRASE: ${{ secrets.AUR_SSH_KEY_PASSPHRASE }}
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
[[ -n "$AUR_SSH_PRIVATE_KEY" ]]
|
||||
[[ -n "$AUR_SSH_KEY_PASSPHRASE" ]]
|
||||
|
||||
private_key="$RUNNER_TEMP/aur_ed25519"
|
||||
askpass="$RUNNER_TEMP/aur_askpass"
|
||||
known_hosts="$RUNNER_TEMP/aur_known_hosts"
|
||||
printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > "$private_key"
|
||||
unset AUR_SSH_PRIVATE_KEY
|
||||
chmod 0600 "$private_key"
|
||||
printf '%s\n' \
|
||||
'#!/usr/bin/env bash' \
|
||||
'printf '\''%s\n'\'' "$AUR_SSH_KEY_PASSPHRASE"' \
|
||||
> "$askpass"
|
||||
chmod 0700 "$askpass"
|
||||
eval "$(ssh-agent -s)"
|
||||
trap 'ssh-agent -k >/dev/null; rm -f -- "$private_key" "$askpass"' EXIT
|
||||
DISPLAY=:0 SSH_ASKPASS="$askpass" SSH_ASKPASS_REQUIRE=force \
|
||||
ssh-add "$private_key" </dev/null
|
||||
unset AUR_SSH_KEY_PASSPHRASE
|
||||
|
||||
ssh-keyscan -T 10 -t ed25519 aur.archlinux.org > "$known_hosts"
|
||||
fingerprint="$(ssh-keygen -lf "$known_hosts" -E sha256 | awk '{print $2}')"
|
||||
[[ "$fingerprint" == \
|
||||
'SHA256:RFzBCUItH9LZS0cKB5UE6ceAYhBD5C8GeOBip8Z11+4' ]]
|
||||
|
||||
export GIT_SSH_COMMAND="ssh -F /dev/null -i $private_key \
|
||||
-o BatchMode=yes -o IdentitiesOnly=yes \
|
||||
-o StrictHostKeyChecking=yes \
|
||||
-o UserKnownHostsFile=$known_hosts"
|
||||
publish_aur_package() {
|
||||
local package_name="$1"
|
||||
local commit_message="$2"
|
||||
local source_dir="packaging/aur/$package_name"
|
||||
local aur_dir="$RUNNER_TEMP/${package_name}-aur"
|
||||
|
||||
git clone --branch master --single-branch \
|
||||
"ssh://aur@aur.archlinux.org/${package_name}.git" "$aur_dir"
|
||||
install -m 0644 "$source_dir/PKGBUILD" "$aur_dir/PKGBUILD"
|
||||
install -m 0644 "$source_dir/.SRCINFO" "$aur_dir/.SRCINFO"
|
||||
|
||||
git -C "$aur_dir" config user.name komaruworld
|
||||
git -C "$aur_dir" config user.email rtysus228@gmail.com
|
||||
git -C "$aur_dir" add PKGBUILD .SRCINFO
|
||||
if git -C "$aur_dir" diff --cached --quiet; then
|
||||
printf '%s is already published\n' "$package_name"
|
||||
return
|
||||
fi
|
||||
git -C "$aur_dir" commit -m "$commit_message"
|
||||
git -C "$aur_dir" push origin HEAD:master
|
||||
}
|
||||
|
||||
publish_aur_package mocktail-git "Update to ${AUR_PKGVER}"
|
||||
publish_aur_package mocktail 'make builds stable'
|
||||
publish_aur_package mocktail-bin 'make builds stable'
|
||||
- name: Upload AUR metadata
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: Nightcap-AUR
|
||||
path: packaging/aur/nightcap-git/.SRCINFO
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -8,22 +8,32 @@ on:
|
||||
- 'CMakeLists.txt'
|
||||
- 'Makefile'
|
||||
- 'README.md'
|
||||
- '.gitmodules'
|
||||
- 'cmake/**'
|
||||
- 'config/**'
|
||||
- 'include/**'
|
||||
- 'packaging/**'
|
||||
- 'scripts/**'
|
||||
- 'src/**'
|
||||
- 'stubs/**'
|
||||
- 'tests/**'
|
||||
- 'third_party/**'
|
||||
pull_request:
|
||||
paths:
|
||||
- '.github/workflows/**'
|
||||
- 'CMakeLists.txt'
|
||||
- 'Makefile'
|
||||
- 'README.md'
|
||||
- '.gitmodules'
|
||||
- 'cmake/**'
|
||||
- 'config/**'
|
||||
- 'include/**'
|
||||
- 'packaging/**'
|
||||
- 'scripts/**'
|
||||
- 'src/**'
|
||||
- 'stubs/**'
|
||||
- 'tests/**'
|
||||
- 'third_party/**'
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
@@ -65,3 +75,43 @@ jobs:
|
||||
bash tests/flatpak_packaging_test.sh .
|
||||
bash tests/native_packaging_test.sh .
|
||||
bash tests/anylinux_dependencies_test.sh .
|
||||
|
||||
native-build:
|
||||
name: Native build (${{ matrix.arch }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 60
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- arch: x86_64
|
||||
runner: ubuntu-26.04
|
||||
- arch: aarch64
|
||||
runner: ubuntu-26.04-arm
|
||||
steps:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
submodules: recursive
|
||||
|
||||
- name: Install build dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install --yes --no-install-recommends \
|
||||
build-essential binutils cmake git ninja-build pkg-config lld \
|
||||
libsdl3-dev libsdl3-ttf-dev libcurl4-openssl-dev libssl-dev \
|
||||
nlohmann-json3-dev libyaml-dev libelf-dev libminizip-dev \
|
||||
libcapstone-dev libgtk-4-dev libadwaita-1-dev libwebkitgtk-6.0-dev \
|
||||
libutf8proc-dev libfontconfig1-dev libegl-dev libvulkan-dev \
|
||||
libplacebo-dev libpng-dev zlib1g-dev
|
||||
|
||||
- name: Build and check native executables
|
||||
shell: bash
|
||||
run: |
|
||||
test "$(uname -m)" = "${{ matrix.arch }}"
|
||||
cmake -S . -B build-ci -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF
|
||||
cmake --build build-ci --parallel 4
|
||||
./build-ci/mocktail --help
|
||||
./build-ci/mocktail_updater status
|
||||
@@ -126,10 +126,153 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
deb:
|
||||
name: DEB (Ubuntu 26.04)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
- name: Build DEB
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
docker run --rm \
|
||||
--volume "$GITHUB_WORKSPACE:/workspace" \
|
||||
--workdir /workspace \
|
||||
--env MOCKTAIL_PACKAGE_VERSION="$(./scripts/package_version.sh)" \
|
||||
ubuntu:26.04 bash -Eeuo pipefail -c '
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install --yes --no-install-recommends \
|
||||
build-essential cmake git ninja-build pkg-config lld fakeroot \
|
||||
dpkg-dev file libsdl3-dev libsdl3-ttf-dev \
|
||||
libcurl4-openssl-dev libssl-dev nlohmann-json3-dev \
|
||||
libyaml-dev libelf-dev libminizip-dev libcapstone-dev \
|
||||
libgtk-4-dev libadwaita-1-dev libwebkitgtk-6.0-dev \
|
||||
libutf8proc-dev libfontconfig1-dev libegl-dev \
|
||||
libvulkan-dev libplacebo-dev zlib1g-dev libpng-dev
|
||||
cmake -S . -B build-deb -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DMOCKTAIL_PACKAGE_NAME=nightcap \
|
||||
-DMOCKTAIL_PACKAGE_VERSION="$MOCKTAIL_PACKAGE_VERSION" \
|
||||
-DBUILD_TESTING=OFF
|
||||
cmake --build build-deb --parallel 4
|
||||
cpack --config build-deb/CPackConfig.cmake \
|
||||
-G DEB -B dist/deb
|
||||
dpkg-deb --info dist/deb/*.deb >/dev/null
|
||||
'
|
||||
|
||||
- name: Upload DEB
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: Nightcap-DEB
|
||||
path: dist/deb/*.deb
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
rpm:
|
||||
name: RPM (Fedora 44)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
- name: Build RPM
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
docker run --rm \
|
||||
--volume "$GITHUB_WORKSPACE:/workspace" \
|
||||
--workdir /workspace \
|
||||
--env MOCKTAIL_PACKAGE_VERSION="$(./scripts/package_version.sh)" \
|
||||
fedora:44 bash -Eeuo pipefail -c '
|
||||
dnf install --assumeyes \
|
||||
gcc-c++ cmake git ninja-build pkgconf-pkg-config lld rpm-build \
|
||||
SDL3-devel SDL3_ttf-devel libcurl-devel openssl-devel \
|
||||
nlohmann-json-devel libyaml-devel elfutils-libelf-devel \
|
||||
minizip-ng-compat-devel capstone-devel gtk4-devel libadwaita-devel \
|
||||
webkitgtk6.0-devel utf8proc-devel fontconfig-devel \
|
||||
libglvnd-devel vulkan-headers vulkan-loader-devel \
|
||||
libplacebo-devel zlib-ng-compat-devel libpng-devel
|
||||
cmake -S . -B build-rpm -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DCMAKE_INSTALL_LIBDIR=lib \
|
||||
-DMOCKTAIL_PACKAGE_NAME=nightcap \
|
||||
-DMOCKTAIL_PACKAGE_VERSION="$MOCKTAIL_PACKAGE_VERSION" \
|
||||
-DBUILD_TESTING=OFF
|
||||
cmake --build build-rpm --parallel 4
|
||||
cpack --config build-rpm/CPackConfig.cmake \
|
||||
-G RPM -B dist/rpm
|
||||
rpm --query --package --info dist/rpm/*.rpm >/dev/null
|
||||
'
|
||||
|
||||
- name: Upload RPM
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: Nightcap-RPM
|
||||
path: dist/rpm/*.rpm
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
arch:
|
||||
name: Pacman package (Arch Linux)
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 45
|
||||
steps:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 0
|
||||
submodules: recursive
|
||||
|
||||
- name: Build pacman package
|
||||
shell: bash
|
||||
run: |
|
||||
set -Eeuo pipefail
|
||||
version="$(./scripts/package_version.sh)"
|
||||
sed -i "s/^pkgver=.*/pkgver=${version}/" packaging/arch/PKGBUILD
|
||||
docker run --rm \
|
||||
--volume "$GITHUB_WORKSPACE:/workspace" \
|
||||
--workdir /workspace \
|
||||
ghcr.io/archlinux/archlinux:base-devel@sha256:c3953446016873a756fb7814f10087cac1634c127f7302e80c81c512da796d05 bash -Eeuo pipefail -c '
|
||||
pacman -Syu --needed --noconfirm \
|
||||
cmake git ninja pkgconf lld sdl3 sdl3_ttf curl openssl \
|
||||
nlohmann-json libyaml libelf minizip capstone gtk4 \
|
||||
libadwaita webkitgtk-6.0 libutf8proc fontconfig libpng \
|
||||
libplacebo vulkan-headers vulkan-icd-loader libglvnd zlib
|
||||
useradd --create-home builder
|
||||
chown -R builder:builder /workspace
|
||||
runuser -u builder -- env MOCKTAIL_SOURCE_DIR=/workspace \
|
||||
makepkg --dir /workspace/packaging/arch \
|
||||
--noconfirm --cleanbuild --force
|
||||
install -d dist/arch
|
||||
cp packaging/arch/*.pkg.tar.zst dist/arch/
|
||||
pacman -Qp dist/arch/*.pkg.tar.zst >/dev/null
|
||||
'
|
||||
|
||||
- name: Upload pacman package
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: Nightcap-Arch
|
||||
path: dist/arch/*.pkg.tar.zst
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
publish:
|
||||
name: Publish GitHub release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
needs: [appimage]
|
||||
needs: [appimage, deb, rpm, arch]
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
permissions:
|
||||
@@ -138,6 +281,13 @@ jobs:
|
||||
- name: Check out source
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
||||
- name: Download packages
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
pattern: 'Nightcap-*'
|
||||
merge-multiple: true
|
||||
path: release
|
||||
|
||||
- name: Download AppImage
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
with:
|
||||
@@ -152,7 +302,28 @@ jobs:
|
||||
set -Eeuo pipefail
|
||||
tag="${GITHUB_REF_NAME}"
|
||||
mv release/Mocktail-x86_64.AppImage release/Nightcap-x86_64.AppImage
|
||||
(cd release && sha256sum Nightcap-x86_64.AppImage > Nightcap-x86_64.AppImage.sha256)
|
||||
# An unmatched glob would otherwise reach sha256sum and gh as its own
|
||||
# literal text, so every package pattern has to match before upload.
|
||||
shopt -s nullglob
|
||||
assets=(Nightcap-x86_64.AppImage)
|
||||
for glob in '*.deb' '*.rpm' '*.pkg.tar.zst'; do
|
||||
matched=(release/$glob)
|
||||
if [[ ${#matched[@]} -eq 0 ]]; then
|
||||
echo "::error::no ${glob} package among the release artifacts"
|
||||
exit 1
|
||||
fi
|
||||
assets+=("${matched[@]#release/}")
|
||||
done
|
||||
uploads=()
|
||||
for asset in "${assets[@]}"; do
|
||||
uploads+=("release/$asset" "release/$asset.sha256")
|
||||
done
|
||||
(
|
||||
cd release
|
||||
for asset in "${assets[@]}"; do
|
||||
sha256sum "$asset" > "$asset.sha256"
|
||||
done
|
||||
)
|
||||
./scripts/release_notes.sh "$tag" > release/notes.md
|
||||
# The Flatpak workflow creates the same release; whichever job
|
||||
# arrives second sees "already exists" and continues.
|
||||
@@ -164,5 +335,4 @@ jobs:
|
||||
gh release edit "$tag" --repo "$GITHUB_REPOSITORY" \
|
||||
--title "Nightcap $tag" --notes-file release/notes.md
|
||||
gh release upload "$tag" --repo "$GITHUB_REPOSITORY" --clobber \
|
||||
release/Nightcap-x86_64.AppImage \
|
||||
release/Nightcap-x86_64.AppImage.sha256
|
||||
"${uploads[@]}"
|
||||
@@ -177,3 +177,6 @@ lsan.log*
|
||||
# Test fixtures
|
||||
!/third_party/mcpelauncher-linker/core/libziparchive/**/*.zip
|
||||
!/third_party/mcpelauncher-linker/core/libziparchive/**/*.apk
|
||||
|
||||
# Working plans, not part of the shipped documentation
|
||||
/docs/plans/
|
||||
+167
-1
@@ -6,6 +6,169 @@ GitHub are taken from the matching section here.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.3.2] - 2026-09-29
|
||||
|
||||
### Added
|
||||
|
||||
- Performance recordings made with `--profile` now show how busy the CPU was
|
||||
during each frame, which makes it easier to tell what caused a stutter.
|
||||
- Experimental support for ARM64 (`aarch64`) Linux, running Roblox's Android
|
||||
`arm64-v8a` client.
|
||||
|
||||
### Fixed
|
||||
|
||||
- When Roblox asks for a Google Play device check during login, Nightcap now
|
||||
answers right away that it isn't supported. Before, the "Verifying you're
|
||||
not a bot" screen waited about a minute for an answer and then sent you
|
||||
back to the login screen.
|
||||
- Solving a login challenge now closes its window. Before, Roblox's
|
||||
"challenge completed" signal was ignored and the window stayed open.
|
||||
Thanks to @glook9001.
|
||||
- Login no longer stalls after you pass a verification check. Before, Roblox
|
||||
only saw the page's "challenge completed" signal after a one-minute
|
||||
timeout, so it gave up and the login failed. On a Roblox build Nightcap
|
||||
can't handle this way, the log says "WebViewProtocol getter not
|
||||
recognized" and web pages behave as before.
|
||||
- Login check windows and other web pages get 5 seconds to start instead of
|
||||
3, so a slow start no longer closes them. The log says how long each one
|
||||
took to open.
|
||||
- Less stutter while joining a game and while textures load in. In Blade
|
||||
Ball, loading hitches dropped by about half, and the worst one went from
|
||||
0.8 seconds to 0.55 seconds.
|
||||
- Clicking Play on a private server now joins right away. Before, nothing
|
||||
happened until you clicked a sidebar tab like Home.
|
||||
- Middle click now reaches Roblox as the middle mouse button.
|
||||
- Scrolling follows your system's natural scrolling setting.
|
||||
- Fixed a crash on some x86_64 hosts when Roblox asked about a thread other
|
||||
than the one making the call.
|
||||
- Roblox updates no longer mix up the ARM64 and x86_64 compatibility profiles
|
||||
for the same version.
|
||||
- A partial or out-of-range user id in `MOCKTAIL_ROBLOX_USER_ID` or
|
||||
`MOCKTAIL_LOCAL_STORAGE_CURRENT_USER_ID` is now ignored instead of being
|
||||
partly read.
|
||||
|
||||
### Changed
|
||||
|
||||
- `make flatpak` and `scripts/build_flatpak.sh` now build with 2 jobs by
|
||||
default instead of 4, so a local Flatpak build is less likely to run out
|
||||
of memory. Set `FLATPAK_JOBS` or `MOCKTAIL_FLATPAK_JOBS` to use more.
|
||||
Thanks to @glook9001.
|
||||
|
||||
## [0.3.1] - 2026-09-20
|
||||
|
||||
### Added
|
||||
|
||||
- Each release carries a DEB, an RPM, and a pacman package beside the
|
||||
AppImage, with a `.sha256` for every file. They install `/usr/bin/mocktail`
|
||||
and conflict with each other and with upstream's `mocktail` package.
|
||||
Nightcap is in no distribution repository or the AUR; the recipes under
|
||||
`packaging/aur/nightcap{,-bin,-git}` build from this repository locally.
|
||||
- The AppStream metadata lists the Nightcap releases, so software centres
|
||||
show the release history instead of upstream's.
|
||||
|
||||
### Fixed
|
||||
|
||||
- ETC2 texture decoding no longer blocks the thread that submits the frame.
|
||||
Uploads decode on a background dispatcher and the submit carries a timeline
|
||||
semaphore wait, so the GPU waits for the texture instead of the render
|
||||
thread. Reading the application's compressed bytes moves to that dispatcher
|
||||
too whenever they are already mapped. In Blade Ball the worst
|
||||
`vkQueueSubmit` fell from 140ms to 1ms, its p99 from 4.9ms to 0.05ms, and
|
||||
the total time spent in submits from 2534ms to 309ms. Frame interval is
|
||||
unchanged: the remaining tail is the engine's own main-thread step. A device
|
||||
without the `timelineSemaphore` feature decodes inline as before, as does a
|
||||
submit whose `pNext` already sizes arrays by its semaphore counts.
|
||||
- The mouse pointer jumped when a right-click camera drag ended, and drifted
|
||||
to the viewport edge during one. The input router inferred pointer capture
|
||||
from SDL reporting zero absolute coordinates, which holds on X11 but not on
|
||||
Wayland, where the reported position accumulates the relative deltas and
|
||||
leaves the window. Motion, button, and wheel events now carry the window's
|
||||
relative mouse mode. The right-click camera fallback also only captures
|
||||
inside an experience, so the cursor stays free over the app surface.
|
||||
- Shutting the window down while an experience was starting or leaving could
|
||||
free the pointer capture owner underneath the thread using it. Callers off
|
||||
the SDL thread now hold a reference for the length of their call.
|
||||
- The TextBox caret did not move when a trailing space was typed in a
|
||||
single-line field. The final cluster rect SDL_ttf reports stops at the last
|
||||
inked glyph, so the laid-out width is used there instead. Wrapped layouts
|
||||
keep the clamp, because their width is the widest line rather than the last.
|
||||
- Every TextBox keystroke re-ran `TTF_Init`, a fontconfig sort, six
|
||||
`TTF_OpenFont` calls, and `TTF_Quit` on the render thread. The overlay holds
|
||||
its opened fonts and reopens them only when the Roblox font or the point
|
||||
size changes, keeping the current set when a reopen fails. Measured over 100
|
||||
rasters, 1.59ms to 0.12ms per keystroke.
|
||||
- Staged ETC2 copies now carry an explicit host-write barrier. A queue
|
||||
submission only makes host writes from before it visible to the device, and
|
||||
an asynchronous decode writes after the submit, so without the barrier those
|
||||
texels were not guaranteed to reach the copy that reads them.
|
||||
|
||||
### Changed
|
||||
|
||||
- `docs/PERFORMANCE.md` documents the GameMode settings to run with. A
|
||||
`desiredgov=powersave` in `~/.config/gamemode.ini` overrides the packaged
|
||||
`performance` default and clocks the CPU down for the whole session while
|
||||
still reporting an active performance request.
|
||||
|
||||
## [0.3.0] - 2026-09-18
|
||||
|
||||
### Added
|
||||
|
||||
- Custom Discord presence. `integrations.discord_rpc.text.title` replaces the
|
||||
name in "Playing Nightcap", and `integrations.discord_rpc.images` sets the
|
||||
large and small icons and their hover text. Text and image fields accept
|
||||
`{place_name}`, `{place_icon}`, and `{creator_name}`. A field that expands
|
||||
an empty placeholder is left out, and `text.state: ""` hides the state line.
|
||||
- The default Discord card now matches Sober: the title is "Roblox", the
|
||||
details line is "Playing <experience>", the state is "by <creator>", and
|
||||
the Roblox badge sits inside the experience icon. The creator comes from the
|
||||
same Roblox games request that already fetches the experience name. With
|
||||
`show_place_name: false` the creator is hidden too, so the card shows only
|
||||
the title and timer.
|
||||
- `--profile <file>` writes a Chrome-format trace of the Vulkan adapter's
|
||||
work: presents, GPU waits, submits, ETC2 texture decode, and pipeline and
|
||||
shader creation. Open it in ui.perfetto.dev. `docs/BENCHMARKING.md`
|
||||
describes the benchmark runs, and `scripts/summarize_profile_trace.py`
|
||||
turns traces into a before and after table.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Texture uploads stalled the frame they were submitted on. ETC2 batches
|
||||
decoded on worker threads but were then resampled one upload at a time on
|
||||
the submitting thread, which at the default 4x upscale is sixteen times the
|
||||
decoded texels. Resampling now runs on the same worker pool, in two passes so
|
||||
mip level 0 still resolves before the mips built from it. In a 70k-part
|
||||
place the worst `vkQueueSubmit` fell from 167ms to 92ms.
|
||||
- Most ETC2 batches decoded on a single thread. Workers were created and
|
||||
joined per batch, so the parallel floor had to cover that cost and sat at a
|
||||
1024x1024 image; batches under it ran on the caller, which was 54% of all
|
||||
decode time in a 70k-part place. Decode workers are now a persistent pool,
|
||||
and the floor drops to a 128x128 image. Mean decode time in that place fell
|
||||
from 8.2ms to 4.7ms, and 11.8ms before both texture fixes.
|
||||
- On CPUs with a wide core-speed spread, Feral GameMode pinned the process to
|
||||
the few fastest cores, concentrating Roblox's worker pool onto them instead
|
||||
of spreading it. With `performance.gamemode: auto`, a request that narrows
|
||||
the CPU affinity is now released again, which releases the pin. Set
|
||||
`pin_cores=no` in `~/.config/gamemode.ini` to keep GameMode without the
|
||||
pinning, or `performance.gamemode: on` to accept it. See
|
||||
`docs/PERFORMANCE.md`.
|
||||
- With `show_place_name: false`, Discord no longer shows the experience
|
||||
thumbnail or its name on hover.
|
||||
- The host main thread no longer spins on the engine's message pump, which
|
||||
cost about half a core and 146,000 empty calls a second. It now rests 100 µs
|
||||
between polls: sleeping when the governor is `performance`, parking the
|
||||
core with TPAUSE on CPUs that have it, spinning otherwise. With GameMode
|
||||
setting the governor, process CPU in a 60k-part place fell from 216% to
|
||||
107% at the same 120 fps. `MOCKTAIL_ENGINE_PUMP_REST` forces a mode; see
|
||||
`docs/PERFORMANCE.md`.
|
||||
- ETC2 uploads with a `bufferRowLength` or `bufferImageHeight` larger than
|
||||
the image read the padded rows as packed data and decoded garbage.
|
||||
- ETC2 resampling created and joined worker threads on every batch. It now
|
||||
runs on the persistent decode pool.
|
||||
- A failed trace write left the profile writer thread waking every 250 ms
|
||||
for the rest of the session. It now exits.
|
||||
- The `--profile` trace gains a `pump` slice for the engine's main-thread
|
||||
step.
|
||||
|
||||
## [0.2.0] - 2026-09-16
|
||||
|
||||
### Added
|
||||
@@ -75,6 +238,9 @@ First Nightcap release, forked from komaruworld/mocktail.
|
||||
- The AppImage build no longer fails on stale checksums for the slimmed
|
||||
Arch packages.
|
||||
|
||||
[Unreleased]: https://github.com/CoderDayton/nightcap/compare/v0.2.0...HEAD
|
||||
[Unreleased]: https://github.com/CoderDayton/nightcap/compare/v0.3.2...HEAD
|
||||
[0.3.2]: https://github.com/CoderDayton/nightcap/releases/tag/v0.3.2
|
||||
[0.3.1]: https://github.com/CoderDayton/nightcap/releases/tag/v0.3.1
|
||||
[0.3.0]: https://github.com/CoderDayton/nightcap/releases/tag/v0.3.0
|
||||
[0.2.0]: https://github.com/CoderDayton/nightcap/releases/tag/v0.2.0
|
||||
[0.1.0]: https://github.com/CoderDayton/nightcap/releases/tag/v0.1.0
|
||||
+33
-20
@@ -10,7 +10,7 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(Mocktail
|
||||
VERSION 1.0.4
|
||||
DESCRIPTION "Android x86-64 Roblox compatibility runtime for Linux"
|
||||
DESCRIPTION "Android Roblox compatibility runtime for Linux"
|
||||
LANGUAGES CXX
|
||||
)
|
||||
|
||||
@@ -266,6 +266,7 @@ add_library(mocktail_runtime STATIC
|
||||
src/runtime/crash_report_policy.cc
|
||||
src/runtime/discord_rpc.cc
|
||||
src/runtime/device_profile.cc
|
||||
src/runtime/engine_pump_rest.cc
|
||||
src/runtime/environment.cc
|
||||
src/runtime/external_launch_broker.cc
|
||||
src/runtime/frame_rate_policy.cc
|
||||
@@ -287,6 +288,7 @@ add_library(mocktail_runtime STATIC
|
||||
src/runtime/roblox_game_session_native_adapter.cc
|
||||
src/runtime/roblox_web_view_bridge.cc
|
||||
src/runtime/roblox_permissions_bridge.cc
|
||||
src/runtime/roblox_account_bridge.cc
|
||||
src/runtime/payload_update_preflight.cc
|
||||
src/runtime/process_launch_policy.cc
|
||||
src/runtime/process_diagnostics.cc
|
||||
@@ -384,7 +386,8 @@ add_library(mocktail_webview_helper_policy STATIC
|
||||
src/webview/webview_helper_policy.cc
|
||||
)
|
||||
add_library(Mocktail::WebViewHelperPolicy ALIAS mocktail_webview_helper_policy)
|
||||
target_include_directories(mocktail_webview_helper_policy PUBLIC src)
|
||||
target_include_directories(mocktail_webview_helper_policy PUBLIC src
|
||||
PRIVATE include)
|
||||
target_link_libraries(mocktail_webview_helper_policy PUBLIC
|
||||
PkgConfig::WEBKITGTK6
|
||||
nlohmann_json::nlohmann_json
|
||||
@@ -649,6 +652,11 @@ target_link_options(mocktail PRIVATE
|
||||
)
|
||||
|
||||
# Native FreeBSD helper for Linuxulator's unsupported DF socket option.
|
||||
# The helper is x86-64 assembly; other host architectures have nothing to
|
||||
# assemble.
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64)$")
|
||||
set(MOCKTAIL_BUILD_FREEBSD_SOCKET_HELPER OFF)
|
||||
endif()
|
||||
option(MOCKTAIL_BUILD_FREEBSD_SOCKET_HELPER
|
||||
"Build the native FreeBSD Linuxulator socket helper" ON)
|
||||
if(MOCKTAIL_BUILD_FREEBSD_SOCKET_HELPER)
|
||||
@@ -785,33 +793,39 @@ install(CODE "
|
||||
endif()
|
||||
")
|
||||
|
||||
set(MOCKTAIL_PACKAGE_NAMES mocktail mocktail-nightly nightcap nightcap-nightly)
|
||||
set(MOCKTAIL_PACKAGE_NAME "mocktail" CACHE STRING
|
||||
"Native package name"
|
||||
)
|
||||
set(MOCKTAIL_PACKAGE_VERSION "${PROJECT_VERSION}" CACHE STRING
|
||||
"Native package version"
|
||||
)
|
||||
set(MOCKTAIL_PACKAGE_VERSION_SUFFIX "" CACHE STRING
|
||||
"Native package version suffix"
|
||||
)
|
||||
if(NOT MOCKTAIL_PACKAGE_NAME STREQUAL "mocktail" AND
|
||||
NOT MOCKTAIL_PACKAGE_NAME STREQUAL "mocktail-nightly")
|
||||
if(NOT MOCKTAIL_PACKAGE_NAME IN_LIST MOCKTAIL_PACKAGE_NAMES)
|
||||
string(JOIN ", " MOCKTAIL_PACKAGE_NAMES_TEXT ${MOCKTAIL_PACKAGE_NAMES})
|
||||
message(FATAL_ERROR
|
||||
"MOCKTAIL_PACKAGE_NAME must be mocktail or mocktail-nightly")
|
||||
"MOCKTAIL_PACKAGE_NAME must be one of ${MOCKTAIL_PACKAGE_NAMES_TEXT}")
|
||||
endif()
|
||||
|
||||
set(CPACK_PACKAGE_NAME "${MOCKTAIL_PACKAGE_NAME}")
|
||||
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}${MOCKTAIL_PACKAGE_VERSION_SUFFIX}")
|
||||
set(CPACK_PACKAGE_VENDOR "Mocktail Project")
|
||||
set(CPACK_PACKAGE_CONTACT "komaruworld <rtysus228@gmail.com>")
|
||||
set(CPACK_PACKAGE_HOMEPAGE_URL "https://github.com/komaruworld/mocktail")
|
||||
set(CPACK_PACKAGE_VERSION
|
||||
"${MOCKTAIL_PACKAGE_VERSION}${MOCKTAIL_PACKAGE_VERSION_SUFFIX}"
|
||||
)
|
||||
set(CPACK_PACKAGE_VENDOR "Nightcap")
|
||||
set(CPACK_PACKAGE_CONTACT "vii <coderdayton14@gmail.com>")
|
||||
set(CPACK_PACKAGE_HOMEPAGE_URL "https://github.com/CoderDayton/nightcap")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "${PROJECT_DESCRIPTION}")
|
||||
set(CPACK_PACKAGE_DESCRIPTION
|
||||
"Runs the Android x86-64 Roblox client on Linux."
|
||||
"Runs the Android Roblox client on Linux."
|
||||
)
|
||||
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_SOURCE_DIR}/LICENSE")
|
||||
set(CPACK_PACKAGING_INSTALL_PREFIX "/usr")
|
||||
set(CPACK_STRIP_FILES TRUE)
|
||||
|
||||
set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
|
||||
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "komaruworld <rtysus228@gmail.com>")
|
||||
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "vii <coderdayton14@gmail.com>")
|
||||
set(CPACK_DEBIAN_PACKAGE_SECTION "games")
|
||||
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
|
||||
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
|
||||
@@ -821,15 +835,14 @@ set(CPACK_RPM_PACKAGE_LICENSE "Apache-2.0")
|
||||
set(CPACK_RPM_PACKAGE_GROUP "Amusements/Games")
|
||||
set(CPACK_RPM_PACKAGE_AUTOREQPROV ON)
|
||||
|
||||
if(MOCKTAIL_PACKAGE_NAME STREQUAL "mocktail-nightly")
|
||||
set(CPACK_DEBIAN_PACKAGE_CONFLICTS "mocktail")
|
||||
set(CPACK_DEBIAN_PACKAGE_REPLACES "mocktail")
|
||||
set(CPACK_RPM_PACKAGE_CONFLICTS "mocktail")
|
||||
else()
|
||||
set(CPACK_DEBIAN_PACKAGE_CONFLICTS "mocktail-nightly")
|
||||
set(CPACK_DEBIAN_PACKAGE_REPLACES "mocktail-nightly")
|
||||
set(CPACK_RPM_PACKAGE_CONFLICTS "mocktail-nightly")
|
||||
endif()
|
||||
# Every variant installs the same /usr/bin/mocktail and /usr/share/mocktail,
|
||||
# so only one of them can be present at a time.
|
||||
set(MOCKTAIL_PACKAGE_SIBLINGS ${MOCKTAIL_PACKAGE_NAMES})
|
||||
list(REMOVE_ITEM MOCKTAIL_PACKAGE_SIBLINGS "${MOCKTAIL_PACKAGE_NAME}")
|
||||
string(JOIN ", " MOCKTAIL_PACKAGE_CONFLICTS ${MOCKTAIL_PACKAGE_SIBLINGS})
|
||||
set(CPACK_DEBIAN_PACKAGE_CONFLICTS "${MOCKTAIL_PACKAGE_CONFLICTS}")
|
||||
set(CPACK_DEBIAN_PACKAGE_REPLACES "${MOCKTAIL_PACKAGE_CONFLICTS}")
|
||||
set(CPACK_RPM_PACKAGE_CONFLICTS "${MOCKTAIL_PACKAGE_CONFLICTS}")
|
||||
include(CPack)
|
||||
|
||||
add_dependencies(mocktail all_stubs)
|
||||
|
||||
@@ -42,6 +42,18 @@ attach `latest.log`:
|
||||
|
||||
For native installs, a custom `$XDG_STATE_HOME` replaces `~/.local/state`.
|
||||
|
||||
## Can I run multiple Roblox instances?
|
||||
|
||||
No. Nightcap won't add multi-instance launching. It would mean working around
|
||||
Roblox's restrictions on running several clients. The [Roblox Terms of Use](https://en.help.roblox.com/hc/en-us/articles/115004647846-Roblox-Terms-of-Use)
|
||||
prohibit bypassing technical protections, and violating the terms can get your
|
||||
account suspended.
|
||||
|
||||
Bloxstrap brought the option back in [v2.9.0](https://github.com/bloxstraplabs/bloxstrap/releases/tag/v2.9.0)
|
||||
with a "use at your own risk" warning, then removed it in
|
||||
[v2.10.0](https://github.com/bloxstraplabs/bloxstrap/releases/tag/v2.10.0)
|
||||
after Roblox added measures against running multiple clients.
|
||||
|
||||
## Can I play in VR?
|
||||
|
||||
VR is experimental and lives on upstream's `vr` branch, which does not
|
||||
|
||||
@@ -21,7 +21,7 @@ ANYLINUX_APPIMAGETOOL ?= appimagetool
|
||||
PREFIX ?= /usr
|
||||
FLATPAK_BUILD_DIR ?= build-flatpak
|
||||
FLATPAK_MANIFEST ?= packaging/flatpak/io.github.CoderDayton.nightcap.json
|
||||
FLATPAK_JOBS ?= 4
|
||||
FLATPAK_JOBS ?= 2
|
||||
|
||||
define build_native_runtime
|
||||
@git submodule update --init --recursive
|
||||
@@ -130,8 +130,8 @@ auto-run: ## Build/run loop with crash summaries
|
||||
run-gles: build ## Run strict system EGL/OpenGL ES 3 without Vulkan fallback
|
||||
@$(BINARY) --graphics opengl
|
||||
|
||||
run-angle: ## Run with ANGLE/Vulkan compatibility backend
|
||||
@MOCKTAIL_GRAPHICS_BACKEND=angle-vulkan ./scripts/run_sober.sh
|
||||
run-angle: build ## Run with ANGLE/Vulkan compatibility backend
|
||||
@$(BINARY) --graphics angle-vulkan
|
||||
|
||||
update-roblox: ## Validate and import the current x86_64 Roblox bundle cached by Sober
|
||||
@./scripts/update_roblox_payload.sh
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
<!-- Modified by vii from komaruworld/mocktail. See "About this fork" below. -->
|
||||
# Nightcap
|
||||
|
||||
[](https://github.com/CoderDayton/nightcap/actions/workflows/ci.yml)
|
||||
[](https://github.com/CoderDayton/nightcap/stargazers)
|
||||
[](LICENSE)
|
||||
<div align="center">
|
||||
<img src="https://raw.githubusercontent.com/CoderDayton/nightcap/main/packaging/io.github.CoderDayton.nightcap.svg" alt="Nightcap logo" width="128">
|
||||
<h1 style="margin-top: 5px;">
|
||||
Nightcap
|
||||
<br>
|
||||
<a href="https://github.com/CoderDayton/nightcap/actions/workflows/ci.yml"><img src="https://github.com/CoderDayton/nightcap/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
|
||||
<a href="https://github.com/CoderDayton/nightcap/stargazers"><img src="https://img.shields.io/github/stars/CoderDayton/nightcap?style=flat&logo=github" alt="Stars"></a>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-blue.svg" alt="License"></a>
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
Nightcap is Mocktail, tuned for playing on a real PC. It runs the Android
|
||||
`x86_64` Roblox client on Linux, including a Linux userspace hosted by
|
||||
@@ -25,7 +30,8 @@ side by side.
|
||||
waiting in a queue.
|
||||
- **Sharper textures.** Small textures are upscaled 4x by default, and you
|
||||
can replace any texture with your own PNG in `~/.config/mocktail/textures`.
|
||||
Set `MOCKTAIL_SMALL_TEXTURE_UPSCALE=1` to turn the upscale off.
|
||||
A ready-made crosshair is in [`textures/`](textures/README.md). Set
|
||||
`MOCKTAIL_SMALL_TEXTURE_UPSCALE=1` to turn the upscale off.
|
||||
- **ETC2 textures on any GPU.** Games that use compressed mobile textures now
|
||||
render correctly on desktop GPUs, without stutter.
|
||||
- **No more error 319 kicks.** Servers no longer drop you shortly after
|
||||
@@ -36,8 +42,9 @@ side by side.
|
||||
|
||||
Everything else works the same as upstream. See the
|
||||
[roadmap](docs/ROADMAP.md) for what is coming next, the
|
||||
[changelog](CHANGELOG.md) for what each release changed, and the
|
||||
[FAQ](FAQ.md) for Discord RPC, logs, and VR.
|
||||
[changelog](CHANGELOG.md) for what each release changed,
|
||||
[performance](docs/PERFORMANCE.md) for CPU load, heat and the knobs that change
|
||||
them, and the [FAQ](FAQ.md) for Discord RPC, logs, and VR.
|
||||
|
||||
## Install with Flatpak
|
||||
|
||||
@@ -59,10 +66,24 @@ chmod +x Nightcap-x86_64.AppImage
|
||||
./Nightcap-x86_64.AppImage
|
||||
```
|
||||
|
||||
Or build and install it from source using the steps under
|
||||
[Building](#building). There are no AUR, DEB, or RPM packages of Nightcap.
|
||||
Upstream ships those for unmodified Mocktail, see
|
||||
[komaruworld/mocktail](https://github.com/komaruworld/mocktail#readme).
|
||||
## Distribution packages
|
||||
|
||||
Each release also carries a DEB, an RPM, and a pacman package, with a
|
||||
`.sha256` beside every file on the
|
||||
[releases page](https://github.com/CoderDayton/nightcap/releases/latest):
|
||||
|
||||
```bash
|
||||
sudo apt install ./nightcap_<version>_amd64.deb
|
||||
sudo dnf install ./nightcap-<version>-1.x86_64.rpm
|
||||
sudo pacman -U nightcap-<version>-1-x86_64.pkg.tar.zst
|
||||
```
|
||||
|
||||
They install `/usr/bin/mocktail`, so they conflict with upstream's `mocktail`
|
||||
package. Nightcap is not in any distribution repository or the AUR; the
|
||||
recipes under `packaging/aur` are kept for local builds only.
|
||||
|
||||
Or build and install from source using the steps under
|
||||
[Building](#building).
|
||||
|
||||
## How it works
|
||||
|
||||
@@ -114,8 +135,9 @@ Linux `x86_64` is supported. Experimental FreeBSD 15.1 Linuxulator support has
|
||||
been tested with an `x86_64` Fedora 44 userspace. On FreeBSD, Nightcap runs
|
||||
inside Linuxulator; it is not a native FreeBSD binary. Building requires CMake
|
||||
3.20+, Git, pkg-config, LLD, binutils, a C++17 compiler, SDL 3.4+, SDL3_ttf,
|
||||
Vulkan, EGL, libplacebo, fontconfig, libcurl, OpenSSL, libelf, libyaml, minizip,
|
||||
Capstone 5, utf8proc, nlohmann/json, GTK4, libadwaita 1.6+, and WebKitGTK 6.0.
|
||||
Vulkan, EGL, libplacebo, fontconfig, libcurl, OpenSSL, libelf, libyaml, libpng,
|
||||
minizip, Capstone 5, utf8proc, nlohmann/json, GTK4, libadwaita 1.6+, and
|
||||
WebKitGTK 6.0.
|
||||
|
||||
See the [FreeBSD Guide](packaging/freebsd/README.md) for setup and launch instructions.
|
||||
|
||||
@@ -126,7 +148,7 @@ See the [FreeBSD Guide](packaging/freebsd/README.md) for setup and launch instru
|
||||
sudo apt update
|
||||
sudo apt install build-essential cmake git ninja-build pkg-config lld \
|
||||
libsdl3-dev libsdl3-ttf-dev libcurl4-openssl-dev libssl-dev \
|
||||
nlohmann-json3-dev libyaml-dev libelf-dev libminizip-dev \
|
||||
nlohmann-json3-dev libyaml-dev libpng-dev libelf-dev libminizip-dev \
|
||||
libcapstone-dev libgtk-4-dev libadwaita-1-dev libwebkitgtk-6.0-dev \
|
||||
libutf8proc-dev libfontconfig1-dev libegl-dev libvulkan-dev \
|
||||
libplacebo-dev zlib1g-dev
|
||||
@@ -138,7 +160,7 @@ sudo apt install build-essential cmake git ninja-build pkg-config lld \
|
||||
|
||||
```bash
|
||||
sudo pacman -S --needed base-devel cmake git ninja pkgconf lld sdl3 sdl3_ttf \
|
||||
curl openssl nlohmann-json libyaml libelf minizip capstone gtk4 \
|
||||
curl openssl nlohmann-json libyaml libpng libelf minizip capstone gtk4 \
|
||||
libadwaita webkitgtk-6.0 libutf8proc fontconfig libglvnd \
|
||||
libplacebo vulkan-headers vulkan-icd-loader zlib
|
||||
```
|
||||
@@ -150,7 +172,8 @@ sudo pacman -S --needed base-devel cmake git ninja pkgconf lld sdl3 sdl3_ttf \
|
||||
```bash
|
||||
sudo dnf install gcc-c++ cmake git ninja-build pkgconf-pkg-config lld \
|
||||
SDL3-devel SDL3_ttf-devel libcurl-devel openssl-devel \
|
||||
nlohmann-json-devel libyaml-devel elfutils-libelf-devel minizip-ng-compat-devel \
|
||||
nlohmann-json-devel libyaml-devel libpng-devel elfutils-libelf-devel \
|
||||
minizip-ng-compat-devel \
|
||||
capstone-devel gtk4-devel libadwaita-devel webkitgtk6.0-devel \
|
||||
utf8proc-devel fontconfig-devel libglvnd-devel vulkan-headers \
|
||||
vulkan-loader-devel libplacebo-devel zlib-ng-compat-devel
|
||||
@@ -174,6 +197,11 @@ Use `sudo make install` instead to install system-wide under `/usr`. To make
|
||||
Roblox website links open the build tree copy without installing, run
|
||||
`make register-url-handler`.
|
||||
|
||||
To build and install the Flatpak from source, install `flatpak-builder` and run
|
||||
`make flatpak`. It builds with 2 parallel jobs to keep memory use low. Pass
|
||||
`FLATPAK_JOBS=N` to `make flatpak`, or set `MOCKTAIL_FLATPAK_JOBS=N` for
|
||||
`scripts/build_flatpak.sh`, to change that.
|
||||
|
||||
To run the same checks as CI before each commit and push, install
|
||||
[lefthook](https://github.com/evilmartians/lefthook) and run once:
|
||||
|
||||
|
||||
@@ -112,12 +112,24 @@ integrations:
|
||||
public_servers_only: true
|
||||
# button_label: Join Server
|
||||
# English defaults. Uncomment only the lines you want to customize.
|
||||
# Text and image fields accept {place_name}, {place_icon}, and
|
||||
# {creator_name}. A field that expands an empty placeholder is left out,
|
||||
# and a "" title shows the app name.
|
||||
# title, state, and the images fields may be "" to hide them.
|
||||
# text:
|
||||
# browsing: Browsing experiences
|
||||
# joining: Joining an experience
|
||||
# playing: "{place_name}"
|
||||
# state: Playing Roblox
|
||||
# playing: "Playing {place_name}"
|
||||
# state: "by {creator_name}"
|
||||
# unknown_place: Unknown experience
|
||||
# title: Roblox
|
||||
# Images take an https:// URL, or an asset key uploaded to application_id.
|
||||
# large: "" hides both images; the small image needs a large one.
|
||||
# images:
|
||||
# large: "{place_icon}"
|
||||
# large_text: "{place_name}"
|
||||
# small: roblox_small
|
||||
# small_text: Roblox
|
||||
# Advanced: overrides the application bundled by the package maintainer.
|
||||
# application_id: 123456789012345678
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
{
|
||||
"version_name": "2.721.1108",
|
||||
"version_code": 2350,
|
||||
"abi": "x86_64",
|
||||
"elf_build_id": "50e1b0abd123350e794226062fe3a1ef360c5f0d",
|
||||
"status": "legacy-researched",
|
||||
"default_allowed": false,
|
||||
@@ -15,6 +16,7 @@
|
||||
{
|
||||
"version_name": "2.725.1142",
|
||||
"version_code": 2546,
|
||||
"abi": "x86_64",
|
||||
"elf_build_id": "d0cb1fa0deb3d9161b4cd77530cbcd2e50de3a21",
|
||||
"status": "supported",
|
||||
"default_allowed": true,
|
||||
@@ -35,6 +37,7 @@
|
||||
{
|
||||
"version_name": "2.727.1199",
|
||||
"version_code": 2628,
|
||||
"abi": "x86_64",
|
||||
"elf_build_id": "1686400865ae0e408cd7bd67de7a439625c6fd13",
|
||||
"status": "supported",
|
||||
"default_allowed": true,
|
||||
@@ -46,6 +49,7 @@
|
||||
{
|
||||
"version_name": "2.734.917",
|
||||
"version_code": 2908,
|
||||
"abi": "x86_64",
|
||||
"elf_build_id": "63c5109637b7d7b2bdb8ed8f858023ff5ef49326",
|
||||
"status": "supported",
|
||||
"default_allowed": true,
|
||||
@@ -66,6 +70,19 @@
|
||||
{
|
||||
"version_name": "2.736.1408",
|
||||
"version_code": 2998,
|
||||
"abi": "arm64-v8a",
|
||||
"elf_build_id": "ed2b035768b1513561d0e6ea7f9bbec35b0e60e5",
|
||||
"status": "supported",
|
||||
"default_allowed": true,
|
||||
"allow_legacy_binary_patches": false,
|
||||
"allow_host_abi_bridges": true,
|
||||
"allow_host_constructor_replay": true,
|
||||
"reason": "AArch64 arm64-v8a payload of the same 2.736.1408 release as the verified x86-64 profile; allocator, constructor replay, and pre-JNI bootstrap RVAs were derived by cross-architecture semantic matching."
|
||||
},
|
||||
{
|
||||
"version_name": "2.736.1408",
|
||||
"version_code": 2998,
|
||||
"abi": "x86_64",
|
||||
"elf_build_id": "ade08266c67aee88ec9c1d00902150e1684dad3a",
|
||||
"status": "supported",
|
||||
"default_allowed": true,
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# Benchmarking
|
||||
|
||||
A pull request that claims a speedup shows before and after numbers taken
|
||||
the way this guide describes. Numbers from different machines are not
|
||||
compared with each other. Each run is compared with a run on the same
|
||||
machine.
|
||||
|
||||
## Two layers, two tools
|
||||
|
||||
Roblox measures its own work. Nightcap measures the layer between Roblox and
|
||||
your driver.
|
||||
|
||||
| Layer | What it covers | Tool |
|
||||
| --- | --- | --- |
|
||||
| Roblox | Scripts, physics, rendering jobs, network | Roblox's stats overlays, Shift+F4 and Shift+F5 in game |
|
||||
| Nightcap | Vulkan adapter: present, swapchain and GPU waits, submits, ETC2 texture decode, pipeline and shader creation | `--profile` |
|
||||
|
||||
A Nightcap change should move the `--profile` numbers. If it only moves the
|
||||
Roblox overlay numbers, say so in the pull request, since the cause is then
|
||||
less direct.
|
||||
|
||||
## Recording a trace
|
||||
|
||||
```sh
|
||||
mocktail --profile ~/nightcap-before.json
|
||||
```
|
||||
|
||||
The Vulkan adapter writes a Chrome-format trace to that file, a few times a
|
||||
second. The file is valid JSON after every write, so a session that crashes
|
||||
or is killed still leaves a readable trace. Exit from the Roblox menu when you are done. Open the file
|
||||
in [ui.perfetto.dev](https://ui.perfetto.dev) or `chrome://tracing`.
|
||||
|
||||
Expect about 130 bytes per event, around 15 MB per minute at 240 FPS.
|
||||
Profiling is off unless `--profile` is given, and `MOCKTAIL_PROFILE_TRACE`
|
||||
does the same thing as the flag.
|
||||
|
||||
### What the trace contains
|
||||
|
||||
Each slice is named after the call it times, on the thread that made it.
|
||||
|
||||
| Category | Slices | Arguments |
|
||||
| --- | --- | --- |
|
||||
| `present` | `vkQueuePresentKHR`: the whole adapter present, including the text overlay | `result` |
|
||||
| `present` | `host present`: the host driver's present, nested inside the slice above | |
|
||||
| `wait` | `vkAcquireNextImageKHR`, `vkAcquireNextImage2KHR`, `vkWaitForFences`, `vkWaitSemaphores`, `vkWaitSemaphoresKHR`, `vkQueueWaitIdle`, `vkDeviceWaitIdle` | |
|
||||
| `submit` | `vkQueueSubmit`, `vkQueueSubmit2`, `vkQueueSubmit2KHR` | `submits` |
|
||||
| `texture` | `etc2 decode`: CPU decode of ETC2 textures. On a device with a timeline semaphore this runs on the decode dispatcher, not the submitting thread | `uploads`, `compressed_bytes`, `decoded_bytes` |
|
||||
| `texture` | `etc2 gather`: the part of an asynchronous upload that stays on the submitting thread. Absent when the decode ran inline | `uploads`, `compressed_bytes`, `decoded_bytes`, `ticket` |
|
||||
| `texture` | `etc2 staging create`: creating a staging block for ETC2 uploads, when no block has room left | `bytes` |
|
||||
| `texture` | `etc2 staging destroy`: destroying empty staging blocks beyond the four kept idle | `buffers` |
|
||||
| `texture` | `etc2 release wait`: a command buffer reset waiting for its uploads' decode. Only waits of 0.1 ms or more are recorded | `ticket` |
|
||||
| `memory` | `vkAllocateMemory` | `bytes`, `type` (memory type index), `result` |
|
||||
| `memory` | `vkFreeMemory`, `vkUnmapMemory`: both include waiting for ETC2 decodes that still read that memory | |
|
||||
| `memory` | `vkMapMemory`, `vkCreateImage`, `vkDestroyImage` | |
|
||||
| `pipeline` | `vkCreateGraphicsPipelines`, `vkCreateComputePipelines` | `count`, `cache` (1 when a pipeline cache was passed), `result` |
|
||||
| `pipeline` | `vkCreateShaderModule` | `bytes`, `result` |
|
||||
| `pipeline` | `vkCreatePipelineCache` | `initial_bytes`, `result` |
|
||||
| `pump` | `nativeCallMessagesFromMainThread`: the engine's main-thread step, on the host main thread. Only calls of 20 µs or more are recorded; the empty polls between them are not. | `cpu_us`: CPU time the main thread used during the call. Far below the slice's duration means the step spent it waiting |
|
||||
|
||||
The `frame interval (ms)` counter is the time between successive adapter
|
||||
presents. `vkQueuePresentKHR` time minus `host present` time is the adapter's
|
||||
own cost per frame.
|
||||
|
||||
Two more counters cover the same interval. `present thread cpu (ms)` is the
|
||||
CPU time the thread that presents used in it, and is absent for a frame
|
||||
presented from a different thread than the one before. `process cpu (ms)` is
|
||||
the CPU time of every thread together, so dividing it by the frame interval
|
||||
gives the number of cores busy. A long frame with little present-thread CPU
|
||||
was spent waiting.
|
||||
|
||||
## The benchmark runs
|
||||
|
||||
Run every scenario before and after the change, on the same build type
|
||||
(`make build`), with the same `config.yaml`. Close other GPU-heavy apps.
|
||||
Record `graphics.frame_rate_limit` and `graphics.vsync` in the pull request,
|
||||
because a frame cap hides frame time gains.
|
||||
|
||||
Record `~/.config/gamemode.ini` too, and do not change it between the before
|
||||
and after runs. `desiredgov` there decides the CPU governor for the whole
|
||||
session and therefore which engine pump mode is chosen, which moves process
|
||||
CPU by more than most changes under test. See
|
||||
[PERFORMANCE.md](PERFORMANCE.md).
|
||||
|
||||
Frame interval p99 varies by 2 ms or more between identical runs, so a
|
||||
difference that size is not a result. Three runs per scenario is the minimum
|
||||
for any frame-time claim; slice totals for a specific subsystem are far less
|
||||
noisy and can be read from fewer.
|
||||
|
||||
| Scenario | How to start | What to do | What it shows |
|
||||
| --- | --- | --- | --- |
|
||||
| Home screen, cold | `mocktail --profile home-cold.json` with an empty shader cache (below) | Wait 30 s on the home screen, exit | First-load stutter: `pipeline` and `texture` slices |
|
||||
| Tower of Hell | `mocktail --profile toh.json --launch-uri "roblox://experiences/start?placeId=1962086868"` | Stand still at spawn for 60 s, exit | Steady-state frame time on a light scene |
|
||||
| Murder Mystery 2 | `mocktail --profile mm2.json --launch-uri "roblox://experiences/start?placeId=142823291"` | Stay in the lobby for 60 s, exit | Frame time with many players and a busier scene |
|
||||
|
||||
For the cold run, point the driver's shader cache at an empty directory, so
|
||||
your normal cache is left alone:
|
||||
|
||||
```sh
|
||||
cache=$(mktemp -d)
|
||||
MESA_SHADER_CACHE_DIR="$cache" __GL_SHADER_DISK_CACHE_PATH="$cache" \
|
||||
mocktail --profile home-cold.json
|
||||
```
|
||||
|
||||
`MESA_SHADER_CACHE_DIR` applies to Mesa drivers (AMD, Intel) and
|
||||
`__GL_SHADER_DISK_CACHE_PATH` to the NVIDIA driver.
|
||||
|
||||
Run each scenario three times and keep the median run, since one run can
|
||||
catch a background stall.
|
||||
|
||||
## Comparing runs
|
||||
|
||||
```sh
|
||||
scripts/summarize_profile_trace.py toh-before.json toh-after.json
|
||||
```
|
||||
|
||||
This prints a Markdown table with one column per trace: frame count, frame
|
||||
interval mean, p50, p95, p99 and max, then count, total, mean, p99 and max
|
||||
for every slice name, largest total first. Paste the table into the pull
|
||||
request and attach both traces.
|
||||
|
||||
For frame time, compare p95 and p99 as well as the mean. Stutter shows up in
|
||||
the tail first. For first-load work, compare the `total (ms)` rows of the
|
||||
`pipeline` and `texture` slices from the cold run.
|
||||
@@ -0,0 +1,193 @@
|
||||
# Performance and CPU load
|
||||
|
||||
What Nightcap does to your CPU and GPU, which knobs change it, and how to
|
||||
measure rather than guess.
|
||||
|
||||
## GameMode core pinning
|
||||
|
||||
Nightcap asks Feral GameMode for a performance session at startup
|
||||
(`performance.gamemode`, default `auto`). GameMode raises the CPU governor and
|
||||
the process priority, which helps.
|
||||
|
||||
On a CPU with a wide spread of per-core maximum frequencies — Intel P-core and
|
||||
E-core parts, AMD parts with preferred cores — GameMode also pins the process
|
||||
to the fastest cores. On a 32-thread host that can mean 4 usable threads out of
|
||||
32. Roblox spreads its work across a worker pool, so the pin concentrates that
|
||||
pool onto a couple of physical cores instead of spreading it. Those cores sit
|
||||
near their boost ceiling and run hot while the rest of the chip idles.
|
||||
|
||||
GameMode re-applies the pin roughly every 5 seconds, so widening the mask from
|
||||
inside the process does not hold. Releasing the request does release the pin.
|
||||
|
||||
Under `auto`, Nightcap therefore checks its CPU affinity immediately after the
|
||||
request. If GameMode narrowed it, Nightcap ends the request and prints:
|
||||
|
||||
```
|
||||
[gamemode] released: it pinned this process to a subset of the CPUs, ...
|
||||
```
|
||||
|
||||
The trade is that GameMode's governor and priority boost go with it. To keep
|
||||
those and lose only the pinning, turn pinning off for every game on the host.
|
||||
|
||||
These are the settings to run with:
|
||||
|
||||
```ini
|
||||
# ~/.config/gamemode.ini
|
||||
[general]
|
||||
desiredgov=performance
|
||||
|
||||
[cpu]
|
||||
pin_cores=no
|
||||
park_cores=no
|
||||
```
|
||||
|
||||
`desiredgov` is the one to check first. The packaged default in
|
||||
`/usr/share/gamemode/gamemode.ini` is already `performance`, but a value in
|
||||
your own file replaces it, and `desiredgov=powersave` there means GameMode
|
||||
clocks the CPU **down** for the whole session while still reporting
|
||||
`[gamemode] performance request active`. The symptoms are a low CPU clock
|
||||
under load, a GPU that never leaves its lower SM clocks, and the engine pump
|
||||
falling back to `tpause` — which costs about 70% of a core instead of 3%,
|
||||
because `sleep` is only chosen when the governor reads `performance`. On one
|
||||
13900K host, correcting `powersave` to `performance` took the process from
|
||||
177% CPU to 42% and the package from 70°C to 53-63°C, at the same frame rate.
|
||||
|
||||
GameMode reads `$XDG_CONFIG_HOME`, `/usr/share/gamemode` and `/etc`, in that
|
||||
order. It does not read anything under Nightcap's own config directory, so this
|
||||
file has to live in one of those three places. The daemon reads it when it
|
||||
starts, so restart it after editing: `systemctl --user restart gamemoded`.
|
||||
|
||||
Restarting the daemon drops the session of any game already running; relaunch
|
||||
the game for new settings to apply to it.
|
||||
|
||||
`gamemoded` is D-Bus activated through
|
||||
`com.feralinteractive.GameMode.service`, so `systemctl --user stop gamemoded`
|
||||
does not hold — the next client request starts it again within seconds. To
|
||||
measure with GameMode genuinely off, mask it:
|
||||
|
||||
```bash
|
||||
systemctl --user mask gamemoded # and --unmask afterwards
|
||||
```
|
||||
|
||||
The governor switch runs through polkit. Debian and Ubuntu only allow it for
|
||||
members of the `gamemode` group; without that, the daemon's journal shows
|
||||
`cpugovctl set performance: Not authorized` and the governor stays put while
|
||||
the session is otherwise active. Add yourself and log in again:
|
||||
|
||||
```bash
|
||||
sudo usermod -aG gamemode "$USER"
|
||||
```
|
||||
|
||||
Fedora and Arch allow any logged-in local user.
|
||||
|
||||
Setting `performance.gamemode: on` accepts the pinning instead: `on` is an
|
||||
explicit request for GameMode, and Nightcap keeps the session whatever it does
|
||||
to the affinity. `off` never contacts the daemon.
|
||||
|
||||
To see which CPUs the process may use:
|
||||
|
||||
```bash
|
||||
pid=$(pgrep -x Main)
|
||||
for t in /proc/$pid/task/*; do taskset -pc "${t##*/}"; done
|
||||
```
|
||||
|
||||
Two traps here. The engine process reports its name as `Main`, not
|
||||
`mocktail`; `pgrep -x mocktail` finds only the launcher, which sits near 0%
|
||||
CPU and tells you nothing. And `taskset -p` reads one thread, not the whole
|
||||
process, so a single call reports the main thread's mask and says nothing
|
||||
about the workers — which is where the game's load actually is.
|
||||
|
||||
For the same reason, `ps -L -o psr=` shows which core each thread is running
|
||||
on right now, not which cores it is allowed on. On a hybrid CPU the scheduler
|
||||
preferring P-cores for runnable work is normal and is not a mask.
|
||||
|
||||
## The main-thread pump
|
||||
|
||||
Roblox posts its per-frame main-thread step at a time of its own choosing,
|
||||
and nothing signals the host when it does. The host main thread therefore
|
||||
polls `nativeCallMessagesFromMainThread`, and a post that waits more than a
|
||||
fraction of a millisecond costs a whole frame. Between polls the thread rests
|
||||
for 100 µs, and how it rests decides the CPU clock:
|
||||
|
||||
| Mode | When | What it costs |
|
||||
| --- | --- | --- |
|
||||
| `sleep` | The governor is `performance`, which GameMode sets | The thread idles at about 3% of a core. The governor holds the clock. |
|
||||
| `tpause` | Otherwise, on a CPU with WAITPKG (Intel 12th gen and newer) | The core stays awake in a light C0 state. Frame rate holds; the OS books the time as busy, so the thread shows around 70% of a core, at lower power than a spin. |
|
||||
| `spin` | Otherwise | The core stays awake at full power. |
|
||||
|
||||
Under a power-saving governor the CPU clocks a bursty core down unless some
|
||||
core stays awake, and Roblox's render thread then runs slower and drops
|
||||
frames. That is why `sleep` is not the default there. Startup prints the
|
||||
chosen mode:
|
||||
|
||||
```
|
||||
[main] engine pump rest: tpause (MOCKTAIL_ENGINE_PUMP_REST=sleep|tpause|spin)
|
||||
```
|
||||
|
||||
`MOCKTAIL_ENGINE_PUMP_REST` forces a mode. `sleep` without the governor's help
|
||||
runs cooler for a few frames per second less; measure before keeping it.
|
||||
|
||||
## Small texture upscaling
|
||||
|
||||
`MOCKTAIL_SMALL_TEXTURE_UPSCALE` (default `4`) redraws ETC2 textures of 64px or
|
||||
smaller at N times their width and height. At the default that is 16 times the
|
||||
pixels per affected texture.
|
||||
|
||||
The cost lands in two places. Decoding and resampling is CPU work on up to 8
|
||||
threads while textures load, which shows up as a burst rather than a steady
|
||||
load. The enlarged textures then stay in GPU memory for the session and cost
|
||||
extra sampling bandwidth on every frame that uses them.
|
||||
|
||||
That decode does not run on the thread that submits the frame. On a device
|
||||
with a timeline semaphore, uploads decode on a background dispatcher and the
|
||||
submit carries a semaphore wait, so the GPU waits for the texture instead of
|
||||
the render thread. In the trace this is the `etc2 decode` slice on its own
|
||||
thread, with only a negligible `etc2 gather` left on the submitting one. A
|
||||
device without that feature decodes inline as before.
|
||||
|
||||
Set it to `1` to turn upscaling off:
|
||||
|
||||
```bash
|
||||
MOCKTAIL_SMALL_TEXTURE_UPSCALE=1 mocktail
|
||||
```
|
||||
|
||||
## Frame rate and present mode
|
||||
|
||||
`graphics.frame_rate_limit` (default `-1`) leaves Roblox's own in-game
|
||||
framerate cap in charge; Nightcap sets no `DFIntTaskSchedulerTargetFps`
|
||||
override. A fixed value forwards that number to the scheduler.
|
||||
|
||||
`graphics.vsync` (default `auto`) selects the presentation mode. `auto` and
|
||||
`on` both pick the lowest-latency synchronized mode the driver offers, in
|
||||
order: `FIFO_LATEST_READY`, `MAILBOX`, `FIFO_RELAXED`, `FIFO`. The first two do
|
||||
not block the render thread on the display refresh, so the frame rate is
|
||||
governed by the in-game cap rather than by presentation. `off` selects
|
||||
`IMMEDIATE` and does not synchronize at all.
|
||||
|
||||
If the frame rate is higher than your refresh rate, the extra frames are work
|
||||
you cannot see. Lower the in-game cap to your refresh rate first.
|
||||
|
||||
## Measuring
|
||||
|
||||
Shift+F4 in game shows Roblox's own scheduler jobs, with a millisecond cost and
|
||||
a percentage for each. It does not show Nightcap's threads — the Vulkan
|
||||
adapter, the ETC2 decode workers, the libc shim — so it is a reading on the
|
||||
game, not on the process.
|
||||
|
||||
For the whole process:
|
||||
|
||||
```bash
|
||||
top -H -p $(pgrep -x mocktail) # per-thread CPU, sorted
|
||||
ps -L -o psr=,pcpu=,comm= -p $(pgrep -x mocktail) # which core each thread is on
|
||||
nvidia-smi --query-gpu=utilization.gpu,temperature.gpu,power.draw --format=csv
|
||||
```
|
||||
|
||||
A thread pinned near 100% while the frame rate is steady is a busy-wait. The
|
||||
one exception is the host main thread in `tpause` mode, which the OS reports
|
||||
as busy while the core is parked (see above). Load spread across many
|
||||
`RBX Worker` threads is the game's own scheduler, and its cost tracks the
|
||||
place you are in — part count, moving parts and joints all show in the
|
||||
Shift+F4 World section.
|
||||
|
||||
`--profile <file>` writes a Chrome trace of the Vulkan adapter's work for
|
||||
ui.perfetto.dev. See [BENCHMARKING.md](BENCHMARKING.md).
|
||||
+32
-46
@@ -15,7 +15,8 @@ Goal: a small GTK4 settings window, reachable from the app menu and from a
|
||||
- Graphics tab: backend, frame rate limit, vsync, small texture upscale.
|
||||
- Input tab: the `input.raw_mouse` toggle and controller options.
|
||||
- Advanced tab: FFlag overrides with a plain text editor for `fflags.json`.
|
||||
- Discord tab: the `discord_rpc` block (see item 3).
|
||||
- Discord tab: every field in the `discord_rpc` block, so a friend can see
|
||||
what you are playing and you can switch it all off in one click.
|
||||
- Changes apply on next launch. A restart button restarts Nightcap.
|
||||
|
||||
Done when every option in `config/mocktail.example.yaml` that a player would
|
||||
@@ -28,68 +29,53 @@ already hot-plug and release their held inputs when unplugged. One rough edge
|
||||
is left.
|
||||
|
||||
- Correct button glyphs for the connected pad. `SDL_GetGamepadType` is only
|
||||
read for Xbox and PlayStation pads, so a Switch Pro, a GameCube pad, or any
|
||||
generic pad SDL reports as `SDL_GAMEPAD_TYPE_STANDARD` reaches Roblox as
|
||||
type 0 and draws generic glyphs. `SDL_GetRealGamepadType`, and the vendor
|
||||
and product IDs, are available and unused.
|
||||
read for Xbox and PlayStation pads, so a Switch Pro, a GameCube pad, or any
|
||||
generic pad SDL reports as `SDL_GAMEPAD_TYPE_STANDARD` reaches Roblox as
|
||||
type 0 and draws generic glyphs. `SDL_GetRealGamepadType`, and the vendor
|
||||
and product IDs, are available and unused.
|
||||
|
||||
Done when a plugged-in pad shows its own buttons.
|
||||
|
||||
## 3. Discord Rich Presence
|
||||
|
||||
Upstream ships Discord RPC. Nightcap turns it on by default; see the
|
||||
[FAQ](../FAQ.md) to switch it off. It shows the experience name, elapsed
|
||||
time, the experience icon, and a join button when the server is public.
|
||||
|
||||
- Custom presence: set the title, details line, state line, and large and
|
||||
small icons from `config.yaml`, with placeholders like the experience name
|
||||
and elapsed time.
|
||||
- A Discord tab in the settings window to toggle each field.
|
||||
|
||||
Done when a friend can see what you are playing and join in one click, and
|
||||
you can switch it all off in one click.
|
||||
|
||||
## 4. Performance profiling
|
||||
|
||||
Every performance change should come with numbers. Today they come with a
|
||||
feeling.
|
||||
|
||||
- A frame time overlay, toggled by a key and a config flag, showing CPU time,
|
||||
GPU time, and present latency.
|
||||
- Shader compile and pipeline cache tracing, so first-load stutter can be
|
||||
measured and cut.
|
||||
- A `--profile` flag that writes a Chrome-format trace file, readable in
|
||||
`ui.perfetto.dev` and `chrome://tracing`.
|
||||
- A short benchmark guide in `docs/` with a fixed set of experiences, so
|
||||
before and after numbers can be compared across machines.
|
||||
|
||||
Done when a pull request that claims a speedup can show the trace that
|
||||
proves it.
|
||||
|
||||
## Shipped
|
||||
|
||||
- Lower input latency: frames are presented as soon as they are ready.
|
||||
- Controllers hot-plug without a restart, and a pad that is unplugged mid-game
|
||||
releases its held buttons and sticks instead of leaving them stuck.
|
||||
releases its held buttons and sticks instead of leaving them stuck.
|
||||
- Mouse look keeps responding after a long turn, instead of going dead until
|
||||
the pointer travels back from past the screen edge.
|
||||
the pointer travels back from past the screen edge.
|
||||
- Optional raw mouse input: `input.raw_mouse` in `config.yaml` sends look
|
||||
deltas in host units, so fractional display scaling no longer changes
|
||||
first-person sensitivity.
|
||||
deltas in host units, so fractional display scaling no longer changes
|
||||
first-person sensitivity.
|
||||
- Small textures upscaled 4x by default, with PNG overrides in
|
||||
`~/.config/mocktail/textures`.
|
||||
`~/.config/mocktail/textures`.
|
||||
- ETC2 textures decoded on desktop GPUs without stutter.
|
||||
- No more error 319 kicks after joining a server.
|
||||
- Roblox sees the real host RAM and screen size.
|
||||
- Desktop launcher that works on Wayland and finds the installed binary.
|
||||
- Discord Rich Presence on by default.
|
||||
- Discord Rich Presence on by default, with the experience name, creator,
|
||||
elapsed time, the experience icon with a Roblox badge, and a join button
|
||||
when the server is public. See the [FAQ](../FAQ.md) to switch it off.
|
||||
- Custom Discord presence: title, details, state, and large and small icons
|
||||
from `config.yaml`, with `{place_name}`, `{place_icon}`, and
|
||||
`{creator_name}` placeholders.
|
||||
- `--profile` writes a Chrome-format trace of the Vulkan adapter's work,
|
||||
including shader and pipeline creation, readable in `ui.perfetto.dev`.
|
||||
[BENCHMARKING.md](BENCHMARKING.md) fixes the experiences to measure and
|
||||
`scripts/summarize_profile_trace.py` builds the before and after table.
|
||||
- Texture uploads no longer stall the frame they land on: ETC2 decode and
|
||||
resampling run on a persistent worker pool.
|
||||
- Less stutter while joining an experience and while textures load in. See
|
||||
the [changelog](../CHANGELOG.md) for the numbers.
|
||||
- The host main thread rests between engine polls instead of spinning, and
|
||||
GameMode's core pinning is released, so Roblox's workers spread across
|
||||
every core. See [PERFORMANCE.md](PERFORMANCE.md).
|
||||
- Own app ID `io.github.CoderDayton.nightcap`, so Nightcap installs next to
|
||||
upstream.
|
||||
upstream.
|
||||
- AppImage and signed Flatpak releases on every `v*` tag, with the Flatpak
|
||||
repo on GitHub Pages.
|
||||
repo on GitHub Pages.
|
||||
|
||||
## Not planned
|
||||
|
||||
- Replacing the `mocktail` binary and config names. Keeping them makes
|
||||
upstream merges clean.
|
||||
- DEB, RPM, and AUR packages. Upstream ships those for unmodified Mocktail.
|
||||
upstream merges clean.
|
||||
|
||||
@@ -33,6 +33,23 @@ void SetLegacyBionicDiagnosticsEnabled(bool enabled);
|
||||
// guest layout explicit instead of exposing the incompatible host libc type.
|
||||
using MocktailBionicMutexAttr = int64_t;
|
||||
|
||||
// Bionic LP64 pthread_attr_t: 56 bytes with explicit field offsets. The host
|
||||
// glibc layout is opaque and wider on aarch64, so guest buffers must be read
|
||||
// and written through this struct only.
|
||||
struct MocktailBionicPthreadAttr {
|
||||
std::uint32_t flags;
|
||||
void* stack_base;
|
||||
std::size_t stack_size;
|
||||
std::size_t guard_size;
|
||||
std::int32_t sched_policy;
|
||||
std::int32_t sched_priority;
|
||||
char reserved[16];
|
||||
};
|
||||
static_assert(sizeof(MocktailBionicPthreadAttr) == 56);
|
||||
|
||||
inline constexpr std::uint32_t kMocktailBionicAttrFlagDetached = 0x1;
|
||||
inline constexpr std::uint32_t kMocktailBionicAttrFlagUserStack = 0x2;
|
||||
|
||||
extern "C" {
|
||||
|
||||
void mocktail_set_current_jni_env(void* env);
|
||||
@@ -84,6 +101,19 @@ int mocktail_pthread_barrier_init(pthread_barrier_t* barrier,
|
||||
int mocktail_pthread_barrier_destroy(pthread_barrier_t* barrier);
|
||||
int mocktail_pthread_barrier_wait(pthread_barrier_t* barrier);
|
||||
|
||||
int mocktail_pthread_attr_init(MocktailBionicPthreadAttr* attr);
|
||||
int mocktail_pthread_attr_destroy(MocktailBionicPthreadAttr* attr);
|
||||
int mocktail_pthread_attr_setstacksize(MocktailBionicPthreadAttr* attr,
|
||||
size_t stack_size);
|
||||
int mocktail_pthread_attr_setdetachstate(MocktailBionicPthreadAttr* attr,
|
||||
int detach_state);
|
||||
int mocktail_pthread_attr_setschedparam(MocktailBionicPthreadAttr* attr,
|
||||
const struct sched_param* parameters);
|
||||
int mocktail_pthread_getattr_np(pthread_t thread,
|
||||
MocktailBionicPthreadAttr* attr);
|
||||
int mocktail_pthread_attr_getstack(const MocktailBionicPthreadAttr* attr,
|
||||
void** stack_base, size_t* stack_size);
|
||||
|
||||
extern void* mocktail_gameactivity_on_start_native;
|
||||
extern void* mocktail_gameactivity_on_resume_native;
|
||||
extern void* mocktail_gameactivity_on_surface_created_native;
|
||||
|
||||
@@ -25,11 +25,12 @@ void ConfigureBionicPthreadThreadInitializer(
|
||||
|
||||
} // namespace mocktail::compat
|
||||
|
||||
struct MocktailBionicPthreadAttr;
|
||||
|
||||
// Rebuilds attributes instead of passing Android pthread_attr_t to glibc.
|
||||
extern "C" int mocktail_bionic_pthread_create(pthread_t* thread,
|
||||
const pthread_attr_t* attr,
|
||||
void* (*start_routine)(void*),
|
||||
void* argument);
|
||||
extern "C" int mocktail_bionic_pthread_create(
|
||||
pthread_t* thread, const MocktailBionicPthreadAttr* attr,
|
||||
void* (*start_routine)(void*), void* argument);
|
||||
|
||||
// Guest real-time scheduling is denied to avoid the host RLIMIT_RTTIME watchdog.
|
||||
extern "C" int mocktail_bionic_pthread_setschedparam(
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#ifndef MOCKTAIL_COMPAT_GUEST_ABI_H_
|
||||
#define MOCKTAIL_COMPAT_GUEST_ABI_H_
|
||||
|
||||
#include <elf.h>
|
||||
#include <string_view>
|
||||
|
||||
namespace mocktail::compat {
|
||||
|
||||
#if defined(__aarch64__)
|
||||
// Android ABI name as it appears in APK lib/ directories and build metadata.
|
||||
inline constexpr std::string_view kGuestAbi = "arm64-v8a";
|
||||
// APK split-config name carrying the guest native libraries.
|
||||
inline constexpr std::string_view kGuestApkSplitName = "config.arm64_v8a";
|
||||
// File name the payload store uses for the split APK.
|
||||
inline constexpr std::string_view kGuestSplitApkFile =
|
||||
"split_config.arm64_v8a.apk";
|
||||
// sha256 map key holding the split APK digest in payload metadata.
|
||||
inline constexpr std::string_view kGuestSplitApkHashKey = "arm64_v8a_split_apk";
|
||||
// Short CPU label for device metadata and user-facing strings.
|
||||
inline constexpr std::string_view kGuestCpuName = "aarch64";
|
||||
inline constexpr int kGuestElfMachine = EM_AARCH64;
|
||||
#elif defined(__x86_64__)
|
||||
inline constexpr std::string_view kGuestAbi = "x86_64";
|
||||
inline constexpr std::string_view kGuestApkSplitName = "config.x86_64";
|
||||
inline constexpr std::string_view kGuestSplitApkFile = "split_config.x86_64.apk";
|
||||
inline constexpr std::string_view kGuestSplitApkHashKey = "x86_64_split_apk";
|
||||
inline constexpr std::string_view kGuestCpuName = "x86_64";
|
||||
inline constexpr int kGuestElfMachine = EM_X86_64;
|
||||
#else
|
||||
#error "mocktail only supports aarch64 and x86_64 hosts"
|
||||
#endif
|
||||
|
||||
// APK zip entry holding the guest libroblox.so.
|
||||
inline constexpr std::string_view kGuestLibApkEntryPrefix = "lib/";
|
||||
|
||||
} // namespace mocktail::compat
|
||||
|
||||
#endif // MOCKTAIL_COMPAT_GUEST_ABI_H_
|
||||
@@ -0,0 +1,190 @@
|
||||
#ifndef MOCKTAIL_COMPAT_WEB_VIEW_PROTOCOL_CONTRACT_H_
|
||||
#define MOCKTAIL_COMPAT_WEB_VIEW_PROTOCOL_CONTRACT_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
|
||||
// Roblox's Subsystem<IWebViewProtocol> getter is not exported. The exported
|
||||
// WebViewProtocol.initializeAndroidWebViewProtocol calls it first, into a
|
||||
// stack slot, then reads the protocol from the returned holder:
|
||||
//
|
||||
// x86-64: lea slot(%rbp),%rbx; mov %rbx,%rdi; call getter;
|
||||
// mov (%rbx),%rbx; mov 0x18(%rbx),%rax
|
||||
// AArch64: add x8, sp, #slot; bl getter; ldr xN, [sp, #slot];
|
||||
// ldr x8, [xN, #0x18]
|
||||
//
|
||||
// These functions find that call site in the initializer's first bytes and
|
||||
// check the getter's own code. Only relocated or build-varying fields (stack
|
||||
// slots, frame sizes, PC-relative offsets, the call target) are masked.
|
||||
// Verified on x86_64 2.734.917, 2.736.1408 and 2.738.1397, and on arm64-v8a
|
||||
// 2.738.1397 and 2.740.931.
|
||||
|
||||
namespace mocktail::compat {
|
||||
|
||||
// Covers the call site in every verified build (x86-64 +0x27, AArch64 +0x34).
|
||||
inline constexpr std::size_t kWebViewProtocolInitializerScanBytes = 128;
|
||||
inline constexpr std::size_t kWebViewProtocolGetterBytesX86_64 = 44;
|
||||
inline constexpr std::size_t kWebViewProtocolGetterBytesArm64 = 60;
|
||||
|
||||
namespace web_view_protocol_contract_detail {
|
||||
|
||||
inline bool MatchesMasked(std::string_view code, std::size_t offset,
|
||||
std::string_view pattern,
|
||||
std::string_view wildcard) {
|
||||
if (offset > code.size() || code.size() - offset < pattern.size()) {
|
||||
return false;
|
||||
}
|
||||
for (std::size_t index = 0; index < pattern.size(); ++index) {
|
||||
if (wildcard[index] == 'x') continue;
|
||||
if (code[offset + index] != pattern[index]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// AArch64 instructions are little-endian words.
|
||||
inline std::uint32_t Word(std::string_view code, std::size_t index) {
|
||||
std::uint32_t word = 0;
|
||||
for (std::size_t byte = 0; byte < 4; ++byte) {
|
||||
word |= static_cast<std::uint32_t>(
|
||||
static_cast<unsigned char>(code[index * 4 + byte]))
|
||||
<< (8 * byte);
|
||||
}
|
||||
return word;
|
||||
}
|
||||
|
||||
// One AArch64 instruction word: bits outside `mask` may vary.
|
||||
struct MaskedWord {
|
||||
std::uint32_t mask;
|
||||
std::uint32_t value;
|
||||
};
|
||||
|
||||
inline constexpr std::uint32_t kExact = 0xffffffffU;
|
||||
// adrp Xd, page: immlo and immhi vary.
|
||||
inline constexpr std::uint32_t kAdrpMask = 0x9f00001fU;
|
||||
// add Xd, Xn, #imm12: imm12 varies.
|
||||
inline constexpr std::uint32_t kAddImmediateMask = 0xffc003ffU;
|
||||
|
||||
} // namespace web_view_protocol_contract_detail
|
||||
|
||||
// Returns the getter address called from the x86-64 initializer at
|
||||
// `address`, or nullopt unless the frame setup and exactly one call site
|
||||
// match.
|
||||
inline std::optional<std::uintptr_t> FindWebViewProtocolGetterCallX86_64(
|
||||
std::string_view code, std::uintptr_t address) {
|
||||
using web_view_protocol_contract_detail::MatchesMasked;
|
||||
// push %rbp; mov %rsp,%rbp
|
||||
if (!MatchesMasked(code, 0, "\x55\x48\x89\xe5", "....")) {
|
||||
return std::nullopt;
|
||||
}
|
||||
static constexpr std::string_view kCallSite(
|
||||
"\x48\x8d\x5d\x00\x48\x89\xdf\xe8\x00\x00\x00\x00\x48\x8b\x1b\x48\x8b\x43"
|
||||
"\x18",
|
||||
19);
|
||||
static constexpr std::string_view kCallSiteWildcard("...x....xxxx.......");
|
||||
static constexpr std::size_t kCallDisplacement = 8;
|
||||
const std::string_view window =
|
||||
code.substr(0, kWebViewProtocolInitializerScanBytes);
|
||||
std::optional<std::size_t> call_site;
|
||||
for (std::size_t offset = 0; offset < window.size(); ++offset) {
|
||||
if (MatchesMasked(window, offset, kCallSite, kCallSiteWildcard)) {
|
||||
if (call_site.has_value()) return std::nullopt;
|
||||
call_site = offset;
|
||||
}
|
||||
}
|
||||
if (!call_site.has_value()) return std::nullopt;
|
||||
std::int32_t displacement = 0;
|
||||
std::memcpy(&displacement, window.data() + *call_site + kCallDisplacement,
|
||||
sizeof(displacement));
|
||||
const std::uintptr_t next_instruction =
|
||||
address + *call_site + kCallDisplacement + sizeof(displacement);
|
||||
return next_instruction +
|
||||
static_cast<std::uintptr_t>(static_cast<std::intptr_t>(displacement));
|
||||
}
|
||||
|
||||
// The x86-64 getter stores the holder returned by the subsystem's acquire
|
||||
// into its result slot (%rdi) and returns that slot.
|
||||
inline bool HasWebViewProtocolGetterContractX86_64(std::string_view code) {
|
||||
return web_view_protocol_contract_detail::MatchesMasked(
|
||||
code, 0,
|
||||
std::string_view(
|
||||
"\x55\x48\x89\xe5\x53\x50\x48\x89\xfb\x8a\x05\x00\x00\x00\x00\x84\xc0"
|
||||
"\x74\x19\x48\x8d\x3d\x00\x00\x00\x00\xe8\x59\x00\x00\x00\x48\x89\x03"
|
||||
"\x48\x89\xd8\x48\x83\xc4\x08\x5b\x5d\xc3",
|
||||
kWebViewProtocolGetterBytesX86_64),
|
||||
"...........xxxx.......xxxx..................");
|
||||
}
|
||||
|
||||
// Returns the getter address called from the AArch64 initializer at
|
||||
// `address`, or nullopt unless exactly one call site matches.
|
||||
inline std::optional<std::uintptr_t> FindWebViewProtocolGetterCallArm64(
|
||||
std::string_view code, std::uintptr_t address) {
|
||||
using web_view_protocol_contract_detail::Word;
|
||||
const std::size_t words =
|
||||
code.substr(0, kWebViewProtocolInitializerScanBytes).size() / 4;
|
||||
std::optional<std::uintptr_t> getter;
|
||||
for (std::size_t index = 0; index + 4 <= words; ++index) {
|
||||
const std::uint32_t slot_address = Word(code, index);
|
||||
const std::uint32_t call = Word(code, index + 1);
|
||||
const std::uint32_t handle_load = Word(code, index + 2);
|
||||
const std::uint32_t protocol_load = Word(code, index + 3);
|
||||
// add x8, sp, #slot
|
||||
if ((slot_address & 0xffc003ffU) != 0x910003e8U) continue;
|
||||
// bl getter
|
||||
if ((call & 0xfc000000U) != 0x94000000U) continue;
|
||||
// ldr xN, [sp, #slot]
|
||||
if ((handle_load & 0xffc003e0U) != 0xf94003e0U) continue;
|
||||
const std::uint32_t slot = (slot_address >> 10) & 0xfffU;
|
||||
if (((handle_load >> 10) & 0xfffU) * 8 != slot) continue;
|
||||
// ldr x8, [xN, #0x18]
|
||||
const std::uint32_t handle_register = handle_load & 0x1fU;
|
||||
if (protocol_load != (0xf9400c08U | (handle_register << 5))) continue;
|
||||
if (getter.has_value()) return std::nullopt;
|
||||
// imm26 is a signed word offset from the bl instruction.
|
||||
const std::int64_t imm26 = call & 0x03ffffffU;
|
||||
const std::int64_t words_from_call =
|
||||
(imm26 & 0x02000000) != 0 ? imm26 - 0x04000000 : imm26;
|
||||
getter = address + (index + 1) * 4 +
|
||||
static_cast<std::uintptr_t>(words_from_call * 4);
|
||||
}
|
||||
return getter;
|
||||
}
|
||||
|
||||
// The AArch64 getter saves its result slot (x8) and stores the holder
|
||||
// returned by the subsystem's acquire there.
|
||||
inline bool HasWebViewProtocolGetterContractArm64(std::string_view code) {
|
||||
using namespace web_view_protocol_contract_detail;
|
||||
static constexpr MaskedWord kGetter[] = {
|
||||
{kExact, 0xa9be7bfdU}, // stp x29, x30, [sp, #-0x20]!
|
||||
{kExact, 0xf9000bf3U}, // str x19, [sp, #0x10]
|
||||
{kExact, 0x910003fdU}, // mov x29, sp
|
||||
{kAdrpMask, 0x90000009U}, // adrp x9, guard
|
||||
{kAddImmediateMask, 0x91000129U}, // add x9, x9, :lo12:guard
|
||||
{kExact, 0xaa0803f3U}, // mov x19, x8
|
||||
{kExact, 0x08dffd29U}, // ldarb w9, [x9]
|
||||
{kExact, 0x36000109U}, // tbz w9, #0, initialize
|
||||
{kAdrpMask, 0x90000000U}, // adrp x0, holder
|
||||
{kAddImmediateMask, 0x91000000U}, // add x0, x0, :lo12:holder
|
||||
{kExact, 0x94000017U}, // bl acquire
|
||||
{kExact, 0xf9000260U}, // str x0, [x19]
|
||||
{kExact, 0xf9400bf3U}, // ldr x19, [sp, #0x10]
|
||||
{kExact, 0xa8c27bfdU}, // ldp x29, x30, [sp], #0x20
|
||||
{kExact, 0xd65f03c0U}, // ret
|
||||
};
|
||||
static_assert(sizeof(kGetter) / sizeof(kGetter[0]) * 4 ==
|
||||
kWebViewProtocolGetterBytesArm64);
|
||||
if (code.size() < kWebViewProtocolGetterBytesArm64) return false;
|
||||
for (std::size_t index = 0; index < sizeof(kGetter) / sizeof(kGetter[0]);
|
||||
++index) {
|
||||
if ((Word(code, index) & kGetter[index].mask) != kGetter[index].value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace mocktail::compat
|
||||
|
||||
#endif // MOCKTAIL_COMPAT_WEB_VIEW_PROTOCOL_CONTRACT_H_
|
||||
@@ -48,9 +48,15 @@ struct PlatformIdentity {
|
||||
std::string manufacturer = "Mocktail";
|
||||
std::string model = "Mocktail Headless";
|
||||
std::string brand = "Mocktail";
|
||||
#if defined(__aarch64__)
|
||||
std::string device_code = "linux-arm64";
|
||||
std::string device_sku = "mocktail-arm64";
|
||||
std::string soc_model = "aarch64";
|
||||
#else
|
||||
std::string device_code = "linux-x86_64";
|
||||
std::string device_sku = "mocktail-x86_64";
|
||||
std::string soc_model = "x86_64";
|
||||
#endif
|
||||
};
|
||||
|
||||
struct RobloxCredentialView {
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
#if defined(__x86_64__)
|
||||
#include <xmmintrin.h>
|
||||
#endif
|
||||
#if defined(__aarch64__)
|
||||
#include <cstdint>
|
||||
#endif
|
||||
|
||||
namespace mocktail::audio {
|
||||
|
||||
@@ -22,16 +25,23 @@ class FmodThreadFloatingPointMode final {
|
||||
delete;
|
||||
|
||||
bool Enable(const char* thread_name) noexcept {
|
||||
#if defined(__x86_64__)
|
||||
#if defined(__x86_64__) || defined(__aarch64__)
|
||||
if (active_ || thread_name == nullptr) return false;
|
||||
const std::string_view name(thread_name);
|
||||
if (name != "FMOD mixer thread" && name != "FMOD feeder thread" &&
|
||||
name != "FMOD Convolution thread" && name != "FMOD Worker Thread") {
|
||||
return false;
|
||||
}
|
||||
#if defined(__x86_64__)
|
||||
const unsigned int control = _mm_getcsr();
|
||||
original_mode_ = control & kModeMask;
|
||||
_mm_setcsr(control | kModeMask);
|
||||
#else
|
||||
std::uint64_t control;
|
||||
__asm__ volatile("mrs %0, fpcr" : "=r"(control));
|
||||
original_mode_ = control & kModeMask;
|
||||
__asm__ volatile("msr fpcr, %0" ::"r"(control | kModeMask));
|
||||
#endif
|
||||
active_ = true;
|
||||
return true;
|
||||
#else
|
||||
@@ -41,11 +51,18 @@ class FmodThreadFloatingPointMode final {
|
||||
}
|
||||
|
||||
void Restore() noexcept {
|
||||
#if defined(__x86_64__)
|
||||
#if defined(__x86_64__) || defined(__aarch64__)
|
||||
if (active_) {
|
||||
// Restore only our two bits, preserving rounding, exception masks and
|
||||
// status flags set by the guest while the thread was attached.
|
||||
#if defined(__x86_64__)
|
||||
_mm_setcsr((_mm_getcsr() & ~kModeMask) | original_mode_);
|
||||
#else
|
||||
std::uint64_t control;
|
||||
__asm__ volatile("mrs %0, fpcr" : "=r"(control));
|
||||
__asm__ volatile("msr fpcr, %0" ::"r"((control & ~kModeMask) |
|
||||
original_mode_));
|
||||
#endif
|
||||
active_ = false;
|
||||
}
|
||||
#endif
|
||||
@@ -56,6 +73,13 @@ class FmodThreadFloatingPointMode final {
|
||||
static constexpr unsigned int kModeMask = (1U << 15) | (1U << 6);
|
||||
unsigned int original_mode_ = 0;
|
||||
bool active_ = false;
|
||||
#elif defined(__aarch64__)
|
||||
// FPCR FZ flushes single/double subnormals; FZ16 covers the half-precision
|
||||
// path used by some voice DSP filters.
|
||||
static constexpr std::uint64_t kModeMask =
|
||||
(std::uint64_t{1} << 24) | (std::uint64_t{1} << 19);
|
||||
std::uint64_t original_mode_ = 0;
|
||||
bool active_ = false;
|
||||
#endif
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
#ifndef MOCKTAIL_GRAPHICS_CHROME_TRACE_WRITER_H_
|
||||
#define MOCKTAIL_GRAPHICS_CHROME_TRACE_WRITER_H_
|
||||
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
#include <initializer_list>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
|
||||
namespace mocktail {
|
||||
namespace graphics {
|
||||
|
||||
// Environment variable naming the trace file the Vulkan adapter writes.
|
||||
inline constexpr char kProfileTraceEnvironment[] = "MOCKTAIL_PROFILE_TRACE";
|
||||
|
||||
struct TraceArg {
|
||||
const char* key;
|
||||
std::int64_t value;
|
||||
};
|
||||
|
||||
// CLOCK_MONOTONIC in nanoseconds.
|
||||
std::uint64_t TraceClockNanos();
|
||||
// CPU time used so far by the calling thread, in nanoseconds.
|
||||
std::uint64_t TraceThreadCpuNanos();
|
||||
// CPU time used so far by every thread of the process, in nanoseconds.
|
||||
std::uint64_t TraceProcessCpuNanos();
|
||||
|
||||
// CPU time spent between two successive presents.
|
||||
struct FrameCpuSample {
|
||||
double process_ms = 0;
|
||||
// Set only when the previous present came from the same thread; thread CPU
|
||||
// clocks of different threads cannot be subtracted.
|
||||
bool has_thread = false;
|
||||
double thread_ms = 0;
|
||||
};
|
||||
|
||||
// Turns CPU clocks read at each present into per-frame CPU time.
|
||||
// Thread-safe.
|
||||
class FrameCpuSampler final {
|
||||
public:
|
||||
// Returns false for the first present, which ends no frame.
|
||||
bool Sample(std::uint64_t thread_id, std::uint64_t thread_cpu_ns,
|
||||
std::uint64_t process_cpu_ns, FrameCpuSample* sample);
|
||||
|
||||
private:
|
||||
std::mutex mutex_;
|
||||
bool has_previous_ = false;
|
||||
std::uint64_t previous_thread_id_ = 0;
|
||||
std::uint64_t previous_thread_cpu_ns_ = 0;
|
||||
std::uint64_t previous_process_cpu_ns_ = 0;
|
||||
};
|
||||
|
||||
// Writes the Trace Event Format JSON array read by chrome://tracing and
|
||||
// ui.perfetto.dev. Recording threads only format into a shared buffer; a
|
||||
// background thread owns file writes, so disk stalls do not land inside the
|
||||
// measured calls. Events are written in arrival order. Each write ends the
|
||||
// file with the closing bracket, so a killed session leaves a loadable trace
|
||||
// holding everything written before it died.
|
||||
// Names, categories, and keys must outlive the call.
|
||||
class ChromeTraceWriter final {
|
||||
public:
|
||||
static std::unique_ptr<ChromeTraceWriter> Open(
|
||||
const std::filesystem::path& path, std::string* error);
|
||||
|
||||
~ChromeTraceWriter();
|
||||
ChromeTraceWriter(const ChromeTraceWriter&) = delete;
|
||||
ChromeTraceWriter& operator=(const ChromeTraceWriter&) = delete;
|
||||
|
||||
// A complete ("X") slice on the calling thread. Slices on one thread must
|
||||
// nest, which scoped timing gives.
|
||||
void Slice(const char* name, const char* category, std::uint64_t start_ns,
|
||||
std::uint64_t end_ns, std::initializer_list<TraceArg> args = {});
|
||||
void Slice(const char* name, const char* category, std::uint64_t start_ns,
|
||||
std::uint64_t end_ns, const TraceArg* args,
|
||||
std::size_t arg_count);
|
||||
// A counter ("C") sample; each name becomes one counter track.
|
||||
void Counter(const char* name, std::uint64_t timestamp_ns, double value);
|
||||
|
||||
// Returns once every event recorded before the call is on disk.
|
||||
void Flush();
|
||||
// Flushes, closes the file, and drops later events. Idempotent.
|
||||
void Close();
|
||||
|
||||
private:
|
||||
explicit ChromeTraceWriter(std::FILE* file);
|
||||
void Append(const char* event, std::size_t size);
|
||||
void WriterLoop();
|
||||
void WritePending();
|
||||
|
||||
std::FILE* file_;
|
||||
const int owner_pid_;
|
||||
std::mutex file_mutex_; // Guards file_ and spare_.
|
||||
std::string spare_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable wake_;
|
||||
std::string pending_;
|
||||
bool first_event_ = true;
|
||||
bool closed_ = false;
|
||||
bool stopping_ = false;
|
||||
std::thread writer_;
|
||||
};
|
||||
|
||||
// The process trace named by MOCKTAIL_PROFILE_TRACE, opened on first use.
|
||||
// Null when profiling is off or the file could not be opened. The writer is
|
||||
// never destroyed; it is closed when the process exits normally.
|
||||
ChromeTraceWriter* ActiveProfileTrace();
|
||||
|
||||
// Times its own lifetime as one slice. A null writer records nothing.
|
||||
class TraceScope final {
|
||||
public:
|
||||
TraceScope(ChromeTraceWriter* writer, const char* name,
|
||||
const char* category)
|
||||
: writer_(writer),
|
||||
name_(name),
|
||||
category_(category),
|
||||
start_ns_(writer != nullptr ? TraceClockNanos() : 0) {}
|
||||
~TraceScope() {
|
||||
if (writer_ != nullptr) {
|
||||
writer_->Slice(name_, category_, start_ns_, TraceClockNanos(), args_,
|
||||
arg_count_);
|
||||
}
|
||||
}
|
||||
TraceScope(const TraceScope&) = delete;
|
||||
TraceScope& operator=(const TraceScope&) = delete;
|
||||
|
||||
// Keeps the first kMaxArgs arguments.
|
||||
void Arg(const char* key, std::int64_t value) {
|
||||
if (writer_ != nullptr && arg_count_ < kMaxArgs) {
|
||||
args_[arg_count_++] = {key, value};
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr std::size_t kMaxArgs = 4;
|
||||
ChromeTraceWriter* writer_;
|
||||
const char* name_;
|
||||
const char* category_;
|
||||
std::uint64_t start_ns_;
|
||||
TraceArg args_[kMaxArgs]{};
|
||||
std::size_t arg_count_ = 0;
|
||||
};
|
||||
|
||||
} // namespace graphics
|
||||
} // namespace mocktail
|
||||
|
||||
#endif // MOCKTAIL_GRAPHICS_CHROME_TRACE_WRITER_H_
|
||||
@@ -66,6 +66,14 @@ struct EtcDecodeJob {
|
||||
void DecodeEtcJobs(EtcDecodeJob* jobs, std::size_t count,
|
||||
unsigned worker_count);
|
||||
|
||||
// Calls run(context) worker_count times, once on the caller and the rest on
|
||||
// pooled decode workers that run alongside it, and returns when every call
|
||||
// has returned. `run` must be safe to call from several threads at once, so
|
||||
// it should drain a shared queue. When the pool is busy with another batch,
|
||||
// or no worker could be started, run is called on the caller alone.
|
||||
void RunOnDecodeWorkers(void (*run)(void*), void* context,
|
||||
unsigned worker_count);
|
||||
|
||||
} // namespace mocktail::graphics
|
||||
|
||||
#endif // MOCKTAIL_GRAPHICS_ETC2_DECODER_H_
|
||||
@@ -47,17 +47,30 @@ inline constexpr std::uint32_t kSmallTextureMaxExtent = 64;
|
||||
inline constexpr std::uint32_t kDefaultSmallTextureUpscale = 4;
|
||||
std::uint32_t SmallTextureUpscale(const char* value);
|
||||
|
||||
// Staging for decoded uploads is carved out of host-visible blocks this
|
||||
// large; an upload that needs more gets a block of its own.
|
||||
inline constexpr VkDeviceSize kEtc2StagingBlockBytes = 16 * 1024 * 1024;
|
||||
|
||||
// A timeline semaphore and the value an asynchronous decode will signal.
|
||||
// `semaphore` is VK_NULL_HANDLE when the decode already finished on the
|
||||
// calling thread and the submit needs no extra wait.
|
||||
struct Etc2SubmitWait {
|
||||
VkSemaphore semaphore = VK_NULL_HANDLE;
|
||||
std::uint64_t value = 0;
|
||||
};
|
||||
|
||||
// Reports ETC2/EAC support on hosts without native ETC2 (desktop GPUs) and
|
||||
// stores those textures decoded. Images are created with the host format;
|
||||
// each staged upload into one is redirected to a host-visible staging buffer
|
||||
// that is filled by decoding the application's staging bytes when the
|
||||
// command buffer is submitted. Every submit decodes again, as a native copy
|
||||
// re-reads its source on each execution.
|
||||
// Staging buffers live until their command buffer is begun, reset or freed.
|
||||
// Staging ranges live until their command buffer is begun, reset or freed.
|
||||
// MOCKTAIL_DISABLE_ETC2_EMULATION=1 turns the emulation off.
|
||||
class VulkanEtc2Emulation final {
|
||||
public:
|
||||
VulkanEtc2Emulation();
|
||||
explicit VulkanEtc2Emulation(
|
||||
VkDeviceSize staging_block_bytes = kEtc2StagingBlockBytes);
|
||||
~VulkanEtc2Emulation();
|
||||
VulkanEtc2Emulation(const VulkanEtc2Emulation&) = delete;
|
||||
VulkanEtc2Emulation& operator=(const VulkanEtc2Emulation&) = delete;
|
||||
@@ -66,10 +79,14 @@ class VulkanEtc2Emulation final {
|
||||
bool PhysicalDeviceNeedsEmulation(VkPhysicalDevice physical_device,
|
||||
PFN_vkGetPhysicalDeviceFeatures host);
|
||||
|
||||
// `timeline_semaphore` states whether the device was created with the
|
||||
// timelineSemaphore feature enabled. Without it every decode runs on the
|
||||
// calling thread.
|
||||
void RegisterDevice(VkDevice device, VkPhysicalDevice physical_device,
|
||||
bool emulated,
|
||||
const VkPhysicalDeviceMemoryProperties& memory,
|
||||
PFN_vkGetDeviceProcAddr get_device_proc_addr);
|
||||
PFN_vkGetDeviceProcAddr get_device_proc_addr,
|
||||
bool timeline_semaphore = false);
|
||||
void DestroyDevice(VkDevice device);
|
||||
|
||||
VkResult CreateImage(VkDevice device, const VkImageCreateInfo* create_info,
|
||||
@@ -112,12 +129,27 @@ class VulkanEtc2Emulation final {
|
||||
const VkCommandBuffer* secondaries);
|
||||
|
||||
// Decodes every upload recorded into these command buffers and the
|
||||
// secondary command buffers they execute. Large batches decode on worker
|
||||
// threads; this returns once every upload is decoded.
|
||||
void PrepareSubmit(const VkCommandBuffer* command_buffers,
|
||||
std::uint32_t count);
|
||||
// secondary command buffers they execute.
|
||||
//
|
||||
// With `allow_async` on a device that has a timeline semaphore, the decode
|
||||
// runs on worker threads, and so does the gather of the compressed bytes
|
||||
// whenever the application already has them mapped. The returned semaphore
|
||||
// and value must then be added to the submit's waits, so the GPU copy
|
||||
// cannot execute before the decode finishes. Values are signalled in the
|
||||
// order they are handed out.
|
||||
//
|
||||
// Those threads read the application's source bytes after this returns,
|
||||
// which Vulkan allows: the application may not write them between the
|
||||
// submit and the copy's completion. Unmapping or freeing that memory waits
|
||||
// for the decodes still reading it.
|
||||
//
|
||||
// Returns `{VK_NULL_HANDLE, 0}` when there was nothing to decode, when
|
||||
// `allow_async` is false, or when the device has no timeline semaphore. In
|
||||
// those cases every upload is already decoded when this returns.
|
||||
Etc2SubmitWait PrepareSubmit(const VkCommandBuffer* command_buffers,
|
||||
std::uint32_t count, bool allow_async = false);
|
||||
// Destroys the staging buffers owned by a command buffer that is no longer
|
||||
// pending.
|
||||
// pending, after waiting for any decode still writing into them.
|
||||
void ReleaseCommandBuffer(VkCommandBuffer command_buffer);
|
||||
|
||||
struct State;
|
||||
|
||||
@@ -152,6 +152,10 @@ struct MouseMotionEvent {
|
||||
float delta_x = 0.0f;
|
||||
float delta_y = 0.0f;
|
||||
std::uint32_t buttons = 0;
|
||||
// True while the window holds relative mouse mode. The absolute coordinates
|
||||
// are meaningless then: X11 reports zeroes, Wayland reports a position that
|
||||
// accumulates the deltas and can leave the window entirely.
|
||||
bool relative = false;
|
||||
};
|
||||
|
||||
struct MouseButtonEvent {
|
||||
@@ -160,6 +164,8 @@ struct MouseButtonEvent {
|
||||
std::uint8_t clicks = 0;
|
||||
float x = 0.0f;
|
||||
float y = 0.0f;
|
||||
// See MouseMotionEvent::relative.
|
||||
bool relative = false;
|
||||
};
|
||||
|
||||
struct MouseWheelEvent {
|
||||
@@ -167,6 +173,8 @@ struct MouseWheelEvent {
|
||||
float delta_y = 0.0f;
|
||||
float mouse_x = 0.0f;
|
||||
float mouse_y = 0.0f;
|
||||
// See MouseMotionEvent::relative.
|
||||
bool relative = false;
|
||||
};
|
||||
|
||||
struct TouchEvent {
|
||||
|
||||
@@ -33,6 +33,8 @@ struct CommandLineOptions {
|
||||
// Requests one explicit launch of the provider latest without promoting it
|
||||
// into the managed payload state.
|
||||
bool force_run_latest = false;
|
||||
// Chrome trace file the Vulkan adapter writes; empty when not profiling.
|
||||
std::string profile_trace_path;
|
||||
};
|
||||
|
||||
struct CommandLineParseResult {
|
||||
|
||||
@@ -13,11 +13,14 @@ namespace mocktail {
|
||||
namespace runtime {
|
||||
|
||||
struct DiscordRpcActivity {
|
||||
std::string name;
|
||||
std::string details;
|
||||
std::string state;
|
||||
std::optional<int64_t> start_timestamp;
|
||||
std::string large_image;
|
||||
std::string large_text;
|
||||
std::string small_image;
|
||||
std::string small_text;
|
||||
std::string button_label;
|
||||
std::string button_url;
|
||||
};
|
||||
@@ -27,7 +30,8 @@ std::string BuildDiscordJoinUrl(const RobloxExperienceLaunchRequest& request);
|
||||
DiscordRpcActivity BuildDiscordRpcActivity(
|
||||
const DiscordRpcConfig& config, RobloxExperiencePresencePhase phase,
|
||||
const RobloxExperienceLaunchRequest* request, std::string place_name,
|
||||
int64_t session_started_at, std::string place_icon_url = {});
|
||||
int64_t session_started_at, std::string place_icon_url = {},
|
||||
std::string creator_name = {});
|
||||
|
||||
// Maintains a direct, unauthenticated Discord Desktop RPC connection. The
|
||||
// worker owns all network and IPC work; lifecycle notifications only replace
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#ifndef MOCKTAIL_RUNTIME_ENGINE_PUMP_REST_H_
|
||||
#define MOCKTAIL_RUNTIME_ENGINE_PUMP_REST_H_
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace mocktail::runtime {
|
||||
|
||||
// The engine posts its per-frame main-thread step at a time of its own
|
||||
// choosing, with no signal the host can block on, so the host main thread
|
||||
// polls nativeCallMessagesFromMainThread. An empty poll costs a few
|
||||
// microseconds; polled back to back it burns a core.
|
||||
//
|
||||
// Between polls the thread rests for kEnginePumpRestNs. A post is then picked
|
||||
// up at most kEnginePumpRestNs + timer slack + wake latency late, far under
|
||||
// the engine's sub-millisecond slack.
|
||||
//
|
||||
// How it rests decides the clock. Under a power-saving governor the CPU clocks
|
||||
// a bursty core down unless some core stays awake, and the engine's render
|
||||
// thread then runs slower and drops frames. So:
|
||||
// kSleep nanosleep. The core idles. Correct only when the governor holds
|
||||
// the clock up on its own (performance, which GameMode sets).
|
||||
// kTpause TPAUSE in C0.2. The core stays awake at reduced power, the clock
|
||||
// holds, and the OS books the time as busy. Needs WAITPKG.
|
||||
// kSpin No rest. The core stays awake at full power.
|
||||
inline constexpr uint64_t kEnginePumpRestNs = 100'000;
|
||||
// Timer slack the calling thread is set to; the kernel default of 50 us would
|
||||
// otherwise stretch every sleep.
|
||||
inline constexpr uint64_t kEnginePumpTimerSlackNs = 10'000;
|
||||
// Shallow C-state exit plus scheduler latency on the host, for the bound.
|
||||
inline constexpr uint64_t kShallowWakeNs = 50'000;
|
||||
|
||||
enum class EnginePumpRestMode { kSleep, kTpause, kSpin };
|
||||
|
||||
const char* EnginePumpRestModeName(EnginePumpRestMode mode);
|
||||
|
||||
struct EnginePumpRestInputs {
|
||||
bool governor_performance = false;
|
||||
bool cpu_has_waitpkg = false;
|
||||
// MOCKTAIL_ENGINE_PUMP_REST: "sleep", "tpause" or "spin". Null, empty or
|
||||
// unknown defers to the policy; "tpause" without WAITPKG does too.
|
||||
const char* override = nullptr;
|
||||
};
|
||||
|
||||
EnginePumpRestMode ChooseEnginePumpRestMode(const EnginePumpRestInputs& inputs);
|
||||
|
||||
// True when the file holds "performance". `path` is a cpufreq
|
||||
// scaling_governor file; cpu0's stands for the machine.
|
||||
bool CpuGovernorIsPerformance(const char* path);
|
||||
|
||||
bool CpuHasWaitPkg();
|
||||
|
||||
// The mode chosen from the host on first use.
|
||||
EnginePumpRestMode ActiveEnginePumpRestMode();
|
||||
|
||||
// Rests the calling thread in the given mode and returns the rest length, 0
|
||||
// for kSpin. The first call lowers the thread's timer slack to
|
||||
// kEnginePumpTimerSlackNs.
|
||||
uint64_t RestAfterEnginePump(EnginePumpRestMode mode);
|
||||
inline uint64_t RestAfterEnginePump() {
|
||||
return RestAfterEnginePump(ActiveEnginePumpRestMode());
|
||||
}
|
||||
|
||||
} // namespace mocktail::runtime
|
||||
|
||||
#endif // MOCKTAIL_RUNTIME_ENGINE_PUMP_REST_H_
|
||||
@@ -1,6 +1,8 @@
|
||||
#ifndef MOCKTAIL_RUNTIME_GAME_MODE_H_
|
||||
#define MOCKTAIL_RUNTIME_GAME_MODE_H_
|
||||
|
||||
#include <sched.h>
|
||||
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
@@ -22,6 +24,7 @@ enum class GameModeSessionState {
|
||||
kDisabled,
|
||||
kUnavailable,
|
||||
kRequestFailed,
|
||||
kDeclinedCorePinning,
|
||||
kAlreadyActive,
|
||||
kActive,
|
||||
kStopped,
|
||||
@@ -43,9 +46,37 @@ struct GameModeClientApi {
|
||||
ErrorFn error_string = nullptr;
|
||||
};
|
||||
|
||||
// The CPU affinity calls, injectable so tests exercise the restore without
|
||||
// moving the threads they run on.
|
||||
struct CpuAffinityApi {
|
||||
// Reads the calling thread's permitted CPUs. GameMode pins every thread
|
||||
// alike, so one thread's mask is enough to detect the pin.
|
||||
using GetFn = int (*)(cpu_set_t* mask);
|
||||
// Applies `mask` to every thread of this process, not only the caller.
|
||||
// Returns 0 when each live thread took it.
|
||||
using SetFn = int (*)(const cpu_set_t* mask);
|
||||
|
||||
GetFn get = nullptr;
|
||||
SetFn set = nullptr;
|
||||
};
|
||||
|
||||
CpuAffinityApi HostCpuAffinityApi();
|
||||
|
||||
// True when `after` permits a strict subset of the CPUs `before` permits.
|
||||
// An equal, wider or merely relocated set is not a narrowing.
|
||||
bool CpuAffinityNarrowed(const cpu_set_t& before, const cpu_set_t& after);
|
||||
|
||||
// Owns at most one ref-counted GameMode request. Missing host support and
|
||||
// daemon rejection remain nonfatal because GameMode is an optimization, not a
|
||||
// correctness dependency.
|
||||
//
|
||||
// GameMode pins the calling process to the host's fastest cores when it sees a
|
||||
// wide core-speed spread. Roblox spreads its own work over a worker pool, so
|
||||
// that pin concentrates the load onto a couple of cores instead of helping,
|
||||
// and the daemon re-applies it every few seconds, so correcting the mask in
|
||||
// place does not hold. Under `auto`, a request that narrows the affinity is
|
||||
// released again: ending the request is what releases the pin. `on` is an
|
||||
// explicit choice and keeps the pinned session.
|
||||
class GameModeSession final {
|
||||
public:
|
||||
GameModeSession() = default;
|
||||
@@ -59,6 +90,8 @@ class GameModeSession final {
|
||||
static GameModeSession Start(GameModePolicy policy);
|
||||
static GameModeSession StartWithClientForTesting(
|
||||
GameModePolicy policy, GameModeClientApi api);
|
||||
static GameModeSession StartWithClientForTesting(
|
||||
GameModePolicy policy, GameModeClientApi api, CpuAffinityApi affinity);
|
||||
|
||||
GameModeSessionState state() const { return state_; }
|
||||
const std::string& detail() const { return detail_; }
|
||||
@@ -73,6 +106,7 @@ class GameModeSession final {
|
||||
private:
|
||||
static GameModeSession StartBound(GameModePolicy policy,
|
||||
GameModeClientApi api,
|
||||
CpuAffinityApi affinity,
|
||||
void* library_handle);
|
||||
void CloseLibrary();
|
||||
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
#ifndef MOCKTAIL_RUNTIME_ROBLOX_ACCOUNT_BRIDGE_H_
|
||||
#define MOCKTAIL_RUNTIME_ROBLOX_ACCOUNT_BRIDGE_H_
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
|
||||
#include "mocktail/status.h"
|
||||
#include "runtime/roblox_game_session_native_adapter.h"
|
||||
|
||||
namespace mocktail {
|
||||
namespace runtime {
|
||||
|
||||
// Exact JNI entrypoints behind the APK AccountProtocol device-integrity
|
||||
// handlers: JNIAccountProtocol name getters and MessageBus raw handlers.
|
||||
struct RobloxAccountProtocolSymbols {
|
||||
using GetStringFn = jstring (*)(JNIEnv*, jclass);
|
||||
|
||||
GetStringFn get_protocol_name = nullptr;
|
||||
GetStringFn get_device_integrity_available_method_name = nullptr;
|
||||
GetStringFn get_integrity_token_method_name = nullptr;
|
||||
GetStringFn get_support_key = nullptr;
|
||||
GetStringFn get_token_key = nullptr;
|
||||
GetStringFn get_result_key = nullptr;
|
||||
void (*set_request_handler_raw)(JNIEnv*, jobject, jstring, jstring,
|
||||
jobject) = nullptr;
|
||||
void (*clear_request_handler)(JNIEnv*, jobject, jstring, jstring) = nullptr;
|
||||
|
||||
bool complete() const {
|
||||
return get_protocol_name && get_device_integrity_available_method_name &&
|
||||
get_integrity_token_method_name && get_support_key &&
|
||||
get_token_key && get_result_key && set_request_handler_raw &&
|
||||
clear_request_handler;
|
||||
}
|
||||
};
|
||||
|
||||
struct RobloxAccountProtocolObjects {
|
||||
jobject message_bus = nullptr;
|
||||
void* context = nullptr;
|
||||
jobject (*create_request_handler)(void*, std::shared_ptr<void>,
|
||||
std::string (*)(void*, JNIEnv*,
|
||||
jstring)) = nullptr;
|
||||
void (*clear_request_handler)(void*, jobject) = nullptr;
|
||||
|
||||
bool complete() const {
|
||||
return message_bus && context && create_request_handler &&
|
||||
clear_request_handler;
|
||||
}
|
||||
};
|
||||
|
||||
// Answers AccountProtocol device-integrity requests for a host that cannot
|
||||
// produce Play Integrity tokens. No integrity token is ever produced.
|
||||
//
|
||||
// DeviceIntegrityAvailable reports no support. The APK handler always reports
|
||||
// support, so this answer differs from Android: it tells Roblox's challenge
|
||||
// flow up front that no token can come, instead of letting it request one.
|
||||
//
|
||||
// GetIntegrityToken returns at once with an empty token and
|
||||
// TOKEN_PROVIDER_UNINITIALIZED, the APK's answer when its Play token provider
|
||||
// never initialized. The APK answers INVALID_NONCE for a request without a
|
||||
// requestHash; this bridge never inspects the request, so it cannot.
|
||||
// LuaApp bounds each token request with its
|
||||
// DeviceIntegrityNativeTimeoutMilliseconds flag; an immediate answer keeps a
|
||||
// login challenge from sitting out that bound.
|
||||
class RobloxAccountBridge final {
|
||||
public:
|
||||
RobloxAccountBridge(JniEnvironmentProvider environment,
|
||||
RobloxAccountProtocolSymbols symbols,
|
||||
RobloxAccountProtocolObjects objects);
|
||||
~RobloxAccountBridge();
|
||||
RobloxAccountBridge(const RobloxAccountBridge&) = delete;
|
||||
RobloxAccountBridge& operator=(const RobloxAccountBridge&) = delete;
|
||||
|
||||
Status Initialize();
|
||||
Status Shutdown();
|
||||
|
||||
private:
|
||||
struct State;
|
||||
Status ShutdownLocked();
|
||||
|
||||
const JniEnvironmentProvider environment_;
|
||||
const RobloxAccountProtocolSymbols symbols_;
|
||||
const RobloxAccountProtocolObjects objects_;
|
||||
// Serializes lifecycle only. Native dispatch never holds this mutex.
|
||||
std::mutex lifecycle_mutex_;
|
||||
std::shared_ptr<State> state_;
|
||||
};
|
||||
|
||||
} // namespace runtime
|
||||
} // namespace mocktail
|
||||
|
||||
#endif // MOCKTAIL_RUNTIME_ROBLOX_ACCOUNT_BRIDGE_H_
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
#include <jni.h>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
@@ -17,6 +18,7 @@
|
||||
#include "runtime/roblox_experience_launch_bridge.h"
|
||||
#include "runtime/roblox_experience_presence.h"
|
||||
#include "runtime/roblox_fresh_game_launch_controller.h"
|
||||
#include "runtime/roblox_account_bridge.h"
|
||||
#include "runtime/roblox_permissions_bridge.h"
|
||||
#include "runtime/roblox_web_view_bridge.h"
|
||||
#include "runtime/webview_roblox_cookie.h"
|
||||
@@ -120,7 +122,8 @@ class RobloxExperienceComposition final {
|
||||
RobloxExperienceSurfaceProvider surface_provider = {},
|
||||
RobloxExperiencePresenceObserver presence_observer = {},
|
||||
bool clear_persisted_web_view_cookie = false,
|
||||
bool microphone_enabled = false);
|
||||
bool microphone_enabled = false,
|
||||
RobloxAccountProtocolSymbols account_symbols = {});
|
||||
~RobloxExperienceComposition();
|
||||
|
||||
RobloxExperienceComposition(const RobloxExperienceComposition&) = delete;
|
||||
@@ -162,6 +165,7 @@ class RobloxExperienceComposition final {
|
||||
bool visible = true;
|
||||
bool back_navigation_disabled = false;
|
||||
bool show_domain_as_title = false;
|
||||
bool close_when_challenge_solved = false;
|
||||
};
|
||||
|
||||
static Status DispatchLaunch(void* context,
|
||||
@@ -201,8 +205,11 @@ class RobloxExperienceComposition final {
|
||||
const WebSurfacePresentation& presentation);
|
||||
// WebViewProtocol and BrowserService are two logical transports over the
|
||||
// APK's single physical WebView container. Either protocol may close or
|
||||
// mutate the surface that the other one opened.
|
||||
Status CloseWebSurface();
|
||||
// mutate the surface that the other one opened. A nonzero
|
||||
// expected_logical_generation closes only that surface.
|
||||
Status CloseWebSurface(uint64_t expected_logical_generation = 0);
|
||||
// Closes a solved challenge that Roblox left open past its grace period.
|
||||
Status CloseUnclaimedSolvedChallenge();
|
||||
void HandleWebSurfaceExit(uint64_t process_generation);
|
||||
Status Dispatch(const RobloxExperienceLaunchRequest& request);
|
||||
Status PromoteAuthenticatedSession();
|
||||
@@ -229,6 +236,7 @@ class RobloxExperienceComposition final {
|
||||
const RobloxWebViewMessageBusSymbols web_view_symbols_;
|
||||
const RobloxBrowserServiceSymbols browser_service_symbols_;
|
||||
const RobloxPermissionsMessageBusSymbols permissions_symbols_;
|
||||
const RobloxAccountProtocolSymbols account_symbols_;
|
||||
const bool microphone_enabled_;
|
||||
const RobloxGameSessionSymbols game_symbols_;
|
||||
const RobloxExperienceJniFactory jni_factory_;
|
||||
@@ -248,6 +256,8 @@ class RobloxExperienceComposition final {
|
||||
std::unique_ptr<RobloxWebViewBridge> web_view_bridge_;
|
||||
std::unique_ptr<RobloxBrowserServiceBridge> browser_service_bridge_;
|
||||
std::unique_ptr<RobloxPermissionsBridge> permissions_bridge_;
|
||||
// Optional: a payload without the AccountProtocol entrypoints still starts.
|
||||
std::unique_ptr<RobloxAccountBridge> account_bridge_;
|
||||
std::shared_ptr<WebViewHelperProcess> web_surface_process_;
|
||||
std::shared_ptr<WebSurfaceExitTarget> web_surface_exit_target_;
|
||||
std::shared_ptr<LifecycleTarget> lifecycle_target_;
|
||||
@@ -257,6 +267,13 @@ class RobloxExperienceComposition final {
|
||||
uint64_t web_surface_logical_generation_ = 0;
|
||||
uint64_t next_web_surface_process_generation_ = 1;
|
||||
uint64_t next_web_surface_logical_generation_ = 1;
|
||||
// The current surface closes as soon as its solved challenge is forwarded.
|
||||
bool web_surface_close_when_challenge_solved_ = false;
|
||||
// Set when a solved challenge is forwarded; applies only to that logical
|
||||
// surface generation.
|
||||
std::optional<std::chrono::steady_clock::time_point>
|
||||
solved_challenge_close_deadline_;
|
||||
uint64_t solved_challenge_logical_generation_ = 0;
|
||||
SecureWebViewRobloxCookie web_view_cookie_;
|
||||
std::string web_view_cookie_initialization_error_;
|
||||
bool web_view_cookie_synchronized_ = false;
|
||||
|
||||
@@ -40,9 +40,10 @@ struct AndroidKeyMapping {
|
||||
// through with an ABI-incompatible numeric value.
|
||||
AndroidKeyMapping MapSdlKeyToAndroid(uint32_t sdl_scancode, uint32_t sdl_key = 0);
|
||||
|
||||
// Mirrors the APK's MotionEvent.getActionButton() - 1 conversion. SDL button
|
||||
// numbers are not numerically compatible with Android button bit values.
|
||||
int32_t MapSdlMouseButtonToAndroid(uint8_t sdl_button);
|
||||
// Translates SDL button numbers to the nativePassMouseButton argument.
|
||||
// The first three are Roblox's zero-based MouseButton1/2/3 indices, not Android
|
||||
// MotionEvent button bits.
|
||||
int32_t MapSdlMouseButtonToRoblox(uint8_t sdl_button);
|
||||
|
||||
int32_t MapSdlGamepadButtonToAndroid(uint8_t sdl_button);
|
||||
int32_t RobloxGamepadType(platform::GamepadFamily family);
|
||||
@@ -223,6 +224,10 @@ class RobloxInputRouter final {
|
||||
Status DisconnectGamepadLocked(ActiveGamepad& gamepad);
|
||||
Status DisconnectGamepadsLocked();
|
||||
Status ReleasePressedInputsLocked();
|
||||
// Keeps mouse_x_/mouse_y_ where they are for an event that carries no
|
||||
// usable position, clamped to the current viewport. Before any absolute
|
||||
// position has been seen, the held position is the viewport center.
|
||||
void HoldPointerLocked(const platform::SurfaceCoordinateTransform& transform);
|
||||
int32_t AllocatePointerIdLocked() const;
|
||||
std::vector<ActiveTouch>::iterator FindTouchIteratorLocked(int64_t touch_id,
|
||||
int64_t finger_id);
|
||||
@@ -238,8 +243,13 @@ class RobloxInputRouter final {
|
||||
std::vector<ActiveTouch> active_touches_;
|
||||
std::vector<ActiveKey> active_keys_;
|
||||
std::vector<ActiveGamepad> gamepads_;
|
||||
// Last known pointer position in guest units. Relative-mode motion, and
|
||||
// wheel or button events with zero coordinates, do not move it: the pointer
|
||||
// stays where it was captured while the deltas pass through.
|
||||
float mouse_x_ = 0.0f;
|
||||
float mouse_y_ = 0.0f;
|
||||
// True once an absolute position has been received since Activate.
|
||||
bool pointer_anchored_ = false;
|
||||
bool raw_mouse_ = false;
|
||||
};
|
||||
|
||||
|
||||
@@ -19,6 +19,13 @@ inline constexpr std::size_t kMaximumRobloxLaunchUriBytes = 64 * 1024;
|
||||
Status ParseRobloxLaunchUri(std::string_view uri,
|
||||
RobloxExperienceLaunchRequest* request);
|
||||
|
||||
// Converts a WebView launchGame command
|
||||
// ({"functionName":"launchGame","params":{"request":{...}}}) into the same
|
||||
// contract. Returns kUnsupported for other commands and kInvalidArgument for
|
||||
// a malformed launchGame request.
|
||||
Status ParseRobloxWebViewLaunchGame(std::string_view command,
|
||||
RobloxExperienceLaunchRequest* request);
|
||||
|
||||
} // namespace runtime
|
||||
} // namespace mocktail
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#ifndef MOCKTAIL_RUNTIME_ROBLOX_PLATFORM_WEB_SYMBOLS_H_
|
||||
#define MOCKTAIL_RUNTIME_ROBLOX_PLATFORM_WEB_SYMBOLS_H_
|
||||
|
||||
#include "runtime/roblox_account_bridge.h"
|
||||
#include "runtime/roblox_browser_service_bridge.h"
|
||||
#include "runtime/roblox_permissions_bridge.h"
|
||||
#include "runtime/roblox_web_view_bridge.h"
|
||||
@@ -15,6 +16,8 @@ struct RobloxPlatformWebSymbols {
|
||||
RobloxWebViewMessageBusSymbols web_view;
|
||||
RobloxBrowserServiceSymbols browser_service;
|
||||
RobloxPermissionsMessageBusSymbols permissions;
|
||||
// Optional and excluded from complete(); see RobloxExperienceComposition.
|
||||
RobloxAccountProtocolSymbols account;
|
||||
|
||||
bool complete() const {
|
||||
return web_view.complete() && browser_service.complete() &&
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
#include "mocktail/status.h"
|
||||
#include "runtime/roblox_text_display_state.h"
|
||||
|
||||
struct TTF_Font;
|
||||
|
||||
namespace mocktail {
|
||||
namespace runtime {
|
||||
|
||||
@@ -39,6 +41,8 @@ class RobloxTextSurfaceOverlay final {
|
||||
const RobloxTextDisplayUpdate& update);
|
||||
void ApplyUpdate(const RobloxTextDisplayUpdate& update);
|
||||
Status RasterizeLocked();
|
||||
Status OpenFontsLocked(std::int32_t font, float point_size);
|
||||
void CloseFontsLocked();
|
||||
void ClearFrameLocked();
|
||||
void RecordFailureLocked(Status status);
|
||||
|
||||
@@ -46,10 +50,14 @@ class RobloxTextSurfaceOverlay final {
|
||||
RobloxTextDisplayState state_;
|
||||
RobloxTextOverlayViewport viewport_;
|
||||
std::vector<std::uint8_t> rgba_;
|
||||
std::vector<TTF_Font*> fonts_;
|
||||
std::int32_t fonts_font_ = 0;
|
||||
float fonts_point_size_ = 0.0F;
|
||||
std::uint64_t state_revision_ = 0;
|
||||
std::uint64_t raster_revision_ = 0;
|
||||
Status failure_;
|
||||
bool initialized_ = false;
|
||||
bool ttf_initialized_ = false;
|
||||
bool failure_logged_ = false;
|
||||
bool ready_logged_ = false;
|
||||
};
|
||||
|
||||
@@ -13,6 +13,8 @@
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
|
||||
#include "mocktail/status.h"
|
||||
#include "runtime/roblox_game_session_native_adapter.h"
|
||||
@@ -42,6 +44,10 @@ struct RobloxWebViewOpenRequest {
|
||||
std::optional<bool> show_domain_as_title;
|
||||
std::optional<bool> back_button_visible;
|
||||
std::optional<bool> hide_header;
|
||||
// Set by the bridge, never parsed. The host closes an OPEN_CAPTCHA_VIEW
|
||||
// window once its solved captcha has been forwarded, as Android's captcha
|
||||
// activity finishes itself on success.
|
||||
bool close_when_challenge_solved = false;
|
||||
};
|
||||
|
||||
// WebViewProtocol.mutateWindow is a partial update. Field absence must remain
|
||||
@@ -61,6 +67,9 @@ Status ParseRobloxWebViewMutationJson(const std::string& json,
|
||||
RobloxWebViewMutationRequest* request);
|
||||
Status ParseRobloxCaptchaOpenJson(const std::string& json,
|
||||
RobloxWebViewOpenRequest* request);
|
||||
// True for a page's Navigation.navigateToFeature command reporting a solved
|
||||
// verification (see webview::IsRobloxChallengeSolvedFeature).
|
||||
bool IsRobloxWebViewChallengeSuccess(std::string_view command);
|
||||
Status ParseRobloxProfileViewUrl(const std::string& url,
|
||||
RobloxWebViewOpenRequest* request);
|
||||
Status ParseRobloxPurchaseRobuxNotification(const std::string& json,
|
||||
@@ -108,6 +117,33 @@ using BroadcastWebViewDataModelFocusFn = void (*)(JNIEnv *, jclass, jstring,
|
||||
using SignalWebViewJavascriptCallbackFn = void (*)(JNIEnv*, jclass, jstring);
|
||||
using UpdateRobloxCookieSetHandlerFn =
|
||||
void (*)(JNIEnv*, jobject, jobject);
|
||||
// Roblox's counted handle to its Subsystem<IWebViewProtocol>. The protocol,
|
||||
// and its handleJavascriptCallback subscriber, exist only while a handle is
|
||||
// held. Roblox's handle type is not trivially destructible, so its getter
|
||||
// returns it through the caller-supplied result slot (rdi on x86-64, x8 on
|
||||
// AArch64). The user-provided destructor gives this type the same calling
|
||||
// convention. It does not release the handle.
|
||||
class RobloxWebViewProtocolHandle final {
|
||||
public:
|
||||
RobloxWebViewProtocolHandle() = default;
|
||||
explicit RobloxWebViewProtocolHandle(void* holder) : holder_(holder) {}
|
||||
RobloxWebViewProtocolHandle(const RobloxWebViewProtocolHandle&) = default;
|
||||
RobloxWebViewProtocolHandle& operator=(const RobloxWebViewProtocolHandle&) =
|
||||
default;
|
||||
~RobloxWebViewProtocolHandle() {}
|
||||
|
||||
void* holder() const { return holder_; }
|
||||
|
||||
private:
|
||||
void* holder_ = nullptr;
|
||||
};
|
||||
static_assert(sizeof(RobloxWebViewProtocolHandle) == sizeof(void*));
|
||||
static_assert(!std::is_trivially_destructible_v<RobloxWebViewProtocolHandle>);
|
||||
|
||||
// Roblox's Subsystem<IWebViewProtocol> getter. It is not exported; the
|
||||
// resolver finds it through the first call in
|
||||
// WebViewProtocol.initializeAndroidWebViewProtocol.
|
||||
using AcquireWebViewProtocolFn = RobloxWebViewProtocolHandle (*)();
|
||||
|
||||
struct RobloxWebViewMessageBusSymbols {
|
||||
GetWebViewOpenWindowIdFn get_open_window_id = nullptr;
|
||||
@@ -129,6 +165,8 @@ struct RobloxWebViewMessageBusSymbols {
|
||||
GetWebViewCloseWindowIdFn get_close_window_id = nullptr;
|
||||
SignalWebViewJavascriptCallbackFn signal_javascript_callback = nullptr;
|
||||
UpdateRobloxCookieSetHandlerFn update_cookie_set_handler = nullptr;
|
||||
// Optional: found by code contract, not by symbol name.
|
||||
AcquireWebViewProtocolFn acquire_web_view_protocol = nullptr;
|
||||
|
||||
bool complete() const {
|
||||
return get_open_window_id != nullptr &&
|
||||
@@ -287,6 +325,10 @@ private:
|
||||
std::array<std::shared_ptr<RawCallbackTarget>, kSubscriptionCount>
|
||||
raw_callback_targets_{};
|
||||
std::shared_ptr<HostWindowCloseTarget> host_window_close_target_;
|
||||
// The reference this counts is kept for the process lifetime, as Roblox's
|
||||
// Android app start keeps its own. Neither Shutdown nor destruction
|
||||
// releases it.
|
||||
RobloxWebViewProtocolHandle web_view_protocol_handle_;
|
||||
std::size_t in_flight_dispatches_ = 0;
|
||||
bool initializing_ = false;
|
||||
bool shutting_down_ = false;
|
||||
|
||||
@@ -51,14 +51,27 @@ struct NetworkProxyConfig {
|
||||
int port = 0;
|
||||
};
|
||||
|
||||
// Text and image fields expand {place_name}, {place_icon}, and
|
||||
// {creator_name}. A field that expands an empty placeholder, or renders
|
||||
// empty, is left out of the activity.
|
||||
struct DiscordRpcTextConfig {
|
||||
std::string title = "Roblox";
|
||||
std::string browsing = "Browsing experiences";
|
||||
std::string joining = "Joining an experience";
|
||||
std::string playing = "{place_name}";
|
||||
std::string state = "Playing Roblox";
|
||||
std::string playing = "Playing {place_name}";
|
||||
std::string state = "by {creator_name}";
|
||||
std::string unknown_place = "Unknown experience";
|
||||
};
|
||||
|
||||
// Images are an https URL or a Discord application asset key. Discord shows
|
||||
// the small image only next to a large one.
|
||||
struct DiscordRpcImagesConfig {
|
||||
std::string large = "{place_icon}";
|
||||
std::string large_text = "{place_name}";
|
||||
std::string small = "roblox_small";
|
||||
std::string small_text = "Roblox";
|
||||
};
|
||||
|
||||
struct DiscordRpcConfig {
|
||||
bool enabled = true;
|
||||
bool show_place_name = true;
|
||||
@@ -68,6 +81,7 @@ struct DiscordRpcConfig {
|
||||
std::string join_button_label = "Join Server";
|
||||
std::string application_id;
|
||||
DiscordRpcTextConfig text;
|
||||
DiscordRpcImagesConfig images;
|
||||
};
|
||||
|
||||
std::optional<NetworkProxyConfig> ParseNetworkProxyConfig(
|
||||
|
||||
@@ -14,7 +14,7 @@ struct ActivePayloadPaths {
|
||||
std::filesystem::path root;
|
||||
std::filesystem::path roblox_library;
|
||||
std::filesystem::path base_apk;
|
||||
std::filesystem::path x86_64_split_apk;
|
||||
std::filesystem::path arch_split_apk;
|
||||
std::filesystem::path assets_content;
|
||||
std::filesystem::path compatibility_manifest;
|
||||
std::filesystem::path host_abi_profile;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#ifndef MOCKTAIL_WEBVIEW_ROBLOX_CHALLENGE_FEATURES_H_
|
||||
#define MOCKTAIL_WEBVIEW_ROBLOX_CHALLENGE_FEATURES_H_
|
||||
|
||||
#include <string_view>
|
||||
|
||||
namespace mocktail::webview {
|
||||
|
||||
// Navigation.navigateToFeature features a Roblox verification page sends when
|
||||
// the user has solved it. The captcha page sends CaptchaSuccess; the generic
|
||||
// challenge page (challenge/cdn/hybrid) sends challengeCompleted. The WebView
|
||||
// helper and the runtime both classify page events with this list.
|
||||
inline bool IsRobloxChallengeSolvedFeature(std::string_view feature) {
|
||||
return feature == "CaptchaSuccess" || feature == "challengeCompleted" ||
|
||||
feature == "ChallengeCompleted";
|
||||
}
|
||||
|
||||
} // namespace mocktail::webview
|
||||
|
||||
#endif // MOCKTAIL_WEBVIEW_ROBLOX_CHALLENGE_FEATURES_H_
|
||||
@@ -0,0 +1,10 @@
|
||||
# Allowed reduced aarch64 packages from pkgforge-dev/archlinux-pkgs-debloated.
|
||||
# The installer verifies the rolling release asset IDs and SHA256 digests.
|
||||
ffmpeg-mini-aarch64.pkg.tar.zst
|
||||
gdk-pixbuf2-mini-aarch64.pkg.tar.xz
|
||||
gtk4-mini-aarch64.pkg.tar.zst
|
||||
icu-mini-aarch64.pkg.tar.zst
|
||||
librsvg-mini-aarch64.pkg.tar.zst
|
||||
libxml2-mini-aarch64.pkg.tar.zst
|
||||
mesa-mini-aarch64.pkg.tar.zst
|
||||
opus-mini-aarch64.pkg.tar.zst
|
||||
@@ -1,12 +1,14 @@
|
||||
# Maintainer: komaruworld <rtysus228@gmail.com>
|
||||
# Maintainer: vii <coderdayton14@gmail.com>
|
||||
|
||||
pkgname=mocktail
|
||||
pkgver=1.0.3
|
||||
pkgrel=2
|
||||
pkgname=nightcap
|
||||
pkgver=0.3.1
|
||||
pkgrel=1
|
||||
pkgdesc='Android x86-64 Roblox compatibility runtime for Linux'
|
||||
arch=('x86_64')
|
||||
url='https://github.com/komaruworld/mocktail'
|
||||
url='https://github.com/CoderDayton/nightcap'
|
||||
license=('Apache-2.0')
|
||||
provides=('mocktail')
|
||||
conflicts=('mocktail')
|
||||
depends=(
|
||||
'capstone'
|
||||
'curl'
|
||||
@@ -16,6 +18,7 @@ depends=(
|
||||
'libelf'
|
||||
'libglvnd'
|
||||
'libplacebo'
|
||||
'libpng'
|
||||
'libutf8proc'
|
||||
'libyaml'
|
||||
'minizip'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
pkgbase = mocktail-bin
|
||||
pkgbase = nightcap-bin
|
||||
pkgdesc = Android x86-64 Roblox compatibility runtime for Linux (prebuilt)
|
||||
pkgver = 1.0.4
|
||||
pkgver = 0.3.1
|
||||
pkgrel = 1
|
||||
url = https://github.com/komaruworld/mocktail
|
||||
url = https://github.com/CoderDayton/nightcap
|
||||
arch = x86_64
|
||||
license = Apache-2.0
|
||||
depends = capstone
|
||||
@@ -17,6 +17,7 @@ pkgbase = mocktail-bin
|
||||
depends = libelf
|
||||
depends = libglvnd
|
||||
depends = libplacebo
|
||||
depends = libpng
|
||||
depends = libsoup3
|
||||
depends = libutf8proc
|
||||
depends = libyaml
|
||||
@@ -29,12 +30,14 @@ pkgbase = mocktail-bin
|
||||
depends = zlib
|
||||
optdepends = gamemode: Feral GameMode integration
|
||||
provides = mocktail
|
||||
provides = nightcap
|
||||
conflicts = mocktail
|
||||
conflicts = mocktail-git
|
||||
noextract = mocktail-1.0.4-x86_64.pkg.tar.zst
|
||||
conflicts = nightcap
|
||||
conflicts = nightcap-git
|
||||
noextract = nightcap-0.3.1-1-x86_64.pkg.tar.zst
|
||||
options = !debug
|
||||
options = !strip
|
||||
source = mocktail-1.0.4-x86_64.pkg.tar.zst::https://github.com/komaruworld/mocktail/releases/download/1.0.4/mocktail-1.0.4-x86_64.pkg.tar.zst
|
||||
sha256sums = d5cc7216e88fd2889369e8eb7fba4276b2746c2b084dce566aaaa7505bc2ffb7
|
||||
source = nightcap-0.3.1-1-x86_64.pkg.tar.zst::https://github.com/CoderDayton/nightcap/releases/download/v0.3.1/nightcap-0.3.1-1-x86_64.pkg.tar.zst
|
||||
sha256sums = SKIP
|
||||
|
||||
pkgname = mocktail-bin
|
||||
pkgname = nightcap-bin
|
||||
@@ -1,11 +1,11 @@
|
||||
# Maintainer: komaruworld <rtysus228 at gmail dot com>
|
||||
# Maintainer: vii <coderdayton14 at gmail dot com>
|
||||
|
||||
pkgname=mocktail-bin
|
||||
pkgver=1.0.4
|
||||
pkgname=nightcap-bin
|
||||
pkgver=0.3.1
|
||||
pkgrel=1
|
||||
pkgdesc='Android x86-64 Roblox compatibility runtime for Linux (prebuilt)'
|
||||
arch=('x86_64')
|
||||
url='https://github.com/komaruworld/mocktail'
|
||||
url='https://github.com/CoderDayton/nightcap'
|
||||
license=('Apache-2.0')
|
||||
depends=(
|
||||
'capstone'
|
||||
@@ -20,6 +20,7 @@ depends=(
|
||||
'libelf'
|
||||
'libglvnd'
|
||||
'libplacebo'
|
||||
'libpng'
|
||||
'libsoup3'
|
||||
'libutf8proc'
|
||||
'libyaml'
|
||||
@@ -32,17 +33,18 @@ depends=(
|
||||
'zlib'
|
||||
)
|
||||
optdepends=('gamemode: Feral GameMode integration')
|
||||
provides=('mocktail')
|
||||
conflicts=('mocktail' 'mocktail-git')
|
||||
provides=('mocktail' 'nightcap')
|
||||
conflicts=('mocktail' 'nightcap' 'nightcap-git')
|
||||
options=('!debug' '!strip')
|
||||
# Release asset names do not include the AUR package release.
|
||||
_archive="mocktail-${pkgver}-${CARCH}.pkg.tar.zst"
|
||||
source=("${_archive}::https://github.com/komaruworld/mocktail/releases/download/${pkgver}/${_archive}")
|
||||
# The release asset carries the pacman package release built by release.yml.
|
||||
_archive="nightcap-${pkgver}-1-${CARCH}.pkg.tar.zst"
|
||||
source=("${_archive}::https://github.com/CoderDayton/nightcap/releases/download/v${pkgver}/${_archive}")
|
||||
noextract=("${_archive}")
|
||||
sha256sums=('d5cc7216e88fd2889369e8eb7fba4276b2746c2b084dce566aaaa7505bc2ffb7')
|
||||
# Replace with the checksum published beside the release asset.
|
||||
sha256sums=('SKIP')
|
||||
|
||||
package() {
|
||||
bsdtar -xf "${srcdir}/${_archive}" -C "${pkgdir}" usr
|
||||
install -Dm644 "${pkgdir}/usr/share/licenses/mocktail/LICENSE" \
|
||||
install -Dm644 "${pkgdir}/usr/share/licenses/nightcap/LICENSE" \
|
||||
"${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
pkgbase = mocktail
|
||||
pkgbase = nightcap-git
|
||||
pkgdesc = Android x86-64 Roblox compatibility runtime for Linux
|
||||
pkgver = 1.0.4
|
||||
pkgver = 0.3.1.r0.g0000000
|
||||
pkgrel = 1
|
||||
url = https://github.com/komaruworld/mocktail
|
||||
url = https://github.com/CoderDayton/nightcap
|
||||
arch = x86_64
|
||||
license = Apache-2.0
|
||||
makedepends = cmake>=3.20
|
||||
@@ -24,6 +24,7 @@ pkgbase = mocktail
|
||||
depends = libelf
|
||||
depends = libglvnd
|
||||
depends = libplacebo
|
||||
depends = libpng
|
||||
depends = libsoup3
|
||||
depends = libutf8proc
|
||||
depends = libyaml
|
||||
@@ -35,11 +36,13 @@ pkgbase = mocktail
|
||||
depends = webkitgtk-6.0
|
||||
depends = zlib
|
||||
optdepends = gamemode: Feral GameMode integration
|
||||
conflicts = mocktail-bin
|
||||
conflicts = mocktail-git
|
||||
provides = mocktail
|
||||
provides = nightcap
|
||||
conflicts = mocktail
|
||||
conflicts = nightcap
|
||||
conflicts = nightcap-bin
|
||||
options = !debug
|
||||
options = !lto
|
||||
source = mocktail::git+https://github.com/komaruworld/mocktail.git#tag=1.0.4
|
||||
source = nightcap::git+https://github.com/CoderDayton/nightcap.git#branch=main
|
||||
sha256sums = SKIP
|
||||
|
||||
pkgname = mocktail
|
||||
pkgname = nightcap-git
|
||||
@@ -1,11 +1,11 @@
|
||||
# Maintainer: komaruworld <rtysus228 at gmail dot com>
|
||||
# Maintainer: vii <coderdayton14 at gmail dot com>
|
||||
|
||||
pkgname=mocktail-git
|
||||
pkgver=1.0.2.r24.g9bdd737
|
||||
pkgname=nightcap-git
|
||||
pkgver=0.3.1.r0.g0000000
|
||||
pkgrel=1
|
||||
pkgdesc='Android x86-64 Roblox compatibility runtime for Linux'
|
||||
arch=('x86_64')
|
||||
url='https://github.com/komaruworld/mocktail'
|
||||
url='https://github.com/CoderDayton/nightcap'
|
||||
license=('Apache-2.0')
|
||||
depends=(
|
||||
'capstone'
|
||||
@@ -20,6 +20,7 @@ depends=(
|
||||
'libelf'
|
||||
'libglvnd'
|
||||
'libplacebo'
|
||||
'libpng'
|
||||
'libsoup3'
|
||||
'libutf8proc'
|
||||
'libyaml'
|
||||
@@ -41,31 +42,30 @@ makedepends=(
|
||||
'vulkan-headers'
|
||||
)
|
||||
optdepends=('gamemode: Feral GameMode integration')
|
||||
provides=('mocktail')
|
||||
conflicts=('mocktail' 'mocktail-bin')
|
||||
provides=('mocktail' 'nightcap')
|
||||
conflicts=('mocktail' 'nightcap' 'nightcap-bin')
|
||||
options=('!debug')
|
||||
source=(
|
||||
'mocktail::git+https://github.com/komaruworld/mocktail.git#branch=main'
|
||||
'nightcap::git+https://github.com/CoderDayton/nightcap.git#branch=main'
|
||||
)
|
||||
sha256sums=(
|
||||
'SKIP'
|
||||
)
|
||||
|
||||
pkgver() {
|
||||
cd mocktail
|
||||
cd nightcap
|
||||
|
||||
local version
|
||||
version="$(sed -n \
|
||||
's/^[[:space:]]*VERSION[[:space:]]\+\([0-9][0-9.]*\).*/\1/p' \
|
||||
CMakeLists.txt | head -n 1)"
|
||||
version="$(git describe --tags --abbrev=0 --match='v[0-9]*' 2>/dev/null)"
|
||||
version="${version#v}"
|
||||
printf '%s.r%s.g%s' \
|
||||
"${version}" \
|
||||
"${version:-0.0.0}" \
|
||||
"$(git rev-list --count HEAD)" \
|
||||
"$(git rev-parse --short=7 HEAD)"
|
||||
}
|
||||
|
||||
prepare() {
|
||||
cd mocktail
|
||||
cd nightcap
|
||||
|
||||
sed -i \
|
||||
's|add_subdirectory(third_party/Vulkan-Headers EXCLUDE_FROM_ALL)|find_package(VulkanHeaders CONFIG REQUIRED)|' \
|
||||
@@ -73,7 +73,7 @@ prepare() {
|
||||
}
|
||||
|
||||
build() {
|
||||
cmake -S mocktail -B build -G Ninja \
|
||||
cmake -S nightcap -B build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DCMAKE_INSTALL_LIBDIR=lib \
|
||||
@@ -86,6 +86,6 @@ build() {
|
||||
|
||||
package() {
|
||||
DESTDIR="${pkgdir}" cmake --install build
|
||||
install -Dm644 mocktail/LICENSE \
|
||||
install -Dm644 nightcap/LICENSE \
|
||||
"${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
pkgbase = mocktail-git
|
||||
pkgbase = nightcap
|
||||
pkgdesc = Android x86-64 Roblox compatibility runtime for Linux
|
||||
pkgver = 1.0.2.r24.g9bdd737
|
||||
pkgver = 0.3.1
|
||||
pkgrel = 1
|
||||
url = https://github.com/komaruworld/mocktail
|
||||
url = https://github.com/CoderDayton/nightcap
|
||||
arch = x86_64
|
||||
license = Apache-2.0
|
||||
makedepends = cmake>=3.20
|
||||
@@ -24,6 +24,7 @@ pkgbase = mocktail-git
|
||||
depends = libelf
|
||||
depends = libglvnd
|
||||
depends = libplacebo
|
||||
depends = libpng
|
||||
depends = libsoup3
|
||||
depends = libutf8proc
|
||||
depends = libyaml
|
||||
@@ -37,9 +38,11 @@ pkgbase = mocktail-git
|
||||
optdepends = gamemode: Feral GameMode integration
|
||||
provides = mocktail
|
||||
conflicts = mocktail
|
||||
conflicts = mocktail-bin
|
||||
conflicts = nightcap-bin
|
||||
conflicts = nightcap-git
|
||||
options = !debug
|
||||
source = mocktail::git+https://github.com/komaruworld/mocktail.git#branch=main
|
||||
options = !lto
|
||||
source = nightcap::git+https://github.com/CoderDayton/nightcap.git#tag=v0.3.1
|
||||
sha256sums = SKIP
|
||||
|
||||
pkgname = mocktail-git
|
||||
pkgname = nightcap
|
||||
@@ -1,11 +1,11 @@
|
||||
# Maintainer: komaruworld <rtysus228 at gmail dot com>
|
||||
# Maintainer: vii <coderdayton14 at gmail dot com>
|
||||
|
||||
pkgname=mocktail
|
||||
pkgver=1.0.4
|
||||
pkgname=nightcap
|
||||
pkgver=0.3.1
|
||||
pkgrel=1
|
||||
pkgdesc='Android x86-64 Roblox compatibility runtime for Linux'
|
||||
arch=('x86_64')
|
||||
url='https://github.com/komaruworld/mocktail'
|
||||
url='https://github.com/CoderDayton/nightcap'
|
||||
license=('Apache-2.0')
|
||||
depends=(
|
||||
'capstone'
|
||||
@@ -20,6 +20,7 @@ depends=(
|
||||
'libelf'
|
||||
'libglvnd'
|
||||
'libplacebo'
|
||||
'libpng'
|
||||
'libsoup3'
|
||||
'libutf8proc'
|
||||
'libyaml'
|
||||
@@ -41,17 +42,18 @@ makedepends=(
|
||||
'vulkan-headers'
|
||||
)
|
||||
optdepends=('gamemode: Feral GameMode integration')
|
||||
conflicts=('mocktail-bin' 'mocktail-git')
|
||||
provides=('mocktail')
|
||||
conflicts=('mocktail' 'nightcap-bin' 'nightcap-git')
|
||||
options=('!debug' '!lto')
|
||||
source=(
|
||||
"mocktail::git+https://github.com/komaruworld/mocktail.git#tag=${pkgver}"
|
||||
"nightcap::git+https://github.com/CoderDayton/nightcap.git#tag=v${pkgver}"
|
||||
)
|
||||
sha256sums=(
|
||||
'SKIP'
|
||||
)
|
||||
|
||||
prepare() {
|
||||
cd mocktail
|
||||
cd nightcap
|
||||
|
||||
sed -i \
|
||||
's|add_subdirectory(third_party/Vulkan-Headers EXCLUDE_FROM_ALL)|find_package(VulkanHeaders CONFIG REQUIRED)|' \
|
||||
@@ -59,7 +61,7 @@ prepare() {
|
||||
}
|
||||
|
||||
build() {
|
||||
cmake -S mocktail -B build -G Ninja \
|
||||
cmake -S nightcap -B build -G Ninja \
|
||||
-DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_INSTALL_PREFIX=/usr \
|
||||
-DCMAKE_INSTALL_LIBDIR=lib \
|
||||
@@ -72,6 +74,6 @@ build() {
|
||||
|
||||
package() {
|
||||
DESTDIR="${pkgdir}" cmake --install build
|
||||
install -Dm644 mocktail/LICENSE \
|
||||
install -Dm644 nightcap/LICENSE \
|
||||
"${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
|
||||
}
|
||||
@@ -21,8 +21,9 @@
|
||||
Sign in to Roblox, browse experiences, and play them on Linux.
|
||||
</p>
|
||||
<p>
|
||||
Mocktail is an independent community project. It is not affiliated with
|
||||
Roblox Corporation or VinegarHQ, and the Roblox client is not included.
|
||||
Nightcap is an independent community project, forked from Mocktail. It
|
||||
is not affiliated with Roblox Corporation or VinegarHQ, and the Roblox
|
||||
client is not included.
|
||||
</p>
|
||||
</description>
|
||||
<screenshots>
|
||||
@@ -56,45 +57,61 @@
|
||||
<binary>mocktail</binary>
|
||||
</provides>
|
||||
<releases>
|
||||
<release version="1.0.4" date="2026-09-11">
|
||||
<release version="0.3.2" date="2026-09-29">
|
||||
<description>
|
||||
<ul>
|
||||
<li>Fixed login issues</li>
|
||||
<li>Fixed low-resolution textures, skybox rendering and HiDPI scaling.</li>
|
||||
<li>Added vc support.</li>
|
||||
<li>Added Xbox and PlayStation gamepad support.</li>
|
||||
<li>Added Nix support</li>
|
||||
<li>Improved text input, fullscreen mode, window sizing, and mouse controls.</li>
|
||||
<li>Updated support for Roblox 2.736.1408.</li>
|
||||
<li>Added experimental support for ARM64 Linux.</li>
|
||||
<li>Fixed login stalling after passing a verification check.</li>
|
||||
<li>Fixed login check windows staying open after they were solved.</li>
|
||||
<li>Fixed Play on a private server doing nothing until a sidebar tab was clicked.</li>
|
||||
<li>Less stutter while joining a game and while textures load in.</li>
|
||||
<li>Middle click and natural scrolling now work as expected.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="1.0.3" date="2026-08-16">
|
||||
<release version="0.3.1" date="2026-09-20">
|
||||
<description>
|
||||
<ul>
|
||||
<li>Fixed issues with downloading Roblox on first launch</li>
|
||||
<li>Added fflags.json for custom FFlags</li>
|
||||
<li>Added a message if your cookies have expired</li>
|
||||
<li>Added DEB, RPM, and pacman packages to every release.</li>
|
||||
<li>Smoother frames: textures no longer decode on the thread that submits the frame.</li>
|
||||
<li>Fixed the mouse pointer jumping when a right-click camera drag ended.</li>
|
||||
<li>Fixed the text caret not moving when a trailing space was typed.</li>
|
||||
<li>Faster typing in text boxes.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="1.0.2" date="2026-08-14">
|
||||
<release version="0.3.0" date="2026-09-18">
|
||||
<description>
|
||||
<ul>
|
||||
<li>Fixed the “Roblox is out of date” bug</li>
|
||||
<li>Improved logging</li>
|
||||
<li>Fixed issues with Discord RPC where the game you were playing wasn’t displayed</li>
|
||||
<li>Added a custom Discord presence: set the title, state, and icons.</li>
|
||||
<li>Added --profile to record a trace of the renderer's work.</li>
|
||||
<li>Faster texture loading: compressed textures decode and resample on worker threads.</li>
|
||||
<li>Lower CPU use while playing.</li>
|
||||
<li>Fixed GameMode pinning the game to a few CPU cores.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="1.0.1" date="2026-08-13">
|
||||
<release version="0.2.0" date="2026-09-16">
|
||||
<description>
|
||||
<ul>
|
||||
<li>Fix issues with GameMode</li>
|
||||
<li>Add Discord RPC support</li>
|
||||
<li>Discord Rich Presence is on by default.</li>
|
||||
<li>Added input.raw_mouse for mouse look in the host's own units.</li>
|
||||
<li>Fixed mouse look after a long turn.</li>
|
||||
<li>Fixed a first-run failure with "cannot lock appStorage".</li>
|
||||
<li>Values in fflags.json now win over the performance preset.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="0.1.0" date="2026-09-15">
|
||||
<description>
|
||||
<ul>
|
||||
<li>First Nightcap release, forked from Mocktail.</li>
|
||||
<li>Added ETC2 and EAC texture emulation on Vulkan.</li>
|
||||
<li>Added PNG texture overrides.</li>
|
||||
<li>Lower input latency.</li>
|
||||
<li>Roblox now sees the real host RAM and display size.</li>
|
||||
</ul>
|
||||
</description>
|
||||
</release>
|
||||
<release version="0.1.0" date="2026-08-12"/>
|
||||
</releases>
|
||||
</component>
|
||||
@@ -23,6 +23,7 @@
|
||||
elfutils,
|
||||
libglvnd,
|
||||
libplacebo,
|
||||
libpng,
|
||||
libsoup_3,
|
||||
libutf8proc,
|
||||
libyaml,
|
||||
@@ -92,6 +93,7 @@ stdenv.mkDerivation (finalAttrs: {
|
||||
elfutils
|
||||
libglvnd
|
||||
libplacebo
|
||||
libpng
|
||||
libsoup_3
|
||||
libutf8proc
|
||||
libyaml
|
||||
|
||||
@@ -461,6 +461,7 @@ LatestSupportedBootstrapProfile() {
|
||||
.version_code <= ($remote_version_code | tonumber)) and
|
||||
.status == "supported" and .default_allowed == true and
|
||||
.allow_legacy_binary_patches == false and
|
||||
(.abi // "x86_64") == "x86_64" and
|
||||
(.version_name | type) == "string" and
|
||||
(.version_name | length) > 0)] |
|
||||
group_by(.version_code) |
|
||||
@@ -495,6 +496,7 @@ SelectSupportedBootstrapFallback() {
|
||||
bootstrap_source="$(jq -er --argjson version_code "${fallback_version_code}" '
|
||||
[.sources[]? |
|
||||
select(.version_code == $version_code and
|
||||
(.abi // "x86_64") == "x86_64" and
|
||||
.provider == "uptodown")] |
|
||||
if length == 1 then .[0].provider else empty end
|
||||
' "${BOOTSTRAP_SOURCES_PATH}" 2>/dev/null || true)"
|
||||
|
||||
@@ -329,6 +329,7 @@ def run_trial(args, max_ctors, skipped_offsets, trial_id):
|
||||
log_path = args.log_dir / f"trial_{trial_id:03d}_max_{max_ctors}.log"
|
||||
env = os.environ.copy()
|
||||
env.update({
|
||||
"ROBLOX_LIB_PATH": str(args.libroblox),
|
||||
"MOCKTAIL_RUN_LIBROBLOX_CTORS": "1",
|
||||
"MOCKTAIL_LIBROBLOX_CTOR_POLICY": args.ctor_policy,
|
||||
"MOCKTAIL_GRAPHICS_BACKEND": args.graphics_backend,
|
||||
@@ -500,7 +501,7 @@ def parse_args():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--project-root", type=Path, default=project_root)
|
||||
parser.add_argument("--run-script", type=Path,
|
||||
default=project_root / "scripts" / "run_sober.sh")
|
||||
default=project_root / "build" / "mocktail")
|
||||
parser.add_argument("--libroblox", type=Path,
|
||||
default=project_root / "rbx_bin" / "libroblox.so")
|
||||
parser.add_argument("--log-dir", type=Path,
|
||||
|
||||
@@ -10,18 +10,18 @@ readonly PROJECT_ROOT="$(cd -- "${SCRIPT_DIR}/.." && pwd -P)"
|
||||
|
||||
BUILD_DIR="${PROJECT_ROOT}/build-flatpak"
|
||||
MANIFEST="${PROJECT_ROOT}/packaging/flatpak/io.github.CoderDayton.nightcap.json"
|
||||
JOBS="${MOCKTAIL_FLATPAK_JOBS:-4}"
|
||||
JOBS="${MOCKTAIL_FLATPAK_JOBS:-2}"
|
||||
|
||||
Usage() {
|
||||
cat <<'EOF'
|
||||
Usage: scripts/build_flatpak.sh [OPTIONS]
|
||||
|
||||
Build and install Mocktail as a per-user x86-64 Flatpak.
|
||||
Build and install Mocktail as a per-user Flatpak for the host architecture.
|
||||
|
||||
Options:
|
||||
--build-dir DIR Builder output directory (default: build-flatpak).
|
||||
--manifest FILE Flatpak manifest path.
|
||||
--jobs N Maximum parallel build jobs (default: 4).
|
||||
--jobs N Maximum parallel build jobs (default: 2).
|
||||
-h, --help Show this help.
|
||||
EOF
|
||||
}
|
||||
@@ -93,8 +93,11 @@ done
|
||||
[[ "${JOBS}" =~ ^[1-9][0-9]*$ && "${JOBS}" -le 256 ]] ||
|
||||
Die "--jobs must be an integer between 1 and 256"
|
||||
|
||||
[[ "$(uname -m)" == x86_64 ]] ||
|
||||
Die "the Roblox payload and Flatpak manifest currently require x86-64"
|
||||
HOST_ARCH="$(uname -m)"
|
||||
case "${HOST_ARCH}" in
|
||||
x86_64|aarch64) ;;
|
||||
*) Die "Flatpak builds require an x86_64 or aarch64 Linux host" ;;
|
||||
esac
|
||||
command -v flatpak >/dev/null 2>&1 || Die "flatpak is required"
|
||||
|
||||
MANIFEST="$(realpath -e -- "${MANIFEST}")" ||
|
||||
@@ -123,7 +126,7 @@ CleanupStaleBuilderMounts
|
||||
|
||||
cd -- "${PROJECT_ROOT}"
|
||||
exec "${builder[@]}" \
|
||||
--arch=x86_64 \
|
||||
--arch="${HOST_ARCH}" \
|
||||
--jobs="${JOBS}" \
|
||||
--force-clean \
|
||||
--install-deps-from=flathub \
|
||||
|
||||
@@ -61,6 +61,7 @@ def supported_profiles(catalog: dict) -> list[dict]:
|
||||
if isinstance(profile, dict)
|
||||
and profile.get("status") == "supported"
|
||||
and profile.get("default_allowed") is True
|
||||
and profile.get("abi", ARCHITECTURE) == ARCHITECTURE
|
||||
and isinstance(profile.get("version_name"), str)
|
||||
and isinstance(profile.get("version_code"), int)
|
||||
]
|
||||
|
||||
@@ -18,12 +18,15 @@ AnyLinuxDependencyRequireContainer() {
|
||||
}
|
||||
|
||||
AnyLinuxDependencySnapshot() {
|
||||
local manifest="$1" release="$2" filename remainder names_json
|
||||
local manifest="$1" release="$2" host_arch="${3:-$(uname -m)}"
|
||||
local filename remainder names_json
|
||||
[[ "${host_arch}" == x86_64 || "${host_arch}" == aarch64 ]] ||
|
||||
AnyLinuxDependencyDie 'unsupported AppImage architecture'
|
||||
local -a names=()
|
||||
local -A seen=()
|
||||
while read -r filename remainder || [[ -n "${filename}" ]]; do
|
||||
[[ -n "${filename}" && "${filename}" != \#* ]] || continue
|
||||
[[ "${filename}" =~ ^[a-z0-9-]+-mini-x86_64\.pkg\.tar\.zst$ &&
|
||||
[[ "${filename}" =~ ^[a-z0-9-]+-mini-${host_arch}\.pkg\.tar\.(zst|xz)$ &&
|
||||
-z "${remainder}" && -z "${seen[${filename}]:-}" ]] ||
|
||||
AnyLinuxDependencyDie 'invalid or duplicate dependency manifest entry'
|
||||
seen["${filename}"]=1
|
||||
@@ -108,7 +111,13 @@ AnyLinuxDependenciesMain() (
|
||||
AnyLinuxDependencyRequireContainer
|
||||
(( $# == 0 )) || AnyLinuxDependencyDie 'no arguments are supported'
|
||||
readonly ROOT="$(cd -P -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
readonly MANIFEST="${ROOT}/packaging/anylinux-dependencies.txt"
|
||||
local host_arch="$(uname -m)" manifest_name
|
||||
case "${host_arch}" in
|
||||
x86_64) manifest_name=anylinux-dependencies.txt ;;
|
||||
aarch64) manifest_name=anylinux-dependencies-aarch64.txt ;;
|
||||
*) AnyLinuxDependencyDie "unsupported AppImage architecture: ${host_arch}" ;;
|
||||
esac
|
||||
readonly MANIFEST="${ROOT}/packaging/${manifest_name}"
|
||||
readonly DOWNLOADS="$(mktemp -d "${TMPDIR:-/tmp}/mocktail-debloated.XXXXXX")"
|
||||
trap 'rm -rf -- "${DOWNLOADS}"' EXIT
|
||||
AnyLinuxDownloadDependencies "${MANIFEST}" "${DOWNLOADS}"
|
||||
|
||||
@@ -119,6 +119,7 @@ libyaml
|
||||
fontconfig
|
||||
minizip
|
||||
libplacebo
|
||||
libpng
|
||||
util-linux'
|
||||
INSTALL_ARGS='-S --needed --noconfirm'
|
||||
;;
|
||||
@@ -144,6 +145,7 @@ libyaml
|
||||
fontconfig
|
||||
minizip
|
||||
libplacebo
|
||||
libpng
|
||||
util-linux'
|
||||
if HostUsesMusl; then
|
||||
PACKAGES="$PACKAGES gcompat"
|
||||
@@ -172,6 +174,7 @@ libyaml
|
||||
fontconfig
|
||||
minizip
|
||||
libplacebo
|
||||
libpng
|
||||
coreutils
|
||||
findutils
|
||||
util-linux'
|
||||
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
# Modified by vii from komaruworld/mocktail. See README "About this fork".
|
||||
# Copyright 2026 Mocktail Project Authors
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
#
|
||||
# Prints the native package version for the current ref. A release tag gives
|
||||
# its own version; anything else gives 0.0.0, which sorts below every release.
|
||||
|
||||
set -Eeuo pipefail
|
||||
|
||||
ref="${1:-${GITHUB_REF_NAME:-}}"
|
||||
version="${ref#v}"
|
||||
|
||||
if [[ "${version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
printf '%s\n' "${version}"
|
||||
else
|
||||
printf '0.0.0\n'
|
||||
fi
|
||||
Executable
+126
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2026 Mocktail Project Authors
|
||||
# Licensed under the Apache License, Version 2.0.
|
||||
"""Summarizes `--profile` traces as a Markdown table for pull requests.
|
||||
|
||||
Usage: summarize_profile_trace.py TRACE [TRACE ...]
|
||||
|
||||
Each trace gets its own column, so `before.json after.json` compares them.
|
||||
Frame times come from the "frame interval (ms)" counter; every other row is
|
||||
a slice name recorded by the Vulkan adapter.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Iterable
|
||||
|
||||
FRAME_COUNTER = "frame interval (ms)"
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Distribution:
|
||||
count: int
|
||||
total: float
|
||||
mean: float
|
||||
p50: float
|
||||
p95: float
|
||||
p99: float
|
||||
max: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Summary:
|
||||
frames: Distribution | None
|
||||
slices: dict[str, Distribution]
|
||||
|
||||
|
||||
def _nearest_rank(ordered: list[float], percent: float) -> float:
|
||||
rank = max(1, math.ceil(percent / 100 * len(ordered)))
|
||||
return ordered[rank - 1]
|
||||
|
||||
|
||||
def _distribution(values: list[float]) -> Distribution:
|
||||
ordered = sorted(values)
|
||||
total = sum(ordered)
|
||||
return Distribution(count=len(ordered), total=total,
|
||||
mean=total / len(ordered),
|
||||
p50=_nearest_rank(ordered, 50),
|
||||
p95=_nearest_rank(ordered, 95),
|
||||
p99=_nearest_rank(ordered, 99), max=ordered[-1])
|
||||
|
||||
|
||||
def summarize(events: Iterable[dict]) -> Summary:
|
||||
frames: list[float] = []
|
||||
slices: dict[str, list[float]] = {}
|
||||
for event in events:
|
||||
phase = event.get("ph")
|
||||
if phase == "C" and event.get("name") == FRAME_COUNTER:
|
||||
frames.append(float(event["args"]["value"]))
|
||||
elif phase == "X":
|
||||
slices.setdefault(event["name"], []).append(event["dur"] / 1000)
|
||||
return Summary(
|
||||
frames=_distribution(frames) if frames else None,
|
||||
slices={name: _distribution(values)
|
||||
for name, values in slices.items()})
|
||||
|
||||
|
||||
def _row(label: str, cells: list[str]) -> str:
|
||||
return "| " + " | ".join([label, *cells]) + " |"
|
||||
|
||||
|
||||
def _cell(distribution: Distribution | None, field: str) -> str:
|
||||
if distribution is None:
|
||||
return "-"
|
||||
if field == "count":
|
||||
return str(distribution.count)
|
||||
return f"{getattr(distribution, field):.2f}"
|
||||
|
||||
|
||||
def _metric_row(label: str, distributions: list[Distribution | None],
|
||||
field: str) -> str:
|
||||
return _row(label, [_cell(item, field) for item in distributions])
|
||||
|
||||
|
||||
def to_markdown(traces: list[tuple[str, Summary]]) -> str:
|
||||
summaries = [summary for _, summary in traces]
|
||||
lines = [_row("metric", [name for name, _ in traces]),
|
||||
_row("---", ["---:"] * len(traces))]
|
||||
|
||||
frames = [summary.frames for summary in summaries]
|
||||
lines.append(_metric_row("frames", frames, "count"))
|
||||
if any(frames):
|
||||
lines += [_metric_row(f"frame interval {field} (ms)", frames, field)
|
||||
for field in ("mean", "p50", "p95", "p99", "max")]
|
||||
|
||||
# Largest total time first, taken from whichever trace spent the most.
|
||||
totals: dict[str, float] = {}
|
||||
for summary in summaries:
|
||||
for name, distribution in summary.slices.items():
|
||||
totals[name] = max(totals.get(name, 0.0), distribution.total)
|
||||
for name in sorted(totals, key=lambda name: -totals[name]):
|
||||
column = [summary.slices.get(name) for summary in summaries]
|
||||
lines.append(_metric_row(f"{name} count", column, "count"))
|
||||
lines += [_metric_row(f"{name} {field} (ms)", column, field)
|
||||
for field in ("total", "mean", "p99", "max")]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main(arguments: list[str]) -> int:
|
||||
if not arguments:
|
||||
print(__doc__.strip(), file=sys.stderr)
|
||||
return 2
|
||||
traces = []
|
||||
for argument in arguments:
|
||||
path = Path(argument)
|
||||
traces.append((path.name, summarize(json.loads(path.read_text()))))
|
||||
print(to_markdown(traces))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv[1:]))
|
||||
@@ -110,8 +110,14 @@ for elf in "$@"; do
|
||||
fi
|
||||
machine="$(LC_ALL=C readelf --file-header "${elf}" 2>/dev/null |
|
||||
sed -n 's/^[[:space:]]*Machine:[[:space:]]*//p')"
|
||||
if [[ "${machine}" != *X86-64* ]]; then
|
||||
printf 'ABI check: %s is not x86-64 (%s)\n' "${elf}" "${machine}" >&2
|
||||
case "$(uname -m)" in
|
||||
x86_64) expected_machine='X86-64' ;;
|
||||
aarch64) expected_machine='AArch64' ;;
|
||||
*) expected_machine='X86-64' ;;
|
||||
esac
|
||||
if [[ "${machine}" != *"${expected_machine}"* ]]; then
|
||||
printf 'ABI check: %s is not %s (%s)\n' "${elf}" "${expected_machine}" \
|
||||
"${machine}" >&2
|
||||
status=1
|
||||
fi
|
||||
|
||||
|
||||
@@ -22,6 +22,10 @@
|
||||
<p>Flatpak</p>
|
||||
<code>flatpak install --user https://coderdayton.github.io/nightcap/nightcap.flatpakref
|
||||
flatpak run io.github.CoderDayton.nightcap</code>
|
||||
<p>DEB, RPM and pacman</p>
|
||||
<code>sudo apt install ./nightcap_<version>-1_amd64.deb
|
||||
sudo dnf install ./nightcap-<version>-1.x86_64.rpm
|
||||
sudo pacman -U nightcap-<version>-1-x86_64.pkg.tar.zst</code>
|
||||
<p>Build from source</p>
|
||||
<code>git clone --recurse-submodules https://github.com/CoderDayton/nightcap.git
|
||||
cd nightcap && make build
|
||||
@@ -40,6 +44,7 @@ cd nightcap && make build
|
||||
<p class="links">
|
||||
<a href="https://github.com/CoderDayton/nightcap/releases/latest/download/Nightcap-x86_64.AppImage">AppImage</a>
|
||||
<a href="Nightcap-x86_64.flatpak">Flatpak bundle</a>
|
||||
<a href="https://github.com/CoderDayton/nightcap/releases/latest">DEB, RPM, pacman</a>
|
||||
<a href="nightcap-flatpak.gpg">Signing key</a>
|
||||
<a href="terms.html">Terms</a>
|
||||
<a href="privacy.html">Privacy</a>
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
#include "compat/bionic_pthread_create_runtime.h"
|
||||
#include "compat/guest_abi.h"
|
||||
#include "compat/http_client_spin_guard.h"
|
||||
#include "window/window.h"
|
||||
|
||||
@@ -31,6 +33,14 @@ const char* EnvironmentOr(const char* name, const char* fallback) {
|
||||
return value != nullptr && value[0] != '\0' ? value : fallback;
|
||||
}
|
||||
|
||||
const char* GuestAbiPropertyValue() {
|
||||
#if defined(__aarch64__)
|
||||
return "arm64-v8a";
|
||||
#else
|
||||
return "x86_64";
|
||||
#endif
|
||||
}
|
||||
|
||||
int CallHostVsnprintf(char* dst, size_t count, const char* format,
|
||||
va_list args) {
|
||||
using HostVsnprintf = int (*)(char*, size_t, const char*, va_list);
|
||||
@@ -173,8 +183,12 @@ int __system_property_get(const char* name, char* value) {
|
||||
result = "35";
|
||||
} else if (std::strcmp(name, "ro.build.version.release") == 0) {
|
||||
result = "15";
|
||||
} else if (std::strcmp(name, "ro.product.cpu.abi") == 0) {
|
||||
result = "x86_64";
|
||||
} else if (std::strcmp(name, "ro.product.cpu.abi") == 0 ||
|
||||
std::strcmp(name, "ro.product.cpu.abilist") == 0 ||
|
||||
std::strcmp(name, "ro.product.cpu.abilist64") == 0) {
|
||||
result = GuestAbiPropertyValue();
|
||||
} else if (std::strcmp(name, "ro.product.cpu.abilist32") == 0) {
|
||||
result = "";
|
||||
} else if (std::strcmp(name, "ro.product.manufacturer") == 0) {
|
||||
result = EnvironmentOr("MOCKTAIL_DEVICE_MANUFACTURER", "Mocktail");
|
||||
} else if (std::strcmp(name, "ro.product.model") == 0) {
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
#include "compat/bionic_pthread_create_runtime.h"
|
||||
|
||||
#include "compat/bionic_abi_exports.h"
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
@@ -69,24 +73,28 @@ size_t HostStackSizeForGuest(size_t guest_stack_size) noexcept {
|
||||
return guest_stack_size;
|
||||
}
|
||||
|
||||
int CopySupportedThreadAttributes(const pthread_attr_t& source,
|
||||
// Guest pthread_attr_t buffers use the Bionic LP64 layout; they are never a
|
||||
// host pthread_attr_t, so decode the fixed fields directly.
|
||||
int GuestDetachState(const MocktailBionicPthreadAttr& source) noexcept {
|
||||
return (source.flags & kMocktailBionicAttrFlagDetached) != 0
|
||||
? PTHREAD_CREATE_DETACHED
|
||||
: PTHREAD_CREATE_JOINABLE;
|
||||
}
|
||||
|
||||
size_t GuestStackSize(const MocktailBionicPthreadAttr& source) noexcept {
|
||||
return source.stack_size != 0 ? source.stack_size
|
||||
: kBionicLp64DefaultThreadStackSize;
|
||||
}
|
||||
|
||||
int CopySupportedThreadAttributes(const MocktailBionicPthreadAttr& source,
|
||||
pthread_attr_t* destination) noexcept {
|
||||
int detach_state = PTHREAD_CREATE_JOINABLE;
|
||||
int result = pthread_attr_getdetachstate(&source, &detach_state);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = pthread_attr_setdetachstate(destination, detach_state);
|
||||
int result =
|
||||
pthread_attr_setdetachstate(destination, GuestDetachState(source));
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
size_t guard_size = 0;
|
||||
result = pthread_attr_getguardsize(&source, &guard_size);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = pthread_attr_setguardsize(destination, guard_size);
|
||||
result = pthread_attr_setguardsize(destination, source.guard_size);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
@@ -95,53 +103,38 @@ int CopySupportedThreadAttributes(const pthread_attr_t& source,
|
||||
// pthread_attr_setstack. Copying pthread_attr_getstack's address is unsafe:
|
||||
// glibc represents an automatically allocated stack with a synthetic
|
||||
// address derived from its size.
|
||||
size_t stack_size = 0;
|
||||
result = pthread_attr_getstacksize(&source, &stack_size);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = pthread_attr_setstacksize(destination,
|
||||
HostStackSizeForGuest(stack_size));
|
||||
result = pthread_attr_setstacksize(
|
||||
destination, HostStackSizeForGuest(GuestStackSize(source)));
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
int inherit_scheduler = PTHREAD_INHERIT_SCHED;
|
||||
result = pthread_attr_getinheritsched(&source, &inherit_scheduler);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
// Bionic applies the attribute's scheduling policy at creation whenever it
|
||||
// differs from the normal policy.
|
||||
if (RejectRealtimeScheduling(source.sched_policy)) {
|
||||
return EPERM;
|
||||
}
|
||||
if (inherit_scheduler == PTHREAD_EXPLICIT_SCHED) {
|
||||
int scheduler_policy = 0;
|
||||
sched_param scheduler_parameters{};
|
||||
result = pthread_attr_getschedpolicy(&source, &scheduler_policy);
|
||||
if (result == 0) {
|
||||
result = pthread_attr_getschedparam(&source, &scheduler_parameters);
|
||||
}
|
||||
if (result == 0 && RejectRealtimeScheduling(scheduler_policy)) {
|
||||
return EPERM;
|
||||
}
|
||||
if (result == 0) {
|
||||
result = pthread_attr_setschedpolicy(destination, scheduler_policy);
|
||||
}
|
||||
if (result == 0) {
|
||||
result = pthread_attr_setschedparam(destination, &scheduler_parameters);
|
||||
}
|
||||
if (source.sched_policy != SCHED_NORMAL) {
|
||||
result = pthread_attr_setschedpolicy(destination, source.sched_policy);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
sched_param scheduler_parameters{};
|
||||
scheduler_parameters.sched_priority = source.sched_priority;
|
||||
result = pthread_attr_setschedparam(destination, &scheduler_parameters);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
return pthread_attr_setinheritsched(destination, PTHREAD_EXPLICIT_SCHED);
|
||||
}
|
||||
return pthread_attr_setinheritsched(destination, inherit_scheduler);
|
||||
|
||||
return pthread_attr_setinheritsched(destination, PTHREAD_INHERIT_SCHED);
|
||||
}
|
||||
|
||||
int CopyRequiredThreadAttributes(const pthread_attr_t& source,
|
||||
int CopyRequiredThreadAttributes(const MocktailBionicPthreadAttr& source,
|
||||
pthread_attr_t* destination) noexcept {
|
||||
int detach_state = PTHREAD_CREATE_JOINABLE;
|
||||
int result = pthread_attr_getdetachstate(&source, &detach_state);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = pthread_attr_setdetachstate(destination, detach_state);
|
||||
int result =
|
||||
pthread_attr_setdetachstate(destination, GuestDetachState(source));
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
@@ -149,32 +142,20 @@ int CopyRequiredThreadAttributes(const pthread_attr_t& source,
|
||||
// The retry must retain an explicitly requested guest stack. Falling back
|
||||
// to a null/default host attr is unsafe on musl, whose default stack is much
|
||||
// smaller than Bionic's and can be exhausted by a single libroblox frame.
|
||||
size_t stack_size = 0;
|
||||
result = pthread_attr_getstacksize(&source, &stack_size);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
return pthread_attr_setstacksize(destination,
|
||||
HostStackSizeForGuest(stack_size));
|
||||
return pthread_attr_setstacksize(
|
||||
destination, HostStackSizeForGuest(GuestStackSize(source)));
|
||||
}
|
||||
|
||||
int ConfigureHostSafeStackFallback(const pthread_attr_t* source,
|
||||
int ConfigureHostSafeStackFallback(const MocktailBionicPthreadAttr* source,
|
||||
pthread_attr_t* destination) noexcept {
|
||||
size_t guest_stack_size = 0;
|
||||
if (source != nullptr) {
|
||||
int detach_state = PTHREAD_CREATE_JOINABLE;
|
||||
int result = pthread_attr_getdetachstate(source, &detach_state);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = pthread_attr_setdetachstate(destination, detach_state);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
result = pthread_attr_getstacksize(source, &guest_stack_size);
|
||||
int result =
|
||||
pthread_attr_setdetachstate(destination, GuestDetachState(*source));
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
guest_stack_size = GuestStackSize(*source);
|
||||
}
|
||||
|
||||
size_t host_default_stack_size = 0;
|
||||
@@ -207,7 +188,8 @@ void ConfigureBionicPthreadThreadInitializer(
|
||||
g_thread_initializer.store(initializer, std::memory_order_release);
|
||||
}
|
||||
|
||||
int CreateBionicPthread(pthread_t* thread, const pthread_attr_t* attr,
|
||||
int CreateBionicPthread(pthread_t* thread,
|
||||
const MocktailBionicPthreadAttr* attr,
|
||||
void* (*start_routine)(void*), void* argument) {
|
||||
if (thread == nullptr || start_routine == nullptr) {
|
||||
return EINVAL;
|
||||
@@ -289,10 +271,124 @@ int CreateBionicPthread(pthread_t* thread, const pthread_attr_t* attr,
|
||||
|
||||
} // namespace mocktail::compat
|
||||
|
||||
extern "C" int mocktail_bionic_pthread_create(pthread_t* thread,
|
||||
const pthread_attr_t* attr,
|
||||
void* (*start_routine)(void*),
|
||||
void* argument) {
|
||||
extern "C" {
|
||||
|
||||
int mocktail_pthread_attr_init(MocktailBionicPthreadAttr* attr) {
|
||||
if (attr == nullptr) {
|
||||
return EINVAL;
|
||||
}
|
||||
attr->flags = 0;
|
||||
attr->stack_base = nullptr;
|
||||
attr->stack_size =
|
||||
mocktail::compat::kBionicLp64DefaultThreadStackSize;
|
||||
const long page_size = sysconf(_SC_PAGESIZE);
|
||||
attr->guard_size = page_size > 0 ? static_cast<size_t>(page_size) : 0;
|
||||
attr->sched_policy = SCHED_OTHER;
|
||||
attr->sched_priority = 0;
|
||||
std::memset(attr->reserved, 0, sizeof(attr->reserved));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mocktail_pthread_attr_destroy(MocktailBionicPthreadAttr* attr) {
|
||||
(void)attr;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mocktail_pthread_attr_setstacksize(MocktailBionicPthreadAttr* attr,
|
||||
size_t stack_size) {
|
||||
if (attr == nullptr || stack_size < PTHREAD_STACK_MIN) {
|
||||
return EINVAL;
|
||||
}
|
||||
attr->stack_size = stack_size;
|
||||
attr->flags &= ~kMocktailBionicAttrFlagUserStack;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mocktail_pthread_attr_setdetachstate(MocktailBionicPthreadAttr* attr,
|
||||
int detach_state) {
|
||||
if (attr == nullptr || (detach_state != PTHREAD_CREATE_DETACHED &&
|
||||
detach_state != PTHREAD_CREATE_JOINABLE)) {
|
||||
return EINVAL;
|
||||
}
|
||||
if (detach_state == PTHREAD_CREATE_DETACHED) {
|
||||
attr->flags |= kMocktailBionicAttrFlagDetached;
|
||||
} else {
|
||||
attr->flags &= ~kMocktailBionicAttrFlagDetached;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mocktail_pthread_attr_setschedparam(MocktailBionicPthreadAttr* attr,
|
||||
const struct sched_param* parameters) {
|
||||
if (attr == nullptr || parameters == nullptr) {
|
||||
return EINVAL;
|
||||
}
|
||||
attr->sched_priority = parameters->sched_priority;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mocktail_pthread_getattr_np(pthread_t thread,
|
||||
MocktailBionicPthreadAttr* attr) {
|
||||
if (attr == nullptr) {
|
||||
return EINVAL;
|
||||
}
|
||||
pthread_attr_t host_attr;
|
||||
int result = pthread_getattr_np(thread, &host_attr);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
void* stack_base = nullptr;
|
||||
size_t stack_size = 0;
|
||||
result = pthread_attr_getstack(&host_attr, &stack_base, &stack_size);
|
||||
size_t guard_size = 0;
|
||||
if (result == 0) {
|
||||
result = pthread_attr_getguardsize(&host_attr, &guard_size);
|
||||
}
|
||||
int detach_state = PTHREAD_CREATE_JOINABLE;
|
||||
if (result == 0) {
|
||||
result = pthread_attr_getdetachstate(&host_attr, &detach_state);
|
||||
}
|
||||
sched_param parameters{};
|
||||
int policy = SCHED_OTHER;
|
||||
if (result == 0) {
|
||||
result = pthread_getschedparam(thread, &policy, ¶meters);
|
||||
}
|
||||
pthread_attr_destroy(&host_attr);
|
||||
if (result != 0) {
|
||||
return result;
|
||||
}
|
||||
attr->flags = detach_state == PTHREAD_CREATE_DETACHED
|
||||
? kMocktailBionicAttrFlagDetached
|
||||
: 0;
|
||||
attr->stack_base = stack_base;
|
||||
attr->stack_size = stack_size;
|
||||
attr->guard_size = guard_size;
|
||||
attr->sched_policy = policy;
|
||||
attr->sched_priority = parameters.sched_priority;
|
||||
std::memset(attr->reserved, 0, sizeof(attr->reserved));
|
||||
return 0;
|
||||
}
|
||||
|
||||
int mocktail_pthread_attr_getstack(const MocktailBionicPthreadAttr* attr,
|
||||
void** stack_base, size_t* stack_size) {
|
||||
if (attr == nullptr) {
|
||||
return EINVAL;
|
||||
}
|
||||
if (stack_base != nullptr) {
|
||||
*stack_base = attr->stack_base;
|
||||
}
|
||||
if (stack_size != nullptr) {
|
||||
*stack_size = attr->stack_size;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
} // extern "C"
|
||||
|
||||
extern "C" int mocktail_bionic_pthread_create(
|
||||
pthread_t* thread, const MocktailBionicPthreadAttr* attr,
|
||||
void* (*start_routine)(void*), void* argument) {
|
||||
return mocktail::compat::CreateBionicPthread(thread, attr, start_routine,
|
||||
argument);
|
||||
}
|
||||
|
||||
@@ -39,12 +39,23 @@ bool PatchAbsoluteJump(uintptr_t address, void *target) noexcept {
|
||||
return false;
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
// ldr x16, #8 ; br x16 ; .quad target
|
||||
// x16 is the intra-procedure-call scratch register, free to clobber.
|
||||
unsigned char patch[] = {
|
||||
0x50, 0x00, 0x00, 0x58, 0x00, 0x02, 0x1f, 0xd6,
|
||||
0, 0, 0, 0, 0, 0, 0, 0,
|
||||
};
|
||||
const uintptr_t target_address = reinterpret_cast<uintptr_t>(target);
|
||||
std::memcpy(patch + 8, &target_address, sizeof(target_address));
|
||||
#else
|
||||
unsigned char patch[] = {
|
||||
0x48, 0xb8, // movabs rax, imm64
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xe0, // jmp rax
|
||||
};
|
||||
const uintptr_t target_address = reinterpret_cast<uintptr_t>(target);
|
||||
std::memcpy(patch + 2, &target_address, sizeof(target_address));
|
||||
#endif
|
||||
|
||||
const uintptr_t page_mask = static_cast<uintptr_t>(page_size) - 1;
|
||||
const uintptr_t page = address & ~page_mask;
|
||||
|
||||
@@ -6,6 +6,34 @@ namespace mocktail::compat {
|
||||
namespace {
|
||||
|
||||
constexpr HostAbiProfile kProfiles[] = {
|
||||
// Roblox 2.736.1408 arm64-v8a. Every RVA was derived from the AArch64
|
||||
// payload of the same release as the x86-64 reference above, matched by
|
||||
// allocator internals, init_array call graphs, and static state layout.
|
||||
// Constructor policy mirrors x86-64 by semantic role: the pre-init
|
||||
// entries 0..3 stay skipped, index 4 is mi_process_load (thread init
|
||||
// checkpoint), index 5 is allocator wiring and index 6 is the lazy clock
|
||||
// singleton getter, both excluded under host bridges only.
|
||||
{"ed2b035768b1513561d0e6ea7f9bbec35b0e60e5",
|
||||
{{{0x1d53840, HostBridgeKind::kAllocate, "small-allocate"},
|
||||
{0x1d56c34, HostBridgeKind::kUsableSize, "usable-size"},
|
||||
{0x1d6ef80, HostBridgeKind::kReallocate, "reallocate"},
|
||||
{0x1d53568, HostBridgeKind::kAllocate, "allocate"},
|
||||
{0x61d3850, HostBridgeKind::kAlignedAllocate,
|
||||
"aligned-allocate-direct"},
|
||||
{0x1d57328, HostBridgeKind::kFree, "free"}}},
|
||||
6,
|
||||
{0, 0, 0x7296c88, 0x400, 0x1d53c54, 0x1dc76a0,
|
||||
0x71d6c90, 0x71d2c40, 0x400000},
|
||||
{0x1d53568, 0x1d57328},
|
||||
0x6733128,
|
||||
3565,
|
||||
{{{4, 5}, {7, 3565}}},
|
||||
2,
|
||||
{{{4, 3565}}},
|
||||
1,
|
||||
4,
|
||||
{0x2132c5c, 0x71d6d30},
|
||||
HostAllocatorStrategy::kNativeMimalloc},
|
||||
// Roblox 2.736.1408. Derived from the verified 2908 profile and validated
|
||||
// by two isolated no-recovery Vulkan canaries and real game sessions.
|
||||
{"ade08266c67aee88ec9c1d00902150e1684dad3a",
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
#include <openssl/evp.h>
|
||||
|
||||
#include "compat/elf_build_id.h"
|
||||
#include "compat/guest_abi.h"
|
||||
|
||||
namespace mocktail::compat {
|
||||
namespace {
|
||||
@@ -611,19 +612,26 @@ std::unique_ptr<OwnedHostAbiProfile> ParseProfile(const Json& root,
|
||||
*error = "external host ABI profile has inconsistent constructor policy";
|
||||
return nullptr;
|
||||
}
|
||||
if (owned->profile.init_array_count <= 5 ||
|
||||
// The verified constructor layout is the same on both guest ABIs: a single
|
||||
// process-load constructor at the thread-initializer checkpoint, two wiring
|
||||
// entries excluded under host bridges, and one contiguous native-mimalloc
|
||||
// replay from the checkpoint to the end of .init_array. Only the checkpoint
|
||||
// index itself differs between payloads.
|
||||
const std::size_t checkpoint =
|
||||
owned->profile.native_mimalloc_thread_initializer_after_constructor;
|
||||
if (owned->profile.init_array_count <= checkpoint + 3 ||
|
||||
owned->profile.constructor_run_range_count != 2 ||
|
||||
owned->profile.constructor_run_ranges[0].begin != 2 ||
|
||||
owned->profile.constructor_run_ranges[0].end_exclusive != 3 ||
|
||||
owned->profile.constructor_run_ranges[1].begin != 5 ||
|
||||
owned->profile.constructor_run_ranges[0].begin != checkpoint ||
|
||||
owned->profile.constructor_run_ranges[0].end_exclusive != checkpoint + 1 ||
|
||||
owned->profile.constructor_run_ranges[1].begin != checkpoint + 3 ||
|
||||
owned->profile.constructor_run_ranges[1].end_exclusive !=
|
||||
owned->profile.init_array_count ||
|
||||
owned->profile.native_mimalloc_constructor_run_range_count != 1 ||
|
||||
owned->profile.native_mimalloc_constructor_run_ranges[0].begin != 2 ||
|
||||
owned->profile.native_mimalloc_constructor_run_ranges[0].begin !=
|
||||
checkpoint ||
|
||||
owned->profile.native_mimalloc_constructor_run_ranges[0].end_exclusive !=
|
||||
owned->profile.init_array_count ||
|
||||
owned->profile.native_mimalloc_thread_initializer_after_constructor !=
|
||||
2) {
|
||||
(kGuestElfMachine == EM_X86_64 && checkpoint != 2)) {
|
||||
*error =
|
||||
"external host ABI profile changed the verified constructor policy";
|
||||
return nullptr;
|
||||
@@ -669,9 +677,10 @@ bool ValidateProfileAgainstElf(const std::string& payload_path,
|
||||
}
|
||||
GElf_Ehdr header{};
|
||||
if (gelf_getehdr(elf.get(), &header) == nullptr ||
|
||||
gelf_getclass(elf.get()) != ELFCLASS64 || header.e_machine != EM_X86_64 ||
|
||||
header.e_type != ET_DYN) {
|
||||
*error = "payload must be an x86-64 ET_DYN ELF object";
|
||||
gelf_getclass(elf.get()) != ELFCLASS64 ||
|
||||
header.e_machine != kGuestElfMachine || header.e_type != ET_DYN) {
|
||||
*error = "payload must be a " + std::string(kGuestAbi) +
|
||||
" ET_DYN ELF object";
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// Android Vulkan loader ABI -> host Vulkan loader + SDL3 WSI.
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <pthread.h>
|
||||
#include <time.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
@@ -11,12 +12,14 @@
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <deque>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "mocktail/graphics/android_vulkan_wsi_adapter.h"
|
||||
#include "mocktail/graphics/chrome_trace_writer.h"
|
||||
#include "mocktail/graphics/present_mode_policy.h"
|
||||
#include "mocktail/graphics/vulkan_etc2_emulation.h"
|
||||
#include "mocktail/graphics/vulkan_text_overlay_compositor.h"
|
||||
@@ -1011,7 +1014,8 @@ VkResult WaitForSemaphoresObserved(const char* call_name,
|
||||
}
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
static_cast<void>(call_name);
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
call_name, "wait");
|
||||
const VkResult result = host_wait(device, wait_info, timeout);
|
||||
if (observation != nullptr) {
|
||||
observation->SetResult(result);
|
||||
@@ -1130,7 +1134,12 @@ ObservedHostQueuePresent(VkQueue queue, const VkPresentInfoKHR* present_info) {
|
||||
}
|
||||
const bool fps_trace = FpsTraceEnabled();
|
||||
const std::uint64_t present_start_ns = fps_trace ? MonotonicNanos() : 0;
|
||||
const VkResult result = host_present(queue, present_info);
|
||||
VkResult result = VK_SUCCESS;
|
||||
{
|
||||
mocktail::graphics::TraceScope scope(
|
||||
mocktail::graphics::ActiveProfileTrace(), "host present", "present");
|
||||
result = host_present(queue, present_info);
|
||||
}
|
||||
if (fps_trace) {
|
||||
PresentWaitTrace().Record(present_start_ns);
|
||||
}
|
||||
@@ -1142,6 +1151,159 @@ ObservedHostQueuePresent(VkQueue queue, const VkPresentInfoKHR* present_info) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Samples the time between successive adapter present calls, and the CPU
|
||||
// time the presenting thread and the whole process used in it.
|
||||
void RecordProfiledFrame(mocktail::graphics::ChromeTraceWriter* trace,
|
||||
std::uint64_t present_start_ns) {
|
||||
static std::atomic<std::uint64_t> previous_start_ns{0};
|
||||
static mocktail::graphics::FrameCpuSampler cpu_sampler;
|
||||
const std::uint64_t previous =
|
||||
previous_start_ns.exchange(present_start_ns, std::memory_order_relaxed);
|
||||
if (previous != 0 && present_start_ns > previous) {
|
||||
trace->Counter("frame interval (ms)", present_start_ns,
|
||||
static_cast<double>(present_start_ns - previous) / 1e6);
|
||||
}
|
||||
mocktail::graphics::FrameCpuSample cpu;
|
||||
if (cpu_sampler.Sample(static_cast<std::uint64_t>(pthread_self()),
|
||||
mocktail::graphics::TraceThreadCpuNanos(),
|
||||
mocktail::graphics::TraceProcessCpuNanos(), &cpu)) {
|
||||
trace->Counter("process cpu (ms)", present_start_ns, cpu.process_ms);
|
||||
if (cpu.has_thread) {
|
||||
trace->Counter("present thread cpu (ms)", present_start_ns,
|
||||
cpu.thread_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pipeline and shader creation is wrapped only while profiling, so a normal
|
||||
// session calls the host driver directly.
|
||||
VkResult VKAPI_CALL ProfiledCreateGraphicsPipelines(
|
||||
VkDevice device, VkPipelineCache cache, std::uint32_t count,
|
||||
const VkGraphicsPipelineCreateInfo* infos,
|
||||
const VkAllocationCallbacks* allocator, VkPipeline* pipelines) {
|
||||
const auto host = reinterpret_cast<PFN_vkCreateGraphicsPipelines>(
|
||||
HostDeviceProc(device, "vkCreateGraphicsPipelines"));
|
||||
if (host == nullptr) {
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkCreateGraphicsPipelines",
|
||||
"pipeline");
|
||||
const VkResult result =
|
||||
host(device, cache, count, infos, allocator, pipelines);
|
||||
scope.Arg("count", count);
|
||||
scope.Arg("cache", cache != VK_NULL_HANDLE);
|
||||
scope.Arg("result", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
VkResult VKAPI_CALL ProfiledCreateComputePipelines(
|
||||
VkDevice device, VkPipelineCache cache, std::uint32_t count,
|
||||
const VkComputePipelineCreateInfo* infos,
|
||||
const VkAllocationCallbacks* allocator, VkPipeline* pipelines) {
|
||||
const auto host = reinterpret_cast<PFN_vkCreateComputePipelines>(
|
||||
HostDeviceProc(device, "vkCreateComputePipelines"));
|
||||
if (host == nullptr) {
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkCreateComputePipelines",
|
||||
"pipeline");
|
||||
const VkResult result =
|
||||
host(device, cache, count, infos, allocator, pipelines);
|
||||
scope.Arg("count", count);
|
||||
scope.Arg("cache", cache != VK_NULL_HANDLE);
|
||||
scope.Arg("result", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
VkResult VKAPI_CALL ProfiledCreateShaderModule(
|
||||
VkDevice device, const VkShaderModuleCreateInfo* create_info,
|
||||
const VkAllocationCallbacks* allocator, VkShaderModule* shader_module) {
|
||||
const auto host = reinterpret_cast<PFN_vkCreateShaderModule>(
|
||||
HostDeviceProc(device, "vkCreateShaderModule"));
|
||||
if (host == nullptr) {
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkCreateShaderModule", "pipeline");
|
||||
const VkResult result = host(device, create_info, allocator, shader_module);
|
||||
scope.Arg("bytes", create_info != nullptr
|
||||
? static_cast<std::int64_t>(create_info->codeSize)
|
||||
: 0);
|
||||
scope.Arg("result", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
VkResult VKAPI_CALL ProfiledCreatePipelineCache(
|
||||
VkDevice device, const VkPipelineCacheCreateInfo* create_info,
|
||||
const VkAllocationCallbacks* allocator, VkPipelineCache* cache) {
|
||||
const auto host = reinterpret_cast<PFN_vkCreatePipelineCache>(
|
||||
HostDeviceProc(device, "vkCreatePipelineCache"));
|
||||
if (host == nullptr) {
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkCreatePipelineCache", "pipeline");
|
||||
const VkResult result = host(device, create_info, allocator, cache);
|
||||
scope.Arg("initial_bytes",
|
||||
create_info != nullptr
|
||||
? static_cast<std::int64_t>(create_info->initialDataSize)
|
||||
: 0);
|
||||
scope.Arg("result", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
VkResult VKAPI_CALL ProfiledAllocateMemory(
|
||||
VkDevice device, const VkMemoryAllocateInfo* allocate_info,
|
||||
const VkAllocationCallbacks* allocator, VkDeviceMemory* memory) {
|
||||
const auto host = reinterpret_cast<PFN_vkAllocateMemory>(
|
||||
HostDeviceProc(device, "vkAllocateMemory"));
|
||||
if (host == nullptr) {
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkAllocateMemory", "memory");
|
||||
const VkResult result = host(device, allocate_info, allocator, memory);
|
||||
scope.Arg("bytes", allocate_info != nullptr
|
||||
? static_cast<std::int64_t>(
|
||||
allocate_info->allocationSize)
|
||||
: 0);
|
||||
scope.Arg("type", allocate_info != nullptr
|
||||
? static_cast<std::int64_t>(
|
||||
allocate_info->memoryTypeIndex)
|
||||
: -1);
|
||||
scope.Arg("result", result);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Null unless profiling is on and `name` is a profiled device command.
|
||||
// These take precedence over the ETC2 wrappers, so a command both wrap is
|
||||
// timed inside its adapter function instead.
|
||||
PFN_vkVoidFunction ProfileAdapterProc(const char* name) {
|
||||
if (name == nullptr || mocktail::graphics::ActiveProfileTrace() == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
if (std::strcmp(name, "vkCreateGraphicsPipelines") == 0) {
|
||||
return reinterpret_cast<PFN_vkVoidFunction>(
|
||||
ProfiledCreateGraphicsPipelines);
|
||||
}
|
||||
if (std::strcmp(name, "vkCreateComputePipelines") == 0) {
|
||||
return reinterpret_cast<PFN_vkVoidFunction>(
|
||||
ProfiledCreateComputePipelines);
|
||||
}
|
||||
if (std::strcmp(name, "vkCreateShaderModule") == 0) {
|
||||
return reinterpret_cast<PFN_vkVoidFunction>(ProfiledCreateShaderModule);
|
||||
}
|
||||
if (std::strcmp(name, "vkCreatePipelineCache") == 0) {
|
||||
return reinterpret_cast<PFN_vkVoidFunction>(ProfiledCreatePipelineCache);
|
||||
}
|
||||
if (std::strcmp(name, "vkAllocateMemory") == 0) {
|
||||
return reinterpret_cast<PFN_vkVoidFunction>(ProfiledAllocateMemory);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
template <typename Function>
|
||||
Function HostPhysicalDeviceProc(const char* name, const char* alias) {
|
||||
VkInstance instance = VK_NULL_HANDLE;
|
||||
@@ -1180,18 +1342,134 @@ void ReleaseEtc2PoolCommandBuffers(VkDevice device,
|
||||
}
|
||||
}
|
||||
|
||||
void PrepareEtc2Submit2(std::uint32_t submit_count,
|
||||
const VkSubmitInfo2* submits) {
|
||||
if (submits == nullptr) {
|
||||
return;
|
||||
// The stage the decoded staging bytes are read at. Every emulated upload is
|
||||
// a buffer-to-image copy, so the transfer stage is the earliest point the GPU
|
||||
// may touch them.
|
||||
constexpr VkPipelineStageFlags kEtc2WaitStage = VK_PIPELINE_STAGE_TRANSFER_BIT;
|
||||
|
||||
// Holds the arrays a rewritten submit points at, so they outlive the call.
|
||||
// Deques keep earlier elements addressable as later ones are appended.
|
||||
struct Etc2SubmitRewrite {
|
||||
std::deque<std::vector<VkSemaphore>> wait_semaphores;
|
||||
std::deque<std::vector<VkPipelineStageFlags>> wait_stages;
|
||||
std::deque<std::vector<std::uint64_t>> wait_values;
|
||||
std::deque<std::vector<std::uint64_t>> signal_values;
|
||||
std::deque<VkTimelineSemaphoreSubmitInfo> timelines;
|
||||
std::deque<std::vector<VkSemaphoreSubmitInfo>> wait_infos;
|
||||
std::vector<VkSubmitInfo> rewritten;
|
||||
std::vector<VkSubmitInfo2> rewritten2;
|
||||
};
|
||||
|
||||
// Adds each submit's decode wait to its wait list. A submit whose pNext chain
|
||||
// already sizes arrays by its own semaphore counts is decoded on this thread
|
||||
// instead: a VkTimelineSemaphoreSubmitInfo would have to be rebuilt, and a
|
||||
// VkDeviceGroupSubmitInfo's pWaitSemaphoreDeviceIndices would be left one
|
||||
// entry short of the grown wait list.
|
||||
const VkSubmitInfo* PrepareEtc2Submit(std::uint32_t submit_count,
|
||||
const VkSubmitInfo* submits,
|
||||
Etc2SubmitRewrite* rewrite) {
|
||||
if (submits == nullptr || submit_count == 0) {
|
||||
return submits;
|
||||
}
|
||||
bool rewritten_any = false;
|
||||
for (std::uint32_t index = 0; index < submit_count; ++index) {
|
||||
for (std::uint32_t info = 0; info < submits[index].commandBufferInfoCount;
|
||||
++info) {
|
||||
State().etc2.PrepareSubmit(
|
||||
&submits[index].pCommandBufferInfos[info].commandBuffer, 1);
|
||||
const VkSubmitInfo& original = submits[index];
|
||||
const bool fixed_wait_list =
|
||||
FindFeature(original.pNext,
|
||||
VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO) !=
|
||||
nullptr ||
|
||||
FindFeature(original.pNext,
|
||||
VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO) != nullptr;
|
||||
const mocktail::graphics::Etc2SubmitWait wait = State().etc2.PrepareSubmit(
|
||||
original.pCommandBuffers, original.commandBufferCount,
|
||||
!fixed_wait_list);
|
||||
if (wait.semaphore == VK_NULL_HANDLE) {
|
||||
continue;
|
||||
}
|
||||
if (!rewritten_any) {
|
||||
rewrite->rewritten.assign(submits, submits + submit_count);
|
||||
rewritten_any = true;
|
||||
}
|
||||
std::vector<VkSemaphore>& semaphores = rewrite->wait_semaphores.emplace_back(
|
||||
original.pWaitSemaphores,
|
||||
original.pWaitSemaphores + original.waitSemaphoreCount);
|
||||
semaphores.push_back(wait.semaphore);
|
||||
std::vector<VkPipelineStageFlags>& stages =
|
||||
rewrite->wait_stages.emplace_back(
|
||||
original.pWaitDstStageMask,
|
||||
original.pWaitDstStageMask + original.waitSemaphoreCount);
|
||||
stages.push_back(kEtc2WaitStage);
|
||||
// Binary semaphores ignore their value; only the appended entry is read.
|
||||
std::vector<std::uint64_t>& values = rewrite->wait_values.emplace_back(
|
||||
original.waitSemaphoreCount, 0);
|
||||
values.push_back(wait.value);
|
||||
|
||||
VkTimelineSemaphoreSubmitInfo& timeline =
|
||||
rewrite->timelines.emplace_back();
|
||||
timeline.sType = VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO;
|
||||
timeline.pNext = original.pNext;
|
||||
timeline.waitSemaphoreValueCount = static_cast<std::uint32_t>(values.size());
|
||||
timeline.pWaitSemaphoreValues = values.data();
|
||||
if (original.signalSemaphoreCount != 0) {
|
||||
std::vector<std::uint64_t>& signals =
|
||||
rewrite->signal_values.emplace_back(original.signalSemaphoreCount, 0);
|
||||
timeline.signalSemaphoreValueCount =
|
||||
static_cast<std::uint32_t>(signals.size());
|
||||
timeline.pSignalSemaphoreValues = signals.data();
|
||||
}
|
||||
|
||||
VkSubmitInfo& target = rewrite->rewritten[index];
|
||||
target.pNext = &timeline;
|
||||
target.waitSemaphoreCount = static_cast<std::uint32_t>(semaphores.size());
|
||||
target.pWaitSemaphores = semaphores.data();
|
||||
target.pWaitDstStageMask = stages.data();
|
||||
}
|
||||
return rewritten_any ? rewrite->rewritten.data() : submits;
|
||||
}
|
||||
|
||||
const VkSubmitInfo2* PrepareEtc2Submit2(std::uint32_t submit_count,
|
||||
const VkSubmitInfo2* submits,
|
||||
Etc2SubmitRewrite* rewrite) {
|
||||
if (submits == nullptr || submit_count == 0) {
|
||||
return submits;
|
||||
}
|
||||
bool rewritten_any = false;
|
||||
for (std::uint32_t index = 0; index < submit_count; ++index) {
|
||||
const VkSubmitInfo2& original = submits[index];
|
||||
std::vector<VkCommandBuffer> command_buffers;
|
||||
command_buffers.reserve(original.commandBufferInfoCount);
|
||||
for (std::uint32_t info = 0; info < original.commandBufferInfoCount;
|
||||
++info) {
|
||||
command_buffers.push_back(
|
||||
original.pCommandBufferInfos[info].commandBuffer);
|
||||
}
|
||||
const mocktail::graphics::Etc2SubmitWait wait = State().etc2.PrepareSubmit(
|
||||
command_buffers.data(),
|
||||
static_cast<std::uint32_t>(command_buffers.size()), true);
|
||||
if (wait.semaphore == VK_NULL_HANDLE) {
|
||||
continue;
|
||||
}
|
||||
if (!rewritten_any) {
|
||||
rewrite->rewritten2.assign(submits, submits + submit_count);
|
||||
rewritten_any = true;
|
||||
}
|
||||
std::vector<VkSemaphoreSubmitInfo>& waits = rewrite->wait_infos.emplace_back(
|
||||
original.pWaitSemaphoreInfos,
|
||||
original.pWaitSemaphoreInfos + original.waitSemaphoreInfoCount);
|
||||
VkSemaphoreSubmitInfo decoded{};
|
||||
decoded.sType = VK_STRUCTURE_TYPE_SEMAPHORE_SUBMIT_INFO;
|
||||
decoded.semaphore = wait.semaphore;
|
||||
decoded.value = wait.value;
|
||||
// Matches kEtc2WaitStage: the staging bytes are read by transfer
|
||||
// commands, which includes the blits an upscaled upload records.
|
||||
decoded.stageMask = VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT;
|
||||
waits.push_back(decoded);
|
||||
|
||||
VkSubmitInfo2& target = rewrite->rewritten2[index];
|
||||
target.waitSemaphoreInfoCount = static_cast<std::uint32_t>(waits.size());
|
||||
target.pWaitSemaphoreInfos = waits.data();
|
||||
}
|
||||
return rewritten_any ? rewrite->rewritten2.data() : submits;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
@@ -1397,6 +1675,10 @@ vkGetInstanceProcAddr(VkInstance instance, const char* name) {
|
||||
vkGetPhysicalDeviceSurfacePresentModesKHR)
|
||||
: nullptr;
|
||||
}
|
||||
if (const PFN_vkVoidFunction profiled = ProfileAdapterProc(name);
|
||||
profiled != nullptr) {
|
||||
return HostInstanceProc(instance, name) != nullptr ? profiled : nullptr;
|
||||
}
|
||||
if (const PFN_vkVoidFunction adapter = AdapterProc(name);
|
||||
adapter != nullptr) {
|
||||
if ((IsDeviceAdapterProc(name) || IsEtc2PhysicalDeviceProc(name)) &&
|
||||
@@ -1418,6 +1700,10 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkDevice device,
|
||||
const PFN_vkVoidFunction host = host_get_device_proc_addr != nullptr
|
||||
? host_get_device_proc_addr(device, name)
|
||||
: nullptr;
|
||||
if (const PFN_vkVoidFunction profiled = ProfileAdapterProc(name);
|
||||
profiled != nullptr) {
|
||||
return host != nullptr ? profiled : nullptr;
|
||||
}
|
||||
if (!IsDeviceAdapterProc(name)) {
|
||||
return host;
|
||||
}
|
||||
@@ -1536,7 +1822,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(
|
||||
host_memory_properties(physical_device, &memory_properties);
|
||||
}
|
||||
State().etc2.RegisterDevice(*device, physical_device, etc2_emulated,
|
||||
memory_properties, host_get_device_proc_addr);
|
||||
memory_properties, host_get_device_proc_addr,
|
||||
enabled.vulkan12.timelineSemaphore == VK_TRUE);
|
||||
|
||||
std::uint32_t queue_family_count = 0;
|
||||
const auto host_get_queue_families =
|
||||
@@ -1599,6 +1886,10 @@ vkDestroyDevice(VkDevice device, const VkAllocationCallbacks* allocator) {
|
||||
host_destroy(device, allocator);
|
||||
}
|
||||
RemoveHostDeviceDispatch(device);
|
||||
if (auto* trace = mocktail::graphics::ActiveProfileTrace();
|
||||
trace != nullptr) {
|
||||
trace->Flush();
|
||||
}
|
||||
}
|
||||
|
||||
VKAPI_ATTR void VKAPI_CALL vkGetDeviceQueue(VkDevice device,
|
||||
@@ -1754,6 +2045,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImageKHR(
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkAcquireNextImageKHR", "wait");
|
||||
const bool fps_trace = FpsTraceEnabled();
|
||||
const std::uint64_t acquire_start_ns = fps_trace ? MonotonicNanos() : 0;
|
||||
const VkResult host_result = host_acquire(
|
||||
@@ -1783,6 +2076,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkAcquireNextImage2KHR(
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkAcquireNextImage2KHR", "wait");
|
||||
const VkResult host_result =
|
||||
host_acquire(device, acquire_info, image_index);
|
||||
const VkResult result = NormalizeSwapchainResult(host_result);
|
||||
@@ -1807,6 +2102,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkWaitForFences(
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkWaitForFences", "wait");
|
||||
const bool fps_trace = FpsTraceEnabled();
|
||||
const std::uint64_t fence_start_ns = fps_trace ? MonotonicNanos() : 0;
|
||||
const VkResult result =
|
||||
@@ -2002,14 +2299,14 @@ VKAPI_ATTR VkResult VKAPI_CALL vkQueueSubmit(
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
if (submits != nullptr) {
|
||||
for (std::uint32_t index = 0; index < submit_count; ++index) {
|
||||
State().etc2.PrepareSubmit(submits[index].pCommandBuffers,
|
||||
submits[index].commandBufferCount);
|
||||
}
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkQueueSubmit", "submit");
|
||||
scope.Arg("submits", submit_count);
|
||||
Etc2SubmitRewrite rewrite;
|
||||
const VkSubmitInfo* prepared =
|
||||
PrepareEtc2Submit(submit_count, submits, &rewrite);
|
||||
const VkResult result = State().text_overlay.QueueSubmit(
|
||||
queue, submit_count, submits, fence, host_submit);
|
||||
queue, submit_count, prepared, fence, host_submit);
|
||||
observation.SetResult(result);
|
||||
return result;
|
||||
}
|
||||
@@ -2024,9 +2321,14 @@ VKAPI_ATTR VkResult VKAPI_CALL vkQueueSubmit2(
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
PrepareEtc2Submit2(submit_count, submits);
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkQueueSubmit2", "submit");
|
||||
scope.Arg("submits", submit_count);
|
||||
Etc2SubmitRewrite rewrite;
|
||||
const VkSubmitInfo2* prepared =
|
||||
PrepareEtc2Submit2(submit_count, submits, &rewrite);
|
||||
const VkResult result = State().text_overlay.QueueSubmit2(
|
||||
queue, submit_count, submits, fence, host_submit);
|
||||
queue, submit_count, prepared, fence, host_submit);
|
||||
observation.SetResult(result);
|
||||
return result;
|
||||
}
|
||||
@@ -2041,9 +2343,14 @@ VKAPI_ATTR VkResult VKAPI_CALL vkQueueSubmit2KHR(
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
PrepareEtc2Submit2(submit_count, submits);
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkQueueSubmit2KHR", "submit");
|
||||
scope.Arg("submits", submit_count);
|
||||
Etc2SubmitRewrite rewrite;
|
||||
const VkSubmitInfo2* prepared =
|
||||
PrepareEtc2Submit2(submit_count, submits, &rewrite);
|
||||
const VkResult result = State().text_overlay.QueueSubmit2(
|
||||
queue, submit_count, submits, fence,
|
||||
queue, submit_count, prepared, fence,
|
||||
reinterpret_cast<PFN_vkQueueSubmit2>(host_submit));
|
||||
observation.SetResult(result);
|
||||
return result;
|
||||
@@ -2073,6 +2380,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkQueueWaitIdle(VkQueue queue) {
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkQueueWaitIdle", "wait");
|
||||
const bool fps_trace = FpsTraceEnabled();
|
||||
const std::uint64_t idle_start_ns = fps_trace ? MonotonicNanos() : 0;
|
||||
const VkResult result =
|
||||
@@ -2092,6 +2401,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkDeviceWaitIdle(VkDevice device) {
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkDeviceWaitIdle", "wait");
|
||||
const VkResult result =
|
||||
State().text_overlay.DeviceWaitIdle(device, host_wait);
|
||||
observation.SetResult(result);
|
||||
@@ -2210,8 +2521,15 @@ vkQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR* present_info) {
|
||||
observation.SetResult(VK_ERROR_INITIALIZATION_FAILED);
|
||||
return VK_ERROR_INITIALIZATION_FAILED;
|
||||
}
|
||||
mocktail::graphics::ChromeTraceWriter* const trace =
|
||||
mocktail::graphics::ActiveProfileTrace();
|
||||
mocktail::graphics::TraceScope scope(trace, "vkQueuePresentKHR", "present");
|
||||
if (trace != nullptr) {
|
||||
RecordProfiledFrame(trace, mocktail::graphics::TraceClockNanos());
|
||||
}
|
||||
const VkResult result = state.text_overlay.QueuePresent(
|
||||
queue, present_info, ObservedHostQueuePresent);
|
||||
scope.Arg("result", result);
|
||||
const VkResult normalized_result = NormalizeSwapchainResult(result);
|
||||
if (normalized_result == VK_ERROR_OUT_OF_DATE_KHR) {
|
||||
const NoteSurfaceOutOfDateFn note_surface_out_of_date =
|
||||
@@ -2375,11 +2693,15 @@ VKAPI_ATTR VkResult VKAPI_CALL vkGetPhysicalDeviceImageFormatProperties2(
|
||||
VKAPI_ATTR VkResult VKAPI_CALL vkCreateImage(
|
||||
VkDevice device, const VkImageCreateInfo* create_info,
|
||||
const VkAllocationCallbacks* allocator, VkImage* image) {
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkCreateImage", "memory");
|
||||
return State().etc2.CreateImage(device, create_info, allocator, image);
|
||||
}
|
||||
|
||||
VKAPI_ATTR void VKAPI_CALL vkDestroyImage(
|
||||
VkDevice device, VkImage image, const VkAllocationCallbacks* allocator) {
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkDestroyImage", "memory");
|
||||
State().etc2.DestroyImage(device, image, allocator);
|
||||
}
|
||||
|
||||
@@ -2408,6 +2730,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkMapMemory(VkDevice device,
|
||||
VkDeviceSize size,
|
||||
VkMemoryMapFlags flags,
|
||||
void** data) {
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkMapMemory", "memory");
|
||||
return State().etc2.MapMemory(device, memory, offset, size, flags, data);
|
||||
}
|
||||
|
||||
@@ -2419,6 +2743,9 @@ VKAPI_ATTR VkResult VKAPI_CALL vkMapMemory2(VkDevice device,
|
||||
|
||||
VKAPI_ATTR void VKAPI_CALL vkUnmapMemory(VkDevice device,
|
||||
VkDeviceMemory memory) {
|
||||
// Includes waiting for ETC2 decodes that still read this memory.
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkUnmapMemory", "memory");
|
||||
State().etc2.UnmapMemory(device, memory);
|
||||
}
|
||||
|
||||
@@ -2430,6 +2757,9 @@ VKAPI_ATTR VkResult VKAPI_CALL vkUnmapMemory2(VkDevice device,
|
||||
VKAPI_ATTR void VKAPI_CALL vkFreeMemory(
|
||||
VkDevice device, VkDeviceMemory memory,
|
||||
const VkAllocationCallbacks* allocator) {
|
||||
// Includes waiting for ETC2 decodes that still read this memory.
|
||||
mocktail::graphics::TraceScope scope(mocktail::graphics::ActiveProfileTrace(),
|
||||
"vkFreeMemory", "memory");
|
||||
State().etc2.FreeMemory(device, memory, allocator);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
#include "mocktail/graphics/chrome_trace_writer.h"
|
||||
|
||||
#include <sys/types.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cerrno>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace mocktail {
|
||||
namespace graphics {
|
||||
namespace {
|
||||
|
||||
// Buffered bytes that wake the writer before its periodic tick.
|
||||
constexpr std::size_t kWakeBytes = 256 * 1024;
|
||||
constexpr std::chrono::milliseconds kWriteInterval{250};
|
||||
// Every write ends the file with this, and the next write starts over it.
|
||||
constexpr char kArrayEnd[] = "\n]\n";
|
||||
constexpr long kArrayEndBytes = sizeof(kArrayEnd) - 1;
|
||||
|
||||
void AppendInteger(std::string* out, std::int64_t value) {
|
||||
char digits[24];
|
||||
const auto [end, error] =
|
||||
std::to_chars(digits, digits + sizeof(digits), value);
|
||||
if (error == std::errc()) {
|
||||
out->append(digits, end);
|
||||
} else {
|
||||
// Appending nothing would leave "ts": with no value, which costs the
|
||||
// whole trace rather than the one field.
|
||||
out->push_back('0');
|
||||
}
|
||||
}
|
||||
|
||||
void AppendDouble(std::string* out, double value) {
|
||||
// to_chars spells inf and nan without quotes, which no JSON reader accepts.
|
||||
if (!std::isfinite(value)) {
|
||||
out->push_back('0');
|
||||
return;
|
||||
}
|
||||
char digits[32];
|
||||
const auto [end, error] =
|
||||
std::to_chars(digits, digits + sizeof(digits), value);
|
||||
if (error == std::errc()) {
|
||||
out->append(digits, end);
|
||||
} else {
|
||||
out->push_back('0');
|
||||
}
|
||||
}
|
||||
|
||||
void AppendString(std::string* out, const char* value) {
|
||||
out->push_back('"');
|
||||
for (const char* cursor = value != nullptr ? value : ""; *cursor != '\0';
|
||||
++cursor) {
|
||||
const unsigned char byte = static_cast<unsigned char>(*cursor);
|
||||
if (byte == '"' || byte == '\\') {
|
||||
out->push_back('\\');
|
||||
out->push_back(static_cast<char>(byte));
|
||||
} else if (byte < 0x20) {
|
||||
static constexpr char kHex[] = "0123456789abcdef";
|
||||
out->append("\\u00");
|
||||
out->push_back(kHex[byte >> 4]);
|
||||
out->push_back(kHex[byte & 0xf]);
|
||||
} else {
|
||||
out->push_back(static_cast<char>(byte));
|
||||
}
|
||||
}
|
||||
out->push_back('"');
|
||||
}
|
||||
|
||||
void AppendHeader(std::string* out, const char* name, const char* category,
|
||||
char phase, std::uint64_t timestamp_ns) {
|
||||
static const std::int64_t pid = getpid();
|
||||
thread_local const std::int64_t tid = gettid();
|
||||
out->append("{\"name\":");
|
||||
AppendString(out, name);
|
||||
if (category != nullptr) {
|
||||
out->append(",\"cat\":");
|
||||
AppendString(out, category);
|
||||
}
|
||||
out->append(",\"ph\":\"");
|
||||
out->push_back(phase);
|
||||
out->append("\",\"ts\":");
|
||||
AppendInteger(out, static_cast<std::int64_t>(timestamp_ns / 1000));
|
||||
out->append(",\"pid\":");
|
||||
AppendInteger(out, pid);
|
||||
out->append(",\"tid\":");
|
||||
AppendInteger(out, tid);
|
||||
}
|
||||
|
||||
std::string& ThreadScratch() {
|
||||
thread_local std::string scratch;
|
||||
scratch.clear();
|
||||
return scratch;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::uint64_t TraceClockNanos() {
|
||||
timespec now{};
|
||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
return static_cast<std::uint64_t>(now.tv_sec) * 1'000'000'000ULL +
|
||||
static_cast<std::uint64_t>(now.tv_nsec);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
std::uint64_t ClockNanos(clockid_t clock) {
|
||||
timespec now{};
|
||||
clock_gettime(clock, &now);
|
||||
return static_cast<std::uint64_t>(now.tv_sec) * 1'000'000'000ULL +
|
||||
static_cast<std::uint64_t>(now.tv_nsec);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::uint64_t TraceThreadCpuNanos() {
|
||||
return ClockNanos(CLOCK_THREAD_CPUTIME_ID);
|
||||
}
|
||||
|
||||
std::uint64_t TraceProcessCpuNanos() {
|
||||
return ClockNanos(CLOCK_PROCESS_CPUTIME_ID);
|
||||
}
|
||||
|
||||
bool FrameCpuSampler::Sample(std::uint64_t thread_id,
|
||||
std::uint64_t thread_cpu_ns,
|
||||
std::uint64_t process_cpu_ns,
|
||||
FrameCpuSample* sample) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
const bool had_previous = has_previous_;
|
||||
// Clocks are read before the lock, so a reading can arrive after a later
|
||||
// one; a reused thread id restarts its thread clock. Neither may wrap.
|
||||
if (had_previous) {
|
||||
*sample = {};
|
||||
if (process_cpu_ns > previous_process_cpu_ns_) {
|
||||
sample->process_ms =
|
||||
static_cast<double>(process_cpu_ns - previous_process_cpu_ns_) / 1e6;
|
||||
}
|
||||
if (thread_id == previous_thread_id_ &&
|
||||
thread_cpu_ns >= previous_thread_cpu_ns_) {
|
||||
sample->has_thread = true;
|
||||
sample->thread_ms =
|
||||
static_cast<double>(thread_cpu_ns - previous_thread_cpu_ns_) / 1e6;
|
||||
}
|
||||
}
|
||||
has_previous_ = true;
|
||||
previous_thread_id_ = thread_id;
|
||||
previous_thread_cpu_ns_ = thread_cpu_ns;
|
||||
previous_process_cpu_ns_ = std::max(previous_process_cpu_ns_, process_cpu_ns);
|
||||
return had_previous;
|
||||
}
|
||||
|
||||
std::unique_ptr<ChromeTraceWriter> ChromeTraceWriter::Open(
|
||||
const std::filesystem::path& path, std::string* error) {
|
||||
std::FILE* file = std::fopen(path.c_str(), "wb");
|
||||
if (file == nullptr || std::fputs("[", file) == EOF ||
|
||||
std::fputs(kArrayEnd, file) == EOF || std::fflush(file) != 0) {
|
||||
const int saved = errno;
|
||||
if (file != nullptr) {
|
||||
std::fclose(file);
|
||||
}
|
||||
if (error != nullptr) {
|
||||
*error = "could not open profile trace " + path.string() + ": " +
|
||||
std::strerror(saved);
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
return std::unique_ptr<ChromeTraceWriter>(new ChromeTraceWriter(file));
|
||||
}
|
||||
|
||||
ChromeTraceWriter::ChromeTraceWriter(std::FILE* file)
|
||||
: file_(file), owner_pid_(getpid()) {
|
||||
writer_ = std::thread([this] { WriterLoop(); });
|
||||
}
|
||||
|
||||
ChromeTraceWriter::~ChromeTraceWriter() { Close(); }
|
||||
|
||||
void ChromeTraceWriter::Slice(const char* name, const char* category,
|
||||
std::uint64_t start_ns, std::uint64_t end_ns,
|
||||
std::initializer_list<TraceArg> args) {
|
||||
Slice(name, category, start_ns, end_ns, args.begin(), args.size());
|
||||
}
|
||||
|
||||
void ChromeTraceWriter::Slice(const char* name, const char* category,
|
||||
std::uint64_t start_ns, std::uint64_t end_ns,
|
||||
const TraceArg* args, std::size_t arg_count) {
|
||||
std::string& event = ThreadScratch();
|
||||
AppendHeader(&event, name, category, 'X', start_ns);
|
||||
event.append(",\"dur\":");
|
||||
const std::uint64_t start_us = start_ns / 1000;
|
||||
const std::uint64_t end_us = end_ns / 1000;
|
||||
AppendInteger(&event, static_cast<std::int64_t>(
|
||||
end_us > start_us ? end_us - start_us : 0));
|
||||
if (args != nullptr && arg_count != 0) {
|
||||
event.append(",\"args\":{");
|
||||
for (std::size_t index = 0; index < arg_count; ++index) {
|
||||
if (index != 0) {
|
||||
event.push_back(',');
|
||||
}
|
||||
AppendString(&event, args[index].key);
|
||||
event.push_back(':');
|
||||
AppendInteger(&event, args[index].value);
|
||||
}
|
||||
event.push_back('}');
|
||||
}
|
||||
event.push_back('}');
|
||||
Append(event.data(), event.size());
|
||||
}
|
||||
|
||||
void ChromeTraceWriter::Counter(const char* name, std::uint64_t timestamp_ns,
|
||||
double value) {
|
||||
std::string& event = ThreadScratch();
|
||||
AppendHeader(&event, name, nullptr, 'C', timestamp_ns);
|
||||
event.append(",\"args\":{\"value\":");
|
||||
AppendDouble(&event, value);
|
||||
event.append("}}");
|
||||
Append(event.data(), event.size());
|
||||
}
|
||||
|
||||
void ChromeTraceWriter::Append(const char* event, std::size_t size) {
|
||||
bool wake = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (closed_) {
|
||||
return;
|
||||
}
|
||||
pending_.append(first_event_ ? "\n" : ",\n");
|
||||
first_event_ = false;
|
||||
pending_.append(event, size);
|
||||
wake = pending_.size() >= kWakeBytes;
|
||||
}
|
||||
if (wake) {
|
||||
wake_.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
void ChromeTraceWriter::WriterLoop() {
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
while (!stopping_) {
|
||||
wake_.wait_for(lock, kWriteInterval, [this] {
|
||||
return stopping_ || pending_.size() >= kWakeBytes;
|
||||
});
|
||||
if (stopping_) {
|
||||
break;
|
||||
}
|
||||
lock.unlock();
|
||||
WritePending();
|
||||
lock.lock();
|
||||
}
|
||||
}
|
||||
|
||||
// The file lock is taken before the buffer lock, so chunks reach the file in
|
||||
// the order they were buffered.
|
||||
void ChromeTraceWriter::WritePending() {
|
||||
std::lock_guard<std::mutex> file_lock(file_mutex_);
|
||||
spare_.clear();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
pending_.swap(spare_);
|
||||
}
|
||||
if (file_ == nullptr || spare_.empty()) {
|
||||
return;
|
||||
}
|
||||
if (std::fseek(file_, -kArrayEndBytes, SEEK_END) != 0 ||
|
||||
std::fwrite(spare_.data(), 1, spare_.size(), file_) != spare_.size() ||
|
||||
std::fputs(kArrayEnd, file_) == EOF || std::fflush(file_) != 0) {
|
||||
std::fprintf(stderr, " [profile] trace write failed: %s\n",
|
||||
std::strerror(errno));
|
||||
std::fclose(file_);
|
||||
file_ = nullptr;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
closed_ = true;
|
||||
// Nothing can reach the file now, so the writer thread exits instead of
|
||||
// ticking for the rest of the process.
|
||||
stopping_ = true;
|
||||
}
|
||||
wake_.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
void ChromeTraceWriter::Flush() { WritePending(); }
|
||||
|
||||
void ChromeTraceWriter::Close() {
|
||||
// A forked child shares the file but not the writer thread.
|
||||
if (getpid() != owner_pid_) {
|
||||
return;
|
||||
}
|
||||
// A write failure sets stopping_ without joining the thread, so the join
|
||||
// below runs even when stopping_ is already set.
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
stopping_ = true;
|
||||
}
|
||||
wake_.notify_all();
|
||||
if (writer_.joinable() && writer_.get_id() != std::this_thread::get_id()) {
|
||||
writer_.join();
|
||||
}
|
||||
WritePending();
|
||||
std::lock_guard<std::mutex> file_lock(file_mutex_);
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
closed_ = true;
|
||||
}
|
||||
if (file_ != nullptr) {
|
||||
std::fclose(file_);
|
||||
file_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
ChromeTraceWriter* ActiveProfileTrace() {
|
||||
static ChromeTraceWriter* const trace = []() -> ChromeTraceWriter* {
|
||||
const char* path = std::getenv(kProfileTraceEnvironment);
|
||||
if (path == nullptr || path[0] == '\0') {
|
||||
return nullptr;
|
||||
}
|
||||
std::string error;
|
||||
std::unique_ptr<ChromeTraceWriter> writer =
|
||||
ChromeTraceWriter::Open(path, &error);
|
||||
if (writer == nullptr) {
|
||||
std::fprintf(stderr, " [profile] %s\n", error.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
std::fprintf(stderr, " [profile] writing Chrome trace to %s\n", path);
|
||||
// Leaked so threads still recording during exit never touch a destroyed
|
||||
// writer; they find it closed instead.
|
||||
static struct CloseAtExit {
|
||||
ChromeTraceWriter* writer;
|
||||
~CloseAtExit() { writer->Close(); }
|
||||
} close_at_exit{writer.get()};
|
||||
return writer.release();
|
||||
}();
|
||||
return trace;
|
||||
}
|
||||
|
||||
} // namespace graphics
|
||||
} // namespace mocktail
|
||||
+111
-20
@@ -5,7 +5,9 @@
|
||||
#include <pthread.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace mocktail::graphics {
|
||||
@@ -213,10 +215,11 @@ std::size_t EtcDecodedTexelBytes(EtcFormat format) {
|
||||
|
||||
namespace {
|
||||
|
||||
// Blocks per band handed to one worker: about a 256x256 texel image.
|
||||
constexpr std::uint64_t kBlocksPerBand = 16384;
|
||||
// Batches smaller than a 1024x1024 texel image decode on the caller.
|
||||
constexpr std::uint64_t kParallelMinimumBlocks = 65536;
|
||||
// Blocks per band handed to one worker: about a 128x128 texel image.
|
||||
constexpr std::uint64_t kBlocksPerBand = 4096;
|
||||
// Batches smaller than a 128x128 texel image decode on the caller. Waking a
|
||||
// pooled worker costs microseconds, so the floor only has to cover that.
|
||||
constexpr std::uint64_t kParallelMinimumBlocks = 4096;
|
||||
|
||||
bool ImageFits(EtcFormat format, const std::uint8_t* source,
|
||||
std::size_t source_bytes, std::uint32_t width,
|
||||
@@ -274,10 +277,97 @@ struct DecodeBandQueue {
|
||||
}
|
||||
};
|
||||
|
||||
void* RunDecodeBandQueue(void* queue) {
|
||||
static_cast<DecodeBandQueue*>(queue)->Run();
|
||||
return nullptr;
|
||||
}
|
||||
// Decode workers outlive the batches that use them: creating and joining a
|
||||
// thread per batch costs more than decoding a small one. The threads park on
|
||||
// a condition variable and are never joined, so the pool is leaked at exit.
|
||||
class DecodePool {
|
||||
public:
|
||||
static DecodePool& Instance() {
|
||||
static DecodePool* pool = new DecodePool();
|
||||
return *pool;
|
||||
}
|
||||
|
||||
// Calls run(context) on the calling thread and on pooled workers, `workers`
|
||||
// calls in all. Returns false without calling it when another batch
|
||||
// already holds the pool or no worker could be started, leaving the whole
|
||||
// batch to the caller.
|
||||
bool Run(void (*run)(void*), void* context, std::size_t workers) {
|
||||
if (workers < 2) {
|
||||
return false;
|
||||
}
|
||||
std::unique_lock<std::mutex> batch(batch_mutex_, std::try_to_lock);
|
||||
if (!batch.owns_lock()) {
|
||||
return false;
|
||||
}
|
||||
const std::size_t helpers = Reserve(workers - 1);
|
||||
if (helpers == 0) {
|
||||
return false;
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
run_ = run;
|
||||
context_ = context;
|
||||
unclaimed_ = helpers;
|
||||
running_ = helpers;
|
||||
}
|
||||
ready_.notify_all();
|
||||
run(context);
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
done_.wait(lock, [this] { return running_ == 0; });
|
||||
run_ = nullptr;
|
||||
context_ = nullptr;
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
DecodePool() = default;
|
||||
|
||||
// Grows the pool towards `wanted` and reports how many workers exist, so a
|
||||
// pthread_create failure degrades instead of deadlocking the wait below.
|
||||
std::size_t Reserve(std::size_t wanted) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
while (threads_ < wanted) {
|
||||
pthread_t worker;
|
||||
if (pthread_create(&worker, nullptr, &DecodePool::RunWorker, this) != 0) {
|
||||
break;
|
||||
}
|
||||
pthread_detach(worker);
|
||||
++threads_;
|
||||
}
|
||||
return std::min(threads_, wanted);
|
||||
}
|
||||
|
||||
static void* RunWorker(void* pool) {
|
||||
static_cast<DecodePool*>(pool)->WorkerLoop();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void WorkerLoop() {
|
||||
std::unique_lock<std::mutex> lock(mutex_);
|
||||
for (;;) {
|
||||
ready_.wait(lock, [this] { return unclaimed_ > 0; });
|
||||
--unclaimed_;
|
||||
void (*run)(void*) = run_;
|
||||
void* context = context_;
|
||||
lock.unlock();
|
||||
run(context);
|
||||
lock.lock();
|
||||
if (--running_ == 0) {
|
||||
done_.notify_all();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::mutex batch_mutex_;
|
||||
std::mutex mutex_;
|
||||
std::condition_variable ready_;
|
||||
std::condition_variable done_;
|
||||
void (*run_)(void*) = nullptr;
|
||||
void* context_ = nullptr;
|
||||
std::size_t unclaimed_ = 0;
|
||||
std::size_t running_ = 0;
|
||||
std::size_t threads_ = 0;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -311,19 +401,20 @@ void DecodeEtcJobs(EtcDecodeJob* jobs, std::size_t count,
|
||||
total_blocks < kParallelMinimumBlocks
|
||||
? 1
|
||||
: std::min<std::size_t>(std::max(worker_count, 1U), bands.size());
|
||||
std::vector<pthread_t> workers;
|
||||
workers.reserve(threads > 0 ? threads - 1 : 0);
|
||||
for (std::size_t index = 1; index < threads; ++index) {
|
||||
pthread_t worker;
|
||||
// The caller decodes whatever workers that failed to start leave behind.
|
||||
if (pthread_create(&worker, nullptr, RunDecodeBandQueue, &queue) != 0) {
|
||||
break;
|
||||
}
|
||||
workers.push_back(worker);
|
||||
RunOnDecodeWorkers(
|
||||
[](void* context) { static_cast<DecodeBandQueue*>(context)->Run(); },
|
||||
&queue, static_cast<unsigned>(threads));
|
||||
}
|
||||
|
||||
void RunOnDecodeWorkers(void (*run)(void*), void* context,
|
||||
unsigned worker_count) {
|
||||
if (run == nullptr) {
|
||||
return;
|
||||
}
|
||||
queue.Run();
|
||||
for (pthread_t worker : workers) {
|
||||
pthread_join(worker, nullptr);
|
||||
// The pool declines when it is already busy; the caller drains the whole
|
||||
// batch itself then, exactly as a single-threaded batch does.
|
||||
if (!DecodePool::Instance().Run(run, context, worker_count)) {
|
||||
run(context);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <png.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
@@ -82,6 +83,23 @@ void ResampleRgba(const std::uint8_t* source, std::uint32_t source_width,
|
||||
height == 0 || source_width == 0 || source_height == 0) {
|
||||
return;
|
||||
}
|
||||
// Source box of destination column x is [columns[2x], columns[2x + 1]).
|
||||
thread_local std::vector<std::uint32_t> columns;
|
||||
columns.resize(static_cast<std::size_t>(width) * 2);
|
||||
bool one_texel_columns = true;
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
const std::uint32_t x0 = static_cast<std::uint32_t>(
|
||||
static_cast<std::uint64_t>(x) * source_width / width);
|
||||
const std::uint32_t x1 = std::max<std::uint32_t>(
|
||||
x0 + 1, static_cast<std::uint32_t>(
|
||||
(static_cast<std::uint64_t>(x) + 1) * source_width / width));
|
||||
columns[2 * static_cast<std::size_t>(x)] = x0;
|
||||
columns[2 * static_cast<std::size_t>(x) + 1] = x1;
|
||||
one_texel_columns = one_texel_columns && x1 == x0 + 1;
|
||||
}
|
||||
const std::size_t row_bytes = static_cast<std::size_t>(width) * 4;
|
||||
std::uint64_t previous_y0 = 0;
|
||||
std::uint64_t previous_y1 = 0;
|
||||
for (std::uint32_t y = 0; y < height; ++y) {
|
||||
const std::uint64_t y0 = static_cast<std::uint64_t>(y) * source_height / height;
|
||||
std::uint64_t y1 =
|
||||
@@ -89,13 +107,25 @@ void ResampleRgba(const std::uint8_t* source, std::uint32_t source_width,
|
||||
if (y1 <= y0) {
|
||||
y1 = y0 + 1;
|
||||
}
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
const std::uint64_t x0 = static_cast<std::uint64_t>(x) * source_width / width;
|
||||
std::uint64_t x1 =
|
||||
(static_cast<std::uint64_t>(x) + 1) * source_width / width;
|
||||
if (x1 <= x0) {
|
||||
x1 = x0 + 1;
|
||||
std::uint8_t* out_row = destination + y * row_bytes;
|
||||
if (y > 0 && y0 == previous_y0 && y1 == previous_y1) {
|
||||
std::memcpy(out_row, out_row - row_bytes, row_bytes);
|
||||
continue;
|
||||
}
|
||||
previous_y0 = y0;
|
||||
previous_y1 = y1;
|
||||
if (one_texel_columns && y1 == y0 + 1) {
|
||||
const std::uint8_t* source_row = source + y0 * source_width * 4;
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
std::memcpy(out_row + static_cast<std::size_t>(x) * 4,
|
||||
source_row + columns[2 * static_cast<std::size_t>(x)] * 4,
|
||||
4);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
for (std::uint32_t x = 0; x < width; ++x) {
|
||||
const std::uint64_t x0 = columns[2 * static_cast<std::size_t>(x)];
|
||||
const std::uint64_t x1 = columns[2 * static_cast<std::size_t>(x) + 1];
|
||||
std::uint64_t sum[4] = {0, 0, 0, 0};
|
||||
for (std::uint64_t sy = y0; sy < y1; ++sy) {
|
||||
for (std::uint64_t sx = x0; sx < x1; ++sx) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+119
-37
@@ -62,7 +62,10 @@ thread_local JNIEnv* g_thread_local_env = nullptr;
|
||||
thread_local JNIEnv g_thread_env_storage = {};
|
||||
thread_local VM* g_thread_vm_instance = nullptr;
|
||||
thread_local mocktail::audio::FmodThreadFloatingPointMode g_thread_audio_fp_mode;
|
||||
thread_local std::vector<std::vector<jobject>> g_local_frames;
|
||||
// Each frame counts how many local references it holds per handle, so
|
||||
// DeleteLocalRef costs one hash lookup per open frame.
|
||||
using LocalFrame = std::unordered_map<jobject, uint32_t>;
|
||||
thread_local std::vector<LocalFrame> g_local_frames;
|
||||
|
||||
std::recursive_mutex g_jni_state_mutex;
|
||||
// Authentication preflight can briefly own a second VM. Keep every live
|
||||
@@ -289,6 +292,10 @@ constexpr uint32_t kJniHandleShift = 16;
|
||||
std::shared_ptr<void> g_segment_owners[kJniSegmentCapacity];
|
||||
std::unordered_set<jclass> g_known_classes;
|
||||
std::unordered_map<std::string, jobject> g_singleton_objects;
|
||||
std::unordered_set<jobject> g_singleton_handles;
|
||||
// One handle per Class. Class slots are never freed, so the table holds at
|
||||
// most one slot per distinct class.
|
||||
std::unordered_map<const Class*, jclass> g_class_handles;
|
||||
std::unordered_map<std::string, std::shared_ptr<Class>> g_fallback_classes;
|
||||
std::unordered_set<jstring> g_known_strings;
|
||||
std::list<std::string> g_method_name_storage;
|
||||
@@ -339,7 +346,7 @@ void RegisterLocalRef(jobject obj) {
|
||||
return;
|
||||
}
|
||||
EnsureLocalFrame();
|
||||
g_local_frames.back().push_back(obj);
|
||||
++g_local_frames.back()[obj];
|
||||
}
|
||||
|
||||
void UnregisterLocalRef(jobject obj) {
|
||||
@@ -348,10 +355,27 @@ void UnregisterLocalRef(jobject obj) {
|
||||
}
|
||||
for (auto frame = g_local_frames.rbegin(); frame != g_local_frames.rend();
|
||||
++frame) {
|
||||
for (auto it = frame->rbegin(); it != frame->rend(); ++it) {
|
||||
if (*it == obj) {
|
||||
frame->erase(std::next(it).base());
|
||||
return;
|
||||
auto it = frame->find(obj);
|
||||
if (it != frame->end()) {
|
||||
if (--it->second == 0) {
|
||||
frame->erase(it);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ReleaseJniReference(jobject obj);
|
||||
|
||||
// A detached thread can no longer use its local references, so they go the
|
||||
// way ART drops them on detach.
|
||||
void ReleaseThreadLocalRefs() {
|
||||
std::vector<LocalFrame> frames = std::move(g_local_frames);
|
||||
g_local_frames.clear();
|
||||
for (const LocalFrame& frame : frames) {
|
||||
for (const auto& [obj, count] : frame) {
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
ReleaseJniReference(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -370,6 +394,8 @@ void RetainJniReference(jobject obj) {
|
||||
}
|
||||
}
|
||||
|
||||
void ReportHandleTableFull();
|
||||
|
||||
int AllocateSegmentSlot(void* value, std::shared_ptr<void> owner = nullptr,
|
||||
SegmentType type = SegmentType::kObject) {
|
||||
std::lock_guard<std::recursive_mutex> lock(g_jni_state_mutex);
|
||||
@@ -381,6 +407,7 @@ int AllocateSegmentSlot(void* value, std::shared_ptr<void> owner = nullptr,
|
||||
static_cast<uint32_t>(g_jni_ref_index) < kJniSegmentCapacity) {
|
||||
index = g_jni_ref_index++;
|
||||
} else {
|
||||
ReportHandleTableFull();
|
||||
return 0;
|
||||
}
|
||||
my_segment[index] = value;
|
||||
@@ -739,6 +766,13 @@ std::shared_ptr<Class> ClassFromJClass(jclass clazz) {
|
||||
static jclass StoreClass(std::shared_ptr<Class> cls) {
|
||||
std::lock_guard<std::recursive_mutex> lock(g_jni_state_mutex);
|
||||
Class* raw_ptr = cls.get();
|
||||
if (raw_ptr == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
auto cached = g_class_handles.find(raw_ptr);
|
||||
if (cached != g_class_handles.end()) {
|
||||
return cached->second;
|
||||
}
|
||||
int index = AllocateSegmentSlot(raw_ptr, cls, SegmentType::kClass);
|
||||
if (index <= 0) {
|
||||
return nullptr;
|
||||
@@ -746,6 +780,7 @@ static jclass StoreClass(std::shared_ptr<Class> cls) {
|
||||
jclass handle =
|
||||
reinterpret_cast<jclass>(JniHandleFromIndex(static_cast<uint32_t>(index)));
|
||||
g_known_classes.insert(handle);
|
||||
g_class_handles.emplace(raw_ptr, handle);
|
||||
return handle;
|
||||
}
|
||||
|
||||
@@ -790,10 +825,8 @@ void ReleaseJniReference(jobject obj) {
|
||||
g_known_classes.end()) {
|
||||
return;
|
||||
}
|
||||
for (const auto& pair : g_singleton_objects) {
|
||||
if (pair.second == obj) {
|
||||
return;
|
||||
}
|
||||
if (g_singleton_handles.count(obj) != 0) {
|
||||
return;
|
||||
}
|
||||
const uint32_t index = JniIndexFromHandle(obj);
|
||||
if (index > 0 && index < kJniSegmentCapacity) {
|
||||
@@ -850,6 +883,7 @@ jobject SingletonObject(const std::string& class_name) {
|
||||
}
|
||||
jobject object = MakeObjectForClass(class_name);
|
||||
g_singleton_objects[class_name] = object;
|
||||
g_singleton_handles.insert(object);
|
||||
return object;
|
||||
}
|
||||
|
||||
@@ -861,6 +895,38 @@ std::string_view ObjectClassName(jobject obj) {
|
||||
return pseudo_object->GetClass()->GetName();
|
||||
}
|
||||
|
||||
// Logs once per process which classes hold the live handles, so the leak
|
||||
// behind a later null FindClass or NewStringUTF can be named.
|
||||
void ReportHandleTableFull() {
|
||||
std::lock_guard<std::recursive_mutex> lock(g_jni_state_mutex);
|
||||
static bool reported = false;
|
||||
if (reported) {
|
||||
return;
|
||||
}
|
||||
reported = true;
|
||||
std::unordered_map<std::string_view, std::size_t> live_by_class;
|
||||
for (const auto& entry : g_object_storage) {
|
||||
std::string_view name = ObjectClassName(entry.first);
|
||||
++live_by_class[name.empty() ? std::string_view("<unknown>") : name];
|
||||
}
|
||||
std::vector<std::pair<std::string_view, std::size_t>> ranked(
|
||||
live_by_class.begin(), live_by_class.end());
|
||||
const std::size_t shown = std::min<std::size_t>(ranked.size(), 10);
|
||||
std::partial_sort(ranked.begin(), ranked.begin() + shown, ranked.end(),
|
||||
[](const auto& a, const auto& b) {
|
||||
return a.second > b.second;
|
||||
});
|
||||
fprintf(stderr,
|
||||
"[JNI] handle table full (%u slots): %zu objects, %zu classes, "
|
||||
"%zu arrays live; new objects return null\n",
|
||||
kJniSegmentCapacity, g_object_storage.size(),
|
||||
g_class_handles.size(), g_array_storage.size());
|
||||
for (std::size_t i = 0; i < shown; ++i) {
|
||||
fprintf(stderr, "[JNI] %zu x %.*s\n", ranked[i].second,
|
||||
static_cast<int>(ranked[i].first.size()), ranked[i].first.data());
|
||||
}
|
||||
}
|
||||
|
||||
jobject ExactMessageBusStaticObject(jclass clazz, jmethodID method_id) {
|
||||
const std::shared_ptr<Class> object_class = ClassFromJClass(clazz);
|
||||
if (object_class == nullptr ||
|
||||
@@ -881,6 +947,8 @@ jobject EngineJavaCallbackObject() {
|
||||
}
|
||||
g_engine_java_callback =
|
||||
MakeObjectForClass("com/roblox/engine/jni/EngineJavaCallback2");
|
||||
// VM-owned like a singleton, so detaching the creating thread keeps it.
|
||||
g_singleton_handles.insert(g_engine_java_callback);
|
||||
g_static_object_fields["sImplementation"] = g_engine_java_callback;
|
||||
return g_engine_java_callback;
|
||||
}
|
||||
@@ -1149,7 +1217,7 @@ static inline bool IsRawStringPointer(jstring str) {
|
||||
if (val < 0x10000) {
|
||||
return false;
|
||||
}
|
||||
if (val < 0x10000000ULL && (val & 0xffff) == 0) {
|
||||
if ((val & 0xffff) == 0 && (val >> kJniHandleShift) < kJniSegmentCapacity) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
@@ -1582,9 +1650,13 @@ jlong ParseLocalStorageUserIdFromEnv() {
|
||||
if (!value || value[0] == '\0') {
|
||||
return 0;
|
||||
}
|
||||
errno = 0;
|
||||
char* end = nullptr;
|
||||
long long parsed = std::strtoll(value, &end, 10);
|
||||
return end == value ? 0 : static_cast<jlong>(parsed);
|
||||
if (errno == ERANGE || end == value || *end != '\0') {
|
||||
return 0;
|
||||
}
|
||||
return static_cast<jlong>(parsed);
|
||||
}
|
||||
|
||||
jlong CurrentLocalStorageUserLocked() {
|
||||
@@ -2230,10 +2302,9 @@ bool HandleRobloxCookieSetVoidMethodA(jobject obj, jmethodID method_id,
|
||||
|
||||
jobject MakeFileObject(const char* path) {
|
||||
jobject file = MakeObjectForClass("java/io/File");
|
||||
auto* pseudo_object = PseudoObjectFromRef(file);
|
||||
if (pseudo_object) {
|
||||
pseudo_object->object_fields["path"] = MakeString(path);
|
||||
}
|
||||
// The field owns a reference, so the calling thread's local ref can be
|
||||
// released on detach without freeing the value.
|
||||
SetStringFieldRaw(file, "path", path);
|
||||
return file;
|
||||
}
|
||||
|
||||
@@ -2270,25 +2341,26 @@ jobject MakeDeviceStaticParamsObject() {
|
||||
auto* pseudo_object = PseudoObjectFromRef(object);
|
||||
if (pseudo_object) {
|
||||
const PlatformIdentity identity = CurrentPlatformIdentity();
|
||||
pseudo_object->object_fields["osVersion"] = MakeString("Android 13");
|
||||
pseudo_object->object_fields["deviceName"] =
|
||||
MakeString(identity.device_name.c_str());
|
||||
// The field owns a reference, so the calling thread's local ref can be
|
||||
// released on detach without freeing the value.
|
||||
const auto set_string = [pseudo_object](const char* field,
|
||||
const char* value) {
|
||||
jobject text = MakeString(value);
|
||||
RetainJniReference(text);
|
||||
pseudo_object->object_fields[field] = text;
|
||||
};
|
||||
set_string("osVersion", "Android 13");
|
||||
set_string("deviceName", identity.device_name.c_str());
|
||||
const char* app_version = std::getenv("MOCKTAIL_ROBLOX_VERSION");
|
||||
pseudo_object->object_fields["appVersion"] =
|
||||
MakeString(app_version != nullptr ? app_version : "unknown");
|
||||
pseudo_object->object_fields["manufacturer"] =
|
||||
MakeString(identity.manufacturer.c_str());
|
||||
pseudo_object->object_fields["model"] = MakeString(identity.model.c_str());
|
||||
pseudo_object->object_fields["brand"] = MakeString(identity.brand.c_str());
|
||||
pseudo_object->object_fields["device"] =
|
||||
MakeString(identity.device_code.c_str());
|
||||
pseudo_object->object_fields["deviceSku"] =
|
||||
MakeString(identity.device_sku.c_str());
|
||||
pseudo_object->object_fields["appBuildVariant"] = MakeString("headless");
|
||||
pseudo_object->object_fields["socModel"] =
|
||||
MakeString(identity.soc_model.c_str());
|
||||
pseudo_object->object_fields["soc_model"] =
|
||||
MakeString(identity.soc_model.c_str());
|
||||
set_string("appVersion", app_version != nullptr ? app_version : "unknown");
|
||||
set_string("manufacturer", identity.manufacturer.c_str());
|
||||
set_string("model", identity.model.c_str());
|
||||
set_string("brand", identity.brand.c_str());
|
||||
set_string("device", identity.device_code.c_str());
|
||||
set_string("deviceSku", identity.device_sku.c_str());
|
||||
set_string("appBuildVariant", "headless");
|
||||
set_string("socModel", identity.soc_model.c_str());
|
||||
set_string("soc_model", identity.soc_model.c_str());
|
||||
pseudo_object->boolean_fields["cpu64Bit"] = JNI_TRUE;
|
||||
const mocktail::runtime::DisplaySize host_display =
|
||||
mocktail::runtime::ParseDisplaySize(
|
||||
@@ -6486,6 +6558,7 @@ void VM::InitJNIFunctionTables() {
|
||||
if (g_thread_vm_instance != owner || !IsThreadLocalEnvValid()) {
|
||||
return JNI_EDETACHED;
|
||||
}
|
||||
ReleaseThreadLocalRefs();
|
||||
g_thread_audio_fp_mode.Restore();
|
||||
g_thread_local_env = nullptr;
|
||||
g_thread_vm_instance = nullptr;
|
||||
@@ -6615,17 +6688,26 @@ void VM::InitJNIFunctionTables() {
|
||||
native_interface_.PopLocalFrame =
|
||||
[](JNIEnv* /*env*/, jobject result) -> jobject {
|
||||
EnsureLocalFrame();
|
||||
std::vector<jobject> frame = std::move(g_local_frames.back());
|
||||
LocalFrame frame = std::move(g_local_frames.back());
|
||||
if (g_local_frames.size() > 1) {
|
||||
g_local_frames.pop_back();
|
||||
} else {
|
||||
g_local_frames.back().clear();
|
||||
}
|
||||
for (jobject obj : frame) {
|
||||
if (obj != result) {
|
||||
bool result_kept = false;
|
||||
for (const auto& [obj, count] : frame) {
|
||||
uint32_t releases = count;
|
||||
if (obj == result) {
|
||||
--releases;
|
||||
result_kept = true;
|
||||
}
|
||||
for (uint32_t i = 0; i < releases; ++i) {
|
||||
ReleaseJniReference(obj);
|
||||
}
|
||||
}
|
||||
if (result != nullptr && !result_kept) {
|
||||
RetainJniReference(result);
|
||||
}
|
||||
RegisterLocalRef(result);
|
||||
return result;
|
||||
};
|
||||
|
||||
+175
-14
@@ -37,7 +37,9 @@
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/prctl.h>
|
||||
#if defined(__x86_64__)
|
||||
#include <asm/prctl.h>
|
||||
#endif
|
||||
#include <sys/syscall.h>
|
||||
#include <vector>
|
||||
|
||||
@@ -50,6 +52,7 @@
|
||||
#include "compat/bionic_socket_runtime.h"
|
||||
#include "compat/build_profile.h"
|
||||
#include "compat/elf_build_id.h"
|
||||
#include "compat/guest_abi.h"
|
||||
#include "compat/host_abi_experiment.h"
|
||||
#include "compat/host_abi_profile.h"
|
||||
#include "compat/host_allocator_bridge.h"
|
||||
@@ -58,6 +61,8 @@
|
||||
#include "libc_shim/libc_shim.h"
|
||||
#include "linker/linker.h"
|
||||
#include "mocktail/graphics/bionic_egl_bridge.h"
|
||||
#include "mocktail/graphics/chrome_trace_writer.h"
|
||||
#include "runtime/engine_pump_rest.h"
|
||||
#include "runtime/device_memory_profile.h"
|
||||
#include "runtime/display_size.h"
|
||||
#include "runtime/environment.h"
|
||||
@@ -762,7 +767,12 @@ uint64_t MonotonicNanos() {
|
||||
static_cast<uint64_t>(ts.tv_nsec);
|
||||
}
|
||||
|
||||
JNIEnv* AttachMainThreadJniEnv() {
|
||||
// `attached` reports whether AttachCurrentThread itself succeeded, so a caller
|
||||
// that caches the env can tell a real attach from the GetJNIEnv fallback.
|
||||
JNIEnv* AttachMainThreadJniEnv(bool* attached = nullptr) {
|
||||
if (attached != nullptr) {
|
||||
*attached = false;
|
||||
}
|
||||
if (g_vm_for_main_thread_pump == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
@@ -773,6 +783,9 @@ JNIEnv* AttachMainThreadJniEnv() {
|
||||
jint attach_result = java_vm->AttachCurrentThread(&raw_env, nullptr);
|
||||
if (attach_result == JNI_OK && raw_env != nullptr) {
|
||||
env = static_cast<JNIEnv*>(raw_env);
|
||||
if (attached != nullptr) {
|
||||
*attached = true;
|
||||
}
|
||||
} else if (IsEnabled("MOCKTAIL_TRACE_MAIN_THREAD_PUMP")) {
|
||||
std::cerr << " [main] AttachCurrentThread failed in pump: "
|
||||
<< attach_result << '\n'
|
||||
@@ -787,6 +800,35 @@ JNIEnv* AttachMainThreadJniEnv() {
|
||||
return env;
|
||||
}
|
||||
|
||||
// The pseudo-VM attach is idempotent: once this thread holds a live env for
|
||||
// the VM, re-attaching hands back the same thread-local pointer. Only the
|
||||
// main thread calls this, so the cache needs no synchronization. The game
|
||||
// session installs RestoreGameSessionJniEnvironment, which restores the JNI
|
||||
// function tables when a guest JNI_OnLoad replaces them.
|
||||
JNIEnv* MainThreadPumpJniEnv() {
|
||||
static JNIEnv* cached_env = nullptr;
|
||||
static const jnivm::VM* cached_vm = nullptr;
|
||||
if (cached_env != nullptr && cached_vm == g_vm_for_main_thread_pump) {
|
||||
// Only the attach is cached. The table restore and the env publish run on
|
||||
// every tick: a guest JNI_OnLoad can replace the function tables, and any
|
||||
// other thread that publishes its own env overwrites the single global
|
||||
// slot this one shares.
|
||||
g_vm_for_main_thread_pump->RestoreFunctions();
|
||||
PublishCurrentJniEnv(cached_env);
|
||||
return cached_env;
|
||||
}
|
||||
// Only a real attach is worth caching. The GetJNIEnv fallback means this
|
||||
// thread is not attached to the VM, and the next tick has to retry: a VM
|
||||
// swap can make AttachCurrentThread fail for one tick and succeed after.
|
||||
bool attached = false;
|
||||
JNIEnv* env = AttachMainThreadJniEnv(&attached);
|
||||
if (env != nullptr && attached) {
|
||||
cached_env = env;
|
||||
cached_vm = g_vm_for_main_thread_pump;
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
bool InvokeTaskSchedulerForeground(
|
||||
JNIEnv* env, jclass native_gl_class,
|
||||
NativeSetTaskSchedulerBackgroundModeFn native_set_task_scheduler_background_mode,
|
||||
@@ -905,6 +947,43 @@ bool RunTaskSchedulerForegroundOnMainThread(
|
||||
}
|
||||
}
|
||||
|
||||
// The profile trace writer is compiled into the Vulkan adapter, which the host
|
||||
// dlopens RTLD_GLOBAL, so the pump slice goes through symbols resolved from it.
|
||||
// Until the adapter is loaded there is no writer and nothing is recorded.
|
||||
struct PumpTraceHooks {
|
||||
using ActiveFn = mocktail::graphics::ChromeTraceWriter* (*)();
|
||||
using ClockFn = std::uint64_t (*)();
|
||||
using SliceFn = void (*)(mocktail::graphics::ChromeTraceWriter*, const char*,
|
||||
const char*, std::uint64_t, std::uint64_t,
|
||||
const mocktail::graphics::TraceArg*, std::size_t);
|
||||
ActiveFn active = nullptr;
|
||||
ClockFn clock = nullptr;
|
||||
SliceFn slice = nullptr;
|
||||
};
|
||||
|
||||
const PumpTraceHooks& PumpTrace() {
|
||||
static PumpTraceHooks hooks;
|
||||
// The adapter loads during startup, so a few hundred ticks cover it. After
|
||||
// that the lookups stop and the pump stays untraced.
|
||||
static int attempts = 0;
|
||||
if (hooks.active == nullptr && attempts++ < 1000) {
|
||||
PumpTraceHooks resolved;
|
||||
resolved.active = reinterpret_cast<PumpTraceHooks::ActiveFn>(
|
||||
::dlsym(RTLD_DEFAULT, "_ZN8mocktail8graphics18ActiveProfileTraceEv"));
|
||||
resolved.clock = reinterpret_cast<PumpTraceHooks::ClockFn>(
|
||||
::dlsym(RTLD_DEFAULT, "_ZN8mocktail8graphics15TraceClockNanosEv"));
|
||||
resolved.slice = reinterpret_cast<PumpTraceHooks::SliceFn>(::dlsym(
|
||||
RTLD_DEFAULT,
|
||||
"_ZN8mocktail8graphics17ChromeTraceWriter5SliceEPKcS3_mmPKNS0_"
|
||||
"8TraceArgEm"));
|
||||
if (resolved.active != nullptr && resolved.clock != nullptr &&
|
||||
resolved.slice != nullptr) {
|
||||
hooks = resolved;
|
||||
}
|
||||
}
|
||||
return hooks;
|
||||
}
|
||||
|
||||
void PumpRobloxMainThreadMessagesOnce() {
|
||||
static const bool force_early =
|
||||
IsEnabled("MOCKTAIL_FORCE_EARLY_MAIN_THREAD_MESSAGE_PUMP");
|
||||
@@ -944,7 +1023,7 @@ void PumpRobloxMainThreadMessagesOnce() {
|
||||
return;
|
||||
}
|
||||
|
||||
JNIEnv* env = AttachMainThreadJniEnv();
|
||||
JNIEnv* env = MainThreadPumpJniEnv();
|
||||
if (env == nullptr) {
|
||||
static bool logged_missing_env = false;
|
||||
if (!logged_missing_env && trace_pump) {
|
||||
@@ -966,8 +1045,33 @@ void PumpRobloxMainThreadMessagesOnce() {
|
||||
<< std::flush;
|
||||
}
|
||||
}
|
||||
const PumpTraceHooks& hooks = PumpTrace();
|
||||
mocktail::graphics::ChromeTraceWriter* trace =
|
||||
hooks.active != nullptr ? hooks.active() : nullptr;
|
||||
const std::uint64_t pump_start_ns = trace != nullptr ? hooks.clock() : 0;
|
||||
// CPU time separates a step that computes from one that waits.
|
||||
const auto thread_cpu_ns = [] {
|
||||
timespec now{};
|
||||
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
|
||||
return static_cast<std::uint64_t>(now.tv_sec) * 1'000'000'000ULL +
|
||||
static_cast<std::uint64_t>(now.tv_nsec);
|
||||
};
|
||||
const std::uint64_t pump_start_cpu_ns =
|
||||
trace != nullptr ? thread_cpu_ns() : 0;
|
||||
g_native_call_messages_from_main_thread(
|
||||
env, g_native_gl_class_for_main_thread);
|
||||
if (trace != nullptr) {
|
||||
// Empty polls run at kilohertz rates and would swamp the trace, so only
|
||||
// calls that ran a message are recorded.
|
||||
const std::uint64_t pump_end_ns = hooks.clock();
|
||||
if (pump_end_ns - pump_start_ns >= 20'000) {
|
||||
const mocktail::graphics::TraceArg args[] = {
|
||||
{"cpu_us", static_cast<std::int64_t>(
|
||||
(thread_cpu_ns() - pump_start_cpu_ns) / 1000)}};
|
||||
hooks.slice(trace, "nativeCallMessagesFromMainThread", "pump",
|
||||
pump_start_ns, pump_end_ns, args, 1);
|
||||
}
|
||||
}
|
||||
if (__builtin_expect(trace_pump, 0)) {
|
||||
if (pump_count <= 10 || pump_count % 100 == 0) {
|
||||
std::cerr << " [main] nativeCallMessagesFromMainThread returned #"
|
||||
@@ -1007,7 +1111,7 @@ struct BionicAddrInfo {
|
||||
};
|
||||
|
||||
static_assert(sizeof(BionicAddrInfo) == 48,
|
||||
"unexpected x86_64 bionic addrinfo size");
|
||||
"unexpected bionic addrinfo size");
|
||||
|
||||
bool DnsTraceEnabled() {
|
||||
return IsEnabled("MOCKTAIL_DNS_TRACE");
|
||||
@@ -1372,15 +1476,31 @@ bool IsUnsafeSoftTimeoutModule(void* rip) {
|
||||
void JniOnLoadTimeoutAlarm(int, siginfo_t* info, void* context) {
|
||||
static_cast<void>(info);
|
||||
auto* uc = static_cast<ucontext_t*>(context);
|
||||
#if defined(__x86_64__)
|
||||
auto rip = uc ? static_cast<uintptr_t>(uc->uc_mcontext.gregs[REG_RIP]) : 0;
|
||||
auto rsp = uc ? static_cast<uintptr_t>(uc->uc_mcontext.gregs[REG_RSP]) : 0;
|
||||
auto rbp = uc ? static_cast<uintptr_t>(uc->uc_mcontext.gregs[REG_RBP]) : 0;
|
||||
auto rax = uc ? static_cast<uintptr_t>(uc->uc_mcontext.gregs[REG_RAX]) : 0;
|
||||
const char* regs_format =
|
||||
" [timeout] RIP=0x%016llx RSP=0x%016llx RBP=0x%016llx "
|
||||
"RAX=0x%016llx\n";
|
||||
#elif defined(__aarch64__)
|
||||
auto rip = uc ? static_cast<uintptr_t>(uc->uc_mcontext.pc) : 0;
|
||||
auto rsp = uc ? static_cast<uintptr_t>(uc->uc_mcontext.sp) : 0;
|
||||
auto rbp = uc ? static_cast<uintptr_t>(uc->uc_mcontext.regs[29]) : 0;
|
||||
auto rax = uc ? static_cast<uintptr_t>(uc->uc_mcontext.regs[0]) : 0;
|
||||
const char* regs_format =
|
||||
" [timeout] PC=0x%016llx SP=0x%016llx FP=0x%016llx "
|
||||
"X0=0x%016llx\n";
|
||||
#else
|
||||
uintptr_t rip = 0, rsp = 0, rbp = 0, rax = 0;
|
||||
const char* regs_format =
|
||||
" [timeout] PC=0x%016llx SP=0x%016llx FP=0x%016llx "
|
||||
"X0=0x%016llx\n";
|
||||
#endif
|
||||
char regs_msg[192];
|
||||
int len = std::snprintf(
|
||||
regs_msg, sizeof(regs_msg),
|
||||
" [timeout] RIP=0x%016llx RSP=0x%016llx RBP=0x%016llx "
|
||||
"RAX=0x%016llx\n",
|
||||
regs_msg, sizeof(regs_msg), regs_format,
|
||||
static_cast<unsigned long long>(rip), static_cast<unsigned long long>(rsp),
|
||||
static_cast<unsigned long long>(rbp), static_cast<unsigned long long>(rax));
|
||||
write(2, regs_msg, static_cast<size_t>(len));
|
||||
@@ -1414,8 +1534,11 @@ void JniOnLoadTimeoutAlarm(int, siginfo_t* info, void* context) {
|
||||
|
||||
void PublishCurrentJniEnv(JNIEnv* env) {
|
||||
using SetCurrentJniEnvFn = void (*)(void*);
|
||||
auto* set_current_jni_env = reinterpret_cast<SetCurrentJniEnvFn>(
|
||||
::dlsym(RTLD_DEFAULT, "mocktail_set_current_jni_env"));
|
||||
// RTLD_DEFAULT resolves this to the runtime's own exported setter, so the
|
||||
// address is fixed for the life of the process.
|
||||
static SetCurrentJniEnvFn set_current_jni_env =
|
||||
reinterpret_cast<SetCurrentJniEnvFn>(
|
||||
::dlsym(RTLD_DEFAULT, "mocktail_set_current_jni_env"));
|
||||
if (set_current_jni_env) {
|
||||
set_current_jni_env(env);
|
||||
}
|
||||
@@ -2425,10 +2548,12 @@ jobject BuildDeviceParams(JNIEnv* env) {
|
||||
GetEnvString("MOCKTAIL_DEVICE_NAME", "Mocktail Linux");
|
||||
const std::string manufacturer =
|
||||
GetEnvString("MOCKTAIL_DEVICE_MANUFACTURER", "Mocktail");
|
||||
const std::string device_sku =
|
||||
GetEnvString("MOCKTAIL_DEVICE_SKU", "mocktail-x86_64");
|
||||
const std::string device_sku = GetEnvString(
|
||||
"MOCKTAIL_DEVICE_SKU",
|
||||
("mocktail-" + std::string(mocktail::compat::kGuestCpuName)).c_str());
|
||||
const std::string soc_model =
|
||||
GetEnvString("MOCKTAIL_DEVICE_SOC_MODEL", "x86_64");
|
||||
GetEnvString("MOCKTAIL_DEVICE_SOC_MODEL",
|
||||
std::string(mocktail::compat::kGuestCpuName).c_str());
|
||||
SetStringField(env, params, "osVersion", "33");
|
||||
SetStringField(env, params, "deviceName", device_name.c_str());
|
||||
const std::string app_version =
|
||||
@@ -4626,12 +4751,14 @@ int mocktail::legacy::Run(const runtime::CommandLineOptions& options,
|
||||
|
||||
// Roblox internal threads trigger SI_KERNEL traps from CET shadow-stack
|
||||
// return mismatches. Unsupported kernels ignore this request.
|
||||
#if defined(__x86_64__)
|
||||
{
|
||||
long r = syscall(SYS_arch_prctl, ARCH_SHSTK_DISABLE, ARCH_SHSTK_SHSTK);
|
||||
if (r == 0) {
|
||||
std::cout << " [cet] shadow-stack (SHSTK) disabled\n";
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
if (build_profile.allow_legacy_binary_patches) {
|
||||
std::cerr
|
||||
@@ -5551,6 +5678,27 @@ int mocktail::legacy::Run(const runtime::CommandLineOptions& options,
|
||||
reinterpret_cast<void*>(mocktail_pthread_spin_trylock));
|
||||
linker::RegisterSymbol("pthread_spin_unlock",
|
||||
reinterpret_cast<void*>(mocktail_pthread_spin_unlock));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_attr_init",
|
||||
reinterpret_cast<void*>(mocktail_pthread_attr_init));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_attr_destroy",
|
||||
reinterpret_cast<void*>(mocktail_pthread_attr_destroy));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_attr_setstacksize",
|
||||
reinterpret_cast<void*>(mocktail_pthread_attr_setstacksize));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_attr_setdetachstate",
|
||||
reinterpret_cast<void*>(mocktail_pthread_attr_setdetachstate));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_attr_setschedparam",
|
||||
reinterpret_cast<void*>(mocktail_pthread_attr_setschedparam));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_getattr_np",
|
||||
reinterpret_cast<void*>(mocktail_pthread_getattr_np));
|
||||
linker::RegisterSymbol(
|
||||
"pthread_attr_getstack",
|
||||
reinterpret_cast<void*>(mocktail_pthread_attr_getstack));
|
||||
linker::RegisterSymbol("pthread_barrier_init",
|
||||
reinterpret_cast<void*>(mocktail_pthread_barrier_init));
|
||||
linker::RegisterSymbol(
|
||||
@@ -5670,7 +5818,8 @@ int mocktail::legacy::Run(const runtime::CommandLineOptions& options,
|
||||
|
||||
if (roblox_handle == nullptr) {
|
||||
std::cerr << "\n[FATAL] Could not load '" << library_path << "'.\n"
|
||||
<< " Extract lib/x86_64/libroblox.so from a Roblox APK and\n"
|
||||
<< " Extract lib/" << compat::kGuestAbi
|
||||
<< "/libroblox.so from a Roblox APK and\n"
|
||||
<< " place it at the path above (or set ROBLOX_LIB_PATH).\n";
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
@@ -6573,7 +6722,8 @@ int mocktail::legacy::Run(const runtime::CommandLineOptions& options,
|
||||
mocktail::runtime::RobloxExperienceSurfaceProvider{},
|
||||
discord_rpc.observer(),
|
||||
dependencies.clear_persisted_web_view_cookie(),
|
||||
runtime_config.microphone_enabled());
|
||||
runtime_config.microphone_enabled(),
|
||||
platform_web_symbols.account);
|
||||
const mocktail::Status platform_protocol_status =
|
||||
experience_composition->InitializePlatformProtocols();
|
||||
if (!platform_protocol_status.ok()) {
|
||||
@@ -6831,6 +6981,10 @@ int mocktail::legacy::Run(const runtime::CommandLineOptions& options,
|
||||
bool input_shutdown_completed = window_input_runtime == nullptr;
|
||||
bool resize_readiness_completed = true;
|
||||
if (mocktail::window::IsInitialised()) {
|
||||
std::cout << " [main] engine pump rest: "
|
||||
<< mocktail::runtime::EnginePumpRestModeName(
|
||||
mocktail::runtime::ActiveEnginePumpRestMode())
|
||||
<< " (MOCKTAIL_ENGINE_PUMP_REST=sleep|tpause|spin)\n";
|
||||
std::cout << " [main] entering SDL event loop (close the window to quit)\n"
|
||||
<< std::flush;
|
||||
std::unique_ptr<mocktail::window::WindowGameSurfaceBridge> surface_bridge;
|
||||
@@ -6946,7 +7100,14 @@ int mocktail::legacy::Run(const runtime::CommandLineOptions& options,
|
||||
}
|
||||
}
|
||||
const uint64_t fps_after_launch_ns = fps_trace ? MonotonicNanos() : 0;
|
||||
const uint64_t fps_pace_ns = mocktail::window::PaceInputPump();
|
||||
// The pacer sleeps only under throttled presentation. Unthrottled, the
|
||||
// engine pump above is a poll, and the rest between polls is what keeps
|
||||
// it from spinning.
|
||||
uint64_t fps_pace_ns = mocktail::window::PaceInputPump();
|
||||
if (fps_pace_ns == 0 &&
|
||||
mocktail::window::UnthrottledPresentationRequested()) {
|
||||
fps_pace_ns = mocktail::runtime::RestAfterEnginePump();
|
||||
}
|
||||
if (fps_trace) {
|
||||
const uint64_t fps_tick_end_ns = MonotonicNanos();
|
||||
++fps_samples;
|
||||
|
||||
+40
-23
@@ -11,6 +11,8 @@
|
||||
#include <filesystem>
|
||||
#include <iostream>
|
||||
#include <limits.h>
|
||||
#include <algorithm>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <unistd.h>
|
||||
#include <vector>
|
||||
@@ -20,8 +22,19 @@ namespace libc_shim {
|
||||
namespace {
|
||||
|
||||
std::unordered_map<std::string, std::string> g_path_mappings;
|
||||
// g_path_mappings ordered longest Android prefix first, so the first match
|
||||
// is the most specific one. Rebuilt whenever the mappings change.
|
||||
std::vector<std::pair<std::string, std::string>> g_ordered_mappings;
|
||||
std::vector<std::string> g_ca_bundle_aliases;
|
||||
|
||||
void RebuildOrderedMappings() {
|
||||
g_ordered_mappings.assign(g_path_mappings.begin(), g_path_mappings.end());
|
||||
std::stable_sort(g_ordered_mappings.begin(), g_ordered_mappings.end(),
|
||||
[](const auto& a, const auto& b) {
|
||||
return a.first.size() > b.first.size();
|
||||
});
|
||||
}
|
||||
|
||||
bool g_installed = false;
|
||||
std::atomic<GuestAllocator> g_guest_allocator{nullptr};
|
||||
|
||||
@@ -72,11 +85,9 @@ std::string DefaultDataRoot() {
|
||||
return RuntimeRoot() + "/data";
|
||||
}
|
||||
|
||||
bool PrefixMatchesPath(const std::string& path, const std::string& prefix) {
|
||||
if (path.size() < prefix.size()) {
|
||||
return false;
|
||||
}
|
||||
if (path.compare(0, prefix.size(), prefix) != 0) {
|
||||
bool PrefixMatchesPath(std::string_view path, std::string_view prefix) {
|
||||
if (path.size() < prefix.size() ||
|
||||
std::memcmp(path.data(), prefix.data(), prefix.size()) != 0) {
|
||||
return false;
|
||||
}
|
||||
return path.size() == prefix.size() || path[prefix.size()] == '/';
|
||||
@@ -202,6 +213,7 @@ HostCaBundleResolution ResolveHostCaBundle() {
|
||||
|
||||
HostCaBundleResolution ConfigureHostCaBundlePathMappings() {
|
||||
for (const auto& alias : g_ca_bundle_aliases) g_path_mappings.erase(alias);
|
||||
RebuildOrderedMappings();
|
||||
g_ca_bundle_aliases.assign(kAndroidCaBundlePaths.begin(), kAndroidCaBundlePaths.end());
|
||||
if (const char* content = GetEnvNonEmpty("MOCKTAIL_ASSET_PATH")) {
|
||||
auto root = std::filesystem::path(content).lexically_normal();
|
||||
@@ -297,31 +309,33 @@ void Install() {
|
||||
<< g_path_mappings.size() << " prefix mappings)\n";
|
||||
}
|
||||
|
||||
std::string TranslatePath(const std::string& android_path) {
|
||||
const std::string* best_android_prefix = nullptr;
|
||||
const std::string* best_host_prefix = nullptr;
|
||||
for (const auto& [android_prefix, host_prefix] : g_path_mappings) {
|
||||
if (PrefixMatchesPath(android_path, android_prefix) &&
|
||||
(best_android_prefix == nullptr ||
|
||||
android_prefix.size() > best_android_prefix->size())) {
|
||||
best_android_prefix = &android_prefix;
|
||||
best_host_prefix = &host_prefix;
|
||||
bool TranslatePathInto(std::string_view android_path, std::string* host_path) {
|
||||
for (const auto& [android_prefix, host_prefix] : g_ordered_mappings) {
|
||||
if (PrefixMatchesPath(android_path, android_prefix)) {
|
||||
const std::string_view rest = android_path.substr(android_prefix.size());
|
||||
host_path->reserve(host_prefix.size() + rest.size());
|
||||
host_path->assign(host_prefix);
|
||||
host_path->append(rest);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
if (best_android_prefix != nullptr && best_host_prefix != nullptr) {
|
||||
return *best_host_prefix +
|
||||
android_path.substr(best_android_prefix->size());
|
||||
}
|
||||
return android_path;
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string TranslatePath(const std::string& android_path) {
|
||||
std::string host_path;
|
||||
return TranslatePathInto(android_path, &host_path) ? host_path : android_path;
|
||||
}
|
||||
|
||||
void RegisterPathMapping(const std::string& android_prefix,
|
||||
const std::string& host_prefix) {
|
||||
g_path_mappings[android_prefix] = host_prefix;
|
||||
RebuildOrderedMappings();
|
||||
}
|
||||
|
||||
void ClearPathMappings() {
|
||||
g_path_mappings.clear();
|
||||
g_ordered_mappings.clear();
|
||||
g_ca_bundle_aliases.clear();
|
||||
}
|
||||
|
||||
@@ -333,13 +347,16 @@ const char* HostPath(const char* path, std::string* storage) {
|
||||
if (path == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
*storage = libc_shim::TranslatePath(path);
|
||||
return storage->c_str();
|
||||
return libc_shim::TranslatePathInto(path, storage) ? storage->c_str() : path;
|
||||
}
|
||||
|
||||
// Read once: the guest calls these shims on every file operation.
|
||||
bool PathTraceEnabled() {
|
||||
const char* value = std::getenv("MOCKTAIL_PATH_TRACE");
|
||||
return value != nullptr && value[0] != '\0' && value[0] != '0';
|
||||
static const bool enabled = [] {
|
||||
const char* value = std::getenv("MOCKTAIL_PATH_TRACE");
|
||||
return value != nullptr && value[0] != '\0' && value[0] != '0';
|
||||
}();
|
||||
return enabled;
|
||||
}
|
||||
|
||||
void TracePathCall(const char* name, const char* path, const char* host_path,
|
||||
|
||||
@@ -552,6 +552,12 @@ int main(int argc, char* argv[]) {
|
||||
case mocktail::runtime::GameModeSessionState::kActive:
|
||||
std::cout << " [gamemode] performance request active\n";
|
||||
break;
|
||||
case mocktail::runtime::GameModeSessionState::kDeclinedCorePinning:
|
||||
std::cout << " [gamemode] released: it pinned this process to a subset "
|
||||
"of the CPUs, which concentrates the worker pool. Set "
|
||||
"pin_cores=no in ~/.config/gamemode.ini to keep GameMode, "
|
||||
"or performance.gamemode: on to accept the pinning\n";
|
||||
break;
|
||||
case mocktail::runtime::GameModeSessionState::kAlreadyActive:
|
||||
std::cout << " [gamemode] already active for this process\n";
|
||||
break;
|
||||
|
||||
@@ -61,24 +61,24 @@ bool ConvertSdlEvent(SDL_Window* window, const SDL_Event& source,
|
||||
return true;
|
||||
case SDL_EVENT_MOUSE_MOTION:
|
||||
destination->payload = MouseMotionEvent{
|
||||
source.motion.x, source.motion.y, source.motion.xrel,
|
||||
source.motion.yrel, static_cast<std::uint32_t>(source.motion.state)};
|
||||
source.motion.x, source.motion.y,
|
||||
source.motion.xrel, source.motion.yrel,
|
||||
static_cast<std::uint32_t>(source.motion.state),
|
||||
SDL_GetWindowRelativeMouseMode(window)};
|
||||
return true;
|
||||
case SDL_EVENT_MOUSE_BUTTON_DOWN:
|
||||
case SDL_EVENT_MOUSE_BUTTON_UP:
|
||||
destination->payload = MouseButtonEvent{
|
||||
source.button.down, source.button.button, source.button.clicks,
|
||||
source.button.x, source.button.y};
|
||||
source.button.down, source.button.button, source.button.clicks,
|
||||
source.button.x, source.button.y,
|
||||
SDL_GetWindowRelativeMouseMode(window)};
|
||||
return true;
|
||||
case SDL_EVENT_MOUSE_WHEEL: {
|
||||
float delta_x = source.wheel.x;
|
||||
float delta_y = source.wheel.y;
|
||||
if (source.wheel.direction == SDL_MOUSEWHEEL_FLIPPED) {
|
||||
delta_x = -delta_x;
|
||||
delta_y = -delta_y;
|
||||
}
|
||||
// SDL already applies the host's natural-scrolling preference to x/y.
|
||||
// Undoing SDL_MOUSEWHEEL_FLIPPED here would ignore the OS setting.
|
||||
destination->payload = MouseWheelEvent{
|
||||
delta_x, delta_y, source.wheel.mouse_x, source.wheel.mouse_y};
|
||||
source.wheel.x, source.wheel.y, source.wheel.mouse_x,
|
||||
source.wheel.mouse_y, SDL_GetWindowRelativeMouseMode(window)};
|
||||
return true;
|
||||
}
|
||||
case SDL_EVENT_FINGER_DOWN:
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
#include "runtime/command_line.h"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "compat/guest_abi.h"
|
||||
#include "runtime/roblox_launch_uri.h"
|
||||
|
||||
namespace mocktail {
|
||||
@@ -78,6 +80,12 @@ CommandLineParseResult ParseCommandLine(int argc, const char* const argv[]) {
|
||||
result.options.allow_unverified_build = true;
|
||||
} else if (argument == "--force-run-latest") {
|
||||
result.options.force_run_latest = true;
|
||||
} else if (argument == "--profile") {
|
||||
if (!ReadOptionValue(argc, argv, &index, argument,
|
||||
&result.options.profile_trace_path,
|
||||
&result.error)) {
|
||||
return result;
|
||||
}
|
||||
} else if (argument == "--launch-uri") {
|
||||
if (!result.options.launch_request_json.empty()) {
|
||||
result.error = "duplicate option: --launch-uri";
|
||||
@@ -227,6 +235,20 @@ bool ApplyCommandLineEnvironment(const CommandLineOptions& options,
|
||||
error)) {
|
||||
return false;
|
||||
}
|
||||
if (!options.profile_trace_path.empty()) {
|
||||
// Absolute, so a later working-directory change cannot move the trace.
|
||||
std::error_code absolute_error;
|
||||
const std::filesystem::path trace_path =
|
||||
std::filesystem::absolute(options.profile_trace_path, absolute_error);
|
||||
if (absolute_error ||
|
||||
!SetEnvironment("MOCKTAIL_PROFILE_TRACE", trace_path.string(),
|
||||
error)) {
|
||||
if (error != nullptr && absolute_error) {
|
||||
*error = "could not resolve --profile path";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (options.window_mode == WindowMode::kHeadless) {
|
||||
return SetEnvironment("MOCKTAIL_HEADLESS", "1", error);
|
||||
}
|
||||
@@ -241,11 +263,12 @@ std::string CommandLineUsage(const std::string& program_name) {
|
||||
usage
|
||||
<< "Usage: " << (program_name.empty() ? "mocktail" : program_name)
|
||||
<< " [options] [roblox-uri]\n\n"
|
||||
<< "Normal startup downloads and activates a verified managed x86_64 "
|
||||
"Roblox payload automatically.\n\n"
|
||||
<< "Normal startup downloads and activates a verified managed "
|
||||
<< compat::kGuestAbi
|
||||
<< " Roblox payload automatically.\n\n"
|
||||
<< "Options:\n"
|
||||
<< " --roblox-lib <path> Development override for a specific "
|
||||
"x86_64 libroblox.so\n"
|
||||
<< compat::kGuestAbi << " libroblox.so\n"
|
||||
<< " --headless Run without creating an SDL window\n"
|
||||
<< " --windowed Force windowed startup (default)\n"
|
||||
<< " --graphics <backend> direct-vulkan | opengl | system | "
|
||||
@@ -256,6 +279,8 @@ std::string CommandLineUsage(const std::string& program_name) {
|
||||
"without approval; it is not activated\n"
|
||||
<< " --launch-uri <uri> Join from a roblox: or roblox-player: "
|
||||
"website link\n"
|
||||
<< " --profile <file> Write a Chrome trace of Vulkan adapter "
|
||||
"work for ui.perfetto.dev\n"
|
||||
<< " --help, -h Show this help\n\n"
|
||||
<< "Auth:\n"
|
||||
<< " When no saved Roblox session is found, Roblox's welcome screen "
|
||||
|
||||
+139
-47
@@ -84,14 +84,50 @@ std::string DumpJson(const Json& value) {
|
||||
return value.dump(-1, ' ', false, Json::error_handler_t::replace);
|
||||
}
|
||||
|
||||
std::string RenderPlaceTemplate(std::string text, std::string_view place_name) {
|
||||
constexpr std::string_view placeholder = "{place_name}";
|
||||
// Expands in one pass, so placeholder text inside a place name stays literal.
|
||||
// A template that expands an empty placeholder renders empty, so "by
|
||||
// {creator_name}" never shows a dangling "by".
|
||||
std::string RenderPresenceTemplate(std::string_view text,
|
||||
std::string_view place_name,
|
||||
std::string_view place_icon,
|
||||
std::string_view creator_name) {
|
||||
constexpr std::string_view kPlaceName = "{place_name}";
|
||||
constexpr std::string_view kPlaceIcon = "{place_icon}";
|
||||
constexpr std::string_view kCreatorName = "{creator_name}";
|
||||
std::string rendered;
|
||||
rendered.reserve(text.size());
|
||||
std::size_t offset = 0;
|
||||
while ((offset = text.find(placeholder, offset)) != std::string::npos) {
|
||||
text.replace(offset, placeholder.size(), place_name);
|
||||
offset += place_name.size();
|
||||
const auto expand = [&](std::string_view token, std::string_view value) {
|
||||
if (value.empty()) {
|
||||
return false;
|
||||
}
|
||||
rendered += value;
|
||||
offset += token.size();
|
||||
return true;
|
||||
};
|
||||
while (offset < text.size()) {
|
||||
const std::string_view rest = text.substr(offset);
|
||||
if (rest.substr(0, kPlaceName.size()) == kPlaceName) {
|
||||
if (!expand(kPlaceName, place_name)) return {};
|
||||
} else if (rest.substr(0, kPlaceIcon.size()) == kPlaceIcon) {
|
||||
if (!expand(kPlaceIcon, place_icon)) return {};
|
||||
} else if (rest.substr(0, kCreatorName.size()) == kCreatorName) {
|
||||
if (!expand(kCreatorName, creator_name)) return {};
|
||||
} else {
|
||||
rendered.push_back(text[offset]);
|
||||
++offset;
|
||||
}
|
||||
}
|
||||
return TruncateUtf8(std::move(text), 128);
|
||||
return rendered;
|
||||
}
|
||||
|
||||
bool IsDiscordAssetKey(std::string_view key) {
|
||||
return !key.empty() && key.size() <= 32 &&
|
||||
std::all_of(key.begin(), key.end(), [](unsigned char byte) {
|
||||
return (byte >= 'a' && byte <= 'z') ||
|
||||
(byte >= 'A' && byte <= 'Z') ||
|
||||
(byte >= '0' && byte <= '9') || byte == '_' || byte == '-';
|
||||
});
|
||||
}
|
||||
|
||||
std::string PercentEncode(std::string_view value) {
|
||||
@@ -329,8 +365,14 @@ bool HandshakeDiscord(int descriptor, std::string_view application_id) {
|
||||
}
|
||||
|
||||
Json ActivityJson(const DiscordRpcActivity& activity) {
|
||||
Json result = {
|
||||
{"type", 0}, {"details", activity.details}, {"instance", true}};
|
||||
// Discord rejects the whole activity when a text field is an empty string.
|
||||
Json result = {{"type", 0}, {"instance", true}};
|
||||
if (!activity.details.empty()) {
|
||||
result["details"] = activity.details;
|
||||
}
|
||||
if (!activity.name.empty()) {
|
||||
result["name"] = activity.name;
|
||||
}
|
||||
if (!activity.state.empty()) {
|
||||
result["state"] = activity.state;
|
||||
}
|
||||
@@ -342,6 +384,12 @@ Json ActivityJson(const DiscordRpcActivity& activity) {
|
||||
if (!activity.large_text.empty()) {
|
||||
result["assets"]["large_text"] = activity.large_text;
|
||||
}
|
||||
if (!activity.small_image.empty()) {
|
||||
result["assets"]["small_image"] = activity.small_image;
|
||||
if (!activity.small_text.empty()) {
|
||||
result["assets"]["small_text"] = activity.small_text;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!activity.button_label.empty() && !activity.button_url.empty()) {
|
||||
result["buttons"] = Json::array(
|
||||
@@ -446,6 +494,7 @@ std::optional<Json> GetRobloxJson(std::string url) {
|
||||
|
||||
struct ResolvedPlaceMetadata {
|
||||
std::string name;
|
||||
std::string creator_name;
|
||||
std::string icon_url;
|
||||
};
|
||||
|
||||
@@ -494,6 +543,13 @@ ResolvedPlaceMetadata ResolvePlaceMetadata(int64_t place_id) {
|
||||
metadata.name =
|
||||
TruncateUtf8(first["name"].get<std::string>(), 128);
|
||||
}
|
||||
if (first.contains("creator") && first["creator"].is_object()) {
|
||||
const Json& creator = first["creator"];
|
||||
if (creator.contains("name") && creator["name"].is_string()) {
|
||||
metadata.creator_name =
|
||||
TruncateUtf8(creator["name"].get<std::string>(), 128);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::optional<Json> thumbnail = GetRobloxJson(
|
||||
@@ -542,46 +598,74 @@ std::string BuildDiscordJoinUrl(const RobloxExperienceLaunchRequest& request) {
|
||||
DiscordRpcActivity BuildDiscordRpcActivity(
|
||||
const DiscordRpcConfig& config, RobloxExperiencePresencePhase phase,
|
||||
const RobloxExperienceLaunchRequest* request, std::string place_name,
|
||||
int64_t session_started_at, std::string place_icon_url) {
|
||||
int64_t session_started_at, std::string place_icon_url,
|
||||
std::string creator_name) {
|
||||
const bool browsing = phase == RobloxExperiencePresencePhase::kBrowsing;
|
||||
const bool joining_without_place =
|
||||
phase == RobloxExperiencePresencePhase::kJoining && place_name.empty();
|
||||
if (!browsing && place_name.empty()) {
|
||||
place_name = config.text.unknown_place;
|
||||
}
|
||||
// Hidden or absent places expose nothing to any template, icons included.
|
||||
const bool show_place =
|
||||
!browsing && !joining_without_place && config.show_place_name;
|
||||
const std::string_view shown_name =
|
||||
show_place ? std::string_view(place_name) : std::string_view();
|
||||
const std::string_view shown_icon =
|
||||
show_place && IsSafeExternalImageUrl(place_icon_url)
|
||||
? std::string_view(place_icon_url)
|
||||
: std::string_view();
|
||||
const std::string_view shown_creator =
|
||||
show_place ? std::string_view(creator_name) : std::string_view();
|
||||
const auto render = [&](std::string_view text) {
|
||||
return RenderPresenceTemplate(text, shown_name, shown_icon,
|
||||
shown_creator);
|
||||
};
|
||||
const auto render_text = [&](std::string_view text) {
|
||||
return TruncateUtf8(render(text), 128);
|
||||
};
|
||||
const auto is_image = [](std::string_view image) {
|
||||
return IsSafeExternalImageUrl(image) || IsDiscordAssetKey(image);
|
||||
};
|
||||
|
||||
DiscordRpcActivity activity;
|
||||
activity.state = TruncateUtf8(config.text.state, 128);
|
||||
switch (phase) {
|
||||
case RobloxExperiencePresencePhase::kBrowsing:
|
||||
activity.details = TruncateUtf8(config.text.browsing, 128);
|
||||
break;
|
||||
case RobloxExperiencePresencePhase::kJoining:
|
||||
case RobloxExperiencePresencePhase::kPlaying: {
|
||||
if (place_name.empty()) {
|
||||
if (phase == RobloxExperiencePresencePhase::kJoining) {
|
||||
activity.details = TruncateUtf8(config.text.joining, 128);
|
||||
break;
|
||||
}
|
||||
place_name = config.text.unknown_place;
|
||||
}
|
||||
if (config.show_place_name) {
|
||||
activity.details = RenderPlaceTemplate(config.text.playing, place_name);
|
||||
} else {
|
||||
activity.details = activity.state;
|
||||
activity.state.clear();
|
||||
}
|
||||
if (phase == RobloxExperiencePresencePhase::kPlaying &&
|
||||
config.show_elapsed_time && session_started_at > 0) {
|
||||
activity.start_timestamp = session_started_at;
|
||||
}
|
||||
if (IsSafeExternalImageUrl(place_icon_url)) {
|
||||
activity.large_image = std::move(place_icon_url);
|
||||
activity.large_text = TruncateUtf8(place_name, 128);
|
||||
}
|
||||
if (phase == RobloxExperiencePresencePhase::kPlaying &&
|
||||
config.join_enabled && request != nullptr &&
|
||||
(!config.public_servers_only || IsPublicDiscordJoin(*request))) {
|
||||
activity.button_url = BuildDiscordJoinUrl(*request);
|
||||
if (!activity.button_url.empty()) {
|
||||
activity.button_label = config.join_button_label;
|
||||
}
|
||||
}
|
||||
break;
|
||||
activity.name = render_text(config.text.title);
|
||||
activity.state = render_text(config.text.state);
|
||||
if (browsing) {
|
||||
activity.details = render_text(config.text.browsing);
|
||||
} else if (joining_without_place) {
|
||||
activity.details = render_text(config.text.joining);
|
||||
} else {
|
||||
if (config.show_place_name) {
|
||||
activity.details = render_text(config.text.playing);
|
||||
} else {
|
||||
activity.details = std::move(activity.state);
|
||||
activity.state.clear();
|
||||
}
|
||||
if (phase == RobloxExperiencePresencePhase::kPlaying &&
|
||||
config.show_elapsed_time && session_started_at > 0) {
|
||||
activity.start_timestamp = session_started_at;
|
||||
}
|
||||
if (phase == RobloxExperiencePresencePhase::kPlaying &&
|
||||
config.join_enabled && request != nullptr &&
|
||||
(!config.public_servers_only || IsPublicDiscordJoin(*request))) {
|
||||
activity.button_url = BuildDiscordJoinUrl(*request);
|
||||
if (!activity.button_url.empty()) {
|
||||
activity.button_label = config.join_button_label;
|
||||
}
|
||||
}
|
||||
}
|
||||
activity.large_image = render(config.images.large);
|
||||
if (!is_image(activity.large_image)) {
|
||||
activity.large_image.clear();
|
||||
return activity;
|
||||
}
|
||||
activity.large_text = render_text(config.images.large_text);
|
||||
activity.small_image = render(config.images.small);
|
||||
if (is_image(activity.small_image)) {
|
||||
activity.small_text = render_text(config.images.small_text);
|
||||
} else {
|
||||
activity.small_image.clear();
|
||||
}
|
||||
return activity;
|
||||
}
|
||||
@@ -697,6 +781,7 @@ class DiscordRpcSession::Impl final {
|
||||
|
||||
struct CachedPlaceMetadata {
|
||||
std::string name;
|
||||
std::string creator_name;
|
||||
std::string icon_url;
|
||||
std::chrono::steady_clock::time_point next_attempt{};
|
||||
unsigned failures = 0;
|
||||
@@ -734,6 +819,7 @@ class DiscordRpcSession::Impl final {
|
||||
Desired desired = Snapshot();
|
||||
std::string place_name;
|
||||
std::string place_icon_url;
|
||||
std::string creator_name;
|
||||
bool resolve_metadata_after_publish = false;
|
||||
if ((desired.phase == RobloxExperiencePresencePhase::kJoining ||
|
||||
desired.phase == RobloxExperiencePresencePhase::kPlaying) &&
|
||||
@@ -742,6 +828,7 @@ class DiscordRpcSession::Impl final {
|
||||
place_metadata_[desired.request.place_id];
|
||||
place_name = cached.name;
|
||||
place_icon_url = cached.icon_url;
|
||||
creator_name = cached.creator_name;
|
||||
if ((cached.name.empty() || cached.icon_url.empty()) &&
|
||||
std::chrono::steady_clock::now() >= cached.next_attempt) {
|
||||
resolve_metadata_after_publish = true;
|
||||
@@ -787,7 +874,7 @@ class DiscordRpcSession::Impl final {
|
||||
? nullptr
|
||||
: &desired.request,
|
||||
std::move(place_name), desired.started_at,
|
||||
std::move(place_icon_url));
|
||||
std::move(place_icon_url), std::move(creator_name));
|
||||
if (!SetDiscordActivity(descriptor, &activity, nonce++)) {
|
||||
(void)close(descriptor);
|
||||
descriptor = -1;
|
||||
@@ -811,6 +898,11 @@ class DiscordRpcSession::Impl final {
|
||||
cached.name = resolved.name;
|
||||
changed = true;
|
||||
}
|
||||
if (!resolved.creator_name.empty() &&
|
||||
resolved.creator_name != cached.creator_name) {
|
||||
cached.creator_name = resolved.creator_name;
|
||||
changed = true;
|
||||
}
|
||||
if (!resolved.icon_url.empty() &&
|
||||
resolved.icon_url != cached.icon_url) {
|
||||
cached.icon_url = resolved.icon_url;
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
#include "runtime/engine_pump_rest.h"
|
||||
|
||||
#include <sys/prctl.h>
|
||||
#include <time.h>
|
||||
|
||||
#if defined(__x86_64__)
|
||||
#include <cpuid.h>
|
||||
#include <immintrin.h>
|
||||
#include <x86intrin.h>
|
||||
#endif
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace mocktail::runtime {
|
||||
namespace {
|
||||
|
||||
uint64_t NowNs() {
|
||||
timespec now{};
|
||||
clock_gettime(CLOCK_MONOTONIC, &now);
|
||||
return static_cast<uint64_t>(now.tv_sec) * 1'000'000'000ULL +
|
||||
static_cast<uint64_t>(now.tv_nsec);
|
||||
}
|
||||
|
||||
// The kernel caps one TPAUSE at umwait_control/max_time TSC cycles (100000 by
|
||||
// default), so the wait is a loop of short pauses up to the deadline. Control
|
||||
// bit 0 clear selects C0.2, the deeper of the two light states.
|
||||
#if defined(__x86_64__)
|
||||
__attribute__((target("waitpkg"))) void TpauseUntil(uint64_t deadline_ns) {
|
||||
while (NowNs() < deadline_ns) {
|
||||
_tpause(0, __rdtsc() + 100000ULL);
|
||||
}
|
||||
}
|
||||
#else
|
||||
// TPAUSE is x86-only. CpuHasWaitPkg() is false on other hosts, so kTpause is
|
||||
// never chosen there; this waits out the deadline if it is forced anyway.
|
||||
void TpauseUntil(uint64_t deadline_ns) {
|
||||
while (NowNs() < deadline_ns) {
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void LowerTimerSlackOnce() {
|
||||
// Only the main thread rests, so the slack is set once per process.
|
||||
static const bool slack_set = [] {
|
||||
return prctl(PR_SET_TIMERSLACK, kEnginePumpTimerSlackNs) == 0;
|
||||
}();
|
||||
(void)slack_set;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
const char* EnginePumpRestModeName(EnginePumpRestMode mode) {
|
||||
switch (mode) {
|
||||
case EnginePumpRestMode::kSleep:
|
||||
return "sleep";
|
||||
case EnginePumpRestMode::kTpause:
|
||||
return "tpause";
|
||||
case EnginePumpRestMode::kSpin:
|
||||
return "spin";
|
||||
}
|
||||
return "spin";
|
||||
}
|
||||
|
||||
EnginePumpRestMode ChooseEnginePumpRestMode(
|
||||
const EnginePumpRestInputs& inputs) {
|
||||
if (inputs.override != nullptr) {
|
||||
if (std::strcmp(inputs.override, "sleep") == 0) {
|
||||
return EnginePumpRestMode::kSleep;
|
||||
}
|
||||
if (std::strcmp(inputs.override, "spin") == 0) {
|
||||
return EnginePumpRestMode::kSpin;
|
||||
}
|
||||
if (std::strcmp(inputs.override, "tpause") == 0 &&
|
||||
inputs.cpu_has_waitpkg) {
|
||||
return EnginePumpRestMode::kTpause;
|
||||
}
|
||||
}
|
||||
if (inputs.governor_performance) {
|
||||
return EnginePumpRestMode::kSleep;
|
||||
}
|
||||
return inputs.cpu_has_waitpkg ? EnginePumpRestMode::kTpause
|
||||
: EnginePumpRestMode::kSpin;
|
||||
}
|
||||
|
||||
bool CpuGovernorIsPerformance(const char* path) {
|
||||
std::FILE* file = std::fopen(path, "r");
|
||||
if (file == nullptr) {
|
||||
return false;
|
||||
}
|
||||
char governor[32] = {};
|
||||
const bool read = std::fgets(governor, sizeof(governor), file) != nullptr;
|
||||
std::fclose(file);
|
||||
if (!read) {
|
||||
return false;
|
||||
}
|
||||
governor[std::strcspn(governor, "\r\n")] = '\0';
|
||||
return std::strcmp(governor, "performance") == 0;
|
||||
}
|
||||
|
||||
bool CpuHasWaitPkg() {
|
||||
#if defined(__x86_64__)
|
||||
unsigned eax = 0, ebx = 0, ecx = 0, edx = 0;
|
||||
if (__get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx) == 0) {
|
||||
return false;
|
||||
}
|
||||
return (ecx & (1u << 5)) != 0;
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
EnginePumpRestMode ActiveEnginePumpRestMode() {
|
||||
static const EnginePumpRestMode mode = [] {
|
||||
EnginePumpRestInputs inputs;
|
||||
inputs.governor_performance = CpuGovernorIsPerformance(
|
||||
"/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor");
|
||||
inputs.cpu_has_waitpkg = CpuHasWaitPkg();
|
||||
inputs.override = std::getenv("MOCKTAIL_ENGINE_PUMP_REST");
|
||||
return ChooseEnginePumpRestMode(inputs);
|
||||
}();
|
||||
return mode;
|
||||
}
|
||||
|
||||
uint64_t RestAfterEnginePump(EnginePumpRestMode mode) {
|
||||
LowerTimerSlackOnce();
|
||||
switch (mode) {
|
||||
case EnginePumpRestMode::kSpin:
|
||||
return 0;
|
||||
case EnginePumpRestMode::kTpause:
|
||||
TpauseUntil(NowNs() + kEnginePumpRestNs);
|
||||
return kEnginePumpRestNs;
|
||||
case EnginePumpRestMode::kSleep:
|
||||
break;
|
||||
}
|
||||
timespec rest{};
|
||||
rest.tv_sec = 0;
|
||||
rest.tv_nsec = static_cast<long>(kEnginePumpRestNs);
|
||||
// A signal may cut the rest short. The remainder is not slept again: an
|
||||
// early poll only costs a few microseconds.
|
||||
(void)clock_nanosleep(CLOCK_MONOTONIC, 0, &rest, nullptr);
|
||||
return kEnginePumpRestNs;
|
||||
}
|
||||
|
||||
} // namespace mocktail::runtime
|
||||
@@ -349,6 +349,7 @@ class ExternalLaunchBroker::Impl final {
|
||||
Status initial_status = NormalizeRequest(*initial_request, &normalized);
|
||||
if (!initial_status.ok()) return initial_status;
|
||||
pending_.push_back(std::move(normalized));
|
||||
PublishPendingCount();
|
||||
}
|
||||
socket_path_ = options_.socket_path;
|
||||
Status status = socket_path_.empty()
|
||||
@@ -426,6 +427,14 @@ class ExternalLaunchBroker::Impl final {
|
||||
if (!sink.valid()) {
|
||||
return Invalid("external-launch sink is incomplete");
|
||||
}
|
||||
// The host main loop drains on every tick and the queue is almost always
|
||||
// empty. Observe that without either lock, so an idle tick never waits
|
||||
// behind a dispatch already in flight. A request queued just after this
|
||||
// load is delivered on the next tick.
|
||||
if (pending_count_.load(std::memory_order_acquire) == 0 &&
|
||||
!stopping_.load(std::memory_order_acquire)) {
|
||||
return Status::Ok();
|
||||
}
|
||||
std::lock_guard<std::mutex> drain_lock(drain_mutex_);
|
||||
if (stopping_.load(std::memory_order_acquire)) {
|
||||
return Failed("external-launch broker is stopping");
|
||||
@@ -437,11 +446,13 @@ class ExternalLaunchBroker::Impl final {
|
||||
if (pending_.empty()) break;
|
||||
request = std::move(pending_.front());
|
||||
pending_.pop_front();
|
||||
PublishPendingCount();
|
||||
}
|
||||
Status status = sink.dispatch(sink.context, request);
|
||||
if (!status.ok()) {
|
||||
std::lock_guard<std::mutex> lock(queue_mutex_);
|
||||
pending_.push_front(std::move(request));
|
||||
PublishPendingCount();
|
||||
return status;
|
||||
}
|
||||
}
|
||||
@@ -482,6 +493,7 @@ class ExternalLaunchBroker::Impl final {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(queue_mutex_);
|
||||
pending_.clear();
|
||||
PublishPendingCount();
|
||||
}
|
||||
started_ = false;
|
||||
return Status::Ok();
|
||||
@@ -577,9 +589,16 @@ class ExternalLaunchBroker::Impl final {
|
||||
return Unavailable("external-launch queue is full");
|
||||
}
|
||||
pending_.push_back(std::move(request));
|
||||
PublishPendingCount();
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
// Mirrors pending_.size() for Drain's lock-free idle check. Every caller
|
||||
// holds queue_mutex_, except Start, which runs before the worker exists.
|
||||
void PublishPendingCount() {
|
||||
pending_count_.store(pending_.size(), std::memory_order_release);
|
||||
}
|
||||
|
||||
void CleanupEndpoint() {
|
||||
CloseDescriptor(&stop_event_);
|
||||
CloseDescriptor(&listener_);
|
||||
@@ -607,6 +626,7 @@ class ExternalLaunchBroker::Impl final {
|
||||
std::mutex drain_mutex_;
|
||||
std::mutex lifecycle_mutex_;
|
||||
std::deque<RobloxExperienceLaunchRequest> pending_;
|
||||
std::atomic<std::size_t> pending_count_{0};
|
||||
OwnedPthread worker_;
|
||||
std::atomic<bool> stopping_{true};
|
||||
int listener_ = -1;
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
#include "runtime/game_mode.h"
|
||||
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#if defined(__GLIBC__)
|
||||
#include <link.h>
|
||||
#endif
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
@@ -56,8 +59,63 @@ void* OpenClientLibrary(const char* name) {
|
||||
#endif
|
||||
}
|
||||
|
||||
int GetThreadAffinity(cpu_set_t* mask) {
|
||||
return sched_getaffinity(0, sizeof(*mask), mask);
|
||||
}
|
||||
|
||||
// sched_setaffinity binds one thread, and GameMode pins every thread it finds,
|
||||
// so restoring the mask means walking the task list. Threads that exit while
|
||||
// the directory is being read are skipped, not treated as failures.
|
||||
int SetAffinityOfEveryThread(const cpu_set_t* mask) {
|
||||
DIR* tasks = opendir("/proc/self/task");
|
||||
if (tasks == nullptr) {
|
||||
return sched_setaffinity(0, sizeof(*mask), mask);
|
||||
}
|
||||
int result = 0;
|
||||
for (;;) {
|
||||
// readdir() reports both end-of-directory and failure with a null return,
|
||||
// so a read that dies partway must not pass for a completed walk.
|
||||
errno = 0;
|
||||
const dirent* entry = readdir(tasks);
|
||||
if (entry == nullptr) {
|
||||
if (errno != 0) {
|
||||
result = -1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
const long tid = std::strtol(entry->d_name, nullptr, 10);
|
||||
if (tid <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (sched_setaffinity(static_cast<pid_t>(tid), sizeof(*mask), mask) != 0 &&
|
||||
errno != ESRCH) {
|
||||
result = -1;
|
||||
}
|
||||
}
|
||||
closedir(tasks);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
CpuAffinityApi HostCpuAffinityApi() {
|
||||
return CpuAffinityApi{&GetThreadAffinity, &SetAffinityOfEveryThread};
|
||||
}
|
||||
|
||||
bool CpuAffinityNarrowed(const cpu_set_t& before, const cpu_set_t& after) {
|
||||
if (CPU_COUNT(&after) >= CPU_COUNT(&before)) {
|
||||
return false;
|
||||
}
|
||||
// A smaller set that escapes `before` is a move, not a narrowing, and the
|
||||
// daemon's choice of CPUs is then the only one known to be permitted.
|
||||
for (int cpu = 0; cpu < CPU_SETSIZE; ++cpu) {
|
||||
if (CPU_ISSET(cpu, &after) && !CPU_ISSET(cpu, &before)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ParseGameModePolicy(std::string_view value, GameModePolicy* policy) {
|
||||
if (policy == nullptr) {
|
||||
return false;
|
||||
@@ -97,6 +155,8 @@ const char* GameModeSessionStateName(GameModeSessionState state) {
|
||||
return "unavailable";
|
||||
case GameModeSessionState::kRequestFailed:
|
||||
return "request-failed";
|
||||
case GameModeSessionState::kDeclinedCorePinning:
|
||||
return "declined-core-pinning";
|
||||
case GameModeSessionState::kAlreadyActive:
|
||||
return "already-active";
|
||||
case GameModeSessionState::kActive:
|
||||
@@ -123,7 +183,7 @@ GameModeSession::GameModeSession(GameModeSession&& other) noexcept
|
||||
|
||||
GameModeSession GameModeSession::Start(GameModePolicy policy) {
|
||||
if (policy == GameModePolicy::kOff) {
|
||||
return StartBound(policy, {}, nullptr);
|
||||
return StartBound(policy, {}, {}, nullptr);
|
||||
}
|
||||
|
||||
void* library = OpenClientLibrary("libgamemode.so.0");
|
||||
@@ -155,7 +215,8 @@ GameModeSession GameModeSession::Start(GameModePolicy policy) {
|
||||
(void)ResolveFunction(library, "real_gamemode_query_status",
|
||||
&api.query_status, nullptr);
|
||||
|
||||
GameModeSession session = StartBound(policy, api, library);
|
||||
GameModeSession session =
|
||||
StartBound(policy, api, HostCpuAffinityApi(), library);
|
||||
if (!session.owns_request_) {
|
||||
session.CloseLibrary();
|
||||
}
|
||||
@@ -164,11 +225,17 @@ GameModeSession GameModeSession::Start(GameModePolicy policy) {
|
||||
|
||||
GameModeSession GameModeSession::StartWithClientForTesting(
|
||||
GameModePolicy policy, GameModeClientApi api) {
|
||||
return StartBound(policy, api, nullptr);
|
||||
return StartBound(policy, api, {}, nullptr);
|
||||
}
|
||||
|
||||
GameModeSession GameModeSession::StartWithClientForTesting(
|
||||
GameModePolicy policy, GameModeClientApi api, CpuAffinityApi affinity) {
|
||||
return StartBound(policy, api, affinity, nullptr);
|
||||
}
|
||||
|
||||
GameModeSession GameModeSession::StartBound(GameModePolicy policy,
|
||||
GameModeClientApi api,
|
||||
CpuAffinityApi affinity,
|
||||
void* library_handle) {
|
||||
GameModeSession session;
|
||||
if (policy == GameModePolicy::kOff) {
|
||||
@@ -185,6 +252,11 @@ GameModeSession GameModeSession::StartBound(GameModePolicy policy,
|
||||
session.state_ = GameModeSessionState::kAlreadyActive;
|
||||
return session;
|
||||
}
|
||||
cpu_set_t before;
|
||||
CPU_ZERO(&before);
|
||||
const bool affinity_readable =
|
||||
policy != GameModePolicy::kOn && affinity.get != nullptr &&
|
||||
affinity.set != nullptr && affinity.get(&before) == 0;
|
||||
if (api.request_start() != 0) {
|
||||
session.state_ = GameModeSessionState::kRequestFailed;
|
||||
session.detail_ = ClientError(api, "GameMode request was rejected");
|
||||
@@ -192,6 +264,21 @@ GameModeSession GameModeSession::StartBound(GameModePolicy policy,
|
||||
}
|
||||
session.state_ = GameModeSessionState::kActive;
|
||||
session.owns_request_ = true;
|
||||
// The daemon pins before the request call returns, and re-pins every few
|
||||
// seconds afterwards. Ending the request is what releases the pin.
|
||||
cpu_set_t after;
|
||||
CPU_ZERO(&after);
|
||||
if (affinity_readable && affinity.get(&after) == 0 &&
|
||||
CpuAffinityNarrowed(before, after)) {
|
||||
session.state_ = GameModeSessionState::kDeclinedCorePinning;
|
||||
session.detail_ = "GameMode pinned the process to a subset of its CPUs";
|
||||
// A release that fails leaves the daemon holding the request, so keep
|
||||
// owning it and let Stop() retry rather than reporting it released.
|
||||
if (api.request_end() == 0) {
|
||||
session.owns_request_ = false;
|
||||
}
|
||||
(void)affinity.set(&before);
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,12 +29,21 @@ constexpr const char* kIcdDirectories[] = {
|
||||
"/usr/local/share/vulkan/icd.d",
|
||||
};
|
||||
|
||||
#if defined(__aarch64__)
|
||||
constexpr char kNativeArchitecture[] = "aarch64";
|
||||
|
||||
constexpr const char* kForeignArchitectures[] = {
|
||||
"i686", "i586", "i486", "i386", "x86_64", "x86.",
|
||||
"amd64", "armhf", "armv7", "ppc64", "riscv64", "s390x",
|
||||
};
|
||||
#else
|
||||
constexpr char kNativeArchitecture[] = "x86_64";
|
||||
|
||||
constexpr const char* kForeignArchitectures[] = {
|
||||
"i686", "i586", "i486", "i386", "x86.", "aarch64",
|
||||
"arm64", "armhf", "armv7", "ppc64", "riscv64", "s390x",
|
||||
};
|
||||
#endif
|
||||
|
||||
struct HostGpus {
|
||||
bool intel = false;
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
#include "runtime/roblox_account_bridge.h"
|
||||
|
||||
#include <array>
|
||||
#include <condition_variable>
|
||||
#include <cstdio>
|
||||
#include <iterator>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
namespace mocktail {
|
||||
namespace runtime {
|
||||
namespace {
|
||||
|
||||
constexpr char kAccountProtocolClass[] =
|
||||
"com/roblox/universalapp/account/JNIAccountProtocol";
|
||||
// Serialized name of the APK status enum for a missing Play token provider.
|
||||
constexpr char kTokenProviderUninitialized[] = "TOKEN_PROVIDER_UNINITIALIZED";
|
||||
constexpr std::size_t kMaximumNameBytes = 128;
|
||||
|
||||
enum Method : std::size_t { kDeviceIntegrityAvailable, kGetIntegrityToken };
|
||||
constexpr std::size_t kMethodCount = 2;
|
||||
constexpr const char* kMethodLabels[kMethodCount] = {"DeviceIntegrityAvailable",
|
||||
"GetIntegrityToken"};
|
||||
|
||||
Status Unavailable(const char* message) {
|
||||
return Status::Error(StatusCode::kUnavailable, message);
|
||||
}
|
||||
|
||||
Status CheckJni(JNIEnv* env) {
|
||||
if (!env->ExceptionCheck()) return Status::Ok();
|
||||
env->ExceptionClear();
|
||||
return Unavailable("AccountProtocol JNI operation failed");
|
||||
}
|
||||
|
||||
// Copies a non-empty, bounded engine-provided name.
|
||||
bool ReadName(JNIEnv* env, jstring value, std::string* name) {
|
||||
if (!value) return false;
|
||||
const jsize size = env->GetStringUTFLength(value);
|
||||
const char* bytes = env->GetStringUTFChars(value, nullptr);
|
||||
const bool valid = bytes && size > 0 &&
|
||||
static_cast<std::size_t>(size) <= kMaximumNameBytes;
|
||||
if (valid) name->assign(bytes, static_cast<std::size_t>(size));
|
||||
if (bytes) env->ReleaseStringUTFChars(value, bytes);
|
||||
return valid;
|
||||
}
|
||||
|
||||
// Pins a valid engine-provided name as a global reference.
|
||||
jstring RetainName(JNIEnv* env, jstring value) {
|
||||
std::string ignored;
|
||||
return ReadName(env, value, &ignored)
|
||||
? static_cast<jstring>(env->NewGlobalRef(value))
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
struct RobloxAccountBridge::State {
|
||||
struct Endpoint {
|
||||
std::shared_ptr<State> state;
|
||||
Method method;
|
||||
};
|
||||
struct Registration {
|
||||
jobject handler = nullptr;
|
||||
jstring method = nullptr;
|
||||
bool registered = false;
|
||||
};
|
||||
|
||||
jobject bus = nullptr;
|
||||
jstring protocol = nullptr;
|
||||
std::string support_key;
|
||||
std::string token_key;
|
||||
std::string result_key;
|
||||
std::array<Registration, kMethodCount> registrations;
|
||||
std::mutex mutex;
|
||||
std::condition_variable drained;
|
||||
bool accepting = true;
|
||||
std::size_t in_flight = 0;
|
||||
|
||||
// The request payload is never parsed or logged: both answers are fixed.
|
||||
static std::string Answer(void* context, JNIEnv*, jstring) {
|
||||
const auto* endpoint = static_cast<Endpoint*>(context);
|
||||
const auto state = endpoint->state;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
if (!state->accepting) return {};
|
||||
++state->in_flight;
|
||||
}
|
||||
struct Finish {
|
||||
std::shared_ptr<State> state;
|
||||
~Finish() {
|
||||
std::lock_guard<std::mutex> lock(state->mutex);
|
||||
--state->in_flight;
|
||||
state->drained.notify_all();
|
||||
}
|
||||
} finish{state};
|
||||
|
||||
nlohmann::json body;
|
||||
const char* result = nullptr;
|
||||
if (endpoint->method == kDeviceIntegrityAvailable) {
|
||||
body = {{state->support_key, false}};
|
||||
result = "unsupported";
|
||||
} else {
|
||||
body = {{state->token_key, ""},
|
||||
{state->result_key, kTokenProviderUninitialized}};
|
||||
result = kTokenProviderUninitialized;
|
||||
}
|
||||
std::fprintf(stderr, " [account] AccountProtocol method=%s result=%s\n",
|
||||
kMethodLabels[endpoint->method], result);
|
||||
return body.dump();
|
||||
}
|
||||
};
|
||||
|
||||
RobloxAccountBridge::RobloxAccountBridge(JniEnvironmentProvider environment,
|
||||
RobloxAccountProtocolSymbols symbols,
|
||||
RobloxAccountProtocolObjects objects)
|
||||
: environment_(environment), symbols_(symbols), objects_(objects) {}
|
||||
|
||||
RobloxAccountBridge::~RobloxAccountBridge() { (void)Shutdown(); }
|
||||
|
||||
Status RobloxAccountBridge::Initialize() {
|
||||
std::lock_guard<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
if (state_) {
|
||||
return Status::Error(StatusCode::kFailedPrecondition,
|
||||
"AccountProtocol is already initialized");
|
||||
}
|
||||
if (!environment_.valid() || !symbols_.complete() || !objects_.complete()) {
|
||||
return Unavailable("AccountProtocol prerequisites are incomplete");
|
||||
}
|
||||
JNIEnv* env = nullptr;
|
||||
Status status = environment_.Acquire(&env);
|
||||
if (!status.ok()) return status;
|
||||
|
||||
jclass protocol_class = env->FindClass(kAccountProtocolClass);
|
||||
if (!protocol_class) {
|
||||
(void)CheckJni(env);
|
||||
return Unavailable("JNIAccountProtocol class is unavailable");
|
||||
}
|
||||
const jstring protocol = symbols_.get_protocol_name(env, protocol_class);
|
||||
const jstring methods[kMethodCount] = {
|
||||
symbols_.get_device_integrity_available_method_name(env, protocol_class),
|
||||
symbols_.get_integrity_token_method_name(env, protocol_class)};
|
||||
const jstring keys[] = {symbols_.get_support_key(env, protocol_class),
|
||||
symbols_.get_token_key(env, protocol_class),
|
||||
symbols_.get_result_key(env, protocol_class)};
|
||||
env->DeleteLocalRef(protocol_class);
|
||||
|
||||
state_ = std::make_shared<State>();
|
||||
std::string* const key_targets[] = {&state_->support_key,
|
||||
&state_->token_key, &state_->result_key};
|
||||
bool names_valid = true;
|
||||
for (std::size_t i = 0; i < std::size(keys); ++i) {
|
||||
names_valid = ReadName(env, keys[i], key_targets[i]) && names_valid;
|
||||
if (keys[i]) env->DeleteLocalRef(keys[i]);
|
||||
}
|
||||
state_->protocol = RetainName(env, protocol);
|
||||
if (protocol) env->DeleteLocalRef(protocol);
|
||||
for (std::size_t i = 0; i < kMethodCount; ++i) {
|
||||
state_->registrations[i].method = RetainName(env, methods[i]);
|
||||
names_valid = state_->registrations[i].method && names_valid;
|
||||
if (methods[i]) env->DeleteLocalRef(methods[i]);
|
||||
}
|
||||
state_->bus = env->NewGlobalRef(objects_.message_bus);
|
||||
auto fail = [this](Status failure) {
|
||||
(void)ShutdownLocked();
|
||||
return failure;
|
||||
};
|
||||
if (!CheckJni(env).ok() || !names_valid || !state_->protocol ||
|
||||
!state_->bus) {
|
||||
return fail(Unavailable("AccountProtocol names are unavailable"));
|
||||
}
|
||||
|
||||
for (std::size_t i = 0; i < kMethodCount; ++i) {
|
||||
auto& entry = state_->registrations[i];
|
||||
auto endpoint = std::make_shared<State::Endpoint>(
|
||||
State::Endpoint{state_, static_cast<Method>(i)});
|
||||
jobject handler = objects_.create_request_handler(objects_.context,
|
||||
endpoint, &State::Answer);
|
||||
if (handler) {
|
||||
entry.handler = env->NewGlobalRef(handler);
|
||||
if (!entry.handler) {
|
||||
objects_.clear_request_handler(objects_.context, handler);
|
||||
}
|
||||
env->DeleteLocalRef(handler);
|
||||
}
|
||||
if (!entry.handler || !CheckJni(env).ok()) {
|
||||
return fail(Unavailable("could not create AccountProtocol handler"));
|
||||
}
|
||||
entry.registered = true;
|
||||
symbols_.set_request_handler_raw(env, state_->bus, state_->protocol,
|
||||
entry.method, entry.handler);
|
||||
status = CheckJni(env);
|
||||
if (!status.ok()) return fail(status);
|
||||
}
|
||||
std::fprintf(stderr,
|
||||
" [account] AccountProtocol ready device_integrity=unsupported\n");
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
Status RobloxAccountBridge::Shutdown() {
|
||||
std::lock_guard<std::mutex> lifecycle(lifecycle_mutex_);
|
||||
return ShutdownLocked();
|
||||
}
|
||||
|
||||
Status RobloxAccountBridge::ShutdownLocked() {
|
||||
if (!state_) return Status::Ok();
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(state_->mutex);
|
||||
state_->accepting = false;
|
||||
state_->drained.wait(lock, [this] { return state_->in_flight == 0; });
|
||||
}
|
||||
JNIEnv* env = nullptr;
|
||||
Status status = environment_.Acquire(&env);
|
||||
if (!status.ok()) return status; // Keep roots for a later shutdown retry.
|
||||
// Clear any exception from partially failed initialization before cleanup.
|
||||
const Status pending = CheckJni(env);
|
||||
if (!pending.ok()) status = pending;
|
||||
for (auto& entry : state_->registrations) {
|
||||
if (entry.registered) {
|
||||
symbols_.clear_request_handler(env, state_->bus, state_->protocol,
|
||||
entry.method);
|
||||
const Status cleared = CheckJni(env);
|
||||
if (!cleared.ok()) status = cleared;
|
||||
}
|
||||
if (entry.handler) {
|
||||
objects_.clear_request_handler(objects_.context, entry.handler);
|
||||
env->DeleteGlobalRef(entry.handler);
|
||||
}
|
||||
if (entry.method) env->DeleteGlobalRef(entry.method);
|
||||
entry = {};
|
||||
}
|
||||
if (state_->protocol) env->DeleteGlobalRef(state_->protocol);
|
||||
if (state_->bus) env->DeleteGlobalRef(state_->bus);
|
||||
state_.reset();
|
||||
return status;
|
||||
}
|
||||
|
||||
} // namespace runtime
|
||||
} // namespace mocktail
|
||||
@@ -11,6 +11,7 @@
|
||||
|
||||
#include "jnivm/jnivm.h"
|
||||
#include "runtime/external_launch_broker.h"
|
||||
#include "runtime/roblox_launch_uri.h"
|
||||
#include "runtime/webview_helper_launcher.h"
|
||||
#include "window/window.h"
|
||||
|
||||
@@ -21,7 +22,13 @@ namespace {
|
||||
constexpr size_t kMaxPendingLaunchRequests = 8;
|
||||
// libroblox's static TLS requires the proven 16 MiB guest-thread stack floor.
|
||||
constexpr size_t kLaunchWorkerStackSize = 64ULL * 1024 * 1024;
|
||||
constexpr std::chrono::milliseconds kWebSurfaceReadyTimeout{3000};
|
||||
// Covers helper exec through window creation, including cold Flatpak starts.
|
||||
constexpr std::chrono::milliseconds kWebSurfaceReadyTimeout{5000};
|
||||
// Roblox closes a solved WebViewProtocol challenge itself with closeWindow,
|
||||
// as on Android. The host closes it only if Roblox has not done so within
|
||||
// this period. Captcha windows close at once instead (see
|
||||
// RobloxWebViewOpenRequest::close_when_challenge_solved).
|
||||
constexpr std::chrono::milliseconds kSolvedChallengeCloseGrace{3000};
|
||||
constexpr char kRobloxBaseUrl[] = "https://www.roblox.com/";
|
||||
|
||||
Status Invalid(std::string message) {
|
||||
@@ -158,24 +165,33 @@ Status LaunchRobloxWebSurface(
|
||||
}
|
||||
std::fprintf(stderr, " [%s] opening validated Roblox web surface\n",
|
||||
transport);
|
||||
const auto started = std::chrono::steady_clock::now();
|
||||
const WebViewHelperLaunchResult launched =
|
||||
LaunchWebViewHelper(helper, url, std::move(exit_observer));
|
||||
if (!launched) {
|
||||
return Unavailable("could not display Roblox web surface: " +
|
||||
launched.error);
|
||||
}
|
||||
if (launched.process == nullptr ||
|
||||
!launched.process->WaitUntilReady(kWebSurfaceReadyTimeout)) {
|
||||
const bool ready = launched.process != nullptr &&
|
||||
launched.process->WaitUntilReady(kWebSurfaceReadyTimeout);
|
||||
const long long elapsed_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - started)
|
||||
.count();
|
||||
if (!ready) {
|
||||
if (launched.process != nullptr) {
|
||||
(void)launched.process->RequestClose();
|
||||
}
|
||||
return Unavailable(
|
||||
"Roblox web surface did not become ready before the deadline");
|
||||
"Roblox web surface did not become ready before the deadline (" +
|
||||
std::to_string(elapsed_ms) + " ms of " +
|
||||
std::to_string(kWebSurfaceReadyTimeout.count()) + " ms)");
|
||||
}
|
||||
if (process != nullptr) {
|
||||
*process = launched.process;
|
||||
}
|
||||
std::fprintf(stderr, " [%s] Roblox web surface launched\n", transport);
|
||||
std::fprintf(stderr, " [%s] Roblox web surface launched in %lld ms\n",
|
||||
transport, elapsed_ms);
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
@@ -299,12 +315,14 @@ RobloxExperienceComposition::RobloxExperienceComposition(
|
||||
const SecureRobloxCredential* initial_web_view_credential,
|
||||
RobloxExperienceSurfaceProvider surface_provider,
|
||||
RobloxExperiencePresenceObserver presence_observer,
|
||||
bool clear_persisted_web_view_cookie, bool microphone_enabled)
|
||||
bool clear_persisted_web_view_cookie, bool microphone_enabled,
|
||||
RobloxAccountProtocolSymbols account_symbols)
|
||||
: environment_(environment),
|
||||
message_bus_symbols_(message_bus_symbols),
|
||||
web_view_symbols_(web_view_symbols),
|
||||
browser_service_symbols_(browser_service_symbols),
|
||||
permissions_symbols_(permissions_symbols),
|
||||
account_symbols_(account_symbols),
|
||||
microphone_enabled_(microphone_enabled),
|
||||
game_symbols_(game_symbols),
|
||||
jni_factory_(jni_factory),
|
||||
@@ -425,11 +443,33 @@ Status RobloxExperienceComposition::InitializePlatformProtocols() {
|
||||
(void)ReleaseGlobalObjects();
|
||||
return status;
|
||||
}
|
||||
// AccountProtocol only shortens a device-integrity login challenge that
|
||||
// cannot succeed here, so its absence or failure never blocks startup.
|
||||
std::unique_ptr<RobloxAccountBridge> account_bridge;
|
||||
if (account_symbols_.complete()) {
|
||||
account_bridge = std::make_unique<RobloxAccountBridge>(
|
||||
environment_, account_symbols_,
|
||||
RobloxAccountProtocolObjects{web_view_objects.message_bus,
|
||||
jni_factory_.context,
|
||||
jni_factory_.create_request_handler,
|
||||
jni_factory_.clear_request_handler});
|
||||
const Status account_status = account_bridge->Initialize();
|
||||
if (!account_status.ok()) {
|
||||
std::fprintf(stderr, " [account] AccountProtocol unavailable: %s\n",
|
||||
account_status.message().c_str());
|
||||
account_bridge.reset();
|
||||
}
|
||||
} else {
|
||||
std::fprintf(stderr,
|
||||
" [account] AccountProtocol entrypoints are missing; "
|
||||
"device-integrity challenges wait for Roblox's timeout\n");
|
||||
}
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
web_view_bridge_ = std::move(web_view_bridge);
|
||||
browser_service_bridge_ = std::move(browser_service_bridge);
|
||||
permissions_bridge_ = std::move(permissions_bridge);
|
||||
account_bridge_ = std::move(account_bridge);
|
||||
platform_protocols_initialized_ = true;
|
||||
}
|
||||
std::fprintf(stderr,
|
||||
@@ -602,6 +642,8 @@ Status RobloxExperienceComposition::OpenWebSurface(
|
||||
web_surface_process_generation_ = process_generation;
|
||||
web_surface_route_ = route;
|
||||
web_surface_logical_generation_ = logical_generation;
|
||||
web_surface_close_when_challenge_solved_ =
|
||||
presentation.close_when_challenge_solved;
|
||||
web_surface_logical_exit_observer_ = std::move(exit_observer);
|
||||
}
|
||||
if (superseded_observer.valid()) {
|
||||
@@ -614,13 +656,16 @@ Status RobloxExperienceComposition::OpenWebSurface(
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
Status RobloxExperienceComposition::CloseWebSurface() {
|
||||
Status RobloxExperienceComposition::CloseWebSurface(
|
||||
uint64_t expected_logical_generation) {
|
||||
std::lock_guard<std::mutex> operation_lock(web_surface_operation_mutex_);
|
||||
std::shared_ptr<WebViewHelperProcess> process;
|
||||
WebViewHelperExitObserver exit_observer;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (web_surface_route_ == WebSurfaceRoute::kNone) {
|
||||
if (web_surface_route_ == WebSurfaceRoute::kNone ||
|
||||
(expected_logical_generation != 0 &&
|
||||
expected_logical_generation != web_surface_logical_generation_)) {
|
||||
return Status::Ok();
|
||||
}
|
||||
process = std::move(web_surface_process_);
|
||||
@@ -628,6 +673,7 @@ Status RobloxExperienceComposition::CloseWebSurface() {
|
||||
exit_observer = std::move(web_surface_logical_exit_observer_);
|
||||
web_surface_route_ = WebSurfaceRoute::kNone;
|
||||
web_surface_logical_generation_ = 0;
|
||||
web_surface_close_when_challenge_solved_ = false;
|
||||
}
|
||||
// A closed challenge must stop executing. Reusing its hidden document lets
|
||||
// late callbacks from the old attempt reach the next login attempt. The APK
|
||||
@@ -643,6 +689,33 @@ Status RobloxExperienceComposition::CloseWebSurface() {
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
Status RobloxExperienceComposition::CloseUnclaimedSolvedChallenge() {
|
||||
uint64_t generation = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!solved_challenge_close_deadline_.has_value()) {
|
||||
return Status::Ok();
|
||||
}
|
||||
const bool still_open =
|
||||
web_surface_route_ != WebSurfaceRoute::kNone &&
|
||||
solved_challenge_logical_generation_ == web_surface_logical_generation_;
|
||||
if (still_open &&
|
||||
std::chrono::steady_clock::now() < *solved_challenge_close_deadline_) {
|
||||
return Status::Ok();
|
||||
}
|
||||
solved_challenge_close_deadline_.reset();
|
||||
if (!still_open) {
|
||||
return Status::Ok();
|
||||
}
|
||||
generation = solved_challenge_logical_generation_;
|
||||
}
|
||||
std::fprintf(stderr,
|
||||
" [webview] closing solved challenge window; Roblox did not "
|
||||
"close it within %lld ms\n",
|
||||
static_cast<long long>(kSolvedChallengeCloseGrace.count()));
|
||||
return CloseWebSurface(generation);
|
||||
}
|
||||
|
||||
void RobloxExperienceComposition::WebSurfaceExited(void* context) {
|
||||
auto* exit_context = static_cast<WebSurfaceExitContext*>(context);
|
||||
if (exit_context == nullptr || exit_context->target == nullptr ||
|
||||
@@ -668,6 +741,7 @@ void RobloxExperienceComposition::HandleWebSurfaceExit(
|
||||
web_surface_process_generation_ = 0;
|
||||
web_surface_route_ = WebSurfaceRoute::kNone;
|
||||
web_surface_logical_generation_ = 0;
|
||||
web_surface_close_when_challenge_solved_ = false;
|
||||
exit_observer = std::move(web_surface_logical_exit_observer_);
|
||||
}
|
||||
if (exit_observer.valid()) {
|
||||
@@ -693,6 +767,8 @@ Status RobloxExperienceComposition::DispatchWebViewOpen(
|
||||
// host back navigation too.
|
||||
presentation.back_navigation_disabled =
|
||||
request.back_button_visible.has_value() && !*request.back_button_visible;
|
||||
presentation.close_when_challenge_solved =
|
||||
request.close_when_challenge_solved;
|
||||
return composition->OpenWebSurface(request.url, "webview",
|
||||
WebSurfaceRoute::kWebView,
|
||||
std::move(exit_observer), presentation);
|
||||
@@ -951,9 +1027,45 @@ Status RobloxExperienceComposition::RouteCurrentWebSurfaceEvent(
|
||||
route = web_surface_route_;
|
||||
web_view_bridge = web_view_bridge_.get();
|
||||
}
|
||||
return event.type == WebViewHelperEventType::kRobloxCookie
|
||||
? AcceptWebViewRobloxCookie(event.payload)
|
||||
: RouteWebSurfaceEvent(route, event, web_view_bridge);
|
||||
if (event.type == WebViewHelperEventType::kRobloxCookie) {
|
||||
return AcceptWebViewRobloxCookie(event.payload);
|
||||
}
|
||||
if (event.type == WebViewHelperEventType::kExecuteRoblox) {
|
||||
// A web Play button's launchGame is launched through the experience
|
||||
// pipeline and closes the surface. It is never forwarded, so Roblox
|
||||
// cannot start a second join from the same command.
|
||||
RobloxExperienceLaunchRequest request;
|
||||
if (ParseRobloxWebViewLaunchGame(event.payload, &request).ok() &&
|
||||
Dispatch(request).ok()) {
|
||||
std::fprintf(stderr,
|
||||
"[experience] WebView launchGame queued place_id=%lld\n",
|
||||
static_cast<long long>(request.place_id));
|
||||
return CloseWebSurface();
|
||||
}
|
||||
}
|
||||
const Status status = RouteWebSurfaceEvent(route, event, web_view_bridge);
|
||||
if (!status.ok() || !IsRobloxWebViewChallengeSuccess(event.payload)) {
|
||||
return status;
|
||||
}
|
||||
std::fprintf(stderr, " [webview] solved challenge forwarded to Roblox\n");
|
||||
bool close_now = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (logical_generation != web_surface_logical_generation_) {
|
||||
return status;
|
||||
}
|
||||
close_now = web_surface_close_when_challenge_solved_;
|
||||
if (!close_now) {
|
||||
solved_challenge_close_deadline_ =
|
||||
std::chrono::steady_clock::now() + kSolvedChallengeCloseGrace;
|
||||
solved_challenge_logical_generation_ = logical_generation;
|
||||
}
|
||||
}
|
||||
if (!close_now) {
|
||||
return status;
|
||||
}
|
||||
std::fprintf(stderr, " [webview] closing solved captcha window\n");
|
||||
return CloseWebSurface(logical_generation);
|
||||
}
|
||||
|
||||
Status RobloxExperienceComposition::DrainPlatformEvents() {
|
||||
@@ -1002,6 +1114,9 @@ Status RobloxExperienceComposition::DrainPlatformEvents() {
|
||||
status = drain_helper(web_surface_process, process_generation,
|
||||
logical_generation);
|
||||
}
|
||||
if (status.ok()) {
|
||||
status = CloseUnclaimedSolvedChallenge();
|
||||
}
|
||||
if (status.ok() && browser_service_bridge != nullptr) {
|
||||
status = browser_service_bridge->DrainOutgoingEvents();
|
||||
}
|
||||
@@ -1242,6 +1357,7 @@ Status RobloxExperienceComposition::DrainLaunchRequests() {
|
||||
if (active_launch_ != nullptr) {
|
||||
completed_result = active_launch_->result;
|
||||
game_active_ = completed_result.ok();
|
||||
window::SetGameSessionActive(game_active_);
|
||||
active_game_canonical_json_ =
|
||||
completed_result.ok() ? active_launch_->request.canonical_json
|
||||
: std::string();
|
||||
@@ -1279,6 +1395,7 @@ Status RobloxExperienceComposition::DrainLaunchRequests() {
|
||||
return observed;
|
||||
}
|
||||
game_active_ = false;
|
||||
window::SetGameSessionActive(false);
|
||||
active_game_canonical_json_.clear();
|
||||
presence_request_.reset();
|
||||
playing_presence_published_ = false;
|
||||
@@ -1454,6 +1571,7 @@ Status RobloxExperienceComposition::LeaveGame() {
|
||||
if (status.ok()) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
game_active_ = false;
|
||||
window::SetGameSessionActive(false);
|
||||
active_game_canonical_json_.clear();
|
||||
}
|
||||
return status;
|
||||
@@ -1540,6 +1658,7 @@ Status RobloxExperienceComposition::Shutdown() {
|
||||
std::unique_ptr<RobloxWebViewBridge> web_view_bridge;
|
||||
std::unique_ptr<RobloxBrowserServiceBridge> browser_service_bridge;
|
||||
std::unique_ptr<RobloxPermissionsBridge> permissions_bridge;
|
||||
std::unique_ptr<RobloxAccountBridge> account_bridge;
|
||||
std::shared_ptr<WebViewHelperProcess> web_surface_process;
|
||||
jnivm::VM* late_lifecycle_vm = nullptr;
|
||||
{
|
||||
@@ -1552,6 +1671,7 @@ Status RobloxExperienceComposition::Shutdown() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
subscribed_ = false;
|
||||
game_active_ = false;
|
||||
window::SetGameSessionActive(false);
|
||||
active_game_canonical_json_.clear();
|
||||
presence_request_.reset();
|
||||
playing_presence_published_ = false;
|
||||
@@ -1563,6 +1683,7 @@ Status RobloxExperienceComposition::Shutdown() {
|
||||
web_view_bridge = std::move(web_view_bridge_);
|
||||
browser_service_bridge = std::move(browser_service_bridge_);
|
||||
permissions_bridge = std::move(permissions_bridge_);
|
||||
account_bridge = std::move(account_bridge_);
|
||||
web_surface_process = std::move(web_surface_process_);
|
||||
web_surface_logical_exit_observer_ = {};
|
||||
web_surface_route_ = WebSurfaceRoute::kNone;
|
||||
@@ -1579,8 +1700,12 @@ Status RobloxExperienceComposition::Shutdown() {
|
||||
if (web_surface_process != nullptr) {
|
||||
(void)web_surface_process->RequestClose();
|
||||
}
|
||||
Status status = permissions_bridge != nullptr ? permissions_bridge->Shutdown()
|
||||
: Status::Ok();
|
||||
Status status =
|
||||
account_bridge != nullptr ? account_bridge->Shutdown() : Status::Ok();
|
||||
const Status permissions_status = permissions_bridge != nullptr
|
||||
? permissions_bridge->Shutdown()
|
||||
: Status::Ok();
|
||||
if (status.ok()) status = permissions_status;
|
||||
const Status browser_status = browser_service_bridge != nullptr
|
||||
? browser_service_bridge->Shutdown()
|
||||
: Status::Ok();
|
||||
@@ -1596,6 +1721,7 @@ Status RobloxExperienceComposition::Shutdown() {
|
||||
status = bridge_status;
|
||||
}
|
||||
browser_service_bridge.reset();
|
||||
account_bridge.reset();
|
||||
permissions_bridge.reset();
|
||||
web_view_bridge.reset();
|
||||
bridge.reset();
|
||||
|
||||
@@ -274,14 +274,15 @@ AndroidKeyMapping MapSdlKeyToAndroid(uint32_t sdl_scancode,
|
||||
return {};
|
||||
}
|
||||
|
||||
int32_t MapSdlMouseButtonToAndroid(uint8_t sdl_button) {
|
||||
int32_t MapSdlMouseButtonToRoblox(uint8_t sdl_button) {
|
||||
switch (sdl_button) {
|
||||
case SDL_BUTTON_LEFT:
|
||||
return 0;
|
||||
case SDL_BUTTON_RIGHT:
|
||||
return 1;
|
||||
case SDL_BUTTON_MIDDLE:
|
||||
return 3;
|
||||
// MouseButton3 is index 2, not BUTTON_TERTIARY (4) minus one.
|
||||
return 2;
|
||||
case SDL_BUTTON_X1:
|
||||
return 7;
|
||||
case SDL_BUTTON_X2:
|
||||
@@ -316,6 +317,7 @@ Status RobloxInputRouter::Activate(RobloxInputViewport viewport,
|
||||
gamepads_.clear();
|
||||
mouse_x_ = 0.0f;
|
||||
mouse_y_ = 0.0f;
|
||||
pointer_anchored_ = false;
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
@@ -549,20 +551,21 @@ RobloxInputDispatchResult RobloxInputRouter::HandleMouseMotionLocked(
|
||||
const float delta_x = transform.HostLogicalToGuestX(event.delta_x);
|
||||
const float delta_y = transform.HostLogicalToGuestY(event.delta_y);
|
||||
|
||||
const float max_x = std::max(0.0F, transform.guest_width() - 1.0F);
|
||||
const float max_y = std::max(0.0F, transform.guest_height() - 1.0F);
|
||||
|
||||
// mouse_x_/mouse_y_ stay inside the viewport. Relative-mode motion reports
|
||||
// zero absolute coordinates, so the accumulated position is the only
|
||||
// position there; letting it drift past the edge would swallow every
|
||||
// reversal until the pointer walked all the way back.
|
||||
if (event.x == 0.0f && event.y == 0.0f &&
|
||||
(delta_x != 0.0f || delta_y != 0.0f)) {
|
||||
mouse_x_ = std::clamp(mouse_x_ + delta_x, 0.0f, max_x);
|
||||
mouse_y_ = std::clamp(mouse_y_ + delta_y, 0.0f, max_y);
|
||||
// The pointer holds its captured position while the delta passes through, so
|
||||
// a long camera turn neither parks the reported position at the viewport edge
|
||||
// nor swallows the reversal. Roblox draws its cursor at the held position
|
||||
// when the capture ends, which matches where the host pointer is warped.
|
||||
// Capture is read from the event, not inferred: only X11 zeroes the absolute
|
||||
// coordinates, while Wayland reports a position that accumulates the deltas.
|
||||
if (event.relative || (event.x == 0.0f && event.y == 0.0f &&
|
||||
(delta_x != 0.0f || delta_y != 0.0f))) {
|
||||
HoldPointerLocked(transform);
|
||||
} else {
|
||||
const float max_x = std::max(0.0F, transform.guest_width() - 1.0F);
|
||||
const float max_y = std::max(0.0F, transform.guest_height() - 1.0F);
|
||||
mouse_x_ = std::clamp(transform.HostLogicalToGuestX(event.x), 0.0f, max_x);
|
||||
mouse_y_ = std::clamp(transform.HostLogicalToGuestY(event.y), 0.0f, max_y);
|
||||
pointer_anchored_ = true;
|
||||
}
|
||||
|
||||
// Raw mouse reports the host's own delta, skipping the guest-surface scale
|
||||
@@ -584,25 +587,28 @@ RobloxInputDispatchResult RobloxInputRouter::HandleMouseButtonLocked(
|
||||
RobloxInputEventKind::kMouseButton,
|
||||
Unsupported("native mouse buttons are unavailable"));
|
||||
}
|
||||
const int32_t android_button = MapSdlMouseButtonToAndroid(event.button);
|
||||
if (android_button < 0) {
|
||||
const int32_t roblox_button = MapSdlMouseButtonToRoblox(event.button);
|
||||
if (roblox_button < 0) {
|
||||
return Result(RobloxInputDispatchState::kIgnoredUnsupported,
|
||||
RobloxInputEventKind::kMouseButton,
|
||||
Unsupported("SDL mouse button has no Android mapping"));
|
||||
}
|
||||
if (event.x > 0.0f || event.y > 0.0f ||
|
||||
(mouse_x_ == 0.0f && mouse_y_ == 0.0f)) {
|
||||
const platform::SurfaceCoordinateTransform transform =
|
||||
CoordinateTransform(snapshot_.viewport);
|
||||
mouse_x_ = transform.HostLogicalToGuestX(event.x);
|
||||
mouse_y_ = transform.HostLogicalToGuestY(event.y);
|
||||
Unsupported("SDL mouse button has no Roblox mapping"));
|
||||
}
|
||||
const platform::SurfaceCoordinateTransform transform =
|
||||
CoordinateTransform(snapshot_.viewport);
|
||||
const float max_x = std::max(0.0F, transform.guest_width() - 1.0F);
|
||||
const float max_y = std::max(0.0F, transform.guest_height() - 1.0F);
|
||||
const float clamped_x = std::clamp(mouse_x_, 0.0f, max_x);
|
||||
const float clamped_y = std::clamp(mouse_y_, 0.0f, max_y);
|
||||
// Button events during pointer capture must not move the held position.
|
||||
// Their coordinates are zeroed on X11 and drifted on Wayland, so the capture
|
||||
// flag decides.
|
||||
if (!event.relative && (event.x > 0.0f || event.y > 0.0f)) {
|
||||
mouse_x_ = std::clamp(transform.HostLogicalToGuestX(event.x), 0.0f, max_x);
|
||||
mouse_y_ = std::clamp(transform.HostLogicalToGuestY(event.y), 0.0f, max_y);
|
||||
pointer_anchored_ = true;
|
||||
} else {
|
||||
HoldPointerLocked(transform);
|
||||
}
|
||||
const float clamped_x = mouse_x_;
|
||||
const float clamped_y = mouse_y_;
|
||||
if (event.pressed) {
|
||||
const RobloxTextEditorSnapshot text = text_editor_.Snapshot();
|
||||
if (text.focused) {
|
||||
@@ -611,12 +617,12 @@ RobloxInputDispatchResult RobloxInputRouter::HandleMouseButtonLocked(
|
||||
}
|
||||
}
|
||||
Status status = sink_.mouse_button(sink_.context, clamped_x, clamped_y,
|
||||
event.pressed, android_button);
|
||||
event.pressed, roblox_button);
|
||||
if (status.ok()) {
|
||||
const auto active = std::find(active_mouse_buttons_.begin(),
|
||||
active_mouse_buttons_.end(), android_button);
|
||||
active_mouse_buttons_.end(), roblox_button);
|
||||
if (event.pressed && active == active_mouse_buttons_.end()) {
|
||||
active_mouse_buttons_.push_back(android_button);
|
||||
active_mouse_buttons_.push_back(roblox_button);
|
||||
} else if (!event.pressed && active != active_mouse_buttons_.end()) {
|
||||
active_mouse_buttons_.erase(active);
|
||||
}
|
||||
@@ -635,13 +641,39 @@ RobloxInputDispatchResult RobloxInputRouter::HandleMouseWheelLocked(
|
||||
}
|
||||
const platform::SurfaceCoordinateTransform transform =
|
||||
CoordinateTransform(snapshot_.viewport);
|
||||
mouse_x_ = transform.HostLogicalToGuestX(std::max(0.0f, event.mouse_x));
|
||||
mouse_y_ = transform.HostLogicalToGuestY(std::max(0.0f, event.mouse_y));
|
||||
// Wheel events during pointer capture must not move the held position.
|
||||
// Their coordinates are zeroed on X11 and drifted on Wayland, so the capture
|
||||
// flag decides.
|
||||
if (!event.relative && (event.mouse_x > 0.0f || event.mouse_y > 0.0f)) {
|
||||
const float max_x = std::max(0.0F, transform.guest_width() - 1.0F);
|
||||
const float max_y = std::max(0.0F, transform.guest_height() - 1.0F);
|
||||
mouse_x_ = std::clamp(transform.HostLogicalToGuestX(event.mouse_x), 0.0f,
|
||||
max_x);
|
||||
mouse_y_ = std::clamp(transform.HostLogicalToGuestY(event.mouse_y), 0.0f,
|
||||
max_y);
|
||||
pointer_anchored_ = true;
|
||||
} else {
|
||||
HoldPointerLocked(transform);
|
||||
}
|
||||
return NativeResultLocked(
|
||||
sink_.mouse_wheel(sink_.context, mouse_x_, mouse_y_, event.delta_y),
|
||||
RobloxInputEventKind::kMouseWheel);
|
||||
}
|
||||
|
||||
void RobloxInputRouter::HoldPointerLocked(
|
||||
const platform::SurfaceCoordinateTransform& transform) {
|
||||
const float max_x = std::max(0.0F, transform.guest_width() - 1.0F);
|
||||
const float max_y = std::max(0.0F, transform.guest_height() - 1.0F);
|
||||
if (!pointer_anchored_) {
|
||||
mouse_x_ = max_x / 2.0f;
|
||||
mouse_y_ = max_y / 2.0f;
|
||||
pointer_anchored_ = true;
|
||||
return;
|
||||
}
|
||||
mouse_x_ = std::clamp(mouse_x_, 0.0f, max_x);
|
||||
mouse_y_ = std::clamp(mouse_y_, 0.0f, max_y);
|
||||
}
|
||||
|
||||
RobloxInputDispatchResult RobloxInputRouter::HandleTouchLocked(
|
||||
const platform::TouchEvent& event) {
|
||||
if (sink_.touch == nullptr) {
|
||||
|
||||
@@ -640,5 +640,64 @@ Status ParseRobloxLaunchUri(std::string_view uri,
|
||||
return MakeRequest(fields, request);
|
||||
}
|
||||
|
||||
Status ParseRobloxWebViewLaunchGame(std::string_view command,
|
||||
RobloxExperienceLaunchRequest* request) {
|
||||
if (request == nullptr) {
|
||||
return Invalid("Roblox launchGame output is null");
|
||||
}
|
||||
*request = {};
|
||||
const nlohmann::json document =
|
||||
command.size() <= kMaximumRobloxLaunchUriBytes
|
||||
? nlohmann::json::parse(command, nullptr, false)
|
||||
: nlohmann::json();
|
||||
const auto function_name = document.is_object()
|
||||
? document.find("functionName")
|
||||
: document.end();
|
||||
if (!document.is_object() || function_name == document.end() ||
|
||||
*function_name != "launchGame") {
|
||||
return Status::Error(StatusCode::kUnsupported,
|
||||
"WebView command is not launchGame");
|
||||
}
|
||||
const auto params = document.find("params");
|
||||
if (params == document.end() || !params->is_object()) {
|
||||
return Invalid("Roblox launchGame has no params");
|
||||
}
|
||||
const auto launch = params->find("request");
|
||||
if (launch == params->end() || !launch->is_object()) {
|
||||
return Invalid("Roblox launchGame has no request");
|
||||
}
|
||||
if (launch->size() > kMaximumParameterCount) {
|
||||
return Invalid("Roblox launchGame request has too many fields");
|
||||
}
|
||||
LaunchFields fields;
|
||||
for (const auto& [key, value] : launch->items()) {
|
||||
std::string text;
|
||||
if (value.is_string()) {
|
||||
text = value.get<std::string>();
|
||||
} else if (value.is_number_unsigned()) {
|
||||
text = std::to_string(value.get<uint64_t>());
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if (text.size() > kMaximumParameterValueBytes ||
|
||||
ContainsControlBytes(text)) {
|
||||
return Invalid("Roblox launchGame field is invalid");
|
||||
}
|
||||
Status status = AssignField(key == "requestType" ? "request" : key,
|
||||
std::move(text), false, &fields);
|
||||
if (!status.ok()) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
if (fields.request_type.empty()) {
|
||||
return Invalid("Roblox launchGame request type is missing");
|
||||
}
|
||||
Status status = MakeRequest(fields, request);
|
||||
if (!status.ok()) {
|
||||
*request = {};
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
} // namespace runtime
|
||||
} // namespace mocktail
|
||||
@@ -1,7 +1,11 @@
|
||||
#include "runtime/roblox_platform_web_symbols.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "compat/web_view_protocol_contract.h"
|
||||
#include "linker/linker.h"
|
||||
|
||||
namespace mocktail {
|
||||
@@ -14,6 +18,41 @@ Function Resolve(void* library, const char* name) {
|
||||
linker::ResolveSymbol(library, std::string(name)));
|
||||
}
|
||||
|
||||
// Reads the mapped initializer and follows its getter call only when both
|
||||
// match the code contract for this host's architecture. Both reads stay
|
||||
// inside libroblox.so's text segment: the initializer is longer than the scan
|
||||
// window, and the getter address comes from a verified call site.
|
||||
AcquireWebViewProtocolFn FindWebViewProtocolGetter(const void* initializer) {
|
||||
if (initializer == nullptr) return nullptr;
|
||||
const auto address = reinterpret_cast<std::uintptr_t>(initializer);
|
||||
const std::string_view code(static_cast<const char*>(initializer),
|
||||
compat::kWebViewProtocolInitializerScanBytes);
|
||||
#if defined(__x86_64__)
|
||||
const std::optional<std::uintptr_t> getter =
|
||||
compat::FindWebViewProtocolGetterCallX86_64(code, address);
|
||||
const bool getter_matches =
|
||||
getter.has_value() &&
|
||||
compat::HasWebViewProtocolGetterContractX86_64(std::string_view(
|
||||
reinterpret_cast<const char*>(*getter),
|
||||
compat::kWebViewProtocolGetterBytesX86_64));
|
||||
#elif defined(__aarch64__)
|
||||
const std::optional<std::uintptr_t> getter =
|
||||
compat::FindWebViewProtocolGetterCallArm64(code, address);
|
||||
const bool getter_matches =
|
||||
getter.has_value() &&
|
||||
compat::HasWebViewProtocolGetterContractArm64(std::string_view(
|
||||
reinterpret_cast<const char*>(*getter),
|
||||
compat::kWebViewProtocolGetterBytesArm64));
|
||||
#else
|
||||
const std::optional<std::uintptr_t> getter;
|
||||
const bool getter_matches = false;
|
||||
(void)code;
|
||||
(void)address;
|
||||
#endif
|
||||
return getter_matches ? reinterpret_cast<AcquireWebViewProtocolFn>(*getter)
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
RobloxPlatformWebSymbols ResolveRobloxPlatformWebSymbols(
|
||||
@@ -46,6 +85,9 @@ RobloxPlatformWebSymbols ResolveRobloxPlatformWebSymbols(
|
||||
roblox_library,
|
||||
"Java_com_roblox_protocols_webview_WebViewProtocol_"
|
||||
"initializeAndroidWebViewProtocol");
|
||||
symbols.web_view.acquire_web_view_protocol = FindWebViewProtocolGetter(
|
||||
reinterpret_cast<const void*>(
|
||||
symbols.web_view.initialize_android_web_view_protocol));
|
||||
symbols.web_view.subscribe_raw = subscribe_raw;
|
||||
symbols.web_view.delete_connection = delete_connection;
|
||||
symbols.web_view.set_request_handler_raw =
|
||||
@@ -118,6 +160,24 @@ RobloxPlatformWebSymbols ResolveRobloxPlatformWebSymbols(
|
||||
roblox_library,
|
||||
"Java_com_roblox_universalapp_messagebus_MessageBus_"
|
||||
"callResponseHandlerRaw");
|
||||
using AccountStringFn = RobloxAccountProtocolSymbols::GetStringFn;
|
||||
constexpr char kAccountPrefix[] =
|
||||
"Java_com_roblox_universalapp_account_JNIAccountProtocol_";
|
||||
const auto account_getter = [&](const char* name) {
|
||||
return Resolve<AccountStringFn>(roblox_library,
|
||||
(std::string(kAccountPrefix) + name).c_str());
|
||||
};
|
||||
symbols.account.get_protocol_name = account_getter("getProtocolName");
|
||||
symbols.account.get_device_integrity_available_method_name =
|
||||
account_getter("getDeviceIntegrityAvailableMethodName");
|
||||
symbols.account.get_integrity_token_method_name =
|
||||
account_getter("getGetIntegrityTokenMethodName");
|
||||
symbols.account.get_support_key = account_getter("getSupportKey");
|
||||
symbols.account.get_token_key = account_getter("getTokenKey");
|
||||
symbols.account.get_result_key = account_getter("getResultKey");
|
||||
symbols.account.set_request_handler_raw =
|
||||
symbols.web_view.set_request_handler_raw;
|
||||
symbols.account.clear_request_handler = symbols.web_view.clear_request_handler;
|
||||
return symbols;
|
||||
}
|
||||
|
||||
|
||||
@@ -244,7 +244,7 @@ struct TextBytePosition {
|
||||
};
|
||||
|
||||
TextBytePosition TextPosition(TTF_Text* layout, std::size_t byte_offset,
|
||||
int text_width) {
|
||||
int text_width, bool single_line) {
|
||||
if (layout == nullptr) {
|
||||
return {};
|
||||
}
|
||||
@@ -259,7 +259,11 @@ TextBytePosition TextPosition(TTF_Text* layout, std::size_t byte_offset,
|
||||
position.y = substring.rect.y;
|
||||
position.height = substring.rect.h;
|
||||
if ((substring.flags & TTF_SUBSTRING_TEXT_END) != 0) {
|
||||
position.x = std::min(text_width, substring.rect.x + substring.rect.w);
|
||||
// Trailing whitespace has no ink, so the final cluster rect stops short of
|
||||
// the laid-out width that a caret at the end of a single line sits behind.
|
||||
position.x = single_line ? text_width
|
||||
: std::min(text_width,
|
||||
substring.rect.x + substring.rect.w);
|
||||
}
|
||||
return position;
|
||||
}
|
||||
@@ -297,6 +301,7 @@ Status RobloxTextSurfaceOverlay::Shutdown() {
|
||||
}
|
||||
state_.Reset();
|
||||
ClearFrameLocked();
|
||||
CloseFontsLocked();
|
||||
viewport_ = {};
|
||||
initialized_ = false;
|
||||
if (owned_active_overlay) {
|
||||
@@ -441,10 +446,6 @@ Status RobloxTextSurfaceOverlay::RasterizeLocked() {
|
||||
const bool wrapped_layout =
|
||||
presentation.multiline || presentation.text_wrapped;
|
||||
|
||||
if (!TTF_Init()) {
|
||||
SecureClear(&candidate);
|
||||
return RasterizationFailure("unable to initialize SDL3_ttf");
|
||||
}
|
||||
const RobloxTextFontSelection font_selection =
|
||||
ResolveRobloxTextFont(presentation.font);
|
||||
const float native_point_size =
|
||||
@@ -454,23 +455,12 @@ Status RobloxTextSurfaceOverlay::RasterizeLocked() {
|
||||
? std::clamp(native_point_size * font_selection.size_scale, 1.0F,
|
||||
512.0F)
|
||||
: std::clamp(static_cast<float>(height) * 0.38F, 12.0F, 28.0F);
|
||||
const std::vector<std::string> font_files = ResolveFontFiles(font_selection);
|
||||
std::vector<TTF_Font*> fonts;
|
||||
fonts.reserve(font_files.size());
|
||||
for (const std::string& file : font_files) {
|
||||
TTF_Font* font = TTF_OpenFont(file.c_str(), point_size);
|
||||
if (font != nullptr) {
|
||||
fonts.push_back(font);
|
||||
}
|
||||
}
|
||||
if (fonts.empty()) {
|
||||
TTF_Quit();
|
||||
if (Status status = OpenFontsLocked(presentation.font, point_size);
|
||||
!status.ok()) {
|
||||
SecureClear(&candidate);
|
||||
return RasterizationFailure("unable to open a Roblox or fallback font");
|
||||
}
|
||||
for (std::size_t index = 1; index < fonts.size(); ++index) {
|
||||
(void)TTF_AddFallbackFont(fonts.front(), fonts[index]);
|
||||
return status;
|
||||
}
|
||||
const std::vector<TTF_Font*>& fonts = fonts_;
|
||||
if (wrapped_layout) {
|
||||
TTF_HorizontalAlignment alignment = TTF_HORIZONTAL_ALIGN_LEFT;
|
||||
if (presentation.x_alignment == 1) {
|
||||
@@ -501,11 +491,12 @@ Status RobloxTextSurfaceOverlay::RasterizeLocked() {
|
||||
TextBytePosition selection_end_position;
|
||||
if (layout != nullptr) {
|
||||
(void)TTF_GetTextSize(layout, &text_width, &text_height);
|
||||
caret_position = TextPosition(layout, caret_byte, text_width);
|
||||
selection_begin_position =
|
||||
TextPosition(layout, selection_begin_byte, text_width);
|
||||
caret_position =
|
||||
TextPosition(layout, caret_byte, text_width, !wrapped_layout);
|
||||
selection_begin_position = TextPosition(layout, selection_begin_byte,
|
||||
text_width, !wrapped_layout);
|
||||
selection_end_position =
|
||||
TextPosition(layout, selection_end_byte, text_width);
|
||||
TextPosition(layout, selection_end_byte, text_width, !wrapped_layout);
|
||||
}
|
||||
if (!text.value.empty()) {
|
||||
// SDL_ttf implementations have historically differed on whether fg.a is
|
||||
@@ -624,11 +615,6 @@ Status RobloxTextSurfaceOverlay::RasterizeLocked() {
|
||||
if (layout != nullptr) {
|
||||
TTF_DestroyText(layout);
|
||||
}
|
||||
TTF_ClearFallbackFonts(fonts.front());
|
||||
for (auto iterator = fonts.rbegin(); iterator != fonts.rend(); ++iterator) {
|
||||
TTF_CloseFont(*iterator);
|
||||
}
|
||||
TTF_Quit();
|
||||
|
||||
if (!status.ok()) {
|
||||
SecureClear(&candidate);
|
||||
@@ -646,6 +632,58 @@ Status RobloxTextSurfaceOverlay::RasterizeLocked() {
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
Status RobloxTextSurfaceOverlay::OpenFontsLocked(std::int32_t font,
|
||||
float point_size) {
|
||||
if (!fonts_.empty() && fonts_font_ == font &&
|
||||
fonts_point_size_ == point_size) {
|
||||
return Status::Ok();
|
||||
}
|
||||
if (!TTF_Init()) {
|
||||
return RasterizationFailure("unable to initialize SDL3_ttf");
|
||||
}
|
||||
const std::vector<std::string> files =
|
||||
ResolveFontFiles(ResolveRobloxTextFont(font));
|
||||
std::vector<TTF_Font*> opened;
|
||||
opened.reserve(files.size());
|
||||
for (const std::string& file : files) {
|
||||
TTF_Font* candidate = TTF_OpenFont(file.c_str(), point_size);
|
||||
if (candidate != nullptr) {
|
||||
opened.push_back(candidate);
|
||||
}
|
||||
}
|
||||
// A failed reopen leaves the fonts already rendering in place.
|
||||
if (opened.empty()) {
|
||||
TTF_Quit();
|
||||
return RasterizationFailure("unable to open a Roblox or fallback font");
|
||||
}
|
||||
for (std::size_t index = 1; index < opened.size(); ++index) {
|
||||
(void)TTF_AddFallbackFont(opened.front(), opened[index]);
|
||||
}
|
||||
CloseFontsLocked();
|
||||
fonts_ = std::move(opened);
|
||||
ttf_initialized_ = true;
|
||||
fonts_font_ = font;
|
||||
fonts_point_size_ = point_size;
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
void RobloxTextSurfaceOverlay::CloseFontsLocked() {
|
||||
if (!fonts_.empty()) {
|
||||
TTF_ClearFallbackFonts(fonts_.front());
|
||||
for (auto iterator = fonts_.rbegin(); iterator != fonts_.rend();
|
||||
++iterator) {
|
||||
TTF_CloseFont(*iterator);
|
||||
}
|
||||
fonts_.clear();
|
||||
}
|
||||
fonts_font_ = 0;
|
||||
fonts_point_size_ = 0.0F;
|
||||
if (ttf_initialized_) {
|
||||
TTF_Quit();
|
||||
ttf_initialized_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void RobloxTextSurfaceOverlay::ClearFrameLocked() {
|
||||
SecureClear(&rgba_);
|
||||
raster_revision_ = 0;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <utility>
|
||||
|
||||
#include "runtime/environment.h"
|
||||
#include "webview/roblox_challenge_features.h"
|
||||
|
||||
namespace mocktail {
|
||||
namespace runtime {
|
||||
@@ -401,6 +402,39 @@ Status ParseRobloxCaptchaOpenJson(const std::string& json,
|
||||
return Status::Ok();
|
||||
}
|
||||
|
||||
bool IsRobloxWebViewChallengeSuccess(std::string_view command) {
|
||||
if (command.empty() || command.size() > kMaximumRobloxWebViewJsonBytes) {
|
||||
return false;
|
||||
}
|
||||
const nlohmann::json document =
|
||||
nlohmann::json::parse(command.begin(), command.end(), nullptr, false);
|
||||
const auto string_field = [](const nlohmann::json& object,
|
||||
const char* key) -> const std::string* {
|
||||
const auto field = object.find(key);
|
||||
return field != object.end() && field->is_string()
|
||||
? &field->get_ref<const std::string&>()
|
||||
: nullptr;
|
||||
};
|
||||
const auto object_field = [](const nlohmann::json& object,
|
||||
const char* key) -> const nlohmann::json* {
|
||||
const auto field = object.find(key);
|
||||
return field != object.end() && field->is_object() ? &*field : nullptr;
|
||||
};
|
||||
if (!document.is_object()) {
|
||||
return false;
|
||||
}
|
||||
const std::string* module = string_field(document, "moduleID");
|
||||
const std::string* function = string_field(document, "functionName");
|
||||
const nlohmann::json* outer = object_field(document, "params");
|
||||
const nlohmann::json* navigation =
|
||||
outer != nullptr ? object_field(*outer, "params") : nullptr;
|
||||
const std::string* feature =
|
||||
navigation != nullptr ? string_field(*navigation, "feature") : nullptr;
|
||||
return module != nullptr && *module == "Navigation" && function != nullptr &&
|
||||
*function == "navigateToFeature" && feature != nullptr &&
|
||||
webview::IsRobloxChallengeSolvedFeature(*feature);
|
||||
}
|
||||
|
||||
Status ParseRobloxProfileViewUrl(const std::string& url,
|
||||
RobloxWebViewOpenRequest* request) {
|
||||
if (request == nullptr) {
|
||||
@@ -911,6 +945,20 @@ Status RobloxWebViewBridge::Initialize() {
|
||||
// handler and window subscriptions are installed before the native Android
|
||||
// protocol is initialized. Calling the native initializer earlier loses
|
||||
// messages that it can publish synchronously during startup.
|
||||
// Roblox's Android app start holds a WebViewProtocol handle for the process
|
||||
// lifetime. Without one, the protocol is deleted as soon as each caller
|
||||
// releases it, and page callbacks wait for the next Lua WebView call to
|
||||
// recreate it. Taking it before the native initializer keeps the protocol
|
||||
// that initializer configures.
|
||||
if (symbols_.acquire_web_view_protocol != nullptr) {
|
||||
if (web_view_protocol_handle_.holder() == nullptr) {
|
||||
web_view_protocol_handle_ = symbols_.acquire_web_view_protocol();
|
||||
}
|
||||
} else {
|
||||
std::fprintf(stderr,
|
||||
" [webview] WebViewProtocol getter not recognized; page "
|
||||
"callbacks may wait for the next Roblox WebView call\n");
|
||||
}
|
||||
jclass initialization_class = env->FindClass(kWebViewProtocolClass);
|
||||
if (initialization_class != nullptr) {
|
||||
symbols_.initialize_android_web_view_protocol(env, initialization_class);
|
||||
@@ -1266,6 +1314,7 @@ Status RobloxWebViewBridge::DispatchOpenRequest(
|
||||
exit_context->target->browser_login_fallback = browser_login_fallback;
|
||||
}
|
||||
}
|
||||
request.close_when_challenge_solved = source == OpenSource::kCaptcha;
|
||||
if (status.ok()) {
|
||||
status = sink_.dispatch_open(
|
||||
sink_.context, request,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
#include <climits>
|
||||
#include <cstdlib>
|
||||
#include <optional>
|
||||
#include <tuple>
|
||||
|
||||
#ifndef MOCKTAIL_DISCORD_APPLICATION_ID
|
||||
#define MOCKTAIL_DISCORD_APPLICATION_ID ""
|
||||
@@ -40,13 +41,17 @@ bool IsDiscordApplicationId(std::string_view value) {
|
||||
}));
|
||||
}
|
||||
|
||||
bool IsDiscordText(std::string_view value, std::size_t maximum) {
|
||||
return !value.empty() && value.size() <= maximum &&
|
||||
bool IsDiscordOptionalText(std::string_view value, std::size_t maximum) {
|
||||
return value.size() <= maximum &&
|
||||
std::none_of(value.begin(), value.end(), [](unsigned char byte) {
|
||||
return byte < 0x20 || byte == 0x7f;
|
||||
});
|
||||
}
|
||||
|
||||
bool IsDiscordText(std::string_view value, std::size_t maximum) {
|
||||
return !value.empty() && IsDiscordOptionalText(value, maximum);
|
||||
}
|
||||
|
||||
bool ReadBoolean(const Environment& environment, std::string_view name,
|
||||
bool default_value, bool* valid) {
|
||||
const std::optional<std::string> value = environment.Get(name);
|
||||
@@ -357,18 +362,40 @@ RuntimeConfig RuntimeConfig::FromEnvironment(const Environment& environment) {
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_JOINING", config.discord_rpc_.text.joining);
|
||||
config.discord_rpc_.text.playing = environment.GetOr(
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_PLAYING", config.discord_rpc_.text.playing);
|
||||
config.discord_rpc_.text.state = environment.GetOr(
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_STATE", config.discord_rpc_.text.state);
|
||||
config.discord_rpc_.text.unknown_place = environment.GetOr(
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_UNKNOWN_PLACE",
|
||||
config.discord_rpc_.text.unknown_place);
|
||||
config.discord_rpc_valid_ = discord_booleans_valid &&
|
||||
// An empty presence field hides it, so only an unset variable keeps the
|
||||
// default.
|
||||
bool discord_presence_valid = true;
|
||||
for (const auto& [variable, field, maximum] : {
|
||||
std::tuple<std::string_view, std::string*, std::size_t>(
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_TITLE",
|
||||
&config.discord_rpc_.text.title, 128),
|
||||
{"MOCKTAIL_DISCORD_RPC_TEXT_STATE",
|
||||
&config.discord_rpc_.text.state, 128},
|
||||
{"MOCKTAIL_DISCORD_RPC_IMAGE_LARGE",
|
||||
&config.discord_rpc_.images.large, 512},
|
||||
{"MOCKTAIL_DISCORD_RPC_IMAGE_LARGE_TEXT",
|
||||
&config.discord_rpc_.images.large_text, 128},
|
||||
{"MOCKTAIL_DISCORD_RPC_IMAGE_SMALL",
|
||||
&config.discord_rpc_.images.small, 512},
|
||||
{"MOCKTAIL_DISCORD_RPC_IMAGE_SMALL_TEXT",
|
||||
&config.discord_rpc_.images.small_text, 128},
|
||||
}) {
|
||||
if (std::optional<std::string> value = environment.Get(variable)) {
|
||||
*field = std::move(*value);
|
||||
}
|
||||
discord_presence_valid =
|
||||
discord_presence_valid && IsDiscordOptionalText(*field, maximum);
|
||||
}
|
||||
config.discord_rpc_valid_ =
|
||||
discord_booleans_valid && discord_presence_valid &&
|
||||
IsDiscordApplicationId(config.discord_rpc_.application_id) &&
|
||||
IsDiscordText(config.discord_rpc_.join_button_label, 32) &&
|
||||
IsDiscordText(config.discord_rpc_.text.browsing, 128) &&
|
||||
IsDiscordText(config.discord_rpc_.text.joining, 128) &&
|
||||
IsDiscordText(config.discord_rpc_.text.playing, 128) &&
|
||||
IsDiscordText(config.discord_rpc_.text.state, 128) &&
|
||||
IsDiscordText(config.discord_rpc_.text.unknown_place, 128);
|
||||
for (const std::string_view name : kUnsafeDetachedThreadOverrides) {
|
||||
if (LegacyEnabled(environment, name)) {
|
||||
|
||||
@@ -131,12 +131,24 @@ integrations:
|
||||
public_servers_only: true
|
||||
# button_label: Join Server
|
||||
# English defaults. Uncomment only the lines you want to customize.
|
||||
# Text and image fields accept {place_name}, {place_icon}, and
|
||||
# {creator_name}. A field that expands an empty placeholder is left out,
|
||||
# and a "" title shows the app name.
|
||||
# title, state, and the images fields may be "" to hide them.
|
||||
# text:
|
||||
# browsing: Browsing experiences
|
||||
# joining: Joining an experience
|
||||
# playing: "{place_name}"
|
||||
# state: Playing Roblox
|
||||
# playing: "Playing {place_name}"
|
||||
# state: "by {creator_name}"
|
||||
# unknown_place: Unknown experience
|
||||
# title: Roblox
|
||||
# Images take an https:// URL, or an asset key uploaded to application_id.
|
||||
# large: "" hides both images; the small image needs a large one.
|
||||
# images:
|
||||
# large: "{place_icon}"
|
||||
# large_text: "{place_name}"
|
||||
# small: roblox_small
|
||||
# small_text: Roblox
|
||||
# Advanced: overrides the application bundled by the package maintainer.
|
||||
# application_id: 123456789012345678
|
||||
|
||||
|
||||
@@ -205,6 +205,11 @@ bool ValidateAndMap(const ValueMap& yaml, ValueMap* environment,
|
||||
"integrations.discord_rpc.text.playing",
|
||||
"integrations.discord_rpc.text.state",
|
||||
"integrations.discord_rpc.text.unknown_place",
|
||||
"integrations.discord_rpc.text.title",
|
||||
"integrations.discord_rpc.images.large",
|
||||
"integrations.discord_rpc.images.large_text",
|
||||
"integrations.discord_rpc.images.small",
|
||||
"integrations.discord_rpc.images.small_text",
|
||||
};
|
||||
for (const auto& [key, ignored] : yaml) {
|
||||
if (supported.find(key) == supported.end()) {
|
||||
@@ -554,8 +559,6 @@ bool ValidateAndMap(const ValueMap& yaml, ValueMap* environment,
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_JOINING", 128},
|
||||
{"integrations.discord_rpc.text.playing",
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_PLAYING", 128},
|
||||
{"integrations.discord_rpc.text.state",
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_STATE", 128},
|
||||
{"integrations.discord_rpc.text.unknown_place",
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_UNKNOWN_PLACE", 128},
|
||||
}) {
|
||||
@@ -574,6 +577,36 @@ bool ValidateAndMap(const ValueMap& yaml, ValueMap* environment,
|
||||
}
|
||||
(*environment)[std::string(field.variable)] = *configured;
|
||||
}
|
||||
// Presence fields may be empty: an empty value hides that field.
|
||||
for (const DiscordStringField& field : {
|
||||
DiscordStringField{"integrations.discord_rpc.text.title",
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_TITLE", 128},
|
||||
{"integrations.discord_rpc.text.state",
|
||||
"MOCKTAIL_DISCORD_RPC_TEXT_STATE", 128},
|
||||
{"integrations.discord_rpc.images.large",
|
||||
"MOCKTAIL_DISCORD_RPC_IMAGE_LARGE", 512},
|
||||
{"integrations.discord_rpc.images.large_text",
|
||||
"MOCKTAIL_DISCORD_RPC_IMAGE_LARGE_TEXT", 128},
|
||||
{"integrations.discord_rpc.images.small",
|
||||
"MOCKTAIL_DISCORD_RPC_IMAGE_SMALL", 512},
|
||||
{"integrations.discord_rpc.images.small_text",
|
||||
"MOCKTAIL_DISCORD_RPC_IMAGE_SMALL_TEXT", 128},
|
||||
}) {
|
||||
const std::optional<std::string> configured = value(field.yaml);
|
||||
if (!configured.has_value()) {
|
||||
continue;
|
||||
}
|
||||
if (configured->size() > field.maximum ||
|
||||
std::any_of(configured->begin(), configured->end(),
|
||||
[](unsigned char byte) {
|
||||
return byte < 0x20 || byte == 0x7f;
|
||||
})) {
|
||||
*error = std::string(field.yaml) +
|
||||
" must be bounded and contain no control bytes";
|
||||
return false;
|
||||
}
|
||||
(*environment)[std::string(field.variable)] = *configured;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -940,7 +973,17 @@ bool ExportRuntimeConfigEnvironment(const RuntimeConfig& config,
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_TEXT_STATE",
|
||||
config.discord_rpc().text.state, error) &&
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_TEXT_UNKNOWN_PLACE",
|
||||
config.discord_rpc().text.unknown_place, error);
|
||||
config.discord_rpc().text.unknown_place, error) &&
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_TEXT_TITLE",
|
||||
config.discord_rpc().text.title, error) &&
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_IMAGE_LARGE",
|
||||
config.discord_rpc().images.large, error) &&
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_IMAGE_LARGE_TEXT",
|
||||
config.discord_rpc().images.large_text, error) &&
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_IMAGE_SMALL",
|
||||
config.discord_rpc().images.small, error) &&
|
||||
SetEnvironmentValue("MOCKTAIL_DISCORD_RPC_IMAGE_SMALL_TEXT",
|
||||
config.discord_rpc().images.small_text, error);
|
||||
if (!base_exported) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@
|
||||
#include <unistd.h>
|
||||
#include <utility>
|
||||
|
||||
#include "compat/guest_abi.h"
|
||||
|
||||
namespace mocktail {
|
||||
namespace runtime {
|
||||
namespace {
|
||||
@@ -438,8 +440,8 @@ ActivePayloadPaths RuntimePaths::ResolveActivePayload() const {
|
||||
const std::filesystem::path library = canonical_root / "libroblox.so";
|
||||
const std::filesystem::path package_root = canonical_root / "sober_apk";
|
||||
const std::filesystem::path base_apk = package_root / "base.apk";
|
||||
const std::filesystem::path x86_64_split_apk =
|
||||
package_root / "split_config.x86_64.apk";
|
||||
const std::filesystem::path arch_split_apk =
|
||||
package_root / compat::kGuestSplitApkFile;
|
||||
const std::filesystem::path assets_root = canonical_root / "assets";
|
||||
const std::filesystem::path assets = canonical_root / "assets/content";
|
||||
const std::filesystem::file_status library_status =
|
||||
@@ -460,7 +462,8 @@ ActivePayloadPaths RuntimePaths::ResolveActivePayload() const {
|
||||
for (const auto& [path, name] :
|
||||
std::array<std::pair<std::filesystem::path, const char*>, 2>{
|
||||
std::pair{base_apk, "base.apk"},
|
||||
std::pair{x86_64_split_apk, "split_config.x86_64.apk"}}) {
|
||||
std::pair{arch_split_apk,
|
||||
compat::kGuestSplitApkFile.data()}}) {
|
||||
const std::filesystem::file_status status =
|
||||
std::filesystem::symlink_status(path, filesystem_error);
|
||||
if (filesystem_error || !std::filesystem::is_regular_file(status) ||
|
||||
@@ -489,7 +492,7 @@ ActivePayloadPaths RuntimePaths::ResolveActivePayload() const {
|
||||
result.root = canonical_root;
|
||||
result.roblox_library = library;
|
||||
result.base_apk = base_apk;
|
||||
result.x86_64_split_apk = x86_64_split_apk;
|
||||
result.arch_split_apk = arch_split_apk;
|
||||
result.assets_content = assets;
|
||||
|
||||
const auto compatibility_manifest =
|
||||
|
||||
+25
-13
@@ -28,6 +28,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "compat/elf_build_id.h"
|
||||
#include "compat/guest_abi.h"
|
||||
#include "update/android_manifest.h"
|
||||
#include "update/apk_signature.h"
|
||||
#include "update/payload_integrity.h"
|
||||
@@ -173,10 +174,15 @@ bool EndsWith(std::string_view value, std::string_view suffix) {
|
||||
struct ApkCandidate {
|
||||
std::filesystem::path path;
|
||||
AndroidManifestIdentity identity;
|
||||
bool has_x86_64_library = false;
|
||||
bool has_guest_library = false;
|
||||
bool has_assets = false;
|
||||
};
|
||||
|
||||
std::string GuestLibEntryName() {
|
||||
return std::string(compat::kGuestLibApkEntryPrefix) +
|
||||
std::string(compat::kGuestAbi) + "/libroblox.so";
|
||||
}
|
||||
|
||||
bool CollectCandidates(const std::vector<std::filesystem::path>& archives,
|
||||
const std::filesystem::path& directory,
|
||||
std::vector<std::filesystem::path>* candidates,
|
||||
@@ -250,7 +256,7 @@ bool InspectCandidates(const std::vector<std::filesystem::path>& paths,
|
||||
ApkCandidate candidate;
|
||||
candidate.path = path;
|
||||
candidate.identity = std::move(identity);
|
||||
candidate.has_x86_64_library = HasEntry(list, "lib/x86_64/libroblox.so");
|
||||
candidate.has_guest_library = HasEntry(list, GuestLibEntryName());
|
||||
candidate.has_assets = std::any_of(
|
||||
list.entries.begin(), list.entries.end(), [](const ZipEntry& entry) {
|
||||
return entry.name.size() > 7 && entry.name.substr(0, 7) == "assets/";
|
||||
@@ -314,7 +320,8 @@ std::vector<std::string> CommonTrustedCertificates(
|
||||
const ApkSignatureResult split_signature =
|
||||
base == split ? base_signature : VerifyApkSignature(split);
|
||||
if (!split_signature) {
|
||||
*error = "x86_64 APK signature: " + split_signature.error;
|
||||
*error = std::string(compat::kGuestAbi) +
|
||||
" APK signature: " + split_signature.error;
|
||||
return {};
|
||||
}
|
||||
std::vector<std::string> accepted;
|
||||
@@ -356,9 +363,11 @@ bool ValidateElf(const std::filesystem::path& path, std::string* build_id,
|
||||
}
|
||||
GElf_Ehdr header{};
|
||||
if (gelf_getehdr(elf.get(), &header) == nullptr ||
|
||||
header.e_machine != EM_X86_64 || gelf_getclass(elf.get()) != ELFCLASS64) {
|
||||
header.e_machine != compat::kGuestElfMachine ||
|
||||
gelf_getclass(elf.get()) != ELFCLASS64) {
|
||||
close_elf();
|
||||
*error = "libroblox.so is not an x86-64 ELF";
|
||||
*error = "libroblox.so is not a " + std::string(compat::kGuestAbi) +
|
||||
" ELF";
|
||||
return false;
|
||||
}
|
||||
std::size_t section_count = 0;
|
||||
@@ -464,16 +473,18 @@ PreparedPayload PreparePayloadFromArchives(
|
||||
base = &candidate;
|
||||
}
|
||||
}
|
||||
const std::string guest_split_name(compat::kGuestApkSplitName);
|
||||
for (const ApkCandidate& candidate : candidates) {
|
||||
if (candidate.has_x86_64_library &&
|
||||
(candidate.identity.split_name == "config.x86_64" ||
|
||||
if (candidate.has_guest_library &&
|
||||
(candidate.identity.split_name == guest_split_name ||
|
||||
candidate.identity.split_name.empty()) &&
|
||||
split == nullptr) {
|
||||
split = &candidate;
|
||||
}
|
||||
}
|
||||
if (base == nullptr || split == nullptr) {
|
||||
result.error = "no matching Roblox base and x86_64 APK pair was found";
|
||||
result.error = "no matching Roblox base and " +
|
||||
std::string(compat::kGuestAbi) + " APK pair was found";
|
||||
return result;
|
||||
}
|
||||
const std::set<std::string> trusted =
|
||||
@@ -488,12 +499,13 @@ PreparedPayload PreparePayloadFromArchives(
|
||||
if (filesystem_error ||
|
||||
!CopyRegular(base->path, prepared / "sober_apk/base.apk",
|
||||
&result.error) ||
|
||||
!CopyRegular(split->path, prepared / "sober_apk/split_config.x86_64.apk",
|
||||
!CopyRegular(split->path,
|
||||
prepared / "sober_apk" / compat::kGuestSplitApkFile,
|
||||
&result.error)) {
|
||||
if (result.error.empty()) result.error = "cannot create prepared payload";
|
||||
return result;
|
||||
}
|
||||
if (!ExtractZipEntry(split->path, "lib/x86_64/libroblox.so",
|
||||
if (!ExtractZipEntry(split->path, GuestLibEntryName(),
|
||||
prepared / "libroblox.so", kMaximumApkBytes,
|
||||
&result.error)) {
|
||||
return result;
|
||||
@@ -527,7 +539,7 @@ PreparedPayload PreparePayloadFromArchives(
|
||||
const std::string base_hash =
|
||||
HashRegularFile(prepared / "sober_apk/base.apk", &hash_error);
|
||||
const std::string split_hash = HashRegularFile(
|
||||
prepared / "sober_apk/split_config.x86_64.apk", &hash_error);
|
||||
prepared / "sober_apk" / compat::kGuestSplitApkFile, &hash_error);
|
||||
if (!hash_error.empty()) {
|
||||
result.error = hash_error;
|
||||
return result;
|
||||
@@ -537,12 +549,12 @@ PreparedPayload PreparePayloadFromArchives(
|
||||
{"package", "com.roblox.client"},
|
||||
{"version_name", expected.version_name},
|
||||
{"version_code", expected.version_code},
|
||||
{"abi", "x86_64"},
|
||||
{"abi", std::string(compat::kGuestAbi)},
|
||||
{"elf_build_id", build_id},
|
||||
{"sha256",
|
||||
{{"libroblox", library_hash},
|
||||
{"base_apk", base_hash},
|
||||
{"x86_64_split_apk", split_hash}}},
|
||||
{std::string(compat::kGuestSplitApkHashKey), split_hash}}},
|
||||
{"signing_certificates_sha256", accepted},
|
||||
{"assets",
|
||||
{{"file_count", asset_count_verified},
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "compat/guest_abi.h"
|
||||
#include "update/http_download.h"
|
||||
|
||||
namespace mocktail::update {
|
||||
@@ -199,7 +200,8 @@ std::vector<std::string> ParseApkPureExactDownloadUrls(
|
||||
}
|
||||
|
||||
ProviderVersion ApkPureProvider::CheckLatest() const {
|
||||
const HttpBytesResult metadata = FetchMetadata("x86_64");
|
||||
const HttpBytesResult metadata =
|
||||
FetchMetadata(std::string(compat::kGuestAbi));
|
||||
if (!metadata) return ProviderVersion{{}, 0, metadata.error};
|
||||
return ParseApkPureLatestMetadata(metadata.bytes);
|
||||
}
|
||||
@@ -223,7 +225,7 @@ ProviderDownloadResult ApkPureProvider::DownloadExact(
|
||||
result.error = "APKPure output directory must exist and be empty";
|
||||
return result;
|
||||
}
|
||||
HttpBytesResult metadata = FetchMetadata("x86_64");
|
||||
HttpBytesResult metadata = FetchMetadata(std::string(compat::kGuestAbi));
|
||||
if (!metadata) {
|
||||
result.error = metadata.error;
|
||||
return result;
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include <string_view>
|
||||
|
||||
#include "compat/elf_build_id.h"
|
||||
#include "compat/guest_abi.h"
|
||||
#include "update/payload_integrity.h"
|
||||
|
||||
namespace mocktail::update {
|
||||
@@ -260,7 +261,7 @@ std::string PayloadRuntimeFingerprint(
|
||||
evidence.append("base_apk=")
|
||||
.append(payload.metadata.base_apk_sha256)
|
||||
.append("\n");
|
||||
evidence.append("x86_64_split=")
|
||||
evidence.append(std::string(compat::kGuestAbi) + "_split=")
|
||||
.append(payload.metadata.split_apk_sha256)
|
||||
.append("\n");
|
||||
evidence.append("assets=")
|
||||
|
||||
@@ -11,6 +11,9 @@
|
||||
#include <cerrno>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "compat/guest_abi.h"
|
||||
|
||||
namespace mocktail::update {
|
||||
namespace {
|
||||
@@ -81,6 +84,16 @@ CompatibilityCatalogResult LoadCompatibilityCatalog(
|
||||
profile.value("allow_legacy_binary_patches", true)) {
|
||||
continue;
|
||||
}
|
||||
const auto declared_abi = profile.find("abi");
|
||||
if (declared_abi != profile.end() && !declared_abi->is_string()) {
|
||||
result.error = "supported compatibility profile is incomplete";
|
||||
return result;
|
||||
}
|
||||
const std::string_view profile_abi =
|
||||
declared_abi == profile.end()
|
||||
? std::string_view("x86_64")
|
||||
: std::string_view(declared_abi->get_ref<const std::string&>());
|
||||
if (profile_abi != compat::kGuestAbi) continue;
|
||||
if (!profile.contains("version_name") ||
|
||||
!profile["version_name"].is_string() ||
|
||||
!profile.contains("version_code") ||
|
||||
|
||||
@@ -30,6 +30,7 @@
|
||||
|
||||
#include "compat/elf_build_id.h"
|
||||
#include "compat/fmod_output_device_contract.h"
|
||||
#include "compat/guest_abi.h"
|
||||
#include "update/payload_integrity.h"
|
||||
|
||||
namespace mocktail::update {
|
||||
@@ -222,9 +223,10 @@ class ElfImage final {
|
||||
if (elf_ == nullptr || elf_kind(elf_) != ELF_K_ELF ||
|
||||
gelf_getehdr(elf_, &header) == nullptr ||
|
||||
gelf_getclass(elf_) != ELFCLASS64 || header.e_type != ET_DYN ||
|
||||
header.e_machine != EM_X86_64 || header.e_version != EV_CURRENT ||
|
||||
header.e_machine != compat::kGuestElfMachine ||
|
||||
header.e_version != EV_CURRENT ||
|
||||
header.e_ident[EI_DATA] != ELFDATA2LSB) {
|
||||
*error = "candidate must be a little-endian x86-64 ET_DYN ELF";
|
||||
*error = "candidate must be a little-endian guest-abi ET_DYN ELF";
|
||||
return false;
|
||||
}
|
||||
std::size_t program_count = 0;
|
||||
@@ -1901,7 +1903,7 @@ std::optional<Json> LoadCandidateMetadata(const std::filesystem::path& root,
|
||||
metadata->contains("sha256") ? &(*metadata)["sha256"] : nullptr;
|
||||
if (metadata->value("schema_version", 0) != 1 ||
|
||||
metadata->value("package", "") != "com.roblox.client" ||
|
||||
metadata->value("abi", "") != "x86_64" || version_name.empty() ||
|
||||
metadata->value("abi", "") != compat::kGuestAbi || version_name.empty() ||
|
||||
version_code == 0 ||
|
||||
metadata->value("elf_build_id", "") != candidate.build_id() ||
|
||||
hashes == nullptr || !hashes->is_object() ||
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "compat/guest_abi.h"
|
||||
|
||||
namespace mocktail::update {
|
||||
namespace {
|
||||
|
||||
@@ -291,7 +293,7 @@ PayloadIntegrityResult InspectPreparedPayload(
|
||||
for (const std::filesystem::path& relative : {
|
||||
std::filesystem::path("libroblox.so"),
|
||||
std::filesystem::path("sober_apk/base.apk"),
|
||||
std::filesystem::path("sober_apk/split_config.x86_64.apk"),
|
||||
std::filesystem::path("sober_apk") / compat::kGuestSplitApkFile,
|
||||
std::filesystem::path("roblox_payload.json"),
|
||||
}) {
|
||||
const auto status =
|
||||
@@ -335,7 +337,7 @@ PayloadIntegrityResult InspectPreparedPayload(
|
||||
result.metadata.library_sha256 = document["sha256"].value("libroblox", "");
|
||||
result.metadata.base_apk_sha256 = document["sha256"].value("base_apk", "");
|
||||
result.metadata.split_apk_sha256 =
|
||||
document["sha256"].value("x86_64_split_apk", "");
|
||||
document["sha256"].value(std::string(compat::kGuestSplitApkHashKey), "");
|
||||
if (!document["assets"].contains("file_count") ||
|
||||
!document["assets"]["file_count"].is_number_unsigned()) {
|
||||
result.error = "payload metadata asset count is invalid";
|
||||
@@ -368,7 +370,8 @@ PayloadIntegrityResult VerifyPreparedPayload(
|
||||
const std::array<std::pair<std::filesystem::path, std::string>, 3> files = {{
|
||||
{"libroblox.so", result.metadata.library_sha256},
|
||||
{"sober_apk/base.apk", result.metadata.base_apk_sha256},
|
||||
{"sober_apk/split_config.x86_64.apk", result.metadata.split_apk_sha256},
|
||||
{std::filesystem::path("sober_apk") / compat::kGuestSplitApkFile,
|
||||
result.metadata.split_apk_sha256},
|
||||
}};
|
||||
for (const auto& [relative, expected] : files) {
|
||||
const std::string actual =
|
||||
|
||||
@@ -108,15 +108,9 @@ struct SurfaceState {
|
||||
unsigned int resource_retries = 0;
|
||||
};
|
||||
|
||||
// A solved challenge stays open: the host forwards the event to Roblox, and
|
||||
// Roblox or the host closes the window after Roblox has received it.
|
||||
struct CallbackConfirmation {
|
||||
CallbackConfirmation(GtkWindow* surface_window, CaptchaEventType event_type)
|
||||
: type(event_type) {
|
||||
g_weak_ref_init(&window, G_OBJECT(surface_window));
|
||||
}
|
||||
|
||||
~CallbackConfirmation() { g_weak_ref_clear(&window); }
|
||||
|
||||
GWeakRef window;
|
||||
CaptchaEventType type = CaptchaEventType::kShown;
|
||||
};
|
||||
|
||||
@@ -612,16 +606,6 @@ void FinishCallbackConfirmation(GObject* source_object, GAsyncResult* result,
|
||||
if (value != nullptr) {
|
||||
g_object_unref(value);
|
||||
}
|
||||
|
||||
auto* window_object =
|
||||
static_cast<GObject*>(g_weak_ref_get(&confirmation->window));
|
||||
if (confirmed && confirmation->type == CaptchaEventType::kSuccess &&
|
||||
window_object != nullptr) {
|
||||
gtk_window_close(GTK_WINDOW(window_object));
|
||||
}
|
||||
if (window_object != nullptr) {
|
||||
g_object_unref(window_object);
|
||||
}
|
||||
delete confirmation;
|
||||
}
|
||||
|
||||
@@ -644,9 +628,8 @@ void HandleHybridCommand(WebKitUserContentManager* manager,
|
||||
if (window_object == nullptr) {
|
||||
return;
|
||||
}
|
||||
auto* confirmation =
|
||||
new CallbackConfirmation(GTK_WINDOW(window_object), event.type);
|
||||
g_object_unref(window_object);
|
||||
auto* confirmation = new CallbackConfirmation{event.type};
|
||||
const std::string script = BuildCallbackScript(event.callback_id);
|
||||
WebKitWebView* web_view = WEBKIT_WEB_VIEW(
|
||||
g_object_get_data(G_OBJECT(manager), "mocktail-web-view"));
|
||||
|
||||
Loaded 100 of 142 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user